Ejemplo n.º 1
0
def drawHists(upHist,downHist,i,j,k):
    upHist.Draw('HIST')
    upHist.GetXaxis().SetTitle('m_{#tilde{g}} [TeV]')
    upHist.GetYaxis().SetTitle('% uncertainty')
    upHist.SetFillColor(ROOT.kBlue-10)
    upHist.SetLineColor(ROOT.kBlue)
    if upHist.GetMaximum() < 5:
        upHist.SetMaximum(5)
        upHist.SetMinimum(0)
    elif upHist.GetMaximum() < 10:
        upHist.SetMaximum(10)
        upHist.SetMinimum(0)
    else:
        mx = upHist.GetMaximum()
        upHist.SetMaximum(1.1*mx)
        upHist.SetMinimum(0)
        
    gridLine = ROOT.TLine()
    gridLine.SetLineColor(ROOT.kBlack)
    gridLine.DrawLine(0.850,0,1.850,0)

    ROOT.ATLASLabel(0.525,0.88,'Simulation Internal')
    lat = ROOT.TLatex()

    lat.DrawLatexNDC(0.5,0.8,'PDF Uncertainty (%)')
    lat.DrawLatexNDC(0.2,0.88,srNames[i])
    lat.DrawLatexNDC(0.2,0.8,mjCutNames[j])
Ejemplo n.º 2
0
def plotCR(lumi, path, region, var, indir, debug):
    if debug: print "opening output file"
    o = ROOT.TFile("test.root", "RECREATE")
    if debug: print "Getting MC list"
    BGhist_list = GetBGHists(GetRootFiles(indir, debug), path, debug)
    if debug: print "Getting data hist"
    m_data = GetDataHists(GetRootFiles(indir, debug), path, debug)
    myRange = m_data.GetNbinsX()
    if debug: print "Making MC hist stack"
    m_hstack = MakeHistStack(BGhist_list, lumi, debug)
    m_hsum = SumMCHists(BGhist_list, lumi, debug)
    m_ratio = MakeNewRatio(m_data, m_hsum, debug)
    m_legend = MakeLegend(BGhist_list, m_data, region)

    canvas, p1, p2 = SetRatioCanvas('CR', region, var)
    p2.cd()
    m_ratio.Draw("P")
    p1.cd()
    m_hstack.Draw("HIST")
    m_data.Draw("PESAME")
    o.cd()
    m_hstack.Write()
    canvas.Write()
    canvas.cd()
    m_legend.Draw()
    ROOT.gStyle.SetLegendBorderSize(0)
    ROOT.gROOT.ForceStyle()
    #ROOT.myText(       0.41,  0.85, 1, "2.5fb^{-1}@ #sqrt{s}= 13 TeV")
    #ROOT.myText(       0.41,  0.80, 1, "data16PeriodK")
    #ROOT.myText(       0.41,  0.85, 1, "%s" % region)
    ROOT.ATLASLabel(0.41, 0.90, "Internal")
    #raw_input("-->")
    canvas.Print('%s_CR_%s.pdf' % (region, var))
    canvas.Close()
    return True
Ejemplo n.º 3
0
def drawHists(upHist,downHist,i,j,k=-1):
    ROOT.gStyle.SetPaintTextFormat('1.1f')
    upHist.Draw('TEXT')
    upHist.GetXaxis().SetTickLength(0)
    upHist.GetXaxis().SetTitle('m_{#tilde{g}} [TeV]')
    upHist.GetYaxis().SetTitle('m_{#tilde{#chi}} [GeV]')
    upHist.GetYaxis().SetTickLength(0)
    upHist.GetYaxis().SetLabelOffset(99)
    upHist.GetXaxis().SetLabelOffset(99)
    upHist.SetMarkerSize(0.8)
    t=ROOT.TText()
    t.SetTextAngle(0)
    t.SetTextSize(0.05)
    t.SetTextAlign(33)

    gridLine = ROOT.TLine()
    gridLine.SetLineStyle(2)
    gridLine.SetLineColor(ROOT.kGray)

    for xLab in range(1000,2000,100):
        t.DrawText(xLab+25,-115,str(xLab/1000.))
    for yLab in range(50,2000,200):
        t.DrawText(965,(yLab+50),str(yLab))

    ROOT.ATLASLabel(0.2,0.88,'Simulation Internal')
    lat = ROOT.TLatex()

    lat.DrawLatexNDC(0.2,0.8,'PDF Uncertainty (%)')
    lat.DrawLatexNDC(0.175,0.72,srNames[i])
    lat.DrawLatexNDC(0.175,0.65,mjCutNames[j])
Ejemplo n.º 4
0
def drawHists(upHist,downHist,i,j,k):
    ROOT.gStyle.SetPaintTextFormat('+1.1f')
    upHist.Draw('TEXT')
    upHist.GetXaxis().SetTickLength(0)
    upHist.GetXaxis().SetTitle('m_{#tilde{g}} [TeV]')
    upHist.GetYaxis().SetTitle('m_{#tilde{#chi}} [GeV]')
    upHist.GetYaxis().SetTickLength(0)
    upHist.GetYaxis().SetLabelOffset(99)
    upHist.GetXaxis().SetLabelOffset(99)
    upHist.SetMarkerSize(1.5)
    t=ROOT.TText()
    t.SetTextAngle(0)
    t.SetTextSize(0.05)
    t.SetTextAlign(33)

    gridLine = ROOT.TLine()
    gridLine.SetLineStyle(2)
    gridLine.SetLineColor(ROOT.kGray)
    #vertical lines
    for xi in range(650,1950,100):
        if k >= -1:
            gridLine.DrawLine(xi,-200,xi,1800)
        elif xi > 650:
            gridLine.DrawLine(xi,-50,xi,1750)
    for yi in range(-50,1850,200):
        if k >= -1:
            gridLine.DrawLine(550,yi,1950,yi)
        elif  yi > -50 and yi < 1600:
            gridLine.DrawLine(650,yi,1950,yi)
    for xLab in range(700,2000,100):
        if k >= -1:
            t.DrawText(xLab+50,-215,str(xLab/1000.))
        else:
            t.DrawText(xLab+50,-65,str(xLab/1000.))
    for yLab in range(50,1700,200):
        if k >=-1:
            t.DrawText(535,(yLab+50),str(yLab))
        else:
            t.DrawText(635,(yLab+50),str(yLab))
    if downHist:
        downHist.SetMarkerSize(1.5)
        downHist.Draw('TEXT SAME')

    ROOT.ATLASLabel(0.2,0.88,'Simulation Internal')
    lat = ROOT.TLatex()
    if k>=0:
        lat.DrawLatexNDC(0.2,0.8,systDict[systList[k]])
    elif k==-1:
        lat.DrawLatexNDC(0.2,0.8,'AkT10 Total JMS Uncertainty (%)')
    elif k==-2:
        ROOT.gStyle.SetPaintTextFormat('1.1f')
        lat.DrawLatexNDC(0.2,0.8,'MC Statistical Uncertainty (%)')
    elif k==-3:
        ROOT.gStyle.SetPaintTextFormat('1.1f')
        lat.DrawLatexNDC(0.2,0.8,'Selection efficiency (%)')
    lat.DrawLatexNDC(0.2,0.72,srNames[i])
    lat.DrawLatexNDC(0.2,0.65,mjCutNames[j])
Ejemplo n.º 5
0
def drawHists(upHist, downHist, i, j, k):
    upHist.Draw('HIST')
    upHist.GetXaxis().SetTitle('m_{#tilde{g}} [TeV]')
    if k >= -2:
        upHist.GetYaxis().SetTitle('% uncertainty')
    elif k == -3:
        upHist.GetYaxis().SetTitle('selectione efficiency (%)')
    upHist.SetFillColor(ROOT.kBlue - 10)
    upHist.SetLineColor(ROOT.kBlue)
    if upHist.GetMaximum() < 15:
        upHist.SetMaximum(15)
        upHist.SetMinimum(0)
        if downHist:
            upHist.SetMinimum(-15)
    elif upHist.GetMaximum() < 20:
        upHist.SetMaximum(20)
        upHist.SetMinimum(0)
        if downHist:
            upHist.SetMinimum(-20)
    else:
        mx = upHist.GetMaximum()
        upHist.SetMaximum(1.1 * mx)
        upHist.SetMinimum(0)
        if downHist:
            upHist.SetMinimum(-1.1 * mx)

    if downHist:
        downHist.SetMarkerSize(1.5)
        downHist.Draw('HIST SAME')
        downHist.Draw('SAME AXIS')
        downHist.SetFillColorAlpha(ROOT.kRed - 10, 1.0)
        downHist.SetLineColor(ROOT.kRed)

    gridLine = ROOT.TLine()
    gridLine.SetLineColor(ROOT.kBlack)
    gridLine.DrawLine(0.850, 0, 1.850, 0)

    ROOT.ATLASLabel(0.525, 0.88, 'Simulation Internal')
    lat = ROOT.TLatex()
    if k >= 0:
        lat.DrawLatexNDC(0.525, 0.8, systDict[systList[k]])
        lat.DrawLatexNDC(0.7, 0.72, srNames[i])
        lat.DrawLatexNDC(0.7, 0.65, mjCutNames[j])
    elif k == -1:
        lat.DrawLatexNDC(0.2, 0.8, 'AkT10 Total JMS Uncertainty (%)')
        lat.DrawLatexNDC(0.7, 0.72, srNames[i])
        lat.DrawLatexNDC(0.7, 0.65, mjCutNames[j])
    elif k == -2:
        ROOT.gStyle.SetPaintTextFormat('1.1f')
        lat.DrawLatexNDC(0.2, 0.8, 'MC Statistical Uncertainty (%)')
        lat.DrawLatexNDC(0.2, 0.72, srNames[i])
        lat.DrawLatexNDC(0.2, 0.65, mjCutNames[j])
    elif k == -3:
        ROOT.gStyle.SetPaintTextFormat('1.1f')
        lat.DrawLatexNDC(0.2, 0.8, 'Selection efficiency (%)')
        lat.DrawLatexNDC(0.2, 0.72, srNames[i])
        lat.DrawLatexNDC(0.2, 0.65, mjCutNames[j])
Ejemplo n.º 6
0
def plotHistograms(h_map,
                   save_name,
                   xlabel="",
                   ylabel="",
                   interactive=False,
                   logy=False,
                   atltext=""):

    can = ROOT.TCanvas("can", "can")
    h_keys = h_map.keys()
    h_values = h_map.values()

    if len(h_keys) < 1:
        print "No histograms found in h_map. Drawing blank canvas."
        return

    # Get maxes/mins of all hists
    maxy = 1.5 * getMaximum(h_values)
    miny = 0
    if logy:
        maxy *= 1e4
        miny = 1e-1

    # Draw histograms
    colorHists(h_values)
    h_map[h_keys[0]].GetXaxis().SetTitle(xlabel)
    h_map[h_keys[0]].GetYaxis().SetTitle(ylabel)
    h_values[0].SetMinimum(miny)
    h_values[0].SetMaximum(maxy)
    h_map[h_keys[0]].Draw("hist")
    if logy: ROOT.gPad.SetLogy(1)
    for k in h_keys[1:]:
        h_map[k].Draw("hist same")

    leg = ROOT.TLegend(.66, .64, .8, .88)
    for k in h_keys:
        leg.AddEntry(h_map[k], k, "l")
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.Draw()
    if interactive: raw_input("...")

    if atltext != "":
        ROOT.ATLASLabel(0.2, 0.85, atltext[0])
        text = ROOT.TLatex()
        text.SetNDC()
        text.SetTextSize(0.04)
        for i, t in enumerate(atltext[1:]):
            text.DrawLatex(0.2, 0.85 - 0.07 * (i + 1), t)

    can.SaveAs(save_name)
    return
Ejemplo n.º 7
0
def drawHists(upHist, downHist, i, j, k):
    ROOT.gStyle.SetPaintTextFormat('1.2f')
    upHist.Draw('TEXT')
    upHist.GetXaxis().SetTickLength(0)
    upHist.GetXaxis().SetTitle('m_{#tilde{g}} [TeV]')
    upHist.GetYaxis().SetTitle('m_{#tilde{#chi}} [GeV]')
    upHist.GetYaxis().SetTickLength(0)
    upHist.GetYaxis().SetLabelOffset(99)
    upHist.GetXaxis().SetLabelOffset(99)
    upHist.SetMarkerSize(1.5)
    t = ROOT.TText()
    t.SetTextAngle(0)
    t.SetTextSize(0.05)
    t.SetTextAlign(33)

    gridLine = ROOT.TLine()
    gridLine.SetLineStyle(2)
    gridLine.SetLineColor(ROOT.kGray)
    #vertical lines
    for xi in range(650, 1950, 100):
        if xi > 650:
            gridLine.DrawLine(xi, -50, xi, 1750)
    for yi in range(-50, 1850, 200):
        if yi > -50 and yi < 1600:
            gridLine.DrawLine(650, yi, 1950, yi)
    for xLab in range(700, 2000, 100):
        t.DrawText(xLab + 50, -65, str(xLab / 1000.))
    for yLab in range(50, 1700, 200):
        t.DrawText(635, (yLab + 50), str(yLab))
    if downHist:
        downHist.SetMarkerSize(1.5)
        downHist.Draw('TEXT SAME')
    ROOT.ATLASLabel(0.2, 0.88, 'Simulation Internal')
    lat = ROOT.TLatex()
    lat.DrawLatexNDC(0.2, 0.8, 'A^{reco}_{new}/A^{reco}_{old}')
    lat.DrawLatexNDC(0.2, 0.72, '#bf{' + srNames[i] + '}')
    lat.DrawLatexNDC(0.2, 0.65, mjCutNames[j])
