示例#1
0
文件: makePlot.py 项目: sparolia/pyrk
def makeSinglePlot(his, var, smpl, addFile="", saveFile=True, retur=False):
    ROOT.gROOT.SetBatch()
    ROOT.gStyle.SetOptStat(0)
    his.SetMarkerStyle(20)
    his.SetMarkerSize(0.9)
    his.SetLineColor(ROOT.kBlack)
    #legend
    legend = ROOT.TLegend(0.51, 0.70, 0.78, 0.86)
    legend.AddEntry(his, smpl.legendName, "lp")
    legend.SetTextFont(43)
    legend.SetTextSize(15)
    legend.SetBorderSize(0)
    legend.SetFillColor(0)

    ########
    #canvas#
    ########
    c = ROOT.TCanvas("", "", 700, 700)

    c.cd()
    c.SetTicks(True)
    c.SetBottomMargin(2)
    c.SetLeftMargin(0.15)
    c.SetRightMargin(0.15)
    c.Draw()
    c.cd()

    his.Draw("e")
    legend.Draw("SAME")
    his.SetTitle("")
    his.GetYaxis().SetTitle("Events / bin")
    his.GetYaxis().SetLabelOffset(0.01)
    his.GetYaxis().SetTitleOffset(2)
    his.GetYaxis().SetLabelFont(43)
    his.GetYaxis().SetLabelSize(15)
    his.GetYaxis().SetTitleFont(43)
    his.GetYaxis().SetTitleSize(18)
    his.SetMaximum(his.GetMaximum() * 1.5)

    his.GetXaxis().SetLabelOffset(0.01)
    his.GetXaxis().SetTitleOffset(1.6)
    his.GetXaxis().SetLabelFont(43)
    his.GetXaxis().SetLabelSize(15)
    his.GetXaxis().SetTitleFont(43)
    his.GetXaxis().SetTitleSize(18)
    his.GetXaxis().SetTitle(var.xlabel + " " + var.unit)
    CMS_lumi(c, 4, 1)
    c.RedrawAxis()

    if saveFile:
        folder = "pngPlots/"
        c.SaveAs(folder + var.name + "_" + smpl.name + addFile + ".png")
        c.SaveAs(folder + var.name + "_" + smpl.name + addFile + ".pdf")
        print("Saved '" + folder + var.name + "_" + smpl.name + addFile +
              ".png'")
    if (retur == True):
        return his
示例#2
0
def DrawThis(onetree):
    c2 = ROOT.TCanvas('c2', '', 700, 700)
    c2.cd()
    c2.Draw()
    for effidx, eff in enumerate(iso_efficiencies):
        if 'raw' in var:
            options = 'a' * (effidx != 0) + 'pl' + ' same' * (effidx != 0)
            ROOT.gStyle.SetOptStat(0)
        else:
            options = 'a' * (effidx == 0) + 'pl' + ' same' * (effidx != 0)
        eff.Draw(options)
        eff.SetFillColor(0)
        eff.SetTitle('; ' + Xtitles[varidx] + '; efficiency')
        ROOT.gPad.SetGridx()
        ROOT.gPad.SetGridy()
        ROOT.gPad.Update()
        ROOT.gPad.SetTicky(1)
        ROOT.gPad.SetLogx(False)
        if 'raw' in var:
            eff.GetYaxis().SetRangeUser(minim - 0.5 * (maxim * 1.05 - minim),
                                        maxim * 1.05)
            eff.GetXaxis().SetRangeUser(Xranges[varidx][0], Xranges[varidx][1])
        else:
            eff.GetPaintedGraph().GetYaxis().SetRangeUser(
                minim - 0.5 * (maxim * 1.05 - minim), maxim * 1.05)
            eff.GetPaintedGraph().GetXaxis().SetRangeUser(
                Xranges[varidx][0], Xranges[varidx][1])

        CMS_lumi(ROOT.gPad, lumiindex, 0)
        ROOT.gPad.Update()

    if not onetree:
        leg.SetHeader("Genuine #tau_{h} from " + samplename + ", " + num[1],
                      "C")
    leg.Draw('same')
    ROOT.gPad.Update()
    for iformat in ['png']:  # , 'pdf'
        savename = 'eff_' + var
        if not onetree: savename = 'eff_' + var + '_' + str(numidx)
        if doGen and ('gen' not in savename): savename = savename + '_gen'
        ROOT.gPad.SaveAs(savename + '.%s' % iformat)
    del c2
