示例#1
0
def plotRegion(config,
               cut,
               xTitle,
               yTitle="N Events",
               Logy=0,
               rebin=None,
               rebinarry=None,
               outputFolder=""):
    #load configurations from config file
    filepath = config["root"]
    filename = config["inputdir"]
    outputFolder = config["outputdir"]
    blinded = config["blind"]
    #print config, filepath, filename
    #print cut
    ROOT.gStyle.SetErrorX(0)
    ROOT.gStyle.SetHatchesSpacing(0.7)
    ROOT.gStyle.SetHatchesLineWidth(1)

    # input file
    ifile = ROOT.TFile(filepath + filename + ".root", "read")

    # read stuff
    data = ifile.Get("data_" + cut)
    if "Signal" in cut and blinded:
        data = ifile.Get("data_est_" + cut)
    data_est = ifile.Get("data_est_" + cut)
    qcd = ifile.Get("qcd_est_" + cut)
    #qcd_origin = ifile.Get("qcd_" + cut )
    #print "factor is ", qcd.Integral()/qcd_origin.Integral()
    ttbar = ifile.Get("ttbar_est_" + cut)
    #zjet = ifile.Get("zjet_" + cut )
    RSG1_1000 = ifile.Get("RSG1_1000_" + cut)
    RSG1_1500 = ifile.Get("RSG1_1500_" + cut)
    RSG1_1500.Scale(10)
    RSG1_2500 = ifile.Get("RSG1_2500_" + cut)
    RSG1_2500.Scale(100)

    if not rebin == None:
        data.Rebin(rebin)
        data_est.Rebin(rebin)
        qcd.Rebin(rebin)
        ttbar.Rebin(rebin)
        #zjet.Rebin(rebin)
        RSG1_1000.Rebin(rebin)
        RSG1_1500.Rebin(rebin)
        RSG1_2500.Rebin(rebin)

    #use array to rebin histgrams
    if not rebinarry == None:
        data = data.Rebin(
            len(rebinarry) - 1,
            data.GetName() + "_rebinned", rebinarry)
        data_est = data_est.Rebin(
            len(rebinarry) - 1,
            data_est.GetName() + "_rebinned", rebinarry)
        qcd = qcd.Rebin(
            len(rebinarry) - 1,
            qcd.GetName() + "_rebinned", rebinarry)
        ttbar = ttbar.Rebin(
            len(rebinarry) - 1,
            ttbar.GetName() + "_rebinned", rebinarry)
        #zjet      = zjet.Rebin(len(rebinarry) - 1, zjet.GetName()+"_rebinned", rebinarry)
        RSG1_1000 = RSG1_1000.Rebin(
            len(rebinarry) - 1,
            RSG1_1000.GetName() + "_rebinned", rebinarry)
        RSG1_1500 = RSG1_1500.Rebin(
            len(rebinarry) - 1,
            RSG1_1500.GetName() + "_rebinned", rebinarry)
        RSG1_2500 = RSG1_2500.Rebin(
            len(rebinarry) - 1,
            RSG1_2500.GetName() + "_rebinned", rebinarry)

    #get QS scores
    if "Signal" in cut and blinded:
        ks = 0
    else:
        ks = data.KolmogorovTest(data_est, "QU")
    int_data = data.Integral(0, data.GetXaxis().GetNbins() + 1)
    int_data_est = data_est.Integral(0, data_est.GetXaxis().GetNbins() + 1)
    percentdiff = (int_data_est - int_data) / int_data * 100.0
    #chi2 =        data.Chi2Test(data_est, "QU CHI2")
    #ndf  = chi2 / data.Chi2Test(data_est, "QU CHI2/NDF") if chi2 else 0.0

    xMin = data.GetXaxis().GetBinLowEdge(1)
    xMax = data.GetXaxis().GetBinUpEdge(data.GetXaxis().GetNbins())
    yMax = data.GetMaximum() * 1.8
    if ("FourTag" in cut):
        yMax = data.GetMaximum() * 2.0
    if Logy == 1:
        yMax = yMax * 20
    #qcd_fit = ifile.Get("qcd_fit")
    #qcd_fitUp = ifile.Get("qcd_fitUp")
    #qcd_fitDown = ifile.Get("qcd_fitDown")
    syst_up = []
    syst_down = []
    if ("Control" in cut and "mHH" in cut):
        #print "deal with CR mass systmeatics"
        #hard code a file...
        if cut.find("FourTag") > -1:
            tag = "FourTag"
        elif cut.find("ThreeTag") > -1:
            tag = "ThreeTag"
        elif cut.find("TwoTag") > -1:
            tag = "TwoTag_split"
        #print CONF.inputpath + ops.inputdir + "/Limitinput/" + ops.inputdir + "_limit_" + tag + "_fullsys.root"
        #syst_file = ROOT.TFile(CONF.inputpath + ops.inputdir + "/Limitinput/" + ops.inputdir + "_limit_" + tag + "_fullsys.root", "read")
        syst_file = ROOT.TFile(
            CONF.inputpath + ops.inputdir + "/Limitinput/" + ops.inputdir +
            "_limit_" + tag + "_CR.root", "read")
        syst_file.cd()
        for key in ROOT.gDirectory.GetListOfKeys():
            kname = key.GetName()
            # if "QCDShape" in kname:
            #     continue
            temp_syst_norm = ttbar.Clone()
            temp_syst_norm.Add(qcd, 1)
            if "totalbkg_hh" in kname and ("QCDShapeCRLow" in kname
                                           or "QCDShapeCRHigh" in kname):
                temp_syst = syst_file.Get(kname).Clone(kname)
                temp_syst.Scale(temp_syst_norm.Integral() /
                                temp_syst.Integral())
                if "up" in kname:
                    syst_up.append(temp_syst)
                elif "down" in kname:
                    syst_down.append(temp_syst)
        syst_file.Close()
    #print len(syst_up), len(syst_down)

    data = h_plt.makeTotBkg([data])[1]
    bkg = h_plt.makeTotBkg([ttbar, qcd], syst_up, syst_down)
    #bkg = makeTotBkg([ttbar,qcd,zjet])
    # bkg/data ratios: [0] band for stat errors, [1] bkg/data with syst errors
    ratios = h_plt.makeDataRatio(data, bkg[1])

    # stack signal on background
    RSG1_1000.Add(bkg[0])
    RSG1_1500.Add(bkg[0])
    RSG1_2500.Add(bkg[0])

    # canvas
    c0 = ROOT.TCanvas("c0" + filename + cut,
                      "Insert hilarious TCanvas name here", 800, 600)
    c0.SetRightMargin(0.05)

    # top pad
    pad0 = ROOT.TPad("pad0", "pad0", 0.0, 0.31, 1., 1.)
    pad0.SetRightMargin(0.05)
    pad0.SetBottomMargin(0.0001)
    pad0.SetFrameFillColor(0)
    pad0.SetFrameBorderMode(0)
    pad0.SetFrameFillColor(0)
    pad0.SetBorderMode(0)
    pad0.SetBorderSize(0)

    pad1 = ROOT.TPad("pad1", "pad1", 0.0, 0.0, 1., 0.30)
    pad1.SetRightMargin(0.05)
    pad1.SetBottomMargin(0.38)
    pad1.SetTopMargin(0.0001)
    pad1.SetFrameFillColor(0)
    pad1.SetFillStyle(0)  # transparent
    pad1.SetFrameBorderMode(0)
    pad1.SetFrameFillColor(0)
    pad1.SetBorderMode(0)
    pad1.SetBorderSize(0)

    c0.cd()
    pad0.SetLogy(Logy)
    pad0.Draw()
    pad0.cd()

    bkg[0].SetTitle("")
    bkg[0].SetStats(0)
    bkg[0].SetLineColor(ROOT.kBlack)
    bkg[0].SetLineWidth(2)
    bkg[0].GetYaxis().SetTitleFont(43)
    bkg[0].GetYaxis().SetTitleSize(35)
    bkg[0].GetYaxis().SetLabelFont(43)
    bkg[0].GetYaxis().SetLabelSize(28)
    bkg[0].GetYaxis().SetTitle(yTitle)
    bkg[0].GetYaxis().SetTitleOffset(1.25)
    if ("Control" in cut and "mHH" in cut):
        bkg[0].GetYaxis().SetRangeUser(0.02, yMax)  #set range for ratio plot
    else:
        bkg[0].GetYaxis().SetRangeUser(0.2, yMax)
    bkg[0].SetFillColor(ROOT.kYellow)
    bkg[0].Draw("HISTO")

    # RSG1_1000.SetLineWidth(2)
    # RSG1_1000.SetLineStyle(2)
    # RSG1_1000.SetLineColor(ROOT.kViolet+7)
    # RSG1_1000.Draw("HISTO SAME")

    RSG1_1500.SetLineWidth(2)
    RSG1_1500.SetLineStyle(2)
    RSG1_1500.SetLineColor(ROOT.kPink + 7)
    #RSG1_1500.Draw("HISTO SAME")

    RSG1_2500.SetLineWidth(2)
    RSG1_2500.SetLineStyle(2)
    RSG1_2500.SetLineColor(ROOT.kGreen + 4)
    #RSG1_2500.Draw("HISTO SAME")

    bkg[1].SetFillColor(CONF.col_dic["syst"])
    bkg[1].SetLineColor(CONF.col_dic["syst"])
    bkg[1].SetFillStyle(3345)
    bkg[1].SetMarkerSize(0)
    bkg[1].Draw("E2 SAME")

    ttbar.SetLineWidth(2)
    ttbar.SetLineColor(ROOT.kBlack)
    ttbar.SetFillColor(ROOT.kAzure - 9)
    ttbar.Draw("HISTO SAME")

    #zjet.SetLineWidth(2)
    #zjet.SetLineColor(ROOT.kBlack)
    #zjet.SetFillColor(ROOT.kGreen+4)
    #zjet.Draw("HISTO SAME")

    h_plt.zeroXerror(data)
    data.SetMarkerStyle(20)
    data.SetMarkerSize(1)
    data.SetLineWidth(2)
    data.GetXaxis().SetLabelSize(0)
    data.GetXaxis().SetLabelOffset(999)
    if not ("Signal" in cut and blinded):
        data.Draw("EPZ SAME")

    # bottom pad
    c0.cd()
    pad1.Draw()
    pad1.cd()

    hratio = ROOT.TH1F("hratio", "", 1, xMin, xMax)
    hratio.SetStats(0)

    hratio.GetYaxis().SetTitleFont(43)
    hratio.GetYaxis().SetTitleSize(35)
    hratio.GetYaxis().SetLabelFont(43)
    hratio.GetYaxis().SetLabelSize(28)
    hratio.GetYaxis().SetTitleOffset(1.25)
    hratio.GetYaxis().SetTitle("Data / Bkgd")
    if ("Control" in cut and "mHH" in cut):
        hratio.GetYaxis().SetRangeUser(0.5, 2.4)  #set range for ratio plot
    else:
        hratio.GetYaxis().SetRangeUser(0.5, 1.5)  #set range for ratio plot

    hratio.GetYaxis().SetNdivisions(405)
    hratio.GetXaxis().SetTitleFont(43)
    hratio.GetXaxis().SetTitleOffset(2.8)
    hratio.GetXaxis().SetTitleSize(35)
    hratio.GetXaxis().SetLabelFont(43)
    hratio.GetXaxis().SetLabelSize(28)
    hratio.GetXaxis().SetTitle(xTitle)

    hratio.Draw()

    #
    # Add stat uncertianty
    #
    ratios[0].SetFillColor(CONF.col_dic["syst"])
    ratios[0].SetFillStyle(3345)
    ratios[0].Draw("E2")

    #zeroXerror(ratios[1])
    ratios[1].SetMarkerStyle(20)
    ratios[1].SetMarkerSize(1)
    ratios[1].SetLineWidth(2)
    if not ("Signal" in cut and blinded):
        ratios[1].Draw("E0PZ SAME")
    h_plt.drawarrow(ratios[1], 0.4, 1.8)
    # qcd_fit.SetLineColor(kRed)
    # qcd_fitUp.SetLineColor(kRed)
    # qcd_fitUp.SetLineStyle(2)
    # qcd_fitDown.SetLineColor(kRed)
    # qcd_fitDown.SetLineStyle(2)
    # qcd_fit.Draw("SAME")
    # qcd_fitUp.Draw("SAME")
    # qcd_fitDown.Draw("SAME")

    # Fit the ratio with a TF1
    # if not ("Signal" in cut and blinded):
    #     testfit = ROOT.TF1("testfit", "pol2", xMin, xMax)
    #     testfit.SetParameters(1, 0, 0)
    #     ratios[1].Fit("testfit")
    #     testfit.SetLineColor(kRed)
    #     testfit.Draw("SAME")
    #     fitresult = testfit.GetParameters()
    #     myText(0.2, 0.17, 1, "y=%s x^2 + %s x + %s" % (str('%.2g' % fitresult[0]), \
    #         str('%.2g' % fitresult[1]),str('%.2g' % fitresult[2])), CONF.paperlegsize)

    # draw the ratio 1 line
    line = ROOT.TLine(xMin, 1.0, xMax, 1.0)
    line.SetLineStyle(1)
    line.Draw()

    c0.cd()
    #
    # Add ks score
    #
    #myText(0.15, 0.97, 1, "KS = %s" % str(('%.3g' % ks)), CONF.paperlegsize)
    #myText(0.4, 0.97, 1, "(Est-Obs)/Obs = %s; E=%s; O=%s" % (str(('%.1f' % percentdiff)), str(('%.1f' % int_data_est)), str(('%.1f' % int_data))), CONF.paperlegsize)
    #myText(0.15, 0.92, 1, "#chi^{2} / ndf = %s / %s" % (str(chi2), str(ndf)), CONF.paperlegsize)

    # labels
    legHunit = 0.05
    legH = legHunit * 6  # retuned below based on number of entries to 0.05*num_entries
    legW = 0.4
    if ("Control" in cut and "mHH" in cut):
        leg = ROOT.TLegend(0.57, 0.83, 0.93, 0.93)
    else:
        leg = ROOT.TLegend(0.57, 0.83, 0.93, 0.93)
    # top right, a bit left
    ROOT.ATLASLabel(0.19, 0.91, StatusLabel)
    if "15" in filepath:
        ROOT.myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 2015, 3.2 fb^{-1}",
                    CONF.paperlegsize)
    elif "16" in filepath:
        ROOT.myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 2016, 2.6 fb^{-1}",
                    CONF.paperlegsize)
    else:
        ROOT.myText(0.19, 0.87, 1,
                    "#sqrt{s}=13 TeV, " + str(CONF.totlumi) + " fb^{-1}",
                    CONF.paperlegsize)
    if cut.find("Signal") > -1:
        if filename.find("ZZ"):
            tag = "Low Mass Validation Region"
        if filename.find("TT"):
            tag = "High Mass Validation Region"
        else:
            tag = "Boosted Signal Region"
    elif cut.find("Control") > -1:
        tag = "Boosted Control Region"
    elif cut.find("Sideband") > -1:
        tag = "Boosted Sideband Region"
    if cut.find("FourTag") > -1:
        tag += ", 4-tag"
    elif cut.find("ThreeTag") > -1:
        tag += ", 3-tag"
    elif cut.find("TwoTag") > -1:
        tag += ", 2-tag"
    ROOT.myText(0.19, 0.83, 1, tag, CONF.paperlegsize)
    ##### legend
    #leg.SetNColumns(2)
    leg.SetTextFont(43)
    leg.SetTextSize(CONF.paperlegsize)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)
    leg.AddEntry(data, "Data", "PE")
    leg.AddEntry(bkg[0], "Multijet", "F")
    leg.AddEntry(ttbar, "t#bar{t}", "F")
    #leg.AddEntry(zjet, "Z+jets","F")
    if ("Control" in cut and "mHH" in cut):
        leg.AddEntry(bkg[1], "Stat Uncertainties", "FF")
    else:
        leg.AddEntry(bkg[1], "Stat Uncertainties", "FF")

    #leg.AddEntry(RSG1_1000, "RSG1, 1TeV", "F")
    #leg.AddEntry(RSG1_1500, "RSG 1.5TeV * 10", "F")
    #leg.AddEntry(RSG1_2500, "RSG 2.5TeV * 100", "F")
    #leg.AddEntry(qcd_fit, "Fit to Ratio", "L")
    #leg.AddEntry(qcd_fitUp, "#pm 1#sigma Uncertainty", "L")
    leg.SetY1(leg.GetY2() - leg.GetNRows() * legHunit)
    leg.Draw()

    # save
    postname = ("" if Logy == 0 else "_" + str(Logy)) + (
        "" if not ("Signal" in cut and blinded) else "_blind")
    #c0.SaveAs(outputFolder+"/"+filename.replace(".root", ".pdf"))
    c0.SaveAs(outputFolder + "/" + filename + "_" + cut + postname + ".png")
    c0.SaveAs(outputFolder + "/" + filename + "_" + cut + postname + ".pdf")
    c0.SaveAs(outputFolder + "/" + filename + "_" + cut + postname + ".eps")
    c0.SaveAs(outputFolder + "/" + filename + "_" + cut + postname + ".C")
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + ".pdf")
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + ".eps")

    pad0.Close()
    pad1.Close()
    c0.Close()
