예제 #1
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
예제 #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
    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)
예제 #4
0
def plot_calibrations(group_data, voltage, cal_pars_list, stacked=False):
    group_name = str(group_data[0].run_number)
    run = group_data[2]
    name = str(run.run_number)
    hists_and_lines = []
    for cal_pars in cal_pars_list:
        pars = parameters.gain_pars[cal_pars]
        run.calibrate_energies(voltage, pars)
        hist = make_hist(name, run.calibrated_energies, 0, 3500)
        K_line = TLine(1460.820, 0, 1460.820, 1000000)
        K_line.SetLineColor(632)
        Tl_line = TLine(2614.511, 0, 2614.511, 1000000)
        Tl_line.SetLineColor(632)
        hists_and_lines.append([hist, K_line, Tl_line])

    if stacked:
        print('Plotting stacked calibrated histograms.')
        run_canvas = TCanvas()
        run_canvas.SetLogy()
        colors = [808, 397, 436, 424, 628, 852, 800, 863, 403, 797]
        color_index = 0
        hs = THStack('hs', 'Group %s Histograms' % group_name)
        for entry in hists_and_lines:
            title = str(run.run_number)
            entry[0].SetLineColor(colors[color_index])
            color_index += 1
            hs.Add(entry[0])
        hs.Draw('nostack')
        K_line = TLine(1460.820, 0, 1460.820, 1000000)
        K_line.SetLineColor(632)
        K_line.Draw()
        Tl_line = TLine(2614.511, 0, 2614.511, 1000000)
        Tl_line.SetLineColor(632)
        Tl_line.Draw()
        run_canvas.BuildLegend()
        path = 'output/group_' + str(group_data[0].run_number) + '/'
        run_canvas.Print((path + str(group_data[0].run_number) +
                          '_stacked_calibrated_histogram.pdf['))
        run_canvas.Print((path + str(group_data[0].run_number) +
                          '_stacked_calibrated_histogram.pdf'))
        run_canvas.Print((path + str(group_data[0].run_number) +
                          '_stacked_calibrated_histogram.pdf]'))
    else:
        print('Plotting calibrated energy histogram.')
        run_canvas = TCanvas("run_canvas", "run canvas")
        run_canvas.Divide(3, int(len(cal_pars_list) / 2))
        canvas_index = 1
        for entry in hists_and_lines:
            pad = run_canvas.cd(canvas_index)
            pad.SetLogy()
            entry[0].Draw()
            entry[1].Draw()
            entry[2].Draw()
            pad.Update()
            canvas_index += 1

            path = 'output/group_' + group_name + '/'
            run_canvas.Print((path + name + '_calibrated_histograms.pdf['))
            run_canvas.Print((path + name + '_calibrated_histograms.pdf'))
            run_canvas.Print((path + name + '_calibrated_histograms.pdf]'))
예제 #5
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
예제 #6
0
def drawAppMVAOutputPlots(region, method, isMC):

    MCstr = ""
    if isMC:
        MCstr = "BsMC12"
    Region = region[:1].upper() + region[
        1:]  #capitalize first letter for retrieving file names
    HistName = "ApplicationOutput" + MCstr + Region + method
    CvsName = "canvasMVA_" + MCstr + method + region
    canvas = TCanvas(CvsName, CvsName)
    stackBDT = THStack(HistName, HistName)
    histos = []
    appFiles = []
    canvas.Draw()

    # note: TMVApp file name structure: "TMVApp"+Region+method+sample+".root"
    #                             "BsMC12TMVApp"+Region+method+sample+".root"
    appFile = TFile(MCstr + "TMVApp" + Region + method + ".root")
    histo = appFile.Get("MVA_" + method).Clone(HistName)
    histo.Scale(1 / histo.GetEntries())
    stackBDT.Add(histo)

    for sample in range(3):
        appFiles.append(
            TFile(MCstr + "TMVApp" + Region + method + str(sample) + ".root"))
        histos.append(appFiles[sample].Get("MVA_" + method).Clone("HistName" +
                                                                  str(sample)))
        histos[sample].SetLineColor(2 * sample)
        histos[sample].Scale(1 / histos[sample].GetEntries())
        stackBDT.Add(histos[sample])

    stackBDT.Draw("nostack")
    if isMC:
        applicationBDTLegend = TLegend(0.2, 0.7, 0.5, 0.9, "", "brNDC")
        #applicationBDTLegend.SetHeader("Bs MC "+region.split("BsMC")[1])
        applicationBDTLegend.SetHeader("Bs MC " + Region)
    else:
        applicationBDTLegend = TLegend(0.55, 0.7, 0.85, 0.9, "", "brNDC")
        applicationBDTLegend.SetHeader(Region)

    applicationBDTLegend.AddEntry(histo, "Full sample", "l")
    applicationBDTLegend.AddEntry(histos[0],
                                  "Trained on 0, tested on 1, applied on 2",
                                  "l")
    applicationBDTLegend.AddEntry(histos[1],
                                  "Trained on 1, tested on 2, applied on 0",
                                  "l")
    applicationBDTLegend.AddEntry(histos[2],
                                  "Trained on 2, tested on 0, applied on 1",
                                  "l")
    applicationBDTLegend.Draw("same")
    applicationBDTLegend.SetFillColor(0)
    applicationBDTLegend.SetLineColor(0)
    canvas.SaveAs(figuresDir + "Application" + method + "Output_" + MCstr +
                  region + ".pdf")
예제 #7
0
def DrawStackHistograms(histograms, outname, blind=True, verbose=False):

    #hists_sorted = sorted(histograms, key=lambda h: h.Integral())

    hs = THStack("h_stack", "")
    h_obs = None

    l = TLegend(0.77, 0.60, 0.90, 0.87)

    for hist in histograms:

        hname = hist.GetName()

        if "data_obs" in hname:
            if not blind:
                h_obs = hist
                SetHistogramStyle(h_obs, "Observed")
                l.AddEntry(h_obs, "Observed", "p")
        else:
            SetHistogramStyle(hist)
            label = GetLabelName(hist)
            hs.Add(hist)
            l.AddEntry(hist, label, "f")

    h_est = hs.GetStack().Last().Clone()

    if verbose:
        est_err = Double(0.)
        nbins_est = h_est.GetNbinsX()
        est_yields = h_est.IntegralAndError(1, nbins_est, est_err)
        print "predicted yields :", est_yields, "+/-", est_err
        if not blind:
            print "observed yields :", h_obs.Integral()

    # draw

    # SetCMSStyle()   TODO

    canvas = TCanvas()
    gPad.SetLogy()

    #ymax_hs = hs.GetMaximum()
    #ymax = ymax_hs if h_obs is None else max(ymax_hs, h_obs.GetMaximum())
    ymax = 10000
    ymin = 0.1

    hs.SetMaximum(ymax)
    hs.SetMinimum(ymin)
    hs.Draw("HIST")
    l.Draw("same")
    if not blind:
        h_obs.Draw("same")

    canvas.SaveAs(outname)
