Exemplo n.º 1
0
thisTrue.Draw('hist same')
thisMeas.Draw('same')
thisTrue.UseCurrentStyle()
thisTrue.SetLineColor(4)
thisTrue.GetYaxis().SetTitleSize(25)
thisTrue.GetXaxis().SetLabelSize(0)

leg = TLegend(0.5, 0.55, 0.9, 0.75)
leg.SetFillStyle(0)
leg.SetTextFont(42)
leg.SetTextSize(0.045)
leg.SetBorderSize(0)

tt = TLatex()
tt.SetNDC()
tt.SetTextFont(42)
leg.AddEntry(thisReco, 'Unfolded MC (Powheg)', 'p')
leg.AddEntry(thisTrue, 'Generated (Powheg)', 'l')
leg.AddEntry(thisMeas, 'Reco-level (Powheg)', 'p')
tt.DrawLatex(0.55, 0.45, "MC closure test")
leg.Draw()

# write histograms to file
thisReco.SetName("UnfoldedMC")

thisReco.Write()
thisTrue.Write()
thisMeas.Write()

text1 = TLatex()
text1.SetNDC()
Exemplo n.º 2
0
        outName[i] = testFiles[i][:-5]
        outEst[i] = BGNormalization

    l = TLegend(0.35, 0.70, 0.7, 0.9, "", "brNDC")
    l.SetBorderSize(0)
    l.SetFillColor(0)
    l.SetTextSize(.03)
    l.AddEntry(hist_Data, "SS Data ", "p")
    l.AddEntry(outHist[i], "BG Est.(Shape from Relaxed Tau Iso.)", "lpf")
    #    l.AddEntry(hist_Estimation_ff, "BG Est.(both tau Iso Reverted)", "lpf")
    l.Draw()

    #Text in Histogram
    t = TLatex()
    t.SetNDC()
    t.SetTextFont(62)
    t.SetTextAlign(12)
    t.SetTextSize(0.03)
    t.DrawLatex(0.1, .92, "CMS Preliminary 2012")
    t.DrawLatex(0.45, .92, "#sqrt{s} = 8 TeV, L = 19.7 fb^{-1}")
    t.DrawLatex(0.80, .92, "ll#tau#tau")
    #    t.DrawLatex(0.5, .60, "Data, SS, 10 GeV Tau LooseIso")
    #    t.DrawLatex(0.5, .52, "Data = " + str(DataNormalization))
    ############### Tp Print Normalization in the plots
    #    for i in range(len(testFiles)):
    #        clr = i + 1
    #        if i == 4: clr = 7
    #        t.SetTextColor(clr)
    #        t.DrawLatex(0.5, .52-((i + 1) / 20.), outName[i] + " = " + str(outEst[i]))

    canvas.SaveAs("Compare_tauFR2.pdf")
Exemplo n.º 3
0
def plot1D(histname, histnum2D, histden2D, year, channel, title="", log=False):
    """Plot efficiency."""
    dir = ensureDirectory('plots/%d' % year)
    name = "%s/%s_%s" % (dir, histname, channel)
    if log:
        name += "_log"
    header = ""
    xtitle = 'jet p_{T} [GeV]'
    ytitle = 'b tag efficiencies' if '_b_' in histname else 'b mistag rate'
    xmin, xmax = 20 if log else 10, histnum2D.GetXaxis().GetXmax()
    ymin, ymax = 5e-3 if log else 0.0, 2.0
    colors = [kBlue, kRed, kOrange]
    x1, y1 = (0.27, 0.44) if '_b_' in histname else (0.55, 0.80)
    width, height = 0.3, 0.16
    x2, y2 = x1 + width, y1 - height
    hists = createEff1D(histnum2D, histden2D)

    canvas = TCanvas('canvas', 'canvas', 100, 100, 800, 700)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetFrameFillStyle(0)
    canvas.SetFrameBorderMode(0)
    canvas.SetTopMargin(0.04)
    canvas.SetBottomMargin(0.13)
    canvas.SetLeftMargin(0.12)
    canvas.SetRightMargin(0.05)
    canvas.SetTickx(0)
    canvas.SetTicky(0)
    canvas.SetGrid()
    gStyle.SetOptTitle(0)
    if log:
        canvas.SetLogx()
        canvas.SetLogy()
    canvas.cd()

    frame = hists[0]
    for i, hist in enumerate(hists):
        hist.SetLineColor(colors[i % len(colors)])
        hist.SetMarkerColor(colors[i % len(colors)])
        hist.SetLineWidth(2)
        hist.SetMarkerSize(2)
        hist.SetMarkerStyle(1)
        hist.Draw('PE0SAME')
    frame.GetXaxis().SetTitle(xtitle)
    frame.GetYaxis().SetTitle(ytitle)
    frame.GetXaxis().SetLabelSize(0.048)
    frame.GetYaxis().SetLabelSize(0.048)
    frame.GetXaxis().SetTitleSize(0.058)
    frame.GetYaxis().SetTitleSize(0.058)
    frame.GetXaxis().SetTitleOffset(1.03)
    frame.GetYaxis().SetTitleOffset(1.04)
    frame.GetXaxis().SetLabelOffset(-0.004 if log else 0.005)
    frame.GetXaxis().SetRangeUser(xmin, xmax)
    frame.SetMinimum(ymin)
    frame.SetMaximum(ymax)

    if title:
        latex = TLatex()
        latex.SetTextSize(0.04)
        latex.SetTextAlign(13)
        latex.SetTextFont(62)
        latex.SetNDC(True)
        latex.DrawLatex(0.15, 0.94, title)

    legend = TLegend(x1, y1, x2, y2)
    legend.SetTextSize(0.04)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    legend.SetFillColor(0)
    if header:
        legend.SetTextFont(62)
        legend.SetHeader(header)
    legend.SetTextFont(42)
    for hist in hists:
        legend.AddEntry(hist, hist.GetTitle(), 'lep')
    legend.Draw()

    canvas.SaveAs(name + '.pdf')
    canvas.SaveAs(name + '.png')
    canvas.Close()