示例#2
0
def plotRegion(config,
               cut,
               xTitle,
               yTitle="N Events",
               Logy=0,
               labelPos=11,
               rebin=None,
               rebinarry=[],
               fitrange=[0, 0]):
    #load configurations from config file
    filepath = config["root"]
    filename = config["inputdir"]
    outputFolder = config["outputdir"]
    #debug
    #print filepath, filename, cut
    ROOT.gStyle.SetErrorX(0)
    ROOT.gStyle.SetHatchesSpacing(0.7)
    ROOT.gStyle.SetHatchesLineWidth(1)
    # input file
    ifile = ROOT.TFile(filepath + filename + ".root")
    # read stuff
    #print "data_" + cut
    if config[
            "compcut"] is not "":  ## this means qcd estimate is something special now; NOTICE: things are inverted here!!!
        #print config, filepath, filename, config["compcut"]
        data = ifile.Get("data_" +
                         cut.replace(config["cut"], config["compcut"]))
        ttbar = ifile.Get("ttbar_" +
                          cut.replace(config["cut"], config["compcut"]))
        qcd = ifile.Get("data_" + cut)  #note these are the compcut plots
        ttbar_est = ifile.Get("ttbar_" + cut)
        #zjet = ifile.Get("zjet_" + cut )
        data.Add(ttbar, -1)
        qcd.Add(
            ttbar_est, -1
        )  ##special treatment here; directly subtracting the MC component
    else:  ##default method
        data = ifile.Get("data_" + cut)
        qcd = ifile.Get("qcd_est_" + cut)
        ttbar = ifile.Get("ttbar_est_" + cut)
        #zjet = ifile.Get("zjet_" + cut )
        #modify data
        data.Add(ttbar, -1)
        #data.Add(zjet, -1)
    #qcd_origin = ifile.Get("qcd_" + cut )
    #print "factor is ", qcd.Integral()/qcd_origin.Integral()

    #clear factioned binns; only for reweighting purpose
    # for b in range(1, data.GetNbinsX()+1):
    #     if  data.GetBinContent(b) < 1:
    #         data.SetBinContent(b, 0)
    #         data.SetBinError(b, 0)

    #swap data if blinded
    if "Signal" in cut and blinded:
        data = qcd.Clone()
    #do rebin
    if not rebin == None:
        data.Rebin(rebin)
        qcd.Rebin(rebin)
        ttbar.Rebin(rebin)
        #zjet.Rebin(rebin)
    if rebinarry != []:
        data = h_plt.do_variable_rebinning(data, rebinarry)
        qcd = h_plt.do_variable_rebinning(qcd, rebinarry)
        ttbar = h_plt.do_variable_rebinning(ttbar, rebinarry)
        #zjet      = h_plt.do_variable_rebinning(zjet, rebinarry)

    #get QS scores
    if "Signal" in cut and blinded:
        ks = 0
    else:
        ks = data.KolmogorovTest(qcd, "QU")
    int_data = data.Integral(0, data.GetXaxis().GetNbins() + 1)
    int_qcd = qcd.Integral(0, qcd.GetXaxis().GetNbins() + 1)
    percentdiff = (int_qcd - int_data) / int_data * 100.0
    #chi2 =        data.Chi2Test(qcd, "QU CHI2")
    #ndf  = chi2 / data.Chi2Test(qcd, "QU CHI2/NDF") if chi2 else 0.0
    if config["compcut"] is not "":
        ##special treatment here: for comps, rescale the original distributions
        ##thus the number of events is kept the same!
        data.Scale(int_qcd / int_data)

    xMin = data.GetXaxis().GetBinLowEdge(1)
    xMax = data.GetXaxis().GetBinUpEdge(data.GetXaxis().GetNbins())
    yMax = data.GetMaximum() * 1.5
    if Logy == 1:
        yMax = yMax * 100

    ##Tony: a fix for only the ratios used in reweighting; idea from Patrick
    hist_ratio = data.Clone("ratio")
    hist_ratio.Divide(qcd)
    hist_ratio.Smooth()
    #this is the important part...where the backgrounds are set
    data = h_plt.makeTotBkg([data])[1]
    bkg = h_plt.makeTotBkg([qcd])
    #bkg = h_plt.makeTotBkg([ttbar,qcd,zjet]) #original
    # bkg/data ratios: [0] band for bkg errors, [1] bkg/data with stat errors only
    ratios = h_plt.makeDataRatio(data, bkg[1])

    # canvas
    c0 = ROOT.TCanvas("c0" + filename + cut,
                      "Insert hilarious TCanvas name here", 800, 800)
    c0.SetRightMargin(0.05)

    # top pad
    pad0 = ROOT.TPad("pad0", "pad0", 0.0, 0.31, 1., 1.)
    pad0.SetRightMargin(0.05)
    pad0.SetBottomMargin(0.0001)
    pad0.SetFrameFillColor(0)
    pad0.SetFrameBorderMode(0)
    pad0.SetFrameFillColor(0)
    pad0.SetBorderMode(0)
    pad0.SetBorderSize(0)

    pad1 = ROOT.TPad("pad1", "pad1", 0.0, 0.0, 1., 0.30)
    pad1.SetRightMargin(0.05)
    pad1.SetBottomMargin(0.38)
    pad1.SetTopMargin(0.0001)
    pad1.SetFrameFillColor(0)
    pad1.SetFillStyle(0)  # transparent
    pad1.SetFrameBorderMode(0)
    pad1.SetFrameFillColor(0)
    pad1.SetBorderMode(0)
    pad1.SetBorderSize(0)

    c0.cd()
    pad0.SetLogy(Logy)
    pad0.Draw()
    pad0.cd()

    bkg[0].SetTitle("")
    bkg[0].SetStats(0)
    bkg[0].SetLineColor(ROOT.kBlack)
    bkg[0].SetLineWidth(2)
    bkg[0].GetYaxis().SetTitleFont(43)
    bkg[0].GetYaxis().SetTitleSize(28)
    bkg[0].GetYaxis().SetLabelFont(43)
    bkg[0].GetYaxis().SetLabelSize(28)
    bkg[0].GetYaxis().SetTitle(yTitle)
    bkg[0].GetYaxis().SetRangeUser(0.001, yMax)
    bkg[0].SetFillColor(ROOT.kYellow)
    bkg[0].Draw("HISTO")

    bkg[1].SetFillColor(CONF.col_dic["syst"])
    bkg[1].SetLineColor(CONF.col_dic["syst"])
    bkg[1].SetFillStyle(3345)
    bkg[1].SetMarkerSize(0)
    bkg[1].Draw("E2 SAME")

    #ttbar.SetLineWidth(2)
    #ttbar.SetLineColor(ROOT.kBlack)
    #ttbar.SetFillColor(ROOT.kAzure-9)
    #ttbar.Draw("HISTO SAME")

    #zjet.SetLineWidth(2)
    #zjet.SetLineColor(ROOT.kBlack)
    #zjet.SetFillColor(ROOT.kGreen+4)
    #zjet.Draw("HISTO SAME")

    h_plt.zeroXerror(data)
    data.SetMarkerStyle(20)
    data.SetMarkerSize(1)
    data.SetLineWidth(2)
    data.GetXaxis().SetLabelSize(0)
    data.GetXaxis().SetLabelOffset(999)
    if not ("Signal" in cut and blinded):
        data.Draw("EPZ SAME")

    # bottom pad
    c0.cd()
    pad1.Draw()
    pad1.cd()

    hratio = ROOT.TH1F("hratio", "", 1, xMin, xMax)
    hratio.SetStats(0)
    ratio_ylow = 0.5  ##this the ratio low bin
    ratio_yhigh = 1.5  ##this the ratio high bin
    hratio.GetYaxis().SetTitleFont(43)
    hratio.GetYaxis().SetTitleSize(28)
    hratio.GetYaxis().SetLabelFont(43)
    hratio.GetYaxis().SetLabelSize(28)
    hratio.GetYaxis().SetTitle("Data / Bkgd")
    hratio.GetYaxis().SetRangeUser(ratio_ylow,
                                   ratio_yhigh)  #set range for ratio plot
    hratio.GetYaxis().SetNdivisions(405)

    hratio.GetXaxis().SetTitleFont(43)
    hratio.GetXaxis().SetTitleOffset(3.5)
    hratio.GetXaxis().SetTitleSize(28)
    hratio.GetXaxis().SetLabelFont(43)
    hratio.GetXaxis().SetLabelSize(28)
    hratio.GetXaxis().SetTitle(xTitle)

    hratio.Draw()

    #
    # Add stat uncertianty
    #
    ratios[0].SetFillColor(CONF.col_dic["syst"])
    ratios[0].SetFillStyle(3345)
    ratios[0].Draw("E2")

    #zeroXerror(ratios[1])
    ratios[1].SetMarkerStyle(20)
    ratios[1].SetMarkerSize(1)
    ratios[1].SetLineWidth(2)
    if not ("Signal" in cut and blinded):
        ratios[1].Draw("E0PZ SAME")

    ##add arrows; call this function
    h_plt.drawarrow(ratios[1], ratio_ylow, ratio_yhigh)
    # ratio_arrow = ROOT.TArrow(0, 0, 0, 0, 0.01, "|>")
    # ratio_arrow.SetLineWidth(3)
    # ratio_arrow.SetLineColor(ROOT.kBlue)
    # ratio_arrow.SetFillColor(ROOT.kBlue)

    # for pt in xrange(ratios[1].GetN()):
    #     y = ratios[1].GetY()[pt]
    #     x = ratios[1].GetX()[pt]
    #     y_low  = y + ratios[1].GetEYhigh()[pt]
    #     y_high = y - ratios[1].GetEYlow()[pt]
    #     if y_low < ratio_ylow * 1.1:
    #         ratio_arrow.DrawArrow(x, 1 - abs(1 - ratio_ylow)*2./3., x, ratio_ylow)
    #     elif y_high > ratio_yhigh * 0.9:
    #         ratio_arrow.DrawArrow(x, 1 + abs(1 - ratio_yhigh)*2./3., x, ratio_yhigh)

    testfit = {}
    # Fit the ratio with a TF1
    if not ("Signal" in cut and blinded):
        if fitrange == [0, 0]:
            fitMin = xMin
            fitMax = xMax
        else:
            fitMin = fitrange[0]
            fitMax = fitrange[1]

        #enable smart fit~! will pick the highest prob fit
        #no 0 order polynomial!!!
        for iter_fit in range(1, 4):
            testfit[iter_fit] = ROOT.TF1("testfit" + str(iter_fit),
                                         "pol" + str(iter_fit), xMin, xMax)
        #initialization of parameters
        if ("trk0_Pt" in cut):  #for the leading track jet fit
            #testfit[3].SetParameters(1, 0.006, -2E-5, +2E-8)
            testfit[3].SetParameters(0.76, 0.009, -5E-5, +9E-8)
            #testfit[3].SetParameters(0.6, 0.007, -3E-5, +3E-8); testing version
        elif ("trk1_Pt" in cut):  #for the subleading track jet fit
            testfit[2].SetParameters(0.82, 0.004, -1E-5)
        elif ("trks_Pt" in cut):  #for the subleading track jet fit
            testfit[3].SetParameters(0.82, 0.004, -2E-5, -2E-8)
        elif ("trk_pt_diff" in cut):  #for the subleading track jet fit
            testfit[3].SetParameters(1, 0.001, -0.000001, -0.00000001)
        elif ("Pt_m" in cut):  #for the subleading track jet fit
            testfit[1].SetParameters(0.9, 0.0005)
        elif ("Rhh" in cut):  #for the subleading track jet fit
            testfit[1].SetParameters(1, 0.7)
        #for the other distributions
        testfit[1].SetParameters(0.9, 0.001)
        #testfit[1].SetParLimits(1, 0.8, 1.2)
        testfit[2].SetParameters(1.0, 0.0, 0.0)
        #testfit[2].SetParLimits(0, 0.8, 1.2)
        testfit[3].SetParameters(1.0, 0.0, 0.0, 0.0)

        #do the 3 fits and save the output
        testfitprob = [0]
        for iter_fit in range(1, 4):
            ratios[1].Fit("testfit" + str(iter_fit), "QWLR0IBF", "", fitMin,
                          fitMax)
            testfitprob.append(float(testfit[iter_fit].GetProb()))
        #pick the best iteration; try to avoid higher order function as much as possible
        best_iter = 1
        if testfitprob[2] / (testfitprob[best_iter] + 1E-8) > 1.1:
            best_iter = 2
        if testfitprob[3] / (testfitprob[best_iter] + 1E-8) > 1.1:
            best_iter = 3

        #proceed with saving parameters
        fitprob = testfitprob[best_iter]
        fitresult = testfit[best_iter].GetParameters()
        if len(fitresult) < 4:  #fill in 0 if there are less than 3 paramters
            fitresult += [int(0)] * (4 - len(fitresult))
        testfit[best_iter].SetLineColor(ROOT.kRed)
        testfit[best_iter].SetLineStyle(9)
        testfit[best_iter].Draw("SAME")
        ROOT.myText(
            0.02, 0.17, 1, "y=%s + %s x + %sx^2 + %sx^3, prob:%s" %
            (str('%.2g' % fitresult[0]), str('%.2g' % fitresult[1]),
             str('%.2g' % fitresult[2]), str(
                 '%.2g' % fitresult[3]), str('%.2g' % fitprob)), CONF.legsize)
        #draw the line for stat and end of the fit
        ystart = ROOT.TLine(fitMin, 0.60, fitMin, 1.40)
        ystart.SetLineStyle(5)
        ystart.Draw()
        yend = ROOT.TLine(fitMax, 0.60, fitMax, 1.40)
        yend.SetLineStyle(5)
        yend.Draw()

        #write out the reweighting parameteres; for things in the sideband only
        f_reweight = open(
            reweightfolder + "r" + str(iter_reweight) + "_" + cut + ".txt",
            "w")
        f_reweight.write("reweighting function of: " + cut + "; prob is: " +
                         str('%.2g' % fitprob) + "\n")
        f_reweight.write("par0: " + str('%.3g' % fitresult[0]) + " \n")
        f_reweight.write("par1: " + str('%.3g' % fitresult[1]) + " \n")
        f_reweight.write("par2: " + str('%.3g' % fitresult[2]) + " \n")
        f_reweight.write("par3: " + str('%.3g' % fitresult[3]) + " \n")
        f_reweight.write("low:  " + str('%.3g' % fitMin) + " \n")
        f_reweight.write("high: " + str('%.3g' % fitMax) + " \n")
        f_reweight.close()

        #done with the fit!!
        #try spline interpolation: CSPLINE, LINEAR, POLYNOMIAL, CSPLINE_PERIODIC, AKIMA, AKIMA_PERIODIC
        inter = ROOT.Math.Interpolator(0, ROOT.Math.Interpolation.kCSPLINE)
        ni = ratios[1].GetN()  ##GetN()
        xi = ROOT.vector('double')(ni + 2)
        yi = ROOT.vector('double')(ni + 2)
        #deal with the beginning
        for k in range(0, ni):
            xk = ROOT.Double()
            yk = ROOT.Double()
            ratios[1].GetPoint(k, xk, yk)
            xi[k + 1] = xk
            yi[k + 1] = yk
        #for edge effects
        xi[0] = xi[1] - abs(xi[1] - xi[2])
        yi[0] = yi[1]
        xi[ni + 1] = xi[ni] + abs(xi[ni] - xi[ni - 1])
        yi[ni + 1] = yi[ni]
        inter.SetData(xi, yi)
        temp_graph = ROOT.TGraph(ni + 2)
        for k in range(0, ni + 2):
            temp_graph.SetPoint(k, xi[k], yi[k])

        spline = ROOT.TSpline3(cut, temp_graph)
        #spline = ROOT.TSpline3(hist_ratio)
        spline.SaveAs(reweightfolder + "rs" + str(iter_reweight) + "_" + cut +
                      ".cxx")
        hist_ratio.SetMarkerColor(ROOT.kGreen)
        hist_ratio.Draw("SAME")

        inter_step = 5
        xf = ROOT.vector('double')(ni * inter_step)
        yf = ROOT.vector('double')(ni * inter_step)
        inter_graph = ROOT.TGraph(ni * inter_step)
        spline_graph = ROOT.TGraph(ni * inter_step)
        for k in range(0, (ni * inter_step)):
            xf[k] = xi[0] + (xi[ni + 1] - xi[0]) / (ni * inter_step * 1.0) * k
            #print k, xf[k], inter.Eval(xf[k])
            inter_graph.SetPoint(k, xf[k], inter.Eval(xf[k]))
            spline_graph.SetPoint(k, xf[k], spline.Eval(xf[k]))

        inter_graph.SetLineColor(ROOT.kBlue)  ## this is the interpolation
        inter_graph.SetLineWidth(2)
        inter_graph.Draw("SAME L")
        spline_graph.SetLineColor(ROOT.kGreen)  ## this is the spline fit
        spline_graph.SetLineWidth(2)
        spline_graph.Draw("SAME L")

    # draw the ratio 1 line
    line = ROOT.TLine(xMin, 1.0, xMax, 1.0)
    line.SetLineStyle(1)
    line.Draw()

    c0.cd()
    #
    # Add ks score
    #
    ROOT.myText(0.15, 0.97, 1, "KS = %s" % str(('%.3g' % ks)), CONF.legsize)
    ROOT.myText(
        0.4, 0.97, 1, "(Est-Obs)/Obs = %s; E=%s; O=%s" % (str(
            ('%.1f' % percentdiff)), str(
                ('%.1f' % int_qcd)), str(('%.1f' % int_data))), CONF.legsize)
    #myText(0.15, 0.92, 1, "#chi^{2} / ndf = %s / %s" % (str(chi2), str(ndf)), CONF.legsize)

    # labels
    legHunit = 0.05
    legH = legHunit * 6  # retuned below based on number of entries to 0.05*num_entries
    legW = 0.4
    leg = ROOT.TLegend(0.65, 0.75, 0.95, 0.95)
    # top right, a bit left
    ROOT.ATLASLabel(0.19, 0.91, StatusLabel)
    if "15" in filepath:
        ROOT.myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 2015, 3.2 fb^{-1}",
                    CONF.legsize)
    elif "16" in filepath:
        ROOT.myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 2016, 2.6 fb^{-1}",
                    CONF.legsize)
    elif "cb" in filepath:
        ROOT.myText(
            0.19, 0.87, 1,
            "#sqrt{s}=13 TeV, 15+16, " + str(CONF.totlumi) + " fb^{-1}",
            CONF.legsize)
    else:
        ROOT.myText(
            0.19, 0.87, 1,
            "#sqrt{s}=13 TeV, 15+16, " + str(CONF.totlumi) + " fb^{-1}",
            CONF.legsize)
    ##### legend
    leg.SetNColumns(1)
    leg.SetTextFont(43)
    leg.SetTextSize(12)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)
    if config["compcut"] is not "":
        #inverted here as well!!!
        leg.AddEntry(data, config["compcut"].replace("_", " "), "PE")
        leg.AddEntry(bkg[0], config["cut"].replace("_", " "), "F")
    else:
        leg.AddEntry(data, "Data", "PE")
        leg.AddEntry(bkg[0], "Multijet Est", "F")
    #leg.AddEntry(ttbar, "t#bar{t}","F")
    #leg.AddEntry(zjet, "Z+jets","F")
    leg.AddEntry(bkg[1], "Stat Uncertainty", "F")
    #leg.AddEntry(RSG1_1000, "RSG1, 1TeV", "F")
    #leg.AddEntry(RSG1_1500, "RSG1, 1.5TeV * 25", "F")
    #leg.AddEntry(RSG1_2500, "RSG1, 2.5TeV * 1000", "F")
    #leg.AddEntry(qcd_fit, "Fit to Ratio", "L")
    #leg.AddEntry(qcd_fitUp, "#pm 1#sigma Uncertainty", "L")
    leg.SetY1(leg.GetY2() - leg.GetNRows() * legHunit)
    leg.Draw()

    # save
    postname = ("" if Logy == 0 else "_" + str(Logy)) + (
        "" if not ("Signal" in cut and blinded) else "_blind")
    #c0.SaveAs(outputFolder+"/"+filename.replace(".root", ".pdf"))
    c0.SaveAs(outputFolder + "/" + filename + "_" + cut + postname + ".png")
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".pdf")
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + ".pdf")
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + ".eps")

    pad0.Close()
    pad1.Close()
    c0.Close()
    del (data)
    del (qcd)
    del (ttbar)
    #del(zjet)
    #del(RSG1_1000)
    #del(RSG1_1500)
    #del(RSG1_2500)
    del (testfit)

    ##rename the spline function generated
    with open(reweightfolder + "rs" + str(iter_reweight) + "_" + cut + ".cxx",
              "r") as f:
        newlines = []
        for line in f.readlines():
            newlines.append(
                line.replace("/afs/cern",
                             "rs" + str(iter_reweight) + "_" + cut))
        with open(
                reweightfolder + "rs" + str(iter_reweight) + "_" + cut +
                ".cxx", "w") as f:
            for line in newlines:
                f.write(line)

    ##should only be run non-parellel.
    if ("Sideband" in cut and False):
        outputroot.cd()
        ratios[1].SetName(cut)
        ratios[1].Write()