예제 #8
0
class TreeStack(object):
    def __init__(self, name):
        '''Name is the name you want for your treestack.'''
        self.name = name
        self.trees = dict()
        self.styles = dict()
        self.treenames = []
        self.hists = []
        self.histsum = None
        self.stack = THStack('_'.join([self.name, 'stack']), 'title')

    def add(self, name, tree, style=None):
        '''Add a new tree with name "name".
        
        Your tree should have the method Project.
        You may implement tree weighting in this function.

        style should behave like in tools.style
        '''
        self.trees[name] = tree
        self.styles[name] = style
        self.treenames.append(name)

    def hname(self, name):
        return '_'.join([self.name, name])

    def project(self, var, cut, bins, xmin, xmax):
        '''Fill the histograms with all trees, 
        using: 
        var : variable to plot
        cut : cut to use
        These variables will be passed to the Project method of your trees. 
        bins, xmin, xmax defins the histogram binning.
        '''
        for name in self.treenames:
            tree = self.trees[name]
            hname = self.hname(name)
            hist = TH1F(hname, hname, bins, xmin, xmax)
            self.hists.append(hist)
            self.styles[name].formatHisto(hist)
            tree.Project(hname, var, cut)
        for hist in self.hists:
            if self.histsum is None:
                self.histsum = hist.Clone(self.hname('sum'))
            else:
                self.histsum.Add(hist)
            self.stack.Add(hist)

    def draw(self):
        '''Draw the stack. Call project first.'''
        self.stack.Draw()
예제 #9
0
def study_cal_eff():
    # Import data and MC files:
    f_data = TFile.Open("../trees_5gev_e/data_nn50.root", 'read')
    t_data = f_data.data

    f_mc = TFile.Open("../trees_5gev_e/lucas.root", 'read')
    t_mc = f_mc.lumical
    t_mc.AddFriend("lumical_noise=lumical",
                   "../trees_5gev_e/lucas_geocuts_noise_cal.root")
    t_mc.AddFriend("lumical_eff=lumical",
                   "../trees_5gev_e/lucas_geocuts_noise_cal_eff.root")

    c = TCanvas()
    hs = THStack("hs", "title")

    t_data.Draw("energy*(layer > 1)>>h_data50(200, 0, 50)",
                "energy*(layer > 1) > 0")
    h_data50 = gROOT.FindObject("h_data50")
    h_data50.SetTitle("Data")
    h_data50.SetLineWidth(2)
    h_data50.SetLineColor(1)
    hs.Add(h_data50, "histo")

    t_mc.Draw("cal_energy_new/0.0885>>h_mc(200, 0, 50)",
              "cal_energy_new/0.0885 > 0", "", 100000)
    h_mc = gROOT.FindObject("h_mc")
    h_mc.SetTitle("MC smearing and cal eff")
    h_mc.SetLineWidth(2)
    h_mc.SetLineColor(3)
    h_mc.Scale(t_data.GetEntries() / 100000)  #t_mc.GetEntries())
    hs.Add(h_mc, "histo")

    t_mc.Draw("cal_energy_smeared7/0.0885>>h_mc7(200, 0, 50)",
              "cal_energy_smeared7/0.0885 > 0", "", 100000)
    h_mc7 = gROOT.FindObject("h_mc7")
    h_mc7.SetTitle("MC smearing=0.7*#sigma")
    h_mc7.SetLineWidth(2)
    h_mc7.SetLineColor(2)
    h_mc7.Scale(t_data.GetEntries() / 100000)  #t_mc.GetEntries())
    hs.Add(h_mc7, "histo")
    print(h_mc7.GetEntries())
    hs.Draw("nostack")
    hs.SetTitle(
        "Deposited energy in the pads of calorimeter;E, [MIP]; N_{hits}")

    c.SetGridx()
    c.SetGridy()
    c.BuildLegend()
    c.Update()
    input("wait")
예제 #10
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")
예제 #11
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()
예제 #12
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
예제 #13
0
def study_trigger():
    # Import data and MC files:
    f_data = TFile.Open("../trees_5gev_e/.root", 'read')
    t_data = f_data.data

    f_mc = TFile.Open("../trees_5gev_e/lucas.root", 'read')
    t_mc = f_mc.lumical
    t_mc.AddFriend("lumical_tr_clusters=lumical", "../trees_5gev_e/.root")

    c = TCanvas()

    t_data.Draw("tr1_n_clusters>>h_data(6, 0, 6)")
    h_data = gROOT.FindObject("h_data")
    h_data.SetTitle("Data")
    h_data.SetLineWidth(2)
    h_data.SetLineColor(1)

    t_mc.Draw("tr1_n_hits>>h_mc(6, 0, 6)")
    h_mc = gROOT.FindObject("h_mc")
    h_mc.SetTitle("MC")
    h_mc.SetLineWidth(2)
    h_mc.SetLineColor(2)
    h_mc.Scale(t_data.GetEntries() / t_mc.GetEntries())

    t_mc.Draw("tr1_n_clusters>>h_mc2(6, 0, 6)", "n_triggers == 3")
    h_mc2 = gROOT.FindObject("h_mc2")
    h_mc2.SetTitle("MC w/ trigger")
    h_mc2.SetLineWidth(2)
    h_mc2.SetLineColor(4)
    h_mc2.Scale(t_data.GetEntries() / t_mc.GetEntries())

    hs = THStack("hs", "title")
    hs.Add(h_data, "histo")
    hs.Add(h_mc, "histo")
    hs.Add(h_mc2, "histo")
    hs.Draw("nostack")
    hs.SetTitle(
        "Number of clusters in the 1st tracker;N_{particles}; N_{events}")

    c.SetGridx()
    c.SetGridy()
    c.BuildLegend()
    c.Update()
    input("wait")