Ejemplo n.º 8
0
                uncertTruth = math.sqrt(eTruth * (1 - eTruth) / 100000.)
                uncertTotal = (uncertReco * uncertReco) / (effReco * effReco)
                uncertTotal += (uncertTruth * uncertTruth) / (effTruth *
                                                              effTruth)
                uncertTotal *= (effReco * effReco) / (effTruth * effTruth)
                uncertTotal = math.sqrt(uncertTotal)
                mG = key
                effHists[-1].Fill(mG / 1000., effReco / effTruth)
                bin = effHists[-1].FindBin(mG / 1000.)
#                effHists[-1].SetBinError(bin,uncertTotal)

        effHists[-1].SetLineColor(ROOT.kBlue)
        effHists[-1].SetFillColor(ROOT.kBlue - 10)
        effHists[-1].Draw('hist')
        effHists[-1].GetYaxis().SetTitle('A^{reco}_{new}/A^{reco}_{old}')
        effHists[-1].GetYaxis().SetTitleOffset(1.5)
        effHists[-1].GetXaxis().SetTitle('m_{#tilde{g}} [TeV]')
        effHists[-1].SetMinimum(0.5)
        effHists[-1].SetMaximum(1.25)
        lat = ROOT.TLatex()
        lat.DrawLatexNDC(0.2, 0.775,
                         '#bf{' + sr + ' M_{J}^{#Sigma} > ' + mj + '}')
        ROOT.ATLASLabel(0.2, 0.875, 'Simulation Internal')

        fileName = '/global/project/projectdirs/atlas/www/multijet/RPV/btamadio/PreselectionComparison/07_15/preselCompare_RPV6_'
        fileName += srFileNames[j] + '_MJ_' + mj + '_13000'
        print fileName
        can[-1].Print(fileName + '.pdf')
        can[-1].Print(fileName + '.png')
        can[-1].Print(fileName + '.pdf')
Ejemplo n.º 9
0
    if mS == "400":
        x_min, y_min = 0.4, (y_min - 0.5 * tg_2s.GetXaxis().GetTickLength())
    if mS == "150": x_min, y_min = 0.1, y_min
if mH == "400":
    if mS == "100":
        x_min, y_min = 0.05, (y_min - 0.5 * tg_2s.GetXaxis().GetTickLength())

tg_2s.GetXaxis().SetLimits(x_min, x_max)
tg_2s.SetMinimum(y_min)

tg_2s.GetXaxis().SetTitle('s proper decay length [m]')
tg_2s.GetYaxis().SetTitle('95% CL Upper Limit on #sigma #times BR [pb]')

tg_2s.Draw("aC4")
tg_1s.Draw("C4 same ")
tg_Obs.Draw("l same ")
tg_Exp.Draw("l same ")

r.gStyle.SetTextSize(0.05)
r.ATLASLabel(0.5, 0.85, "Work in Progress", 1)
r.gStyle.SetTextSize(0.035)
r.myText(0.5, 0.8, 1,
         "m_{H} = " + args.mH + " GeV, m_{s} = " + args.mS + " GeV")
r.myText(0.5, 0.76, 1, "3.2 fb^{-1}  #it{#sqrt{s}} = 13 TeV")
r.myBoxText(0.5, 0.72, 0.04, r.kYellow, "expected #pm 2#sigma")
r.myBoxText(0.5, 0.68, 0.04, r.kGreen - 4, "expected #pm 1#sigma")
r.myBoxTextDash(0.5, 0.64, 0.04, r.kWhite, r.kBlack, "expected limit", 2)
r.myBoxTextDash(0.5, 0.6, 0.04, r.kWhite, r.kBlack, "observed limit", 1)

canvas.SaveAs(args.plotName)
Ejemplo n.º 10
0
def kinematic_plots_SR(mu, entry, ratio=True, verbose=False):
    rf = ROOT.TFile('~/panalysis/output/prod4/%s_fit/%s_regions.root' %
                    (mu.name, mu.name))
    region = 'SR_OS'

    # scale factors
    k_entry = upsilon_CR
    kW_OS = hist.calc_kX(rf,
                         mu,
                         k_entry,
                         'WCR',
                         'Wlnu',
                         OS='OS',
                         verbose=verbose)
    kW_SS = hist.calc_kX(rf,
                         mu,
                         k_entry,
                         'WCR',
                         'Wlnu',
                         OS='SS',
                         verbose=verbose)
    rQCD = hist.calc_rQCD(rf,
                          mu,
                          k_entry,
                          'QCD',
                          kW_OS=kW_OS,
                          kW_SS=kW_SS,
                          verbose=verbose)
    # left and right handed
    kW_OS_L = hist.calc_kX(rf,
                           mu,
                           k_entry,
                           'WCR',
                           'Wlnu',
                           OS='OS',
                           verbose=verbose,
                           groups=mu.MC + [mu.LH])
    kW_OS_R = hist.calc_kX(rf,
                           mu,
                           k_entry,
                           'WCR',
                           'Wlnu',
                           OS='OS',
                           verbose=verbose,
                           groups=mu.MC + [mu.RH])
    kW_SS_L = hist.calc_kX(rf,
                           mu,
                           k_entry,
                           'WCR',
                           'Wlnu',
                           OS='SS',
                           verbose=verbose,
                           groups=mu.MC + [mu.LH])
    kW_SS_R = hist.calc_kX(rf,
                           mu,
                           k_entry,
                           'WCR',
                           'Wlnu',
                           OS='SS',
                           verbose=verbose,
                           groups=mu.MC + [mu.RH])
    rQCD_L = hist.calc_rQCD(rf,
                            mu,
                            k_entry,
                            'QCD',
                            kW_OS=kW_OS_L,
                            kW_SS=kW_SS_L,
                            verbose=verbose,
                            groups=mu.MC + [mu.LH])
    rQCD_R = hist.calc_rQCD(rf,
                            mu,
                            k_entry,
                            'QCD',
                            kW_OS=kW_OS_R,
                            kW_SS=kW_SS_R,
                            verbose=verbose,
                            groups=mu.MC + [mu.RH])

    rb = entry.rebin

    # Canvas
    if entry.blind: ratio = False
    ratio = False
    cname = '%s_%s_%s' % (mu.name, entry.name, region)
    pname = '%s_%s' % (mu.name, region.rstrip('_OS'))
    if ratio:
        c = ROOT.TCanvas(cname, cname, 1500, 1000)
        #Split for ratio plot
        c.Divide(1, 2)
        c.cd(1).SetPad(0.0, 0.2, 1.0, 1.0)
        c.cd(2).SetPad(0.0, 0.0, 1.0, 0.2)
        c.cd(1)
    else:
        c = ROOT.TCanvas(cname, cname, 1200, 800)

    # Data
    dregion = region
    data = rf.Get('h_%s_%s_%s' % (entry.name, mu.data.name, dregion)).Clone()
    data.SetMarkerStyle(20)
    data.SetMarkerSize(2)
    data.SetLabelSize(0.04, "y")
    data.Rebin(rb)
    if entry.xmax:

        data.SetAxisRange(entry.xmin or 0, entry.xmax)

    # stat. unc. on stack
    stacksum = data.Clone("tmp")
    stacksum.Reset()

    # Legend
    x0 = 0.72
    y0 = 0.5
    step = 0.05

    nl = 4 + len(mu.MC) - 1 * entry.blind
    l = ROOT.TLegend(x0, y0, x0 + .17, y0 + nl * step)
    if entry.leg:
        leg = entry.leg
        l = ROOT.TLegend(leg[0], leg[1], leg[2], leg[3])

    l.SetTextSize(0.035)
    l.SetBorderSize(0)
    l.SetFillColor(0)

    if not entry.blind:
        l.AddEntry(data, 'Data 2012',
                   "P")  # (%.0f)' % data.Integral(0,data.GetNbinsX()+1))

    # Stack
    st = ROOT.THStack(cname, "%s; %s; " % (cname, entry.xtitle))

    # QCD ESTIMATE
    #if region == 'SR_SS': rQCD = ErrorFloat(1.,0.)
    qcd = hist.get_QCD(rf, mu, entry, 'SR_SS', kW=kW_SS, rqcd=rQCD)
    qcd.SetLineWidth(0)
    qcd.SetLineColor(3)
    qcd.SetFillColor(3)
    qcd.SetMarkerStyle(0)
    qcd.SetMarkerColor(3)
    qcd.Rebin(rb)

    # left and right
    lefthand = hist.get_QCD(rf,
                            mu,
                            entry,
                            'SR_SS',
                            kW=kW_SS_L,
                            rqcd=rQCD_L,
                            groups=mu.MC + [mu.LH])
    righthand = hist.get_QCD(rf,
                             mu,
                             entry,
                             'SR_SS',
                             kW=kW_SS_R,
                             rqcd=rQCD_R,
                             groups=mu.MC + [mu.RH])
    lefthand.Rebin(rb)
    righthand.Rebin(rb)
    if not 'SR' in region:
        qcd.Reset()
        lefthand.Reset()
        righthand.Reset()

    if entry.xmax:
        qcd.SetAxisRange(entry.xmin or 0, entry.xmax)
        lefthand.SetAxisRange(entry.xmin or 0, entry.xmax)
        righthand.SetAxisRange(entry.xmin or 0, entry.xmax)

    st.Add(qcd)
    stacksum.Add(qcd)

    if verbose:
        total_est = ErrorFloat(*hist.IntegralError(qcd))
        print 'Data: %.0f +/- %.0f' % (hist.IntegralError(data)[0],
                                       hist.IntegralError(data)[1])
        print 'NQCD: %.0f +/- %.0f' % (hist.IntegralError(qcd)[0],
                                       hist.IntegralError(qcd)[1])

    mc_leg = []
    n_total = ErrorFloat(
        *hist.IntegralError(hist.get_OS(rf, entry, mu.signal, region)))
    groups = mu.MC + [mu.signal]

    for group in groups:
        entry.add_group(group)
        kOS = ErrorFloat(1.0, 0.0)
        kSS = ErrorFloat(1.0, 0.0)
        if group.name == 'Wlnu':
            kOS = kW_OS
            kSS = kW_SS
        if 'SS' not in region:
            h = hist.get_OS(rf, entry, group, region, kOS=kOS)
        else:
            h = hist.get_SS(rf, entry, group, region, kSS=kSS)
        h.Rebin(rb)

        if entry.xmax:
            h.SetAxisRange(entry.xmin or 0, entry.xmax)

        if group.name != mu.signal.name:
            lefthand.Add(h)
            righthand.Add(h)

        h.SetLineColor(entry[group.name]['fill'])
        h.SetLineWidth(0)
        h.SetMarkerStyle(0)
        h.SetMarkerColor(entry[group.name]['fill'])
        h.SetFillColor(entry[group.name]['fill'])
        h.SetLabelSize(0.04, "y")

        st.Add(h)
        stacksum.Add(h)
        mc_leg.append((h, group.legend, hist.IntegralError(h)[0],
                       hist.IntegralError(h)[1]))

        if verbose:
            print '%s: %.0f +/- %.0f' % (group.name, hist.IntegralError(h)[0],
                                         hist.IntegralError(h)[1])
            total_est += ErrorFloat(*hist.IntegralError(h))
            if syst:
                print '%s: %.0f +/- %.0f' % ('up', hist.IntegralError(h_up)[0],
                                             hist.IntegralError(h_up)[1])
                print '%s: %.0f +/- %.0f' % ('down',
                                             hist.IntegralError(h_down)[0],
                                             hist.IntegralError(h_down)[1])
    if verbose:
        print 'Total Estimated: %.0f +/- %.0f' % (total_est.val, total_est.err)

    ## Add left and right
    hLeft = hist.get_OS(rf, entry, mu.LH, region)
    hRight = hist.get_OS(rf, entry, mu.RH, region)
    for h in [hLeft, hRight]:
        h.Rebin(rb)
        h.SetMarkerStyle(0)
        h.SetLineWidth(1)
        if entry.xmax:
            h.SetAxisRange(entry.xmin or 0, entry.xmax)
    lefthand.Add(hLeft)
    righthand.Add(hRight)

    lefthand.SetLineColor(mu.LH.fill)
    righthand.SetLineColor(mu.RH.fill)

    lefthand.SetLineStyle(2)
    righthand.SetLineStyle(2)

    for li in reversed(mc_leg):
        l.AddEntry(li[0], '%s' % (li[1]))
    #l.AddEntry(qcd,'QCD: %.0f +/- %.0f' % (hist.IntegralError(qcd)[0],hist.IntegralError(qcd)[1]))
    if 'SR' in region:
        l.AddEntry(
            qcd, 'Multijet'
        )  #: %.0f +/- %.0f' % (hist.IntegralError(qcd)[0],hist.IntegralError(qcd)[1]))
    l.AddEntry(lefthand, 'Left-Handed', "L")
    l.AddEntry(righthand, 'Right-Handed', "L")

    data.SetXTitle(entry.xtitle)
    data.GetXaxis().SetTitleOffset(1.25)

    stacksum.SetFillStyle(3354)
    stacksum.SetLineColor(1)
    stacksum.SetFillColor(12)
    stacksum.SetMarkerStyle(1)

    maxi = max(data.GetMaximum(), st.GetMaximum())
    mini = 0.
    data.SetMinimum(1.2 * mini)
    data.SetMaximum(1.4 * maxi)

    bw = data.GetXaxis().GetBinWidth(1)

    data.GetYaxis().SetTitle('Events / %s %s' % (bw, entry.units))

    if not entry.blind:
        data.Draw("PE")
        st.Draw("HIST,SAME")
        stacksum.Draw("E2,SAME")
        data.Draw("SAME, PE")
    else:
        data.Reset()
        data.Draw()
        st.SetTitle('')

        st.SetMinimum(1.2 * st.GetMinimum())
        st.SetMaximum(1.5 * st.GetMaximum())
        st.Draw("HIST,SAME")
        stacksum.Draw("E2,SAME")

    lefthand.Draw("HIST,SAME")
    righthand.Draw("HIST,SAME")
    data.Draw("SAME,PE")

    ROOT.gPad.RedrawAxis()
    l.Draw()

    atlas = ROOT.ATLASLabel(0.3, 0.87, "   Work in Progress")
    #td = ROOT.TPaveText(0.3,0.75,0.7,0.85,"NDC")
    if 'SR' in region:
        td = ROOT.TPaveText(0.52, 0.68, 0.65, 0.85, "NDC")
    else:
        td = ROOT.TPaveText(0.19, 0.68, 0.32, 0.85, "NDC")
    td.SetTextAlign(13)
    td.SetBorderSize(0)
    td.SetFillColor(0)
    td.SetTextSize(0.04)

    #td.AddText('#sqrt{s} = 8 TeV    #int Ldt = 20.3 fb^{-1}')
    #td.AddText('#sqrt{s} = 8 TeV')
    #td.AddText('#int Ldt = 20.3 fb^{-1}')
    td.Draw()
    # channel
    tm = ROOT.TPaveText(0.19, 0.85, 0.22, 0.92, "NDC")
    tm.SetBorderSize(0)
    tm.SetFillColor(0)
    tm.SetTextSize(0.05)
    if mu.name == 'mu':
        tm.AddText('#mu#tau_{had}')
    elif mu.name == 'el':
        tm.AddText('e#tau_{had}')
    tm.Draw()

    #atlas.Draw()

    if ratio:
        c.cd(2)
        ROOT.gPad.SetTopMargin(0)
        dataratio = data.Clone('ratio')
        if entry.xmax:
            dataratio.SetAxisRange(0, entry.xmax)
        dataratio.GetYaxis().SetTitle('Data / MC')
        dataratio.GetYaxis().SetTitleOffset(0.25)
        dataratio.GetYaxis().SetTitleSize(0.16)
        dataratio.SetLabelSize(.1, "y")
        dataratio.Divide(stacksum)
        dataratio.SetMaximum(1.5)
        dataratio.SetMinimum(0.5)

        err = stacksum.Clone('err')
        err.Divide(err)
        err.SetFillStyle(3354)
        err.SetLineColor(1)
        err.SetFillColor(12)
        err.SetMarkerStyle(1)
        xmin = dataratio.GetXaxis().GetXmin()
        xmax = entry.xmax or dataratio.GetXaxis().GetXmax()
        cl = ROOT.TLine(xmin, 1, xmax, 1)
        cl.SetLineStyle(3)
        dataratio.GetXaxis().SetLabelSize(0.04)
        dataratio.Draw('PE')
        cl.Draw("SAME")
        err.Draw("SAME,E2")
        c.Update()

    c.Update()
    c.Print('../plots/ttbar/%s.eps' % (cname))