示例#3
0
def plotRegion(config,
               cut,
               xTitle,
               yTitle="N Events",
               Logy=0,
               rebin=None,
               rebinarry=None,
               outputFolder="",
               doZjet=False):
    #load configurations from config file
    filepath = config["root"]
    filename = config["inputdir"]
    outputFolder = config["outputdir"]
    blinded = config["blind"]
    #print config, filepath, filename, cut
    ROOT.gStyle.SetErrorX(0)
    ROOT.gStyle.SetHatchesSpacing(0.7)
    ROOT.gStyle.SetHatchesLineWidth(1)

    # input file
    ifile = ROOT.TFile(filepath + filename + ".root")
    # read stuff
    data = ifile.Get("data_" + cut)
    if "Signal" in cut and blinded:
        data = ifile.Get("data_est_" + cut)
    data_est = ifile.Get("data_est_" + cut)
    qcd = ifile.Get("qcd_est_" + cut)
    #qcd_origin = ifile.Get("qcd_" + cut )
    #print "factor is ", qcd.Integral()/qcd_origin.Integral()
    ttbar = ifile.Get("ttbar_est_" + cut)
    if (doZjet):
        zjet = ifile.Get("zjet_" + cut)
    RSG1_1000 = ifile.Get("RSG1_1000_" + cut)
    RSG1_1500 = ifile.Get("RSG1_1500_" + cut)
    RSG1_1500.Scale(10)
    RSG1_2000 = ifile.Get("RSG1_2000_" + cut)
    RSG1_2000.Scale(30)
    RSG1_2500 = ifile.Get("RSG1_2500_" + cut)
    RSG1_2500.Scale(100)
    SMhh = ifile.Get("sm_" + cut)
    SMhh.Scale(100)

    #do simple rebin as rebin values
    if not rebin == None:
        data.Rebin(rebin)
        data_est.Rebin(rebin)
        qcd.Rebin(rebin)
        ttbar.Rebin(rebin)
        if (doZjet):
            zjet.Rebin(rebin)
        RSG1_1000.Rebin(rebin)
        RSG1_1500.Rebin(rebin)
        RSG1_2000.Rebin(rebin)
        RSG1_2500.Rebin(rebin)
        SMhh.Rebin(rebin)
    #use array to rebin histgrams
    if not rebinarry == None:
        data = data.Rebin(
            len(rebinarry) - 1,
            data.GetName() + "_rebinned", rebinarry)
        data_est = data_est.Rebin(
            len(rebinarry) - 1,
            data_est.GetName() + "_rebinned", rebinarry)
        qcd = qcd.Rebin(
            len(rebinarry) - 1,
            qcd.GetName() + "_rebinned", rebinarry)
        ttbar = ttbar.Rebin(
            len(rebinarry) - 1,
            ttbar.GetName() + "_rebinned", rebinarry)
        if (doZjet):
            zjet = zjet.Rebin(
                len(rebinarry) - 1,
                zjet.GetName() + "_rebinned", rebinarry)
        RSG1_1000 = RSG1_1000.Rebin(
            len(rebinarry) - 1,
            RSG1_1000.GetName() + "_rebinned", rebinarry)
        RSG1_1500 = RSG1_1500.Rebin(
            len(rebinarry) - 1,
            RSG1_1500.GetName() + "_rebinned", rebinarry)
        RSG1_2000 = RSG1_2000.Rebin(
            len(rebinarry) - 1,
            RSG1_2000.GetName() + "_rebinned", rebinarry)
        RSG1_2500 = RSG1_2500.Rebin(
            len(rebinarry) - 1,
            RSG1_2500.GetName() + "_rebinned", rebinarry)
        SMhh = SMhh.Rebin(
            len(rebinarry) - 1,
            RSG1_2500.GetName() + "_rebinned", rebinarry)

    #get QS scores
    if "Signal" in cut and blinded:
        ks = 0
    else:
        ks = data.KolmogorovTest(data_est, "QU")
    int_data = data.Integral(0, data.GetXaxis().GetNbins() + 1)
    int_data_est = data_est.Integral(0, data_est.GetXaxis().GetNbins() + 1)
    percent_ratio = (int_data) / int_data_est
    #chi2 =        data.Chi2Test(data_est, "QU CHI2")
    #ndf  = chi2 / data.Chi2Test(data_est, "QU CHI2/NDF") if chi2 else 0.0

    #load basic information
    xMin = data.GetXaxis().GetBinLowEdge(1)
    xMax = data.GetXaxis().GetBinUpEdge(data.GetXaxis().GetNbins())
    yMax = data.GetMaximum() * 1.6
    if ("FourTag" in cut):
        yMax = data.GetMaximum() * 2.0
    if Logy == 1:
        yMax = yMax * 100
    #qcd_fit = ifile.Get("qcd_fit")
    #qcd_fitUp = ifile.Get("qcd_fitUp")
    #qcd_fitDown = ifile.Get("qcd_fitDown")

    ##add in normalization error at least
    syst_up = []
    syst_down = []
    f1 = open(filepath + filename + ".txt")
    masterdic = json.load(f1)

    ##find the systmatics from the fit
    cut_temp = cut.split("_")
    if cut_temp[1] == "split":
        cut_temp.remove("split")
        cut_temp[0] = "TwoTag_split"
    #for key_temp, value_temp in masterdic["data_est_nofit"][cut_temp[0]].iteritems():
    #print key_temp, value_temp, cut_temp[1]
    #print key_temp, value_temp,
    ##this is the total error in the region from the fit
    #print masterdic["data_est_nofit"][cut_temp[0]][cut_temp[1] + "_err"]
    temp_syst_up = data_est.Clone(data_est.GetName() + "_syst_up")
    temp_syst_up.Scale(
        (data_est.Integral() +
         masterdic["data_est_nofit"][cut_temp[0]][cut_temp[1] + "_err"]) /
        data_est.Integral())
    #print "here", (data_est.Integral() + masterdic["data_est_nofit"][cut_temp[0]][cut_temp[1] + "_err"])/data_est.Integral()
    temp_syst_down = data_est.Clone(data_est.GetName() + "_syst_down")
    temp_syst_down.Scale(
        (data_est.Integral() -
         masterdic["data_est_nofit"][cut_temp[0]][cut_temp[1] + "_err"]) /
        data_est.Integral())
    syst_up.append(temp_syst_up)
    syst_down.append(temp_syst_down)

    #setup data and bkg estiamtes
    data = h_plt.makeTotBkg([data])[1]
    bkg = h_plt.makeTotBkg([ttbar, qcd])
    if (doZjet):
        bkg = h_plt.makeTotBkg([ttbar, qcd, zjet])
    #bkg = h_plt.makeTotBkg([ttbar,qcd], syst_up, syst_down)
    #bkg = h_plt.makeTotBkg([ttbar,qcd,zjet], syst_up, syst_down)
    # bkg/data ratios: [0] band for stat errors, [1] bkg/data with syst errors
    ratios = h_plt.makeDataRatio(data, bkg[1])

    # stack signal on background
    RSG1_1000.Add(bkg[0])
    RSG1_1500.Add(bkg[0])
    RSG1_2000.Add(bkg[0])
    RSG1_2500.Add(bkg[0])
    #SMhh.Add(bkg[0])  ##don't add bkg for SMhh

    # canvas
    c0 = ROOT.TCanvas("c0" + filename + cut,
                      "Insert hilarious TCanvas name here", 600, 600)
    c0.SetRightMargin(0.05)

    # top pad
    pad0 = ROOT.TPad("pad0", "pad0", 0.0, 0.31, 1., 1.)
    pad0.SetRightMargin(0.05)
    pad0.SetBottomMargin(0.0001)
    pad0.SetFrameFillColor(0)
    pad0.SetFrameBorderMode(0)
    pad0.SetFrameFillColor(0)
    pad0.SetBorderMode(0)
    pad0.SetBorderSize(0)

    pad1 = ROOT.TPad("pad1", "pad1", 0.0, 0.0, 1., 0.30)
    pad1.SetRightMargin(0.05)
    pad1.SetBottomMargin(0.38)
    pad1.SetTopMargin(0.0001)
    pad1.SetFrameFillColor(0)
    pad1.SetFillStyle(0)  # transparent
    pad1.SetFrameBorderMode(0)
    pad1.SetFrameFillColor(0)
    pad1.SetBorderMode(0)
    pad1.SetBorderSize(0)

    c0.cd()
    pad0.SetLogy(Logy)
    pad0.Draw()
    pad0.cd()

    bkg[0].SetTitle("")
    bkg[0].SetStats(0)
    bkg[0].SetLineColor(ROOT.kBlack)
    bkg[0].SetLineWidth(2)
    bkg[0].GetYaxis().SetTitleFont(43)
    bkg[0].GetYaxis().SetTitleSize(28)
    bkg[0].GetYaxis().SetLabelFont(43)
    bkg[0].GetYaxis().SetLabelSize(28)
    bkg[0].GetYaxis().SetTitle(yTitle)
    bkg[0].GetYaxis().SetRangeUser(0.02, yMax)
    bkg[0].SetFillColor(ROOT.kYellow)
    bkg[0].Draw("HISTO")

    # RSG1_1000.SetLineWidth(2)
    # RSG1_1000.SetLineStyle(2)
    # RSG1_1000.SetLineColor(ROOT.kViolet+7)
    # RSG1_1000.Draw("HISTO SAME")

    RSG1_1500.SetLineWidth(2)
    RSG1_1500.SetLineStyle(2)
    RSG1_1500.SetLineColor(ROOT.kPink + 7)
    #RSG1_1500.Draw("HISTO SAME")

    RSG1_2000.SetLineWidth(2)
    RSG1_2000.SetLineStyle(2)
    RSG1_2000.SetLineColor(ROOT.kPink + 7)
    RSG1_2000.Draw("HISTO SAME")

    RSG1_2500.SetLineWidth(2)
    RSG1_2500.SetLineStyle(2)
    RSG1_2500.SetLineColor(ROOT.kGreen + 4)
    #RSG1_2500.Draw("HISTO SAME")

    SMhh.SetLineWidth(2)
    SMhh.SetLineStyle(2)
    SMhh.SetLineColor(ROOT.kGreen + 4)
    if ("Signal" in cut):
        SMhh.Draw("HISTO SAME")

    bkg[1].SetFillColor(CONF.col_dic["syst"])
    bkg[1].SetLineColor(CONF.col_dic["syst"])
    bkg[1].SetFillStyle(3345)
    bkg[1].SetMarkerSize(0)
    bkg[1].Draw("E2 SAME")

    ttbar.SetLineWidth(2)
    ttbar.SetLineColor(ROOT.kBlack)
    ttbar.SetFillColor(ROOT.kAzure - 9)
    ttbar.Draw("HISTO SAME")

    if (doZjet):
        zjet.SetLineWidth(2)
        zjet.SetLineColor(ROOT.kBlack)
        zjet.SetFillColor(ROOT.kGreen + 4)
        zjet.Draw("HISTO SAME")

    h_plt.zeroXerror(data)
    data.SetMarkerStyle(20)
    data.SetMarkerSize(1)
    data.SetLineWidth(2)
    data.GetXaxis().SetLabelSize(0)
    data.GetXaxis().SetLabelOffset(999)
    if not ("Signal" in cut and blinded):
        data.Draw("EPZ SAME")

    # bottom pad
    c0.cd()
    pad1.Draw()
    pad1.cd()

    hratio = ROOT.TH1F("hratio", "", 1, xMin, xMax)
    hratio.SetStats(0)

    hratio.GetYaxis().SetTitleFont(43)
    hratio.GetYaxis().SetTitleSize(28)
    hratio.GetYaxis().SetLabelFont(43)
    hratio.GetYaxis().SetLabelSize(28)
    hratio.GetYaxis().SetTitle("Data / Bkgd")
    hratio.GetYaxis().SetRangeUser(0.4, 1.8)  #set range for ratio plot
    hratio.GetYaxis().SetNdivisions(405)

    hratio.GetXaxis().SetTitleFont(43)
    hratio.GetXaxis().SetTitleOffset(3.5)
    hratio.GetXaxis().SetTitleSize(28)
    hratio.GetXaxis().SetLabelFont(43)
    hratio.GetXaxis().SetLabelSize(28)
    hratio.GetXaxis().SetTitle(xTitle)

    hratio.Draw()

    #
    # Add stat uncertianty
    #
    ratios[0].SetFillColor(CONF.col_dic["syst"])
    ratios[0].SetFillStyle(3345)
    ratios[0].Draw("E2")

    #h_plt.zeroXerror(ratios[1])
    ratios[1].SetMarkerStyle(20)
    ratios[1].SetMarkerSize(1)
    ratios[1].SetLineWidth(2)
    if not ("Signal" in cut and blinded):
        ratios[1].Draw("E0PZ SAME")
    ##add arrows; call this function
    h_plt.drawarrow(ratios[1], 0.4, 1.8)
    # qcd_fit.SetLineColor(kRed)
    # qcd_fitUp.SetLineColor(kRed)
    # qcd_fitUp.SetLineStyle(2)
    # qcd_fitDown.SetLineColor(kRed)
    # qcd_fitDown.SetLineStyle(2)
    # qcd_fit.Draw("SAME")
    # qcd_fitUp.Draw("SAME")
    # qcd_fitDown.Draw("SAME")

    ## Fit the ratio with a TF1
    if ("mHH" in cut and not blinded):
        testfit = ROOT.TF1("testfit", "pol1", xMin, xMax)
        testfit.SetParameters(1, 0)
        ratios[1].Fit("testfit", "QLWW0IBF", "")
        testfit.SetLineColor(ROOT.kRed)
        testfit.SetLineStyle(9)
        testfit.Draw("SAME")
        fitresult = testfit.GetParameters()
        ROOT.myText(0.15, 0.12, 1, "y=%s x + %s, prob:%s" % (str('%.2g' % fitresult[0]), \
            str('%.2g' % fitresult[1]), str('%.2g' % float(testfit.GetProb()))), CONF.legsize)

    # draw the ratio 1 line
    line = ROOT.TLine(xMin, 1.0, xMax, 1.0)
    line.SetLineStyle(1)
    line.Draw()
    c0.cd()

    #
    # Add ks score
    #
    if (ops.detail):
        ROOT.myText(0.15, 0.97, 1, "KS = %s" % str(('%.3g' % ks)),
                    CONF.legsize)
        ROOT.myText(
            0.4, 0.97, 1, "Obs/Est = %s/%s = %s" % (str(
                ('%.1f' % int_data)), str(
                    ('%.1f' % int_data_est)), str(('%.3f' % percent_ratio))),
            CONF.legsize)
        #myText(0.15, 0.92, 1, "#chi^{2} / ndf = %s / %s" % (str(chi2), str(ndf)), CONF.legsize)

    # labels
    legHunit = 0.05
    legH = legHunit * 6  # retuned below based on number of entries to 0.05*num_entries
    legW = 0.4
    leg = ROOT.TLegend(0.65, 0.75, 0.95, 0.95)
    # top right, a bit left
    if not CONF.thesis:
        ROOT.ATLASLabel(0.19, 0.91, CONF.StatusLabel)
    if "15" in filepath:
        ROOT.myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 2015, 3.2 fb^{-1}",
                    CONF.legsize)
    elif "16" in filepath:
        ROOT.myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 2016, 2.6 fb^{-1}",
                    CONF.legsize)
    else:
        ROOT.myText(
            0.19, 0.87, 1,
            "#sqrt{s}=13 TeV, 15+16, " + str(CONF.totlumi) + " fb^{-1}",
            CONF.legsize)

    #clean up the info string
    infostr = cut
    infostr = infostr.replace("_", ";")
    infostr = infostr.replace("Sideband",
                              "SB") if "Sideband" in infostr else infostr
    infostr = infostr.replace("Control",
                              "CR") if "Sideband" in infostr else infostr
    infostr = infostr.replace("Signal",
                              "SR") if "Sideband" in infostr else infostr
    infostr = infostr.replace("FourTag",
                              "4b") if "FourTag" in infostr else infostr
    infostr = infostr.replace("ThreeTag",
                              "3b") if "ThreeTag" in infostr else infostr
    infostr = infostr.replace("TwoTag;split",
                              "2bs") if "TwoTag;split" in infostr else infostr
    ROOT.myText(0.19, 0.83, 1, ' ' + infostr, CONF.legsize)

    ##### legend
    #leg.SetNColumns(2)
    leg.SetTextFont(43)
    leg.SetTextSize(CONF.legsize)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)
    leg.AddEntry(data, "Data", "PE")
    leg.AddEntry(bkg[0], "Multijet", "F")
    leg.AddEntry(ttbar, "t#bar{t}", "F")
    if (doZjet):
        leg.AddEntry(zjet, "Z+jets", "F")
    leg.AddEntry(bkg[1], "Stat Uncer.", "F")
    #leg.AddEntry(RSG1_1000, "RSG1, 1TeV", "F")
    #leg.AddEntry(RSG1_1500, "RSG 1.5TeV * 10", "F")
    leg.AddEntry(RSG1_2000, "G(2000)#times30", "F")
    #leg.AddEntry(RSG1_2500, "RSG 2.5TeV * 100", "F")
    if ("Signal" in cut):
        leg.AddEntry(SMhh, "SMNR#times1000", "F")
    #leg.AddEntry(qcd_fit, "Fit to Ratio", "L")
    #leg.AddEntry(qcd_fitUp, "#pm 1#sigma Uncertainty", "L")
    leg.SetY1(leg.GetY2() - leg.GetNRows() * legHunit)
    leg.Draw()

    # save
    postname = ("" if Logy == 0 else "_" + str(Logy)) + (
        "" if not ("Signal" in cut and blinded) else "_blind")
    #c0.SaveAs(outputFolder+"/"+filename.replace(".root", ".pdf"))
    c0.SaveAs(outputFolder + "/" + filename + "_" + cut + postname + ".png")
    c0.SaveAs(outputFolder + "/" + filename + "_" + cut + postname + ".pdf")
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".eps")
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".C")

    #close and quit
    pad0.Close()
    pad1.Close()
    c0.Close()
    f1.close()
    del (leg)