Exemplo n.º 4
0
def plot2D(histname, hist, year, channel, log=False):
    """Plot 2D efficiency."""
    dir = ensureDirectory('plots/%d' % year)
    name = "%s/%s_%s" % (dir, histname, channel)
    if log:
        name += "_log"
    xtitle = 'jet p_{T} [GeV]'
    ytitle = 'jet #eta'
    ztitle = 'b tag efficiencies' if '_b_' in histname else 'b mistag rate'
    xmin, xmax = 20, hist.GetXaxis().GetXmax()
    zmin, zmax = 5e-3 if log else 0.0, 1.0
    angle = 22 if log else 77

    canvas = TCanvas('canvas', 'canvas', 100, 100, 800, 700)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetFrameFillStyle(0)
    canvas.SetFrameBorderMode(0)
    canvas.SetTopMargin(0.07)
    canvas.SetBottomMargin(0.13)
    canvas.SetLeftMargin(0.12)
    canvas.SetRightMargin(0.17)
    canvas.SetTickx(0)
    canvas.SetTicky(0)
    canvas.SetGrid()
    gStyle.SetOptTitle(0)  #FontSize(0.04)
    if log:
        canvas.SetLogx()
        canvas.SetLogz()
    canvas.cd()

    hist.GetXaxis().SetTitle(xtitle)
    hist.GetYaxis().SetTitle(ytitle)
    hist.GetZaxis().SetTitle(ztitle)
    hist.GetXaxis().SetLabelSize(0.048)
    hist.GetYaxis().SetLabelSize(0.048)
    hist.GetZaxis().SetLabelSize(0.048)
    hist.GetXaxis().SetTitleSize(0.058)
    hist.GetYaxis().SetTitleSize(0.058)
    hist.GetZaxis().SetTitleSize(0.056)
    hist.GetXaxis().SetTitleOffset(1.03)
    hist.GetYaxis().SetTitleOffset(1.04)
    hist.GetZaxis().SetTitleOffset(1.03)
    hist.GetXaxis().SetLabelOffset(-0.004 if log else 0.005)
    hist.GetZaxis().SetLabelOffset(-0.005 if log else 0.005)
    hist.GetXaxis().SetRangeUser(xmin, xmax)
    hist.SetMinimum(zmin)
    hist.SetMaximum(zmax)
    hist.Draw('COLZTEXT%d' % angle)

    gStyle.SetPaintTextFormat('.2f')
    hist.SetMarkerColor(kRed)
    hist.SetMarkerSize(1.8 if log else 1)
    #gPad.Update()
    #gPad.RedrawAxis()

    latex = TLatex()
    latex.SetTextSize(0.048)
    latex.SetTextAlign(23)
    latex.SetTextFont(42)
    latex.SetNDC(True)
    latex.DrawLatex(0.475, 0.99,
                    hist.GetTitle())  # to prevent typesetting issues

    canvas.SaveAs(name + '.pdf')
    canvas.SaveAs(name + '.png')
    canvas.Close()