Ejemplo n.º 11
0
def make_graph(data, xlabel, legend_label, legend_header, bin_labels, filename,
               args, min_ratio, max_ratio):
    canvas_name, _, _ = filename.partition(".")
    canvas = ROOT.TCanvas(canvas_name, canvas_name, 800, 600)
    outer_count = 0

    hists = collections.OrderedDict()

    ROOT.gStyle.SetPalette(eval(args.style))

    data["Combined"] = collections.OrderedDict()

    if args.invert:
        min_ratio = -0.3
        max_ratio = 1.25

    # At every iteration make a new histogram.
    for name, dataset in six.iteritems(data):
        hist_name = "hist_" + canvas_name + "_" + str(name)
        hist = ROOT.TH1F(hist_name, hist_name, len(dataset), 0, len(dataset))
        count = 1

        # Now loop through the actual dataset.
        for bin_name, (low, high) in six.iteritems(dataset):
            hist.GetXaxis().SetBinLabel(count, bin_labels[bin_name])

            # Compute ratio. Or not!
            if args.var == "low":
                ratio = low.n
                ratio_error = low.s
            elif args.var == "high":
                ratio = high.n
                ratio_error = high.s
            else:
                ratio, ratio_error = calculate_ratio(low,
                                                     high,
                                                     binomial=args.binomial,
                                                     invert=args.invert)

            hist.SetBinContent(count, ratio)
            hist.SetBinError(count, ratio_error)

            if name != "Combined":
                if bin_name not in data["Combined"]:
                    data["Combined"][bin_name] = (low, high)
                else:
                    cur_low, cur_high = data["Combined"][bin_name]
                    data["Combined"][bin_name] = (low + cur_low,
                                                  high + cur_high)

            if name == "Combined":
                print("Ratio (%s) = %f /- %f" %
                      (str(bin_name), ratio, ratio_error))

            count += 1

            if not args.invert:
                max_ratio = math.ceil(max(max_ratio, ratio))

            if not args.invert:
                min_ratio = math.floor(min(min_ratio, ratio))

        # this is, uh, a hack.
        for _, oldhist in six.iteritems(hists):
            oldhist.GetYaxis().SetRangeUser(min_ratio, max_ratio * 1.05)

        canvas.cd()
        draw_opts = "pe0 plc pmc"
        if outer_count != 0:
            draw_opts += " same"

        hist.Draw(draw_opts)

        # Set the marker.
        # For the combined: use the circle, make it a bit bigger.
        # Otherwise: use a different marker for each set.
        if name == "Combined":
            hist.SetMarkerSize(1.5)
        elif outer_count < len(markers):
            hist.SetMarkerStyle(markers[outer_count])
            if markers[outer_count] == ROOT.kFullDiamond:
                hist.SetMarkerSize(1.3)

        varname = args.var
        if not args.invert:
            varname = "inv" + varname

        offset = 0.05 * hist.GetBinWidth(1) * outer_count
        hist.GetXaxis().SetLimits(-2 + offset, 2 + offset)
        hist.GetXaxis().SetNdivisions(len(dataset), 0, 0, False)
        hist.GetXaxis().SetTitle(xlabel)
        hist.GetYaxis().SetTitle(yaxis_labels[varname])
        hist.GetXaxis().SetLabelSize(0.048)

        hist.GetYaxis().SetRangeUser(min_ratio, max_ratio)

        outer_count += 1

        canvas.Update()
        hists[name] = hist

    xcoord = 0.70

    xcoord2 = 0.90
    if args.invert and len(dataset) > 3:
        xcoord2 -= 0.50
        xcoord -= 0.50

    legend = ROOT.TLegend(xcoord - 0.01, 0.78 - .05 * len(hists), xcoord2,
                          0.87)
    legend.SetBorderSize(0)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    # I _really_ don't understand ROOT font sizes!
    legend.SetTextSize(0.04)
    legend.SetTextFont(42)
    legend.SetHeader(legend_header)

    label_coord = xcoord - 0.01
    if not args.invert:
        label_coord -= 0.04
    label = ROOT.ATLASLabel(label_coord, 0.88, "Internal")

    for name, hist in six.iteritems(hists):
        if name == "Combined":
            legend.AddEntry(hist, "Combined")
        elif type(name) == str and "ep" in name:
            legend.AddEntry(hist, "W #rightarrow e^{+} #nu")
        elif type(name) == str and "em" in name:
            legend.AddEntry(hist, "W #rightarrow e^{-} #nu")
        elif type(name) == str and "low" in name:
            legend.AddEntry(hist, "p_{T}(e) < 150 GeV")
        elif type(name) == str and "high" in name:
            legend.AddEntry(hist, "p_{T}(e) > 150 Gev")
        else:
            legend_name = str(int(name))
            if legend_name == '2016':
                legend_name = '2015+2016'
            legend.AddEntry(hist, legend_label + legend_name)

    legend.Draw()

    canvas.Update()
    if args.wait:
        six.moves.input()
    canvas.SaveAs(filename)
    canvas.SaveAs(filename.replace("eps", "C"))
Ejemplo n.º 12
0
def makeRatioPlot(h1,
                  h2,
                  xname,
                  savename="",
                  logy=False,
                  ytitle="",
                  doEfficiency=False,
                  h11="",
                  rmin=0.5,
                  rmax=1.5):

    ROOT.gStyle.SetErrorX(0.5)
    c = ROOT.TCanvas("c_" + savename, "c_" + savename, 600, 450)

    if ytitle == "":
        ytitle = "ratio"
        if doEfficiency: ytitle = "efficiency"

    # Upper plot will be in pad1
    pad1 = ROOT.TPad("pad1_" + savename, "pad1_" + savename, 0, 0.3, 1, 1.0)
    pad1.SetBottomMargin(0)  # Upper and lower plot are joined
    #pad1.SetGridx()         # Vertical grid
    #pad1.SetGridy()         # horizontal grid
    pad1.Draw()  # Draw the upper pad: pad1
    pad1.cd()  # pad1 becomes the current pad
    h2.SetStats(0)  # No statistics on upper plot
    maxy = 1.4 * getMaximum([h1, h2])
    #if h11!="": maxy = 1.4*getMaximum([h1,h2,h11])
    if h11 != "": maxy = getMaximum([h1, h2, h11])
    if logy:
        maxy = 100 * maxy
        pad1.SetLogy()
    h2.SetMaximum(maxy)
    h2.SetMinimum(0)
    if logy: h2.SetMinimum(0.01)
    h2.Draw("hist")
    h1.Draw("hist e same")  # Draw h1
    if h11 != "":
        h11.SetLineStyle(2)
        h11.Draw("hist e same")  # Draw h11

    #shows the error on h2
    h2_copy = h2.Clone("h2_copy" + savename)
    h2_copy.SetDirectory(0)
    h2_copy.SetFillStyle(3004)
    h2_copy.SetFillColor(ROOT.kBlack)
    h2_copy.SetMarkerSize(0)
    h2_copy.Draw("e2 same")

    # Do not draw the Y axis label on the upper plot and redraw a small
    # axis instead, in order to avoid the first label (0) to be clipped.
    h2.GetYaxis().SetLabelSize(0.)
    if logy:
        axis = ROOT.TGaxis(h1.GetXaxis().GetXmin(), 1,
                           h1.GetXaxis().GetXmin(), maxy, 1, maxy, 510, "G")
    else:
        #axis = ROOT.TGaxis( h1.GetXaxis().GetXmin(), 1, h1.GetXaxis().GetXmin(), maxy, 1, maxy,510)
        axis = ROOT.TGaxis(h1.GetXaxis().GetXmin(), 0.001 * maxy,
                           h1.GetXaxis().GetXmin(), maxy, 0.001 * maxy, maxy,
                           510)
    axis.SetLabelFont(43)  # Absolute font size in pixel (precision 3)
    axis.SetLabelSize(17)

    # lower plot will be in pad
    c.cd()  # Go back to the main canvas before defining pad2
    pad2 = ROOT.TPad("pad2_" + savename, "pad2_" + savename, 0, 0.05, 1, 0.3)
    pad2.SetLogy(0)
    pad2.SetTopMargin(0)
    pad2.SetBottomMargin(0.4)
    pad2.SetGridx()  # vertical grid
    pad2.SetGridy()  # horizontal grid
    pad2.Draw()
    pad2.cd()  # pad2 becomes the current pad

    # Define the ratio plot
    h3 = h1.Clone("h3_" + savename)
    h3.SetDirectory(0)
    h3.SetLineColor(ROOT.kBlack)
    h3.SetStats(0)  # No statistics on lower plot
    #h3.Divide(h3, h2,1, 1,"B")
    h3.Divide(h3, h2)

    if h11 != "":
        h33 = h11.Clone("h33_" + savename)
        h33.SetDirectory(0)
        h33.SetLineColor(ROOT.kBlack)
        #h33.Divide(h33, h2,1, 1,"B")
        h33.Divide(h33, h2)

    #Errors on ratio
    h4 = h2.Clone("h4_" + savename)  # Make hist with error for h2
    h4.SetDirectory(0)
    for x in xrange(h4.GetNbinsX()):
        if h2.GetBinContent(x + 1) != 0:
            h3.SetBinError(x + 1,
                           h1.GetBinError(x + 1) / h2.GetBinContent(x + 1))
        if h11 != "" and h2.GetBinContent(x + 1) != 0:
            h33.SetBinError(x + 1,
                            h11.GetBinError(x + 1) / h2.GetBinContent(x + 1))
        if h2.GetBinContent(x + 1) != 0:
            h4.SetBinError(x + 1,
                           h2.GetBinError(x + 1) / h2.GetBinContent(x + 1))
        h4.SetBinContent(x + 1, 1)

    if h3.GetBinContent(h3.GetMinimumBin()) > 0:
        rmin = min(rmin, .95 * h3.GetBinContent(h3.GetMinimumBin()))
    if h4.GetBinContent(h4.GetMinimumBin()) > 0:
        rmin = min(rmin, .95 * h4.GetBinContent(h4.GetMinimumBin()))
    if h11 != "":
        if h33.GetBinContent(h33.GetMinimumBin()) > 0:
            rmin = min(rmin, .95 * h33.GetBinContent(h33.GetMinimumBin()))
    #if rmin>0.5: rmin=0.5
    rmax = max(rmax, 1.05 * h3.GetBinContent(h3.GetMaximumBin()),
               1.05 * h4.GetBinContent(h4.GetMaximumBin()))
    if h11 != "":
        rmax = max(rmax, 1.05 * h3.GetBinContent(h3.GetMaximumBin()),
                   1.05 * h4.GetBinContent(h4.GetMaximumBin()),
                   1.05 * h33.GetBinContent(h33.GetMaximumBin()))
    #if rmax<1.5: rmax=1.5

    if doEfficiency:
        rmax = 1.1
        rmin = 0.01

    h3.SetMinimum(rmin)  # Define Y ..
    h3.SetMaximum(rmax)  # .. range

    h3.Draw("hist e")
    if h11 != "": h33.Draw("hist e same")
    h4.Draw("e2 same")

    # h1 settings
    h1.SetLineColor(ROOT.kBlack)
    h1.SetLineWidth(2)
    h1.SetMarkerSize(0)
    if h11 != "":
        h11.SetLineColor(ROOT.kBlack)
        h11.SetLineWidth(2)
        h11.SetMarkerSize(0)

    # Y axis h1 plot settings
    h1.GetYaxis().SetTitleSize(20)
    h1.GetYaxis().SetTitleFont(43)
    h1.GetYaxis().SetTitleOffset(1.55)

    # h2 settings
    h2.SetLineColor(theme_colors2[2])
    h2.SetFillColor(theme_colors2[2])
    #h2.SetLineColor(ROOT.kTeal-9)
    #h2.SetFillColor(ROOT.kTeal-9)
    h2.SetMarkerSize(0)
    h2.SetLineWidth(2)

    # Ratio plot (h3) settings
    h3.GetXaxis().SetTitle(xname)
    h3.SetTitle("")  # Remove the ratio title
    h3.SetLineColor(ROOT.kBlack)
    h3.SetLineWidth(2)
    h3.SetMarkerSize(0)
    if h11 != "":
        h33.GetXaxis().SetTitle(xname)
        h33.SetTitle("")  # Remove the ratio title
        h33.SetLineColor(ROOT.kBlack)
        h33.SetLineWidth(2)
        h33.SetMarkerSize(0)
    h4.SetLineWidth(2)
    h4.SetFillStyle(3004)
    h4.SetFillColor(ROOT.kBlack)
    h4.SetLineColor(ROOT.kBlack)
    h4.SetMarkerSize(0)

    # Y axis ratio plot settings
    h3.GetYaxis().SetTitle(ytitle)
    h3.GetYaxis().SetNdivisions(303)
    h3.GetYaxis().SetTitleSize(20)
    h3.GetYaxis().SetTitleFont(43)
    h3.GetYaxis().SetTitleOffset(1.)
    h3.GetYaxis().SetLabelFont(43)  # Absolute font size in pixel (precision 3)
    h3.GetYaxis().SetLabelSize(17)
    h3.GetYaxis().SetMaxDigits(3)

    # X axis ratio plot settings
    h3.GetXaxis().SetTitleSize(20)
    h3.GetXaxis().SetTitleFont(43)
    h3.GetXaxis().SetTitleOffset(3.7)
    h3.GetXaxis().SetLabelFont(43)  # Absolute font size in pixel (precision 3)
    h3.GetXaxis().SetLabelSize(17)
    h3.GetXaxis().SetLabelOffset(.02)

    l = ROOT.TLine(h3.GetXaxis().GetXmin(), 1.0, h3.GetXaxis().GetXmax(), 1.0)
    l.SetLineColor(ROOT.kBlack)
    l.SetLineWidth(2)
    l.Draw("same")
    ROOT.gPad.Update()

    # Draw legend
    pad1.cd()
    ROOT.ATLASLabel(0.6, 0.85, "Internal")
    leg = ROOT.TLegend(.6, .65, .8, .8)
    leg.AddEntry(h1, h1.GetTitle(), "l")
    if h11 != "": leg.AddEntry(h11, h11.GetTitle(), "l")
    leg.AddEntry(h2, h2.GetTitle(), "f")
    leg.Draw("same")
    axis.Draw()

    ROOT.gPad.Update()
    c.Update()
    #raw_input("...")
    if savename != "": c.SaveAs(savename)

    return c