示例#4
0
def plotRegion(config, cut, xTitle, yTitle="N Events", Logy=0, rebin=None, rebinarry=None, outputFolder=""):
    #load configurations from config file
    filepath = config["root"] 
    filename = config["inputdir"] 
    outputFolder= config["outputdir"]
    blinded = config["blind"]
    #print config, filepath, filename
    #print cut
    ROOT.gStyle.SetErrorX(0)
    ROOT.gStyle.SetHatchesSpacing(0.7)
    ROOT.gStyle.SetHatchesLineWidth(1)

    # input file
    ifile = ROOT.TFile(filepath + filename + ".root", "read")

    # read stuff
    data = ifile.Get("data_" + cut )
    if "Signal" in cut and blinded:
        data = ifile.Get("data_est_" + cut )
    data_est = ifile.Get("data_est_" + cut )
    qcd = ifile.Get("qcd_est_" + cut )
    #qcd_origin = ifile.Get("qcd_" + cut )
    #print "factor is ", qcd.Integral()/qcd_origin.Integral()
    ttbar = ifile.Get("ttbar_est_" + cut )
    #zjet = ifile.Get("zjet_" + cut )
    RSG1_1000 = ifile.Get("RSG1_1000_" + cut )
    RSG1_1500 = ifile.Get("RSG1_1500_" + cut )
    RSG1_1500.Scale(10)
    RSG1_2500 = ifile.Get("RSG1_2500_" + cut )
    RSG1_2500.Scale(100)

    if not rebin == None:
        data.Rebin(rebin)
        data_est.Rebin(rebin)
        qcd.Rebin(rebin)
        ttbar.Rebin(rebin)
        #zjet.Rebin(rebin)
        RSG1_1000.Rebin(rebin)
        RSG1_1500.Rebin(rebin)
        RSG1_2500.Rebin(rebin)

    #use array to rebin histgrams
    if not rebinarry == None:
        data      = data.Rebin(len(rebinarry) - 1, data.GetName()+"_rebinned", rebinarry)
        data_est  = data_est.Rebin(len(rebinarry) - 1, data_est.GetName()+"_rebinned", rebinarry)
        qcd       = qcd.Rebin(len(rebinarry) - 1, qcd.GetName()+"_rebinned", rebinarry)
        ttbar     = ttbar.Rebin(len(rebinarry) - 1, ttbar.GetName()+"_rebinned", rebinarry)
        #zjet      = zjet.Rebin(len(rebinarry) - 1, zjet.GetName()+"_rebinned", rebinarry)
        RSG1_1000 = RSG1_1000.Rebin(len(rebinarry) - 1, RSG1_1000.GetName()+"_rebinned", rebinarry)
        RSG1_1500 = RSG1_1500.Rebin(len(rebinarry) - 1, RSG1_1500.GetName()+"_rebinned", rebinarry)
        RSG1_2500 = RSG1_2500.Rebin(len(rebinarry) - 1, RSG1_2500.GetName()+"_rebinned", rebinarry)

    #get QS scores
    if "Signal" in cut and blinded:
        ks = 0
    else:
        ks   = data.KolmogorovTest(data_est, "QU")
    int_data = data.Integral(0, data.GetXaxis().GetNbins()+1)
    int_data_est = data_est.Integral(0, data_est.GetXaxis().GetNbins()+1)
    percentdiff   = (int_data_est - int_data)/int_data * 100.0
    #chi2 =        data.Chi2Test(data_est, "QU CHI2")
    #ndf  = chi2 / data.Chi2Test(data_est, "QU CHI2/NDF") if chi2 else 0.0

    xMin = data.GetXaxis().GetBinLowEdge(1)
    xMax = data.GetXaxis().GetBinUpEdge(data.GetXaxis().GetNbins())
    yMax = data.GetMaximum() * 1.8
    if ("FourTag" in cut):
        yMax = data.GetMaximum() * 2.0
    if Logy==1:
        yMax = yMax * 20
    #qcd_fit = ifile.Get("qcd_fit")
    #qcd_fitUp = ifile.Get("qcd_fitUp")
    #qcd_fitDown = ifile.Get("qcd_fitDown")
    syst_up = []
    syst_down = []
    if ("Control" in cut and "mHH" in cut):
        #print "deal with CR mass systmeatics"
        #hard code a file...
        if cut.find("FourTag") > -1:
            tag = "FourTag"
        elif cut.find("ThreeTag") > -1:
            tag = "ThreeTag"
        elif cut.find("TwoTag") > -1:
            tag = "TwoTag_split"
        #print CONF.inputpath + ops.inputdir + "/Limitinput/" + ops.inputdir + "_limit_" + tag + "_fullsys.root"
        #syst_file = ROOT.TFile(CONF.inputpath + ops.inputdir + "/Limitinput/" + ops.inputdir + "_limit_" + tag + "_fullsys.root", "read")
        syst_file = ROOT.TFile(CONF.inputpath + ops.inputdir + "/Limitinput/" + ops.inputdir + "_limit_" + tag + "_CR.root", "read")
        syst_file.cd()
        for key in ROOT.gDirectory.GetListOfKeys():
            kname = key.GetName()
            # if "QCDShape" in kname:
            #     continue
            temp_syst_norm = ttbar.Clone()
            temp_syst_norm.Add(qcd, 1)
            if "totalbkg_hh" in kname and ("QCDShapeCRLow" in kname or "QCDShapeCRHigh" in kname):
                temp_syst = syst_file.Get(kname).Clone(kname)
                temp_syst.Scale(temp_syst_norm.Integral()/temp_syst.Integral())
                if "up" in kname:
                    syst_up.append(temp_syst)
                elif "down" in kname:
                    syst_down.append(temp_syst)
        syst_file.Close()
    #print len(syst_up), len(syst_down)


    data = h_plt.makeTotBkg([data])[1]
    bkg  = h_plt.makeTotBkg([ttbar,qcd], syst_up, syst_down)
    #bkg = makeTotBkg([ttbar,qcd,zjet])
    # bkg/data ratios: [0] band for stat errors, [1] bkg/data with syst errors
    ratios = h_plt.makeDataRatio(data, bkg[1])

    # stack signal on background
    RSG1_1000.Add(bkg[0]) 
    RSG1_1500.Add(bkg[0]) 
    RSG1_2500.Add(bkg[0]) 

    # canvas
    c0 = ROOT.TCanvas("c0"+filename+cut, "Insert hilarious TCanvas name here", 800, 600)
    c0.SetRightMargin(0.05)

    # top pad
    pad0 = ROOT.TPad("pad0", "pad0", 0.0, 0.31, 1., 1.)
    pad0.SetRightMargin(0.05)
    pad0.SetBottomMargin(0.0001)
    pad0.SetFrameFillColor(0)
    pad0.SetFrameBorderMode(0)
    pad0.SetFrameFillColor(0)
    pad0.SetBorderMode(0)
    pad0.SetBorderSize(0)

    pad1 = ROOT.TPad("pad1", "pad1", 0.0, 0.0, 1., 0.30)
    pad1.SetRightMargin(0.05)
    pad1.SetBottomMargin(0.38)
    pad1.SetTopMargin(0.0001)
    pad1.SetFrameFillColor(0)
    pad1.SetFillStyle(0) # transparent
    pad1.SetFrameBorderMode(0)
    pad1.SetFrameFillColor(0)
    pad1.SetBorderMode(0)
    pad1.SetBorderSize(0)

    c0.cd()
    pad0.SetLogy(Logy)
    pad0.Draw()
    pad0.cd()


    bkg[0].SetTitle("")
    bkg[0].SetStats(0)
    bkg[0].SetLineColor(ROOT.kBlack)
    bkg[0].SetLineWidth(2)
    bkg[0].GetYaxis().SetTitleFont(43)
    bkg[0].GetYaxis().SetTitleSize(35)
    bkg[0].GetYaxis().SetLabelFont(43)
    bkg[0].GetYaxis().SetLabelSize(28)
    bkg[0].GetYaxis().SetTitle(yTitle)
    bkg[0].GetYaxis().SetTitleOffset(1.25)
    if ("Control" in cut and "mHH" in cut):
        bkg[0].GetYaxis().SetRangeUser(0.02, yMax) #set range for ratio plot
    else:
        bkg[0].GetYaxis().SetRangeUser(0.2, yMax)
    bkg[0].SetFillColor(ROOT.kYellow)
    bkg[0].Draw("HISTO")

    # RSG1_1000.SetLineWidth(2)
    # RSG1_1000.SetLineStyle(2)
    # RSG1_1000.SetLineColor(ROOT.kViolet+7)
    # RSG1_1000.Draw("HISTO SAME")

    RSG1_1500.SetLineWidth(2)
    RSG1_1500.SetLineStyle(2)
    RSG1_1500.SetLineColor(ROOT.kPink+7)
    #RSG1_1500.Draw("HISTO SAME")

    RSG1_2500.SetLineWidth(2)
    RSG1_2500.SetLineStyle(2)
    RSG1_2500.SetLineColor(ROOT.kGreen+4)
    #RSG1_2500.Draw("HISTO SAME")

    bkg[1].SetFillColor(CONF.col_dic["syst"])
    bkg[1].SetLineColor(CONF.col_dic["syst"])
    bkg[1].SetFillStyle(3345)
    bkg[1].SetMarkerSize(0)
    bkg[1].Draw("E2 SAME")

    ttbar.SetLineWidth(2)
    ttbar.SetLineColor(ROOT.kBlack)
    ttbar.SetFillColor(ROOT.kAzure-9)
    ttbar.Draw("HISTO SAME")

    #zjet.SetLineWidth(2)
    #zjet.SetLineColor(ROOT.kBlack)
    #zjet.SetFillColor(ROOT.kGreen+4)
    #zjet.Draw("HISTO SAME")

    h_plt.zeroXerror(data)
    data.SetMarkerStyle(20)
    data.SetMarkerSize(1)
    data.SetLineWidth(2)
    data.GetXaxis().SetLabelSize(0)
    data.GetXaxis().SetLabelOffset(999)
    if not ("Signal" in cut and blinded):
        data.Draw("EPZ SAME")

    # bottom pad
    c0.cd()
    pad1.Draw()
    pad1.cd()

    hratio = ROOT.TH1F("hratio","",1, xMin, xMax)
    hratio.SetStats(0)
    
    hratio.GetYaxis().SetTitleFont(43)
    hratio.GetYaxis().SetTitleSize(35)
    hratio.GetYaxis().SetLabelFont(43)
    hratio.GetYaxis().SetLabelSize(28)
    hratio.GetYaxis().SetTitleOffset(1.25)
    hratio.GetYaxis().SetTitle("Data / Bkgd")
    if ("Control" in cut and "mHH" in cut):
        hratio.GetYaxis().SetRangeUser(0.5, 2.4) #set range for ratio plot
    else:
        hratio.GetYaxis().SetRangeUser(0.5, 1.5) #set range for ratio plot

    hratio.GetYaxis().SetNdivisions(405)
    hratio.GetXaxis().SetTitleFont(43)
    hratio.GetXaxis().SetTitleOffset(2.8)
    hratio.GetXaxis().SetTitleSize(35)
    hratio.GetXaxis().SetLabelFont(43)
    hratio.GetXaxis().SetLabelSize(28)
    hratio.GetXaxis().SetTitle(xTitle)

    hratio.Draw()

    #
    # Add stat uncertianty
    #
    ratios[0].SetFillColor(CONF.col_dic["syst"])
    ratios[0].SetFillStyle(3345)
    ratios[0].Draw("E2")

    #zeroXerror(ratios[1])
    ratios[1].SetMarkerStyle(20)
    ratios[1].SetMarkerSize(1)
    ratios[1].SetLineWidth(2)
    if not ("Signal" in cut and blinded):
        ratios[1].Draw("E0PZ SAME")
    h_plt.drawarrow(ratios[1], 0.4, 1.8)
    # qcd_fit.SetLineColor(kRed)
    # qcd_fitUp.SetLineColor(kRed)
    # qcd_fitUp.SetLineStyle(2)
    # qcd_fitDown.SetLineColor(kRed)
    # qcd_fitDown.SetLineStyle(2)
    # qcd_fit.Draw("SAME")
    # qcd_fitUp.Draw("SAME")
    # qcd_fitDown.Draw("SAME")

    # Fit the ratio with a TF1
    # if not ("Signal" in cut and blinded):
    #     testfit = ROOT.TF1("testfit", "pol2", xMin, xMax)
    #     testfit.SetParameters(1, 0, 0)
    #     ratios[1].Fit("testfit")
    #     testfit.SetLineColor(kRed)
    #     testfit.Draw("SAME")
    #     fitresult = testfit.GetParameters()
    #     myText(0.2, 0.17, 1, "y=%s x^2 + %s x + %s" % (str('%.2g' % fitresult[0]), \
    #         str('%.2g' % fitresult[1]),str('%.2g' % fitresult[2])), CONF.paperlegsize)

    # draw the ratio 1 line
    line = ROOT.TLine(xMin, 1.0, xMax, 1.0)
    line.SetLineStyle(1)
    line.Draw()

    c0.cd()
    #
    # Add ks score
    #
    #myText(0.15, 0.97, 1, "KS = %s" % str(('%.3g' % ks)), CONF.paperlegsize)
    #myText(0.4, 0.97, 1, "(Est-Obs)/Obs = %s; E=%s; O=%s" % (str(('%.1f' % percentdiff)), str(('%.1f' % int_data_est)), str(('%.1f' % int_data))), CONF.paperlegsize)
    #myText(0.15, 0.92, 1, "#chi^{2} / ndf = %s / %s" % (str(chi2), str(ndf)), CONF.paperlegsize)

    # labels
    legHunit=0.05
    legH=legHunit*6 # retuned below based on number of entries to 0.05*num_entries
    legW=0.4
    if ("Control" in cut and "mHH" in cut):
        leg = ROOT.TLegend(0.57, 0.83, 0.93, 0.93)
    else:
        leg = ROOT.TLegend(0.57, 0.83, 0.93, 0.93)
    # top right, a bit left
    ROOT.ATLASLabel(0.19, 0.91, StatusLabel)
    if "15" in filepath:
        ROOT.myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 2015, 3.2 fb^{-1}", CONF.paperlegsize)
    elif "16" in filepath:
        ROOT.myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 2016, 2.6 fb^{-1}", CONF.paperlegsize)
    else:
        ROOT.myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, " + str(CONF.totlumi) + " fb^{-1}", CONF.paperlegsize)
    if cut.find("Signal") > -1:
        if filename.find("ZZ"):
            tag = "Low Mass Validation Region"
        if filename.find("TT"):
            tag = "High Mass Validation Region"
        else:
            tag = "Boosted Signal Region"
    elif cut.find("Control") > -1:
        tag = "Boosted Control Region"
    elif cut.find("Sideband") > -1:
        tag = "Boosted Sideband Region"
    if cut.find("FourTag") > -1:
        tag += ", 4-tag"
    elif cut.find("ThreeTag") > -1:
        tag += ", 3-tag"
    elif cut.find("TwoTag") > -1:
        tag += ", 2-tag"
    ROOT.myText(0.19, 0.83, 1, tag, CONF.paperlegsize)
    ##### legend
    #leg.SetNColumns(2)
    leg.SetTextFont(43)
    leg.SetTextSize(CONF.paperlegsize)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)
    leg.AddEntry(data, "Data", "PE")
    leg.AddEntry(bkg[0], "Multijet", "F")
    leg.AddEntry(ttbar, "t#bar{t}","F")
    #leg.AddEntry(zjet, "Z+jets","F")
    if ("Control" in cut and "mHH" in cut):
        leg.AddEntry(bkg[1], "Stat Uncertainties", "FF")
    else:
        leg.AddEntry(bkg[1], "Stat Uncertainties", "FF")

    #leg.AddEntry(RSG1_1000, "RSG1, 1TeV", "F")
    #leg.AddEntry(RSG1_1500, "RSG 1.5TeV * 10", "F")
    #leg.AddEntry(RSG1_2500, "RSG 2.5TeV * 100", "F")
    #leg.AddEntry(qcd_fit, "Fit to Ratio", "L")
    #leg.AddEntry(qcd_fitUp, "#pm 1#sigma Uncertainty", "L")
    leg.SetY1(leg.GetY2()-leg.GetNRows()*legHunit)
    leg.Draw()

    # save
    postname = ("" if Logy == 0 else "_" + str(Logy)) + ("" if not ("Signal" in cut and blinded) else "_blind")
    #c0.SaveAs(outputFolder+"/"+filename.replace(".root", ".pdf"))
    c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".png")
    c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".pdf")
    c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".eps")
    c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".C")
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + ".pdf")
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + ".eps")

    pad0.Close()
    pad1.Close()
    c0.Close()
示例#5
0
def plotRegion(config, cut, xTitle, yTitle="Events / 0.1 TeV", Logy=0, rebin=None, rebinarry=None, outputFolder=""):
    #load configurations from config file
    filepath = config["root"] 
    filename = config["inputdir"] 
    outputFolder= config["outputdir"]
    blinded  = config["blind"]
    #print blinded, " blinded!", config["blind"]
    #print config, filepath, filename
    #print cut
    gStyle.SetErrorX(0)
    gStyle.SetHatchesSpacing(0.7)
    gStyle.SetHatchesLineWidth(1)

    # input file: this part is different!!
    ifile = ROOT.TFile(filepath)
    data = ifile.Get("totalbkg_hh" ).Clone()
    if not blinded:
        data = ifile.Get("data_hh").Clone()
    data_est = ifile.Get("totalbkg_hh").Clone()
    qcd = ifile.Get("qcd_hh").Clone()

    #get all the systematics
    syst_up = []
    syst_down = []
    ifile.cd()
    for key in ROOT.gDirectory.GetListOfKeys():
        kname = key.GetName()
        # if "QCDShape" in kname:
        #     continue
        if "totalbkg_hh" in kname and "up" in kname:
            syst_up.append(ifile.Get(kname).Clone(kname.replace(".", "") + "_cp"))
            #print kname
        elif "totalbkg_hh" in kname and "down" in kname:
            syst_down.append(ifile.Get(kname).Clone(kname.replace(".", "")  + "_cp"))
        elif "totalbkg_hh" in kname:
            syst_up.append(ifile.Get(kname).Clone(kname.replace(".", "")  + "_cp"))
            syst_down.append(ifile.Get(kname).Clone(kname.replace(".", "")  + "_cp"))
    #print len(syst_up), len(syst_down)
    #qcd_origin = ifile.Get("qcd_" + cut )
    #print "factor is ", qcd.Integral()/qcd_origin.Integral()
    ttbar = ifile.Get("ttbar_hh").Clone()
    zjet  = ifile.Get("zjet_hh").Clone()
    RSG1_1000 = ifile.Get("signal_RSG_c10_hh_m1000").Clone()
    RSG1_1500 = ifile.Get("signal_RSG_c10_hh_m1500").Clone()
    RSG1_2000 = ifile.Get("signal_RSG_c10_hh_m2000").Clone()
    Xhh_2000  = ifile.Get("signal_2HDM_hh_m2000").Clone()
    RSG1_1500.Scale(10)
    RSG1_2000.Scale(30 * 1.61) ##stupid
    Xhh_2000.Scale(5)

    if not rebin == None:
        data.Rebin(rebin)
        data_est.Rebin(rebin)
        qcd.Rebin(rebin)
        ttbar.Rebin(rebin)
        #zjet.Rebin(rebin)
        RSG1_1000.Rebin(rebin)
        RSG1_1500.Rebin(rebin)
        RSG1_2000.Rebin(rebin)
        Xhh_2000.Rebin(rebin)

    #use array to rebin histgrams
    if not rebinarry == None:
        data      = data.Rebin(len(rebinarry) - 1, data.GetName()+"_rebinned", rebinarry)
        data_est  = data_est.Rebin(len(rebinarry) - 1, data_est.GetName()+"_rebinned", rebinarry)
        qcd       = qcd.Rebin(len(rebinarry) - 1, qcd.GetName()+"_rebinned", rebinarry)
        ttbar     = ttbar.Rebin(len(rebinarry) - 1, ttbar.GetName()+"_rebinned", rebinarry)
        #zjet      = zjet.Rebin(len(rebinarry) - 1, zjet.GetName()+"_rebinned", rebinarry)
        RSG1_1000 = RSG1_1000.Rebin(len(rebinarry) - 1, RSG1_1000.GetName()+"_rebinned", rebinarry)
        RSG1_1500 = RSG1_1500.Rebin(len(rebinarry) - 1, RSG1_1500.GetName()+"_rebinned", rebinarry)
        RSG1_2000 = RSG1_2000.Rebin(len(rebinarry) - 1, RSG1_2000.GetName()+"_rebinned", rebinarry)
        Xhh_2000  = Xhh_2000.Rebin(len(rebinarry) - 1, Xhh_2000.GetName()+"_rebinned", rebinarry)   

    #get QS scores
    if "Signal" in cut and blinded:
        ks = 0
    else:
        ks   = data.KolmogorovTest(data_est, "QU")
    int_data = data.Integral(0, data.GetXaxis().GetNbins()+1)
    int_data_est = data_est.Integral(0, data_est.GetXaxis().GetNbins()+1)
    percentdiff   = (int_data_est - int_data)/int_data * 100.0
    #chi2 =        data.Chi2Test(data_est, "QU CHI2")
    #ndf  = chi2 / data.Chi2Test(data_est, "QU CHI2/NDF") if chi2 else 0.0

    xMin = data.GetXaxis().GetBinLowEdge(1)
    xMax = data.GetXaxis().GetBinUpEdge(data.GetXaxis().GetNbins())
    yMax = data.GetMaximum() * 1.8
    if ("FourTag" in cut):
        yMax = data.GetMaximum() * 2
    if Logy==1:
        yMax = yMax * 20
    #qcd_fit = ifile.Get("qcd_fit")
    #qcd_fitUp = ifile.Get("qcd_fitUp")
    #qcd_fitDown = ifile.Get("qcd_fitDown")

    #make the total backgroudn with sytematics
    data = makeTotBkg([data])[1]
    #bkg = makeTotBkg([ttbar,qcd])
    bkg = makeTotBkg([data_est], syst_up, syst_down)
    #bkg = makeTotBkg([ttbar,qcd,zjet])
    # bkg/data ratios: [0] band for stat errors, [1] bkg/data with syst errors
    ratios = makeDataRatio(data, bkg[1])

    # stack signal on background
    #RSG1_1000.Add(bkg[0]) 
    #RSG1_1500.Add(bkg[0]) 
    #RSG1_2000.Add(bkg[0]) 

    # canvas
    c0 = ROOT.TCanvas("c0"+filename+cut, "Insert hilarious TCanvas name here", 800, 600)
    c0.SetRightMargin(0.05)

    # top pad
    pad0 = ROOT.TPad("pad0", "pad0", 0.0, 0.31, 1., 1.)
    pad0.SetRightMargin(0.05)
    pad0.SetBottomMargin(0.0001)
    pad0.SetFrameFillColor(0)
    pad0.SetFrameBorderMode(0)
    pad0.SetFrameFillColor(0)
    pad0.SetBorderMode(0)
    pad0.SetBorderSize(0)

    pad1 = ROOT.TPad("pad1", "pad1", 0.0, 0.0, 1., 0.30)
    pad1.SetRightMargin(0.05)
    pad1.SetBottomMargin(0.38)
    pad1.SetTopMargin(0.05)
    pad1.SetFrameFillColor(0)
    pad1.SetFillStyle(0) # transparent
    pad1.SetFrameBorderMode(0)
    pad1.SetFrameFillColor(0)
    pad1.SetBorderMode(0)
    pad1.SetBorderSize(0)

    c0.cd()
    pad0.SetLogy(Logy)
    pad0.Draw()
    pad0.cd()


    bkg[0].SetTitle("")
    bkg[0].SetStats(0)
    bkg[0].SetLineColor(ROOT.kBlack)
    bkg[0].SetLineWidth(1)
    bkg[0].GetYaxis().SetTitleFont(43)
    bkg[0].GetYaxis().SetTitleSize(33)
    bkg[0].GetYaxis().SetLabelFont(43)
    bkg[0].GetYaxis().SetLabelSize(28)
    bkg[0].GetYaxis().SetTitle(yTitle)
    bkg[0].GetYaxis().SetTitleOffset(1.25)
    bkg[0].GetYaxis().SetRangeUser(0.02, yMax)
    bkg[0].SetFillColor(ROOT.kYellow)
    bkg[0].Draw("HISTO")

    # RSG1_1000.SetLineWidth(2)
    # RSG1_1000.SetLineStyle(2)
    # RSG1_1000.SetLineColor(ROOT.kViolet+7)
    # RSG1_1000.Draw("HISTO SAME")

    #RSG1_1500.SetLineWidth(2)
    #RSG1_1500.SetLineStyle(2)
    #RSG1_1500.SetLineColor(ROOT.kGreen+4)
    #RSG1_1500.Draw("HISTO SAME")


    bkg[1].SetFillColor(CONF.col_dic["syst"])
    bkg[1].SetLineColor(0)
    bkg[1].SetFillStyle(3345)
    bkg[1].SetMarkerSize(0)
    bkg[1].Draw("E2 SAME")


    #print config, filepath, filename, cut, ttbar.Integral()
    ttbar.SetLineWidth(1)
    ttbar.SetLineColor(ROOT.kBlack)
    ttbar.SetFillColor(ROOT.kAzure-9)
    ttbar.Draw("HISTO SAME")

    RSG1_2000.SetLineWidth(2)
    RSG1_2000.SetLineStyle(7)
    RSG1_2000.SetLineColor(ROOT.kViolet)
    RSG1_2000.Draw("HISTO SAME")

    Xhh_2000.SetLineWidth(2)
    Xhh_2000.SetLineStyle(2)
    Xhh_2000.SetLineColor(ROOT.kRed)
    Xhh_2000.Draw("HISTO SAME")

    ## add extra line
    line0 = ROOT.TLine(xMin, 0.02, xMax, 0.02)
    line0.SetLineWidth(2)
    line0.Draw()

    #zjet.SetLineWidth(2)
    #zjet.SetLineColor(ROOT.kBlack)
    #zjet.SetFillColor(ROOT.kGreen+4)
    #zjet.Draw("HISTO SAME")

    zeroXerror(data)
    data.SetMarkerStyle(20)
    data.SetMarkerSize(1)
    data.SetLineWidth(2)
    data.GetXaxis().SetLabelSize(0)
    data.GetXaxis().SetLabelOffset(999)
    if not ("Signal" in cut and blinded):
        data.Draw("EPZ SAME")

    # bottom pad
    c0.cd()
    pad1.Draw()
    pad1.cd()

    hratio = ROOT.TH1F("hratio","",1, xMin/1000, xMax/1000)
    hratio.SetStats(0)
    
    hratio.GetYaxis().SetTitleFont(43)
    hratio.GetYaxis().SetTitleSize(33)
    hratio.GetYaxis().SetLabelFont(43)
    hratio.GetYaxis().SetLabelSize(28)
    hratio.GetYaxis().SetTitleOffset(1.25)
    hratio.GetYaxis().SetTitle("Data / Bkgd")
    hratio.GetYaxis().SetRangeUser(0.5, 1.5) #set range for ratio plot
    hratio.GetYaxis().SetNdivisions(503)

    hratio.GetXaxis().SetTitleFont(43)
    hratio.GetXaxis().SetTitleOffset(2.8)
    hratio.GetXaxis().SetTitleSize(33)
    hratio.GetXaxis().SetLabelFont(43)
    hratio.GetXaxis().SetLabelSize(28)
    hratio.GetXaxis().SetTitle(xTitle)
    hratio.Draw()


    #
    # Add stat uncertianty
    #
    ratios[0].SetFillColor(CONF.col_dic["syst"])
    ratios[0].SetFillStyle(3345)
    ratios[0].SetLineColor(0)
    ratios[0].Draw("E2")

    #zeroXerror(ratios[1])
    ratios[1].SetMarkerStyle(20)
    ratios[1].SetMarkerSize(1)
    ratios[1].SetLineWidth(2)
    h_plt.drawarrow(ratios[1], 0.5, 1.5)
    if not ("Signal" in cut and blinded):
        ratios[1].Draw("E0PZ SAME")



    # TeV_axis = ROOT.TGaxis(0, 0, 4000, 0, 0, 4, 510, "");
    # TeV_axis.SetTitle(xTitle);
    # TeV_axis.SetTitleFont(43)
    # TeV_axis.SetTitleOffset(3.5)
    # TeV_axis.SetTitleSize(33)
    # TeV_axis.SetLabelFont(43)
    # TeV_axis.SetLabelSize(28)
    # TeV_axis.SetTitle(xTitle)
    # TeV_axis.Draw()
    # qcd_fit.SetLineColor(kRed)
    # qcd_fitUp.SetLineColor(kRed)
    # qcd_fitUp.SetLineStyle(2)
    # qcd_fitDown.SetLineColor(kRed)
    # qcd_fitDown.SetLineStyle(2)
    # qcd_fit.Draw("SAME")
    # qcd_fitUp.Draw("SAME")
    # qcd_fitDown.Draw("SAME")

    # Fit the ratio with a TF1
    # if not ("Signal" in cut and blinded):
    #     testfit = ROOT.TF1("testfit", "pol2", xMin, xMax)
    #     testfit.SetParameters(1, 0, 0)
    #     ratios[1].Fit("testfit")
    #     testfit.SetLineColor(kRed)
    #     testfit.Draw("SAME")
    #     fitresult = testfit.GetParameters()
    #     myText(0.2, 0.17, 1, "y=%s x^2 + %s x + %s" % (str('%.2g' % fitresult[0]), \
    #         str('%.2g' % fitresult[1]),str('%.2g' % fitresult[2])), CONF.paperlegsize)

    # draw the ratio 1 line
    line = ROOT.TLine(xMin/1000, 1.0, xMax/1000, 1.0)
    line.SetLineStyle(1)
    line.SetLineWidth(1)
    line.Draw()

    c0.cd()
    #
    # Add ks score
    #
    #myText(0.15, 0.97, 1, "KS = %s" % str(('%.3g' % ks)), CONF.paperlegsize)
    #myText(0.4, 0.97, 1, "(Est-Obs)/Obs = %s; E=%s; O=%s" % (str(('%.1f' % percentdiff)), str(('%.1f' % int_data_est)), str(('%.1f' % int_data))), CONF.paperlegsize)
    #myText(0.15, 0.92, 1, "#chi^{2} / ndf = %s / %s" % (str(chi2), str(ndf)), CONF.paperlegsize)

    # labels
    legHunit=0.045
    legH=legHunit*6 # retuned below based on number of entries to 0.05*num_entries
    legW=0.4
    leg = ROOT.TLegend(0.57, 0.83, 0.93, 0.93)
    # top right, a bit left
    ATLASLabel(0.19, 0.91, CONF.StatusLabel)
    if "15" in filepath:
        myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 2015, 3.2 fb^{-1}", CONF.paperlegsize)
    elif "16" in filepath:
        myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 2016, 2.6 fb^{-1}", CONF.paperlegsize)
    else:
        myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, " + str(CONF.totlumi) + " fb^{-1}", CONF.paperlegsize)

    if cut.find("Signal") > -1:
        tag = "Boosted Signal Region"
    elif cut.find("Control") > -1:
        tag = "Boosted Control Region"
    elif cut.find("Sideband") > -1:
        tag = "Boosted Sideband Region"
    if cut.find("FourTag") > -1:
        tag += ", 4-tag"
    elif cut.find("ThreeTag") > -1:
        tag += ", 3-tag"
    elif cut.find("TwoTag") > -1:
        tag += ", 2-tag"
    myText(0.19, 0.83, 1, tag, CONF.paperlegsize)
    ##### legend
    #leg.SetNColumns(2)
    leg.SetTextFont(43)
    leg.SetTextSize(CONF.paperlegsize)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)
    leg.AddEntry(data, "Data", "PE")
    leg.AddEntry(bkg[0], "Multijet", "F")
    leg.AddEntry(ttbar, "t#bar{t}","F")
    #leg.AddEntry(zjet, "Z+jets","F")
    #leg.AddEntry(RSG1_1000, "RSG1, 1TeV", "F")
    #leg.AddEntry(RSG1_1500, "G1.5TeV*10", "F")
    leg.AddEntry(Xhh_2000,  "Scalar (2 TeV)", "l") ## times 5
    leg.AddEntry(RSG1_2000, "G_{KK} (2 TeV k/#bar{M}_{Pl}=1) #times 30", "l")
    leg.AddEntry(bkg[1], "Stat+Syst Uncertainties", "FF")
    #leg.AddEntry(qcd_fit, "Fit to Ratio", "L")
    #leg.AddEntry(qcd_fitUp, "#pm 1#sigma Uncertainty", "L")
    leg.SetY1(leg.GetY2()-leg.GetNRows()*legHunit)
    leg.Draw()
    c0.Update() 
    pad0.Update()
    pad1.Update()

    # save
    postname = ("" if Logy == 0 else "_" + str(Logy)) + ("" if not ("Signal" in cut and blinded) else "_blind")
    #c0.SaveAs(outputFolder+"/"+filename.replace(".root", ".pdf"))
    c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".root")
    c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".C")
    c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".png")
    c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".pdf")
    c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".eps")

    pad0.Close()
    pad1.Close()
    c0.Close()
    del(data)
    del(data_est)
    del(qcd)
    del(ttbar)
    del(zjet)
    del(RSG1_1000)
    del(RSG1_1500)
    del(RSG1_2000)
    del(syst_up)
    del(syst_down)