示例#3
0
        ihist.SetFillColor(colours[i])
        ihist.SetFillStyle(0)  # hollow
        maxima.append(ihist.GetMaximum())

    c1.SetLogy(v[2])

    for i, kv in enumerate(temp_hists[k].items()):
        key = kv[0]
        if key == '%s_data' % k: continue
        ihist = kv[1]
        ihist.SetMaximum(2. * max(maxima))
        if not v[2]:
            ihist.SetMinimum(0.)
        ihist.Draw('hist' + 'same' * (i > 0))

        if v[2]:
            ihist.SetMaximum(20 * max(maxima))
        else:
            ihist.SetMaximum(1.5 * max(maxima))

    leg.Draw('same')

    CMS_lumi(c1, 4, 0, cmsText='CMS', extraText='   Simulation', lumi_13TeV='')

    c1.cd()

    c1.Modified()
    c1.Update()
    c1.SaveAs('plots_shapes_bkg/pdf/%s.pdf' % k)
    c1.SaveAs('plots_shapes_bkg/png/%s.png' % k)
示例#4
0
        # statistical uncertainty
        stats = ths1.GetStack().Last().Clone()
        stats.SetLineColor(0)
        stats.SetFillColor(ROOT.kGray + 1)
        stats.SetFillStyle(3344)
        stats.SetMarkerSize(0)
        stats.Draw('E2 SAME')
        leg.AddEntry(fakes, 'fakes', 'F')
        leg.AddEntry(stats, 'stat. unc.', 'F')
        leg.Draw('same')

        temp_hists[k]['%s_data' % k].Draw('EP SAME')

        CMS_lumi(main_pad,
                 4,
                 0,
                 cmsText='CMS',
                 extraText=' Preliminary',
                 lumi_13TeV='')

        main_pad.cd()
        rjpsi_value = ROOT.TPaveText(0.7, 0.65, 0.88, 0.72, 'nbNDC')
        rjpsi_value.AddText('R(J/#Psi) = %.2f' % weights['jpsi_tau'])
        #     rjpsi_value.SetTextFont(62)
        rjpsi_value.SetFillColor(0)
        rjpsi_value.Draw('EP')

        ratio_pad.cd()
        ratio = temp_hists[k]['%s_data' % k].Clone()
        ratio.SetName(ratio.GetName() + '_ratio')
        ratio.Divide(stats)
        ratio_stats = stats.Clone()
示例#5
0
def gaus_fit(histo,var,plt_name="",ps=[None,None,None,None,None,None],pol="pol1"):
        func= ROOT.TF1("func","gaus(0) +"+ pol+"(3)")
        for i,p in enumerate(ps):
            if(p!=None):
                func.SetParameter(i,p)

        c = ROOT.TCanvas("","",700, 700) 
        histo.SetTitle( '; Events / bin;' + var.xlabel+var.unit+';Counts')
        histo.SetMarkerStyle(20)
        histo.SetMarkerSize(0.9)


        for i in range(1,histo.GetNbinsX()+1):
            histo.SetBinError(i, math.sqrt(histo.GetBinContent(i)))
        fit_result=histo.Fit(func,"S")
        fit_gaus=ROOT.TF1("gaus","gaus",var.xmin,var.xmax)
        fit_gaus.SetParameter(0,fit_result.Parameter(0))
        fit_gaus.SetParameter(1,fit_result.Parameter(1))
        fit_gaus.SetParameter(2,fit_result.Parameter(2))

        #legend
        legend = ROOT.TLegend(0.65,0.70,0.98,0.86)
        legend.AddEntry(histo, "data", "lp")
        legend.AddEntry(fit_gaus, "Gauss fit", "l")
        legend.SetTextFont(43)
        legend.SetTextSize(15)
        legend.SetBorderSize(0)
        legend.SetFillColor(0)

        c.SetTicks(True)
        c.SetBottomMargin(2)
        c.SetLeftMargin(0.15)
        c.SetRightMargin(0.15)
        c.Draw()
        c.cd()

        histo.Draw("e")
        #fit_gaus.Draw("lsame")
        legend.Draw("SAME")

        histo.GetYaxis().SetTitle("Events / bin")
        histo.GetYaxis().SetLabelOffset(0.01)
        histo.GetYaxis().SetTitleOffset(2)
        histo.GetYaxis().SetLabelFont(43)
        histo.GetYaxis().SetLabelSize(15)
        histo.GetYaxis().SetTitleFont(43)
        histo.GetYaxis().SetTitleSize(18)
        histo.SetMaximum(histo.GetMaximum()*0.7)
        histo.GetXaxis().SetLabelOffset(0.01)
        histo.GetXaxis().SetTitleOffset(1.6)
        histo.GetXaxis().SetLabelFont(43)
        histo.GetXaxis().SetLabelSize(15)
        histo.GetXaxis().SetTitleFont(43)
        histo.GetXaxis().SetTitleSize(18)
        histo.GetXaxis().SetTitle(var.xlabel + " " + var.unit)
        c.RedrawAxis()
        CMS_lumi(c,4,1)

        c.SaveAs("pngPlots/"+var.name+"_gausFit_"+plt_name+".png")
        print("Saved 'pngPlots/"+var.name+"_gausFit_"+plt_name+".png'")

        c.SaveAs("pngPlots/"+var.name+"_gausFit_"+plt_name+".pdf")
        print("Saved 'pngPlots/"+var.name+"_gausFit_"+plt_name+".pdf'")

        c2 = ROOT.TCanvas()
        fit_gaus.Draw("l")
        c2.SaveAs("pngPlots/"+var.name+"_Onlygaus_"+plt_name+".png")
        print("Saved 'pngPlots/"+var.name+"_Onlygaus_"+plt_name+".png'")

        f=ROOT.TFile.Open("rootPlots/"+var.name+"_gausFit_"+plt_name+".root","RECREATE")
        histo.Write()
        fit_gaus.Write()
        f.Write()
        f.Close()
        print("Saved 'rootPlots/"+var.name+"_gausFit_"+plt_name+".root'")
        
        integral = fit_gaus.Integral(var.xmin,var.xmax)
        return integral/((var.xmax-var.xmin)/var.nbins)