Ejemplo n.º 13
0
 fastSimHists[i].SetMarkerStyle(20)
 fullSimHists[i].Sumw2()
 fastSimHists[i].Sumw2()
 if fullSimHists[i].Integral() != 0:
     fullSimHists[i].Scale(1. / fullSimHists[i].Integral())
 if fastSimHists[i].Integral() != 0:
     fastSimHists[i].Scale(1. / fastSimHists[i].Integral())
 fullSimHists[i].GetXaxis().SetLabelSize(0)
 fullSimHists[i].Draw('ehist')
 fastSimHists[i].Draw('ehist same')
 if fastSimHists[i].GetMaximum() > fullSimHists[i].GetMaximum():
     fullSimHists[i].SetMaximum(fastSimHists[i].GetMaximum() * maxMult)
 else:
     fullSimHists[i].SetMaximum(fullSimHists[i].GetMaximum() * maxMult)
 leg.Draw()
 label = ROOT.ATLASLabel(0.2, 0.85, 'Internal')
 c[i].cd()
 pad2.append(ROOT.TPad('pad2_' + str(i), 'pad2_' + str(i), 0, 0.05, 1, 0.3))
 pad2[i].SetTopMargin(0)
 pad2[i].SetBottomMargin(0.2)
 pad2[i].SetGridy()
 pad2[i].Draw()
 pad2[i].cd()
 ratioHists.append(fastSimHists[i].Clone('ratio_' + str(i)))
 ratioHists[i].SetLineColor(ROOT.kBlack)
 ratioHists[i].SetMarkerColor(ROOT.kBlack)
 ratioHists[i].Divide(fullSimHists[i])
 ratioHists[i].SetMarkerStyle(21)
 ratioHists[i].SetMaximum(2)
 ratioHists[i].SetMinimum(0)
 ratioHists[i].Draw()