示例#6
0
def plotRegion(config, cut, xTitle, yTitle="N Events", Logy=0, rebin=None, rebinarry=None, outputFolder=""):
    #load configurations from config file
    filepath = config["root"] 
    filename = config["inputdir"] 
    outputFolder= config["outputdir"]
    blinded  = config["blind"]
    selsyst  = config["syst"]
    #print selsyst
    #print blinded, " blinded!", config["blind"]
    #print config, filepath, filename
    #print cut
    gStyle.SetErrorX(0)
    gStyle.SetHatchesSpacing(0.7)
    gStyle.SetHatchesLineWidth(1)

    # input file: this part is different!!
    ifile = ROOT.TFile(filepath)
    data = ifile.Get("totalbkg_hh" )
    if not blinded:
        data = ifile.Get("data_hh")
    data_est = ifile.Get("totalbkg_hh")
    qcd = ifile.Get("qcd_hh")

    #get all the systematics
    syst_up = []
    syst_down = []
    ifile.cd()
    for key in ROOT.gDirectory.GetListOfKeys():
        kname = key.GetName()
        ##print kname
        # if "QCD" in kname: ##this is are buggy now!
        #     continue
        # if "smooth" in kname: ##this is reasonable
        #     continue
        # if "norm" in kname: ##this is reasonable
        #     continue
        # if "JET" in kname: ##this is reasonable
        #     continue
        # if "FT_" in kname: ##these are buggy now!
        #     continue
        if selsyst != "all":## this is only selecting certain systematics, for checking
            if not (selsyst in kname):
                continue

        if "totalbkg_hh" is kname:
            continue
        # if "Tracking_All" not in kname:
        #     continue
        #print kname

        if "totalbkg_hh" in kname and "up" in kname:
            syst_up.append(ifile.Get(kname).Clone(kname))
            #print kname
        elif "totalbkg_hh" in kname and "down" in kname:
            syst_down.append(ifile.Get(kname).Clone(kname))
        elif "totalbkg_hh" in kname:
            syst_up.append(ifile.Get(kname).Clone(kname))
            syst_down.append(ifile.Get(kname).Clone(kname))
    #print len(syst_up), len(syst_down)


    #qcd_origin = ifile.Get("qcd_" + cut )
    #print "factor is ", qcd.Integral()/qcd_origin.Integral()
    ttbar = ifile.Get("ttbar_hh")
    zjet = ifile.Get("zjet_hh")
    RSG1_1000 = ifile.Get("signal_RSG_c10_hh_m1000")
    RSG1_1500 = ifile.Get("signal_RSG_c10_hh_m1500")
    RSG1_2500 = ifile.Get("signal_RSG_c10_hh_m2500")
    RSG1_2000 = ifile.Get("signal_RSG_c10_hh_m2000")
    RSG1_2000.Scale(30)
    RSG1_1500.Scale(10)
    RSG1_2500.Scale(100)

    if not rebin == None:
        data.Rebin(rebin)
        data_est.Rebin(rebin)
        qcd.Rebin(rebin)
        ttbar.Rebin(rebin)
        #zjet.Rebin(rebin)
        RSG1_1000.Rebin(rebin)
        RSG1_1500.Rebin(rebin)
        RSG1_2000.Rebin(rebin)
        RSG1_2500.Rebin(rebin)
        for jhist in syst_up:
            jhist.Rebin(rebin)
        for jhist in syst_down:
            jhist.Rebin(rebin)

    #use array to rebin histgrams
    if not rebinarry == None:
        data      = data.Rebin(len(rebinarry) - 1, data.GetName()+"_rebinned", rebinarry)
        data_est  = data_est.Rebin(len(rebinarry) - 1, data_est.GetName()+"_rebinned", rebinarry)
        qcd       = qcd.Rebin(len(rebinarry) - 1, qcd.GetName()+"_rebinned", rebinarry)
        ttbar     = ttbar.Rebin(len(rebinarry) - 1, ttbar.GetName()+"_rebinned", rebinarry)
        #zjet      = zjet.Rebin(len(rebinarry) - 1, zjet.GetName()+"_rebinned", rebinarry)
        RSG1_1000 = RSG1_1000.Rebin(len(rebinarry) - 1, RSG1_1000.GetName()+"_rebinned", rebinarry)
        RSG1_1500 = RSG1_1500.Rebin(len(rebinarry) - 1, RSG1_1500.GetName()+"_rebinned", rebinarry)
        RSG1_2000 = RSG1_2000.Rebin(len(rebinarry) - 1, RSG1_2000.GetName()+"_rebinned", rebinarry)
        RSG1_2500 = RSG1_2500.Rebin(len(rebinarry) - 1, RSG1_2500.GetName()+"_rebinned", rebinarry)
        for jhist in syst_up:
            jhist = jhist.Rebin(len(rebinarry) - 1, jhist.GetName()+"_rebinned", rebinarry)
        for jhist in syst_down:
            jhist = jhist.Rebin(len(rebinarry) - 1, jhist.GetName()+"_rebinned", rebinarry)

    #get QS scores
    if "Signal" in cut and blinded:
        ks = 0
    else:
        ks   = data.KolmogorovTest(data_est, "QU")
    int_data = data.Integral(0, data.GetXaxis().GetNbins()+1)
    int_data_est = data_est.Integral(0, data_est.GetXaxis().GetNbins()+1)
    percentdiff   = (int_data_est - int_data)/int_data * 100.0
    #chi2 =        data.Chi2Test(data_est, "QU CHI2")
    #ndf  = chi2 / data.Chi2Test(data_est, "QU CHI2/NDF") if chi2 else 0.0

    xMin = data.GetXaxis().GetBinLowEdge(1)
    xMax = data.GetXaxis().GetBinUpEdge(data.GetXaxis().GetNbins())
    yMax = data.GetMaximum() * 1.5
    if ("FourTag" in cut):
        yMax = data.GetMaximum() * 2.0
    if Logy==1:
        yMax = yMax * 100
    #qcd_fit = ifile.Get("qcd_fit")
    #qcd_fitUp = ifile.Get("qcd_fitUp")
    #qcd_fitDown = ifile.Get("qcd_fitDown")

    #make the total backgroudn with sytematics
    data = makeTotBkg([data])[1]
    #bkg = makeTotBkg([ttbar,qcd])
    bkg  = makeTotBkg([ttbar, qcd], syst_up, syst_down)
    #bkg = makeTotBkg([ttbar,qcd,zjet])
    # bkg/data ratios: [0] band for stat errors, [1] bkg/data with syst errors
    ratios = makeDataRatio(data, bkg[1])

    #comput the integrals! and make the table
    if (not blinded):
        texoutpath = CONF.inputpath + ops.inputdir + "/" + "Plot/Tables/"
        if not os.path.exists(texoutpath):
            os.makedirs(texoutpath)
        outtexFile = open( texoutpath + cut + "_SR_region_compare" + ".tex", "w")
        tableList = []
        int_range_lst = [">1000", ">1500", ">2000", ">2500", ">3000"]
        help_table.add_table_head(tableList, int_range_lst, title="Mass Range")
        #get total background
        outstr = ""
        outstr += "totalbkg"
        #print masterdic, systag
        for int_range in int_range_lst:   
            err = ROOT.Double(0.) ##bkg[2] is the hist with uncertainties
            int_range = bkg[2].IntegralAndError(bkg[2].GetXaxis().FindBin(int(int_range.replace(">", ""))), bkg[2].GetXaxis().FindBin(3900), err)
            outstr += help_table.add_entry((int_range, float(err)))
        #finish the current entry
        outstr+="\\\\"
        tableList.append(outstr)
        #get data
        outstr = ""
        outstr += "data"
        #print masterdic, systag
        temp_data = ifile.Get("data_hh" )
        for int_range in int_range_lst:
            err = ROOT.Double(0.)
            int_range = temp_data.IntegralAndError(temp_data.GetXaxis().FindBin(int(int_range.replace(">", ""))), temp_data.GetXaxis().FindBin(3900), err)
            outstr += help_table.add_entry((int_range, float(err)))
        #finish the current entry
        outstr+="\\\\"
        tableList.append(outstr)
        #finish the table
        help_table.add_table_tail(tableList, int_range_lst)
        #return the table
        for line in tableList:
            print line
            outtexFile.write(line+" \n")
        outtexFile.close()

    # stack signal on background
    RSG1_1000.Add(bkg[0]) 
    RSG1_1500.Add(bkg[0]) 
    RSG1_2000.Add(bkg[0]) 
    RSG1_2500.Add(bkg[0]) 

    # canvas
    c0 = ROOT.TCanvas("c0"+filename+cut, "Insert hilarious TCanvas name here", 800, 800)
    c0.SetRightMargin(0.05)

    # top pad
    pad0 = ROOT.TPad("pad0", "pad0", 0.0, 0.31, 1., 1.)
    pad0.SetRightMargin(0.05)
    pad0.SetBottomMargin(0.0001)
    pad0.SetFrameFillColor(0)
    pad0.SetFrameBorderMode(0)
    pad0.SetFrameFillColor(0)
    pad0.SetBorderMode(0)
    pad0.SetBorderSize(0)

    pad1 = ROOT.TPad("pad1", "pad1", 0.0, 0.0, 1., 0.30)
    pad1.SetRightMargin(0.05)
    pad1.SetBottomMargin(0.38)
    pad1.SetTopMargin(0.0001)
    pad1.SetFrameFillColor(0)
    pad1.SetFillStyle(0) # transparent
    pad1.SetFrameBorderMode(0)
    pad1.SetFrameFillColor(0)
    pad1.SetBorderMode(0)
    pad1.SetBorderSize(0)

    c0.cd()
    pad0.SetLogy(Logy)
    pad0.Draw()
    pad0.cd()


    bkg[0].SetTitle("")
    bkg[0].SetStats(0)
    bkg[0].SetLineColor(ROOT.kBlack)
    bkg[0].SetLineWidth(2)
    bkg[0].GetYaxis().SetTitleFont(43)
    bkg[0].GetYaxis().SetTitleSize(28)
    bkg[0].GetYaxis().SetLabelFont(43)
    bkg[0].GetYaxis().SetLabelSize(28)
    bkg[0].GetYaxis().SetTitle(yTitle)
    bkg[0].GetYaxis().SetRangeUser(0.006, yMax)
    bkg[0].SetFillColor(ROOT.kYellow)
    bkg[0].Draw("HISTO")

    # RSG1_1000.SetLineWidth(2)
    # RSG1_1000.SetLineStyle(2)
    # RSG1_1000.SetLineColor(ROOT.kViolet+7)
    # RSG1_1000.Draw("HISTO SAME")

    # RSG1_1500.SetLineWidth(2)
    # RSG1_1500.SetLineStyle(2)
    # RSG1_1500.SetLineColor(ROOT.kPink+7)
    # RSG1_1500.Draw("HISTO SAME")

    RSG1_2000.SetLineWidth(2)
    RSG1_2000.SetLineStyle(2)
    RSG1_2000.SetLineColor(ROOT.kPink+7)
    RSG1_2000.Draw("HISTO SAME")

    # RSG1_2500.SetLineWidth(2)
    # RSG1_2500.SetLineStyle(2)
    # RSG1_2500.SetLineColor(ROOT.kGreen+4)
    # RSG1_2500.Draw("HISTO SAME")

    bkg[1].SetFillColor(CONF.col_dic["syst"])
    bkg[1].SetLineColor(CONF.col_dic["syst"])
    bkg[1].SetFillStyle(3345)
    bkg[1].SetMarkerSize(0)
    bkg[1].Draw("E2 SAME")

    ttbar.SetLineWidth(2)
    ttbar.SetLineColor(ROOT.kBlack)
    ttbar.SetFillColor(ROOT.kAzure-9)
    ttbar.Draw("HISTO SAME")

    #zjet.SetLineWidth(2)
    #zjet.SetLineColor(ROOT.kBlack)
    #zjet.SetFillColor(ROOT.kGreen+4)
    #zjet.Draw("HISTO SAME")

    zeroXerror(data)
    data.SetMarkerStyle(20)
    data.SetMarkerSize(1)
    data.SetLineWidth(2)
    data.GetXaxis().SetLabelSize(0)
    data.GetXaxis().SetLabelOffset(999)
    if not ("Signal" in cut and blinded):
        data.Draw("EPZ SAME")

    # bottom pad
    c0.cd()
    pad1.Draw()
    pad1.cd()

    hratio = ROOT.TH1F("hratio","",1, xMin, xMax)
    hratio.SetStats(0)
    
    hratio.GetYaxis().SetTitleFont(43)
    hratio.GetYaxis().SetTitleSize(28)
    hratio.GetYaxis().SetLabelFont(43)
    hratio.GetYaxis().SetLabelSize(28)
    hratio.GetYaxis().SetTitle("Data / Bkgd")
    hratio.GetYaxis().SetRangeUser(0.5, 2.1) #set range for ratio plot
    h_plt.drawarrow(ratios[1], 0.5, 2.1)
    hratio.GetYaxis().SetNdivisions(405)

    hratio.GetXaxis().SetTitleFont(43)
    hratio.GetXaxis().SetTitleOffset(3.5)
    hratio.GetXaxis().SetTitleSize(28)
    hratio.GetXaxis().SetLabelFont(43)
    hratio.GetXaxis().SetLabelSize(28)
    hratio.GetXaxis().SetTitle(xTitle)

    hratio.Draw()

    #
    # Add stat uncertianty
    #
    ratios[0].SetFillColor(CONF.col_dic["syst"])
    ratios[0].SetFillStyle(3345)
    ratios[0].Draw("E2")

    #zeroXerror(ratios[1])
    ratios[1].SetMarkerStyle(20)
    ratios[1].SetMarkerSize(1)
    ratios[1].SetLineWidth(2)
    if not ("Signal" in cut and blinded):
        ratios[1].Draw("E0PZ SAME")
    # qcd_fit.SetLineColor(kRed)
    # qcd_fitUp.SetLineColor(kRed)
    # qcd_fitUp.SetLineStyle(2)
    # qcd_fitDown.SetLineColor(kRed)
    # qcd_fitDown.SetLineStyle(2)
    # qcd_fit.Draw("SAME")
    # qcd_fitUp.Draw("SAME")
    # qcd_fitDown.Draw("SAME")

    # Fit the ratio with a TF1
    # if not ("Signal" in cut and blinded):
    #     testfit = ROOT.TF1("testfit", "pol2", xMin, xMax)
    #     testfit.SetParameters(1, 0, 0)
    #     ratios[1].Fit("testfit")
    #     testfit.SetLineColor(kRed)
    #     testfit.Draw("SAME")
    #     fitresult = testfit.GetParameters()
    #     myText(0.2, 0.17, 1, "y=%s x^2 + %s x + %s" % (str('%.2g' % fitresult[0]), \
    #         str('%.2g' % fitresult[1]),str('%.2g' % fitresult[2])), CONF.legsize)

    # draw the ratio 1 line
    line = ROOT.TLine(xMin, 1.0, xMax, 1.0)
    line.SetLineStyle(1)
    line.Draw()

    c0.cd()
    #
    # Add ks score
    #
    myText(0.15, 0.97, 1, "KS = %s" % str(('%.3g' % ks)), CONF.legsize)
    myText(0.4, 0.97, 1, "(Est-Obs)/Obs = %s; E=%s; O=%s" % (str(('%.1f' % percentdiff)), str(('%.1f' % int_data_est)), str(('%.1f' % int_data))), CONF.legsize)
    #myText(0.15, 0.92, 1, "#chi^{2} / ndf = %s / %s" % (str(chi2), str(ndf)), CONF.legsize)

    # labels
    legHunit=0.05
    legH=legHunit*6 # retuned below based on number of entries to 0.05*num_entries
    legW=0.4
    leg = ROOT.TLegend(0.65, 0.75, 0.95, 0.95)
    # top right, a bit left
    ATLASLabel(0.19, 0.91, StatusLabel)
    if "15" in filepath:
        myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 2015, 3.2 fb^{-1}", CONF.legsize)
    elif "16" in filepath:
        myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 2016, 2.6 fb^{-1}", CONF.legsize)
    else:
        myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 15+16, " + str(CONF.totlumi) + " fb^{-1}", CONF.legsize)
    myText(0.19, 0.83, 1, ' ' + cut.replace("_", "; "), CONF.legsize)
    ##### legend
    leg.SetNColumns(2)
    leg.SetTextFont(43)
    leg.SetTextSize(CONF.legsize)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)
    leg.AddEntry(data, "Data", "PE")
    leg.AddEntry(bkg[0], "Multijet", "F")
    leg.AddEntry(ttbar, "t#bar{t}","F")
    #leg.AddEntry(zjet, "Z+jets","F")
    leg.AddEntry(bkg[1], "Stat+Syst", "F")
    #leg.AddEntry(RSG1_1000, "RSG1, 1TeV", "F")
    #leg.AddEntry(RSG1_1500, "RSG 1.5TeV * 10", "F")
    leg.AddEntry(RSG1_2000, "RSG 2.0TeV * 30", "F")
    #leg.AddEntry(RSG1_2500, "RSG 2.5TeV * 100", "F")
    #leg.AddEntry(qcd_fit, "Fit to Ratio", "L")
    #leg.AddEntry(qcd_fitUp, "#pm 1#sigma Uncertainty", "L")
    leg.SetY1(leg.GetY2()-leg.GetNRows()*legHunit)
    leg.Draw()

    # save
    postname = ("" if Logy == 0 else "_" + str(Logy)) + ("" if not ("Signal" in cut and blinded) else "_blind") + ("" if selsyst is "all" else "_" + selsyst)
    #c0.SaveAs(outputFolder+"/"+filename.replace(".root", ".pdf"))
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".png")
    c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".pdf")
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + ".pdf")
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + ".eps")

    pad0.Close()
    pad1.Close()
    c0.Close()
    del(data)
    del(data_est)
    del(qcd)
    del(ttbar)
    del(zjet)
    del(RSG1_1000)
    del(RSG1_1500)
    del(RSG1_2500)
    del(syst_up)
    del(syst_down)