예제 #14
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')
예제 #15
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")
예제 #16
0
파일: Histogram.py 프로젝트: bbockelm/DBS-1
class StackedHisto(object):
    def __init__(self, name, title):
        self._name = name
        self._title = title
        self._hstack = THStack(self._name, self._title)

    def addHisto(histo):
        self._hstack.Add(histo.histogram)

    @property
    def name(self):
        return self._name

    @property
    def title(self):
        return self._title

    def create_canvas(self):
        self._canvas = TCanvas(self._name, self._name)

        gStyle.SetCanvasBorderMode(0)
        gStyle.SetPadBorderMode(0)

        self._canvas.cd()

    def draw(self):
        # create canvas to draw histogram
        if not getattr(self, '_canvas', None):
            self.create_canvas()
        self._hstack.Draw('nostack')

    def save_as(self, output_directory, format="png"):
        try:
            self._canvas.Print(
                "%s/%s.%s" % (output_directory, self._name, format), format)
        except AttributeError:
            print("You have to draw histograms before saving.")
            pass

    def set_stats_style(self):
        pass
예제 #17
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")
예제 #18
0
def plotHistograms(histname,
                   filenames,
                   labels,
                   canvas,
                   legend,
                   normalize=False):
    assert (len(filenames) == len(labels))
    TH1.SetDefaultSumw2()
    # get histograms from the files
    histograms = []
    for fname in filenames:
        f = TFile.Open(fname, "READ")
        h = f.Get(histname)
        h.SetDirectory(0)
        histograms.append(h)
        f.Close()

    # plot
    canvas.cd()
    hs = THStack()
    hs.Draw()
    norm = 1.
    for i, (hist, label) in enumerate(zip(histograms, labels)):
        hist.SetStats(0)
        hist.SetLineColor(i + 1)
        hist.SetMarkerColor(i + 1)

        # normalize to the first histogram if needed
        if normalize:
            if i == 0:
                norm = hist.Integral()
            else:
                norm_i = hist.Integral()
                hist.Scale(norm / norm_i)

        hs.Add(hist)
        legend.AddEntry(hist, label)

    return hs
예제 #19
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
예제 #20
0
    hist_met_ = fin.Get('h_summary_' + iprocess)
    hist_met_.Sumw2()
    hist_met_.SetDirectory(0)
    TH1.AddDirectory(0)
    #    gStyle.SetPalette(53)
    hist_met_.SetFillColor(color[i])
    #hist_met_.SetLineColor(color[i])
    bkgStack.Add(hist_met_, 'hist')
    legend.AddEntry(hist_met_, processesLegend[i], "f")
    i = i + 1

c = TCanvas()

c.SetLogy(1)

bkgStack.Draw()
j = 0
for iregion in region:
    bkgStack.GetXaxis().SetBinLabel(j + 1, iregion)
    j = j + 1
legend.Draw()

latex = TLatex(0.15, 0.85, 'CMS')
latex.SetTextSize(0.036)
latex.SetTextAlign(12)
latex.SetNDC(kTRUE)
latex.SetTextFont(61)
latex.Draw()

latex1 = TLatex(0.13, 0.82, 'Preliminary')
latex1.SetTextSize(0.036)
예제 #21
0
def plot(path, leg_title, ecms, xmax, ymax, runNolow, runNoup, mode):
    try:
        f_data = TFile(path[0])
        f_incMC1 = TFile(path[1])
        f_incMC2 = TFile(path[2])
        f_sigMC1 = TFile(path[3])
        f_sigMC2 = TFile(path[4])
        t_data = f_data.Get('save')
        t_incMC1 = f_incMC1.Get('save')
        t_incMC2 = f_incMC2.Get('save')
        t_sigMC1 = f_sigMC1.Get('save')
        t_sigMC2 = f_sigMC2.Get('save')
        entries_data = t_data.GetEntries()
        entries_incMC1 = t_incMC1.GetEntries()
        entries_incMC2 = t_incMC2.GetEntries()
        entries_sigMC1 = t_sigMC1.GetEntries()
        entries_sigMC2 = t_sigMC2.GetEntries()
        logging.info('data entries :' + str(entries_data))
        logging.info('inclusive MC(open charm) entries :' +
                     str(entries_incMC1))
        logging.info('inclusive MC(qqbar) entries :' + str(entries_incMC2))
        logging.info('signal MC(D1(2420)) entries :' + str(entries_sigMC1))
        logging.info('signal MC(psi(3770)) entries :' + str(entries_sigMC2))
    except:
        logging.error('File paths are invalid!')
        sys.exit()

    mbc = TCanvas('mbc', 'mbc', 800, 600)
    set_canvas_style(mbc)
    xmin = 0.4
    xbins = 80
    content = (xmax - xmin) / xbins * 1000
    ytitle = 'Events/%.1f MeV' % content
    xtitle = 'M(#pi^{+}_{0}#pi^{-}_{0})(GeV)'
    h_data = TH1F('data', 'data', xbins, xmin, float(xmax))
    h_incMC1 = TH1F('incMC1', 'inclusive MC: open charm', xbins, xmin,
                    float(xmax))
    h_incMC2 = TH1F('incMC2', 'inclusive MC: qqbar', xbins, xmin, float(xmax))
    h_sigMC1 = TH1F('sigMC1', 'signal MC: D1(2420)', xbins, xmin, float(xmax))
    h_sigMC2 = TH1F('sigMC2', 'signal MC: psi(3770)', xbins, xmin, float(xmax))

    set_histo_style(h_data, h_incMC1, h_incMC2, h_sigMC1, h_sigMC2, xtitle,
                    ytitle, ymax)
    rm_pipi_fill(t_data, t_incMC1, t_incMC2, t_sigMC1, t_sigMC2, h_data,
                 h_incMC1, h_incMC2, h_sigMC1, h_sigMC2, runNolow, runNoup)

    if not os.path.exists('./figs/'):
        os.makedirs('./figs/')

    h_sigMC1.Scale(scale_factor(ecms, 'D1_2420'))
    h_sigMC2.Scale(scale_factor(ecms, 'psipp'))
    h_incMC1.Scale(scale_factor(ecms, 'DD'))
    h_incMC2.Scale(scale_factor(ecms, 'qq'))
    h_data.Draw('E1')
    h_incMC1.SetFillColor(ROOT.kBlue)
    h_incMC2.SetFillColor(ROOT.kYellow)
    h_sigMC1.SetFillColor(ROOT.kGreen)
    h_sigMC2.SetFillColor(ROOT.kRed)
    hs = THStack('hs', 'Stacked')
    hs.Add(h_sigMC1)
    hs.Add(h_sigMC2)
    hs.Add(h_incMC2)
    hs.Add(h_incMC1)
    hs.Draw('same')
    h_data.Draw('sameE1')

    legend = TLegend(0.55, 0.6, 0.8, 0.75)
    set_legend(legend, h_data, h_incMC1, h_incMC2, h_sigMC1, h_sigMC2,
               leg_title)
    legend.Draw()

    mbc.SaveAs('./figs/m_pipi_' + str(ecms) + '_' + mode + '.pdf')