示例#6
0
                    ROOT.RooFit.LineColor(ROOT.kBlue))
fit_function.plotOn(frame, ROOT.RooFit.Components('lxg'),
                    ROOT.RooFit.LineStyle(ROOT.kDashed),
                    ROOT.RooFit.LineColor(ROOT.kOrange))
# fit_function.plotOn(frame, ROOT.RooFit.Components('argus')              , ROOT.RooFit.LineStyle(ROOT.kDashed), ROOT.RooFit.LineColor(ROOT.kViolet))
fit_function.plotOn(frame, ROOT.RooFit.Components('signal_fit_function'),
                    ROOT.RooFit.LineStyle(ROOT.kDashed),
                    ROOT.RooFit.LineColor(ROOT.kRed))
fit_function.plotOn(frame, ROOT.RooFit.Components('jpsik_func'),
                    ROOT.RooFit.LineStyle(ROOT.kDashed),
                    ROOT.RooFit.LineColor(ROOT.kGreen))

frame.Draw()
CMS_lumi(c1,
         4,
         0,
         cmsText='CMS',
         extraText='   Preliminary',
         lumi_13TeV='60 fb^{-1}')

leg = ROOT.TLegend(0.58, .65, .90, .90)
leg.SetBorderSize(0)
leg.SetFillColor(0)
leg.SetFillStyle(0)
leg.SetTextFont(42)
leg.SetTextSize(0.035)
# leg.SetNColumns(3)

# RooFit demmerda
leg.AddEntry(c1.GetPrimitive('fit_function_Norm[%s]_Comp[lxg]' % mass_type),
             'B_{c}#rightarrowJ/#Psi#pi + X', 'L')