示例#7
0
def plotRegion(config, cut, xTitle, yTitle="N Events", Logy=0, labelPos=11, rebin=None, rebinarry=[], fitrange=[0, 0]):
    #load configurations from config file
    filepath = config["root"] 
    filename = config["inputdir"] 
    outputFolder= config["outputdir"]
    #debug
    #print filepath, filename, cut
    ROOT.gStyle.SetErrorX(0)
    ROOT.gStyle.SetHatchesSpacing(0.7)
    ROOT.gStyle.SetHatchesLineWidth(1)
    # input file
    ifile = ROOT.TFile(filepath + filename + ".root")
    # read stuff
    #print "data_" + cut
    if config["compcut"] is not "": ## this means qcd estimate is something special now; NOTICE: things are inverted here!!!
        #print config, filepath, filename, config["compcut"]
        data = ifile.Get("data_" + cut.replace(config["cut"], config["compcut"]) )
        ttbar = ifile.Get("ttbar_" + cut.replace(config["cut"], config["compcut"]) )
        qcd = ifile.Get("data_" + cut) #note these are the compcut plots
        ttbar_est = ifile.Get("ttbar_" + cut)
        #zjet = ifile.Get("zjet_" + cut )
        data.Add(ttbar, -1)
        qcd.Add(ttbar_est, -1) ##special treatment here; directly subtracting the MC component
    else: ##default method
        data = ifile.Get("data_" + cut )
        qcd = ifile.Get("qcd_est_" + cut )
        ttbar = ifile.Get("ttbar_est_" + cut )
        #zjet = ifile.Get("zjet_" + cut )
        #modify data
        data.Add(ttbar, -1)
        #data.Add(zjet, -1)
    #qcd_origin = ifile.Get("qcd_" + cut )
    #print "factor is ", qcd.Integral()/qcd_origin.Integral()

    #clear factioned binns; only for reweighting purpose
    # for b in range(1, data.GetNbinsX()+1): 
    #     if  data.GetBinContent(b) < 1:
    #         data.SetBinContent(b, 0)
    #         data.SetBinError(b, 0)

    #swap data if blinded
    if "Signal" in cut and blinded:
        data = qcd.Clone()
    #do rebin
    if not rebin == None:
        data.Rebin(rebin)
        qcd.Rebin(rebin)
        ttbar.Rebin(rebin)
        #zjet.Rebin(rebin)
    if rebinarry != []:
        data      = h_plt.do_variable_rebinning(data, rebinarry)
        qcd       = h_plt.do_variable_rebinning(qcd, rebinarry)
        ttbar     = h_plt.do_variable_rebinning(ttbar, rebinarry)
        #zjet      = h_plt.do_variable_rebinning(zjet, rebinarry)

    #get QS scores
    if "Signal" in cut and blinded:
        ks = 0
    else:
        ks   = data.KolmogorovTest(qcd, "QU")
    int_data = data.Integral(0, data.GetXaxis().GetNbins()+1)
    int_qcd = qcd.Integral(0, qcd.GetXaxis().GetNbins()+1)
    percentdiff   = (int_qcd - int_data)/int_data * 100.0
    #chi2 =        data.Chi2Test(qcd, "QU CHI2")
    #ndf  = chi2 / data.Chi2Test(qcd, "QU CHI2/NDF") if chi2 else 0.0
    if config["compcut"] is not "": 
        ##special treatment here: for comps, rescale the original distributions
        ##thus the number of events is kept the same!
        #data.Scale(int_qcd/int_data)
        qcd.Scale(int_data/int_qcd)

    xMin = data.GetXaxis().GetBinLowEdge(1)
    xMax = data.GetXaxis().GetBinUpEdge(data.GetXaxis().GetNbins())
    yMax = data.GetMaximum() * 1.5
    if Logy==1:
        yMax = yMax * 100

    ##Tony: a fix for only the ratios used in reweighting; idea from Patrick
    hist_ratio = data.Clone("ratio")
    hist_ratio.Divide(qcd)
    hist_ratio.Smooth()
    #this is the important part...where the backgrounds are set
    data = h_plt.makeTotBkg([data])[1]
    bkg  = h_plt.makeTotBkg([qcd])
    #bkg = h_plt.makeTotBkg([ttbar,qcd,zjet]) #original
    # bkg/data ratios: [0] band for bkg errors, [1] bkg/data with stat errors only
    ratios = h_plt.makeDataRatio(data, bkg[1])

    # canvas
    c0 = ROOT.TCanvas("c0"+filename+cut, "Insert hilarious TCanvas name here", 800, 800)
    c0.SetRightMargin(0.05)

    # top pad
    pad0 = ROOT.TPad("pad0", "pad0", 0.0, 0.31, 1., 1.)
    pad0.SetRightMargin(0.05)
    pad0.SetBottomMargin(0.0001)
    pad0.SetFrameFillColor(0)
    pad0.SetFrameBorderMode(0)
    pad0.SetFrameFillColor(0)
    pad0.SetBorderMode(0)
    pad0.SetBorderSize(0)

    pad1 = ROOT.TPad("pad1", "pad1", 0.0, 0.0, 1., 0.30)
    pad1.SetRightMargin(0.05)
    pad1.SetBottomMargin(0.38)
    pad1.SetTopMargin(0.0001)
    pad1.SetFrameFillColor(0)
    pad1.SetFillStyle(0) # transparent
    pad1.SetFrameBorderMode(0)
    pad1.SetFrameFillColor(0)
    pad1.SetBorderMode(0)
    pad1.SetBorderSize(0)

    c0.cd()
    pad0.SetLogy(Logy)
    pad0.Draw()
    pad0.cd()

    bkg[0].SetTitle("")
    bkg[0].SetStats(0)
    bkg[0].SetLineColor(ROOT.kBlack)
    bkg[0].SetLineWidth(2)
    bkg[0].GetYaxis().SetTitleFont(43)
    bkg[0].GetYaxis().SetTitleSize(28)
    bkg[0].GetYaxis().SetLabelFont(43)
    bkg[0].GetYaxis().SetLabelSize(28)
    bkg[0].GetYaxis().SetTitle(yTitle)
    bkg[0].GetYaxis().SetRangeUser(0.001, yMax)
    bkg[0].SetFillColor(ROOT.kYellow)
    bkg[0].Draw("HISTO")

    bkg[1].SetFillColor(CONF.col_dic["syst"])
    bkg[1].SetLineColor(CONF.col_dic["syst"])
    bkg[1].SetFillStyle(3345)
    bkg[1].SetMarkerSize(0)
    bkg[1].Draw("E2 SAME")

    #ttbar.SetLineWidth(2)
    #ttbar.SetLineColor(ROOT.kBlack)
    #ttbar.SetFillColor(ROOT.kAzure-9)
    #ttbar.Draw("HISTO SAME")

    #zjet.SetLineWidth(2)
    #zjet.SetLineColor(ROOT.kBlack)
    #zjet.SetFillColor(ROOT.kGreen+4)
    #zjet.Draw("HISTO SAME")

    h_plt.zeroXerror(data)
    data.SetMarkerStyle(20)
    data.SetMarkerSize(1)
    data.SetLineWidth(2)
    data.GetXaxis().SetLabelSize(0)
    data.GetXaxis().SetLabelOffset(999)
    if not ("Signal" in cut and blinded):
        data.Draw("EPZ SAME")

    # bottom pad
    c0.cd()
    pad1.Draw()
    pad1.cd()

    hratio = ROOT.TH1F("hratio","", 1, xMin, xMax)
    hratio.SetStats(0)
    ratio_ylow  = 0.5 ##this the ratio low bin
    ratio_yhigh = 1.5 ##this the ratio high bin
    hratio.GetYaxis().SetTitleFont(43)
    hratio.GetYaxis().SetTitleSize(28)
    hratio.GetYaxis().SetLabelFont(43)
    hratio.GetYaxis().SetLabelSize(28)
    hratio.GetYaxis().SetTitle("Data / Bkgd")
    hratio.GetYaxis().SetRangeUser(ratio_ylow, ratio_yhigh) #set range for ratio plot
    hratio.GetYaxis().SetNdivisions(405)

    hratio.GetXaxis().SetTitleFont(43)
    hratio.GetXaxis().SetTitleOffset(3.5)
    hratio.GetXaxis().SetTitleSize(28)
    hratio.GetXaxis().SetLabelFont(43)
    hratio.GetXaxis().SetLabelSize(28)
    hratio.GetXaxis().SetTitle(xTitle)

    hratio.Draw()

    #
    # Add stat uncertianty
    #
    ratios[0].SetFillColor(CONF.col_dic["syst"])
    ratios[0].SetFillStyle(3345)
    ratios[0].Draw("E2")

    #zeroXerror(ratios[1])
    ratios[1].SetMarkerStyle(20)
    ratios[1].SetMarkerSize(1)
    ratios[1].SetLineWidth(2)
    if not ("Signal" in cut and blinded):
        ratios[1].Draw("E0PZ SAME")

    ##add arrows; call this function
    h_plt.drawarrow(ratios[1], ratio_ylow, ratio_yhigh)
    # ratio_arrow = ROOT.TArrow(0, 0, 0, 0, 0.01, "|>")
    # ratio_arrow.SetLineWidth(3)
    # ratio_arrow.SetLineColor(ROOT.kBlue)
    # ratio_arrow.SetFillColor(ROOT.kBlue)

    # for pt in xrange(ratios[1].GetN()):
    #     y = ratios[1].GetY()[pt]
    #     x = ratios[1].GetX()[pt]
    #     y_low  = y + ratios[1].GetEYhigh()[pt]
    #     y_high = y - ratios[1].GetEYlow()[pt]
    #     if y_low < ratio_ylow * 1.1:
    #         ratio_arrow.DrawArrow(x, 1 - abs(1 - ratio_ylow)*2./3., x, ratio_ylow)
    #     elif y_high > ratio_yhigh * 0.9:
    #         ratio_arrow.DrawArrow(x, 1 + abs(1 - ratio_yhigh)*2./3., x, ratio_yhigh)


    testfit={}
    # Fit the ratio with a TF1
    if not ("Signal" in cut and blinded):
        if fitrange == [0, 0]:
            fitMin = xMin
            fitMax = xMax
        else:
            fitMin = fitrange[0]
            fitMax = fitrange[1]

        #enable smart fit~! will pick the highest prob fit
        #no 0 order polynomial!!!
        for iter_fit in range(1, 4):
            testfit[iter_fit] = ROOT.TF1("testfit" + str(iter_fit), "pol" + str(iter_fit), xMin, xMax)
        #initialization of parameters
        if ("trk0_Pt" in cut): #for the leading track jet fit
            #testfit[3].SetParameters(1, 0.006, -2E-5, +2E-8)
            testfit[3].SetParameters(0.76, 0.009, -5E-5, +9E-8)
            #testfit[3].SetParameters(0.6, 0.007, -3E-5, +3E-8); testing version
        elif ("trk1_Pt" in cut): #for the subleading track jet fit
            testfit[2].SetParameters(0.82, 0.004, -1E-5)
        elif ("trks_Pt" in cut): #for the subleading track jet fit
            testfit[3].SetParameters(0.82, 0.004, -2E-5, -2E-8)
        elif ("trk_pt_diff" in cut): #for the subleading track jet fit
            testfit[3].SetParameters(1, 0.001, -0.000001, -0.00000001)
        elif ("Pt_m" in cut): #for the subleading track jet fit
            testfit[1].SetParameters(0.9, 0.0005)
        elif ("Rhh" in cut): #for the subleading track jet fit
            testfit[1].SetParameters(1, 0.7)
        #for the other distributions
        testfit[1].SetParameters(0.9, 0.001)
        #testfit[1].SetParLimits(1, 0.8, 1.2)
        testfit[2].SetParameters(1.0, 0.0, 0.0)
        #testfit[2].SetParLimits(0, 0.8, 1.2)
        testfit[3].SetParameters(1.0, 0.0, 0.0, 0.0)

        #do the 3 fits and save the output
        testfitprob = [0]
        for iter_fit in range(1, 4):
            ratios[1].Fit("testfit" + str(iter_fit), "QWLR0IBF", "", fitMin, fitMax)
            testfitprob.append(float(testfit[iter_fit].GetProb()))
        #pick the best iteration; try to avoid higher order function as much as possible
        best_iter = 1
        if testfitprob[2]/(testfitprob[best_iter] + 1E-8) > 1.1:
            best_iter = 2
        if testfitprob[3]/(testfitprob[best_iter] + 1E-8) > 1.1:
            best_iter = 3
        
        #proceed with saving parameters
        fitprob = testfitprob[best_iter]
        fitresult = testfit[best_iter].GetParameters()
        if len(fitresult) < 4:#fill in 0 if there are less than 3 paramters
            fitresult += [int(0)] * (4 - len(fitresult))
        testfit[best_iter].SetLineColor(ROOT.kRed)
        testfit[best_iter].SetLineStyle(9)
        testfit[best_iter].Draw("SAME")
        ROOT.myText(0.02, 0.17, 1, "y=%s + %s x + %sx^2 + %sx^3, prob:%s" % 
            (str('%.2g' % fitresult[0]),
            str('%.2g' % fitresult[1]), 
            str('%.2g' % fitresult[2]), 
            str('%.2g' % fitresult[3]), 
            str('%.2g' % fitprob))
            , CONF.legsize)
        #draw the line for stat and end of the fit
        ystart = ROOT.TLine(fitMin, 0.60, fitMin, 1.40)
        ystart.SetLineStyle(5)
        ystart.Draw()
        yend = ROOT.TLine(fitMax, 0.60, fitMax, 1.40)
        yend.SetLineStyle(5)
        yend.Draw()

        #write out the reweighting parameteres; for things in the sideband only
        f_reweight = open(reweightfolder + "r" + str(iter_reweight) + "_" + cut +".txt", "w")
        f_reweight.write("reweighting function of: " + cut + "; prob is: " + str('%.2g' % fitprob) + "\n")
        f_reweight.write("par0: " + str('%.3g' % fitresult[0]) + " \n")
        f_reweight.write("par1: " + str('%.3g' % fitresult[1]) + " \n")
        f_reweight.write("par2: " + str('%.3g' % fitresult[2]) + " \n")
        f_reweight.write("par3: " + str('%.3g' % fitresult[3]) + " \n")
        f_reweight.write("low:  " + str('%.3g' % fitMin) + " \n")
        f_reweight.write("high: " + str('%.3g' % fitMax) + " \n")
        f_reweight.close()

        #done with the fit!!
        #try spline interpolation: CSPLINE, LINEAR, POLYNOMIAL, CSPLINE_PERIODIC, AKIMA, AKIMA_PERIODIC
        inter = ROOT.Math.Interpolator(0, ROOT.Math.Interpolation.kCSPLINE)
        ni = ratios[1].GetN() ##GetN()
        xi = ROOT.vector('double')(ni + 2)
        yi = ROOT.vector('double')(ni + 2)
        #deal with the beginning
        for k in range(0, ni):
            xk = ROOT.Double()
            yk = ROOT.Double()
            ratios[1].GetPoint(k, xk, yk)
            xi[k + 1] = xk
            yi[k + 1] = yk
        #for edge effects
        xi[0] = xi[1] - abs(xi[1] - xi[2])
        yi[0] = yi[1]
        xi[ni + 1] = xi[ni] + abs(xi[ni] - xi[ni - 1])
        yi[ni + 1] = yi[ni]
        inter.SetData(xi, yi)
        temp_graph = ROOT.TGraph(ni + 2)
        for k in range(0, ni + 2):
            temp_graph.SetPoint(k, xi[k], yi[k])

        spline = ROOT.TSpline3(cut, temp_graph)
        #spline = ROOT.TSpline3(hist_ratio)
        spline.SaveAs(reweightfolder + "rs" + str(iter_reweight) + "_" + cut +".cxx")
        #hist_ratio.SetMarkerColor(ROOT.kGreen)
        #hist_ratio.Draw("SAME")

        inter_step = 5
        xf = ROOT.vector('double')(ni * inter_step)
        yf = ROOT.vector('double')(ni * inter_step)
        inter_graph = ROOT.TGraph(ni * inter_step)
        spline_graph = ROOT.TGraph(ni * inter_step)
        for k in range(0, (ni * inter_step)):
            xf[k] = xi[0] + (xi[ni + 1] - xi[0])/(ni * inter_step * 1.0) * k
            #print k, xf[k], inter.Eval(xf[k])
            inter_graph.SetPoint(k, xf[k], inter.Eval(xf[k]))
            spline_graph.SetPoint(k, xf[k], spline.Eval(xf[k]))

        inter_graph.SetLineColor(ROOT.kBlue) ## this is the interpolation
        inter_graph.SetLineWidth(2)
        inter_graph.Draw("SAME L")
        spline_graph.SetLineColor(ROOT.kGreen) ## this is the spline fit
        spline_graph.SetLineWidth(2)
        spline_graph.Draw("SAME L")

    # draw the ratio 1 line
    line = ROOT.TLine(xMin, 1.0, xMax, 1.0)
    line.SetLineStyle(1)
    line.Draw()

    c0.cd()
    #
    # Add ks score
    #
    ROOT.myText(0.15, 0.97, 1, "KS = %s" % str(('%.3g' % ks)), CONF.legsize)
    ROOT.myText(0.4, 0.97, 1, "(Est-Obs)/Obs = %s; E=%s; O=%s" % (str(('%.1f' % percentdiff)), str(('%.1f' % int_qcd)), str(('%.1f' % int_data))), CONF.legsize)
    #myText(0.15, 0.92, 1, "#chi^{2} / ndf = %s / %s" % (str(chi2), str(ndf)), CONF.legsize)

    # labels
    legHunit=0.05
    legH=legHunit*6 # retuned below based on number of entries to 0.05*num_entries
    legW=0.4
    leg = ROOT.TLegend(0.65, 0.75, 0.95, 0.95)
    # top right, a bit left
    ROOT.ATLASLabel(0.19, 0.91, StatusLabel)
    if "15" in filepath:
        ROOT.myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 2015, 3.2 fb^{-1}", CONF.legsize)
    elif "16" in filepath:
        ROOT.myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 2016, 2.6 fb^{-1}", CONF.legsize)
    elif "cb" in filepath:
        ROOT.myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 15+16, " + str(CONF.totlumi) + " fb^{-1}", CONF.legsize)
    else:
        ROOT.myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 15+16, " + str(CONF.totlumi) + " fb^{-1}", CONF.legsize)
    ##### legend
    leg.SetNColumns(1)
    leg.SetTextFont(43)
    leg.SetTextSize(12)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)
    if config["compcut"] is not "": 
        #inverted here as well!!!
        leg.AddEntry(data, config["compcut"].replace("_", " "), "PE")
        leg.AddEntry(bkg[0], config["cut"].replace("_", " "), "F")
    else:
        leg.AddEntry(data, "Data", "PE")
        leg.AddEntry(bkg[0], "Multijet Est", "F")
    #leg.AddEntry(ttbar, "t#bar{t}","F")
    #leg.AddEntry(zjet, "Z+jets","F")
    leg.AddEntry(bkg[1], "Stat Uncertainty", "F")
    #leg.AddEntry(RSG1_1000, "RSG1, 1TeV", "F")
    #leg.AddEntry(RSG1_1500, "RSG1, 1.5TeV * 25", "F")
    #leg.AddEntry(RSG1_2500, "RSG1, 2.5TeV * 1000", "F")
    #leg.AddEntry(qcd_fit, "Fit to Ratio", "L")
    #leg.AddEntry(qcd_fitUp, "#pm 1#sigma Uncertainty", "L")
    leg.SetY1(leg.GetY2()-leg.GetNRows()*legHunit)
    leg.Draw()

    # save
    postname = ("" if Logy == 0 else "_" + str(Logy)) + ("" if not ("Signal" in cut and blinded) else "_blind")
    #c0.SaveAs(outputFolder+"/"+filename.replace(".root", ".pdf"))
    c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".png")
    c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".pdf")
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + ".pdf")
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + ".eps")

    pad0.Close()
    pad1.Close()
    c0.Close()
    del(data)
    del(qcd)
    del(ttbar)
    #del(zjet)
    #del(RSG1_1000)
    #del(RSG1_1500)
    #del(RSG1_2500)
    del(testfit)

    ##rename the spline function generated
    with open(reweightfolder + "rs" + str(iter_reweight) + "_" + cut +".cxx","r") as f:
        newlines = []
        for line in f.readlines():
            newlines.append(line.replace("/afs/cern", "rs" + str(iter_reweight) + "_" + cut))
        with open(reweightfolder + "rs" + str(iter_reweight) + "_" + cut +".cxx", "w") as f:
            for line in newlines:
                f.write(line)

    ##should only be run non-parellel.
    if ("Sideband" in cut and False):
        outputroot.cd()
        ratios[1].SetName(cut)
        ratios[1].Write()