예제 #22
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))
예제 #23
0
mc_sum.GetXaxis().SetLabelFont(63)
mc_sum.GetXaxis().SetLabelSize(14)  # labels will be 14 pixels

data.GetYaxis().SetLabelFont(63)
data.GetYaxis().SetLabelSize(14)  # labels will be 14 pixels
mc_sum.GetYaxis().SetLabelFont(63)
mc_sum.GetYaxis().SetLabelSize(14)  # labels will be 14 pixels

if args.ratio:
    mc_sum.GetXaxis().SetLabelOffset(999)
    mc_sum.GetXaxis().SetLabelSize(0)
    data.GetXaxis().SetLabelOffset(999)
    data.GetXaxis().SetLabelSize(0)

mc_sum.Draw("e2")
hs.Draw("same")
mc_sum.Draw("same e2")

if not args.no_data:
    data.SetLineWidth(3)
    data.Draw("same P")

leg.Draw("same")

#left_title = TPaveText(0.1, 0.9, 0.4, 0.94, "brNDC")
#left_title.AddText("CMS preliminary at 13 TeV")
#left_title.SetTextFont(1)

left_title = TPaveText(0.15, 0.82, 0.25, 0.88, "brNDC")
left_title.AddText("CMS")
left_title.SetTextFont(1)
예제 #24
0
def plotter(plotdir,
            plot,
            xTitle,
            logY,
            channels=['VV'],
            includeData=False,
            scaleSignal=0,
            UserRange=[None, None, None, None],
            initPath=''):

    # channelTex={'WPWP':'W^{+}W^{+}', 'WPWM':'W^{+}W^{-}','WMWM':'W^{-}W^{-}','WPZ':'W^{+}Z','WMZ':'W^{-}Z','ZZ':'ZZ'}
    channelTex = {'ZZ': 'ZZ'}
    # plotstyle=[(1,1),(1,2),(2,1),(2,2),(4,1),(4,2)]
    plotstyle = [(1, 1)]
    #             0              1                       2                        3             4              5             6
    # Backgrounds=['QCD',     'WJetsToQQ_HT600ToInf', 'ZJetsToQQ_HT600ToInf',     'TT',         'WW',          'WZ',         'ZZ']
    # BGColors=   [rt.kAzure+7,   rt.kRed-4,              rt.kOrange-2,            rt.kGreen+2,  rt.kOrange+7,  rt.kBlue+1,   rt.kMagenta+2]
    # BGTeX=      ['QCD',        'W+JetsToQQ',           'Z+JetsToQQ',             'TTbar'],      'WW',          'WZ',         'ZZ']
    #stackOrder= [4,5,6,2,1,3,0]
    Backgrounds = [
        'QCD'
    ]  # 'WJetsToQQ_HT600ToInf', 'ZJetsToQQ_HT600ToInf', 'ZZ']  'TT',         'WW',          'WZ',         'ZZ']
    BGColors = [
        rt.kAzure + 7
    ]  #,              rt.kOrange-2,            rt.kGreen+2],  rt.kOrange+7,  rt.kBlue+1,   rt.kMagenta+2]
    BGTeX = ['QCD']  #

    stackOrder = [0]

    PreSelection = [
        'nocuts', 'common', 'corrections', 'cleaner', 'softdropmassCorr',
        'AK4pfidfilter', 'AK8pfidfilter', 'invMAk8sel', 'detaAk8sel',
        'AK8N2sel'
    ]
    Selection = [
        'preselection', 'softdropAK8sel', 'tau21sel', 'deltaR48', 'VVRegion',
        'AK4N2sel', 'OpSignsel', 'detaAk4sel', 'invMAk4sel_1p0', 'Kin_AK8'
    ]

    cutnames = [
        'cleaner', 'AK8N2sel', 'invMAk8sel', 'detaAk8sel', 'softdropAK8sel',
        'tau21sel', 'AK4cleaner', 'AK4N2sel', 'OpSignsel', 'detaAk4sel',
        'invMAk4sel_1p0'
    ]

    cuts = {
        'cleaner':
        '#splitline{p_{T-AK8} > 200 GeV, |#eta_{AK8}| < 2.5}{p_{T-AK4} > 30 GeV, |#eta_{AK4}| < 5.0}',
        'AK8N2sel': 'N_{AK8} #geq 2',
        'invMAk8sel': 'M_{jj-AK8} > 1050 GeV',
        'detaAk8sel': '|#Delta#eta_{jj-AK8}|<1.3',
        'softdropAK8sel': '65 GeV <M_{SD}< 105 GeV',
        'tau21sel': '0 #leq #tau_{2}/#tau_{1}<0.45',
        # 'AK4cleaner':'p_{T-AK4} > 30 GeV, |#eta_{AK4}| < 5.0',
        'AK4cleaner': '',
        'AK4N2sel': 'N_{AK4} #geq 2',
        'OpSignsel': '#eta_{1-AK4} #eta_{2-AK4} < 0',
        'detaAk4sel': '|#Delta#eta_{jj-AK4}| > 3.0',
        'invMAk4sel_1p0': 'M_{jj-AK4} > 1.0 TeV'
    }

    VV = ('VV' in channels)
    seperate = (not VV)
    if VV:
        #channels=["WPWP","WPWM","WMWM","WPZ","WMZ","ZZ"]
        channels = ["ZZ"]

    plottitle = plotdir + '_' + plot

    lumi = 36.814
    xLabelSize = 18.
    yLabelSize = 18.
    xTitleSize = 20.
    yTitleSize = 22.
    xTitleOffset = 4.
    yTitleOffset = 1.3

    printout = False
    Portrait = True
    cutname = False
    ratio = includeData

    if ('highbin' in plot):
        binning = 'dijetbinning'
    else:
        binning = 'default'

    if (Portrait):
        canvX = 600
        canvY = 600
    else:
        canvX = 900
        canvY = 675

    if (plotdir in PreSelection):
        region = 'PreSelection'
        initPath = ''
        referenceHistPath = 'detaAk8sel/N_pv'
        if (PreSelection.index(plotdir) < 4 and ('softdrop' in plot)):
            return 'SofdropMass not filled yet!'
    else:
        region = 'SignalRegion'
        referenceHistPath = 'tau21sel/N_pv'
    referenceHistPath = plotdir + '/' + plot

    if (initPath == ''):
        path = '/nfs/dust/cms/user/loemkerj/bachelor/CMSSW_10_2_16/src/UHH2/aQGCVVjjhadronic/%s' % region
    else:
        path = initPath
    outputPath = path.replace(
        '/nfs/dust/cms/user/loemkerj/bachelor/CMSSW_10_2_16/src/UHH2/aQGCVVjjhadronic/SignalRegion',
        'plots/')
    if (plotdir in PreSelection):
        CutNumber = PreSelection.index(plotdir)
    else:
        CutNumber = Selection.index(plotdir)
    outputPath = outputPath + '/%02i_%s' % (CutNumber, plotdir) + '/'
    if (printout):
        print('InputPath:', path)
        print('OutputPath:', outputPath)
    #check if OutputPath exists - and if not create it!
    if not os.path.exists(outputPath):
        os.makedirs(outputPath)
    # path='/home/albrec/Master/signal/'
    scaleVV = (scaleSignal != 0)
    VVScale = scaleSignal

    if (UserRange[2] == None or UserRange[3] == None):
        YRangeUser = False
        Ymin = UserRange[2]
        Ymax = UserRange[3]
    else:
        YRangeUser = True
        Ymin = UserRange[2]
        Ymax = UserRange[3]

    if (UserRange[0] == None or UserRange[1] == None):
        XRangeUser = False
        Xmin = UserRange[0]
        Xmax = UserRange[1]
    else:
        XRangeUser = True
        Xmin = UserRange[0]
        Xmax = UserRange[1]

    # YRangeUser=False
    # Ymin=0.11
    # Ymax=9*10**3

    # XRangeUser=False
    # Xmin=0
    # Xmax=6000.

    gROOT.ProcessLine("gErrorIgnoreLevel = 2001;")
    SFiles = []
    for i in range(len(channels)):
        SFiles.append(
            TFile(
                path +
                "/uhh2.AnalysisModuleRunner.MC.MC_aQGC_%sjj_hadronic_2016v3.root"
                % channels[i]))