Ejemplo n.º 14
0
def plot_hist(
    backgrounds=None,
    signal=None,
    data=None,
    region=None,
    label=None,
    icut=None,
    histname=None,
    log=False,
    logx=False,
    blind=None,
    xmin=None,
    xmax=None,
    rebin=None,
    rebinVar=[],
    sys_dict=None,
    do_ratio_plot=True,
    save_eps=False,
    plotsfile=None,
    sig_rescale=None,
    xlabel=None,
):
    '''
    TODO: 
        * move this to a new module when finished
        * write description for this function

    '''
    print 'making plot: ', histname, ' in region', region
    print 'rebinVar', rebinVar
    print xlabel

    #assert signal, "ERROR: no signal provided for plot_hist"
    assert backgrounds, "ERROR: no background provided for plot_hist"

    samples = list(backgrounds)
    if signal: samples += signal
    if data: samples += [data]

    ## generate nominal hists
    hists = get_hists(
        region=region,
        icut=icut,
        histname=histname,
        samples=samples,
        rebin=rebin,
        rebinVar=rebinVar,
        sys_dict=sys_dict,
    )
    ## sum nominal background
    h_bkg_list = []
    for b in backgrounds:
        if not b in hists.keys(): continue
        h_bkg_list.append(hists[b])

    h_total = histutils.add_hists(h_bkg_list)

    ## get stat / sys bands
    if sys_dict:
        total_hists = get_total_stat_sys_hists(h_bkg_list, sys_dict)

        g_stat = make_band_graph_from_hist(total_hists[0])
        g_stat.SetFillColor(ROOT.kGray)
        g_stat.SetLineColor(ROOT.kGray)
        g_tot = make_band_graph_from_hist(total_hists[3], total_hists[4])
        g_tot.SetFillColor(ROOT.kOrange - 9)
        g_tot.SetLineColor(ROOT.kOrange - 9)

    else:
        h_total_stat = make_stat_hist(h_total)
        g_stat = make_band_graph_from_hist(h_total_stat)
        g_stat.SetFillColor(ROOT.kGray)
        g_stat.SetLineColor(ROOT.kGray)
        g_tot = None

    ## blind data and create ratio
    h_data = None
    h_ratio = None
    if data:
        h_data = hists[data]
        h_data.SetMarkerSize(0.8)
        h_data.Sumw2(0)
        h_data.SetBinErrorOption(1)
        if blind: apply_blind(h_data, blind)
        h_ratio = h_data.Clone('%s_ratio' % (h_data.GetName()))
        h_ratioGr = ROOT.TGraphAsymmErrors()
        h_ratioGr.SetMarkerSize(0.8)
        ## dont use Divide as it will propagate MC stat error to the ratio.
        #h_ratio.Divide(h_total)
        for i in range(1, h_ratio.GetNbinsX() + 1):
            if h_total.GetBinContent(i) != 0 and h_data.GetBinContent(i) != 0:
                h_ratio.SetBinContent(
                    i,
                    h_ratio.GetBinContent(i) / h_total.GetBinContent(i))
                h_ratio.SetBinError(
                    i,
                    h_ratio.GetBinError(i) / h_total.GetBinContent(i))
                h_ratioGr.SetPoint(h_ratioGr.GetN(), h_ratio.GetBinCenter(i),
                                   h_ratio.GetBinContent(i))
                h_ratioGr.SetPointError(
                    h_ratioGr.GetN() - 1, 0, 0,
                    h_data.GetBinErrorLow(i) / h_total.GetBinContent(i),
                    h_data.GetBinErrorUp(i) / h_total.GetBinContent(i))
            else:
                h_ratio.SetBinContent(i, -100)
                h_ratio.SetBinError(i, 0)
                h_ratioGr.SetPoint(h_ratioGr.GetN(), h_ratio.GetBinCenter(i),
                                   h_ratio.GetBinContent(i))
                h_ratioGr.SetPointError(h_ratioGr.GetN() - 1, 0, 0, 0, 0)

    yaxistitle = None
    for b in reversed(backgrounds):
        if not b in hists.keys(): continue
        else:
            yaxistitle = hists[b].GetYaxis().GetTitle()
            break

    ## create stack
    h_stack = ROOT.THStack()
    #for s in reversed(signal+backgrounds):
    for b in reversed(backgrounds):
        if not b in hists.keys(): continue
        h_stack.Add(hists[b])

    if signal:
        nLegend = len(signal + backgrounds) + 2
    else:
        nLegend = len(backgrounds) + 2
    x_legend = 0.63
    x_leg_shift = 0
    y_leg_shift = -0.1
    legYCompr = 8.0
    legYMax = 0.85
    legYMin = legYMax - (legYMax - (0.55 + y_leg_shift)) / legYCompr * nLegend
    legXMin = x_legend + x_leg_shift
    legXMax = legXMin + 0.25

    ## create legend (could use metaroot functionality?)
    if not do_ratio_plot:
        legXMin -= 0.005
        legXMax -= 0.058
    leg = ROOT.TLegend(legXMin / 1.2,
                       legYMin + 0.05 + (legYMax - legYMin) / 1.9,
                       legXMax + 0.08, legYMax + 0.05)
    leg.SetBorderSize(0)
    leg.SetNColumns(2)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetTextSize(0.045)
    if not do_ratio_plot:
        leg.SetTextSize(0.035)
    if data: leg.AddEntry(h_data, "#font[42]{" + str(data.tlatex) + "}", 'P')
    for b in backgrounds:
        if not b in hists.keys(): continue
        leg.AddEntry(hists[b], "#font[42]{" + str(b.tlatex) + "}", 'F')

    leg2 = ROOT.TLegend(legXMin / 1.2,
                        legYMin + 0.05 + (legYMax - legYMin) / 2.5 - 0.07,
                        legXMax + 0.08 - 0.2,
                        legYMin + 0.05 + (legYMax - legYMin) / 1.9)
    leg2.SetBorderSize(0)
    leg2.SetFillColor(0)
    leg2.SetFillStyle(0)
    leg2.SetTextSize(0.045)
    if not do_ratio_plot:
        leg2.SetTextSize(0.035)
    if signal:
        for s in signal:
            sig_tag = s.tlatex
            if sig_rescale: sig_tag = "%d #times " % int(sig_rescale) + sig_tag
            if not s in hists.keys(): continue
            #leg2.AddEntry(hists[s],"\font[42]{"+str(sig_tag)+"}",'F')
            leg2.AddEntry(hists[s], str(sig_tag), 'F')

    ## create canvas
    reg = region
    if not reg: reg = ""
    name = '_'.join([reg, histname]).replace('/', '_')
    cname = "c_final_%s" % name
    if do_ratio_plot: c = ROOT.TCanvas(cname, cname, 600, 600)
    else: c = ROOT.TCanvas(cname, cname, 600, 600)
    if xmin == None: xmin = h_total.GetBinLowEdge(1)
    if xmax == None: xmax = h_total.GetBinLowEdge(h_total.GetNbinsX() + 1)
    ymin = 1.e-2 if log else 0.0
    ymax = h_total.GetMaximum()
    for b in backgrounds:
        if not b in hists.keys(): continue
        ymax = max([ymax, hists[b].GetMaximum()])
    if data: ymax = max([ymax, h_data.GetMaximum()])
    if log: ymax *= 4000.
    else: ymax *= 1.7
    xtitle = h_total.GetXaxis().GetTitle()

    if do_ratio_plot: rsplit = 0.3
    else: rsplit = 0.
    pad1 = ROOT.TPad("pad1", "top pad", 0., rsplit, 1., 1.)
    pad1.SetLeftMargin(0.15)
    pad1.SetLeftMargin(0.15)
    pad1.SetTicky()
    pad1.SetTickx()
    if do_ratio_plot:
        pad1.SetBottomMargin(0.04)
        pad1.SetTopMargin(0.07)
    else:
        pad1.SetBottomMargin(0.15)

    pad1.Draw()
    if do_ratio_plot:
        pad2 = ROOT.TPad("pad2", "bottom pad", 0, 0, 1, rsplit)
        pad2.SetTopMargin(0.04)
        pad2.SetBottomMargin(0.40)
        pad2.SetLeftMargin(0.15)
        pad2.SetTicky()
        pad2.SetTickx()
        pad2.SetGridy()
        #if do_ratio_plot: pad2.Draw()
        pad2.Draw()
    pad1.cd()

    ytitle = "Events"
    if not rebin: ytitle = yaxistitle
    elif rebin != 1 and "GeV" in xtitle:
        ytitle += " / %s GeV" % rebin

    fr1 = pad1.DrawFrame(xmin, ymin, xmax, ymax, ';%s;%s' % (xtitle, ytitle))
    if do_ratio_plot:
        fr1.GetXaxis().SetTitleSize(0)
        fr1.GetXaxis().SetLabelSize(0)
    xaxis1 = fr1.GetXaxis()
    yaxis1 = fr1.GetYaxis()
    scale = (1.3 + rsplit)

    if not do_ratio_plot:
        xaxis1.SetTitleSize(0.7 * xaxis1.GetTitleSize() * scale)
        xaxis1.SetLabelSize(0.7 * xaxis1.GetLabelSize() * scale)
        xaxis1.SetTickLength(xaxis1.GetTickLength() * scale)
        xaxis1.SetTitleOffset(xaxis1.GetTitleOffset() / scale)
        xaxis1.SetLabelOffset(1. * xaxis1.GetLabelOffset() / scale)
        xaxis1.SetNoExponent()
        xaxis1.SetMoreLogLabels()

    yaxis1.SetTitleSize(yaxis1.GetTitleSize() * scale / 1.3)
    yaxis1.SetTitleOffset(2.1 * yaxis1.GetTitleOffset() / scale / 1.8)
    yaxis1.SetLabelSize(0.8 * yaxis1.GetLabelSize() * scale / 1.09)
    yaxis1.SetLabelOffset(1. * yaxis1.GetLabelOffset() / scale)
    xaxis1.SetNdivisions(510)
    yaxis1.SetNdivisions(510)

    h_stack.Draw("SAME,HIST")

    if signal:
        for s in reversed(signal):
            if not s in hists.keys(): continue
            if sig_rescale: hists[s].Scale(sig_rescale)
            hists[s].Draw("SAME,HIST")

    if data:
        h_data.Draw("SAME X0 P E")
    pad1.SetLogy(log)
    if logx != None: pad1.SetLogx(logx)
    leg.Draw()
    if signal: leg2.Draw()
    pad1.RedrawAxis()

    tlatex = ROOT.TLatex()
    tlatex.SetNDC()
    tlatex.SetTextSize(0.05)
    lx = 0.6  # for ATLAS internal
    ly = 0.845
    tlatex.SetTextFont(42)

    ty = 0.96
    th = 0.07
    tx = 0.18
    lumi = backgrounds[0].estimator.hm.target_lumi / 1000.
    textsize = 0.8
    if not do_ratio_plot: textsize = 0.8
    latex_y = ty - 2. * th + 0.05
    tlatex.DrawLatex(tx, latex_y - 0.054,
                     '#font[42]{#sqrt{s} = 13 TeV, %2.1f fb^{-1}}' % (lumi))
    ROOT.ATLASLabel(tx, latex_y, "Internal", 1)
    if label:
        latex_y -= 0.06
        #for i,line in enumerate(label):
        #  tlatex.DrawLatex(tx,latex_y-i*0.06,"#scale[%lf]{%s}"%(textsize,line))
        tlatex.DrawLatex(tx, latex_y - 0.04, "#font[42]{%s}" % label)
    if blind:
        line = ROOT.TLine()
        line.SetLineColor(ROOT.kBlack)
        line.SetLineStyle(2)
        line.DrawLine(blind, ymin, blind, ymax)
        bltext = ROOT.TLatex()
        bltext.SetTextFont(42)
        bltext.SetTextSize(0.04)
        bltext.SetTextAngle(90.)
        bltext.SetTextAlign(31)
        bltext.DrawLatex(blind, ymax, 'Blind   ')

    if do_ratio_plot:
        pad2.cd()
        fr2 = pad2.DrawFrame(xmin, 0.49, xmax, 1.51,
                             ';%s;Data / Bkg.' % (xtitle))
        xaxis2 = fr2.GetXaxis()
        yaxis2 = fr2.GetYaxis()
        scale = (1. / rsplit)
        yaxis2.SetTitleSize(yaxis2.GetTitleSize() * scale / 1.2)
        yaxis2.SetLabelSize(yaxis2.GetLabelSize() * scale / 1.2)
        yaxis2.SetTitleOffset(2.1 * yaxis2.GetTitleOffset() / scale / 2)
        yaxis2.SetLabelOffset(0.4 * yaxis2.GetLabelOffset() * scale)
        xaxis2.SetTitleSize(xaxis2.GetTitleSize() * scale / 1.2)
        xaxis2.SetLabelSize(0.8 * xaxis2.GetLabelSize() * scale)
        xaxis2.SetTickLength(xaxis2.GetTickLength() * scale)
        xaxis2.SetTitleOffset(3.2 * xaxis2.GetTitleOffset() / scale / 1.2)
        xaxis2.SetLabelOffset(2.5 * xaxis2.GetLabelOffset() / scale)
        yaxis2.SetNdivisions(510)
        xaxis2.SetNdivisions(510)

        if logx:
            pad2.SetLogx(logx)
            xaxis2.SetMoreLogLabels()
            xaxis2.SetNoExponent()
        else:
            pass

        if g_tot:
            g_tot.Draw("E2")
            g_stat.Draw("SAME,E2")
            leg.AddEntry(g_stat, "#font[42]{" + str("MC Stat.") + "}", 'F')
            leg.AddEntry(g_tot, "#font[42]{" + str("Sys. Unc.") + "}", 'F')

        else:
            g_stat.Draw("E2")
            leg.AddEntry(g_stat, "#font[42]{" + str("MC Stat.") + "}", 'F')

        arrows = []
        if data:
            #h_ratio.Draw("SAME X0 P E0")
            h_ratioGr.Draw("SAME E0 P")
            h_ratioGr.SetLineWidth(2)
            for bin_itr in range(1, h_ratio.GetNbinsX() + 1):
                if (h_total.GetBinContent(bin_itr) == 0
                        or h_data.GetBinContent(bin_itr) == 0):
                    continue
                if (h_ratio.GetBinContent(bin_itr) -
                        h_data.GetBinErrorLow(bin_itr) /
                        h_total.GetBinContent(bin_itr)) > 1.51:
                    arrowX = h_ratio.GetBinCenter(bin_itr)
                    arrow = ROOT.TArrow(arrowX, 1.35, arrowX, 1.5, 0.012, "=>")
                    arrow.SetLineWidth(2)
                    arrow.SetLineColor(ROOT.kRed + 1)
                    arrow.SetFillColor(ROOT.kRed + 1)
                    arrows += [arrow]
                    arrow.Draw()
                elif (h_ratio.GetBinContent(bin_itr) +
                      h_data.GetBinErrorUp(bin_itr) /
                      h_total.GetBinContent(bin_itr)
                      ) < 0.49 and h_ratio.GetBinContent(bin_itr) not in [
                          -100, 0
                      ]:
                    arrowX = h_ratio.GetBinCenter(bin_itr)
                    arrow = ROOT.TArrow(arrowX, 0.50, arrowX, 0.65, 0.012,
                                        "<=")
                    arrow.SetLineWidth(2)
                    arrow.SetLineColor(ROOT.kRed + 1)
                    arrow.SetFillColor(ROOT.kRed + 1)
                    arrows += [arrow]
                    arrow.Draw()
        pad2.RedrawAxis()
        pad2.RedrawAxis("g")

    if xlabel:
        if not do_ratio_plot:
            xaxis1.SetTitle(xlabel)
        else:
            xaxis2.SetTitle(xlabel)

    print 'saving plot...'
    if save_eps:
        eps_file = plotsfile.replace(".root", ".eps")
        if not log: c.SaveAs(eps_file)
        else: c.SaveAs(eps_file.replace(".eps", "_LOG.eps"))

    fout = ROOT.TFile.Open(plotsfile, 'UPDATE')
    fout.WriteTObject(c)
    fout.Close()