Exemplo n.º 5
0
def limit():
    method = ''
    channel = "bb"
    if INCLUDEACC:
        particleP = "X"
    else:
        particleP = "Z'"
    particle = 'b#bar{b}'
    multF = ZPTOBB
    THEORY = ['bstar']
    if INCLUDEACC: THEORY.append('SSM')

    suffix = "_" + BTAGGING
    if ISMC: suffix += "_MC"
    if SY: suffix += "_comb"
    #if method=="cls": suffix="_CLs"
    if INCLUDEACC: suffix += "_acc"

    if SY:
        filename = "./combine/limits/bstar/" + BTAGGING + "/combined_run2/" + YEAR + "_M%d.txt"
    else:
        filename = "./combine/limits/bstar/" + BTAGGING + "/" + YEAR + "_M%d.txt"
    if CATEGORY != "":
        if SY:
            filename = filename.replace(
                BTAGGING + "/combined_run2/",
                BTAGGING + "/single_category/combined_run2/" + CATEGORY + "_")
        else:
            filename = filename.replace(
                BTAGGING + "/",
                BTAGGING + "/single_category/" + CATEGORY + "_")
        suffix += "_" + CATEGORY
    if ISMC: filename = filename.replace(".txt", "_MC.txt")
    mass, val = fillValues(filename)

    #print "mass =",mass
    #print "val =", val

    Obs0s = TGraph()
    Exp0s = TGraph()
    Exp1s = TGraphAsymmErrors()
    Exp2s = TGraphAsymmErrors()
    Sign = TGraph()
    pVal = TGraph()
    Best = TGraphAsymmErrors()
    Theory = {}

    for i, m in enumerate(mass):
        if not m in val:
            print "Key Error:", m, "not in value map"
            continue

        if INCLUDEACC:
            acc_factor = ACCEPTANCE[m]
        else:
            acc_factor = 1.

        n = Exp0s.GetN()
        Obs0s.SetPoint(n, m, val[m][0] * multF * acc_factor)
        Exp0s.SetPoint(n, m, val[m][3] * multF * acc_factor)
        Exp1s.SetPoint(n, m, val[m][3] * multF * acc_factor)
        Exp1s.SetPointError(n, 0., 0.,
                            (val[m][3] - val[m][2]) * multF * acc_factor,
                            (val[m][4] - val[m][3]) * multF * acc_factor)
        Exp2s.SetPoint(n, m, val[m][3] * multF * acc_factor)
        Exp2s.SetPointError(n, 0., 0.,
                            (val[m][3] - val[m][1]) * multF * acc_factor,
                            (val[m][5] - val[m][3]) * multF * acc_factor)
        if len(val[m]) > 6: Sign.SetPoint(n, m, val[m][6])
        if len(val[m]) > 7: pVal.SetPoint(n, m, val[m][7])
        if len(val[m]) > 8: Best.SetPoint(n, m, val[m][8])
        if len(val[m]) > 10:
            Best.SetPointError(n, 0., 0., abs(val[m][9]), val[m][10])

    for t in THEORY:
        Theory[t] = TGraphAsymmErrors()
        if 'bstar' == t:
            x = []
            y = []
            with open('bstar_deta1p1_lhc13TeV2.txt') as fin:
                for line in fin.readlines():
                    x.append(float(line.split()[0]))
                    y.append(float(line.split()[1]) * 1000)
                for ind in range(len(x)):
                    Theory[t].SetPoint(ind + 1, x[ind], y[ind])
                Theory[t].SetLineColor(theoryLineColor[t])
                Theory[t].SetFillColor(theoryFillColor[t])
                Theory[t].SetFillStyle(theoryFillStyle[t])
                Theory[t].SetLineWidth(2)
                continue
        Xs_dict = HVT[t]['Z']['XS'] if t != 'SSM' else SSM['Z']
        for m in sorted(Xs_dict.keys()):
            if INCLUDEACC and t != 'SSM':
                acc_factor = ACCEPTANCE[m]
            else:
                acc_factor = 1.
            if m < SIGNALS[0] or m > SIGNALS[-1]: continue
            #if m < mass[0] or m > mass[-1]: continue
            #if t!= 'SSM' and m>4500: continue ## I don't have the higher mass xs
            if m > 4500: continue
            XsZ, XsZ_Up, XsZ_Down = 0., 0., 0.
            if t != 'SSM':
                XsZ = 1000. * HVT[t]['Z']['XS'][m] * SSM["BrZ"][
                    m]  #assuming the same BR as the SSM Z' one
                XsZ_Up = XsZ * (1. + math.hypot(HVT[t]['Z']['QCD'][m][0] - 1.,
                                                HVT[t]['Z']['PDF'][m][0] - 1.))
                XsZ_Down = XsZ * (1. -
                                  math.hypot(1. - HVT[t]['Z']['QCD'][m][0],
                                             1. - HVT[t]['Z']['PDF'][m][0]))
            else:
                XsZ = 1000. * SSM['Z'][m] * SSM["BrZ"][m]
                XsZ_Up = XsZ * (1. +
                                math.hypot(HVT['A1']['Z']['QCD'][m][0] - 1.,
                                           HVT['A1']['Z']['PDF'][m][0] - 1.))
                XsZ_Down = XsZ * (1. -
                                  math.hypot(1. - HVT['A1']['Z']['QCD'][m][0],
                                             1. - HVT['A1']['Z']['PDF'][m][0]))

            n = Theory[t].GetN()
            Theory[t].SetPoint(n, m, XsZ * acc_factor)
            Theory[t].SetPointError(n, 0., 0., (XsZ - XsZ_Down) * acc_factor,
                                    (XsZ_Up - XsZ) * acc_factor)

            Theory[t].SetLineColor(theoryLineColor[t])
            Theory[t].SetFillColor(theoryFillColor[t])
            Theory[t].SetFillStyle(theoryFillStyle[t])
            Theory[t].SetLineWidth(2)
            #Theory[t].SetLineStyle(7)

    Exp2s.SetLineWidth(2)
    Exp2s.SetLineStyle(1)
    Obs0s.SetLineWidth(3)
    Obs0s.SetMarkerStyle(0)
    Obs0s.SetLineColor(1)
    Exp0s.SetLineStyle(2)
    Exp0s.SetLineWidth(3)
    Exp1s.SetFillColor(417)  #kGreen+1
    Exp1s.SetLineColor(417)  #kGreen+1
    Exp2s.SetFillColor(800)  #kOrange
    Exp2s.SetLineColor(800)  #kOrange
    Exp2s.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetTitle(
        "#sigma(" + particleP + ") #bf{#it{#Beta}}(" + particleP +
        " #rightarrow " + particle +
        "){} (fb)".format(" #times #Alpha" if INCLUDEACC else ""))
    Exp2s.GetYaxis().SetTitleOffset(1.5)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetMoreLogLabels()

    Sign.SetLineWidth(2)
    Sign.SetLineColor(629)
    Sign.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    Sign.GetXaxis().SetTitleSize(Sign.GetXaxis().GetTitleSize() * 1.1)
    Sign.GetYaxis().SetTitle("Significance")

    pVal.SetLineWidth(2)
    pVal.SetLineColor(629)
    pVal.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    pVal.GetXaxis().SetTitleSize(pVal.GetXaxis().GetTitleSize() * 1.1)
    pVal.GetYaxis().SetTitle("local p-Value")

    Best.SetLineWidth(2)
    Best.SetLineColor(629)
    Best.SetFillColor(629)
    Best.SetFillStyle(3003)
    Best.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    Best.GetXaxis().SetTitleSize(Best.GetXaxis().GetTitleSize() * 1.1)
    Best.GetYaxis().SetTitle("Best Fit (pb)")

    c1 = TCanvas("c1", "Exclusion Limits", 800, 600)
    c1.cd()
    #SetPad(c1.GetPad(0))
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetLeftMargin(0.12)
    c1.GetPad(0).SetTicks(1, 1)
    #c1.GetPad(0).SetGridx()
    #c1.GetPad(0).SetGridy()
    c1.GetPad(0).SetLogy()
    Exp2s.Draw("A3")
    Exp1s.Draw("SAME, 3")
    for t in THEORY:
        Theory[t].Draw("SAME, L3")
        Theory[t].Draw("SAME, L3X0Y0")
    Exp0s.Draw("SAME, L")
    if not options.blind: Obs0s.Draw("SAME, L")
    #setHistStyle(Exp2s)
    Exp2s.GetXaxis().SetTitleSize(0.050)
    Exp2s.GetYaxis().SetTitleSize(0.050)
    Exp2s.GetXaxis().SetLabelSize(0.045)
    Exp2s.GetYaxis().SetLabelSize(0.045)
    Exp2s.GetXaxis().SetTitleOffset(0.90)
    Exp2s.GetYaxis().SetTitleOffset(1.25)
    Exp2s.GetYaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetNoExponent(True)
    if INCLUDEACC:
        Exp2s.GetYaxis().SetRangeUser(0.05, 5.e3)
    else:
        Exp2s.GetYaxis().SetRangeUser(0.1, 5.e3)
    #else: Exp2s.GetYaxis().SetRangeUser(0.1, 1.e2)
    #Exp2s.GetXaxis().SetRangeUser(mass[0], min(mass[-1], MAXIMUM[channel] if channel in MAXIMUM else 1.e6))
    Exp2s.GetXaxis().SetRangeUser(SIGNALS[0], SIGNALS[-1])
    #drawAnalysis(channel)
    drawAnalysis("")
    #drawRegion(channel, True)
    drawRegion("", True)
    #drawCMS(LUMI, "Simulation Preliminary") #Preliminary
    if CATEGORY == "":
        #drawCMS(LUMI, "Work in Progress", suppressCMS=True)
        drawCMS(LUMI, "", suppressCMS=True)
    else:
        #drawCMS(LUMI, "Work in Progress, "+CAT_LABELS[CATEGORY], suppressCMS=True)
        drawCMS(LUMI, CAT_LABELS[CATEGORY], suppressCMS=True)

    # legend
    top = 0.9
    nitems = 4 + len(THEORY)

    leg = TLegend(0.55, top - nitems * 0.3 / 5., 0.98, top)
    #leg = TLegend(0.45, top-nitems*0.3/5., 0.98, top)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("95% CL upper limits")
    leg.AddEntry(Obs0s, "Observed", "l")
    leg.AddEntry(Exp0s, "Expected", "l")
    leg.AddEntry(Exp1s, "#pm 1 std. deviation", "f")
    leg.AddEntry(Exp2s, "#pm 2 std. deviation", "f")
    for t in THEORY:
        leg.AddEntry(Theory[t], theoryLabel[t], "fl")
    leg.Draw()
    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.045)
    latex.SetTextFont(42)
    #latex.DrawLatex(0.66, leg.GetY1()-0.045, particleP+" #rightarrow "+particle+"h")

    leg2 = TLegend(0.12, 0.225 - 2 * 0.25 / 5., 0.65, 0.225)
    leg2.SetBorderSize(0)
    leg2.SetFillStyle(0)  #1001
    leg2.SetFillColor(0)
    c1.GetPad(0).RedrawAxis()

    leg2.Draw()
    if not options.blind: Obs0s.Draw("SAME, L")
    c1.GetPad(0).Update()

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")

    c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix + ".png")
    c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix + ".pdf")
    if 'ah' in channel or 'sl' in channel:
        c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix + ".C")
        c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix +
                 ".root")

    for t in THEORY:
        print "Model", t, ":",
        for m in range(mass[0], mass[-1], 1):
            if not (Theory[t].Eval(m) > Obs0s.Eval(m)) == (
                    Theory[t].Eval(m + 1) > Obs0s.Eval(m + 1)):
                print m,
        print ""

    return  ##FIXME

    # ---------- Significance ----------
    c2 = TCanvas("c2", "Significance", 800, 600)
    c2.cd()
    c2.GetPad(0).SetTopMargin(0.06)
    c2.GetPad(0).SetRightMargin(0.05)
    c2.GetPad(0).SetTicks(1, 1)
    c2.GetPad(0).SetGridx()
    c2.GetPad(0).SetGridy()
    Sign.GetYaxis().SetRangeUser(0., 5.)
    Sign.Draw("AL3")
    #drawCMS(LUMI, "Preliminary")
    drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawAnalysis(channel[1:3])
    c2.Print("combine/plotsLimit/Significance/" + YEAR + suffix + ".png")
    c2.Print("combine/plotsLimit/Significance/" + YEAR + suffix + ".pdf")
    #    c2.Print("plotsLimit/Significance/"+YEAR+suffix+".root")
    #    c2.Print("plotsLimit/Significance/"+YEAR+suffix+".C")

    # ---------- p-Value ----------
    c3 = TCanvas("c3", "p-Value", 800, 600)
    c3.cd()
    c3.GetPad(0).SetTopMargin(0.06)
    c3.GetPad(0).SetRightMargin(0.05)
    c3.GetPad(0).SetTicks(1, 1)
    c3.GetPad(0).SetGridx()
    c3.GetPad(0).SetGridy()
    c3.GetPad(0).SetLogy()
    pVal.Draw("AL3")
    pVal.GetYaxis().SetRangeUser(2.e-7, 0.5)

    ci = [
        1., 0.317310508, 0.045500264, 0.002699796, 0.00006334, 0.000000573303,
        0.000000001973
    ]
    line = TLine()
    line.SetLineColor(922)
    line.SetLineStyle(7)
    text = TLatex()
    text.SetTextColor(922)
    text.SetTextSize(0.025)
    text.SetTextAlign(12)
    for i in range(1, len(ci) - 1):
        line.DrawLine(pVal.GetXaxis().GetXmin(), ci[i] / 2,
                      pVal.GetXaxis().GetXmax(), ci[i] / 2)
        text.DrawLatex(pVal.GetXaxis().GetXmax() * 1.01, ci[i] / 2,
                       "%d #sigma" % i)

    #drawCMS(LUMI, "Preliminary")
    drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawAnalysis(channel[1:3])
    c3.Print("combine/plotsLimit/pValue/" + YEAR + suffix + ".png")
    c3.Print("combine/plotsLimit/pValue/" + YEAR + suffix + ".pdf")
    #    c3.Print("plotsLimit/pValue/"+YEAR+suffix+".root")
    #    c3.Print("plotsLimit/pValue/"+YEAR+suffix+".C")

    # --------- Best Fit ----------
    c4 = TCanvas("c4", "Best Fit", 800, 600)
    c4.cd()
    c4.GetPad(0).SetTopMargin(0.06)
    c4.GetPad(0).SetRightMargin(0.05)
    c4.GetPad(0).SetTicks(1, 1)
    c4.GetPad(0).SetGridx()
    c4.GetPad(0).SetGridy()
    Best.Draw("AL3")
    #drawCMS(LUMI, "Preliminary")
    drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawAnalysis(channel[1:3])
    c4.Print("combine/plotsLimit/BestFit/" + YEAR + suffix + ".png")
    c4.Print("combine/plotsLimit/BestFit/" + YEAR + suffix + ".pdf")
    #    c4.Print("plotsLimit/BestFit/"+YEAR+suffix+".root")
    #    c4.Print("plotsLimit/BestFit/"+YEAR+suffix+".C")

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")

    if 'ah' in channel:
        outFile = TFile("bands.root", "RECREATE")
        outFile.cd()
        pVal.Write("graph")
        Best.Write("best")
        outFile.Close()