#uhh2.AnalysisModuleRunner.MC.MC_aQGC_ZZjj_hadronic_2016v3.root
##Open Files to get BackgroundHist:
    BFiles = []
    for i in range(len(Backgrounds)):
        BFiles.append(
            TFile(path +
                  "/uhh2.AnalysisModuleRunner.MC.MC_%s.root" % Backgrounds[i]))

    #Open File to get DataHist:

# DataFile = TFile(path+"/uhh2.AnalysisModuleRunner.Data.DATA.root")

#gROOT.ProcessLine( "gErrorIgnoreLevel = 0;")

    if (includeData == True):
        #calculate QCDscale with Integrals from the following Histogram:
        # referenceHistPath = 'tau21sel/N_AK4'
        # referenceHistPath = 'detaAk8sel/N_pv'
        # referenceHistPath = 'tau21sel/met_pt_over_sumptAK8_2'
        QCDscale = float(DataFile.Get(referenceHistPath).Integral())
        QCDNorm = 1
        for i in range(len(BFiles)):
            if ('QCD' in BFiles[i].GetName()):
                QCDNorm = float(BFiles[i].Get(referenceHistPath).Integral())
            else:
                QCDscale -= float(BFiles[i].Get(referenceHistPath).Integral())
        QCDscale /= QCDNorm
    else:
        QCDscale = 1.0
    if (printout):
        print('using QCDscale:', QCDscale)

    SHists = []
    for i in range(len(channels)):
        SHists.append(SFiles[i].Get(plotdir + '/' + plot))

    BHists = []
    for i in range(len(BFiles)):
        BHists.append(BFiles[i].Get(plotdir + '/' + plot))
        if ('QCD' in BFiles[i].GetName()):
            BHists[-1].Scale(QCDscale)

    #if(includeData):
    #    DataHist=DataFile.Get(plotdir+'/'+plot)

    if (binning == 'dijetbinning'):
        fitbinning = array('d')
        binwidth = 200
        NBins = (14000 / binwidth) - ((1040 / binwidth) + 1)
        NBins = int(NBins)
        for i in range(NBins + 1):
            fitbinning.append(1050 + i * binwidth)

        for i in range(len(channels)):
            SHists[i] = SHists[i].Rebin(NBins, "new binning", fitbinning)
        for i in range(len(Backgrounds)):
            BHists[i] = BHists[i].Rebin(NBins, "new binning", fitbinning)

        if (includeData):
            DataHist = DataHist.Rebin(NBins, "new binning", fitbinning)

    canv = TCanvas(plottitle, plottitle, canvX, canvY)

    yplot = 0.7
    yratio = 0.3
    ymax = 1.0
    xmax = 1.0
    xmin = 0.0
    if (ratio):
        plotpad = TPad("plotpad", "Plot", xmin, ymax - yplot, xmax, ymax)
        ratiopad = TPad("ratiopad", "Ratio", xmin, ymax - yplot - yratio, xmax,
                        ymax - yplot)
    else:
        plotpad = TPad("plotpad", "Plot", xmin, ymax - yplot - yratio, xmax,
                       ymax)

    plotpad.SetTopMargin(0.08)
    plotpad.SetLeftMargin(0.1)
    plotpad.SetRightMargin(0.05)
    plotpad.SetTicks()
    plotpad.Draw()

    if (ratio):
        plotpad.SetBottomMargin(0.016)
        ratiopad.SetTopMargin(0.016)
        ratiopad.SetBottomMargin(0.35)
        ratiopad.SetLeftMargin(0.1)
        ratiopad.SetRightMargin(0.05)
        ratiopad.SetTicks()
        ratiopad.Draw()
    else:
        plotpad.SetBottomMargin(0.1)

    if (logY):
        plotpad.SetLogy()
        canv.SetLogy()
    if ('-logX' in xTitle):
        plotpad.SetLogx()
        if (ratio):
            ratiopad.SetLogx()
        canv.SetLogx()

    drawOptions = "HE"

    stack = THStack(plottitle, plottitle)

    BHist = THStack(plottitle, plottitle)

    # for i in range(len(Backgrounds)):
    for i in stackOrder:
        # BHists[i].SetFillColor(BGColors[i])
        BHists[i].SetLineColor(BGColors[i])
        BHist.Add(BHists[i], 'Hist')

    BHist.SetTitle(plottitle)

    BHistErr = BHists[0].Clone()
    for i in range(1, len(Backgrounds)):
        BHistErr.Add(BHists[i])

    BHistErr.SetFillStyle(3204)
    BHistErr.SetFillColor(rt.kGray + 2)
    BHistErr.SetLineColor(1)

    BGMax = BHist.GetMaximum()
    SIGMax = 0
    #if(VV):       #new
    #    SIGMax=VVsum.GetMaximum()
    #else:
    for i in range(len(channels)):
        tmpmax = SHists[i].GetMaximum()
        if (tmpmax > SIGMax):
            SIGMax = tmpmax
    if (scaleVV):
        SIGMax = SIGMax * VVScale
    if (logY):
        MAX = 0.9 * float(10**(magnitude(max(BGMax, SIGMax)) + 1))
        MIN = float(10**(magnitude(max(BGMax, SIGMax)) - 5))
        MIN += float(10**(magnitude(MIN)))
        legendMIN = math.log(max(BGMax, SIGMax)) / math.log(MAX)
    else:
        MAX = (1.0 / 0.8) * max(BGMax, SIGMax)
        legendMIN = 0.7
        MIN = 0.
    legendMIN = (legendMIN * 0.7) + 0.3 - 0.016

    legend = TLegend(0.5, 0.75, 0.85, 0.89)
    legend.SetFillStyle(0)
    legend.SetTextSize(0.02)
    legend.SetMargin(0.4)
    legend.SetNColumns(2)
    legend.SetColumnSeparation(0.3)

    if (includeData):
        DataHist.SetMarkerStyle(8)
        DataHist.SetLineColor(1)
        DataHist.SetTitle(plottitle)

    if VV:
        for i in range(len(channels)):
            if (i == 0):
                VVsum = SHists[i].Clone()
            else:
                VVsum.Add(SHists[i])
        legentry = 'VVjj'
        if (scaleVV):
            VVsum.Scale(VVScale)
            legentry += ' *%0.f' % VVScale
        VVsum.SetLineColor(1)
        VVsum.SetLineStyle(plotstyle[0][1])
        VVsum.SetLineWidth(2)
        legend.AddEntry(VVsum, legentry)
    else:
        for i in range(len(channels)):
            SHists[i].SetLineColor(plotstyle[i][0])
            SHists[i].SetLineStyle(plotstyle[i][1])
            SHists[i].SetLineWidth(2)
            legentry = "%sjj" % channelTex[channels[i]]
            if (scaleVV):
                SHists[i].Scale(VVScale)
                legentry += ' *%.2E' % VVScale
            legend.AddEntry(SHists[i], legentry)

    for i in stackOrder:
        legend.AddEntry(BHists[i], BGTeX[i], "f")
    legend.AddEntry(BHistErr, "stat. Uncertainty", "f")

    if (includeData):
        legend.AddEntry(DataHist, "Data", "lep")

    canv.SetTitle(plottitle)

    BHistErr.GetYaxis().SetTitle('Events')
    BHistErr.GetYaxis().SetRangeUser(MIN, MAX)
    BHistErr.GetYaxis().SetTitleFont(43)
    BHistErr.GetYaxis().SetTitleSize(yTitleSize)
    BHistErr.GetYaxis().SetTitleOffset(yTitleOffset)
    BHistErr.GetYaxis().SetLabelFont(43)
    BHistErr.GetYaxis().SetLabelSize(yLabelSize)
    if (ratio):
        BHistErr.GetXaxis().SetTitleSize(0.0)
        BHistErr.GetXaxis().SetLabelSize(0.0)
    else:
        BHistErr.GetXaxis().SetTitle(xTitle)
        BHistErr.GetXaxis().SetTitleFont(43)
        BHistErr.GetXaxis().SetTitleSize(xTitleSize)
        # BHistErr.GetXaxis().SetTitleOffset(xTitleOffset)
        BHistErr.GetXaxis().SetTitleOffset(1.2)
        BHistErr.GetXaxis().SetLabelFont(43)
        BHistErr.GetXaxis().SetLabelSize(xLabelSize)
        # BHistErr.GetXaxis().SetTickLength(0.08)
        # BHistErr.GetXaxis().SetNdivisions(506)

    if (YRangeUser):
        BHistErr.GetYaxis().SetRangeUser(Ymin, Ymax)
    if (XRangeUser):
        BHistErr.GetXaxis().SetRangeUser(Xmin, Xmax)

    plotpad.cd()

    BHistErr.Draw("E2")
    BHist.Draw("HistSAME")
    BHistErr.Draw("E2SAME")

    if (VV):
        VVsum.Draw("SAME" + drawOptions)
    elif ('-noSig' not in xTitle):
        for i in range(len(channels)):
            SHists[i].Draw("SAME" + drawOptions)

    if (includeData):
        DataHist.Draw("APE1SAME")

    plotpad.RedrawAxis()
    if (ratio):
        ratiopad.cd()

        if (includeData):
            ratioHist = DataHist.Clone()
        else:
            ratioHist = BHistErr.Clone()
        ratioHist.SetLineColor(rt.kBlack)
        # ratioHist.Sumw2()
        ratioHist.SetStats(0)
        ratioHist.Divide(BHistErr)
        ratioHist.SetMarkerStyle(21)
        ratioHist.SetMarkerSize(0.7)

        #Yaxis
        ratioHist.GetYaxis().SetRangeUser(0.3, 1.7)
        ratioHist.GetYaxis().SetTitle("Data/BG")
        ratioHist.GetYaxis().CenterTitle()
        ratioHist.GetYaxis().SetTitleFont(43)
        ratioHist.GetYaxis().SetTitleSize(yTitleSize)
        ratioHist.GetYaxis().SetTitleOffset(yTitleOffset)
        ratioHist.GetYaxis().SetLabelFont(43)
        ratioHist.GetYaxis().SetLabelSize(yLabelSize)
        ratioHist.GetYaxis().SetNdivisions(506)
        #Xaxis
        ratioHist.GetXaxis().SetTitle(xTitle)
        ratioHist.GetXaxis().SetTitleFont(43)
        ratioHist.GetXaxis().SetTitleSize(xTitleSize)
        ratioHist.GetXaxis().SetTitleOffset(xTitleOffset)
        ratioHist.GetXaxis().SetLabelFont(43)
        ratioHist.GetXaxis().SetLabelSize(xLabelSize)
        ratioHist.GetXaxis().SetTickLength(0.08)
        ratioHist.GetXaxis().SetNdivisions(506)

        # if(YRangeUser):
        #     ratioHist.GetYaxis().SetRangeUser(Ymin,Ymax)
        if (XRangeUser):
            ratioHist.GetXaxis().SetRangeUser(Xmin, Xmax)
            ratioXMin = Xmin
            ratioXMax = Xmax
        else:
            ratioXMin = ratioHist.GetXaxis().GetXmin()
            ratioXMax = ratioHist.GetXaxis().GetXmax()
        ratioHist.Draw("ep")

        zeropercent = TLine(ratioXMin, 1, ratioXMax, 1)
        zeropercent.Draw()
        plus10percent = TLine(ratioXMin, 1.1, ratioXMax, 1.1)
        plus10percent.SetLineStyle(rt.kDashed)
        plus10percent.Draw()
        minus10percent = TLine(ratioXMin, 0.9, ratioXMax, 0.9)
        minus10percent.SetLineStyle(rt.kDashed)
        minus10percent.Draw()

    canv.cd()
    gPad.RedrawAxis()
    legend.Draw()

    latex = TLatex()
    latex.SetNDC(kTRUE)
    latex.SetTextSize(20)
    latex.DrawLatex(0.69, 0.953, "%.2f fb^{-1} (13 TeV)" % lumi)
    latex.DrawLatex(0.1, 0.953, "private work")

    lastcut = 'nocuts'
    for cut in cutnames:
        if cut in plotdir:
            lastcut = cut

    if (not (lastcut == 'nocuts') and cutname):
        # latex.SetTextSize(0.03)
        latex.SetTextSize(15)
        for l in range(cutnames.index(lastcut) + 1):
            latex.DrawLatex(0.12, 0.8 - l * 0.04, cuts[cutnames[l]])

    canv.Update()
    canv.Print(outputPath + '/%s_%s.pdf' % (plotdir, plot))
    #prevents memory leak in Canvas Creation/Deletion
    #see: https://root.cern.ch/root/roottalk/roottalk04/2484.html
    gSystem.ProcessEvents()
    if (ratio):
        del ratiopad
    del plotpad, canv
    # gc.collect()
    return 'done!'