Ejemplo n.º 15
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"]
    compfilepath = config["comproot"] 
    compfilename = config["compinputdir"]
    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")
    icompfile = ROOT.TFile(compfilepath + compfilename + ".root")
    # read stuff
    data = ifile.Get("data_" + cut )
    compdata = icompfile.Get("data_" + cut.replace(config["cut"], config["compcut"]) )
    compttbar = icompfile.Get("ttbar_" + cut.replace(config["cut"], config["compcut"]) )
    if "Signal" in cut and blinded:
        data = ifile.Get("data_est_" + cut )
        compdata = icompfile.Get("data_est_" + cut.replace(config["cut"], config["compcut"]) )
    
    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_" + cut )
    #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_2000 = ifile.Get("RSG1_2000_" + cut )
    RSG1_2000.Scale(100)
    RSG1_2500 = ifile.Get("RSG1_2500_" + cut )
    RSG1_2500.Scale(100)

    #do simple rebin as rebin values
    if not rebin == None:
        data.Rebin(rebin)
        compdata.Rebin(rebin)
        compttbar.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)
    #use array to rebin histgrams
    if not rebinarry == None:
        data      = data.Rebin(len(rebinarry) - 1, data.GetName()+"_rebinned", rebinarry)
        compdata  = compdata.Rebin(len(rebinarry) - 1, compdata.GetName()+"_rebinned", rebinarry)
        compttbar = compttbar.Rebin(len(rebinarry) - 1, compttbar.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 compare only: substract ttbar
    data.Add(ttbar, -1)
    compdata.Add(compttbar, -1)
    #get QS scores
    if "Signal" in cut and blinded:
        ks = 0
    else:
        ks   = data.KolmogorovTest(compdata, "QU")
    int_data = data.Integral(0, data.GetXaxis().GetNbins()+1)
    int_data_est = compdata.Integral(0, compdata.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
    if config["compnorm"]:
        compdata.Scale(data.Integral(0, data.GetXaxis().GetNbins()+1)/compdata.Integral(0, compdata.GetXaxis().GetNbins()+1))

    #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")

    #setup data and bkg estiamtes
    data = h_plt.makeTotBkg([data])[1]
    bkg  = h_plt.makeTotBkg([compdata])
    #bkg = h_plt.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_2000.Add(bkg[0]) 
    RSG1_2500.Add(bkg[0]) 

    # 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.001, 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")

    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(config["leg"] + "/" + config["compleg"])
    hratio.GetYaxis().SetRangeUser(0.6, 1.4) #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")
    # 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
    #
    if (ops.detail):
        ROOT.myText(0.15, 0.97, 1, "KS = %s" % str(('%.3g' % ks)), CONF.legsize)
        ROOT.myText(0.4, 0.97, 1, "(E-O)/O = %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
    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  , config["leg"], "PE")
    leg.AddEntry(bkg[0], config["compleg"] + (" norm" if config["compnorm"] else ""), "F")
    #leg.AddEntry(ttbar, "t#bar{t}","F")
    #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)#times100", "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") + \
     "_comp_" + config["leg"] + "_" + config["compleg"]
    #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()
    ifile.Close()
    icompfile.Close()
    del(leg)
Ejemplo n.º 16
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()
Ejemplo n.º 17
0
                downHist.SetLineWidth(2)
                legMJ.append(ROOT.TLegend(0.5,0.7,0.75,0.85))
                legMJ[-1].SetBorderSize(0)
                legMJ[-1].SetFillStyle(0)
                legMJ[-1].SetTextSize(0.04)
                legMJ[-1].AddEntry(nomHist,'nominal','f')
                legMJ[-1].AddEntry(upHist,'b-tagging NP'+str(j+1)+' +1 #sigma','f')
                legMJ[-1].AddEntry(downHist,'b-tagging NP'+str(j+1)+' -1 #sigma','f')

                nomHist.Draw('hist')
                nomHist.GetYaxis().SetTitleOffset(1.5)
                nomHist.GetYaxis().SetTitle('Events')
                upHist.Draw('hist same')
                downHist.Draw('hist same')
                legMJ[-1].Draw()
                ROOT.ATLASLabel(0.47,0.88,'Simulation Internal')
                lumiLatex.DrawLatexNDC(0.675,0.6,lumiString)
                lumiLatex.DrawLatexNDC(0.75,0.5,srNames[m-2])
                mG = str(pointDict[int(dsidList[i])][0])
                mX = str(pointDict[int(dsidList[i])][1])
                massString='#splitline{RPV10}{#splitline{m_{#tilde{g}} = '+mG+'}{m_{#tilde{#chi}} = '+mX+'}}'                
                if mX == '0':
                    massString='#splitline{RPV6}{m_{#tilde{g}} = '+mG+'}'
                lumiLatex.DrawLatexNDC(0.2,0.85,massString)
                
                canMJ[-1].cd()

                pad2.append(ROOT.TPad('pad2_'+str(ci),'pad2_'+str(ci),0,0.05,1,0.3))
                pad2[-1].SetTopMargin(0)
                pad2[-1].SetBottomMargin(0.2)
                pad2[-1].SetGridy()
def compute_ratio(args, tfile, region):
    histname = os.path.join(region, "plotEvent_data", args.var)

    # TODO XXX: should we make this configurable?
    # Note: vvv seems no longer available by default in output ROOT file.
    # (it was a small contribution anyway...)
    valid_mcs = ["wewk", "wqcd", "zewk", "zqcd", "tall"]

    data_hist = tfile.Get(histname)
    print("Reading histogram: " + histname)

    for mcname in valid_mcs:
        newname = histname.replace("data", mcname)
        print("Reading histogram: " + newname)
        mc_hist = tfile.Get(newname)
        try:
            data_hist.Add(mc_hist, -1)
        except:
            print("Error: failed to read histograms!")
            sys.exit(1)
    print("")

    if args.avg:
        mean = data_hist.GetMean()
        mean_error = data_hist.GetMeanError()
        print("Average value in bin " + str(region) + " = " + str(mean) +
              " +/- " + str(mean_error))

    # Integrate from 0 to 4 and retrieve the integrated error.
    low_error = ROOT.Double()
    low = data_hist.IntegralAndError(0, args.cutoff, low_error)

    # Integrate from 4 and above (bin 5+) and retrieve the integrated error.
    high_error = ROOT.Double()
    high = data_hist.IntegralAndError(args.cutoff + 1,
                                      data_hist.GetNbinsX() + 2, high_error)

    ulow = uncertainties.ufloat(low, low_error)
    uhigh = uncertainties.ufloat(high, high_error)

    try:
        ratio = (ulow / uhigh).n
        ratio_error = (ulow / uhigh).s
    except:
        ratio = 0.0
        ratio_error = 0.0

    if args.invert:
        try:
            ratio = (uhigh / ulow).n
            ratio_error = (uhigh / ulow).s
        except:
            ratio = 0.0
            ratio_error = 0.0

    print("")
    if data_hist.GetBinContent(0) != 0:
        print("Below 0 = %f +/- %f" %
              (data_hist.GetBinContent(0), data_hist.GetBinError(0)))

    print("Below 4 = %f +/- %f" % (low, low_error))
    print("Above 4 = %f +/- %f" % (high, high_error))
    print("Ratio = %f +/- %f" % (ratio, ratio_error))
    print("")

    # Now that we've made the estimate, draw the MEt significance template shape.

    # Taken from drawStack.py-- rebin so 1 bin = 1 sqrt(GeV)
    # Actually, make this configurable parameter.
    data_hist.Rebin(args.rebin)

    canvas = ROOT.TCanvas("canvas", "canvas", 800, 600)
    data_hist.Draw()
    canvas.Update()

    data_hist.GetXaxis().SetTitle(args.xlabel)
    data_hist.GetYaxis().SetTitle(args.ylabel)

    label = ROOT.ATLASLabel(0.66, 0.87, "Internal")

    # Get the text to use to describe this region/bin.
    # It could be hardcoded in the global dictionary region_labels (above).
    # Or it could be passed in on the CLI.
    region_text = args.text
    if region_text == "" and args.region in region_labels.keys():
        region_text = region_labels[args.region]

    # Also look up the process (this could be the W to mu nu CR!) and get
    # a human-readable description.
    # This is fragile.
    process_char = args.region.split("_")[-1]
    try:
        process = process_labels[process_char]
    except KeyError:
        process = process_labels['e']

    # Dynamically relocate the legend depending on whether or not we have    # text describing the selection region.
    lower_bound = 0.70
    if not region_text == "":
        lower_bound -= 0.04
    legend = ROOT.TLegend(0.66, lower_bound, 0.95, 0.85)

    # TODO: make energy, configurable...
    legend.AddEntry(
        0, "#sqrt{s} = " + args.energy + " TeV, " + args.lumi + " fb^{-1}", "")
    legend.AddEntry(0, process + ", Anti-ID", "")
    if not region_text == "":
        legend.AddEntry(0, region_text, "")
    legend.AddEntry(0, "Ratio: %0.2f #pm %0.2f" % (ratio, ratio_error), "")
    legend.SetBorderSize(0)
    legend.SetFillColor(0)
    legend.SetMargin(0)
    legend.SetFillStyle(0)
    legend.SetTextSize(0.035)
    legend.SetTextFont(42)
    legend.Draw()

    output_name = "anti_id_template_" + region + ".eps"
    if args.name != "":
        output_name = args.name + "_" + output_name
    canvas.SaveAs(output_name)
    if args.wait:
        raw_input()

    # This is a bit of a mess.
    return ratio, ratio_error, low, low_error, high, high_error
Ejemplo n.º 19
0
        for i in range(len(sigDefs)):
            sigDefList[i].Fill(mG,mX,hSD.GetBinContent(i+1))
            sigDefList[i].GetXaxis().SetTitle('m_{#tilde{g}} [GeV]')
            sigDefList[i].GetYaxis().SetTitle('m_{#tilde{#chi}_{1}^{0}} [GeV]')
outFile.Write()
j=0
for i in range(len(cutflowList)):
    j+=1
    c[i].cd()
    cutflowList[i].SetMarkerSize(2.2)
    cutflowList[i].Draw('text')
    if isRPV6:
        cutflowList[i].GetYaxis().SetLabelOffset(999)
        cutflowList[i].GetYaxis().SetLabelSize(0)
        cutflowList[i].GetYaxis().SetTitle('')
    ROOT.ATLASLabel(0.2,0.85,'Internal')
    lumiLatex.DrawLatexNDC(0.65,0.825,'#int L dt = 6.0 fb^{-1}')
    c[i].SaveAs('/global/project/projectdirs/atlas/www/multijet/RPV/btamadio/SignalYields/RPV/cutflow_'+args.outDir+'_'+str(i)+'_'+cuts[i]+'.pdf')

for i in range(len(effList)):
    j+=1
    c2[i].cd()
    effList[i].SetMarkerSize(2.2)
    effList[i].Draw('text')
    if isRPV6:
        effList[i].GetYaxis().SetLabelOffset(999)
        effList[i].GetYaxis().SetLabelSize(0)
        effList[i].GetYaxis().SetTitle('')
    ROOT.ATLASLabel(0.2,0.85,'Internal')
    lumiLatex.DrawLatexNDC(0.65,0.825,'#int L dt = 6.0 fb^{-1}')
    c2[i].SaveAs('/global/project/projectdirs/atlas/www/multijet/RPV/btamadio/SignalYields/RPV/cutEfficiency_'+args.outDir+'_'+str(i)+'_'+cuts[i]+'.pdf')    
def plotInputs(inputsPath,
               outputPath,
               channels,
               backgrounds,
               signals,
               signalpt=Samp("", 9, 1)):
    #for mass in signal:
    #  thisSig = "h_"+str(mass)+"_TeV_HVT"
    #  #add to list?
    #thisSig = "h_"+str(signal)+"_TeV_HVT"
    ROOT.SetAtlasStyle()
    canv = ROOT.TCanvas("canv", "canv", 800, 600)
    for channel in channels:
        print channel
        canv.Clear()
        canv.SetLeftMargin(0.0)
        canv.SetRightMargin(0.0)

        # divide into legend and plot pads
        canv.Divide(2, 1)

        # format the pad for the plots
        mainpad = canv.cd(1)
        mainpad.Clear()
        mainpad.SetPad(0.0, 0.0, 0.7, 1.0)
        mainpad.Divide(1, 2)

        #pad for the ratio plot
        ratiopad = mainpad.cd(2)
        ratiopad.Clear()
        ratiopad.SetPad(0.0, 0.05, 1.0, 0.3)
        ratiopad.SetTopMargin(0.02)
        ratiopad.SetLeftMargin(0.15)
        ratiopad.SetRightMargin(0.075)
        ratiopad.SetBottomMargin(0.3)

        #this pad will contain the stacked plot
        plotpad = mainpad.cd(1)
        plotpad.Clear()
        plotpad.SetPad(0.0, 0.32, 1.0, 1.0)
        plotpad.SetBottomMargin(0.02)
        plotpad.SetLeftMargin(0.15)
        plotpad.SetRightMargin(0.075)

        myStack = ROOT.THStack("stack", "")
        bkgStack = ROOT.THStack("stack", "")

        for background in backgrounds:
            filename = background.name + "_" + channel
            f = ROOT.TFile.Open('{dest}/{sample}.root'.format(dest=inputsPath,
                                                              sample=filename))
            hist = f.Get("Nominal")
            print filename
            print hist
            #hist1 = hist.Clone()
            #ROOT.SetOwnership(hist1, False)
            hist.SetName(hist.GetTitle())
            hist.SetFillColor(background.plotShade)
            hist.SetFillStyle(1001)
            hist.SetMarkerColor(background.plotShade)
            hist.SetMarkerStyle(0)
            hist.SetMarkerSize(0)
            hist.SetDirectory(0)
            hist.Scale(background.norm)
            hist.GetXaxis().SetTitle("m(lvJ) [GeV]")
            hist.GetYaxis().SetTitle("events")
            hist.GetYaxis().SetTitleOffset(0)
            hist.SetTitle(background.name)
            bkgStack.Add(hist)
            myStack.Add(hist)
            #f.Close()
            #hist.Draw()

        #get signal and add to stack
        if signalpt.name != "":
            filename = signals[0] + str(signalpt.name) + "_" + channel
            sigf = ROOT.TFile.Open('{dest}/{sample}.root'.format(
                dest=inputsPath, sample=filename))
            sighist = sigf.Get("Nominal")
            sighist.Scale(signalpt.norm)
            sighist.SetTitle(str(signalpt.name).split("0")[0] + " TeV HVT")
            sighist.SetFillColor(signalpt.plotShade)
            sighist.SetFillStyle(3017)
            sighist.SetMarkerColor(signalpt.plotShade)
            sighist.SetLineColor(signalpt.plotShade)
            sighist.SetDirectory(0)
            #sighist.GetXaxis().SetTitle(" log_{10}(m_{{\rm VH}} / {\rm MeV})")
            #sighist.Draw("same HIST L")
            myStack.Add(sighist)
            #sighist.Draw("same")

        #time to draw the ratio plot
        ratiopad.cd()

        #draw middle line on ratio
        mylist = list(bkgStack.GetHists())
        histTotal = mylist[0].Clone()
        for i in mylist[1:]:
            histTotal.Add(i)

        #get data
        filename = "data_" + channel
        dataf = ROOT.TFile.Open('{dest}/{sample}.root'.format(dest=inputsPath,
                                                              sample=filename))
        datahist = dataf.Get("Nominal")

        #calc data to MC ratio
        dataratio = datahist.Clone()
        dataratio.Add(histTotal, -1)
        dataratio.Divide(histTotal)
        dataratio.GetYaxis().SetRangeUser(-1, 1)
        dataratio.GetYaxis().SetTitle("Deviation")
        dataratio.GetYaxis().SetLabelSize(0.1)
        dataratio.GetYaxis().SetTitleSize(0.15)
        dataratio.GetYaxis().SetTitleOffset(0.25)
        dataratio.GetYaxis().SetNdivisions(205)
        dataratio.GetXaxis().SetTitle(histTotal.GetXaxis().GetTitle())
        dataratio.GetXaxis().SetLabelSize(0.1)
        dataratio.GetXaxis().SetTitleSize(0.15)
        dataratio.GetXaxis().SetTitleOffset(0.75)
        dataratio.Draw()

        ratioLine = ROOT.TLine(
            dataratio.GetBinLowEdge(0), 0,
            dataratio.GetBinLowEdge(dataratio.GetNbinsX() + 1), 0)
        ratioLine.SetLineColor(ROOT.kBlack)
        ratioLine.SetLineStyle(7)
        ratioLine.Draw("same")

        #draw the stack and the data
        plotpad.cd()
        maximum = myStack.GetMaximum()
        myStack.SetMaximum(2 * maximum)
        myStack.Draw("HIST")
        datahist.Draw("same")
        ROOT.myText(0.75, 0.74, 1, "#sqrt{s}= 13 TeV")
        ROOT.myText(0.5, 0.74, 1, "#int L dt = 1.0 fb^{-1}")
        ROOT.ATLASLabel(0.5, 0.84, "Internal")

        #add legend to canvas
        legpad = canv.cd(2)
        legpad.SetPad(0.7, 0.12, 1.0, 0.93)
        legpad.SetLeftMargin(0.0)
        legpad.SetRightMargin(0.0)
        legpad.SetBorderSize(0)

        leg = ROOT.TLegend(0, 0, 1, 1)
        leg.SetShadowColor(ROOT.kWhite)
        leg.SetLineColor(ROOT.kWhite)
        leg.SetFillStyle(0)
        leg.SetEntrySeparation(0.05)
        leg.SetMargin(0.15)

        #overlay any signal points

        l = list(myStack.GetHists())
        l.reverse()
        map(lambda h: leg.AddEntry(h, h.GetTitle(), "f"), l)
        #    if signalOverlays:
        #      map(lambda h: leg.AddEntry(h, h.GetTitle(), "f"), legSigList)
        leg.SetTextSize(1.0 / len(leg.GetListOfPrimitives()))
        leg.Draw()

        canv.SaveAs(
            str(outputPath) + str(channel) + "_postfit_" + str(signalpt.name) +
            ".png")
        canv.SaveAs(
            str(outputPath) + str(channel) + "_postfit_" + str(signalpt.name) +
            ".C")
        canv.SaveAs(
            str(outputPath) + str(channel) + "_postfit_" + str(signalpt.name) +
            ".eps")
        plotpad.cd()
        plotpad.SetLogy()
        canv.Update()
        canv.SaveAs(
            str(outputPath) + str(channel) + "_postfit_" + str(signalpt.name) +
            "_log.png")
        canv.SaveAs(
            str(outputPath) + str(channel) + "_postfit_" + str(signalpt.name) +
            "_log.C")
        canv.SaveAs(
            str(outputPath) + str(channel) + "_postfit_" + str(signalpt.name) +
            "_log.eps")
Ejemplo n.º 21
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()
Ejemplo n.º 22
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)
Ejemplo n.º 23
0
    h.GetXaxis().SetTitleSize(0.05)
    h.GetXaxis().SetTitleOffset(1.3)
    h.GetYaxis().SetTitle('Fraction of jets')
    h.GetYaxis().SetTitleSize(0.05)
    h.GetYaxis().SetTitleOffset(1.3)
    leg.AddEntry(h, legLabels[i], 'F')
    if not h:
        print 'Histogram not found:', histName
        sys.exit(1)
    if drawCount == 0:
        h.Draw('hist')
        drawCount += 1
    else:
        h.Draw('hist same')
leg.Draw()
ROOT.ATLASLabel(0.65, 0.87, 'Internal')
lat = ROOT.TLatex()
lat.DrawLatexNDC(0.2, 0.85, ptStr)
if int(args.nSubjetBin) < 4:
    lat.DrawLatexNDC(0.2, 0.75, 'n_{subjet} = ' + args.nSubjetBin)
elif int(args.nSubjetBin) == 4:
    lat.DrawLatexNDC(0.2, 0.75, 'n_{subjet} #geq 4')
if int(args.bTag) == 1:
    lat.DrawLatexNDC(0.2, 0.65, 'b-matched')
elif int(args.bTag) == 0:
    lat.DrawLatexNDC(0.2, 0.65, 'non-b-matched')
elif int(args.bTag) == 9:
    lat.DrawLatexNDC(0.2, 0.65, 'b-inclusive')

outFileName = '/global/project/projectdirs/atlas/www/multijet/RPV/btamadio/bkgEstimation/09_09_templates/template_' + fileSuffix
can.Print(outFileName + '.pdf')
Ejemplo n.º 24
0
            # Absolute font size in pixel (precision 3)
            tmpratio.GetXaxis().SetLabelSize(15)

            unityline = ROOT.TLine()
            unityline.DrawLine(ROOT.gPad.GetUxmin(), 1., ROOT.gPad.GetUxmax(),
                               1.)

            try:
                axislabel = axislabels[axislabel]
            except:
                axislabel = axislabel
            tmpratio.GetXaxis().SetTitle(axislabel)

    if plotWithROOT:
        pad1.cd()
        ROOT.ATLASLabel(0.2, 0.9,
                        "Internal      %s, %s" % (regionName, kindOfRegion))

        legend = Legend(4, leftmargin=0.45, margin=0.35, topmargin=0.07)
        hists["DataMain"].SetTitle("Data 15+16 %s fb^{-1}" % lumiscale)
        legend.AddEntry(hists["DataMain"], style='ep')
        # sortedHistsToStack.reverse()
        for BG in reversed(sortedHistsToStack):
            BG.SetTitle(BG.GetTitle().replace("MassiveCB", ""))
            legend.AddEntry(BG, style='F')
        for signalsample in signalsamples:
            skip = 1
            try:
                if any([
                        thissig in signalsample
                        for thissig in plottedsignals[regionName]
                ]):
Ejemplo n.º 25
0
def plotDeco(lumi, region, var, indir, debug):
    if debug: print "opening output file"
    o = ROOT.TFile("test.root", "RECREATE")
    if debug: print "Getting MC list"
    if (var == 'Mt' or var == 'MET'):
        deco_path_list = []
        data_path = 'FFAIDSR/FFAIDSR_FFAID/h_FFAIDSR_FFAID_%s' % var
        deco_path_list.append('AID1/AID1_FFAID/h_AID1_FFAID_%s' % var)
        deco_path_list.append('AID2/AID2_FFAID/h_AID2_FFAID_%s' % var)
        deco_path_list.append('AID3/AID3_FFAID/h_AID3_FFAID_%s' % var)
        deco_path_list.append('AID12/AID12_FFAID/h_AID12_FFAID_%s' % var)
        deco_path_list.append('AID13/AID13_FFAID/h_AID13_FFAID_%s' % var)
        deco_path_list.append('AID23/AID23_FFAID/h_AID23_FFAID_%s' % var)
        deco_path_list.append('AID123/AID123_FFAID/h_AID123_FFAID_%s' % var)
    else:
        data_path = 'FFAIDSR/FFAIDSR_FFAIDSR/h_FFAIDSR_FFAIDSR_%s' % var
        deco_path_list = []
        deco_path_list.append('AID1/AID1_FFAIDSR/h_AID1_FFAIDSR_%s' % var)
        deco_path_list.append('AID2/AID2_FFAIDSR/h_AID2_FFAIDSR_%s' % var)
        deco_path_list.append('AID3/AID3_FFAIDSR/h_AID3_FFAIDSR_%s' % var)
        deco_path_list.append('AID12/AID12_FFAIDSR/h_AID12_FFAIDSR_%s' % var)
        deco_path_list.append('AID13/AID13_FFAIDSR/h_AID13_FFAIDSR_%s' % var)
        deco_path_list.append('AID23/AID23_FFAIDSR/h_AID23_FFAIDSR_%s' % var)
        deco_path_list.append('AID123/AID123_FFAIDSR/h_AID123_FFAIDSR_%s' %
                              var)

    deco_name_list = []
    deco_name_list.append('fail_ID')
    deco_name_list.append('fail_ISO')
    deco_name_list.append('fail_D0')
    deco_name_list.append('fail_ID_ISO')
    deco_name_list.append('fail_ID_D0')
    deco_name_list.append('fail_ISO_D0')
    deco_name_list.append('fail_All')

    deco_hist_list = GetDecoHists(GetRootFiles(indir, debug), deco_path_list,
                                  deco_name_list, debug)
    if debug: print "Getting data hist"
    if debug: print deco_hist_list
    m_data = GetDataHists(GetRootFiles(indir, debug), data_path, debug)
    m_data.SetMarkerSize(0.5)
    if debug: print "Making deco hist stack"
    m_dstack = MakeDataStack(deco_hist_list, lumi, debug)
    m_dsum = SumMCHists(deco_hist_list, lumi, debug)
    m_ratio = MakeDecoRatio(m_data, m_dsum, debug)
    m_legend = MakeLegend(deco_hist_list, m_data, region)
    sum_bin_list = []
    for x in xrange(1, m_dsum.GetNbinsX() + 1):
        if m_dsum.GetBinContent(x) == 0.0:
            sum_bin_list.append(1.0)
        else:
            sum_bin_list.append(m_dsum.GetBinContent(x))
    #clone data hist to normalize
    m_data.SetDirectory(0)
    norm_data = copy.deepcopy(m_data)
    norm_data.SetDirectory(0)
    for s, x in zip(sum_bin_list, xrange(1, len(sum_bin_list) + 1)):
        norm_data.SetBinContent(x, m_data.GetBinContent(x) / s)

    canvas, p1, p2 = SetRatioCanvas('deco', region, var)
    p2.cd()
    m_ratio.Draw("P")
    p1.cd()
    m_dstack.Draw("HIST")
    norm_data.Draw("HIST SAME")
    o.cd()
    canvas.Write()
    canvas.cd()
    m_legend.Draw()
    ROOT.gStyle.SetLegendBorderSize(0)
    ROOT.gROOT.ForceStyle()
    ROOT.myText(0.21, 0.85, 1, "#sqrt{s}= 13 TeV, 10.0 pb^{-1}")
    #ROOT.myText(       0.41,  0.80, 1, "data16PeriodK")
    #ROOT.myText(       0.41,  0.85, 1, "%s" % region)
    ROOT.ATLASLabel(0.21, 0.90, "Internal")
    #raw_input("-->")
    canvas.Print('%s_%s.pdf' % (region, var))
    canvas.Close()
    return True
Ejemplo n.º 26
0
        if i > 0:
            h.Rebin(5)
        h.SetLineColor(cols[j])
        h.SetLineWidth(2)
        h.GetXaxis().SetTitle(xLabList[i])
        h.GetYaxis().SetTitle('a.u.')
        h.GetYaxis().SetTitleOffset(1.5)
        if i == 0:
            leg6.AddEntry(h, legLab6[j], 'f')
        if not drawn:
            h.Draw('hist')
            drawn = True
        else:
            h.Draw('hist same')
    leg6.Draw()
    ROOT.ATLASLabel(0.5, 0.85, 'Simulation Internal')
    c6[i].Print(
        '/global/project/projectdirs/atlas/www/multijet/RPV/btamadio/SignalComparison/RPV6_'
        + histNameList[i].split('_')[1] + '.pdf')
    c6[i].Print(
        '/global/project/projectdirs/atlas/www/multijet/RPV/btamadio/SignalComparison/RPV6_'
        + histNameList[i].split('_')[1] + '.png')
    c6[i].Print(
        '/global/project/projectdirs/atlas/www/multijet/RPV/btamadio/SignalComparison/RPV6_'
        + histNameList[i].split('_')[1] + '.C')

for i in range(len(histNameList)):
    c10[i].cd()
    drawn = False
    hists = []
    for j in range(len(dsid10)):
Ejemplo n.º 27
0
def plotSR(lumi, sample_path, region, variable, indir, debug):
    if debug: print "opening output file"
    o = ROOT.TFile("test.root", "RECREATE")
    if debug: print "Setting variable to plot"
    var = variable
    path = sample_path
    value_list = []
    error_list = []
    if debug: print "Getting MC list"
    BGhist_list = GetBGHists(GetRootFiles(indir, debug), path, debug)
    if debug: print "Getting data hist"
    m_data = GetDataHists(GetRootFiles(indir, debug), path, debug)
    myRange = m_data.GetNbinsX()
    if debug: print "Making MC hist stack"
    m_hstack = MakeHistStack(BGhist_list, lumi, debug)
    m_hsum = SumMCHists(BGhist_list, lumi, debug)
    print '*********** %s Fakes Factors in %s ***********' % (region, var)
    if (var == 'Njet'):
        sum1 = 0.0
        err1 = 0.0
        for x in xrange(3, myRange + 1):
            bkSubtract = m_data.GetBinContent(x) - m_hsum.GetBinContent(x)
            bkSubtract_error = m_data.GetBinError(x) - m_hsum.GetBinError(x)
            if x is 3:
                value_list.append(bkSubtract)
                error_list.append(bkSubtract_error)
            elif x is 4:
                value_list.append(bkSubtract)
                error_list.append(bkSubtract_error)
            elif x is 5:
                value_list.append(bkSubtract)
                error_list.append(bkSubtract_error)
            else:
                sum1 += bkSubtract
                err1 += bkSubtract_error
        value_list.append(sum1)
        error_list.append(err1)
    elif (var == 'Nbjet'):
        sum1 = 0.0
        err1 = 0.0
        for x in xrange(1, myRange + 1):
            bkSubtract = m_data.GetBinContent(x) - m_hsum.GetBinContent(x)
            bkSubtract_error = m_data.GetBinError(x) - m_hsum.GetBinError(x)
            if x is 1:
                value_list.append(bkSubtract)
                error_list.append(bkSubtract_error)
            elif x is 2:
                value_list.append(bkSubtract)
                error_list.append(bkSubtract_error)
            elif x is 3:
                value_list.append(bkSubtract)
                error_list.append(bkSubtract_error)
            else:
                sum1 += bkSubtract
                err1 += bkSubtract_error
        value_list.append(sum1)
        error_list.append(err1)
    elif (var == 'HT'):
        sum1 = 0.0
        err1 = 0.0
        sum2 = 0.0
        err2 = 0.0
        for x in xrange(1, myRange + 1):
            bkSubtract = m_data.GetBinContent(x) - m_hsum.GetBinContent(x)
            bkSubtract_error = m_data.GetBinError(x) - m_hsum.GetBinError(x)
            if x < 5:
                value_list.append(bkSubtract)
                error_list.append(bkSubtract_error)
            elif (x >= 5 and x < 7):
                sum1 += bkSubtract
                err1 += bkSubtract_error
            else:
                sum2 += bkSubtract
                err2 += bkSubtract_error
        value_list.append(sum1)
        error_list.append(err1)
        value_list.append(sum2)
        error_list.append(err2)
    elif (var == 'dphi_l1met' or var == 'dphi_j1met'):
        sum1 = 0.0
        err1 = 0.0
        for x in xrange(1, myRange + 1):
            bkSubtract = m_data.GetBinContent(x) - m_hsum.GetBinContent(x)
            bkSubtract_error = m_data.GetBinError(x) - m_hsum.GetBinError(x)
            if x < 6:
                value_list.append(bkSubtract)
                error_list.append(bkSubtract_error)
            else:
                sum1 += bkSubtract
                err1 += bkSubtract_error
        value_list.append(sum1)
        error_list.append(err1)
    elif (var == 'J1pt'):
        sum1 = 0.0
        err1 = 0.0
        sum2 = 0.0
        err2 = 0.0
        sum3 = 0.0
        err3 = 0.0
        for x in xrange(1, myRange + 1):
            bkSubtract = m_data.GetBinContent(x) - m_hsum.GetBinContent(x)
            bkSubtract_error = m_data.GetBinError(x) - m_hsum.GetBinError(x)
            if x is 1:
                value_list.append(bkSubtract)
                error_list.append(bkSubtract_error)
            elif x is 2:
                value_list.append(bkSubtract)
                error_list.append(bkSubtract_error)
            elif x is 3:
                value_list.append(bkSubtract)
                error_list.append(bkSubtract_error)
            elif (x is 4 or x is 5):
                sum1 += bkSubtract
                err1 += bkSubtract_error
            elif (x is 6 or x is 7):
                sum2 += bkSubtract
                err2 += bkSubtract_error
            else:
                sum3 += bkSubtract
                err3 += bkSubtract_error
        value_list.append(sum1)
        error_list.append(err1)
        value_list.append(sum2)
        error_list.append(err2)
        value_list.append(sum3)
        error_list.append(err3)
    elif (var == 'AntiIDelPt' or var == 'IDelPt'):
        sum1 = 0.0
        err1 = 0.0
        sum2 = 0.0
        err2 = 0.0
        sum3 = 0.0
        err3 = 0.0
        for x in xrange(1, myRange + 1):
            bkSubtract = m_data.GetBinContent(x) - m_hsum.GetBinContent(x)
            bkSubtract_error = m_data.GetBinError(x) - m_hsum.GetBinError(x)
            #print ' bin %i = %f' % (x, bkSubtract)
            # if( x > 5 and x <= 10 ):
            #     value_list.append(bkSubtract)
            #     error_list.append(bkSubtract_error)
            # elif( x > 10 and x <= 15 ):
            #     sum1 += bkSubtract
            #     err1 += bkSubtract_error
            # elif( x > 15 and x <= 20 ):
            #     sum2 += bkSubtract
            #     err2 += bkSubtract_error
            # elif( x > 20 ):
            #     sum3 += bkSubtract
            #     err3 += bkSubtract_error
            if (x > 5 and x <= 7):
                sum1 += bkSubtract
                err1 += bkSubtract_error
            elif (x > 7 and x <= 10):
                sum2 += bkSubtract
                err2 += bkSubtract_error
            elif (x > 10):
                sum3 += bkSubtract
                err3 += bkSubtract_error
        value_list.append(sum1)
        error_list.append(err1)
        value_list.append(sum2)
        error_list.append(err2)
        value_list.append(sum3)
        error_list.append(err3)
    elif (var == 'Npv'):
        sum1 = 0.0
        err1 = 0.0
        sum2 = 0.0
        err2 = 0.0
        sum3 = 0.0
        err3 = 0.0
        sum4 = 0.0
        err4 = 0.0
        sum5 = 0.0
        err5 = 0.0
        for x in xrange(1, myRange + 1):
            bkSubtract = m_data.GetBinContent(x) - m_hsum.GetBinContent(x)
            bkSubtract_error = m_data.GetBinError(x) - m_hsum.GetBinError(x)
            #print ' bin %i = %f' % (x, bkSubtract)
            if (x < 6):
                sum1 += bkSubtract
                err1 += bkSubtract_error
            elif (x >= 6 and x < 11):
                sum2 += bkSubtract
                err2 += bkSubtract_error
            elif (x >= 11 and x < 16):
                sum3 += bkSubtract
                err3 += bkSubtract_error
            elif (x >= 16 and x < 21):
                sum4 += bkSubtract
                err4 += bkSubtract_error
            elif (x >= 21):
                sum5 += bkSubtract
                err5 += bkSubtract_error

        value_list.append(sum1)
        error_list.append(err1)
        value_list.append(sum2)
        error_list.append(err2)
        value_list.append(sum3)
        error_list.append(err3)
        value_list.append(sum4)
        error_list.append(err4)
        value_list.append(sum5)
        error_list.append(err5)
    else:
        for x in xrange(1, myRange + 1):
            bkSubtract = m_data.GetBinContent(x) - m_hsum.GetBinContent(x)
            bkSubtract_error = m_data.GetBinError(x) - m_hsum.GetBinError(x)
            value_list.append(bkSubtract)
            error_list.append(bkSubtract_error)
    #Last entry for the average fake factor
    error_d = ROOT.Double()
    error_m = ROOT.Double()
    integral_d = m_data.IntegralAndError(1, myRange, error_d)
    integral_m = m_hsum.IntegralAndError(1, myRange, error_m)
    bkSubtract = integral_d - integral_m
    bkSubtract_error = error_d - error_m
    value_list.append(bkSubtract)
    error_list.append(bkSubtract_error)

    #print value_list
    #print error_list

    m_ratio = MakeNewRatio(m_data, m_hsum, debug)
    m_legend = MakeLegend(BGhist_list, m_data, region)
    canvas, p1, p2 = SetRatioCanvas('SR', region, var)
    p2.cd()
    m_ratio.Draw("P")
    p1.cd()
    m_hstack.Draw("HIST")
    m_data.Draw("PESAME")
    o.cd()
    m_hstack.Write()
    canvas.Write()

    canvas.cd()
    m_legend.Draw()
    ROOT.gStyle.SetLegendBorderSize(0)
    ROOT.gROOT.ForceStyle()
    #ROOT.myText(       0.41,  0.85, 1, "2.5fb^{-1}@ #sqrt{s}= 13 TeV")
    #ROOT.myText(       0.41,  0.80, 1, "data16PeriodK")
    #ROOT.myText(       0.41,  0.85, 1, "%s" % region)
    ROOT.ATLASLabel(0.41, 0.90, "Internal")
    #raw_input("-->")
    canvas.Print('%s_SR_%s.pdf' % (region, var))
    canvas.Close()
    return value_list, error_list
Ejemplo n.º 28
0
def charged_asymmetry(mu):
    rf = ROOT.TFile('~/panalysis/output/prodr/%s_ttbar/%s_regions.root' %
                    (mu.name, mu.name))
    entry = upsilon_20
    k_entry = upsilon_CR
    verbose = False
    region = 'TTBAR_OS'
    # scale factors
    k_entry = upsilon_CR

    groups = mu.MC + [mu.signal]
    kW_OS = hist.calc_kX(rf,
                         mu,
                         k_entry,
                         'WCR',
                         'Wlnu',
                         OS='OS',
                         verbose=verbose,
                         groups=groups)
    kW_SS = hist.calc_kX(rf,
                         mu,
                         k_entry,
                         'WCR',
                         'Wlnu',
                         OS='SS',
                         verbose=verbose,
                         groups=groups)
    rQCD = hist.calc_rQCD(rf,
                          mu,
                          k_entry,
                          'QCD',
                          kW_OS=kW_OS,
                          kW_SS=kW_SS,
                          verbose=verbose,
                          groups=groups)

    # Canvas
    if entry.blind: ratio = False
    ratio = False
    cname = '%s_%s_%s' % (mu.name, entry.name, region)
    #pname = '%s_%s_%s' % (mu.name,region.rstrip('_OS'), hand)
    if ratio:
        c = ROOT.TCanvas(cname, cname, 1500, 1000)
        #Split for ratio plot
        c.Divide(1, 2)
        c.cd(1).SetPad(0.0, 0.2, 1.0, 1.0)
        c.cd(2).SetPad(0.0, 0.0, 1.0, 0.2)
        c.cd(1)
    else:
        c = ROOT.TCanvas(cname, cname, 1200, 800)
    rb = 1
    # data
    if 'SR_OS' in region: dregion = 'SR_OS'
    if 'SR_SS' in region: dregion = 'SR_SS'
    data = rf.Get('h_%s_%s_%s' % (entry.name, mu.data.name, dregion)).Clone()
    data.SetMarkerStyle(20)
    data.SetMarkerSize(2)
    data.SetLabelSize(0.04, "y")
    data.Rebin(rb)
    # Blind data
    data.Reset()
    if entry.xmax:
        data.SetAxisRange(entry.xmin or 0, entry.xmax)
    # stat. unc. on stack
    stacksum = data.Clone("tmp")
    stacksum.Reset()

    # Legend
    x0 = 0.73
    y0 = 0.55
    step = 0.045

    nl = 4 + len(mu.MC) - 1 * entry.blind
    l = ROOT.TLegend(x0, y0, x0 + .16, y0 + nl * step)
    l.SetTextSize(0.0345)
    l.SetBorderSize(0)
    l.SetFillColor(0)

    # Data
    # Stack
    st = ROOT.THStack(cname, "%s; %s; " % (cname, entry.xtitle))

    # QCD ESTIMATE
    #if region == 'SR_SS': rQCD = ErrorFloat(1.,0.)
    qcd = hist.get_QCDW(rf,
                        mu,
                        entry,
                        'SR_SS',
                        rqcd=rQCD,
                        verbose=False,
                        groups=groups)
    qcd.SetLineWidth(0)
    qcd.SetLineColor(3)
    qcd.SetFillColor(3)
    qcd.SetMarkerStyle(0)
    qcd.SetMarkerColor(3)
    qcd.Rebin(rb)

    if entry.xmax:
        qcd.SetAxisRange(entry.xmin or 0, entry.xmax)

    st.Add(qcd)
    stacksum.Add(qcd)

    if verbose:
        total_est = ErrorFloat(*hist.IntegralError(qcd))
        print 'Data: %.0f +/- %.0f' % (hist.IntegralError(data)[0],
                                       hist.IntegralError(data)[1])
        print 'NQCD: %.0f +/- %.0f' % (hist.IntegralError(qcd)[0],
                                       hist.IntegralError(qcd)[1])

    mc_leg = []

    n_total = ErrorFloat(
        *hist.IntegralError(hist.get_OS(rf, entry, mu.signal, region)))

    for group in groups:
        entry.add_group(group)
        if group.name == 'Wlnu':
            h = hist.get_dataW(rf,
                               mu,
                               entry,
                               'WCR_OS',
                               verbose=False,
                               groups=groups)
        else:
            h = hist.get_OS(rf, entry, group, region)
        h.Rebin(rb)

        if entry.xmax:
            h.SetAxisRange(entry.xmin or 0, entry.xmax)

        h.SetLineColor(entry[group.name]['fill'])
        h.SetLineWidth(0)
        h.SetMarkerStyle(0)
        h.SetMarkerColor(entry[group.name]['fill'])
        h.SetFillColor(entry[group.name]['fill'])
        h.SetLabelSize(0.04, "y")

        st.Add(h)
        stacksum.Add(h)
        mc_leg.append((h, group.legend, hist.IntegralError(h)[0],
                       hist.IntegralError(h)[1]))

        if verbose:
            print '%s: %.0f +/- %.0f' % (group.name, hist.IntegralError(h)[0],
                                         hist.IntegralError(h)[1])
            total_est += ErrorFloat(*hist.IntegralError(h))

    if verbose:
        print 'Total Estimated: %.0f +/- %.0f' % (total_est.val, total_est.err)

    for li in reversed(mc_leg):
        l.AddEntry(li[0], '%s' % (li[1]))

    l.AddEntry(
        qcd, 'Multijet'
    )  #: %.0f +/- %.0f' % (hist.IntegralError(qcd)[0],hist.IntegralError(qcd)[1]))
    data.SetXTitle(entry.xtitle)
    data.GetXaxis().SetTitleOffset(1.25)

    stacksum.SetFillStyle(3354)
    stacksum.SetLineColor(1)
    stacksum.SetFillColor(12)
    stacksum.SetMarkerStyle(1)

    maxi = max(data.GetMaximum(), st.GetMaximum())
    maxi = 6250
    mini = 0.
    data.SetMinimum(1.2 * mini)
    data.SetMaximum(maxi)

    bw = data.GetXaxis().GetBinWidth(1)
    data.GetYaxis().SetTitle('Events / %s %s' % (bw, entry.units))

    if not entry.blind:
        data.Draw("PE")
        st.Draw("HIST,SAME")
        stacksum.Draw("E2,SAME")
        data.Draw("SAME, PE")
    else:
        data.Reset()
        data.Draw()
        st.SetTitle('')

        st.SetMinimum(1.2 * st.GetMinimum())
        st.SetMaximum(1.5 * st.GetMaximum())
        st.Draw("HIST,SAME")
        stacksum.Draw("E2,SAME")

    ROOT.gPad.RedrawAxis()
    l.Draw()

    atlas = ROOT.ATLASLabel(0.32, 0.86, "   Work in Progress")
    td = ROOT.TPaveText(0.54, 0.68, 0.67, 0.85, "NDC")
    td.SetTextAlign(13)
    td.SetBorderSize(0)
    td.SetFillColor(0)
    td.SetTextSize(0.04)

    td.AddText('#sqrt{s} = 8 TeV')
    td.AddText('#int Ldt = 20.3 fb^{-1}')
    td.Draw()
    # channel
    tm = ROOT.TPaveText(0.19, 0.83, 0.22, 0.90, "NDC")
    tm.SetBorderSize(0)
    tm.SetFillColor(0)
    tm.SetTextSize(0.05)
    if mu.name == 'mu':
        tm.AddText('#mu#tau_{had}')
    elif mu.name == 'el':
        tm.AddText('e#tau_{had}')
    tm.Draw()

    c.Update()
    c.Print('../plots/ttbar/%s.eps' % (cname))