示例#8
0
def plotRegion(config,
               cut,
               xTitle,
               yTitle="N Events",
               Logy=0,
               rebin=None,
               rebinarry=None,
               outputFolder=""):
    #load configurations from config file
    filepath = config["root"]
    filename = config["inputdir"]
    outputFolder = config["outputdir"]
    blinded = config["blind"]
    selsyst = config["syst"]
    #print selsyst
    #print blinded, " blinded!", config["blind"]
    #print config, filepath, filename
    #print cut
    gStyle.SetErrorX(0)
    gStyle.SetHatchesSpacing(0.7)
    gStyle.SetHatchesLineWidth(1)

    # input file: this part is different!!
    ifile = ROOT.TFile(filepath)
    data = ifile.Get("totalbkg_hh")
    if not blinded:
        data = ifile.Get("data_hh")
    data_est = ifile.Get("totalbkg_hh")
    qcd = ifile.Get("qcd_hh")

    #get all the systematics
    syst_up = []
    syst_down = []
    ifile.cd()
    for key in ROOT.gDirectory.GetListOfKeys():
        kname = key.GetName()
        ##print kname
        # if "QCD" in kname: ##this is are buggy now!
        #     continue
        # if "smooth" in kname: ##this is reasonable
        #     continue
        # if "norm" in kname: ##this is reasonable
        #     continue
        # if "JET" in kname: ##this is reasonable
        #     continue
        # if "FT_" in kname: ##these are buggy now!
        #     continue
        if selsyst != "all":  ## this is only selecting certain systematics, for checking
            if not (selsyst in kname):
                continue

        if "totalbkg_hh" is kname:
            continue
        # if "Tracking_All" not in kname:
        #     continue
        #print kname

        if "totalbkg_hh" in kname and "up" in kname:
            syst_up.append(ifile.Get(kname).Clone(kname))
            #print kname
        elif "totalbkg_hh" in kname and "down" in kname:
            syst_down.append(ifile.Get(kname).Clone(kname))
        elif "totalbkg_hh" in kname:
            syst_up.append(ifile.Get(kname).Clone(kname))
            syst_down.append(ifile.Get(kname).Clone(kname))
    #print len(syst_up), len(syst_down)

    #qcd_origin = ifile.Get("qcd_" + cut )
    #print "factor is ", qcd.Integral()/qcd_origin.Integral()
    ttbar = ifile.Get("ttbar_hh")
    zjet = ifile.Get("zjet_hh")
    RSG1_1000 = ifile.Get("signal_RSG_c10_hh_m1000")
    RSG1_1500 = ifile.Get("signal_RSG_c10_hh_m1500")
    RSG1_2500 = ifile.Get("signal_RSG_c10_hh_m2500")
    RSG1_2000 = ifile.Get("signal_RSG_c10_hh_m2000")
    RSG1_2000.Scale(30)
    RSG1_1500.Scale(10)
    RSG1_2500.Scale(100)

    if not rebin == None:
        data.Rebin(rebin)
        data_est.Rebin(rebin)
        qcd.Rebin(rebin)
        ttbar.Rebin(rebin)
        #zjet.Rebin(rebin)
        RSG1_1000.Rebin(rebin)
        RSG1_1500.Rebin(rebin)
        RSG1_2000.Rebin(rebin)
        RSG1_2500.Rebin(rebin)
        for jhist in syst_up:
            jhist.Rebin(rebin)
        for jhist in syst_down:
            jhist.Rebin(rebin)

    #use array to rebin histgrams
    if not rebinarry == None:
        data = data.Rebin(
            len(rebinarry) - 1,
            data.GetName() + "_rebinned", rebinarry)
        data_est = data_est.Rebin(
            len(rebinarry) - 1,
            data_est.GetName() + "_rebinned", rebinarry)
        qcd = qcd.Rebin(
            len(rebinarry) - 1,
            qcd.GetName() + "_rebinned", rebinarry)
        ttbar = ttbar.Rebin(
            len(rebinarry) - 1,
            ttbar.GetName() + "_rebinned", rebinarry)
        #zjet      = zjet.Rebin(len(rebinarry) - 1, zjet.GetName()+"_rebinned", rebinarry)
        RSG1_1000 = RSG1_1000.Rebin(
            len(rebinarry) - 1,
            RSG1_1000.GetName() + "_rebinned", rebinarry)
        RSG1_1500 = RSG1_1500.Rebin(
            len(rebinarry) - 1,
            RSG1_1500.GetName() + "_rebinned", rebinarry)
        RSG1_2000 = RSG1_2000.Rebin(
            len(rebinarry) - 1,
            RSG1_2000.GetName() + "_rebinned", rebinarry)
        RSG1_2500 = RSG1_2500.Rebin(
            len(rebinarry) - 1,
            RSG1_2500.GetName() + "_rebinned", rebinarry)
        for jhist in syst_up:
            jhist = jhist.Rebin(
                len(rebinarry) - 1,
                jhist.GetName() + "_rebinned", rebinarry)
        for jhist in syst_down:
            jhist = jhist.Rebin(
                len(rebinarry) - 1,
                jhist.GetName() + "_rebinned", rebinarry)

    #get QS scores
    if "Signal" in cut and blinded:
        ks = 0
    else:
        ks = data.KolmogorovTest(data_est, "QU")
    int_data = data.Integral(0, data.GetXaxis().GetNbins() + 1)
    int_data_est = data_est.Integral(0, data_est.GetXaxis().GetNbins() + 1)
    percentdiff = (int_data_est - int_data) / int_data * 100.0
    #chi2 =        data.Chi2Test(data_est, "QU CHI2")
    #ndf  = chi2 / data.Chi2Test(data_est, "QU CHI2/NDF") if chi2 else 0.0

    xMin = data.GetXaxis().GetBinLowEdge(1)
    xMax = data.GetXaxis().GetBinUpEdge(data.GetXaxis().GetNbins())
    yMax = data.GetMaximum() * 1.5
    if ("FourTag" in cut):
        yMax = data.GetMaximum() * 2.0
    if Logy == 1:
        yMax = yMax * 100
    #qcd_fit = ifile.Get("qcd_fit")
    #qcd_fitUp = ifile.Get("qcd_fitUp")
    #qcd_fitDown = ifile.Get("qcd_fitDown")

    #make the total backgroudn with sytematics
    data = makeTotBkg([data])[1]
    #bkg = makeTotBkg([ttbar,qcd])
    bkg = makeTotBkg([ttbar, qcd], syst_up, syst_down)
    #bkg = makeTotBkg([ttbar,qcd,zjet])
    # bkg/data ratios: [0] band for stat errors, [1] bkg/data with syst errors
    ratios = makeDataRatio(data, bkg[1])

    #comput the integrals! and make the table
    if (not blinded):
        texoutpath = CONF.inputpath + ops.inputdir + "/" + "Plot/Tables/"
        if not os.path.exists(texoutpath):
            os.makedirs(texoutpath)
        outtexFile = open(texoutpath + cut + "_SR_region_compare" + ".tex",
                          "w")
        tableList = []
        int_range_lst = [">1000", ">1500", ">2000", ">2500", ">3000"]
        help_table.add_table_head(tableList, int_range_lst, title="Mass Range")
        #get total background
        outstr = ""
        outstr += "totalbkg"
        #print masterdic, systag
        for int_range in int_range_lst:
            err = ROOT.Double(0.)  ##bkg[2] is the hist with uncertainties
            int_range = bkg[2].IntegralAndError(
                bkg[2].GetXaxis().FindBin(int(int_range.replace(">", ""))),
                bkg[2].GetXaxis().FindBin(3900), err)
            outstr += help_table.add_entry((int_range, float(err)))
        #finish the current entry
        outstr += "\\\\"
        tableList.append(outstr)
        #get data
        outstr = ""
        outstr += "data"
        #print masterdic, systag
        temp_data = ifile.Get("data_hh")
        for int_range in int_range_lst:
            err = ROOT.Double(0.)
            int_range = temp_data.IntegralAndError(
                temp_data.GetXaxis().FindBin(int(int_range.replace(">", ""))),
                temp_data.GetXaxis().FindBin(3900), err)
            outstr += help_table.add_entry((int_range, float(err)))
        #finish the current entry
        outstr += "\\\\"
        tableList.append(outstr)
        #finish the table
        help_table.add_table_tail(tableList, int_range_lst)
        #return the table
        for line in tableList:
            print line
            outtexFile.write(line + " \n")
        outtexFile.close()

    # stack signal on background
    RSG1_1000.Add(bkg[0])
    RSG1_1500.Add(bkg[0])
    RSG1_2000.Add(bkg[0])
    RSG1_2500.Add(bkg[0])

    # canvas
    c0 = ROOT.TCanvas("c0" + filename + cut,
                      "Insert hilarious TCanvas name here", 800, 800)
    c0.SetRightMargin(0.05)

    # top pad
    pad0 = ROOT.TPad("pad0", "pad0", 0.0, 0.31, 1., 1.)
    pad0.SetRightMargin(0.05)
    pad0.SetBottomMargin(0.0001)
    pad0.SetFrameFillColor(0)
    pad0.SetFrameBorderMode(0)
    pad0.SetFrameFillColor(0)
    pad0.SetBorderMode(0)
    pad0.SetBorderSize(0)

    pad1 = ROOT.TPad("pad1", "pad1", 0.0, 0.0, 1., 0.30)
    pad1.SetRightMargin(0.05)
    pad1.SetBottomMargin(0.38)
    pad1.SetTopMargin(0.0001)
    pad1.SetFrameFillColor(0)
    pad1.SetFillStyle(0)  # transparent
    pad1.SetFrameBorderMode(0)
    pad1.SetFrameFillColor(0)
    pad1.SetBorderMode(0)
    pad1.SetBorderSize(0)

    c0.cd()
    pad0.SetLogy(Logy)
    pad0.Draw()
    pad0.cd()

    bkg[0].SetTitle("")
    bkg[0].SetStats(0)
    bkg[0].SetLineColor(ROOT.kBlack)
    bkg[0].SetLineWidth(2)
    bkg[0].GetYaxis().SetTitleFont(43)
    bkg[0].GetYaxis().SetTitleSize(28)
    bkg[0].GetYaxis().SetLabelFont(43)
    bkg[0].GetYaxis().SetLabelSize(28)
    bkg[0].GetYaxis().SetTitle(yTitle)
    bkg[0].GetYaxis().SetRangeUser(0.006, yMax)
    bkg[0].SetFillColor(ROOT.kYellow)
    bkg[0].Draw("HISTO")

    # RSG1_1000.SetLineWidth(2)
    # RSG1_1000.SetLineStyle(2)
    # RSG1_1000.SetLineColor(ROOT.kViolet+7)
    # RSG1_1000.Draw("HISTO SAME")

    # RSG1_1500.SetLineWidth(2)
    # RSG1_1500.SetLineStyle(2)
    # RSG1_1500.SetLineColor(ROOT.kPink+7)
    # RSG1_1500.Draw("HISTO SAME")

    RSG1_2000.SetLineWidth(2)
    RSG1_2000.SetLineStyle(2)
    RSG1_2000.SetLineColor(ROOT.kPink + 7)
    RSG1_2000.Draw("HISTO SAME")

    # RSG1_2500.SetLineWidth(2)
    # RSG1_2500.SetLineStyle(2)
    # RSG1_2500.SetLineColor(ROOT.kGreen+4)
    # RSG1_2500.Draw("HISTO SAME")

    bkg[1].SetFillColor(CONF.col_dic["syst"])
    bkg[1].SetLineColor(CONF.col_dic["syst"])
    bkg[1].SetFillStyle(3345)
    bkg[1].SetMarkerSize(0)
    bkg[1].Draw("E2 SAME")

    ttbar.SetLineWidth(2)
    ttbar.SetLineColor(ROOT.kBlack)
    ttbar.SetFillColor(ROOT.kAzure - 9)
    ttbar.Draw("HISTO SAME")

    #zjet.SetLineWidth(2)
    #zjet.SetLineColor(ROOT.kBlack)
    #zjet.SetFillColor(ROOT.kGreen+4)
    #zjet.Draw("HISTO SAME")

    zeroXerror(data)
    data.SetMarkerStyle(20)
    data.SetMarkerSize(1)
    data.SetLineWidth(2)
    data.GetXaxis().SetLabelSize(0)
    data.GetXaxis().SetLabelOffset(999)
    if not ("Signal" in cut and blinded):
        data.Draw("EPZ SAME")

    # bottom pad
    c0.cd()
    pad1.Draw()
    pad1.cd()

    hratio = ROOT.TH1F("hratio", "", 1, xMin, xMax)
    hratio.SetStats(0)

    hratio.GetYaxis().SetTitleFont(43)
    hratio.GetYaxis().SetTitleSize(28)
    hratio.GetYaxis().SetLabelFont(43)
    hratio.GetYaxis().SetLabelSize(28)
    hratio.GetYaxis().SetTitle("Data / Bkgd")
    hratio.GetYaxis().SetRangeUser(0.5, 2.1)  #set range for ratio plot
    h_plt.drawarrow(ratios[1], 0.5, 2.1)
    hratio.GetYaxis().SetNdivisions(405)

    hratio.GetXaxis().SetTitleFont(43)
    hratio.GetXaxis().SetTitleOffset(3.5)
    hratio.GetXaxis().SetTitleSize(28)
    hratio.GetXaxis().SetLabelFont(43)
    hratio.GetXaxis().SetLabelSize(28)
    hratio.GetXaxis().SetTitle(xTitle)

    hratio.Draw()

    #
    # Add stat uncertianty
    #
    ratios[0].SetFillColor(CONF.col_dic["syst"])
    ratios[0].SetFillStyle(3345)
    ratios[0].Draw("E2")

    #zeroXerror(ratios[1])
    ratios[1].SetMarkerStyle(20)
    ratios[1].SetMarkerSize(1)
    ratios[1].SetLineWidth(2)
    if not ("Signal" in cut and blinded):
        ratios[1].Draw("E0PZ SAME")
    # qcd_fit.SetLineColor(kRed)
    # qcd_fitUp.SetLineColor(kRed)
    # qcd_fitUp.SetLineStyle(2)
    # qcd_fitDown.SetLineColor(kRed)
    # qcd_fitDown.SetLineStyle(2)
    # qcd_fit.Draw("SAME")
    # qcd_fitUp.Draw("SAME")
    # qcd_fitDown.Draw("SAME")

    # Fit the ratio with a TF1
    # if not ("Signal" in cut and blinded):
    #     testfit = ROOT.TF1("testfit", "pol2", xMin, xMax)
    #     testfit.SetParameters(1, 0, 0)
    #     ratios[1].Fit("testfit")
    #     testfit.SetLineColor(kRed)
    #     testfit.Draw("SAME")
    #     fitresult = testfit.GetParameters()
    #     myText(0.2, 0.17, 1, "y=%s x^2 + %s x + %s" % (str('%.2g' % fitresult[0]), \
    #         str('%.2g' % fitresult[1]),str('%.2g' % fitresult[2])), CONF.legsize)

    # draw the ratio 1 line
    line = ROOT.TLine(xMin, 1.0, xMax, 1.0)
    line.SetLineStyle(1)
    line.Draw()

    c0.cd()
    #
    # Add ks score
    #
    myText(0.15, 0.97, 1, "KS = %s" % str(('%.3g' % ks)), CONF.legsize)
    myText(
        0.4, 0.97, 1, "(Est-Obs)/Obs = %s; E=%s; O=%s" % (str(
            ('%.1f' % percentdiff)), str(
                ('%.1f' % int_data_est)), str(('%.1f' % int_data))),
        CONF.legsize)
    #myText(0.15, 0.92, 1, "#chi^{2} / ndf = %s / %s" % (str(chi2), str(ndf)), CONF.legsize)

    # labels
    legHunit = 0.05
    legH = legHunit * 6  # retuned below based on number of entries to 0.05*num_entries
    legW = 0.4
    leg = ROOT.TLegend(0.65, 0.75, 0.95, 0.95)
    # top right, a bit left
    ATLASLabel(0.19, 0.91, StatusLabel)
    if "15" in filepath:
        myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 2015, 3.2 fb^{-1}",
               CONF.legsize)
    elif "16" in filepath:
        myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 2016, 2.6 fb^{-1}",
               CONF.legsize)
    else:
        myText(0.19, 0.87, 1,
               "#sqrt{s}=13 TeV, 15+16, " + str(CONF.totlumi) + " fb^{-1}",
               CONF.legsize)
    myText(0.19, 0.83, 1, ' ' + cut.replace("_", "; "), CONF.legsize)
    ##### legend
    leg.SetNColumns(2)
    leg.SetTextFont(43)
    leg.SetTextSize(CONF.legsize)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)
    leg.AddEntry(data, "Data", "PE")
    leg.AddEntry(bkg[0], "Multijet", "F")
    leg.AddEntry(ttbar, "t#bar{t}", "F")
    #leg.AddEntry(zjet, "Z+jets","F")
    leg.AddEntry(bkg[1], "Stat+Syst", "F")
    #leg.AddEntry(RSG1_1000, "RSG1, 1TeV", "F")
    #leg.AddEntry(RSG1_1500, "RSG 1.5TeV * 10", "F")
    leg.AddEntry(RSG1_2000, "RSG 2.0TeV * 30", "F")
    #leg.AddEntry(RSG1_2500, "RSG 2.5TeV * 100", "F")
    #leg.AddEntry(qcd_fit, "Fit to Ratio", "L")
    #leg.AddEntry(qcd_fitUp, "#pm 1#sigma Uncertainty", "L")
    leg.SetY1(leg.GetY2() - leg.GetNRows() * legHunit)
    leg.Draw()

    # save
    postname = ("" if Logy == 0 else "_" + str(Logy)) + (
        "" if not ("Signal" in cut and blinded) else
        "_blind") + ("" if selsyst is "all" else "_" + selsyst)
    #c0.SaveAs(outputFolder+"/"+filename.replace(".root", ".pdf"))
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".png")
    c0.SaveAs(outputFolder + "/" + filename + "_" + cut + postname + ".pdf")
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + ".pdf")
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + ".eps")

    pad0.Close()
    pad1.Close()
    c0.Close()
    del (data)
    del (data_est)
    del (qcd)
    del (ttbar)
    del (zjet)
    del (RSG1_1000)
    del (RSG1_1500)
    del (RSG1_2500)
    del (syst_up)
    del (syst_down)