extraTextFont = 52

if year == '2016':
    lumiText = "35.9  fb^{#minus1} (13 TeV)"
if year == '2017':
    lumiText = "41.50  fb^{#minus1} (13 TeV)"
if year == '2018':
    lumiText = "59.74  fb^{#minus1} (13 TeV)"
lumiTextSize = 0.55
lumiTextOffset = 0.2
relExtraDY = 1.2

latex.SetTextAngle(0)
latex.SetTextColor(kBlack)
extraTextSize = extraOverCmsTextSize * cmsTextSize
latex.SetTextFont(42)
latex.SetTextAlign(31)
latex.SetTextSize(lumiTextSize * t)

latex.SetTextFont(42)
latex.SetTextAlign(31)
latex.SetTextSize(lumiTextSize * t)
latex.DrawLatex(1 - r, 1 - t + lumiTextOffset * t, lumiText)

latex.SetTextFont(cmsTextFont)
latex.SetTextAlign(11)
latex.SetTextSize(cmsTextSize * t)
latex.DrawLatex(1.15 * l, 1 - t + lumiTextOffset * t, cmsText)

posX_ = 0
posX_ = l + relPosX * (1 - l - r)
Exemplo n.º 7
0
def make_ratioplot(name, ttbar_file=0, qcd_file=0, signal_files=[], histo=0,rebin=1,minx=0,maxx=0,miny=0,maxy=0,logy=False,
                    xtitle='',ytitle='',textsizefactor=1,signal_legend=[],outfile=0,signal_colors=[], signal_zoom=1, qcd_zoom=1, ttbar_zoom=1,
                    ttbar_legend='t#bar{t}',qcd_legend='QCD from MC',dosys=False,docms=True,legendtitle=''):
  
  ###canvas setting up
  canvas=0
  canvas=TCanvas(name,'',0,0,600,600)
  canvas.SetLeftMargin(0.15)
  canvas.SetRightMargin(0.05)
  canvas.SetTopMargin(0.10)
  canvas.SetBottomMargin(0.10)
  charsize=0.04
  offset=1.9

  ###latex label
  latex=0
  latex=TLatex(0.6,0.7,'13 TeV, 2.69 fb^{-1}')
  latex.SetTextSize(charsize)
  latex.SetNDC(1)
  latex.SetTextFont(42)

  ###legend setting up
  #legend=TLegend(0.0,0.75,0.99,1.04)
  legend=TLegend(0.4,0.6,0.94,0.95)
  legend.SetNColumns(2)
  legend.SetHeader('')
  legend.SetFillStyle(0)
  legend.SetBorderSize(0)


  ###mc stack
  stack=THStack(name+'_stack','')
  
  qcd_histo=qcd_file.Get(histo).Clone(name+'_make_plot')
  qcd_histo.Rebin(rebin)
  ttbar_histo=ttbar_file.Get(histo).Clone()
  ttbar_histo.Rebin(rebin)
  ttbar_histo.SetFillColor(kRed-9)
  ttbar_histo.SetLineColor(kRed-9)
  ttbar_histo.SetMarkerColor(kRed-9)
  if ttbar_zoom!=1:
    ttbar_histo.Scale(ttbar_zoom)  
  legend.AddEntry(ttbar_histo,ttbar_legend,'f')
  qcd_histo.SetFillColor(kOrange-5)
  qcd_histo.SetLineColor(kOrange-5)
  qcd_histo.SetMarkerColor(kOrange-5)
  if qcd_zoom!=1:
      qcd_histo.Scale(qcd_zoom)
  legend.AddEntry(qcd_histo,qcd_legend,'f')

  sum_mc=qcd_histo.Clone(histo+'tmp')
  sum_mc.Add(ttbar_histo)
  stack.Add(ttbar_histo)
  stack.Add(qcd_histo)
  
  sum_mc.SetLineColor(kBlack)
  sum_mc.SetFillStyle(0)
  err=TGraphAsymmErrors(sum_mc)
  legend.AddEntry(err,'Total uncertainty','f')

  if legendtitle=='':
    legend.AddEntry(0,"",'')
    legend.AddEntry(0,"g_{RS} #rightarrow t#bar{t} (2pb)",'')
  else:
    legend.AddEntry(0,"",'')
    legend.AddEntry(0,legendtitle,'')

  ###signal setting up
  signal_histos=[]
  colors=[kBlack,kRed,kOrange,kBlue,kGreen+3,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60]
  styles=[1,3,5,7,7,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
  if signal_colors!=[]:
    colors=signal_colors
  for i in range(len(signal_files)):
    signal_histos.append(signal_files[i].Get(histo).Clone())
    signal_histos[i].SetLineWidth(3)
    signal_histos[i].SetLineStyle(styles[i])
    signal_histos[i].SetLineColor(colors[i])
    signal_histos[i].SetMarkerColor(colors[i])
    signal_histos[i].Rebin(rebin)
    if signal_zoom!=1:
      signal_histos[i].Scale(signal_zoom)
    legend.AddEntry(signal_histos[i],signal_legend[i],'l')

  ###mc shape line
  ttbar_line=0
  ttbar_line=ttbar_histo.Clone()
  ttbar_line.SetLineColor(kBlack)
  ttbar_line.SetFillStyle(0)

  ###mc errors
  if dosys:
    sys_diff_qcd=[]
    sys_diff_ttbar=[]
    for imtt in range(1,ttbar_histo.GetNbinsX()+1):
      sys_diff_qcd.append([])
      sys_diff_ttbar.append([])

    #adding stat uncertainties <--removed
    # for imtt in range(1,ttbar_histo.GetNbinsX()+1):
    #   sys_diff_ttbar[imtt-1].append(ttbar_histo.GetBinError(imtt))
    #   sys_diff_ttbar[imtt-1].append(-ttbar_histo.GetBinError(imtt))
    #   sys_diff_qcd[imtt-1].append(qcd_histo.GetBinError(imtt))
    #   sys_diff_qcd[imtt-1].append(-qcd_histo.GetBinError(imtt))
    #adding flat uncertainties
    for imtt in range(1,ttbar_histo.GetNbinsX()+1):
      #ttbar
      for i in [2.4,#pdf
                10.0,#mu
                3.0,#xsec
                6.0,#toppt
                1.0,#lumi
                3.5,#jec
                3.0,#jer
                10.0,#btag
                #3.0,#trig
                10.0,#toptag
                3.0]:#pileup
         sys_diff_ttbar[imtt-1].append(i/100.0*ttbar_histo.GetBinContent(imtt))
         sys_diff_ttbar[imtt-1].append(-i/100.0*ttbar_histo.GetBinContent(imtt))
      closureunc=5.0
      # if '1b' in histo:
      #   closureunc=5.0
      # elif '2b' in histo:
      #   closureunc=10.0
      for i in [2.0,#modmass
                closureunc]:#closure
         sys_diff_qcd[imtt-1].append(i/100.0*qcd_histo.GetBinContent(imtt))
         sys_diff_qcd[imtt-1].append(-i/100.0*qcd_histo.GetBinContent(imtt))
      # #3% trigger
      # sys_diff_ttbar[imtt-1].append(0.03*ttbar_histo.GetBinContent(imtt))
      # sys_diff_ttbar[imtt-1].append(-0.03*ttbar_histo.GetBinContent(imtt))
      # #2.7% lumi
      # sys_diff_ttbar[imtt-1].append(0.023*ttbar_histo.GetBinContent(imtt))
      # sys_diff_ttbar[imtt-1].append(-0.023*ttbar_histo.GetBinContent(imtt))
      # #15% ttbar
      # #sys_diff_ttbar[imtt-1].append(0.15*ttbar_histo.GetBinContent(imtt))
      # #sys_diff_ttbar[imtt-1].append(-0.15*ttbar_histo.GetBinContent(imtt))
      # #2.8% QCD
      # sys_diff_qcd[imtt-1].append(0.028*qcd_histo.GetBinContent(imtt))
      # sys_diff_qcd[imtt-1].append(-0.028*qcd_histo.GetBinContent(imtt))
    #combining uncertainties
    sys_tot_ttbar=[]
    sys_tot_qcd=[]
    sys_tot=[]
    sys_global_ttbar=[0.0,0.0]
    sys_global_qcd=[0.0,0.0]
    nevt_global=[0.0,0.0,0.0]
    for imtt in range(1,ttbar_histo.GetNbinsX()+1):
      uperr_qcd=0
      downerr_qcd=0
      uperr_ttbar=0
      downerr_ttbar=0
      for error in sys_diff_ttbar[imtt-1]:
        if error<0:
          downerr_ttbar=downerr_ttbar+error*error
        else:
          uperr_ttbar=uperr_ttbar+error*error
      for error in sys_diff_qcd[imtt-1]:
        if error<0:
          downerr_qcd=downerr_qcd+error*error
        else:
          uperr_qcd=uperr_qcd+error*error
      sys_tot_ttbar.append([math.sqrt(downerr_ttbar),math.sqrt(uperr_ttbar)])
      sys_tot_qcd.append([math.sqrt(downerr_qcd),math.sqrt(uperr_qcd)])
      sys_tot.append([math.sqrt(downerr_qcd+downerr_ttbar),math.sqrt(uperr_qcd+uperr_ttbar)])
      sys_global_qcd[0]=sys_global_qcd[0]+downerr_qcd
      sys_global_qcd[1]=sys_global_qcd[1]+uperr_qcd
      sys_global_ttbar[0]=sys_global_ttbar[0]+downerr_ttbar
      sys_global_ttbar[1]=sys_global_ttbar[1]+uperr_ttbar
      # nevt_global[0]=nevt_global[0]+data_histo.GetBinContent(imtt)
      nevt_global[1]=nevt_global[1]+qcd_histo.GetBinContent(imtt)
      nevt_global[2]=nevt_global[2]+ttbar_histo.GetBinContent(imtt)
      #print 'ttbar+qcd',math.sqrt(uperr_qcd+uperr_ttbar),math.sqrt(downerr_qcd+downerr_ttbar)
      #print 'qcd',math.sqrt(uperr_qcd),math.sqrt(downerr_qcd)
      #print 'ttbar',math.sqrt(uperr_ttbar),math.sqrt(downerr_ttbar)
      err.SetPointEYhigh(imtt-1,math.sqrt(uperr_qcd+uperr_ttbar))
      err.SetPointEYlow(imtt-1,math.sqrt(downerr_qcd+downerr_ttbar))
    sys_global=[0.0,0.0]
    sys_global[0]=math.sqrt(sys_global_qcd[0]+sys_global_ttbar[0])
    sys_global[1]=math.sqrt(sys_global_qcd[1]+sys_global_ttbar[1])
    sys_global_qcd[0]=math.sqrt(sys_global_qcd[0])
    sys_global_qcd[1]=math.sqrt(sys_global_qcd[1])
    sys_global_ttbar[0]=math.sqrt(sys_global_ttbar[0])
    sys_global_ttbar[1]=math.sqrt(sys_global_ttbar[1])
    # print name
    # print "\hline"
    # print "Multijet QCD & $%.0f^{+%.0f}_{-%.0f}$ \\\\" % (nevt_global[1],sys_global_qcd[1],sys_global_qcd[0])
    # print "SM ttbar & $%.0f^{+%.0f}_{-%.0f}$ \\\\" % (nevt_global[2],sys_global_ttbar[1],sys_global_ttbar[0])
    # print "\hline"
    # print "Total background & $%.0f^{+%.0f}_{-%.0f}$ \\\\" % (nevt_global[1]+nevt_global[2],sys_global[1],sys_global[0])
    # print 'DATA & %.0f' %nevt_global[0]


  err.SetFillStyle(3145)
  err.SetFillColor(kGray+1)

  ###drawing top
  canvas.cd()
  stack.Draw('hist')
  stack.GetXaxis().SetTitle(ttbar_histo.GetXaxis().GetTitle())
  stack.GetYaxis().SetTitle(ttbar_histo.GetYaxis().GetTitle())
  stack.GetXaxis().SetLabelSize(charsize)
  stack.GetXaxis().SetTitleSize(charsize)
  stack.GetYaxis().SetLabelSize(charsize)
  stack.GetYaxis().SetTitleSize(charsize)
  stack.GetYaxis().SetTitleOffset(offset)
  if minx!=0 or maxx!=0:
    stack.GetXaxis().SetRangeUser(minx,maxx)
  #else:
  #  stack.GetXaxis().SetRangeUser(0,4000)
  if miny!=0 or maxy!=0:
    stack.SetMaximum(maxy)
    stack.SetMinimum(miny)
  else:
    if logy:
      stack.SetMaximum(stack.GetMaximum()*10)
      stack.SetMinimum(0.2)
    else:
      stack.SetMaximum(stack.GetMaximum()*2.0)
      stack.SetMinimum(0.001)
  err.Draw('2')
  sum_mc.Draw('samehist')
  if ttbar_file!=0:
    ttbar_line.Draw('samehist')
  for i in signal_histos:
    i.Draw('samehist')
  if logy:
    canvas.SetLogy()
  legend.Draw()

  latex2text=''
  if   'ldy_0b' in name:
    latex2text='#Deltay < 1; 0 b tag'
  elif 'ldy_1b' in name:
    latex2text='#Deltay < 1; 1 b tag'
  elif 'ldy_2b' in name:
    latex2text='#Deltay < 1; 2 b tag'
  elif 'hdy_0b' in name:
    latex2text='#Deltay > 1; 0 b tag'
  elif 'hdy_1b' in name:
    latex2text='#Deltay > 1; 1 b tag'
  elif 'hdy_2b' in name:
    latex2text='#Deltay > 1; 2 b tag'
  latex2=TLatex(0.19,0.7,latex2text)
  latex2.SetTextSize(0.03)
  latex2.SetNDC(1)
  latex2.SetTextFont(42)
  latex2.Draw()

  if docms:
    if '3000' in name:
       CMS_lumi.CMS_lumi(canvas, 3, 11)
    elif '1000' in name:
       CMS_lumi.CMS_lumi(canvas, 2, 11)
    elif '300' in name:
       CMS_lumi.CMS_lumi(canvas, 1, 11)
    elif '36' in name:
       CMS_lumi.CMS_lumi(canvas, 0, 11)

  ###saving
  canvas.SaveAs('pdf/'+name+'.pdf')
  if outfile!=0:
      canvas.Write()