leg.AddEntry(
    iso_efficiency.SetFillColor(ROOT.kWhite)
    iso_efficiency.Draw('apl') 
    iso_efficiencies.append(iso_efficiency)
    leg.AddEntry(iso_efficiency, inum[1])
#     if ii==0: leg.AddEntry(0, '', '')

for ii, ieff in enumerate(iso_efficiencies):
    options = 'a'*(ii==0) + 'pl' + ' same'*(ii!=0)
    ieff.Draw(options)
    ieff.SetFillColor(0)
    ieff.SetTitle('; number of true interactions; fake rate')
    ROOT.gPad.SetGridx()
    ROOT.gPad.SetGridy()
    ROOT.gPad.Update()
    ROOT.gPad.SetLogy()
    ROOT.gPad.SetTicky(1)
    ieff.GetPaintedGraph().GetYaxis().SetTitleOffset(1.35)
#     ieff.GetPaintedGraph().GetYaxis().SetRangeUser(1e-5, 0.2)
    ieff.GetPaintedGraph().GetYaxis().SetRangeUser(1e-3, 0.2)
#     ieff.GetPaintedGraph().GetYaxis().SetRangeUser(1e-3, 1.)
    ieff.GetPaintedGraph().GetXaxis().SetRangeUser(0, 75.0001)
    CMS_lumi(ROOT.gPad, 4, 0)
    ROOT.gPad.Update()

# be a better person, always add a legend
leg.Draw('same')
ROOT.gPad.Update()
for iformat in ['png', 'pdf']:
    ROOT.gPad.SaveAs('pu_ntrueint_fr_pt%d.%s' %(pt, iformat))

示例#8
0
文件: makePlot.py 项目: sparolia/pyrk
def makeStack(datah,
              mch_tmp,
              var,
              path,
              fit=False,
              addFileName="",
              rootFile=False,
              ratioPad=True,
              over=False,
              rootPath="rootFiles"):
    os.system('set LD_PRELOAD=libtcmalloc.so')
    ROOT.gROOT.SetBatch()
    #order = ['mu','tau','chic0','chic1','chic2','hc_mu','jpsi_hc','psi2s_mu','psi2s_tau','comb','mis_id']
    order = [
        'mu', 'tau', 'chic0', 'chic1', 'chic2', 'hc_mu', 'jpsi_hc', 'psi2s_mu',
        'comb', 'mis_id'
    ]
    #    order = ["mc_mu", "mc_tau", "mis_id", "mc_comb"]
    his = [
        histo for i, name in enumerate(order) for histo in mch_tmp
        if histo.GetName() == name
    ]
    sm = [
        i for i, name in enumerate(order) for histo in mch_tmp
        if histo.GetName() == name
    ]
    if (len(his) != len(mch_tmp)):
        print("ERROR: Problem in histos names!")
        return 0

    stack = ROOT.THStack("", "")
    for i, histo, sname in zip(sm, his, order):
        '''
        if over:
            histo.SetBinContent(1, histo.GetBinContent(0) + histo.GetBinContent(1))
            histo.SetBinError(1, math.sqrt(pow(histo.GetBinError(0),2) + pow(histo.GetBinError(1),2)))
            histo.SetBinContent(var.nbins, histo.GetBinContent(var.nbins) + histo.GetBinContent(var.nbins+1))
            histo.SetBinError(var.nbins, math.sqrt(pow(histo.GetBinError(var.nbins),2) + pow(histo.GetBinError(var.nbins+1),2)))
        '''
        #histo.Scale(f)
        histo.SetFillColor(sample_dic[sname].color)
        histo.SetLineColor(sample_dic[sname].color)
        histo.GetXaxis().SetRangeUser(var.xmin, var.xmax)
        stack.Add(histo)
    '''
    if over: #for data!
        datah.SetBinContent(1, datah.GetBinContent(0) + datah.GetBinContent(1))
        datah.SetBinError(1, math.sqrt(pow(datah.GetBinError(0),2) + pow(datah.GetBinError(1),2)))
        datah.SetBinContent(var.nbins, datah.GetBinContent(var.nbins) + datah.GetBinContent(var.nbins+1))
        datah.SetBinError(var.nbins, math.sqrt(pow(datah.GetBinError(var.nbins),2) + pow(datah.GetBinError(var.nbins+1),2)))
    '''

    #stack
    datah.SetMarkerStyle(20)
    datah.SetMarkerSize(0.9)
    '''
    datah.SetBinContent(1, datah.GetBinContent(0) + datah.GetBinContent(1))
    datah.SetBinError(1, math.sqrt(pow(datah.GetBinError(0),2) + pow(datah.GetBinError(1),2)))
    datah.SetBinContent(var.nbins, datah.GetBinContent(var.nbins) + datah.GetBinContent(var.nbins+1))
    datah.SetBinError(var.nbins, math.sqrt(pow(datah.GetBinError(var.nbins),2) + pow(datah.GetBinError(var.nbins+1),2)))
    '''
    maximum = max(datah.GetMaximum(), stack.GetMaximum())
    stack.SetMaximum(maximum * 1.5)
    stack.SetMinimum(0.)
    print("INTEGRALE DATA", datah.Integral())
    #legend
    legend = ROOT.TLegend(0.18, 0.65, 0.85, 0.81)
    legend.SetNColumns(3)
    legend.AddEntry(datah, sample_dic["data"].legendName, "lp")
    for histo, sname in zip(his, order):
        legend.AddEntry(histo, sample_dic[sname].legendName, "f")
    legend.SetTextFont(43)
    legend.SetTextSize(15)
    legend.SetBorderSize(0)
    legend.SetFillColor(0)

    ########
    #canvas#
    ########

    if not ratioPad:
        main_pad = ROOT.TCanvas("", "", 700, 700)
        main_pad.SetBottomMargin(2)

    if ratioPad:
        c = ROOT.TCanvas("", "", 700, 700)
        c.cd()
        ############
        # MAIN PAD #
        ############
        main_pad = ROOT.TPad("", "", 0., 0.25, 1., 1.)
        main_pad.SetBottomMargin(0.02)

    main_pad.SetTicks(True)
    main_pad.SetLeftMargin(0.15)
    main_pad.SetRightMargin(0.15)
    main_pad.Draw()
    main_pad.cd()

    stack.Draw("hist")
    legend.Draw("SAME")

    stack.GetYaxis().SetTitle("Events / bin")
    stack.GetYaxis().SetLabelOffset(0.01)
    stack.GetYaxis().SetTitleOffset(2)
    stack.GetYaxis().SetLabelFont(43)
    stack.GetYaxis().SetLabelSize(15)
    stack.GetYaxis().SetTitleFont(43)
    stack.GetYaxis().SetTitleSize(18)

    if not ratioPad:
        stack.GetXaxis().SetLabelOffset(0.01)
    if ratioPad:
        stack.GetXaxis().SetLabelOffset(0.8)

    stack.GetXaxis().SetTitleOffset(1.6)
    stack.GetXaxis().SetLabelFont(43)
    stack.GetXaxis().SetLabelSize(15)
    stack.GetXaxis().SetTitleFont(43)
    stack.GetXaxis().SetTitleSize(18)
    stack.GetXaxis().SetTitle(var.xlabel + " " + var.unit)
    stack.SetMinimum(0.1)
    #ROOT.gPad.SetLogy()

    # Stat. Errors
    h_err = stack.GetStack().Last().Clone("h_err")
    h_err.SetLineWidth(100)
    h_err.SetFillStyle(3154)
    h_err.SetMarkerSize(0)
    h_err.SetFillColor(ROOT.kGray + 2)
    h_err.Draw("e2same0")
    if fit:
        legend.AddEntry(h_err, "Stat. + Syst. Unc.", "f")
    else:
        legend.AddEntry(h_err, "Stat. Unc.", "f")

    datah.Draw("E same")

    CMS_lumi(main_pad, 4, 1)
    main_pad.RedrawAxis()

    if ratioPad:

        #############
        # RATIO PAD #
        #############
        c.cd()
        ratio_pad = ROOT.TPad("", "", 0., 0., 1., 0.25)

        ratio_pad.SetLeftMargin(0.15)
        ratio_pad.SetRightMargin(0.15)
        ratio_pad.SetTopMargin(0.05)
        ratio_pad.SetBottomMargin(0.5)
        ratio_pad.SetGridy()
        c.cd()
        ratio_pad.Draw()
        ratio_pad.cd()

        #f1 = ROOT.TLine(0, 1., 1, 1.)

        f1 = ROOT.TLine(var.xmin, 1., var.xmax, 1.)
        f1.SetLineColor(ROOT.kBlack)
        f1.SetLineStyle(ROOT.kDashed)
        f1.Draw("same")

        hratio = stack.GetStack().Last()
        ratio = datah.Clone("ratio")
        ratio.SetLineColor(ROOT.kBlack)
        ratio.SetMaximum(1.2)
        ratio.SetMinimum(0.8)
        ratio.Sumw2()
        ratio.SetStats(0)

        ratio.Divide(hratio)
        ratio.SetMarkerStyle(20)
        ratio.SetMarkerSize(0.9)
        ratio.Draw("epx0e0")
        ratio.SetTitle("")

        ratio.GetYaxis().SetTitle("Data / MC")
        ratio.GetYaxis().SetNdivisions(503)
        ratio.GetYaxis().SetLabelFont(43)
        ratio.GetYaxis().SetTitleFont(43)
        ratio.GetYaxis().SetTitleOffset(1.5)
        ratio.GetYaxis().SetLabelSize(15)
        ratio.GetYaxis().SetTitleSize(18)
        ratio.GetYaxis().SetRangeUser(0.8, 1.2)
        ratio.GetYaxis().SetLabelOffset(0.01)

        ratio.GetXaxis().SetLabelFont(43)
        ratio.GetXaxis().SetTitleFont(43)
        ratio.GetXaxis().SetTitleOffset(4)
        ratio.GetXaxis().SetLabelSize(15)
        ratio.GetXaxis().SetTitleSize(18)
        ratio.GetXaxis().SetRangeUser(var.xmin, var.xmax)
        ratio.GetXaxis().SetTitle(var.xlabel + " " + var.unit)
        ratio.GetXaxis().SetLabelOffset(0.04)

        h_bkg_err = hratio.Clone("h_err")
        h_bkg_err.Reset()
        h_bkg_err.Sumw2()

        h_bkg_err.SetLineWidth(100)

        for i in range(1, hratio.GetNbinsX() + 1):
            h_bkg_err.SetBinContent(i, 1)
            if (hratio.GetBinContent(i)):
                h_bkg_err.SetBinError(
                    i, (hratio.GetBinError(i) / hratio.GetBinContent(i)))
            else:
                h_bkg_err.SetBinError(i, 10 ^ (-99))
        h_bkg_err.SetLineWidth(100)

        h_bkg_err.SetMarkerSize(0)
        h_bkg_err.SetFillColor(ROOT.kGray + 1)
        h_bkg_err.SetFillStyle(3154)
        h_bkg_err.Draw("e20same")

        ratio.Draw("epx0e0same")

    #ROOT.TGaxis.SetMaxDigits(3)
    if ratioPad:
        c.Update()
    if not ratioPad:
        main_pad.Update()

    if (rootFile == True):
        f = ROOT.TFile.Open(rootPath + "/" + var.name + addFileName + ".root",
                            "RECREATE")
        f.cd()
        for h in his:
            h.Write()
        datah.SetName("data_obs")

        datah.Write()
        f.Close()
        print("Saved " + rootPath + "/" + var.name + addFileName + ".root")
    if fit:
        folder = path + "/"
    else:
        folder = path + "/"

    if not ratioPad:
        main_pad.SaveAs(folder + var.name + "_" + addFileName + ".png")
        main_pad.SaveAs(folder + var.name + "_" + addFileName + ".pdf")

    if ratioPad:
        c.SaveAs(folder + var.name + "_" + addFileName + ".png")
        c.SaveAs(folder + var.name + "_" + addFileName + ".pdf")

    stack.Delete()
    legend.Delete()
    h_err.Delete()
    main_pad.Delete()
    if ratioPad:
        ratio.Delete()
        f1.Delete()
        h_bkg_err.Delete()
        ratio_pad.Delete()
        c.Delete()
示例#9
0
文件: makePlot.py 项目: sparolia/pyrk
def makeComparison(mch_tmp, var, path, addFile=""):
    order = ["mu", "tau", "mis_id", "comb"]
    his = [
        histo for i, name in enumerate(order) for histo in mch_tmp
        if histo.GetName() == name
    ]
    sm = [
        i for i, name in enumerate(order) for histo in mch_tmp
        if histo.GetName() == name
    ]
    names = [
        name for i, name in enumerate(order) for histo in mch_tmp
        if histo.GetName() == name
    ]

    print(his)
    if (len(his) != len(mch_tmp)):
        print("ERROR: Problem in histos names!")
        return 0

    maxy = []
    for i, histo, sname in zip(sm, his, names):
        print(i, histo)
        histo.SetFillColor(0)
        histo.SetLineColor(sample_dic[sname].color)
        histo.GetXaxis().SetRangeUser(var.xmin, var.xmax)
        histo.Scale(1 / histo.Integral())  #drawnormalized
        maxy.append(histo.GetMaximum())

    maximum = max(maxy)
    his[0].SetMaximum(maximum * 1.35)
    his[0].SetMinimum(0.)

    #legend
    legend = ROOT.TLegend(0.57, 0.70, 0.90, 0.86)
    for i, histo, sname in zip(sm, his, names):
        legend.AddEntry(histo, sample_dic[sname].legendName, "f")
    legend.SetTextFont(43)
    legend.SetTextSize(15)
    legend.SetBorderSize(0)
    legend.SetFillColor(0)

    ########
    #canvas#
    ########
    c = ROOT.TCanvas("", "", 700, 700)
    c.cd()

    c.SetTicks(True)
    c.SetBottomMargin(2)
    c.SetLeftMargin(0.15)
    c.SetRightMargin(0.15)
    c.Draw()
    c.cd()

    his[0].Draw("hist")
    for i in range(1, len(his)):
        his[i].Draw("histSAME")
    legend.Draw("SAME")

    his[0].GetYaxis().SetTitle("Events / bin")
    his[0].GetYaxis().SetLabelOffset(0.01)
    his[0].GetYaxis().SetTitleOffset(2)
    his[0].GetYaxis().SetLabelFont(43)
    his[0].GetYaxis().SetLabelSize(15)
    his[0].GetYaxis().SetTitleFont(43)
    his[0].GetYaxis().SetTitleSize(18)

    his[0].GetXaxis().SetLabelOffset(0.01)
    his[0].GetXaxis().SetTitleOffset(1.6)
    his[0].GetXaxis().SetLabelFont(43)
    his[0].GetXaxis().SetLabelSize(15)
    his[0].GetXaxis().SetTitleFont(43)
    his[0].GetXaxis().SetTitleSize(18)
    his[0].GetXaxis().SetTitle(var.xlabel + " " + var.unit)

    CMS_lumi(c, 4, 1)
    c.RedrawAxis()

    folder = path
    c.SaveAs(folder + "BDT_output/" + var.name + "_comparison_" + addFile +
             ".png")
    c.SaveAs(folder + "BDT_output/" + var.name + "_comparison_" + addFile +
             ".pdf")
示例#10
0
def closure_test(passing_mc_ct, failing_mc_ct):
    '''
    Histos for the closure test are created here.
    3 histos made with MC HbToJpsiMuMU with preselection and cut on third muon applied
    1. pass
    2. fail
    3. fail with NN weights taken from the efficiency computation -> should be equal in shape and yield to pass
    '''
    print("#########################################")
    print("####        Closure Test             ####")
    print("#########################################")
    for var in histos:
        print("Computing now variable " + var)

        #histo for the MC in the pass region
        hist_pass = ROOT.TH1D("pass" + histos[var][0], "", histos[var][2],
                              histos[var][3], histos[var][4])
        for item in passing_mc_ct[histos[var][0]]:
            hist_pass.Fill(item)

        # histo for the MC in the fail reigon
        hist_fail = ROOT.TH1D("fail" + histos[var][0], "", histos[var][2],
                              histos[var][3], histos[var][4])
        for item in failing_mc_ct[histos[var][0]]:
            hist_fail.Fill(item)

        hist_pass_w = ROOT.TH1D("passw" + histos[var][0], "", histos[var][2],
                                histos[var][3], histos[var][4])
        for item, nn in zip(failing_mc_ct[histos[var][0]],
                            failing_mc_ct['nn']):
            hist_pass_w.Fill(item, nn / (1 - nn))

        c1.cd()
        leg = ROOT.TLegend(0.24, .67, .95, .90)
        leg.SetBorderSize(0)
        leg.SetFillColor(0)
        leg.SetFillStyle(0)
        leg.SetTextFont(42)
        leg.SetTextSize(0.035)

        main_pad.cd()
        main_pad.SetLogy(False)

        hist_pass.GetXaxis().SetTitle(histos[var][5])
        hist_pass.GetYaxis().SetTitle('events')
        hist_pass.SetLineColor(ROOT.kMagenta)
        hist_pass.SetFillColor(0)

        hist_pass_w.GetXaxis().SetTitle(histos[var][5])
        hist_pass_w.GetYaxis().SetTitle('events')
        hist_pass_w.SetLineColor(ROOT.kOrange)
        hist_pass_w.SetFillColor(0)

        hist_fail.GetXaxis().SetTitle(histos[var][5])
        hist_fail.GetYaxis().SetTitle('events')
        hist_fail.SetLineColor(ROOT.kBlue)
        hist_fail.SetFillColor(0)

        maximum = max(hist_pass.GetMaximum(), hist_fail.GetMaximum(),
                      hist_pass_w.GetMaximum())
        hist_pass.SetMaximum(2. * maximum)

        CMS_lumi(main_pad,
                 4,
                 0,
                 cmsText='CMS',
                 extraText=' Preliminary',
                 lumi_13TeV='')

        hist_pass.Draw('hist ')
        hist_fail.Draw('hist same')
        hist_pass_w.Draw('hist same')

        leg = ROOT.TLegend(0.24, .67, .95, .90)
        leg.SetBorderSize(0)
        leg.SetFillColor(0)
        leg.SetFillStyle(0)
        leg.SetTextFont(42)
        leg.SetTextSize(0.035)

        leg.AddEntry(hist_pass, 'hb_pass', 'F')
        leg.AddEntry(hist_fail, 'hb_fail', 'F')
        leg.AddEntry(hist_pass_w, 'hb_fail_nn', 'F')

        leg.Draw('same')

        # Kilmogorov test
        h_pass = hist_pass.Clone("h_pass")
        h_fail = hist_fail.Clone("h_fail")
        h_pass_w = hist_pass_w.Clone("h_pass_w")
        h_pass.Scale(1. / h_pass.Integral())
        h_pass_w.Scale(1. / h_pass_w.Integral())
        h_fail.Scale(1. / h_fail.Integral())
        h_ratio_passpass = h_pass.Clone("h_ratio_passpass")
        h_ratio_passpass.Divide(h_pass, h_pass)
        h_ratio_failpass = h_fail.Clone("h_ratio_failpass")
        h_ratio_failpass.Divide(h_fail, h_pass)
        h_ratio_passwpass = h_pass_w.Clone("h_ratio_passwpass")
        h_ratio_passwpass.Divide(h_pass_w, h_pass)

        ks_fail = h_ratio_failpass.KolmogorovTest(h_ratio_passpass)
        ks_fail_rw = h_ratio_passwpass.KolmogorovTest(h_ratio_passpass)
        print("KS fail: ", ks_fail)
        print("KS fail rw: ", ks_fail_rw)

        KS_value = ROOT.TPaveText(0.66, 0.7, 0.92, 0.8, 'nbNDC')
        KS_value.AddText('KS fail    = %.4f' % ks_fail)
        KS_value.AddText('KS fail rw = %.4f' % ks_fail_rw)
        KS_value.SetFillColor(0)
        KS_value.Draw('EP')

        #c1.Modified()
        #c1.Update()
        #c1.SaveAs(final_nn_path + '/closure_test/%s.pdf' %(var))
        c1.SaveAs(final_nn_path + '/closure_test/%s.png' % (var))

        maximum = max(h_pass.GetMaximum(), h_fail.GetMaximum(),
                      h_pass_w.GetMaximum())
        h_pass.SetMaximum(2. * maximum)
        h_pass.Draw('hist ')
        h_fail.Draw('hist same')
        h_pass_w.Draw('hist same')
        leg.Draw('same')
        KS_value.Draw('EP')
        c1.SaveAs(final_nn_path + '/closure_test/norm/%s.png' % (var))
示例#11
0
def DrawThis(onetree):
  c2 = ROOT.TCanvas('c2','',700,700)
  c2.cd()
  c2.Draw()
  for effidx, eff in enumerate(iso_efficiencies):
    if 'raw' in var:
      options = 'a'*(effidx!=0) + 'pl' + ' same'*(effidx!=0)
      ROOT.gStyle.SetOptStat(0)
    else:
      options = 'a'*(effidx==0) + 'pl' + ' same'*(effidx!=0)
    eff.Draw(options)
    eff.SetFillColor(0)
    eff.SetTitle('; '+Xtitles[varidx]+'; fake rate')
    ROOT.gPad.SetGridx()
    ROOT.gPad.SetGridy()
    ROOT.gPad.Update()
    ROOT.gPad.SetTicky(1)
    ROOT.gPad.SetLogy('raw' not in var)

    if 'raw' in var:
      eff.GetYaxis().SetTitleOffset(1.35)
      eff.GetYaxis().SetRangeUser(minim-0.5*(maxim*1.05-minim), maxim*1.05)
      eff.GetXaxis().SetRangeUser(Xranges[varidx][0], Xranges[varidx][1])
    else:
      eff.GetPaintedGraph().GetYaxis().SetTitleOffset(1.35)
      # Logscale: Fix if no labels on y axis due to small range:
      #minim/math.sqrt(maxim*1.1/minim), maxim*1.1
      maximdef = maxim*1.1
      minimdef = minim/math.sqrt(maxim/minim)
      onelabel = False
      for loops in [1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001, 0.00000001, 0.000000001]:
         onelabel = onelabel or ((maximdef>=loops) and (minimdef<=loops))
      if not onelabel:
        for loops in [1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001, 0.00000001, 0.000000001]:
          if maximdef > loops:
            minimdef = minimdef/(loops*11.0/maximdef)
            maximdef = loops * 11.0
            break

      twolabels = False
      for loops in [1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001, 0.00000001, 0.000000001]:
         twolabels = twolabels or ((maximdef>=loops) and (minimdef<=loops/10.0))
      if not twolabels:
        for loops in [1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001, 0.00000001, 0.000000001]:
          if minimdef > loops:
            minimdef = loops * 0.9
            break

      eff.GetPaintedGraph().GetYaxis().SetRangeUser(minimdef, maximdef) # Yranges[varidx][0], Yranges[varidx][1]
      #eff.GetPaintedGraph().GetYaxis().SetRangeUser(0.005, 0.035)
      eff.GetPaintedGraph().GetXaxis().SetRangeUser(Xranges[varidx][0], Xranges[varidx][1])

    CMS_lumi(ROOT.gPad, lumiindex, 0)
    ROOT.gPad.Update()

  if not onetree: leg.SetHeader("Fake #tau_{h} from " + samplename + ", " + num[1], "C")
  leg.Draw('same')
  ROOT.gPad.Update()
  for iformat in ['png']: # , 'pdf'
    savename = 'fake_'+var
    if not onetree: savename = 'fake_'+var+'_'+str(numidx)
    if doJet and (WhatAreFakes.lower() not in savename): savename = savename + '_' + WhatAreFakes.lower()
    ROOT.gPad.SaveAs(savename+'.%s' %iformat)
  del c2
示例#12
0
            options = 'hist' + ' same' * (ii != 0)
            #if ieff.Integral()!= 0: ieff.Scale(1./ieff.Integral())
            ieff.Draw(options)
            ieff.SetFillColor(0)
            #maximum = max(maximum, ieff.GetMaximum())
            ROOT.gPad.SetGridx()
            ROOT.gPad.SetGridy()
            ROOT.gPad.Update()
            ROOT.gPad.SetTicky(1)
            ieff.GetYaxis().SetRangeUser(0., 1.6 * maximum)
            ieff.GetXaxis().SetTitle(Xtitles[varidx])
            ieff.GetYaxis().SetTitle('a.u.')
            ieff.GetXaxis().SetTitleOffset(1.3)
            ieff.GetYaxis().SetTitleOffset(1.3)
            # ROOT.gPad.SetLogy(True)
            CMS_lumi(ROOT.gPad, lumiindex, 0)
            ROOT.gPad.Update()

        # be a better person, always add a legend
        leg.Draw('same')
        ROOT.gPad.Update()

        if 'pt' in var: savename = 'pt'
        if 'eta' in var: savename = 'eta'
        if 'ntrueint' in var: savename = 'pu'
        if jnum == 0: savename2 = ''
        elif jnum == 1: savename2 = '_lowpu'
        elif jnum == 2: savename2 = '_midpu'
        elif jnum == 3: savename2 = '_highpu'

        for iformat in ['png']:  #, 'pdf'
示例#13
0
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetTextFont(42)
    leg.SetTextSize(0.035)
    leg.AddEntry(histo.GetPtr(), "data", "lp")
    leg.AddEntry(fit_gaus, "gaus fit", "l")
    c1.SetTicks(True)
    c1.SetBottomMargin(2)
    c1.SetLeftMargin(0.15)
    c1.SetRightMargin(0.15)

    histo.Draw("e")

    leg.Draw("SAME")

    CMS_lumi(c1, 4, 0, cmsText = 'CMS', extraText = '    Preliminary', lumi_13TeV = '')
    fit_gaus.Draw("lsame")

    c1.Modified()
    c1.Update()
    c1.SaveAs('gaus_fit_'+histo.GetPtr().GetName()+'.png')
    integrals.append(histo.Integral())
    funcs.append(fit_gaus)
    


c2= ROOT.TCanvas()
funcs[0].SetMaximum(2.*max(funcs[0].GetMaximum(),funcs[1].GetMaximum()))
funcs[0].SetMinimum(0.)
funcs[0].Draw("l")
funcs[1].Draw("lsame")