示例#9
0
def plotRegion(config, cut, xTitle, yTitle="N Events", Logy=0, rebin=None, rebinarry=None, outputFolder="", doZjet=False):
    #load configurations from config file
    filepath = config["root"] 
    filename = config["inputdir"]
    outputFolder= config["outputdir"]
    blinded = config["blind"]
    #print config, filepath, filename, cut
    ROOT.gStyle.SetErrorX(0)
    ROOT.gStyle.SetHatchesSpacing(0.7)
    ROOT.gStyle.SetHatchesLineWidth(1)

    # input file
    ifile = ROOT.TFile(filepath + filename + ".root")
    # read stuff
    data = ifile.Get("data_" + cut )
    if "Signal" in cut and blinded:
        data = ifile.Get("data_est_" + cut )
    data_est = ifile.Get("data_est_" + cut )
    qcd = ifile.Get("qcd_est_" + cut )
    #qcd_origin = ifile.Get("qcd_" + cut )
    #print "factor is ", qcd.Integral()/qcd_origin.Integral()
    ttbar = ifile.Get("ttbar_est_" + cut )
    if (doZjet):
        zjet = ifile.Get("zjet_" + cut )
    RSG1_1000 = ifile.Get("RSG1_1000_" + cut )
    RSG1_1500 = ifile.Get("RSG1_1500_" + cut )
    RSG1_1500.Scale(10)
    RSG1_2000 = ifile.Get("RSG1_2000_" + cut )
    RSG1_2000.Scale(30)
    RSG1_2500 = ifile.Get("RSG1_2500_" + cut )
    RSG1_2500.Scale(100)
    SMhh = ifile.Get("sm_" + cut )
    SMhh.Scale(100)


    #do simple rebin as rebin values
    if not rebin == None:
        data.Rebin(rebin)
        data_est.Rebin(rebin)
        qcd.Rebin(rebin)
        ttbar.Rebin(rebin) 
        if (doZjet):
            zjet.Rebin(rebin)
        RSG1_1000.Rebin(rebin)
        RSG1_1500.Rebin(rebin)
        RSG1_2000.Rebin(rebin)
        RSG1_2500.Rebin(rebin)
        SMhh.Rebin(rebin)
    #use array to rebin histgrams
    if not rebinarry == None:
        data      = data.Rebin(len(rebinarry) - 1, data.GetName()+"_rebinned", rebinarry)
        data_est  = data_est.Rebin(len(rebinarry) - 1, data_est.GetName()+"_rebinned", rebinarry)
        qcd       = qcd.Rebin(len(rebinarry) - 1, qcd.GetName()+"_rebinned", rebinarry)
        ttbar     = ttbar.Rebin(len(rebinarry) - 1, ttbar.GetName()+"_rebinned", rebinarry)
        if (doZjet):
            zjet      = zjet.Rebin(len(rebinarry) - 1, zjet.GetName()+"_rebinned", rebinarry)
        RSG1_1000 = RSG1_1000.Rebin(len(rebinarry) - 1, RSG1_1000.GetName()+"_rebinned", rebinarry)
        RSG1_1500 = RSG1_1500.Rebin(len(rebinarry) - 1, RSG1_1500.GetName()+"_rebinned", rebinarry)
        RSG1_2000 = RSG1_2000.Rebin(len(rebinarry) - 1, RSG1_2000.GetName()+"_rebinned", rebinarry)
        RSG1_2500 = RSG1_2500.Rebin(len(rebinarry) - 1, RSG1_2500.GetName()+"_rebinned", rebinarry)
        SMhh      = SMhh.Rebin(len(rebinarry) - 1, RSG1_2500.GetName()+"_rebinned", rebinarry)

    #get QS scores
    if "Signal" in cut and blinded:
        ks = 0
    else:
        ks   = data.KolmogorovTest(data_est, "QU")
    int_data = data.Integral(0, data.GetXaxis().GetNbins()+1)
    int_data_est = data_est.Integral(0, data_est.GetXaxis().GetNbins()+1)
    percent_ratio  = (int_data)/int_data_est
    #chi2 =        data.Chi2Test(data_est, "QU CHI2")
    #ndf  = chi2 / data.Chi2Test(data_est, "QU CHI2/NDF") if chi2 else 0.0

    #load basic information
    xMin = data.GetXaxis().GetBinLowEdge(1)
    xMax = data.GetXaxis().GetBinUpEdge(data.GetXaxis().GetNbins())
    yMax = data.GetMaximum() * 1.6
    if ("FourTag" in cut):
        yMax = data.GetMaximum() * 2.0
    if Logy==1:
        yMax = yMax * 100
    #qcd_fit = ifile.Get("qcd_fit")
    #qcd_fitUp = ifile.Get("qcd_fitUp")
    #qcd_fitDown = ifile.Get("qcd_fitDown")

    ##add in normalization error at least
    syst_up = []
    syst_down = []
    f1 = open(filepath + filename + ".txt")
    masterdic = json.load(f1)

    ##find the systmatics from the fit
    cut_temp = cut.split("_")
    if cut_temp[1] == "split":
        cut_temp.remove("split")
        cut_temp[0] = "TwoTag_split"
    #for key_temp, value_temp in masterdic["data_est_nofit"][cut_temp[0]].iteritems():
        #print key_temp, value_temp, cut_temp[1]
        #print key_temp, value_temp, 
    ##this is the total error in the region from the fit
    #print masterdic["data_est_nofit"][cut_temp[0]][cut_temp[1] + "_err"]
    temp_syst_up = data_est.Clone(data_est.GetName() + "_syst_up")
    temp_syst_up.Scale((data_est.Integral() + masterdic["data_est_nofit"][cut_temp[0]][cut_temp[1] + "_err"])/data_est.Integral())
    #print "here", (data_est.Integral() + masterdic["data_est_nofit"][cut_temp[0]][cut_temp[1] + "_err"])/data_est.Integral()
    temp_syst_down = data_est.Clone(data_est.GetName() + "_syst_down")
    temp_syst_down.Scale((data_est.Integral() - masterdic["data_est_nofit"][cut_temp[0]][cut_temp[1] + "_err"])/data_est.Integral())
    syst_up.append(temp_syst_up)
    syst_down.append(temp_syst_down)

    #setup data and bkg estiamtes
    data = h_plt.makeTotBkg([data])[1]
    bkg = h_plt.makeTotBkg([ttbar,qcd])
    if (doZjet):
        bkg = h_plt.makeTotBkg([ttbar,qcd,zjet])
    #bkg = h_plt.makeTotBkg([ttbar,qcd], syst_up, syst_down)
    #bkg = h_plt.makeTotBkg([ttbar,qcd,zjet], syst_up, syst_down)
    # bkg/data ratios: [0] band for stat errors, [1] bkg/data with syst errors
    ratios = h_plt.makeDataRatio(data, bkg[1])

    # stack signal on background
    RSG1_1000.Add(bkg[0]) 
    RSG1_1500.Add(bkg[0]) 
    RSG1_2000.Add(bkg[0]) 
    RSG1_2500.Add(bkg[0]) 
    #SMhh.Add(bkg[0])  ##don't add bkg for SMhh

    # canvas
    c0 = ROOT.TCanvas("c0"+filename+cut, "Insert hilarious TCanvas name here", 600, 600)
    c0.SetRightMargin(0.05)

    # top pad
    pad0 = ROOT.TPad("pad0", "pad0", 0.0, 0.31, 1., 1.)
    pad0.SetRightMargin(0.05)
    pad0.SetBottomMargin(0.0001)
    pad0.SetFrameFillColor(0)
    pad0.SetFrameBorderMode(0)
    pad0.SetFrameFillColor(0)
    pad0.SetBorderMode(0)
    pad0.SetBorderSize(0)

    pad1 = ROOT.TPad("pad1", "pad1", 0.0, 0.0, 1., 0.30)
    pad1.SetRightMargin(0.05)
    pad1.SetBottomMargin(0.38)
    pad1.SetTopMargin(0.0001)
    pad1.SetFrameFillColor(0)
    pad1.SetFillStyle(0) # transparent
    pad1.SetFrameBorderMode(0)
    pad1.SetFrameFillColor(0)
    pad1.SetBorderMode(0)
    pad1.SetBorderSize(0)

    c0.cd()
    pad0.SetLogy(Logy)
    pad0.Draw()
    pad0.cd()


    bkg[0].SetTitle("")
    bkg[0].SetStats(0)
    bkg[0].SetLineColor(ROOT.kBlack)
    bkg[0].SetLineWidth(2)
    bkg[0].GetYaxis().SetTitleFont(43)
    bkg[0].GetYaxis().SetTitleSize(28)
    bkg[0].GetYaxis().SetLabelFont(43)
    bkg[0].GetYaxis().SetLabelSize(28)
    bkg[0].GetYaxis().SetTitle(yTitle)
    bkg[0].GetYaxis().SetRangeUser(0.02, yMax)
    bkg[0].SetFillColor(ROOT.kYellow)
    bkg[0].Draw("HISTO")

    # RSG1_1000.SetLineWidth(2)
    # RSG1_1000.SetLineStyle(2)
    # RSG1_1000.SetLineColor(ROOT.kViolet+7)
    # RSG1_1000.Draw("HISTO SAME")

    RSG1_1500.SetLineWidth(2)
    RSG1_1500.SetLineStyle(2)
    RSG1_1500.SetLineColor(ROOT.kPink+7)
    #RSG1_1500.Draw("HISTO SAME")


    RSG1_2000.SetLineWidth(2)
    RSG1_2000.SetLineStyle(2)
    RSG1_2000.SetLineColor(ROOT.kPink+7)
    RSG1_2000.Draw("HISTO SAME")

    RSG1_2500.SetLineWidth(2)
    RSG1_2500.SetLineStyle(2)
    RSG1_2500.SetLineColor(ROOT.kGreen+4)
    #RSG1_2500.Draw("HISTO SAME")

    SMhh.SetLineWidth(2)
    SMhh.SetLineStyle(2)
    SMhh.SetLineColor(ROOT.kGreen+4)
    if ("Signal" in cut):
        SMhh.Draw("HISTO SAME")

    bkg[1].SetFillColor(CONF.col_dic["syst"])
    bkg[1].SetLineColor(CONF.col_dic["syst"])
    bkg[1].SetFillStyle(3345)
    bkg[1].SetMarkerSize(0)
    bkg[1].Draw("E2 SAME")

    ttbar.SetLineWidth(2)
    ttbar.SetLineColor(ROOT.kBlack)
    ttbar.SetFillColor(ROOT.kAzure-9)
    ttbar.Draw("HISTO SAME")

    if (doZjet):
        zjet.SetLineWidth(2)
        zjet.SetLineColor(ROOT.kBlack)
        zjet.SetFillColor(ROOT.kGreen+4)
        zjet.Draw("HISTO SAME")

    h_plt.zeroXerror(data)
    data.SetMarkerStyle(20)
    data.SetMarkerSize(1)
    data.SetLineWidth(2)
    data.GetXaxis().SetLabelSize(0)
    data.GetXaxis().SetLabelOffset(999)
    if not ("Signal" in cut and blinded):
        data.Draw("EPZ SAME")

    # bottom pad
    c0.cd()
    pad1.Draw()
    pad1.cd()

    hratio = ROOT.TH1F("hratio","",1, xMin, xMax)
    hratio.SetStats(0)
    
    hratio.GetYaxis().SetTitleFont(43)
    hratio.GetYaxis().SetTitleSize(28)
    hratio.GetYaxis().SetLabelFont(43)
    hratio.GetYaxis().SetLabelSize(28)
    hratio.GetYaxis().SetTitle("Data / Bkgd")
    hratio.GetYaxis().SetRangeUser(0.4, 1.8) #set range for ratio plot
    hratio.GetYaxis().SetNdivisions(405)

    hratio.GetXaxis().SetTitleFont(43)
    hratio.GetXaxis().SetTitleOffset(3.5)
    hratio.GetXaxis().SetTitleSize(28)
    hratio.GetXaxis().SetLabelFont(43)
    hratio.GetXaxis().SetLabelSize(28)
    hratio.GetXaxis().SetTitle(xTitle)

    hratio.Draw()

    #
    # Add stat uncertianty
    #
    ratios[0].SetFillColor(CONF.col_dic["syst"])
    ratios[0].SetFillStyle(3345)
    ratios[0].Draw("E2")

    #h_plt.zeroXerror(ratios[1])
    ratios[1].SetMarkerStyle(20)
    ratios[1].SetMarkerSize(1)
    ratios[1].SetLineWidth(2)
    if not ("Signal" in cut and blinded):
        ratios[1].Draw("E0PZ SAME")
    ##add arrows; call this function
    h_plt.drawarrow(ratios[1], 0.4, 1.8)
    # qcd_fit.SetLineColor(kRed)
    # qcd_fitUp.SetLineColor(kRed)
    # qcd_fitUp.SetLineStyle(2)
    # qcd_fitDown.SetLineColor(kRed)
    # qcd_fitDown.SetLineStyle(2)
    # qcd_fit.Draw("SAME")
    # qcd_fitUp.Draw("SAME")
    # qcd_fitDown.Draw("SAME")

    ## Fit the ratio with a TF1
    if("mHH" in cut and not blinded):
        testfit = ROOT.TF1("testfit", "pol1", xMin, xMax)
        testfit.SetParameters(1, 0)
        ratios[1].Fit("testfit", "QLWW0IBF", "")
        testfit.SetLineColor(ROOT.kRed)
        testfit.SetLineStyle(9)
        testfit.Draw("SAME")
        fitresult = testfit.GetParameters()
        ROOT.myText(0.15, 0.12, 1, "y=%s x + %s, prob:%s" % (str('%.2g' % fitresult[0]), \
            str('%.2g' % fitresult[1]), str('%.2g' % float(testfit.GetProb()))), CONF.legsize)

    # draw the ratio 1 line
    line = ROOT.TLine(xMin, 1.0, xMax, 1.0)
    line.SetLineStyle(1)
    line.Draw()
    c0.cd()

    #
    # Add ks score
    #
    if (ops.detail):
        ROOT.myText(0.15, 0.97, 1, "KS = %s" % str(('%.3g' % ks)), CONF.legsize)
        ROOT.myText(0.4, 0.97, 1, "Obs/Est = %s/%s = %s" % 
            (str(('%.1f' % int_data)), str(('%.1f' % int_data_est)), str(('%.3f' % percent_ratio))), CONF.legsize)
        #myText(0.15, 0.92, 1, "#chi^{2} / ndf = %s / %s" % (str(chi2), str(ndf)), CONF.legsize)

    # labels
    legHunit=0.05
    legH=legHunit*6 # retuned below based on number of entries to 0.05*num_entries
    legW=0.4
    leg = ROOT.TLegend(0.65, 0.75, 0.95, 0.95)
    # top right, a bit left
    if not CONF.thesis:
        ROOT.ATLASLabel(0.19, 0.91, CONF.StatusLabel)
    if "15" in filepath:
        ROOT.myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 2015, 3.2 fb^{-1}", CONF.legsize)
    elif "16" in filepath:
        ROOT.myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 2016, 2.6 fb^{-1}", CONF.legsize)
    else:
        ROOT.myText(0.19, 0.87, 1, "#sqrt{s}=13 TeV, 15+16, " + str(CONF.totlumi) + " fb^{-1}", CONF.legsize)

    #clean up the info string
    infostr = cut
    infostr = infostr.replace("_", ";")
    infostr = infostr.replace("Sideband", "SB") if "Sideband" in infostr else infostr
    infostr = infostr.replace("Control", "CR") if "Sideband" in infostr else infostr
    infostr = infostr.replace("Signal", "SR") if "Sideband" in infostr else infostr
    infostr = infostr.replace("FourTag", "4b") if "FourTag" in infostr else infostr
    infostr = infostr.replace("ThreeTag", "3b") if "ThreeTag" in infostr else infostr
    infostr = infostr.replace("TwoTag;split", "2bs") if "TwoTag;split" in infostr else infostr
    ROOT.myText(0.19, 0.83, 1, ' ' + infostr, CONF.legsize)

    ##### legend
    #leg.SetNColumns(2)
    leg.SetTextFont(43)
    leg.SetTextSize(CONF.legsize)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)
    leg.AddEntry(data, "Data", "PE")
    leg.AddEntry(bkg[0], "Multijet", "F")
    leg.AddEntry(ttbar, "t#bar{t}","F")
    if (doZjet):
        leg.AddEntry(zjet, "Z+jets","F")
    leg.AddEntry(bkg[1], "Stat Uncer.", "F")
    #leg.AddEntry(RSG1_1000, "RSG1, 1TeV", "F")
    #leg.AddEntry(RSG1_1500, "RSG 1.5TeV * 10", "F")
    leg.AddEntry(RSG1_2000, "G(2000)#times30", "F")
    #leg.AddEntry(RSG1_2500, "RSG 2.5TeV * 100", "F")
    if ("Signal" in cut):
        leg.AddEntry(SMhh, "SMNR#times1000", "F")
    #leg.AddEntry(qcd_fit, "Fit to Ratio", "L")
    #leg.AddEntry(qcd_fitUp, "#pm 1#sigma Uncertainty", "L")
    leg.SetY1(leg.GetY2()-leg.GetNRows()*legHunit)
    leg.Draw()


    # save
    postname = ("" if Logy == 0 else "_" + str(Logy)) + ("" if not ("Signal" in cut and blinded) else "_blind")
    #c0.SaveAs(outputFolder+"/"+filename.replace(".root", ".pdf"))
    c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".png")
    c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".pdf")
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".eps")
    #c0.SaveAs(outputFolder+ "/" + filename + "_" + cut + postname + ".C")

    #close and quit
    pad0.Close()
    pad1.Close()
    c0.Close()
    f1.close()
    del(leg)