예제 #25
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
예제 #26
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))
예제 #27
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
예제 #28
0
    LepBDTMCDY_list[i].Scale(norm)  # MC normalization
    LepBDTMCDY_list[i].SetFillColor(kMagenta - 6)
    LepBDTMCDY_list[i].SetLineColor(kBlack)
    hs.Add(LepBDTMCDY_list[i])

    #upper plot pad
    pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0)
    pad1.Draw()
    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)
예제 #29
0
    def show(self, outDir):
        if len(self.mc) == 0:
            print '%s has no MC!' % self.name
            return

        htype = self.mc[0].ClassName()
        if htype.find('TH2') >= 0:
            print 'Skipping TH2'
            return

        ROOT.gStyle.SetOptTitle(0)
        ROOT.gStyle.SetOptStat(0)
        ROOT.gROOT.SetBatch(1)

        canvas = TCanvas('c_' + self.name, 'C', 800, 800)
        canvas.cd()
        t1 = TPad("t1", "t1", 0.0, 0.20, 1.0, 1.0)
        t1.SetBottomMargin(0)
        t1.Draw()
        t1.cd()
        self._garbageList.append(t1)

        frame = None
        # Decide which backgrounds are visible
        maxint = max([x.Integral() for x in self.mc])
        hists_to_add = [h for h in self.mc if h.Integral() > 0.005 * maxint]

        # Make the legend with the correct size
        leg = TLegend(0.75, 0.74 - 0.04 * max(len(hists_to_add) - 2, 0), .89,
                      0.89)
        leg.SetBorderSize(0)
        leg.SetFillStyle(0)
        leg.SetTextFont(43)
        leg.SetTextSize(20)
        nlegCols = 0

        maxY = 1.0
        if self.data is not None:
            leg.AddEntry(self.data, self.data.GetTitle(), 'p')
            frame = self.dataH.Clone('frame')
            self._garbageList.append(frame)
            maxY = self.dataH.GetMaximum()
            frame.Reset('ICE')
        elif self.dataH is not None:
            leg.AddEntry(self.dataH, self.dataH.GetTitle(), 'p')
            frame = self.dataH.Clone('frame')
            self._garbageList.append(frame)
            maxY = self.dataH.GetMaximum()
            frame.Reset('ICE')

        # Add the legend entries for the visible backgrounds
        for h in sorted(hists_to_add, key=lambda x: x.Integral(),
                        reverse=True):
            leg.AddEntry(h, h.GetTitle(), 'f')
            nlegCols = nlegCols + 1

        # Build the stack to plot from all backgrounds
        totalMC = None
        stack = THStack('mc', 'mc')
        for h in sorted(self.mc, key=lambda x: x.Integral()):
            stack.Add(h, 'hist')
            if totalMC is None:
                totalMC = h.Clone('totalmc')
                self._garbageList.append(totalMC)
                totalMC.SetDirectory(0)
            else:
                totalMC.Add(h)

        if totalMC is not None:
            maxY = max(totalMC.GetMaximum(), maxY)
            if frame is None:
                frame = totalMC.Clone('frame')
                frame.Reset('ICE')
                self._garbageList.append(frame)

        if self.data is not None or self.dataH is not None:
            nlegCols = nlegCols + 1
        if nlegCols == 0:
            print '%s is empty' % self.name
            return

        frame.GetYaxis().SetTitleSize(0.045)
        frame.GetYaxis().SetLabelSize(0.04)
        frame.GetYaxis().SetRangeUser(0.5, 1.2 * maxY)
        frame.GetYaxis().SetNoExponent()
        frame.SetDirectory(0)
        frame.Draw()
        frame.GetYaxis().SetTitleOffset(1.6)
        stack.Draw('hist same')
        if self.data is not None:
            self.data.Draw('P')
        elif self.dataH is not None:
            self.dataH.Draw('e1same')

        # leg.SetNColumns(nlegCols)
        leg.Draw()
        # redrawBorder(t1)

        ## Draw CMS Preliminary label
        CMS_lumi(pad=t1, iPeriod=2, iPosX=0, extraText='')  #Work in Progress')

        if self.normalizedToData:
            txt = TLatex()
            txt.SetNDC(True)
            txt.SetTextFont(42)
            txt.SetTextColor(ROOT.kGray + 1)
            txt.SetTextSize(0.035)
            txt.SetTextAngle(90)
            txt.SetTextAlign(12)
            txt.DrawLatex(0.05, 0.05, '#it{Normalized to data}')

        if totalMC is None or (self.data is None and self.dataH is None):
            t1.SetPad(0, 0, 1, 1)
            t1.SetBottomMargin(0.12)
        else:
            canvas.cd()
            t2 = TPad("t2", "t2", 0.0, 0.0, 1.0, 0.2)
            self._garbageList.append(t2)
            t2.SetTopMargin(0)
            t2.SetBottomMargin(0.4)
            t2.SetGridy()
            t2.Draw()
            t2.cd()

            ratioframe = self.dataH.Clone('ratioframe')
            ratioframe.Reset('ICE')
            ratioframe.Draw()
            ratioframe.GetYaxis().SetRangeUser(self.ratiorange[0],
                                               self.ratiorange[1])
            ratioframe.GetYaxis().SetTitle('Obs./Exp.')
            ratioframe.GetYaxis().SetNdivisions(5)
            ratioframe.GetYaxis().SetLabelSize(0.15)
            ratioframe.GetXaxis().SetLabelSize(0.15)
            ratioframe.GetYaxis().SetTitleSize(0.18)
            ratioframe.GetXaxis().SetLabelSize(0.18)
            ratioframe.GetXaxis().SetTitleSize(0.18)
            ratioframe.GetYaxis().SetTitleOffset(0.4)
            ratioframe.GetXaxis().SetTitleOffset(0.9)

            gr = ROOT.TGraphAsymmErrors()
            gr.SetName("data2bkg")
            gr.SetMarkerStyle(self.dataH.GetMarkerStyle())
            gr.SetMarkerSize(0.7 * self.dataH.GetMarkerSize())
            gr.SetMarkerColor(self.dataH.GetMarkerColor())
            gr.SetLineColor(self.dataH.GetLineColor())
            gr.SetLineWidth(self.dataH.GetLineWidth())
            bkgUncGr = ROOT.TGraphErrors()
            bkgUncGr.SetName('bkgunc')
            bkgUncGr.SetMarkerColor(920)
            bkgUncGr.SetMarkerStyle(1)
            bkgUncGr.SetLineColor(920)
            bkgUncGr.SetFillColor(920)
            bkgUncGr.SetFillStyle(3001)
            for xbin in xrange(1, self.dataH.GetXaxis().GetNbins() + 1):
                x = self.dataH.GetXaxis().GetBinCenter(xbin)
                dx = self.dataH.GetXaxis().GetBinWidth(xbin)
                dataCts = self.dataH.GetBinContent(xbin)
                if self.data:
                    data_err_low = self.data.GetErrorYlow(
                        xbin - 1)  #get errors from the graph
                    data_err_up = self.data.GetErrorYhigh(xbin - 1)
                else:
                    data_err_low = self.dataH.GetBinError(xbin)
                    data_err_up = data_err_low
                bkgCts = totalMC.GetBinContent(xbin)
                bkgCts_err = totalMC.GetBinError(xbin)
                if bkgCts == 0: continue
                errLo = math.sqrt(
                    math.pow(data_err_low * bkgCts, 2) +
                    math.pow(dataCts * bkgCts_err, 2)) / math.pow(bkgCts, 2)
                errHi = math.sqrt(
                    math.pow(data_err_up * bkgCts, 2) +
                    math.pow(dataCts * bkgCts_err, 2)) / math.pow(bkgCts, 2)
                np = gr.GetN()
                gr.SetPoint(np, x, dataCts / bkgCts)
                gr.SetPointError(np, 0, 0, errLo, errHi)
                bkgUncGr.SetPoint(np, x, 1)
                bkgUncGr.SetPointError(np, dx, bkgCts_err / bkgCts)
            bkgUncGr.Draw('2')
            gr.Draw('p')
            # redrawBorder(t2)

        canvas.cd()
        canvas.Modified()
        canvas.Update()

        for ext in self.plotformats:
            canvas.SaveAs(os.path.join(outDir, self.name + '.' + ext))
        if self.savelog:
            t1.cd()
            t1.SetLogy()
            frame.GetYaxis().SetRangeUser(70, 2 * maxY)
            # frame.GetYaxis().SetRangeUser(1000,10*maxY)
            canvas.cd()
            for ext in self.plotformats:
                canvas.SaveAs(os.path.join(outDir, self.name + '_log.' + ext))
예제 #30
0
        tex3.SetLineWidth(2)

        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)