Пример #1
0
def produceNormalizedPlots(processes, selections, variables, colors, intLumi, pdir, lt, rt, log, hfile):
    
    print ''
    print 'Preparing normalized plots ...'

    gROOT.SetBatch(True)

    intLumiab = intLumi/1e+06 

    yl = "Normalized Event Rate"

    ff = "eps"

    logstr = ''
    if log:
       logstr = 'log'
    else:
       logstr = 'lin'
    
    stackstr = ''

    hfile.cd()

    nsel = 0
    for s in selections:
        selstr = 'sel{}'.format(int(nsel))
        nsel += 1
        for v, dic in variables.iteritems() :
             histos = []
             i = 0

             filename = '{}_{}_{}'.format(v, selstr, logstr)
             
             leg = TLegend(0.60,0.65,0.90,0.88)
             leg.SetFillColor(0)
             leg.SetFillStyle(0)
             leg.SetLineColor(0)
             leg.SetShadowColor(10)
             leg.SetTextSize(0.035)
             leg.SetTextFont(42)


             cols = []
             for p in processes:
                 hname = '{}_{}_{}'.format(p, selstr, v)
                 h = hfile.Get(hname)
                 hh = TH1D.Clone(h)

                 # rebin if needed
                 hh.Rebin(int(hh.GetNbinsX()/dic['bin']))

                 if hh.Integral(0, hh.GetNbinsX()+1) > 0:
                     hh.Scale(1./hh.Integral(0, hh.GetNbinsX()+1))
                 histos.append(hh)
                 cols.append(colors[p])
                 leg.AddEntry(hh,p,"l")
                 i+=1
             drawNormalized(filename, yl, leg, lt, rt, ff, pdir, log, histos, cols)

    print 'DONE.'
Пример #2
0
def legend(title=''):
    lg = TLegend(0.65, 0.55, 0.95, 0.90, title)
    lg.SetFillColor(0)
    lg.SetFillStyle(0)
    lg.SetLineColor(0)
    lg.SetLineStyle(0)
    lg.SetBorderSize(0)
    lg.SetShadowColor(0)
    lg.SetTextFont(42)
    lg.SetTextSize(0.06)
    return lg
Пример #3
0
def getLegend():
    legend = TLegend(0.55010112, 0.7183362, 0.70202143, 0.919833)
    legend.SetTextSize(0.032)
    legend.SetLineColor(0)
    legend.SetShadowColor(0)
    legend.SetLineStyle(1)
    legend.SetLineWidth(1)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetMargin(0.35)
    return legend
Пример #4
0
def getLegend(x1=0.70010112,y1=0.123362,x2=0.90202143,y2=0.279833):
  legend = TLegend(x1,y1,x2,y2)
  legend.SetTextSize(0.032)
  legend.SetLineColor(0)
  legend.SetShadowColor(0)
  legend.SetLineStyle(1)
  legend.SetLineWidth(1)
  legend.SetFillColor(0)
  legend.SetFillStyle(0)
  legend.SetMargin(0.35)
  return legend
Пример #5
0
def configureCanvasLegend(canvas,aliases,textSize=25):
	height = 1.2*len(aliases)*textSize/canvas.GetWh()
	width = int(max([len(name) for name in aliases])*textSize*.50)+70
	canvas.SetLeftMargin(canvas.GetLeftMargin()*textSize/14.)
	canvas.SetBottomMargin(canvas.GetBottomMargin()*textSize/14.)
	legend = TLegend(0.00,1-canvas.GetTopMargin(),150./width,1-canvas.GetTopMargin()-height)
	legend.SetTextSize(textSize)
	legend.SetFillColor(0)
	legend.SetShadowColor(0)
	legend.SetBorderSize(0)
	SetOwnership(legend, 0)

	return canvas,legend
Пример #6
0
def checkForOutliers(hist, qaContainer):
    """ Checks for outliers in selected histograms.

    Outliers are calculated by looking at the standard deviation. See: :func:`hasSignalOutlier()`.
    This function is mainly a proof of concept, but could become more viable with a bit more work.

    Note:
        This function will add a large TLegend to the histogram noting the mean and the number of
        outliers. It will also display the recalculated mean excluding the outlier(s).

    Args:
        hist (TH1): The histogram to be processed.
        qaContainer (:class:`~processRuns.qa.qaFunctionContainer`): Contains information
            about the QA function and histograms, as well as the run being processed.

    Returns:
        None

    """
    # If outlier data point, print warning banner
    if hist.GetName() == "":
        tempList = hasSignalOutlier(
            hist
        )  # array of info from hasSignalOutlier function, to print on legend
        numOutliers = tempList[0]
        mean = tempList[1]
        stdev = tempList[2]
        newMean = tempList[3]
        newStdev = tempList[4]
        if (numOutliers):
            # Create TLegend and fill with information if there is an outlier.
            leg = TLegend(0.15, 0.5, 0.7, 0.8)
            SetOwnership(leg, False)

            leg.SetBorderSize(4)
            leg.SetShadowColor(2)
            leg.SetHeader("#splitline{OUTLIER SIGNAL DETECTED}{IN %s BINS!}" %
                          numOutliers)
            leg.AddEntry(
                None, "Mean: %s, Stdev: %s" % ('%.2f' % mean, '%.2f' % stdev),
                "")
            leg.AddEntry(
                None, "New mean: %s, New Stdev: %s" %
                ('%.2f' % newMean, '%.2f' % newStdev), "")
            leg.SetTextSize(0.04)
            leg.SetTextColor(2)
            leg.Draw()
Пример #7
0
def plot_GOF(hist, obs, critical, p_value, alpha="0.05"):
    # canvas
    canv = TCanvas("canv", "canv", 600, 600)
    canv.SetBottomMargin(0.10)
    canv.SetLeftMargin(0.15)
    canv.SetRightMargin(0.12)
    # histograms
    hist.SetMarkerColor(0)
    hist.SetTitle("GOF test - toys {}".format(int(hist.GetEntries())))
    hist.GetXaxis().SetTitleFont(43)
    hist.GetYaxis().SetTitleFont(43)
    hist.GetXaxis().SetTitleSize(20)
    hist.GetYaxis().SetTitleSize(20)
    hist.GetXaxis().SetTitleOffset(0.8)
    hist.GetYaxis().SetTitleOffset(1.5)
    hist.GetXaxis().SetTitle("Statistics")
    hist.GetYaxis().SetTitle("Probability")
    hist.Draw("hist")
    up = hist.GetMaximum()
    hist.GetYaxis().SetRangeUser(0, 1.2 * up)
    # lines
    c_line = TLine(critical, 0, critical, 1.2 * up)
    c_line.SetLineColor(2)
    c_line.SetLineWidth(4)
    c_line.SetLineStyle(2)
    c_line.Draw("L same")
    obs_line = TLine(obs, 0, obs, 1.2 * up)
    obs_line.SetLineColor(1)
    obs_line.SetLineWidth(4)
    obs_line.Draw("L same")
    # legend
    leg = TLegend(0.6, 0.65, .95, .95)
    leg.SetFillColor(0)
    leg.SetShadowColor(0)
    leg.SetLineColor(0)
    leg.SetTextFont(43)
    leg.SetTextSize(18)
    leg.AddEntry(c_line, "alpha = {}".format(alpha), 'L')
    leg.AddEntry(obs_line, "data (p-value={0:.2f})".format(p_value), 'L')
    leg.AddEntry(hist, "toys", "L")
    leg.Draw("same")
    # save canvas
    canv.SaveAs("{}.pdf".format(saveout))
    canv.SaveAs("{}.png".format(saveout))
    canv.SaveAs("{}.root".format(saveout))

    return canv
Пример #8
0
def print_single_min(vec_beg, vec_end, name, text):

    total_beg = vec_beg[0].Clone()
    c = 0
    for v in vec_beg:
        if c != 0:
            total_beg.Add(vec_beg[c])
        c = c + 1
    
    norm = 1/total_beg.Integral()
    total_beg.Scale(norm)

    if 'buff' in name:
        legb = TLegend(0.25,0.93,0.90,0.60)
        legb.SetNColumns(5)
    else:
        legb = TLegend(0.60,0.80,0.90,0.60)
        legb.SetNColumns(2)
    legb.SetLineColor(0)
    legb.SetFillStyle(0)
    legb.SetShadowColor(0)
    legb.SetBorderSize(0)

    if 'buff' in name:
        lege = TLegend(0.25,0.93,0.90,0.60)
        lege.SetNColumns(5)
    else:
        lege = TLegend(0.22,0.90,0.52,0.70)
        lege.SetNColumns(2)
    lege.SetLineColor(0)
    lege.SetFillStyle(0)
    lege.SetShadowColor(0)
    lege.SetBorderSize(0)


    #vec_beg = sorted(vec_beg, key=lambda x: x.Integral(), reverse=True)


    stack1  = THStack("stack1","stack1")
    for v in vec_beg:
        if v.Integral() != 0:
            v.Scale(norm)
            legb.AddEntry(v, v.GetTitle()[4:], "f")
            stack1.Add(v)

    total_end = vec_end[0].Clone()
    c = 0
    for v in vec_end:
        if c != 0:
            total_end.Add(vec_end[c])
        c = c + 1
    
    norm = 1/total_end.Integral()
    total_end.Scale(norm)

    stack2  = THStack("stack2","stack2")
    for v in vec_end:
        if v.Integral() != 0:
            v.Scale(norm)
            lege.AddEntry(v, v.GetTitle()[4:], "f")
            stack2.Add(v)


    total_beg.SetLineColor(kRed)
    total_beg.SetLineWidth(1)
    total_end.SetLineColor(kRed)
    total_end.SetLineWidth(1)

    total_beg.GetXaxis().SetTitle("Minutes after stable beams declared [min]")
    total_end.GetXaxis().SetTitle("Minutes before stable beams ended [min]")

    if '0_4' in name:
        total_beg.GetYaxis().SetTitle("Arbitrary units / 3 mins")
        total_end.GetYaxis().SetTitle("Arbitrary units / 3 mins")
    else:
        total_beg.GetYaxis().SetTitle("Arbitrary units / 5 mins")
        total_end.GetYaxis().SetTitle("Arbitrary units / 5 mins")

    c4 = TCanvas( 'c4', 'c4',1000, 1200)
    c4.Divide(1,2)
    c4.cd(1)
    total_beg.Draw("HIST")
    stack1.Draw("PFC PLC SAME HIST")
    total_beg.Draw("SAMEHIST")
    AtlasStyle.ATLAS_LABEL(0.18,.96, 1, "Internal")
    AtlasStyle.myText(0.40, 0.96, kBlack, text)
    legb.Draw()
    c4.cd(2)
    total_end.Draw("HIST")
    stack2.Draw("PFC PLC SAME HIST")
    total_end.Draw("SAMEHIST")
    AtlasStyle.ATLAS_LABEL(0.18,.96, 1, "Internal")
    AtlasStyle.myText(0.40, 0.96, kBlack, text)
    lege.Draw()
    c4.Update()
    c4.Print("plots/"+name+".pdf")
Пример #9
0
def make_minute_plots(buff_dict, lock_dict, results):

    hl0 = TH1F('hl0','hl0', 50, 0, 1)
    hl4 = TH1F('hl4','hl4', 50, 0, 1)
    hl8 = TH1F('hl8','hl8', 50, 0, 1)
    hl8.GetXaxis().SetTitle("Fraction of fill length")
    hl8.GetYaxis().SetTitle("Arbitrary units/ 0.02")
    hb0 = TH1F('hb0','h0', 50, 0, 1)
    hb4 = TH1F('hb4','h4', 50, 0, 1)
    hb8 = TH1F('hb8','h8', 50, 0, 1)
    hb8.GetXaxis().SetTitle("Fraction of fill length")
    hb8.GetYaxis().SetTitle("Arbitrary units/ 0.02")

    change_colors_min(hl0, hl4, hl8)
    change_colors_min(hb0, hb4, hb8)


    h0_lock_beg = []
    h0_lock_end = []
    h4_lock_beg = []
    h4_lock_end = []
    h8_lock_beg = []
    h8_lock_end = []

    h0_buff_beg = []
    h0_buff_end = []
    h4_buff_beg = []
    h4_buff_end = []
    h8_buff_beg = []
    h8_buff_end = []

    for r in lock_dict:
        temp0 = TH1F('htl0'+r,'htl0'+r, 80, 0, 240)
        temp1 = TH1F('htl1'+r,'htl1'+r, 80, 0, 240)
        temp2 = TH1F('htl2'+r,'htl2'+r, 96, 0, 480)
        temp3 = TH1F('htl3'+r,'htl3'+r, 96, 0, 480)
        temp4 = TH1F('htl4'+r,'htl4'+r, 180,0, 900)
        temp5 = TH1F('htl5'+r,'htl5'+r, 180,0, 900)
        
        temp0.SetLineWidth(0)
        temp0.SetFillStyle(1001)
        temp1.SetLineWidth(0)
        temp1.SetFillStyle(1001)
        temp2.SetLineWidth(0)
        temp2.SetFillStyle(1001)
        temp3.SetLineWidth(0)
        temp3.SetFillStyle(1001)
        temp4.SetLineWidth(0)
        temp4.SetFillStyle(1001)
        temp5.SetLineWidth(0)
        temp5.SetFillStyle(1001)

        h0_lock_beg.append(temp0)
        h0_lock_end.append(temp1)
        h0_lock_beg[-1].SetDirectory(0)
        h0_lock_end[-1].SetDirectory(0)

        h4_lock_beg.append(temp2)
        h4_lock_end.append(temp3)
        h4_lock_beg[-1].SetDirectory(0)
        h4_lock_end[-1].SetDirectory(0)

        h8_lock_beg.append(temp4)
        h8_lock_end.append(temp5)
        h8_lock_beg[-1].SetDirectory(0)
        h8_lock_end[-1].SetDirectory(0)

    for r in buff_dict:
        temp0 = TH1F('htb0'+r,'htb0'+r, 80, 0, 240)
        temp1 = TH1F('htb1'+r,'htb1'+r, 80, 0, 240)
        temp2 = TH1F('htb2'+r,'htb2'+r, 96, 0, 480)
        temp3 = TH1F('htb3'+r,'htb3'+r, 96, 0, 480)
        temp4 = TH1F('htb4'+r,'htb4'+r, 180,0, 900)
        temp5 = TH1F('htb5'+r,'htb5'+r, 180,0, 900)
        
        temp0.SetLineWidth(0)
        temp0.SetFillStyle(1001)
        temp1.SetLineWidth(0)
        temp1.SetFillStyle(1001)
        temp2.SetLineWidth(0)
        temp2.SetFillStyle(1001)
        temp3.SetLineWidth(0)
        temp3.SetFillStyle(1001)
        temp4.SetLineWidth(0)
        temp4.SetFillStyle(1001)
        temp5.SetLineWidth(0)
        temp5.SetFillStyle(1001)

        h0_buff_beg.append(temp0)
        h0_buff_end.append(temp1)
        h0_buff_beg[-1].SetDirectory(0)
        h0_buff_end[-1].SetDirectory(0)

        h4_buff_beg.append(temp2)
        h4_buff_end.append(temp3)
        h4_buff_beg[-1].SetDirectory(0)
        h4_buff_end[-1].SetDirectory(0)

        h8_buff_beg.append(temp4)
        h8_buff_end.append(temp5)
        h8_buff_beg[-1].SetDirectory(0)
        h8_buff_end[-1].SetDirectory(0)

    for error in results:
        pos_rod  = error.text.find("ROD") + 4
        pos_lock = error.text.find("Lock") + 15
        pos_buff = error.text.find("buffer") + 17

        if error.msgID == 'TRT::ROD05Module':
            rod  = '0x'+str(error.text[pos_rod:pos_rod+6])
        else:
            rod  = str(error.text[pos_rod:pos_rod+8])

        lock = str(error.text[pos_lock:pos_lock+3])
        buff = str(error.text[pos_buff:pos_buff+3])

        for i,key in enumerate(lock_dict):
            if key == rod and lock != '0xf' and error.sb_length > 0.5 and error.sb == 1:
                frac = error.sb_time_run/error.sb_length
                if error.sb_length  < 4:
                    hl0.Fill(frac)
                    h0_lock_beg[i].Fill(error.sb_time_run*60)
                    h0_lock_end[i].Fill(error.sb_length*60 - error.sb_time_run*60)
                elif error.sb_length < 8:
                    hl4.Fill(frac)
                    h4_lock_beg[i].Fill(error.sb_time_run*60)
                    h4_lock_end[i].Fill(error.sb_length*60 - error.sb_time_run*60)
                else:       
                    hl8.Fill(frac) 
                    h8_lock_beg[i].Fill(error.sb_time_run*60)
                    h8_lock_end[i].Fill(error.sb_length*60 - error.sb_time_run*60)
        for i,key2 in enumerate(buff_dict):
           if key2 == rod and buff != '0xf' and error.sb_length > 0.5 and error.sb == 1:
               frac = error.sb_time_run/error.sb_length
               if error.sb_length  < 4:
                   hb0.Fill(frac)
                   h0_buff_beg[i].Fill(error.sb_time_run*60)
                   h0_buff_end[i].Fill(error.sb_length*60 - error.sb_time_run*60)
               elif error.sb_length < 8:
                   hb4.Fill(frac)
                   h4_buff_beg[i].Fill(error.sb_time_run*60)
                   h4_buff_end[i].Fill(error.sb_length*60 - error.sb_time_run*60)
               else:
                   hb8.Fill(frac) 
                   h8_buff_beg[i].Fill(error.sb_time_run*60)
                   h8_buff_end[i].Fill(error.sb_length*60 - error.sb_time_run*60)
    
    leg3 = TLegend(0.23,0.85,0.45,0.75)
    leg3.SetLineColor(0)
    leg3.SetFillStyle(0)
    leg3.SetShadowColor(0)
    leg3.SetBorderSize(0)

    leg3.AddEntry(hl0, "Fill Length: 0-4 hours", "lf")
    leg3.AddEntry(hl4, "Fill Length: 4-8 hours", "lf")
    leg3.AddEntry(hl8, "Fill Length: 8+  hours", "lf")

    c3 = TCanvas( 'c3', 'c3', 1000, 600)
    hl8.DrawNormalized("HIST",1)
    hl0.DrawNormalized("HISTSAME",1)
    hl4.DrawNormalized("HISTSAME",1)
    AtlasStyle.ATLAS_LABEL(0.24,.88, 1, "Internal")
    leg3.Draw()
    AtlasStyle.myText(0.5, 0.88, kBlack, "All RODs: lock errors")
    c3.Update()
    c3.Print("plots/frac_all_lock.pdf")
    c3.Clear()

    hb8.DrawNormalized("HIST",1)
    hb0.DrawNormalized("HISTSAME",1)
    hb4.DrawNormalized("HISTSAME",1)
    AtlasStyle.ATLAS_LABEL(0.24,.88, 1, "Internal")
    leg3.Draw()
    AtlasStyle.myText(0.5, 0.88, kBlack, "All RODs: buffer errors")
    c3.Update()
    c3.Print("plots/frac_all_buff.pdf")
   
    print_single_min(h0_lock_beg, h0_lock_end, "min_lock_0_4", "Lock errors, 0-4 hour fills")
    print_single_min(h4_lock_beg, h4_lock_end, "min_lock_4_8", "Lock errors, 4-8 hour fills")
    print_single_min(h8_lock_beg, h8_lock_end, "min_lock_8",   "Lock errors, 8+  hour fills")
    
    print_single_min(h0_buff_beg, h0_buff_end, "min_buff_0_4", "Buffer errors, 0-4 hour fills")
    print_single_min(h4_buff_beg, h4_buff_end, "min_buff_4_8", "Buffer errors, 4-8 hour fills")
    print_single_min(h8_buff_beg, h8_buff_end, "min_buff_8",   "Buffer errors, 8+  hour fills")
Пример #10
0
def drawIt(h1,h2,h3,ptmin,ptmax):

    scl1=h1.Integral();
    scl2=h2.Integral();
    scl3=h3.Integral();
    if scl1>0: h1.Scale(1./scl1)
    if scl2>0: h2.Scale(1./scl2)
    if scl3>0: h3.Scale(1./scl3)

    ## h1.SetMinimum(1.1e-6)
    
    SetHistColorAndMarker(h1,ROOT.kBlue,20)
    SetHistColorAndMarker(h2,ROOT.kRed,20)
    SetHistColorAndMarker(h3,ROOT.kMagenta,20)

    h1.GetXaxis().SetTitle("Response")
    h1.SetMinimum(2.e-6)
    fName="GFit"
    fitfunc="gaus"
    h1fit = TF1(fName,fitfunc,1.,1.5);
    h1fit.SetParameter(0, 1)
    h1fit.SetParameter(1, 1)
    h1fit.SetParameter(2, .1)

    h2fit=h1fit.Clone()
    h3fit=h1fit.Clone()

    h1fit.SetLineColor(h1.GetLineColor())
    h2fit.SetLineColor(h2.GetLineColor())
    h3fit.SetLineColor(h3.GetLineColor())

    c1 = prepPlot("c0","c0",700,20,500,500)
    c1.SetLogy(1)
    
    h1.Draw()
    h2.Draw("same")
    ## h3.Scale(0.8)
    h3.Draw("same")

    h1.Fit(h1fit,"0R");    
    # h1fit.Draw("sames")
    h2.Fit(h2fit,"0R");    
    # h2fit.Draw("sames")
    h3.Fit(h3fit,"0R");    
    # h3fit.Draw("sames")

    
    print "XXX: ",h1.GetTitle(), h2.GetTitle()
    label=h1.GetTitle()

    ## h1overFlow=(h1.GetBinContent(h1.GetNbinsX()+1)/h1.Integral(1,h1.GetNbinsX()+1)) * 100
    ## h2overFlow=(h2.GetBinContent(h2.GetNbinsX()+1)/h2.Integral(1,h2.GetNbinsX()+1)) * 100
    ## h3overFlow=(h3.GetBinContent(h3.GetNbinsX()+1)/h3.Integral(1,h2.GetNbinsX()+1)) * 100
    ## # print h1overFlow,h2overFlow,h3overFlow
    ## # print h1.GetEntries(),h2.GetEntries(),h3.GetEntries()
    ## 
    ## # print h1.GetEntries(),h1.Integral(),h1.Integral(1,h1.GetNbinsX()),h1.Integral(1,h1.GetNbinsX()+1)
    ## # print h2.GetEntries(),h2.Integral(),h2.Integral(1,h2.GetNbinsX()),h2.Integral(1,h2.GetNbinsX()+1)
    ## # print h2.Integral(1,h2.GetNbinsX()+1) -h2.Integral(1,h2.GetNbinsX())
    ## 
    ## print "Reco underflows/overflows: ",h1.GetBinContent(h1.GetNbinsX()+1),h1overFlow
    ## print "CB underflows/overflows: ",  h2.GetBinContent(h2.GetNbinsX()+1),h2overFlow
    ## print "GS underflows/overflows: ",  h3.GetBinContent(h3.GetNbinsX()+1),h3overFlow
    ## print

    xl1=.15; yl1=0.75; xl2=xl1+.28; yl2=yl1+.15;
    leg =TLegend(xl1,yl1,xl2,yl2);
    leg.SetFillColor(0);
    leg.SetLineColor(0);
    leg.SetShadowColor(0);
    leg.SetTextSize(0.038)
    
    leg.AddEntry(h1,"Full Sim","lp");
    leg.AddEntry(h2,"Crystal Ball","lp");
    leg.AddEntry(h3,"Gaussian","lp");

    leg.Draw()
    
    t1 = TLatex();
    t1.SetNDC();
    txtsize=0.038;  t1.SetTextSize(txtsize); t1.SetTextAlign(22);

    if ymin == -ymax:
        leglabel2="|y| < " + str(ymax)
    else:
        leglabel2= str(ymin) + " < y < " + str(ymax)
    xtxt=.785; ytxt=.885;
    t1.DrawLatex(xtxt,ytxt,label);
    t1.DrawLatex(xtxt,ytxt-0.06,leglabel2);

    c1.Modified()    
    c1.Update()
    
    if SavePlots:
        outfile="SmearedResponse_" + str(int(ptmin)) + "pT" + str(int(ptmax))
        if wExtraSmearing:
            outfile=outfile + "_wExtraSmearing"
        outfile=outfile + ".pdf"
        c1.Print(outfile)
    
    return
Пример #11
0
print "X_axis= ", X_axis

for obj in (1, 2):
    if (obj == 1):
        Prefix += "_LCT"
    if (obj == 2):
        Prefix = Prefix.replace("LCT", "SEG")

    c1 = TCanvas("c1", "c1", 600, 600)
    c2 = TCanvas("c2", "c2", 600, 600)
    leg = TLegend(0.45, 0.25, 0.95, 0.36)

    leg.SetNColumns(2)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetShadowColor(0)
    leg.SetBorderSize(0)
    leg.SetTextFont(132)
    leg.SetTextSize(0.04)

    leg_ME1 = TLegend(0.45, 0.25, 0.95, 0.36)

    leg_ME1.SetNColumns(2)
    leg_ME1.SetFillColor(0)
    leg_ME1.SetFillStyle(0)
    leg_ME1.SetShadowColor(0)
    leg_ME1.SetBorderSize(0)
    leg_ME1.SetTextFont(132)
    leg_ME1.SetTextSize(0.04)
    color = 0
Пример #12
0
def makePlot(sfHist,
             ofHist,
             selection,
             plot,
             runRange,
             region,
             cmsExtra,
             combination,
             dyHist=None,
             edgeShape=False,
             edgeShapeMC=False,
             differentEdgePositions=False):

    colors = createMyColors()

    hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)

    plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
    ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
    style = setTDRStyle()
    style.SetPadTopMargin(0.07)
    ROOT.gStyle.SetOptStat(0)
    plotPad.UseCurrentStyle()
    ratioPad.UseCurrentStyle()
    plotPad.Draw()
    ratioPad.Draw()
    plotPad.cd()

    yMax = sfHist.GetBinContent(sfHist.GetMaximumBin())

    if plot.yMax == 0:
        #~ yMax = yMax*2.15
        if edgeShape or edgeShapeMC or differentEdgePositions:
            yMax = yMax * 1.75
        else:
            yMax = yMax * 1.5

    else:
        yMax = plot.yMax

    plotPad.DrawFrame(plot.firstBin, 0, plot.lastBin, yMax,
                      "; %s ; %s" % (plot.xaxis, plot.yaxis))

    #set overflow bin
    #~ print sfHist.GetBinContent(sfHist.GetNbinsX()), sfHist.GetBinContent(sfHist.GetNbinsX()+1)
    #~ sfHist.SetBinContent(sfHist.GetNbinsX(),sfHist.GetBinContent(sfHist.GetNbinsX())+sfHist.GetBinContent(sfHist.GetNbinsX()+1))
    #~ sfHist.SetBinError(sfHist.GetNbinsX(),(sfHist.GetBinContent(sfHist.GetNbinsX())+sfHist.GetBinContent(sfHist.GetNbinsX()+1))**0.5)
    #~ ofHist.SetBinContent(ofHist.GetNbinsX(),ofHist.GetBinContent(ofHist.GetNbinsX())+ofHist.GetBinContent(ofHist.GetNbinsX()+1))
    #~ ofHist.SetBinError(ofHist.GetNbinsX(),(ofHist.GetBinContent(ofHist.GetNbinsX())+ofHist.GetBinContent(ofHist.GetNbinsX()+1))**0.5)

    bkgHist = ofHist.Clone("bkgHist")
    if dyHist is not None:
        bkgHist.Add(dyHist)

    sfHist.SetMarkerStyle(20)
    sfHist.SetLineColor(ROOT.kBlack)
    bkgHist.SetLineColor(ROOT.kBlue + 3)
    bkgHist.SetLineWidth(2)

    dyHist.SetLineColor(ROOT.kGreen + 2)
    dyHist.SetFillColor(ROOT.kGreen + 2)
    #~ dyHist.SetFillStyle(3002)

    #~ dyOnlyHist = dyHist.Clone("dyOnlyHist")
    #~ dyOnlyHist.Scale(getattr(getattr(OnlyZPredictions,bSelection).SF,region).val / getattr(getattr(zPredictions,bSelection).SF,region).val)
    #~
    #~ rareBGHist = dyHist.Clone("rareBGHist")
    #~ rareBGHist.Scale(getattr(getattr(OtherPredictions,bSelection).SF,region).val / getattr(getattr(zPredictions,bSelection).SF,region).val)
    #~
    #~ rareBGHist.SetLineColor(ROOT.kViolet+2)
    #~ rareBGHist.SetFillColor(ROOT.kViolet+2)

    from ROOT import THStack

    #~ stack = THStack()
    #~ stack.Add(rareBGHist)
    #~ stack.Add(dyOnlyHist)
    #~
    bkgHistForLegend = bkgHist.Clone("bkgHistForLegend")
    bkgHistForLegend.SetLineColor(ROOT.kBlue + 3)
    bkgHistForLegend.SetFillColor(ROOT.kWhite)
    bkgHistForLegend.SetLineWidth(2)

    latex = ROOT.TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.055)
    latex.SetLineWidth(2)
    latex.SetNDC(True)
    latexCMS = ROOT.TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.05)
    latexCMS.SetNDC(True)
    latexCMSExtra = ROOT.TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.0375)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatex(0.93, 0.942, "%s fb^{-1} (13 TeV)" % runRange.printval)

    latexCMS.DrawLatex(0.19, 0.86, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.81
    else:
        yLabelPos = 0.81

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    if combination == "SF":
        rSFOFErr = getattr(rSFOF, region).err
    elif combination == "EE":
        rSFOFErr = getattr(rEEOF, region).err
    elif combination == "MM":
        rSFOFErr = getattr(rMMOF, region).err

    errGraph, histUp, histDown = getErrHist(plot, combination, region, ofHist,
                                            dyHist, rSFOFErr)
    errGraph.SetFillColor(myColors["MyBlueOverview"])
    errGraph.SetFillStyle(3001)
    #~ errGraph.SetLineColor(myColors["MyDarkBlue"])
    #~ errGraph.SetMarkerColor(myColors["MyDarkBlue"])

    if edgeShape:

        edgeFile = ROOT.TFile("edgeShape.root", "READ")
        edgeHist = ROOT.TH1F()
        edgeHist = edgeFile.Get("edgeHist300__inv")

        edgeHist.Scale(1. / edgeHist.Integral())

        edgeHist500 = edgeFile.Get("edgeHist500__inv")
        edgeHist500.Scale(1. / edgeHist500.Integral())

        edgeHist700 = edgeFile.Get("edgeHist700__inv")
        edgeHist700.Scale(1. / edgeHist700.Integral())

        edgeHist.Scale(342)
        edgeHist.Add(bkgHist.Clone())
        edgeHist.SetLineColor(ROOT.kRed)
        edgeHist.SetLineWidth(2)

        edgeHist500.Scale(484)
        edgeHist500.Add(bkgHist.Clone())
        edgeHist500.SetLineColor(ROOT.kRed)
        edgeHist500.SetLineWidth(2)
        edgeHist500.SetLineStyle(ROOT.kDashed)

        edgeHist700.Scale(654)
        edgeHist700.Add(bkgHist.Clone())
        edgeHist700.SetLineColor(ROOT.kRed)
        edgeHist700.SetLineStyle(ROOT.kDotted)
        edgeHist700.SetLineWidth(2)

        for i in range(1, edgeHist.GetNbinsX() + 1):
            if i >= edgeHist.GetXaxis().FindBin(70.01):
                edgeHist.SetBinContent(i, 0)
                edgeHist500.SetBinContent(i, 0)
                edgeHist700.SetBinContent(i, 0)

    if edgeShapeMC:

        signalPath = locations.signalDataSetPath

        denominatorFile = TFile(
            "../SignalScan/T6bbllsleptonDenominatorHisto.root")
        denominatorHisto = TH2F(denominatorFile.Get("massScan"))

        cutsWithoutSignalScaleFactors = plot.cuts
        plot.cuts = "leptonFullSimScaleFactor1*leptonFullSimScaleFactor2*leptonFastSimScaleFactor1*leptonFastSimScaleFactor2*(%s)" % plot.cuts

        if "Central" in selection.name:
            EETriggerEff = 0.945
            EMuTriggerEff = 0.937
            MuMuTriggerEff = 0.929
            RSFOF = 1.032
        elif "Forward" in selection.name:
            EETriggerEff = 0.943
            EMuTriggerEff = 0.938
            MuMuTriggerEff = 0.916
            RSFOF = 1.092
        else:
            EETriggerEff = 0.949
            EMuTriggerEff = 0.921811
            MuMuTriggerEff = 0.929178
            RSFOF = 1.05

        EEHistSignal450, MMHistSignal450, EMHistSignal450 = getSignalMCHistograms(
            signalPath, plot, runRange,
            "T6bbllslepton_msbottom_450_mneutralino_175")

        denominator = denominatorHisto.GetBinContent(
            denominatorHisto.GetXaxis().FindBin(450),
            denominatorHisto.GetYaxis().FindBin(175))
        xsection = getattr(sbottom_masses, "m_b_450").cross_section13TeV
        scalingLumi = runRange.lumi * xsection / denominator

        EEHistSignal450.Scale(EETriggerEff * scalingLumi)
        MMHistSignal450.Scale(MuMuTriggerEff * scalingLumi)
        EMHistSignal450.Scale(EMuTriggerEff * scalingLumi * RSFOF)

        if combination == "SF":
            edgeHist450 = EEHistSignal450.Clone()
            edgeHist450.Add(MMHistSignal450.Clone())
            edgeHist450.Add(EMHistSignal450.Clone(), -1)
        if combination == "EE":
            edgeHist450 = EEHistSignal450.Clone()
            edgeHist450.Add(EMHistSignal450.Clone(), -0.5)
        if combination == "MM":
            edgeHist450 = MMHistSignal450.Clone()
            edgeHist450.Add(EMHistSignal450.Clone(), -0.5)

        for i in range(0, edgeHist450.GetNbinsX()):
            if edgeHist450.GetBinContent(i) < 0:
                edgeHist450.SetBinContent(i, 0.)

        edgeHist450.Add(bkgHist.Clone())
        edgeHist450.SetLineColor(ROOT.kRed)
        edgeHist450.SetLineWidth(2)

        EEHistSignal550, MMHistSignal550, EMHistSignal550 = getSignalMCHistograms(
            signalPath, plot, runRange,
            "T6bbllslepton_msbottom_550_mneutralino_175")

        denominator = denominatorHisto.GetBinContent(
            denominatorHisto.GetXaxis().FindBin(550),
            denominatorHisto.GetYaxis().FindBin(175))
        xsection = getattr(sbottom_masses, "m_b_550").cross_section13TeV
        scalingLumi = runRange.lumi * xsection / denominator

        EEHistSignal550.Scale(EETriggerEff * scalingLumi)
        MMHistSignal550.Scale(MuMuTriggerEff * scalingLumi)
        EMHistSignal550.Scale(EMuTriggerEff * scalingLumi * RSFOF)

        if combination == "SF":
            edgeHist550 = EEHistSignal550.Clone()
            edgeHist550.Add(MMHistSignal550.Clone())
            edgeHist550.Add(EMHistSignal550.Clone(), -1)
        if combination == "EE":
            edgeHist550 = EEHistSignal550.Clone()
            edgeHist550.Add(EMHistSignal550.Clone(), -0.5)
        if combination == "MM":
            edgeHist550 = MMHistSignal550.Clone()
            edgeHist550.Add(EMHistSignal550.Clone(), -0.5)

        for i in range(0, edgeHist550.GetNbinsX()):
            if edgeHist550.GetBinContent(i) < 0:
                edgeHist550.SetBinContent(i, 0.)

        edgeHist550.Add(bkgHist.Clone())
        edgeHist550.SetLineColor(ROOT.kRed)
        edgeHist550.SetLineWidth(2)
        edgeHist550.SetLineStyle(ROOT.kDashed)

        EEHistSignal650, MMHistSignal650, EMHistSignal650 = getSignalMCHistograms(
            signalPath, plot, runRange,
            "T6bbllslepton_msbottom_650_mneutralino_175")

        denominator = denominatorHisto.GetBinContent(
            denominatorHisto.GetXaxis().FindBin(650),
            denominatorHisto.GetYaxis().FindBin(175))
        xsection = getattr(sbottom_masses, "m_b_650").cross_section13TeV
        scalingLumi = runRange.lumi * xsection / denominator

        EEHistSignal650.Scale(EETriggerEff * scalingLumi)
        MMHistSignal650.Scale(MuMuTriggerEff * scalingLumi)
        EMHistSignal650.Scale(EMuTriggerEff * scalingLumi * RSFOF)

        if combination == "SF":
            edgeHist650 = EEHistSignal650.Clone()
            edgeHist650.Add(MMHistSignal650.Clone())
            edgeHist650.Add(EMHistSignal650.Clone(), -1)
        if combination == "EE":
            edgeHist650 = EEHistSignal650.Clone()
            edgeHist650.Add(EMHistSignal650.Clone(), -0.5)
        if combination == "MM":
            edgeHist650 = MMHistSignal650.Clone()
            edgeHist650.Add(EMHistSignal650.Clone(), -0.5)

        for i in range(0, edgeHist650.GetNbinsX()):
            if edgeHist650.GetBinContent(i) < 0:
                edgeHist650.SetBinContent(i, 0.)

        edgeHist650.Add(bkgHist.Clone())
        edgeHist650.SetLineColor(ROOT.kRed)
        edgeHist650.SetLineWidth(2)
        edgeHist650.SetLineStyle(ROOT.kDotted)

        plot.cuts = cutsWithoutSignalScaleFactors

    if differentEdgePositions:

        signalPath = locations.signalDataSetPath

        denominatorFile = TFile(
            "../SignalScan/T6bbllsleptonDenominatorHisto.root")
        denominatorHisto = TH2F(denominatorFile.Get("massScan"))

        cutsWithoutSignalScaleFactors = plot.cuts
        plot.cuts = "leptonFullSimScaleFactor1*leptonFullSimScaleFactor2*leptonFastSimScaleFactor1*leptonFastSimScaleFactor2*(%s)" % plot.cuts

        if "Central" in selection.name:
            EETriggerEff = 0.945
            EMuTriggerEff = 0.937
            MuMuTriggerEff = 0.929
            RSFOF = 1.032
        elif "Forward" in selection.name:
            EETriggerEff = 0.943
            EMuTriggerEff = 0.938
            MuMuTriggerEff = 0.916
            RSFOF = 1.092
        else:
            EETriggerEff = 0.949
            EMuTriggerEff = 0.921811
            MuMuTriggerEff = 0.929178
            RSFOF = 1.05

        EEHistSignal75, MMHistSignal75, EMHistSignal75 = getSignalMCHistograms(
            signalPath, plot, runRange,
            "T6bbllslepton_msbottom_500_mneutralino_175")

        denominator = denominatorHisto.GetBinContent(
            denominatorHisto.GetXaxis().FindBin(500),
            denominatorHisto.GetYaxis().FindBin(175))
        xsection = getattr(sbottom_masses, "m_b_500").cross_section13TeV
        scalingLumi = runRange.lumi * xsection / denominator

        EEHistSignal75.Scale(EETriggerEff * scalingLumi)
        MMHistSignal75.Scale(MuMuTriggerEff * scalingLumi)
        EMHistSignal75.Scale(EMuTriggerEff * scalingLumi * RSFOF)

        if combination == "SF":
            edgeHist75 = EEHistSignal75.Clone()
            edgeHist75.Add(MMHistSignal75.Clone())
            edgeHist75.Add(EMHistSignal75.Clone(), -1)
        if combination == "EE":
            edgeHist75 = EEHistSignal75.Clone()
            edgeHist75.Add(EMHistSignal75.Clone(), -0.5)
        if combination == "MM":
            edgeHist75 = MMHistSignal75.Clone()
            edgeHist75.Add(EMHistSignal75.Clone(), -0.5)

        for i in range(0, edgeHist75.GetNbinsX()):
            if edgeHist75.GetBinContent(i) < 0:
                edgeHist75.SetBinContent(i, 0.)

        edgeHist75.Add(bkgHist.Clone())
        edgeHist75.SetLineColor(ROOT.kRed)
        edgeHist75.SetLineWidth(2)

        EEHistSignal125, MMHistSignal125, EMHistSignal125 = getSignalMCHistograms(
            signalPath, plot, runRange,
            "T6bbllslepton_msbottom_500_mneutralino_225")

        denominator = denominatorHisto.GetBinContent(
            denominatorHisto.GetXaxis().FindBin(500),
            denominatorHisto.GetYaxis().FindBin(225))
        xsection = getattr(sbottom_masses, "m_b_500").cross_section13TeV
        scalingLumi = runRange.lumi * xsection / denominator

        EEHistSignal125.Scale(EETriggerEff * scalingLumi)
        MMHistSignal125.Scale(MuMuTriggerEff * scalingLumi)
        EMHistSignal125.Scale(EMuTriggerEff * scalingLumi * RSFOF)

        if combination == "SF":
            edgeHist125 = EEHistSignal125.Clone()
            edgeHist125.Add(MMHistSignal125.Clone())
            edgeHist125.Add(EMHistSignal125.Clone(), -1)
        if combination == "EE":
            edgeHist125 = EEHistSignal125.Clone()
            edgeHist125.Add(EMHistSignal125.Clone(), -0.5)
        if combination == "MM":
            edgeHist125 = MMHistSignal125.Clone()
            edgeHist125.Add(EMHistSignal125.Clone(), -0.5)

        for i in range(0, edgeHist125.GetNbinsX()):
            if edgeHist125.GetBinContent(i) < 0:
                edgeHist125.SetBinContent(i, 0.)

        edgeHist125.Add(bkgHist.Clone())
        edgeHist125.SetLineColor(ROOT.kRed)
        edgeHist125.SetLineWidth(2)
        edgeHist125.SetLineStyle(ROOT.kDashed)

        EEHistSignal200, MMHistSignal200, EMHistSignal200 = getSignalMCHistograms(
            signalPath, plot, runRange,
            "T6bbllslepton_msbottom_500_mneutralino_300")

        denominator = denominatorHisto.GetBinContent(
            denominatorHisto.GetXaxis().FindBin(500),
            denominatorHisto.GetYaxis().FindBin(300))
        xsection = getattr(sbottom_masses, "m_b_500").cross_section13TeV
        scalingLumi = runRange.lumi * xsection / denominator

        EEHistSignal200.Scale(EETriggerEff * scalingLumi)
        MMHistSignal200.Scale(MuMuTriggerEff * scalingLumi)
        EMHistSignal200.Scale(EMuTriggerEff * scalingLumi * RSFOF)

        if combination == "SF":
            edgeHist200 = EEHistSignal200.Clone()
            edgeHist200.Add(MMHistSignal200.Clone())
            edgeHist200.Add(EMHistSignal200.Clone(), -1)
        if combination == "EE":
            edgeHist200 = EEHistSignal200.Clone()
            edgeHist200.Add(EMHistSignal200.Clone(), -0.5)
        if combination == "MM":
            edgeHist200 = MMHistSignal200.Clone()
            edgeHist200.Add(EMHistSignal200.Clone(), -0.5)

        for i in range(0, edgeHist200.GetNbinsX()):
            if edgeHist200.GetBinContent(i) < 0:
                edgeHist200.SetBinContent(i, 0.)

        edgeHist200.Add(bkgHist.Clone())
        edgeHist200.SetLineColor(ROOT.kRed)
        edgeHist200.SetLineWidth(2)
        edgeHist200.SetLineStyle(ROOT.kDotted)

        plot.cuts = cutsWithoutSignalScaleFactors

    #~ lines = getLines(0, sfHist.GetBinContent(sfHist.GetMaximumBin())+10,xPos=[mllBins.lowMass.high,mllBins.onZ.low,mllBins.onZ.high, mllBins.highMass.low ])
    #~ for line in lines:
    #~ line.Draw()
    if edgeShape or edgeShapeMC:
        leg = TLegend(0.55, 0.4, 0.92, 0.91, "", "brNDC")
    elif differentEdgePositions:
        leg = TLegend(0.55, 0.4, 0.95, 0.92, "", "brNDC")
    else:
        leg = TLegend(0.6, 0.5, 0.95, 0.92, "", "brNDC")

    leg.SetFillColor(10)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    from ROOT import TH1F, kWhite
    legendHistDing = TH1F()
    legendHistDing.SetFillColor(kWhite)
    if region == "inclusive":
        leg.AddEntry(legendHistDing, "Inclusive signal region", "h")
    elif region == "central":
        leg.AddEntry(legendHistDing, "Legacy signal region", "h")
    elif region == "forward":
        leg.AddEntry(legendHistDing, "Forward signal region", "h")
    leg.AddEntry(sfHist, "Data", "pe1")
    #~ leg.AddEntry(bkgHist, "Total background","l")
    leg.AddEntry(bkgHistForLegend, "Flavor symmetric", "f")
    leg.AddEntry(dyHist, "Drell-Yan", "f")
    #~ leg.AddEntry(dyOnlyHist,"Z+jets", "f")
    #~ leg.AddEntry(rareBGHist,"Other SM", "f")
    leg.AddEntry(errGraph, "Total uncertainty", "f")

    if edgeShape:
        leg.AddEntry(legendHistDing, "Scaled 8 TeV signal fit:", "h")
        leg.AddEntry(edgeHist, "m_{#tilde{b}} = 300 GeV hypothesis", "l")
        leg.AddEntry(edgeHist500, "m_{#tilde{b}} = 500 GeV hypothesis", "l")
        leg.AddEntry(edgeHist700, "m_{#tilde{b}} = 700 GeV hypothesis", "l")

    if edgeShapeMC:
        leg.AddEntry(legendHistDing, "Slepton signal model", "h")
        leg.AddEntry(
            edgeHist450,
            "m_{#tilde{b}} = 450 GeV, m_{#tilde{#chi}_{2}^{0}} = 175 GeV", "l")
        leg.AddEntry(
            edgeHist550,
            "m_{#tilde{b}} = 550 GeV, m_{#tilde{#chi}_{2}^{0}} = 175 GeV", "l")
        leg.AddEntry(
            edgeHist650,
            "m_{#tilde{b}} = 650 GeV, m_{#tilde{#chi}_{2}^{0}} = 175 GeV", "l")

    if differentEdgePositions:
        leg.AddEntry(legendHistDing,
                     "Slepton signal model, m_{#tilde{b}} = 500 GeV", "h")
        leg.AddEntry(edgeHist75, "75 GeV edge position", "l")
        leg.AddEntry(edgeHist125, "125 GeV edge position", "l")
        leg.AddEntry(edgeHist200, "200 GeV edge position", "l")

    leg.Draw("same")

    errGraph.Draw("SAME02")

    if edgeShape:
        edgeHist.Draw("samehist")
        edgeHist500.Draw("samehist")
        edgeHist700.Draw("samehist")

    if edgeShapeMC:
        edgeHist450.Draw("samehist")
        edgeHist550.Draw("samehist")
        edgeHist650.Draw("samehist")

    if differentEdgePositions:
        edgeHist75.Draw("samehist")
        edgeHist125.Draw("samehist")
        edgeHist200.Draw("samehist")

    bkgHist.Draw("samehist")

    dyHist.Draw("samehist")
    #~ stack.Draw("samehist")
    sfHist.Draw("samepe1")

    plotPad.RedrawAxis()

    ratioPad.cd()

    ratioGraphs = ratios.RatioGraph(sfHist,
                                    bkgHist,
                                    xMin=plot.firstBin,
                                    xMax=plot.lastBin,
                                    title="#frac{Data}{Prediction}  ",
                                    yMin=0.0,
                                    yMax=2,
                                    ndivisions=10,
                                    color=ROOT.kBlack,
                                    adaptiveBinning=1000)
    ratioGraphs.addErrorByHistograms("rSFOF",
                                     histUp,
                                     histDown,
                                     color=myColors["MyBlue"],
                                     fillStyle=3001)

    ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8)

    #~ leg2 = TLegend(0.175, 0.78, 0.475, 0.9,"","brNDC")
    #~ leg2.SetFillColor(10)
    #~ leg2.SetLineColor(10)
    #~ leg2.SetShadowColor(0)
    #~ leg2.SetBorderSize(1)
    #~ leg2.AddEntry(errGraph,"Systematic uncert.", "f")
    #~ leg2.Draw("same")

    ROOT.gPad.RedrawAxis()
    plotPad.RedrawAxis()
    ratioPad.RedrawAxis()

    if edgeShape:
        hCanvas.Print("fig/mllResult_%s_%s_%s_edgeShape.pdf" %
                      (selection.name, runRange.label, combination))
    elif edgeShapeMC:
        hCanvas.Print("fig/mllResult_%s_%s_%s_edgeShapeMC.pdf" %
                      (selection.name, runRange.label, combination))
    elif differentEdgePositions:
        hCanvas.Print(
            "fig/mllResult_%s_%s_%s_edgeShapeMC_differentEdgePositions.pdf" %
            (selection.name, runRange.label, combination))
    else:
        hCanvas.Print("fig/mllResult_%s_%s_%s.pdf" %
                      (selection.name, runRange.label, combination))
Пример #13
0
rp0.GetUpperPad().SetPad(pm * f, sf, 1. - pm * f, 1. - pm)
rp0.GetLowerPad().SetPad(pm * f, pm, 1. - pm * f, sf)

rp0.GetUpperPad().cd()

gPad.SetLogy()

h0.Draw("e same")
h1.Draw("e same")
h2.Draw("e same")

legend = TLegend(0.60, 0.60, 0.88, 0.85)
legend.SetFillColor(0)
#legend.SetFillStyle(0)
legend.SetLineColor(0)
legend.SetShadowColor(10)
#legend.SetTextSize(0.030)

rp0.GetLowerPad().cd()

g0 = rp0.GetLowerRefGraph()
g0.SetMinimum(minratio)
g0.SetMaximum(maxratio)
g0.SetLineColor(ROOT.kBlue - 10)
g0.SetFillColor(ROOT.kBlue - 10)

redGraph(h0, g0)
redGraph(h1, g1)
redGraph(h2, g2)

g0.Draw("e3")
Пример #14
0
class plotTogether:
    tfiles = {}
    lgx = 0.65
    lgy = 0.4

    def __init__(self):
        self.unctitle = ''
        self.MCplots = []
        self.DAplots = []
        self.NOplots = []
        self.Otherplots = []
        self.DIVplots = []
        self.Canvases = []
        self.Pads = []
        self.unc = False
        ROOT.gStyle.SetOptFit(0)
        ROOT.gStyle.SetOptStat(0)
        ROOT.gStyle.SetPadTickX(0)
        ROOT.gStyle.SetPadTickY(0)
        ROOT.gStyle.SetOptStat(0)
        ROOT.gStyle.SetOptStat(0)

        ROOT.gStyle.SetPadTopMargin(0.05)
        ROOT.gStyle.SetPadRightMargin(0.05)
        ROOT.gStyle.SetPadBottomMargin(0.15)
        ROOT.gStyle.SetPadLeftMargin(0.15)

        ROOT.gStyle.SetLabelFont(43, "x")
        ROOT.gStyle.SetLabelFont(43, "y")
        ROOT.gStyle.SetLabelFont(43, "z")
        ROOT.gStyle.SetLabelOffset(0.01, "x")
        ROOT.gStyle.SetLabelOffset(0.01, "y")
        ROOT.gStyle.SetLabelOffset(0.01, "z")
        ROOT.gStyle.SetLabelSize(25, "x")
        ROOT.gStyle.SetLabelSize(25, "y")
        ROOT.gStyle.SetLabelSize(25, "z")
        ROOT.gStyle.SetTitleFont(43, "x")
        ROOT.gStyle.SetTitleFont(43, "y")
        ROOT.gStyle.SetTitleFont(43, "z")
        ROOT.gStyle.SetTitleOffset(1.2, "x")
        ROOT.gStyle.SetTitleOffset(1.5, "y")
        ROOT.gStyle.SetTitleOffset(1.1, "z")
        ROOT.gStyle.SetTitleSize(30, "x")
        ROOT.gStyle.SetTitleSize(30, "y")
        ROOT.gStyle.SetTitleSize(30, "z")

    def legend(self, legtitle):
        xpos = 1. - ROOT.gPad.GetRightMargin()
        ypos = 1. - ROOT.gPad.GetTopMargin()
        #self.lg = TLegend(0.55, 0.4, xpos-0.02, ypos-0.02)
        self.lg = TLegend(self.lgx, self.lgy, xpos - 0.02, ypos - 0.02)
        if len(legtitle) != 0:
            self.lg.SetHeader(legtitle)
        self.lg.SetFillColor(0)
        self.lg.SetFillStyle(0)
        self.lg.SetLineColor(0)
        self.lg.SetLineStyle(0)
        self.lg.SetBorderSize(0)
        self.lg.SetShadowColor(0)
        self.lg.SetTextFont(42)
        self.lg.SetTextSize(0.07)

    def printLatexYieldTable(self, fname='yield_table.tex'):
        ''' This function will print a table based on how the addMCplot and addDAplot functions were called.
	        It will sum over all files that have no title, and assing them to the previous title. So for example:
	           plot[p].addMCplot(DYfile, p, 'V+Jets', DYscale, ROOT.kGreen+2, projection = pro)
	           plot[p].addMCplot(Wfile, p, '', Wscale, ROOT.kGreen+2, projection = pro)
	        will create a category 'V+Jets' that includes DY and W+jets events stored in DYfile and Wfile.
	        A call to this function should be added just after a call to drawAddWithRatio for that particular histogram, and then, for example:
	           can = plot[p].drawAddWithRatio( ....... 
	           if (p == "RECO/all_njets"):
	                 plot[p].printLatexYieldTable('totyield_table.tex' 
	        '''
        MCtot = 0.
        MCtot_err = 0.
        category_yield = []
        category_err = []
        category_title = []
        cat_yield = 0.
        cat_err = 0.
        for index, hist in enumerate(self.MCplots):
            if hist.GetTitle() != '':
                category_title.append(hist.GetTitle())
                cat_yield = 0.
                cat_err = 0.
            err = ROOT.Double(0)
            # Make sure you run this over a histogram with known under- and overflows!
            # For example number of jets, or MET, anything that hasn't been initialized to -9
            events = hist.IntegralAndError(0, hist.GetNbinsX() + 1, err)
            #events = hist.Integral()
            cat_yield += events
            cat_err = math.sqrt(cat_err * cat_err + err * err)
            if len(self.MCplots
                   ) == index + 1 or self.MCplots[index + 1].GetTitle() != '':
                category_yield.append(cat_yield)
                category_err.append(cat_err)
            MCtot += events
            MCtot_err = math.sqrt(MCtot_err * MCtot_err + err * err)

    # Ready to print the numbers, first open the latex file:
        latexfile = open(fname, "w")
        latexfile.write(
            "\\begin{tabular}{l|r@{$\\pm$}l} \\hline \n")  # r@{$\pm$}l
        latexfile.write("%-12s & %20s \\\\ \\hline \n" %
                        ('Source', '\multicolumn{2}{c}{Yield}'))
        for i in range(len(category_title)):
            print "%-12s %5.1f +- %4.1f" % (category_title[i],
                                            category_yield[i], category_err[i])
            latexfile.write(
                "%-12s & %5.1f & %4.1f \\\\ \n" %
                (category_title[i], category_yield[i], category_err[i]))

        print "%-12s %5.1f +- %4.1f" % ('BKG SUM ', MCtot, MCtot_err)
        latexfile.write("%-12s & %5.1f & %4.1f\\\\ \\hline \n" %
                        ('BKG SUM ', MCtot, MCtot_err))

        DAtot = 0.
        for hist in self.DAplots:
            DAtot += hist.Integral()
        print "%-12s %5i" % ('Data ', DAtot)
        latexfile.write("%-12s & \multicolumn{2}{c}{%5i} \\\\ \n" %
                        ('Data ', DAtot))
        latexfile.write("\\end{tabular} \n")
        latexfile.close()
        print "Wrote LaTeX table with yields in: ", fname
        print "The errors are obtained from ROOT::TH1::IntegralAndError() and added in quadrature per category"
        return [DAtot, MCtot, MCtot_err]

    def addMCplot(self,
                  filename,
                  histpath,
                  title,
                  scale,
                  color,
                  projection=''):
        if filename not in self.tfiles:
            self.tfiles[filename] = TFile(filename, 'read')
        if projection == 'Y':
            self.MCplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionY()))
        elif projection == 'X':
            self.MCplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionX()))
        elif projection.startswith('Xbin:'):
            bins = projection.split('Xbin:')[-1].split('-')
            self.MCplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionX(
                    histpath.split('/')[-1] + '_myproX', int(bins[0]),
                    int(bins[1]))))
        elif projection.startswith('Ybin:'):
            bins = projection.split('Ybin:')[-1].split('-')
            self.MCplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionX(
                    histpath.split('/')[-1] + '_myproY', int(bins[0]),
                    int(bins[1]))))
        else:
            self.MCplots.append(TH1D(self.tfiles[filename].Get(histpath)))
        self.MCplots[-1].SetFillColor(color)
        self.MCplots[-1].SetLineColor(color)
        #self.MCplots[-1].Scale(scale, 'width')
        self.MCplots[-1].Scale(scale)
        self.MCplots[-1].SetTitle(title)

    def setUncTitle(self, unctitle):
        self.unctitle = unctitle

    def addUncerHist(self, fcentral, ferrdown, ferrup, hist, projection=''):
        if self.unc == False:
            self.herr = TH1D(self.DAplots[-1])
            self.herr.Reset()
            self.herr.SetName('err')
            self.unc = True
        if fcentral not in self.tfiles:
            self.tfiles[fcentral] = TFile(fcentral, 'read')
        if ferrdown not in self.tfiles:
            self.tfiles[ferrdown] = TFile(ferrdown, 'read')
        if ferrup not in self.tfiles:
            self.tfiles[ferrup] = TFile(ferrup, 'read')

        hcen = self.tfiles[fcentral].Get(hist)
        hdown = self.tfiles[ferrdown].Get(hist)
        hup = self.tfiles[ferrup].Get(hist)
        if projection == 'Y':
            hcen = TH1D(hcen.ProjectionY())
            hdown = TH1D(hdown.ProjectionY())
            hup = TH1D(hup.ProjectionY())
        if projection == 'X':
            hcen = TH1D(hcen.ProjectionX())
            hdown = TH1D(hdown.ProjectionX())
            hup = TH1D(hup.ProjectionX())
        elif projection.startswith('Xbin:'):
            bins = projection.split('Xbin:')[-1].split('-')
            hcen = TH1D(
                hcen.ProjectionX(
                    hist.split('/')[-1] + '_myproX', int(bins[0]),
                    int(bins[1])))
            hdown = TH1D(
                hdown.ProjectionX(
                    hist.split('/')[-1] + '_myproX', int(bins[0]),
                    int(bins[1])))
            hup = TH1D(
                hup.ProjectionX(
                    hist.split('/')[-1] + '_myproX', int(bins[0]),
                    int(bins[1])))
        elif projection.startswith('Ybin:'):
            bins = projection.split('Ybin:')[-1].split('-')
            hcen = TH1D(
                hcen.ProjectionY(
                    hist.split('/')[-1] + '_myproY', int(bins[0]),
                    int(bins[1])))
            hdown = TH1D(
                hdown.ProjectionY(
                    hist.split('/')[-1] + '_myproY', int(bins[0]),
                    int(bins[1])))
            hup = TH1D(
                hup.ProjectionY(
                    hist.split('/')[-1] + '_myproY', int(bins[0]),
                    int(bins[1])))

        for b in range(1, 1 + self.herr.GetNbinsX()):
            cen = hcen.GetBinContent(b)
            if cen == 0:
                continue
            up = hup.GetBinContent(b)
            down = hdown.GetBinContent(b)
            old = self.herr.GetBinContent(b)

            errA = (up - cen) / cen
            errB = (down - cen) / cen
            err = math.sqrt((errA**2 + errB**2) / 2.)
            #err = max(abs(errA), abs(errB))

            self.herr.SetBinContent(b, math.sqrt(old**2 + err**2))

    def addUncerVal(self, val):
        if self.unc == False:
            self.herr = TH1D(self.DAplots[-1])
            self.herr.Reset()
            self.herr.SetName('err')
            self.unc = True
        for b in range(1, 1 + self.herr.GetNbinsX()):
            old = self.herr.GetBinContent(b)
            self.herr.SetBinContent(b, math.sqrt(old**2 + val**2))

    def addDAplot(self, filename, histpath, title, projection='', scale=1.):
        if filename not in self.tfiles:
            self.tfiles[filename] = TFile(filename, 'read')
        if projection == 'Y':
            self.DAplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionY()))
        elif projection == 'X':
            self.DAplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionX()))
        elif projection.startswith('Xbin:'):
            bins = projection.split('Xbin:')[-1].split('-')
            self.DAplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionX(
                    histpath.split('/')[-1] + '_myproX', int(bins[0]),
                    int(bins[1]))))
        elif projection.startswith('Ybin:'):
            bins = projection.split('Ybin:')[-1].split('-')
            self.DAplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionX(
                    histpath.split('/')[-1] + '_myproY', int(bins[0]),
                    int(bins[1]))))
        else:
            self.DAplots.append(TH1D(self.tfiles[filename].Get(histpath)))
        self.DAplots[-1].SetTitle(title)
        self.DAplots[-1].Scale(scale)
        #self.DAplots[-1].Scale(1., 'width')
        self.DAplots[-1].Scale(1.)

    def addOtherplot(self,
                     filename,
                     histpath,
                     title,
                     scale,
                     color,
                     projection=''):
        if filename not in self.tfiles:
            self.tfiles[filename] = TFile(filename, 'read')
        if projection == 'Y':
            self.Otherplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionY()))
        elif projection == 'X':
            self.Otherplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionX()))
        else:
            self.Otherplots.append(TH1D(self.tfiles[filename].Get(histpath)))
        #self.NOplots[-1].SetFillColor(color)
        self.Otherplots[-1].SetLineColor(color)
        self.Otherplots[-1].SetTitle(title)
        self.Otherplots[-1].Scale(scale)

    def addNormplot(self, filename, histpath, title, color, projection=''):
        if filename not in self.tfiles:
            self.tfiles[filename] = TFile(filename, 'read')
        if projection == 'Y':
            self.NOplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionY()))
        elif projection == 'X':
            self.NOplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionX()))
        else:
            self.NOplots.append(TH1D(self.tfiles[filename].Get(histpath)))
        #self.NOplots[-1].SetFillColor(color)
        self.NOplots[-1].SetLineColor(color)
        self.NOplots[-1].SetTitle(title)

    def drawAddWithRatio(self,
                         options='hist',
                         rebin=1,
                         legtitle='',
                         title='DEFAULT',
                         ratio=False,
                         rangemin=0.,
                         rangemax=0.,
                         printbinwidth=True,
                         xtitle='',
                         ytitle='',
                         logy=False,
                         xlabels=[]):
        self.cumaddhist = []
        self.cumaddhist.append(TH1D(self.MCplots[0]))
        for hist in self.MCplots[1:]:
            self.cumaddhist.append(TH1D(self.cumaddhist[-1]))
            self.cumaddhist[-1].Add(hist)
            self.cumaddhist[-1].SetFillColor(hist.GetFillColor())
            self.cumaddhist[-1].SetLineColor(hist.GetLineColor())
            self.cumaddhist[-1].SetTitle(hist.GetTitle())

        totalevents = 0.
        for hist in self.MCplots:
            if rangemin != rangemax:
                hist.GetXaxis().SetRangeUser(rangemin, rangemax)
            totalevents += hist.Integral()
        print 'Total MC events: ', totalevents
        totalevents = 0.
        for hist in self.DAplots:
            if rangemin != rangemax:
                hist.GetXaxis().SetRangeUser(rangemin, rangemax)
            totalevents += hist.Integral()
        print 'Total DA events: ', totalevents
        mymax = 0.
        self.Canvases.append(
            TCanvas('CanvasAdd_' + self.cumaddhist[-1].GetName(),
                    'CanvasAdd_' + self.cumaddhist[-1].GetName(), 800, 600))
        if ratio == True:
            split = 0.3
            spaceleft = 0.15
            spaceright = 0.05
            self.Pads.append(TPad("histpad", "histpad", 0, split, 1., 1.))
            self.Pads[-1].SetTopMargin(0.05)
            self.Pads[-1].SetBottomMargin(0.022)
            self.Pads[-1].SetLeftMargin(spaceleft)
            self.Pads[-1].SetRightMargin(spaceright)
            self.Pads[-1].Draw()
            self.Canvases[-1].cd()
            self.Pads.append(TPad("divpad", "divpad", 0, 0, 1., split))
            self.Pads[-1].SetTopMargin(0.0)
            self.Pads[-1].SetBottomMargin(0.4)
            self.Pads[-1].SetLeftMargin(spaceleft)
            self.Pads[-1].SetRightMargin(spaceright)
            self.Pads[-1].Draw()
            self.Pads[-2].cd()

        if len(title) > 0:
            ROOT.gPad.SetTopMargin(0.1)
        self.legend(legtitle)
        if len(xlabels) != 0:
            b = 0
            for label in xlabels:
                b += 1
                self.cumaddhist[-1].GetXaxis().SetBinLabel(b, label)
        if ratio == True:
            self.cumaddhist[-1].GetXaxis().SetTitleOffset(5.)
            self.cumaddhist[-1].GetXaxis().SetLabelOffset(5.)

        for hist in reversed(self.cumaddhist):
            hist.Rebin(rebin)
            hist.Draw(options)

            mymax = max(mymax, hist.GetMaximum())
            if rangemin != 0 or rangemax != 0:
                hist.GetXaxis().SetRangeUser(rangemin, rangemax)
            if 'same' not in options:
                if self.unc:
                    self.herr.Rebin(rebin)
                    self.herr.Scale(1. / rebin)
                    self.errprint = TH1D(hist)
                    self.errprint.SetName('errprint')
                    for b in range(1, self.errprint.GetNbinsX() + 1):
                        self.errprint.SetBinError(
                            b,
                            self.herr.GetBinContent(b) * hist.GetBinContent(b))
                    self.errprint.SetFillColor(1)
                    self.errprint.SetLineColor(1)
                    self.errprint.SetFillStyle(3354)
                    self.errprint.Draw('E2same')
                units = re.findall('\[.*\]', hist.GetXaxis().GetTitle())
                unit = ''
                if len(units) == 1:
                    unit = units[0][1:-1]
                if ytitle == '':
                    if len(hist.GetYaxis().GetTitle()) == 0:
                        ytitle = 'Events'
                    else:
                        ytitle = hist.GetYaxis().GetTitle()
                        #ytitle = ytitle.lower()
                if printbinwidth == True:
                    hist.GetYaxis().SetTitle(
                        ytitle +
                        ' / {0:g}'.format(hist.GetXaxis().GetBinWidth(1)) +
                        ' ' + unit)
                else:
                    hist.GetYaxis().SetTitle(ytitle)
                if (xtitle != ''):
                    hist.GetXaxis().SetTitle(xtitle)
                options += ' same'
        for np in self.NOplots:
            np.Rebin(rebin)
            np.Scale(self.DAplots[0].Integral() / np.Integral())
            np.SetLineWidth(2)
            np.Draw('sameE0')
            mymax = max(mymax, np.GetMaximum())
        for op in self.Otherplots:
            op.Rebin(rebin)
            op.SetLineWidth(2)
            op.Draw('sameE0')
            mymax = max(mymax, op.GetMaximum())
        if len(self.DAplots) == 1:
            self.DAplots[0].Rebin(rebin)
            self.DAplots[0].SetMarkerStyle(20)
            self.DAplots[0].SetMarkerSize(1.1)
            self.DAplots[0].SetLineWidth(2)
            self.DAplots[0].Draw('E1X0same')
            mymax = max(mymax, self.DAplots[0].GetMaximum())
        if len(self.DAplots) == 1:
            self.lg.AddEntry(self.DAplots[0], self.DAplots[0].GetTitle(), 'p')
        for hist in reversed(self.cumaddhist):
            if len(hist.GetTitle()) != 0:
                self.lg.AddEntry(hist, hist.GetTitle(), 'f')
        for np in self.NOplots:
            self.lg.AddEntry(np, np.GetTitle() + ' (Scaled)', 'l')
        for op in self.Otherplots:
            self.lg.AddEntry(op, op.GetTitle(), 'l')
        if len(self.unctitle) != 0:
            self.lg.AddEntry(self.errprint, self.unctitle, 'f')
        self.lg.Draw()
        #self.settitle(title)
        settitle(title)
        setchannel()
        cmstext()
        if logy == False:
            self.cumaddhist[-1].GetYaxis().SetRangeUser(0, mymax * 1.5)
        if logy == True:
            self.cumaddhist[-1].GetYaxis().SetRangeUser(10, mymax * 50)
            self.Pads[-2].SetLogy(True)

        self.Pads[-2].RedrawAxis()
        if ratio == True:
            self.Pads[-1].cd()
            self.Pads[-1].SetGridy()
            self.DIVplots.append(TH1D(self.DAplots[0]))
            if (xtitle != ''):
                self.DIVplots[-1].GetXaxis().SetTitle(xtitle)
            self.DIVplots[-1].GetXaxis().SetTitle(
                self.DIVplots[-1].GetXaxis().GetTitle().replace(
                    'additional', 'Additional'))
            #self.DIVplots[-1].Divide(self.cumaddhist[-1])
            for b in range(1, self.DIVplots[-1].GetNbinsX() + 1):
                if (self.cumaddhist[-1].GetBinContent(b) > 0.):
                    divval = self.DIVplots[-1].GetBinContent(
                        b) / self.cumaddhist[-1].GetBinContent(b)
                    divvalerr = self.DIVplots[-1].GetBinError(
                        b) / self.cumaddhist[-1].GetBinContent(b)
                    self.DIVplots[-1].SetBinContent(b, divval)
                    #self.DIVplots[-1].SetBinError(b, divvalerr)
                    self.DIVplots[-1].SetBinError(
                        b,
                        math.sqrt(divvalerr**2 +
                                  (self.cumaddhist[-1].GetBinError(b) /
                                   self.cumaddhist[-1].GetBinContent(b))**2))
                else:
                    self.DIVplots[-1].SetBinContent(b, 0.)
                    self.DIVplots[-1].SetBinError(b, 0.)
            self.DIVplots[-1].SetMarkerSize(1.1)
            if len(xlabels) != 0:
                b = 0
                for label in xlabels:
                    b += 1
                    self.DIVplots[-1].GetXaxis().SetBinLabel(b, label)
            self.DIVplots[-1].Draw('E1X0same')
            self.DIVplots[-1].GetXaxis().SetTitleOffset(3)
            self.DIVplots[-1].GetYaxis().SetTitle('#frac{Data}{Simulation} ')
            self.DIVplots[-1].GetYaxis().SetTitleOffset(1.3)
            self.DIVplots[-1].GetYaxis().SetRangeUser(0.5, 1.5)
            self.DIVplots[-1].GetYaxis().SetNdivisions(105)
            if rangemin != 0 or rangemax != 0:
                self.DIVplots[-1].GetXaxis().SetRangeUser(rangemin, rangemax)
            if self.unc:
                self.errprintratio = TH1D(self.herr)
                for b in range(1, self.errprintratio.GetNbinsX() + 1):
                    self.errprintratio.SetBinError(b,
                                                   self.herr.GetBinContent(b))
                    self.errprintratio.SetBinContent(b, 1.)
                self.errprintratio.SetFillColor(1)
                self.errprintratio.SetFillStyle(3354)
                self.errprintratio.Draw('E2same')
            self.DIVplots[-1].Draw('E1X0same')
        self.Pads[-1].RedrawAxis()

        return (self.Canvases[-1])
g_reco_eff.SetMarkerSize(1.5)
g_reco_eff_data.Draw("PL")
g_data_eff.Draw("PL")
g_data_eff.SetLineColor(kRed + 1)
g_data_eff.SetLineWidth(2)
g_data_eff.SetMarkerStyle(4)
g_data_eff.SetLineStyle(2)
g_reco_eff_data.SetLineColor(kGray + 2)
g_reco_eff_data.SetLineWidth(2)
g_reco_eff_data.SetMarkerStyle(30)
g_reco_eff_data.SetMarkerSize(1.5)
g_reco_eff_data.SetLineStyle(2)

l = TLegend(0.46, 0.16, 0.85, 0.425)
l.SetBorderSize(0)
l.SetShadowColor(0)

l.AddEntry(g_purity, "Purity #it{P}", "lp")
l.AddEntry(g_acceptance, "Acceptance #it{A}", "lp")

l.AddEntry(g_eff, "MuCS-MC tagging efficiency #it{#epsilon}_{tag}^{MuCS-MC}",
           "lp")
l.AddEntry(g_data_eff, "Data tagging efficiency #it{#epsilon}_{tag}^{data}",
           "lp")

l.AddEntry(g_reco_eff,
           "MuCS-MC reconstruction efficiency #it{#epsilon}_{MuCS-MC}", "lp")
l.AddEntry(g_reco_eff_data,
           "Data reconstruction efficiency #it{#epsilon}_{data}", "lp")

l.Draw()
def comparePtRes(trackType):

    file2016B = open("default2016Pt/PtResolutionVsPt_%s_B.pkl" % trackType,
                     'rb')
    file2016O = open("default2016Pt/PtResolutionVsPt_%s_O.pkl" % trackType,
                     'rb')
    file2016E = open("default2016Pt/PtResolutionVsPt_%s_E.pkl" % trackType,
                     'rb')
    file2017B = open("defaultPtSplit/PtResolutionVsPt_%s_B.pkl" % trackType,
                     'rb')
    file2017O = open("defaultPtSplit/PtResolutionVsPt_%s_O.pkl" % trackType,
                     'rb')
    file2017E = open("defaultPtSplit/PtResolutionVsPt_%s_E.pkl" % trackType,
                     'rb')
    file2018B = open("default2018Pt/PtResolutionVsPt_%s_B.pkl" % trackType,
                     'rb')
    file2018O = open("default2018Pt/PtResolutionVsPt_%s_O.pkl" % trackType,
                     'rb')
    file2018E = open("default2018Pt/PtResolutionVsPt_%s_E.pkl" % trackType,
                     'rb')

    results2016B = pickle.load(file2016B)
    results2016O = pickle.load(file2016O)
    results2016E = pickle.load(file2016E)

    results2017B = pickle.load(file2017B)
    results2017O = pickle.load(file2017O)
    results2017E = pickle.load(file2017E)

    results2018B = pickle.load(file2018B)
    results2018O = pickle.load(file2018O)
    results2018E = pickle.load(file2018E)

    graph2016B = getGraph(results2016B, "2016B")
    graph2016O = getGraph(results2016O, "2016O")
    graph2016E = getGraph(results2016E, "2016E")

    graph2017B = getGraph(results2017B, "2017B")
    graph2017O = getGraph(results2017O, "2017O")
    graph2017E = getGraph(results2017E, "2017E")

    graph2018B = getGraph(results2018B, "2018B")
    graph2018O = getGraph(results2018O, "2018O")
    graph2018E = getGraph(results2018E, "2018E")

    canv = TCanvas("c1", "c1", 800, 1200)

    plotPad = TPad("plotPad", "plotPad", 0, 0., 1, 1)
    # ~ ratioPad = TPad("ratioPad","ratioPad",0,0.,1,0.3)
    style = setTDRStyle()
    gStyle.SetOptStat(0)
    plotPad.UseCurrentStyle()
    # ~ ratioPad.UseCurrentStyle()
    plotPad.Draw()
    # ~ ratioPad.Draw()
    plotPad.cd()
    plotPad.cd()
    plotPad.SetGrid()
    gStyle.SetTitleXOffset(1.45)
    gStyle.SetTitleYOffset(1.55)

    xMax = 0.15
    if trackType == "Inner":
        xMax = 0.3
    if trackType == "Outer":
        xMax = 0.5

    plotPad.DrawFrame(0, 0, 2000, xMax, ";p_{T} [GeV]; p_{T} resolution [%]")

    graph2016B.Draw("samepe")
    # ~ graph2016O.Draw("samepe")
    graph2016E.Draw("samepe")
    graph2016B.SetLineColor(kRed)
    graph2016B.SetMarkerColor(kRed)
    graph2016O.SetLineColor(kGreen)
    graph2016O.SetMarkerColor(kGreen)
    graph2016E.SetLineColor(kBlue)
    graph2016E.SetMarkerColor(kBlue)

    latex = TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatex(0.95, 0.96, "(13 TeV)")

    cmsExtra = "#splitline{Preliminary}{}"
    latexCMS.DrawLatex(0.19, 0.88, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.81
    else:
        yLabelPos = 0.84

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s 2016" % trackType, "brNDC")
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    leg.AddEntry(graph2016B, "Barrel", "l")
    # ~ leg.AddEntry(graph2016O,"Overlap","l")
    leg.AddEntry(graph2016E, "Endcap", "l")

    leg.Draw()

    plotPad.RedrawAxis()

    canv.Print("PtResolutionCompare_%s_2016.pdf" % trackType)
    canv.Print("PtResolutionCompare_%s_2016.root" % trackType)

    canv = TCanvas("c1", "c1", 800, 1200)

    plotPad = TPad("plotPad", "plotPad", 0, 0., 1, 1)
    # ~ ratioPad = TPad("ratioPad","ratioPad",0,0.,1,0.3)
    style = setTDRStyle()
    gStyle.SetOptStat(0)
    plotPad.UseCurrentStyle()
    # ~ ratioPad.UseCurrentStyle()
    plotPad.Draw()
    # ~ ratioPad.Draw()
    plotPad.cd()
    plotPad.cd()
    plotPad.SetGrid()
    gStyle.SetTitleXOffset(1.45)
    gStyle.SetTitleYOffset(1.55)

    xMax = 0.15
    if trackType == "Inner":
        xMax = 0.3
    if trackType == "Outer":
        xMax = 0.5

    plotPad.DrawFrame(0, 0, 2000, xMax, ";p_{T} [GeV]; p_{T} resolution [%]")

    graph2017B.Draw("samepe")
    # ~ graph2017O.Draw("samepe")
    graph2017E.Draw("samepe")
    graph2017B.SetLineColor(kRed)
    graph2017B.SetMarkerColor(kRed)
    graph2017O.SetLineColor(kGreen)
    graph2017O.SetMarkerColor(kGreen)
    graph2017E.SetLineColor(kBlue)
    graph2017E.SetMarkerColor(kBlue)

    latex = TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatex(0.95, 0.96, "(13 TeV)")

    cmsExtra = "#splitline{Preliminary}{}"
    latexCMS.DrawLatex(0.19, 0.88, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.81
    else:
        yLabelPos = 0.84

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s 2017" % trackType, "brNDC")
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    leg.AddEntry(graph2017B, "Barrel", "l")
    # ~ leg.AddEntry(graph2017O,"Overlap","l")
    leg.AddEntry(graph2017E, "Endcap", "l")

    leg.Draw()

    plotPad.RedrawAxis()

    canv.Print("PtResolutionCompare_%s_2017.pdf" % trackType)
    canv.Print("PtResolutionCompare_%s_2017.root" % trackType)

    canv = TCanvas("c1", "c1", 800, 1200)

    plotPad = TPad("plotPad", "plotPad", 0, 0., 1, 1)
    # ~ ratioPad = TPad("ratioPad","ratioPad",0,0.,1,0.3)
    style = setTDRStyle()
    gStyle.SetOptStat(0)
    plotPad.UseCurrentStyle()
    # ~ ratioPad.UseCurrentStyle()
    plotPad.Draw()
    # ~ ratioPad.Draw()
    plotPad.cd()
    plotPad.cd()
    plotPad.SetGrid()
    gStyle.SetTitleXOffset(1.45)
    gStyle.SetTitleYOffset(1.55)

    xMax = 0.15
    if trackType == "Inner":
        xMax = 0.3
    if trackType == "Outer":
        xMax = 0.5

    plotPad.DrawFrame(0, 0, 2000, xMax, ";p_{T} [GeV]; p_{T} resolution [%]")

    graph2018B.Draw("samepe")
    # ~ graph2018O.Draw("samepe")
    graph2018E.Draw("samepe")
    graph2018B.SetLineColor(kRed)
    graph2018B.SetMarkerColor(kRed)
    graph2018O.SetLineColor(kGreen)
    graph2018O.SetMarkerColor(kGreen)
    graph2018E.SetLineColor(kBlue)
    graph2018E.SetMarkerColor(kBlue)

    latex = TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatex(0.95, 0.96, "(13 TeV)")

    cmsExtra = "#splitline{Preliminary}{}"
    latexCMS.DrawLatex(0.19, 0.88, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.81
    else:
        yLabelPos = 0.84

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s 2018" % trackType, "brNDC")
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    leg.AddEntry(graph2018B, "Barrel", "l")
    # ~ leg.AddEntry(graph2018O,"Overlap","l")
    leg.AddEntry(graph2018E, "Endcap", "l")

    leg.Draw()

    plotPad.RedrawAxis()

    canv.Print("PtResolutionCompare_%s_2018.pdf" % trackType)
    canv.Print("PtResolutionCompare_%s_2018.root" % trackType)
Пример #17
0
def rocPlotMacro():
	
	# load TDR-style plotting macro
	gROOT.LoadMacro("$CMSSW_BASE/src/TauAnalysisTools/TauAnalysisTools/macros/tdrstyle.C")
	ROOT.setTDRStyle()
	gStyle.SetFrameLineWidth(3)
	gStyle.SetLineWidth(3)
	gStyle.SetPadGridX(True)
	gStyle.SetPadGridY(True)
	gStyle.SetPadTopMargin(0.08)
	gStyle.SetPadBottomMargin(0.15)
	gStyle.SetPadLeftMargin(0.18)
	gStyle.SetPadRightMargin(0.05)
	gStyle.SetTitleFontSize(0.055)
	gStyle.SetTitleSize(0.055, "XYZ")
	gStyle.SetTitleXOffset(1.25)
	gStyle.SetTitleYOffset(1.60)
	gStyle.SetLabelSize(0.04, "XYZ")
	gStyle.SetLabelOffset(0.013, "XYZ")

	# list of trainings
	reference53X = {
		'folder' : 'forFabio',
		'color'  : ROOT.kGreen,
		'text'   : '53X'
	}
	reference74X = {
		'folder' : 'antiElectronDiscr74X_onlyZWTTjetsHiggsWZprimeSUSY_FullSkim',
		'color'  : ROOT.kMagenta,
		'text'   : '74X (Complete skim)'
	}

	inputFilePath = '/nfs/dust/cms/user/fcolombo/HiggsToTauTau/TauPOG/antiElectronDiscrMVATraining'

	trainingList = []
	trainingList.append(reference53X)
	trainingList.append(reference74X)

	# list of plots to produce
	roc_linear = {
		'file' : 'showROCcurvesAntiElectronDiscrMVA_all_linear.root',
		'name' : 'roc_linear',
		'y_range' : [0.4, 1.],
		'y_log' : False,
		'leg_loc' : [0.2, 0.2, 0.8, 0.35]
	}
	roc_log = {
		'file' : 'showROCcurvesAntiElectronDiscrMVA_all_log.root',
		'name' : 'roc_log',
		'y_range' : [0.001, 1.],
		'y_log' : True,
		'leg_loc' : [0.2, 0.75, 0.8, 0.9]
	}

	plotList = []
	plotList.append(roc_linear)
	plotList.append(roc_log)

	pTbinsList = ['','tauPtLt50_','tauPt50to100_','tauPt100to200_','tauPt200to400_','tauPt400to600_','tauPt600to900_','tauPt900to1200_','tauPtGt1200_']

	for iPlot, plotDict in enumerate(plotList):
		for ptBin in pTbinsList:

			filename = 'showROCcurvesAntiElectronDiscrMVA_all_'+ptBin+('log' if plotDict['y_log'] else 'linear')

			c1 = TCanvas()
			c1.SetTitle(plotDict['name'])

			legend = TLegend(plotDict['leg_loc'][0], plotDict['leg_loc'][1], plotDict['leg_loc'][2], plotDict['leg_loc'][3])
			legend.SetShadowColor(0)
			legend.SetFillColor(0)

			for iTrain, trainDict in enumerate(trainingList):

				file = TFile.Open(os.path.join(inputFilePath, trainDict['folder'], filename+'.root'))
				canvas = file.Get("canvas")
				histo = canvas.GetPrimitive("dummyHistogram")
				graph = canvas.GetPrimitive("mvaAntiElectronDiscr5_TestTree_"+ptBin+"cloned")

				legend.AddEntry(graph, trainDict['text'], 'l')
				c1.cd()
				if (iTrain == 0):
					histo.GetYaxis().SetRangeUser(plotDict['y_range'][0], plotDict['y_range'][1])
					histo.GetYaxis().SetTitleOffset(1.6)
					histo.Draw()

				graph.SetMarkerColor(trainDict['color'])
				graph.SetLineColor(trainDict['color'])
				graph.SetLineWidth(2)
				graph.Draw("LP SAME")

			if (plotDict['y_log'] == True):
				c1.SetLogy()

			legend.Draw()

			if 'plots' not in os.listdir(inputFilePath):
				os.mkdir(os.path.join(inputFilePath, 'plots'))

			c1.SaveAs(os.path.join(inputFilePath, 'plots', plotDict['name']+'_'+(ptBin[:-1] if ptBin != '' else 'all')+'.png'))
Пример #18
0
def produceStackedPlots(processes, selections, variables, colors, intLumi,
                        pdir, lt, rt, log, stacksig, hfile):

    print ''
    print 'Preparing stacked plots ...'

    gROOT.SetBatch(True)

    intLumiab = intLumi / 1e+06

    yl = "events"

    ff = FORMAT

    logstr = ''
    if log:
        logstr = 'log'
    else:
        logstr = 'lin'

    stackstr = ''
    if stacksig:
        stackstr = 'stack'
    else:
        stackstr = 'nostack'

    hfile.cd()

    nsel = 0

    legsize = 0.04 * float(len(processes))

    for s in selections:
        selstr = 'sel{}'.format(int(nsel))
        nsel += 1
        for v, dic in variables.iteritems():
            histos = []
            i = 0

            filename = '{}_{}_{}_{}'.format(v, selstr, stackstr, logstr)

            leg = TLegend(0.60, 0.86 - legsize, 0.86, 0.88)
            leg.SetFillColor(0)
            leg.SetFillStyle(0)
            leg.SetLineColor(0)
            leg.SetShadowColor(10)
            leg.SetTextSize(0.035)
            leg.SetTextFont(42)

            cols = []
            for p in processes:
                hname = '{}_{}_{}'.format(p, selstr, v)
                h = hfile.Get(hname)
                hh = TH1D.Clone(h)
                hh.Scale(intLumi)

                # rebin if needed
                hh.Rebin(int(hh.GetNbinsX() / dic['bin']))

                histos.append(hh)
                cols.append(colors[p])
                if i > 0:
                    leg.AddEntry(hh, p, "f")
                else:
                    leg.AddEntry(hh, p, "l")
                i += 1

            drawStack(filename, yl, leg, lt, rt, ff, pdir, log, stacksig,
                      histos, cols, dic)

    print 'DONE.'
Пример #19
0
def produceStackedHackedPlots(processes, selections, variables, colors,
                              intLumi, pdir, lt, rt, log, stacksig, hfile):

    print ''
    print 'Preparing stacked HACKED plots ...'

    gROOT.SetBatch(True)

    intLumiab = intLumi / 1e+06

    yl = "events"

    ff = FORMAT

    logstr = ''
    if log:
        logstr = 'log'
    else:
        logstr = 'lin'

    stackstr = ''
    if stacksig:
        stackstr = 'stack'
    else:
        stackstr = 'nostack'

    hfile.cd()

    nsel = 0

    legsize = 0.04 * float(len(processes))

    for s in selections:
        selstr = 'sel{}'.format(int(nsel))
        nsel += 1
        for v, dic in variables.iteritems():
            histos = []
            i = 0

            filename = '{}_{}_{}_{}'.format(v, selstr, stackstr, logstr)

            leg = TLegend(0.60, 0.86 - legsize, 0.86, 0.88)
            leg.SetFillColor(0)
            leg.SetFillStyle(0)
            leg.SetLineColor(0)
            leg.SetShadowColor(10)
            leg.SetTextSize(0.035)
            leg.SetTextFont(42)

            cols = []
            for p in processes:
                hname = '{}_{}_{}'.format(p, selstr, v)
                h = hfile.Get(hname)
                hh = TH1D.Clone(h)
                hh.Scale(intLumi)

                if p == 'HH(#kappa_{#lambda}=1.00)':
                    print 'here'
                    hh.Scale(20)

                r = ROOT.TRandom3(5)

                import math
                '''
                 if '#gamma#gamma + Jets' in p and 'haa_m' in filename and 'sel0' in filename:
                    
                    mean = 0
                    for bin in xrange(1, hh.GetNbinsX()+1):
                       #print '#gamma#gamma + Jets' , hh.GetBinContent(bin)
                       
                       mean += hh.GetBinContent(bin)
                       #hh.SetBinContent(bin,r.Poisson(1750))
                       #hh.SetBinContent(bin,r.Gaus(1000, 0.75*math.sqrt(1000)))
                 
                    mean = mean/hh.GetNbinsX()
                    for bin in xrange(1, hh.GetNbinsX()+1):
                       #hh.SetBinContent(bin,r.Gaus(mean, 0.75*math.sqrt(mean)))
                       hh.SetBinContent(bin,r.Gaus(hh.GetBinContent(bin), 0.99*math.sqrt(mean)))

                 if 'j#gamma + Jets' in p and 'haa_m' in hname and 'sel0' in filename:
                    mean = 0
                    for bin in xrange(1,hh.GetNbinsX()+1):
                       #print 'j#gamma + Jets', hh.GetBinContent(bin)
                       mean += hh.GetBinContent(bin)
                       #hh.SetBinContent(bin,r.Poisson(1000))
                       #hh.SetBinContent(bin,r.Gaus(700, 0.75*math.sqrt(700)))
                    
                    mean = mean/hh.GetNbinsX()
                    for bin in xrange(1, hh.GetNbinsX()+1):
                       #hh.SetBinContent(bin,r.Gaus(mean, 0.75*math.sqrt(mean)))
                       hh.SetBinContent(bin,r.Gaus(hh.GetBinContent(bin), 0.99*math.sqrt(mean)))
                 '''

                print p, hname
                '''
                 #hh.Smooth(1)
                 for bin in xrange(1, hh.GetNbinsX()+1):
                    #print '#gamma#gamma + Jets' , hh.GetBinContent(bin)
                    binc = hh.GetBinContent(bin)
                    hh.SetBinContent(bin,r.Poisson(binc))
                 '''

                if 'j#gamma + Jets' in p and 'sel0' in filename and 'haa_m' in hname:

                    href = hfile.Get('#gamma#gamma + Jets_sel0_haa_m')
                    href2 = TH1D.Clone(href)
                    href2.Scale(intLumi)
                    #href2.Smooth(1)

                    for bin in xrange(1, hh.GetNbinsX() + 1):
                        #print '#gamma#gamma + Jets' , hh.GetBinContent(bin)
                        binc = 1.2 * href2.GetBinContent(bin)
                        hh.SetBinContent(bin, r.Poisson(binc))
                '''
		 if 'j#gamma + Jets' in p and 'sel0' in filename and 'hbb_m' in hname:
                     
                     href = hfile.Get('#gamma#gamma + Jets_sel0_hbb_m')
                     href2 = TH1D.Clone(href)
                     href2.Scale(intLumi)
                     #href2.Smooth(1)
                    
                     for bin in xrange(1, hh.GetNbinsX()+1):
                        #print '#gamma#gamma + Jets' , hh.GetBinContent(bin)
                        binc = 1.2*href2.GetBinContent(bin)
                        hh.SetBinContent(bin,r.Poisson(binc))
                 '''

                ## for bbtahtah final state
                if 'top pair' in p and 'sel0' in filename and 'bdt' in hname:
                    for bin in xrange(1, hh.GetNbinsX() + 1):
                        print 'top', bin, hh.GetBinContent(bin)
                        if bin == 47: hh.SetBinContent(bin, 300000.)
                '''
		 ## for bbtahtal final state
		 if 'top pair' in p and 'sel0' in filename and 'bdt' in hname:
                     for bin in xrange(1, hh.GetNbinsX()+1):
                        print 'top', bin , hh.GetBinContent(bin)
                        if bin == 44: hh.SetBinContent(bin,2500000.)
                        if bin == 46: hh.SetBinContent(bin,1500000.)
                        if bin == 47: hh.SetBinContent(bin,1200000.)
                        if bin == 49: hh.SetBinContent(bin,600000.)
                        if bin == 50: hh.SetBinContent(bin,450000.)
                 '''
                '''
		 ## for bbbb final state
		 if 'QCD' in p and 'sel0' in filename and 'bdt' in hname:

                     for bin in xrange(1, hh.GetNbinsX()+1):
                        print 'qcd', bin , hh.GetBinContent(bin)
                        if bin == 47: hh.SetBinContent(bin,220000000.)
                        if bin == 47: hh.SetBinContent(bin,150000000.)
                        if bin == 48: hh.SetBinContent(bin,110000000.)
                        if bin == 49: hh.SetBinContent(bin,75000000.)
                        if bin == 50: hh.SetBinContent(bin,50000000.)
			
			
                 '''
                # rebin if needed
                #if bin == 47: hh.SetBinContent(bin,450000.)

                hh.Rebin(int(hh.GetNbinsX() / dic['bin']))

                histos.append(hh)
                cols.append(colors[p])
                if i > 0:
                    leg.AddEntry(hh, p, "f")
                else:
                    #leg.AddEntry(hh,p+ ' x20',"l")
                    leg.AddEntry(hh, p, "l")

                i += 1

            drawStack(filename, yl, leg, lt, rt, ff, pdir, log, stacksig,
                      histos, cols, dic)

    print 'DONE.'
        gStyle.SetStatW(0.28)

        TH1.SetDefaultSumw2()


# ______________________________________________________________________________
# Globals
tlatex = TLatex()
tlatex.SetNDC()
tlatex.SetTextFont(42)
tlatex.SetTextSize(0.03)

tlegend = TLegend(0.70, 0.74, 0.96, 0.94)
tlegend.SetFillStyle(0)
tlegend.SetLineColor(0)
tlegend.SetShadowColor(0)
tlegend.SetBorderSize(0)

tline = TLine()
tline.SetLineColor(kGray + 2)
tline.SetLineStyle(2)

donotdelete = []  # persist in memory

# ______________________________________________________________________________
# Auxiliary


def count_if(seq, condition):
    return sum(1 for item in seq if condition(item))
Пример #21
0
def makeDependencyPlot(path, selection, plots, useMC, backgrounds, runRange,
                       cmsExtra):
    colors = createMyColors()
    for plotName in plots:
        plot = getPlot(plotName)
        plot.addRegion(selection)
        plot.cuts = plot.cuts % runRange.runCut

        if "Forward" in selection.name:
            region = "forward"
        elif "Central" in selection.name:
            region = "central"
        else:
            region = "inclusive"
        tmpCuts = plot.cuts
        for binName in ["lowMass", "highMass"]:

            plot.cuts = tmpCuts
            plot.cuts += "*(p4.M() > %f && p4.M() < %f)" % (getattr(
                mllBins, binName).low, getattr(mllBins, binName).high)

            histEE, histMM, histEM = getHistograms(path, plot, runRange, False,
                                                   [])
            histSF = histEE.Clone("histSF")
            histSF.Add(histMM.Clone())

            histOFSF = histEM.Clone("histOFSF")
            histOFEE = histEM.Clone("histOFEE")
            histOFMM = histEM.Clone("histOFMM")
            histOFSF.Scale(getattr(rSFOF, region).val)
            histOFEE.Scale(getattr(rEEOF, region).val)
            histOFMM.Scale(getattr(rMMOF, region).val)

            if useMC:
                histEEMC, histMMMC, histEMMC = getHistograms(
                    path, plot, runRange, True, backgrounds)
                histSFMC = histEEMC.Clone("histSFMC")
                histSFMC.Add(histMMMC.Clone())
                histOFSFMC = histEMMC.Clone("histOFSFMC")
                histOFEEMC = histEMMC.Clone("histOFEEMC")
                histOFMMMC = histEMMC.Clone("histOFMMMC")
                histOFSFMC.Scale(getattr(rSFOF, region).valMC)
                histOFEEMC.Scale(getattr(rEEOF, region).valMC)
                histOFMMMC.Scale(getattr(rMMOF, region).valMC)
                histsSFMC = {}
                histsOFMC = {}
                histsSFMC["SF"] = histSFMC
                histsSFMC["EE"] = histEEMC
                histsSFMC["MM"] = histMMMC
                histsOFMC["SF"] = histOFSFMC
                histsOFMC["EE"] = histOFEEMC
                histsOFMC["MM"] = histOFMMMC

            histsSF = {}
            histsOF = {}
            histsSF["SF"] = histSF
            histsSF["EE"] = histEE
            histsSF["MM"] = histMM
            histsOF["SF"] = histOFSF
            histsOF["EE"] = histOFEE
            histsOF["MM"] = histOFMM

            for combination in ["SF", "EE", "MM"]:

                hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)

                plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
                ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
                style = setTDRStyle()
                style.SetPadTopMargin(0.07)
                ROOT.gStyle.SetOptStat(0)
                plotPad.UseCurrentStyle()
                ratioPad.UseCurrentStyle()
                plotPad.Draw()
                ratioPad.Draw()
                plotPad.cd()

                sfHist = histsSF[combination]
                bkgHist = histsOF[combination]

                sfHist.SetMarkerStyle(20)
                bkgHist.SetLineColor(ROOT.kBlue + 3)
                bkgHist.SetLineWidth(2)

                yMax = sfHist.GetBinContent(sfHist.GetMaximumBin())

                if plot.yMax == 0:
                    yMax = yMax * 1.35

                else:
                    yMax = plot.yMax

                plotPad.DrawFrame(plot.firstBin, 0, plot.lastBin, yMax,
                                  "; %s ; %s" % (plot.xaxis, plot.yaxis))

                latex = ROOT.TLatex()
                latex.SetTextFont(42)
                latex.SetTextAlign(31)
                latex.SetTextSize(0.04)
                latex.SetNDC(True)
                latexCMS = ROOT.TLatex()
                latexCMS.SetTextFont(61)
                latexCMS.SetTextSize(0.055)
                latexCMS.SetNDC(True)
                latexCMSExtra = ROOT.TLatex()
                latexCMSExtra.SetTextFont(52)
                latexCMSExtra.SetTextSize(0.03)
                latexCMSExtra.SetNDC(True)

                latex.DrawLatex(0.95, 0.96,
                                "%s fb^{-1} (13 TeV)" % runRange.printval)

                latexCMS.DrawLatex(0.21, 0.88, "CMS")
                if "Simulation" in cmsExtra:
                    yLabelPos = 0.81
                else:
                    yLabelPos = 0.84

                latexCMSExtra.DrawLatex(0.21, yLabelPos, "%s" % (cmsExtra))

                if combination == "SF":
                    rSFOFErr = getattr(rSFOF, region).err
                elif combination == "EE":
                    rSFOFErr = getattr(rEEOF, region).err
                elif combination == "MM":
                    rSFOFErr = getattr(rMMOF, region).err

                errGraph, histUp, histDown = getErrHist(
                    plot, combination, region, bkgHist, None, rSFOFErr)
                errGraph.SetFillColor(myColors["MyBlue"])
                errGraph.SetFillStyle(3001)
                #~ errGraph.SetLineColor(myColors["MyDarkBlue"])
                #~ errGraph.SetMarkerColor(myColors["MyDarkBlue"])

                errGraph.Draw("SAME02")
                bkgHist.Draw("samehist")
                sfHist.Draw("samepe")

                leg = TLegend(0.62, 0.51, 0.89, 0.92, "", "brNDC")
                leg.SetFillColor(10)
                leg.SetLineColor(10)
                leg.SetShadowColor(0)
                leg.SetBorderSize(1)
                from ROOT import TH1F, kWhite
                legendHistDing = TH1F()
                legendHistDing.SetFillColor(kWhite)
                if region == "inclusive":
                    leg.AddEntry(legendHistDing, "Inclusive signal region",
                                 "h")
                elif region == "central":
                    leg.AddEntry(legendHistDing, "Central signal region", "h")
                elif region == "forward":
                    leg.AddEntry(legendHistDing, "Forward signal region", "h")
                leg.AddEntry(sfHist, "Data", "PE")
                leg.AddEntry(bkgHist, "Flav. Sym. backgrounds", "l")
                leg.AddEntry(errGraph, "Background uncert.", "f")

                leg.Draw("same")

                plotPad.RedrawAxis()

                ratioPad.cd()

                ratioGraphs = ratios.RatioGraph(sfHist,
                                                bkgHist,
                                                xMin=plot.firstBin,
                                                xMax=plot.lastBin,
                                                title="%s / OF" % combination,
                                                yMin=0.0,
                                                yMax=2,
                                                ndivisions=10,
                                                color=ROOT.kBlack,
                                                adaptiveBinning=1000)
                ratioGraphs.addErrorByHistograms("rSFOF",
                                                 histUp,
                                                 histDown,
                                                 color=myColors["MyBlue"],
                                                 fillStyle=3001)

                ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8)

                leg2 = TLegend(0.175, 0.78, 0.475, 0.9, "", "brNDC")
                leg2.SetFillColor(10)
                leg2.SetLineColor(10)
                leg2.SetShadowColor(0)
                leg2.SetBorderSize(1)
                leg2.AddEntry(errGraph, "Systematic uncert.", "f")
                leg2.Draw("same")

                ROOT.gPad.RedrawAxis()
                plotPad.RedrawAxis()
                ratioPad.RedrawAxis()

                hCanvas.Print("fig/rSFOFDependency_%s_%s_%s_%s_%s.pdf" %
                              (selection.name, plot.variablePlotName,
                               runRange.label, combination, binName))
Пример #22
0
def make_time_rod_evo(error_dict, rod_dict, results, doLock):
 
    c2 = TCanvas( 'c2', 'c2', 1000, 600)
    leg = TLegend(0.18,0.85,0.45,0.55)
    leg.SetLineColor(0)
    leg.SetFillStyle(0)
    leg.SetShadowColor(0)
    leg.SetBorderSize(0)
    leg.SetNColumns(2)
     
    R15 = TLine(431,0,431,60)
    R15.SetLineColorAlpha(kPink+10,0.4)
    R15.SetLineWidth(4)

    R16 = TLine(1820,0,1820,60)
    R16.SetLineColorAlpha(kMagenta+10,0.4)
    R16.SetLineWidth(4)

    R17 = TLine(3376,0,3376,60)
    R17.SetLineColorAlpha(kGreen-3,0.4)
    R17.SetLineWidth(4)


    TS1 = TLine(431,0,432,60)
    TS1.SetLineColorAlpha(kPink+10,0.5)
    TS1.SetLineWidth(5)

    TS2 = TLine(1415,0,1415,60)
    TS2.SetLineColorAlpha(kMagenta+3,0.5)
    TS2.SetLineWidth(5)

    leg2 = TLegend(0.18,0.45,0.35,0.55)
    leg2.SetLineColor(0)
    leg2.SetFillStyle(0)
    leg2.SetShadowColor(0)
    leg2.SetBorderSize(0)
    gStyle.SetLegendTextSize(0.030)

    leg2.AddEntry(R15, "End of 2015", 'lf')
    leg2.AddEntry(R16, "End of 2016", 'lf')
    leg2.AddEntry(R17, "End of 2017", 'lf')
    #leg2.AddEntry(TS2, "TS2", 'lf')


    for key,val in rod_dict.items(): 
        TS1.SetY2(val*0.5)
        TS2.SetY2(val+1)

        R15.SetY2(val*0.3)
        R16.SetY2(val*0.5)
        R17.SetY2(val*0.8)

        times = {}
        times.clear()
        for e in error_bits:
            times['0x'+e] = [0] 
        for error in results:
            pos_rod  = error.text.find("ROD") + 4
            pos_lock = error.text.find("Lock") + 15
            pos_buff = error.text.find("buffer") + 17

            if error.msgID == 'TRT::ROD05Module':
                rod  = '0x'+str(error.text[pos_rod:pos_rod+6])
            else:
                rod  = str(error.text[pos_rod:pos_rod+8])

            lock = str(error.text[pos_lock:pos_lock+3])
            buff = str(error.text[pos_buff:pos_buff+3])

            if key == rod and doLock and lock != '0xf':
                times[lock].append(error.sb_total_time)


        leg.Clear()
        mg = TMultiGraph()

        for e in error_bits:
            errs = []
            for i,x in enumerate(times['0x'+e]):
                errs.append(i+0.0)
            errs.append(errs[-1])
            #times['0x'+e].append(1800.0)
            times['0x'+e].append(results[-1].sb_total_time)
            gr = TGraph(len(times['0x'+e]), array(times['0x'+e]), array(errs))
            gr.SetMarkerSize(0.7)
            if bin(int('0x'+e, 16))[2:].zfill(4) == '0111':
                leg.AddEntry(gr,'GOL 3',"lp");
            elif bin(int('0x'+e, 16))[2:].zfill(4) == '1011':
                leg.AddEntry(gr,'GOL 2',"lp");
            elif bin(int('0x'+e, 16))[2:].zfill(4) == '1101':
                leg.AddEntry(gr,'GOL 1',"lp");
            elif bin(int('0x'+e, 16))[2:].zfill(4) == '1110':
                leg.AddEntry(gr,'GOL 0',"lp");
            else:
                leg.AddEntry(gr,bin(int('0x'+e, 16))[2:].zfill(4),"lp");
            mg.Add(gr,"pl");

        mg.SetTitle("; Hours of stable beams; # of rocketio io lock errors");
        mg.Draw("PMC PLC a");
        R15.Draw()
        R16.Draw()
        R17.Draw()
        #TS1.Draw()
        #TS2.Draw()
        
        AtlasStyle.ATLAS_LABEL(0.19,.88, 1, "Internal")
        leg.Draw()
        leg2.Draw()
        AtlasStyle.myText(0.4, 0.88, kBlack, "ROD: " + key)
        
        
        leg.SetMargin(0.5)
        gPad.Modified()
        mg.GetXaxis().SetLimits(0,results[-1].sb_total_time)
        mg.SetMinimum(0.)
        mg.SetMaximum(val+1)
        c2.Update()
        c2.Print("plots/time_"+key+".pdf")
        c2.Clear()
Пример #23
0
def make_plot_all_rods(error_dict, rod_dict, name):
    

    leg = TLegend(0,0,0,0)
    if 'lock' in name:
        leg = TLegend(0.18,0.85,0.50,0.55)
    else:
        leg = TLegend(0.18,0.85,0.40,0.55)
    leg.SetLineColor(0)
    leg.SetFillStyle(0)
    leg.SetShadowColor(0)
    leg.SetBorderSize(0)
    leg.SetNColumns(3)
    gStyle.SetLegendTextSize(0.045)

   
    v_hists = []
    #for e,c in zip(error_bits, error_colors):
    for e in error_bits:
        h = TH1F('h'+e,'h'+e, len(rod_dict), 0, len(rod_dict))
        h.SetFillStyle(1001)
        h.SetLineWidth(0)
        v_hists.append(h)
        v_hists[-1].SetDirectory(0)
        if bin(int('0x'+e, 16))[2:].zfill(4) == '0111':
            leg.AddEntry(v_hists[-1],'GOL 3',"f");
        elif bin(int('0x'+e, 16))[2:].zfill(4) == '1011':
            leg.AddEntry(v_hists[-1],'GOL 2',"f");
        elif bin(int('0x'+e, 16))[2:].zfill(4) == '1101':
            leg.AddEntry(v_hists[-1],'GOL 1',"f");
        elif bin(int('0x'+e, 16))[2:].zfill(4) == '1110':
            leg.AddEntry(v_hists[-1],'GOL 0',"f");
        else:
            leg.AddEntry(v_hists[-1],bin(int('0x'+e, 16))[2:].zfill(4),"f");
    h = leg.GetY2()-leg.GetY1();
    w = leg.GetX2()-leg.GetX1()*.6;
    leg.SetMargin(leg.GetNColumns()*h/(leg.GetNRows()*w))
    

    for key,val in error_dict.items():
        idx_rod = 0
        for i, key2 in enumerate(rod_dict):
            if key2 == key[:8]:
                idx_rod = i
        v_hists[int(key[11:12], 16)].Fill(idx_rod, val)
  
    stack  = THStack("stack","stack")
    for hist in v_hists:
        stack.Add(hist)

    if 'buff' in name:
        c1 = TCanvas( 'c1', 'c1', 2000, 500)
    else:
        c1 = TCanvas( 'c1', 'c1', 1000, 500)


    h1 = TH1F('h_1','h_1', len(rod_dict), 0, len(rod_dict))
    for i, key in enumerate(rod_dict):
        h1.GetXaxis().SetBinLabel(i+1,key)
        h1.SetBinContent(i+1,rod_dict[key])

 
    h1.GetXaxis().LabelsOption("v")
    h1.GetXaxis().SetTitle("ROD")
    h1.GetXaxis().SetTitleOffset(2.2)
    h1.GetYaxis().SetTitle("# of rocketio errors")
    h1.SetLineColor(kRed)
    h1.SetLineWidth(1)

    leg.AddEntry(h1,'total',"l");
    
    c1.SetBottomMargin(0.23)  
    h1.GetXaxis().SetTitle("ROD")
    h1.Draw("HIST")
    stack.Draw("PFC PLC SAME HIST")
    h1.Draw("SAMEHIST")
    AtlasStyle.ATLAS_LABEL(0.19,.88, 1, "Internal")
    leg.Draw()
    c1.Update()
    c1.Print("plots/"+name +".pdf")
    c1.Clear()
Пример #24
0
def produceStackedPlots(processes, selections, variables, colors, intLumi, pdir, lt, rt, log, stacksig, hfile, ana_tex):
    
    print ''
    print 'Preparing stacked plots ...'

    gROOT.SetBatch(True)

    intLumiab = intLumi/1e+06 

    yl = "events"

    ff = "eps"

    logstr = ''
    if log:
       logstr = 'log'
    else:
       logstr = 'lin'
    
    stackstr = ''
    if stacksig:
       stackstr = 'stack'
    else:
       stackstr = 'nostack'

    hfile.cd()

    nsel = 0
    
    legsize = 0.04*float(len(processes))
    
    for s in selections:
        selstr = 'sel{}'.format(int(nsel))
        nsel += 1
        for v, dic in variables.iteritems() :
             histos = []
             i = 0

             filename = '{}_{}_{}_{}'.format(v, selstr, stackstr, logstr)

             leg = TLegend(0.58,0.86 - legsize,0.86,0.88)
             leg.SetFillColor(0)
             leg.SetFillStyle(0)
             leg.SetLineColor(0)
             leg.SetShadowColor(10)
             leg.SetTextSize(0.035)
             leg.SetTextFont(42)


             cols = []
             for p in processes:
                 hname = '{}_{}_{}'.format(p, selstr, v)
                 h = hfile.Get(hname)
                 hh = TH1D.Clone(h)
                 hh.Scale(intLumi)
                 
                 # rebin if needed
                 hh.Rebin(int(hh.GetNbinsX()/dic['bin']))

                 histos.append(hh)
                 cols.append(colors[p])
                 # fix names if needed
                 leg_name = p
                 if p.find('m_{Z}')>=0   : leg_name = p.replace('m_{Z}',  'm_{Z\'}'   )
                 if p.find('m_{RSG}')>=0 : leg_name = p.replace('m_{RSG}','m_{G_{RS}}')
                 if p.find('vv')>=0 : leg_name = p.replace('vv','VV (V=Z/W)')
                 if p.find('vj')>=0 : leg_name = p.replace('vj','Vj (V=Z/W)')
                 if p.find('tt')>=0 : leg_name = p.replace('tt','t#bar{t}')
                 if p.find('Drell-Yan')>=0 and ana_tex.find("e^")>=0:   leg_name = p.replace('Drell-Yan','pp #rightarrow Z/#gamma* #rightarrow e^{+}e^{-}')
                 if p.find('Drell-Yan')>=0 and ana_tex.find("mu^")>=0:  leg_name = p.replace('Drell-Yan','pp #rightarrow Z/#gamma* #rightarrow #mu^{+}#mu^{-}')
                 if p.find('Drell-Yan')>=0 and ana_tex.find("tau^")>=0: leg_name = p.replace('Drell-Yan','pp #rightarrow Z/#gamma* #rightarrow #tau^{+}#tau^{-}')
                 if i > 0: 
                     leg.AddEntry(hh,leg_name,"f")
                 else: 
                     leg.AddEntry(hh,leg_name,"l")
                 i+=1
             drawStack(filename, yl, leg, lt, rt, ff, pdir, log, stacksig, histos, cols, ana_tex)
    print 'DONE.'
Пример #25
0
class plotUnc:
    tfiles = {}
    lgx = 0.65
    lgy = 0.4

    def __init__(self):
        self.MCplots = []
        self.MCplotsUp = []
        self.MCplotsDown = []
        self.DAplots = []
        self.Otherplots = []
        self.DIVplots = []
        self.Canvases = []
        self.Pads = []
        self.unc = False
        ROOT.gStyle.SetOptFit(0)
        ROOT.gStyle.SetOptStat(0)
        ROOT.gStyle.SetPadTickX(0)
        ROOT.gStyle.SetPadTickY(0)
        ROOT.gStyle.SetOptStat(0)
        ROOT.gStyle.SetOptStat(0)

        ROOT.gStyle.SetPadTopMargin(0.05)
        ROOT.gStyle.SetPadRightMargin(0.05)
        ROOT.gStyle.SetPadBottomMargin(0.15)
        ROOT.gStyle.SetPadLeftMargin(0.15)

        ROOT.gStyle.SetLabelFont(43, "x")
        ROOT.gStyle.SetLabelFont(43, "y")
        ROOT.gStyle.SetLabelFont(43, "z")
        ROOT.gStyle.SetLabelOffset(0.01, "x")
        ROOT.gStyle.SetLabelOffset(0.01, "y")
        ROOT.gStyle.SetLabelOffset(0.01, "z")
        ROOT.gStyle.SetLabelSize(25, "x")
        ROOT.gStyle.SetLabelSize(25, "y")
        ROOT.gStyle.SetLabelSize(25, "z")
        ROOT.gStyle.SetTitleFont(43, "x")
        ROOT.gStyle.SetTitleFont(43, "y")
        ROOT.gStyle.SetTitleFont(43, "z")
        ROOT.gStyle.SetTitleOffset(1.2, "x")
        ROOT.gStyle.SetTitleOffset(1.5, "y")
        ROOT.gStyle.SetTitleOffset(1.1, "z")
        ROOT.gStyle.SetTitleSize(30, "x")
        ROOT.gStyle.SetTitleSize(30, "y")
        ROOT.gStyle.SetTitleSize(30, "z")

    def legend(self, legtitle):
        xpos = 1. - ROOT.gPad.GetRightMargin()
        ypos = 1. - ROOT.gPad.GetTopMargin()
        #self.lg = TLegend(0.55, 0.4, xpos-0.02, ypos-0.02)
        self.lg = TLegend(self.lgx, self.lgy, xpos - 0.02, ypos - 0.02)
        if len(legtitle) != 0:
            self.lg.SetHeader(legtitle)
        self.lg.SetFillColor(0)
        self.lg.SetFillStyle(0)
        self.lg.SetLineColor(0)
        self.lg.SetLineStyle(0)
        self.lg.SetBorderSize(0)
        self.lg.SetShadowColor(0)
        self.lg.SetTextFont(42)
        self.lg.SetTextSize(0.07)

    def setchannel(self, title='#splitline{l+jets parton}{%s}' % njets):
        xpos = 1. - ROOT.gPad.GetRightMargin()
        ypos = 1. - ROOT.gPad.GetTopMargin()
        lxtitle = TLatex(0., 0., 'Z')
        lxtitle.SetNDC(True)
        lxtitle.SetTextFont(63)
        lxtitle.SetTextSize(25)
        lxtitle.SetTextAlign(13)
        lxtitle.DrawLatex(0.35, ypos - 0.03, title)

    def cmstext(self, add=''):
        xpos = ROOT.gPad.GetLeftMargin()
        ypos = 1. - ROOT.gPad.GetTopMargin()
        self.lx = TLatex(0., 0., 'Z')
        self.lx.SetNDC(True)
        self.lx.SetTextFont(62)
        self.lx.SetTextSize(0.07)
        self.lx.SetTextAlign(13)
        self.lx.DrawLatex(xpos + 0.04, ypos - 0.02, 'CMS')
        self.lx2 = TLatex(0., 0., 'Z')
        self.lx2.SetNDC(True)
        self.lx2.SetTextFont(52)
        self.lx2.SetTextSize(0.07)
        self.lx2.SetTextAlign(13)
        self.lx2.DrawLatex(xpos + 0.04, ypos - 0.08, add)

    def settitle(self, title):
        xpos = 1. - ROOT.gPad.GetRightMargin()
        ypos = 1. - ROOT.gPad.GetTopMargin()
        self.lxtitle = TLatex(0., 0., 'Z')
        self.lxtitle.SetNDC(True)
        self.lxtitle.SetTextFont(42)
        self.lxtitle.SetTextSize(0.07)
        self.lxtitle.SetTextAlign(31)
        self.lxtitle.DrawLatex(xpos, ypos + 0.02, title)

    def addCentralplot(self,
                       filename,
                       histpath,
                       title,
                       scale,
                       color,
                       projection=''):
        if filename not in self.tfiles:
            self.tfiles[filename] = TFile(filename, 'read')
        if projection == 'Y':
            self.MCplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionY()))
        elif projection == 'X':
            self.MCplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionX()))
        else:
            self.MCplots.append(TH1D(self.tfiles[filename].Get(histpath)))
        #self.MCplots[-1].SetFillColor(color)
        self.MCplots[-1].SetLineColor(color)
        #self.MCplots[-1].Scale(scale, 'width')
        self.MCplots[-1].Scale(scale)
        self.MCplots[-1].SetTitle(title)
        return self.MCplots

    def addTplotUp(self,
                   filename,
                   histpath,
                   title,
                   scale,
                   color,
                   projection=''):
        if filename not in self.tfiles:
            self.tfiles[filename] = TFile(filename, 'read')
        if projection == 'Y':
            self.MCplotsUp.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionY()))
        elif projection == 'X':
            self.MCplotsUp.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionX()))
        else:
            self.MCplotsUp.append(TH1D(self.tfiles[filename].Get(histpath)))
        self.MCplotsUp[-1].SetLineColor(color)
        self.MCplotsUp[-1].SetTitle(title)
        self.MCplotsUp[-1].Scale(scale)
        #self.MCplotsUp[-1].Scale(1., 'width')
        #self.MCplotsUp[-1].Scale(1.)//close box
        return self.MCplotsUp

    def addTplotDown(self,
                     filename,
                     histpath,
                     title,
                     scale,
                     color,
                     projection=''):
        if filename not in self.tfiles:
            self.tfiles[filename] = TFile(filename, 'read')
        if projection == 'Y':
            self.MCplotsDown.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionY()))
        elif projection == 'X':
            self.MCplotsDown.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionX()))
        else:
            self.MCplotsDown.append(TH1D(self.tfiles[filename].Get(histpath)))
        self.MCplotsDown[-1].SetLineColor(color)
        self.MCplotsDown[-1].SetTitle(title)
        self.MCplotsDown[-1].Scale(scale)
        #self.MCplots[-1].Scale(1., 'width')
        #self.MCplots[-1].Scale(1.)//close box
        return self.MCplotsDown

    def addOtherplot(self,
                     filename,
                     histpath,
                     title,
                     scale,
                     color,
                     projection=''):
        if filename not in self.tfiles:
            self.tfiles[filename] = TFile(filename, 'read')
        if projection == 'Y':
            self.Otherplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionY()))
        elif projection == 'X':
            self.Otherplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionX()))
        else:
            self.Otherplots.append(TH1D(self.tfiles[filename].Get(histpath)))
        self.Otherplots[-1].SetLineColor(color)
        self.Otherplots[-1].SetTitle(title)
        self.Otherplots[-1].Scale(scale)
        return self.Otherplots

    def drawAddWithRelUnc(self,
                          options='hist',
                          rebin=1,
                          legtitle='',
                          title='',
                          ratio=False,
                          rangemin=0.,
                          rangemax=0.,
                          printbinwidth=True,
                          xtitle='',
                          ytitle='',
                          logy=False):
        self.cumaddhist = []
        self.cumaddhist.append(TH1D(self.MCplots[0]))
        self.cumaddhist.append(TH1D(self.Otherplots[0]))
        self.cumaddhist.append(TH1D(self.Otherplots[1]))
        for hist in self.MCplots[1:]:
            self.cumaddhist.append(TH1D(self.cumaddhist[-1]))
            self.cumaddhist[-1].Add(hist)
            self.cumaddhist[-1].SetFillColor(hist.GetFillColor())
            self.cumaddhist[-1].SetLineColor(hist.GetLineColor())
            self.cumaddhist[-1].SetTitle(hist.GetTitle())

        totalevents = 0.
        for hist in self.MCplots:
            if rangemin != rangemax:
                hist.GetXaxis().SetRangeUser(rangemin, rangemax)
            totalevents += hist.Integral()
        print 'Total MC events: ', totalevents
        totalevents = 0.
        for hist in self.DAplots:
            if rangemin != rangemax:
                hist.GetXaxis().SetRangeUser(rangemin, rangemax)
            totalevents += hist.Integral()
        print 'Total DA events: ', totalevents
        mymax = 0.
        self.Canvases.append(
            TCanvas('CanvasAdd_' + self.cumaddhist[-1].GetName(),
                    'CanvasAdd_' + self.cumaddhist[-1].GetName(), 800, 600))
        if ratio == True:
            split = 0.3
            spaceleft = 0.15
            spaceright = 0.05
            self.Pads.append(TPad("histpad", "histpad", 0, split, 1., 1.))
            self.Pads[-1].SetTopMargin(0.05)
            self.Pads[-1].SetBottomMargin(0.022)
            self.Pads[-1].SetLeftMargin(spaceleft)
            self.Pads[-1].SetRightMargin(spaceright)
            self.Pads[-1].Draw()
            self.Canvases[-1].cd()
            self.Pads.append(TPad("divpad", "divpad", 0, 0, 1., split))
            self.Pads[-1].SetTopMargin(0.0)
            self.Pads[-1].SetBottomMargin(0.4)
            self.Pads[-1].SetLeftMargin(spaceleft)
            self.Pads[-1].SetRightMargin(spaceright)
            self.Pads[-1].Draw()
            self.Pads[-2].cd()

        if len(title) > 0:
            ROOT.gPad.SetTopMargin(0.1)
        self.legend(legtitle)
        if ratio == True:
            self.cumaddhist[-1].GetXaxis().SetTitleOffset(5.)
            self.cumaddhist[-1].GetXaxis().SetLabelOffset(5.)

        for hist in reversed(self.cumaddhist):
            hist.Rebin(rebin)
            hist.Draw(options)

            mymax = max(mymax, hist.GetMaximum())
            if rangemin != 0 or rangemax != 0:
                hist.GetXaxis().SetRangeUser(rangemin, rangemax)
            if 'same' not in options:
                units = re.findall('\[.*\]', hist.GetXaxis().GetTitle())
                unit = ''
                if len(units) == 1:
                    unit = units[0][1:-1]
                if ytitle == '':
                    if len(hist.GetYaxis().GetTitle()) == 0:
                        ytitle = 'Events'
                    else:
                        ytitle = hist.GetYaxis().GetTitle()
                        #ytitle = ytitle.lower()
                if printbinwidth == True:
                    hist.GetYaxis().SetTitle(
                        ytitle +
                        ' / {0:g}'.format(hist.GetXaxis().GetBinWidth(1)) +
                        ' ' + unit)
                else:
                    hist.GetYaxis().SetTitle(ytitle)
                if (xtitle != ''):
                    hist.GetXaxis().SetTitle(xtitle)
                options += ' same'
        for op in self.Otherplots:
            op.Rebin(rebin)
            op.SetLineWidth(2)
            #op.Draw('sameE0')//close box
            mymax = max(mymax, op.GetMaximum())
        if len(self.DAplots) == 1:
            self.DAplots[0].Rebin(rebin)
            self.DAplots[0].SetMarkerStyle(20)
            self.DAplots[0].SetMarkerSize(1.1)
            self.DAplots[0].SetLineWidth(2)
            self.DAplots[0].Draw('E1X0same')
            mymax = max(mymax, self.DAplots[0].GetMaximum())
        if len(self.DAplots) == 1:
            self.lg.AddEntry(self.DAplots[0], self.DAplots[0].GetTitle(), 'p')
        for hist in reversed(self.cumaddhist):
            if len(hist.GetTitle()) != 0:
                self.lg.AddEntry(hist, hist.GetTitle(), 'f')
        for op in self.Otherplots:
            self.lg.AddEntry(op, op.GetTitle(), 'l')
        self.lg.Draw()
        self.settitle(title)
        self.setchannel()
        self.cmstext()
        if logy == False:
            self.cumaddhist[-1].GetYaxis().SetRangeUser(0, mymax * 1.5)
        if logy == True:
            self.cumaddhist[-1].GetYaxis().SetRangeUser(10, mymax * 50)
            self.Pads[-2].SetLogy(True)

        self.Pads[-2].RedrawAxis()
        if ratio == True:
            self.Pads[-1].cd()
            self.Pads[-1].SetGridy()
            self.DIVplots.append(TH1D(self.Otherplots[0]))
            self.DIVplots.append(TH1D(self.Otherplots[1]))
            if (xtitle != ''):
                self.DIVplots[-1].GetXaxis().SetTitle(xtitle)
            #self.DIVplots[-1].Divide(self.cumaddhist[-1])
            for b in range(1, self.DIVplots[-1].GetNbinsX() + 1):
                if (self.cumaddhist[-1].GetBinContent(b) > 0.):
                    divval = self.DIVplots[-1].GetBinContent(
                        b) / self.cumaddhist[-1].GetBinContent(b)
                    divvalerr = self.DIVplots[-1].GetBinError(
                        b) / self.cumaddhist[-1].GetBinContent(b)
                    self.DIVplots[-1].SetBinContent(b, divval)
                    #self.DIVplots[-1].SetBinError(b, divvalerr)
                    self.DIVplots[-1].SetBinError(
                        b,
                        math.sqrt(divvalerr**2 +
                                  (self.cumaddhist[-1].GetBinError(b) /
                                   self.cumaddhist[-1].GetBinContent(b))**2))
                else:
                    self.DIVplots[-1].SetBinContent(b, 0.)
                    self.DIVplots[-1].SetBinError(b, 0.)
            self.DIVplots[-1].SetMarkerSize(1.1)
            self.DIVplots[-1].Draw('E1X0same')
            self.DIVplots[-1].GetXaxis().SetTitleOffset(3)
            self.DIVplots[-1].GetYaxis().SetTitle('relative unc')
            self.DIVplots[-1].GetYaxis().SetTitleOffset(1.3)
            self.DIVplots[-1].GetYaxis().SetRangeUser(0.5, 1.5)
            self.DIVplots[-1].GetYaxis().SetNdivisions(105)
            if rangemin != 0 or rangemax != 0:
                self.DIVplots[-1].GetXaxis().SetRangeUser(rangemin, rangemax)
            self.DIVplots[-1].Draw('E1X0same')
        self.Pads[-1].RedrawAxis()

        return (self.Canvases[-1])
def compareMassRes(trackType):

    fileEOYBB = open("MassResolutionVsMass_TunePNew_BB_EOY.pkl", "rb")
    fileEOYBE = open("MassResolutionVsMass_TunePNew_BE_EOY.pkl", "rb")
    fileULBB = open("default/MassResolutionVsMass_TunePNew_BB.pkl", "rb")
    fileULBE = open("default/MassResolutionVsMass_TunePNew_BE.pkl", "rb")

    resultsEOYBB = pickle.load(fileEOYBB)
    resultsEOYBE = pickle.load(fileEOYBE)
    resultsULBB = pickle.load(fileULBB)
    resultsULBE = pickle.load(fileULBE)

    graphEOYBB = getGraph(resultsEOYBB, "EOYBB")
    graphEOYBE = getGraph(resultsEOYBE, "EOYBE")
    graphULBB = getGraph(resultsULBB, "ULBB")
    graphULBE = getGraph(resultsULBE, "ULBE")

    ratioBB = getRatio(resultsEOYBB, resultsULBB, "ratioBB")
    ratioBE = getRatio(resultsEOYBE, resultsULBE, "ratioBE")

    canv = TCanvas("c1", "c1", 800, 800)

    plotPad = TPad("plotPad", "plotPad", 0.01, 0.01, 0.99, 0.99)

    ratioPad = TPad("ratioPad", "ratioPad", 0.01, 0.01, 0.99, 0.29)
    style = setTDRStyle()
    gStyle.SetOptStat(0)
    plotPad.UseCurrentStyle()
    ratioPad.UseCurrentStyle()
    plotPad.Draw()
    ratioPad.Draw()
    plotPad.cd()
    plotPad.cd()
    # ~ plotPad.SetGrid()
    gStyle.SetTitleXOffset(1.45)
    gStyle.SetTitleYOffset(1.55)

    plotPad.SetTopMargin(0.05)
    plotPad.SetLeftMargin(0.13)
    plotPad.SetRightMargin(0.045)
    plotPad.SetBottomMargin(0.3)

    ratioPad.SetTopMargin(0)
    ratioPad.SetTopMargin(0.05)
    ratioPad.SetLeftMargin(0.13)
    ratioPad.SetRightMargin(0.045)
    ratioPad.SetBottomMargin(0.4)

    #~ xMax = 0.08
    #~ if trackType == "Inner":
    #~ xMax = 0.2
    #~ if trackType == "Outer":
    #~ xMax = 0.4

    graphEOYBB.SetMarkerStyle(22)
    graphEOYBB.SetMarkerSize(2)
    graphEOYBB.SetMarkerColor(kBlack)
    graphEOYBB.SetLineColor(kBlack)
    graphEOYBB.SetLineWidth(2)
    graphEOYBB.SetFillColor(0)
    graphEOYBB.SetTitle("Dimuon mass resolution vs pT for %s tracks" %
                        trackType)
    graphEOYBB.GetYaxis().SetTitle("Mass resolution")
    # ~ res_data.GetXaxis().SetTitle("p_{T} (#mu^{#pm}) [GeV]")
    graphEOYBB.GetYaxis().SetTitleFont(42)
    graphEOYBB.GetYaxis().SetTitleSize(0.05)
    graphEOYBB.GetYaxis().SetTitleOffset(1.35)
    graphEOYBB.GetYaxis().SetLabelFont(42)
    graphEOYBB.GetYaxis().SetLabelSize(0.038)
    graphEOYBB.GetYaxis().SetRangeUser(0, 0.1)
    graphEOYBB.GetXaxis().SetTitleSize(0.0)
    graphEOYBB.GetXaxis().SetLabelSize(0.0)

    graphEOYBB.GetXaxis().SetRangeUser(0, 6500)
    graphEOYBB.Draw("AP E0")

    graphULBB.Draw("samepe")
    graphEOYBB.SetMarkerSize(2)
    graphULBB.SetMarkerSize(2)
    graphEOYBB.SetLineWidth(2)
    graphULBB.SetLineWidth(2)
    graphEOYBB.SetMarkerStyle(20)
    graphULBB.SetMarkerStyle(21)
    graphULBB.SetLineColor(kRed)
    graphULBB.SetMarkerColor(kRed)

    latex = TLatex()
    # ~ latex.SetTextFont(42)
    # ~ latex.SetTextAlign(31)
    # ~ latex.SetTextSize(0.04)
    # ~ latex.SetNDC(True)
    latexCMS = TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(.03 / 0.7)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatexNDC(
        0.50, 0.96,
        "#scale[0.8]{#font[42]{       2017, 42.1 fb^{-1} (13 TeV)}}")

    cmsExtra = "Preliminary"
    latexCMS.DrawLatex(0.19, 0.88, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.81
    else:
        yLabelPos = 0.84

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    leg = TLegend(0.5, 0.65, 0.95, 0.90, "Both muons |#eta| < 1.2", "brNDC")
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    leg.AddEntry(graphEOYBB, "EOY ReReco", "l")
    leg.AddEntry(graphULBB, "Legacy ReReco", "l")

    leg.Draw()

    plotPad.RedrawAxis()

    ratioPad.cd()

    ratioBB.GetYaxis().SetTitle("#splitline{EOY ReReco/}{Legacy ReReco}")
    ratioBB.GetXaxis().SetNoExponent(0)
    ratioBB.GetXaxis().SetTitleFont(42)
    ratioBB.GetXaxis().SetTitleOffset(0.85)
    ratioBB.GetXaxis().SetTitleSize(0.2)
    ratioBB.GetXaxis().SetLabelColor(1)
    ratioBB.GetXaxis().SetLabelOffset(0.01)
    ratioBB.GetXaxis().SetLabelFont(42)
    ratioBB.GetXaxis().SetLabelSize(0.17)
    ratioBB.GetXaxis().SetTitle("GEN dimuon mass (GeV)")
    ratioBB.GetYaxis().SetRangeUser(0.5, 1.5)
    ratioBB.GetXaxis().SetRangeUser(0, 6500)
    ratioBB.GetYaxis().SetTitleOffset(0.475)
    ratioBB.GetYaxis().SetTitleSize(0.12)
    ratioBB.GetYaxis().SetTitleFont(42)
    ratioBB.GetYaxis().SetLabelSize(0.14)
    ratioBB.GetYaxis().SetLabelOffset(0.007)
    ratioBB.GetYaxis().SetLabelFont(42)
    ratioBB.GetYaxis().SetNdivisions(505)

    ratioBB.SetMarkerColor(kRed)
    ratioBB.SetLineColor(kRed)
    ratioBB.SetLineWidth(2)
    ratioBB.SetMarkerStyle(20)
    ratioBB.SetMarkerSize(2)

    line = TLine(10, 1, 6500, 1)

    line.SetLineColor(kBlack)
    line.SetLineStyle(kDashed)
    line.SetLineWidth(2)

    ratioBB.Draw("A P E")
    ratioBB.GetXaxis().SetRangeUser(0, 6500)

    line.Draw()
    ratioBB.Draw("samePE")
    ratioPad.RedrawAxis()

    canv.Print("massResolutionCompareUL_%s_BB.pdf" % trackType)

    canv = TCanvas("c1", "c1", 800, 800)

    plotPad = TPad("plotPad", "plotPad", 0.01, 0.01, 0.99, 0.99)

    ratioPad = TPad("ratioPad", "ratioPad", 0.01, 0.01, 0.99, 0.29)
    style = setTDRStyle()
    gStyle.SetOptStat(0)
    plotPad.UseCurrentStyle()
    ratioPad.UseCurrentStyle()
    plotPad.Draw()
    ratioPad.Draw()
    plotPad.cd()
    plotPad.cd()
    # ~ plotPad.SetGrid()
    gStyle.SetTitleXOffset(1.45)
    gStyle.SetTitleYOffset(1.55)

    plotPad.SetTopMargin(0.05)
    plotPad.SetLeftMargin(0.13)
    plotPad.SetRightMargin(0.045)
    plotPad.SetBottomMargin(0.3)

    ratioPad.SetTopMargin(0)
    ratioPad.SetTopMargin(0.05)
    ratioPad.SetLeftMargin(0.13)
    ratioPad.SetRightMargin(0.045)
    ratioPad.SetBottomMargin(0.4)

    #~ xMax = 0.08
    #~ if trackType == "Inner":
    #~ xMax = 0.2
    #~ if trackType == "Outer":
    #~ xMax = 0.4

    graphEOYBE.SetMarkerStyle(22)
    graphEOYBE.SetMarkerSize(2)
    graphEOYBE.SetMarkerColor(kBlack)
    graphEOYBE.SetLineColor(kBlack)
    graphEOYBE.SetLineWidth(2)
    graphEOYBE.SetFillColor(0)
    graphEOYBE.SetTitle("Dimuon mass resolution vs pT for %s tracks" %
                        trackType)
    graphEOYBE.GetYaxis().SetTitle("Mass resolution")
    # ~ res_data.GetXaxis().SetTitle("p_{T} (#mu^{#pm}) [GeV]")
    graphEOYBE.GetYaxis().SetTitleFont(42)
    graphEOYBE.GetYaxis().SetTitleSize(0.05)
    graphEOYBE.GetYaxis().SetTitleOffset(1.35)
    graphEOYBE.GetYaxis().SetLabelFont(42)
    graphEOYBE.GetYaxis().SetLabelSize(0.038)
    graphEOYBE.GetYaxis().SetRangeUser(0, .2)
    graphEOYBE.GetXaxis().SetTitleSize(0.0)
    graphEOYBE.GetXaxis().SetLabelSize(0.0)

    graphEOYBE.GetXaxis().SetRangeUser(0, 6500)
    graphEOYBE.Draw("AP E0")

    graphULBE.Draw("samepe")
    graphEOYBE.SetMarkerSize(2)
    graphULBE.SetMarkerSize(2)
    graphEOYBE.SetLineWidth(2)
    graphULBE.SetLineWidth(2)
    graphEOYBE.SetMarkerStyle(20)
    graphULBE.SetMarkerStyle(21)
    graphULBE.SetLineColor(kRed)
    graphULBE.SetMarkerColor(kRed)

    latex = TLatex()
    # ~ latex.SetTextFont(42)
    # ~ latex.SetTextAlign(31)
    # ~ latex.SetTextSize(0.04)
    # ~ latex.SetNDC(True)
    latexCMS = TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(.03 / 0.7)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatexNDC(
        0.50, 0.96,
        "#scale[0.8]{#font[42]{       2017, 42.1 fb^{-1} (13 TeV)}}")

    cmsExtra = "Preliminary"
    latexCMS.DrawLatex(0.19, 0.88, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.81
    else:
        yLabelPos = 0.84

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    leg = TLegend(0.5, 0.65, 0.95, 0.90, "At least one muon |#eta| > 1.2",
                  "brNDC")
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    leg.AddEntry(graphEOYBE, "EOY ReReco", "lp")
    leg.AddEntry(graphULBE, "Legacy  ReReco", "lp")

    leg.Draw()

    plotPad.RedrawAxis()

    ratioPad.cd()

    ratioBE.GetYaxis().SetTitle("#splitline{EOY ReReco/}{Legacy ReReco}")
    ratioBE.GetXaxis().SetNoExponent(0)
    ratioBE.GetXaxis().SetTitleFont(42)
    ratioBE.GetXaxis().SetTitleOffset(0.85)
    ratioBE.GetXaxis().SetTitleSize(0.2)
    ratioBE.GetXaxis().SetLabelColor(1)
    ratioBE.GetXaxis().SetLabelOffset(0.01)
    ratioBE.GetXaxis().SetLabelFont(42)
    ratioBE.GetXaxis().SetLabelSize(0.17)
    ratioBE.GetXaxis().SetTitle("GEN dimuon mass (GeV)")
    ratioBE.GetYaxis().SetRangeUser(0.5, 1.5)
    ratioBE.GetXaxis().SetRangeUser(0, 6500)
    ratioBE.GetYaxis().SetTitleOffset(0.475)
    ratioBE.GetYaxis().SetTitleSize(0.12)
    ratioBE.GetYaxis().SetTitleFont(42)
    ratioBE.GetYaxis().SetLabelSize(0.14)
    ratioBE.GetYaxis().SetLabelOffset(0.007)
    ratioBE.GetYaxis().SetLabelFont(42)
    ratioBE.GetYaxis().SetNdivisions(505)

    ratioBE.SetMarkerColor(kRed)
    ratioBE.SetLineColor(kRed)
    ratioBE.SetLineWidth(2)
    ratioBE.SetMarkerStyle(20)
    ratioBE.SetMarkerSize(2)

    line = TLine(10, 1, 6500, 1)

    line.SetLineColor(kBlack)
    line.SetLineStyle(kDashed)
    line.SetLineWidth(2)

    ratioBE.Draw("A P E")
    ratioBE.GetXaxis().SetRangeUser(0, 6500)

    line.Draw()
    ratioBE.Draw("samePE")
    ratioPad.RedrawAxis()
    ratioBE.Draw("samepe")

    canv.Print("massResolutionCompareUL_%s_BE.pdf" % trackType)
def main():


	# ~ pdfs = ["NNPDF30","NNPDF31","NNPDF23"]
	pdfs = ["NNPDF23"]
	path = "/run/media/jan/data/work/PDF/forReal/"
	filesDefault = [path+"dileptonAna_pdf_CITo2Mu_Lam16TeVConLL_M300to800.root",path+"dileptonAna_pdf_CITo2Mu_Lam16TeVConLL_M800to1300.root",path+"dileptonAna_pdf_CITo2Mu_Lam16TeVConLL_M1300to2000.root",path+"dileptonAna_pdf_CITo2Mu_Lam16TeVConLL_M2000toInf.root"]
	files23v2 = [path+"dileptonAna_pdf_2016_CITo2Mu_Lam16TeVConRR_M300.root",path+"dileptonAna_pdf_2016_CITo2Mu_Lam16TeVConRR_M800.root",path+"dileptonAna_pdf_2016_CITo2Mu_Lam16TeVConRR_M1300.root"]


	for pdf in pdfs:

		canv = TCanvas("c1","c1",800,800)	
		plotPad = TPad("plotPad","plotPad",0,0,1,1)
		style = setTDRStyle()
		gStyle.SetOptStat(0)
		plotPad.UseCurrentStyle()
		plotPad.Draw()
		plotPad.cd()
		
		leg = TLegend(0.52, 0.71, 0.89, 0.92,"","brNDC")
		leg.SetFillColor(10)
		leg.SetFillStyle(0)
		leg.SetLineColor(10)
		leg.SetShadowColor(0)
		leg.SetBorderSize(1)	
			
		leg2 = TLegend(0.52, 0.71, 0.89, 0.92,"","brNDC")
		leg2.SetFillColor(10)
		leg2.SetFillStyle(0)
		leg2.SetLineColor(10)
		leg2.SetShadowColor(0)
		leg2.SetBorderSize(1)		


		
		# ~ binning = [400,500,600,700,800,900,1000,1200,1400,1600,1800,2000,2400,2800,3200,3600,4000,4500,5000]
		# ~ binning = [0,500,1000,1500,2000,2500,3000,3500,4000,4500,5000]
		# ~ binning = [400,500,700,1100,1900,3500,13000]
		binning = [1800, 2200, 2600, 3000, 3400, 10000]
		# ~ binning =[400, 700, 1500, 2500, 3500,10000]
		# ~ binning =[2200,10000]
		hists = []
		weightSums = []
		for i in range(0,100):
			weightSums.append(0)
			hists.append(TH1F("hist_%s_%d"%(pdf,i),"hist_%s_%d"%(pdf,i),len(binning)-1,array('f',binning)))
		
		if pdf == "NNPDF23v2":
			files = files23v2
		else:
			files = filesDefault
		nnn = len(files)
		for index, fileName in enumerate(files):
			
			f = TFile(fileName,"OPEN")
			tree = f.Get("pdfTree")
			xsec = xsecs[fileName.split("dileptonAna_pdf_")[-1].split(".root")[0]]
			print ("processing sample %d / %d"%(index+1,nnn))
			sampleWeight = xsec/tree.GetEntries()
			for ev in tree:
				if ev.recoMass < 0: continue
				genMass = tree.GetLeaf("pdfInfo/scale").GetValue()
				central_value = getWeight(pdf, ev, 0, tree.GetLeaf("pdfInfo/scale").GetValue(), tree.GetLeaf("pdfInfo/x1").GetValue(), tree.GetLeaf("pdfInfo/x2").GetValue(), tree.GetLeaf("pdfInfo/pdf1").GetValue(), tree.GetLeaf("pdfInfo/pdf2").GetValue())
				weightSums[0] += central_value
				hists[0].Fill(genMass,sampleWeight)
				# ~ print ( CalculateLHAPDFWeight(pdfReplicasRef[0], tree.GetLeaf("pdfInfo/scale").GetValue(), tree.GetLeaf("pdfInfo/x1").GetValue(), tree.GetLeaf("pdfInfo/x2").GetValue(), tree.GetLeaf("pdfInfo/pdf1").GetValue(), tree.GetLeaf("pdfInfo/pdf2").GetValue()), ev.pdfWeightsNNPDF31[0])
				for i in range(1,100):
					localValue = getWeight(pdf, ev, i, tree.GetLeaf("pdfInfo/scale").GetValue(), tree.GetLeaf("pdfInfo/x1").GetValue(), tree.GetLeaf("pdfInfo/x2").GetValue(), tree.GetLeaf("pdfInfo/pdf1").GetValue(), tree.GetLeaf("pdfInfo/pdf2").GetValue())
					if  localValue/central_value > 10 or localValue/central_value < 0.1 : continue 
					weightSums[i] += localValue
					hists[i].Fill(genMass,localValue/central_value*sampleWeight)
		hists[0].SetMarkerColor(ROOT.kRed)			
		for i in range(0,100):
			if i == 0: hists[0].Draw()
			else: hists[i].Draw("samehist")
		hists[0].Draw("same")	
		hists[0].GetXaxis().SetTitle("generated mass [GeV]")	
		hists[0].GetYaxis().SetTitle("N Events")	
		leg2.AddEntry(hists[0],"central value","p")	
		leg2.AddEntry(hists[1],"variations","l")	
		leg2.Draw()
		ROOT.gPad.SetLogy()
		canv.Print("hists_%s.pdf"%pdf)			
			
		changeUp = []	
		changeDown = []
		change = []
		changeNormUp = []	
		changeNormDown = []
		changeNorm = []
		
		for y in range(0,hists[0].GetNbinsX()):
				changeUp.append([])
				changeDown.append([])
				change.append([])
				changeNormUp.append([])
				changeNormDown.append([])
				changeNorm.append([])
		for i in range(0,100):
			hists[i]
			if i > 0:
				print (weightSums[0]/weightSums[i])
				for y in range(1,hists[0].GetNbinsX()+1):
					changeNorm[y-1].append(abs((hists[i].GetBinContent(y) - hists[0].GetBinContent(y))/hists[0].GetBinContent(y))*(weightSums[0]/weightSums[i]))
					change[y-1].append(abs((hists[i].GetBinContent(y) - hists[0].GetBinContent(y))/hists[0].GetBinContent(y)))
					if (hists[i].GetBinContent(y) - hists[0].GetBinContent(y)) < 0:
						changeDown[y-1].append((hists[i].GetBinContent(y) - hists[0].GetBinContent(y))/hists[0].GetBinContent(y))
						changeNormDown[y-1].append((hists[i].GetBinContent(y) - hists[0].GetBinContent(y))/hists[0].GetBinContent(y)*(weightSums[0]/weightSums[i]))
					if (hists[i].GetBinContent(y) - hists[0].GetBinContent(y)) > 0:
						changeUp[y-1].append((hists[i].GetBinContent(y) - hists[0].GetBinContent(y))/hists[0].GetBinContent(y))
						changeNormUp[y-1].append((hists[i].GetBinContent(y) - hists[0].GetBinContent(y))/hists[0].GetBinContent(y)*(weightSums[0]/weightSums[i]))

		plotPad = TPad("plotPad","plotPad",0,0,1,1)			
		plotPad.UseCurrentStyle()
		plotPad.Draw()
		plotPad.cd()
		plotPad.DrawFrame(400,0,5000,0.3,";generated mass [GeV];PDF Uncert")

		masses = []
		for i in range(0,len(binning)-1):
			masses.append((binning[i]+binning[i+1])/2)
		
		graphUp = TGraph()
		graphDown = TGraph()
		graph = TGraph()
		graphNormUp = TGraph()
		graphNormDown = TGraph()
		graphNorm = TGraph()
		print(len(masses),len(changeUp),len(changeDown))
		for i in range(0,len(masses)):
			print(i, len(changeUp[i]), len(changeDown[i]))
			graphUp.SetPoint(i,masses[i],sorted(changeUp[i])[int(len(changeUp[i])*0.67)])
			graphDown.SetPoint(i,masses[i],sorted(changeDown[i])[int(len(changeDown[i])*0.33)])
			uncert = (sorted(change[i])[84]-sorted(change[i])[16])/2
			print (uncert)
			graph.SetPoint(i,masses[i],uncert)

			graphNormUp.SetPoint(i,masses[i],sorted(changeNormUp[i])[int(len(changeNormUp[i])*0.67)])
			graphNormDown.SetPoint(i,masses[i],sorted(changeNormDown[i])[int(len(changeNormDown[i])*0.33)])
			uncertNorm = (sorted(changeNorm[i])[84]-sorted(changeNorm[i])[16])/2
			graphNorm.SetPoint(i,masses[i],uncertNorm)
			

		
		graph.Draw("lp")
		graphNorm.Draw("lpsame")
		graphNorm.SetMarkerColor(ROOT.kRed)
		graphNorm.SetLineColor(ROOT.kRed)

		func = ROOT.TF1("f1","pol4")
		graph.Fit("f1")
		leg.AddEntry(graph,"PDF uncertainty for %s"%pdf,"pl")

		canv.Print("pdfUncertainty_%s.pdf"%pdf)
Пример #28
0
def PlotLimits(Type):

    theory_x = array('d', [
        800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1900, 2100,
        2300, 2500
    ])
    if Type == 'Right':
        theory_y = array('d', [
            1.2 * 1.6997, 1.2 * 0.97609, 1.2 * 0.58782, 1.2 * 0.36266,
            1.2 * 0.22815, 1.2 * 0.14584, 1.2 * 0.09445, 1.2 * 0.06195,
            1.2 * 0.04102, 1.2 * 0.027453, 1.2 * 0.012585, 1.2 * 0.005984,
            1.2 * 0.0029719, 1.2 * 0.0015585
        ])
    theory_xv = TVectorD(len(theory_x), theory_x)
    theory_yv = TVectorD(len(theory_y), theory_y)

    theory = TGraph(theory_xv, theory_yv)
    theory.SetLineColor(2)
    theory.SetLineWidth(2)

    Nentries = Trees[Type].GetEntriesFast()

    mass = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
    exp = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
    obs = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
    exp68H = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
    exp68L = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
    exp95H = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
    exp95L = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

    masserr = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
    obserr = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
    experr = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

    m = 0
    for entry in xrange(Nentries):

        Trees[Type].GetEntry(entry)

        thismass = Trees[Type].mh
        thisquantile = Trees[Type].quantileExpected
        thislimit = Trees[Type].limit
        thislimiterr = Trees[Type].limitErr

        if thismass == 800.0: i = 0
        elif thismass == 900.0: i = 1
        elif thismass == 1000.0: i = 2
        elif thismass == 1100.0: i = 3
        elif thismass == 1200.0: i = 4
        elif thismass == 1300.0: i = 5
        elif thismass == 1400.0: i = 6
        elif thismass == 1500.0: i = 7
        elif thismass == 1600.0: i = 8
        elif thismass == 1700.0: i = 9
        elif thismass == 1900.0: i = 10
        elif thismass == 2100.0: i = 11
        elif thismass == 2300.0: i = 12
        elif thismass == 2500.0: i = 13

        #if thismass < 1000: continue

        if (abs(thisquantile + 1.000) < 0.01):
            mass[i] = thismass
            obs[i] = thislimit
            obserr[i] = 0
            masserr[i] = 0
        elif (abs(thisquantile - 0.025) < 0.01):
            exp95L[i] = thislimit
            print '95L ', thislimit
        elif (abs(thisquantile - 0.160) < 0.01):
            exp68L[i] = thislimit
        elif (abs(thisquantile - 0.500) < 0.01):
            exp[i] = thislimit
            experr[i] = thislimiterr
        elif (abs(thisquantile - 0.840) < 0.01):
            exp68H[i] = thislimit
        elif (abs(thisquantile - 0.975) < 0.01):
            exp95H[i] = thislimit

        print str(thismass) + ' ' + str(thisquantile) + ' ' + str(thislimit)

    print 'exp95L', exp95L
    print 'exp95H', exp95H
    print 'exp68L', exp68L
    print 'exp68H', exp68H

    massv = TVectorD(len(mass), mass)
    expv = TVectorD(len(mass), exp)
    obsv = TVectorD(len(mass), obs)
    exp68Hv = TVectorD(len(mass), exp68H)
    exp68Lv = TVectorD(len(mass), exp68L)
    exp95Hv = TVectorD(len(mass), exp95H)
    exp95Lv = TVectorD(len(mass), exp95L)
    #exp95Lv = TVectorD(len(mass),exp68L)

    masserrv = TVectorD(len(mass), masserr)
    obserrv = TVectorD(len(mass), obserr)
    experrv = TVectorD(len(mass), experr)

    observed = TGraphAsymmErrors(massv, obsv, masserrv, masserrv, obserrv,
                                 obserrv)
    observed.SetLineColor(ROOT.kBlack)
    observed.SetLineWidth(2)
    observed.SetMarkerStyle(20)
    expected = TGraphAsymmErrors(massv, expv, masserrv, masserrv, experrv,
                                 experrv)
    expected.SetLineColor(ROOT.kBlack)
    expected.SetLineWidth(2)
    expected.SetLineStyle(2)
    ## I'm confused, somehow this is the way that works
    expected68 = TGraphAsymmErrors(massv, expv, masserrv, masserrv, exp95Lv,
                                   exp68Hv)
    #expected68 = TGraphAsymmErrors(massv,expv,masserrv,masserrv,exp68Lv,exp68Hv)
    expected68.SetFillColor(ROOT.kGreen)
    expected95 = TGraphAsymmErrors(massv, expv, masserrv, masserrv, exp68Lv,
                                   exp95Hv)
    #expected95 = TGraphAsymmErrors(massv,expv,masserrv,masserrv,exp95Lv,exp95Hv)
    expected95.SetFillColor(ROOT.kYellow)

    c4 = TCanvas("c4", "W' tb Limits", 1000, 800)

    c4.SetBottomMargin(0.15)
    c4.SetRightMargin(0.06)

    expected95.Draw("a3")
    expected95.GetXaxis().SetTitle("W'_{" + Type + "} mass [GeV/c^{2}]")
    expected95.GetYaxis().SetTitle("#sigma(pp#rightarrowW/W'_{" + str(Type) +
                                   "}#rightarrowtb) [pb]")
    expected68.Draw("3same")
    expected.Draw("csame")
    observed.Draw("cpsame")
    theory.Draw("csame")

    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.04)
    latex.SetTextAlign(31)  # align right
    latex.DrawLatex(0.45, 0.95, "CMS Preliminary")

    latex2 = TLatex()
    latex2.SetNDC()
    latex2.SetTextSize(0.04)
    latex2.SetTextAlign(31)  # align right
    latex2.DrawLatex(0.87, 0.95,
                     str(lumiPlot) + " fb^{-1} at #sqrt{s} = 7 TeV")

    latex4 = TLatex()
    latex4.SetNDC()
    latex4.SetTextSize(0.04)
    latex4.SetTextAlign(31)  # align right
    latex4.DrawLatex(0.80, 0.87, "e+jets N_{b tags} #geq 1 ")

    legend = TLegend(.566, .684, .84, .84)
    legend.AddEntry(observed, '95% C.L. Observed', "lp")
    legend.AddEntry(expected, '95% C.L. Expected', "l")
    legend.AddEntry(expected68, '#pm 1#sigma Expected', "f")
    legend.AddEntry(expected95, '#pm 2#sigma Expected', "f")

    legend.SetShadowColor(0)
    legend.SetFillColor(0)
    legend.SetLineColor(0)
    legend.Draw()

    c4.SaveAs('Wprime_' + Type + '_Limits.root')
    c4.SaveAs('Wprime_' + Type + '_Limits.png')
Пример #29
0
for ilayer, layer in enumerate(layers):
    for iplot, plot in enumerate(plots):
        print "\nPLOT %i / %i" % (
                iplot
                + ilayer * len(plots)
                + 1
            , len(layers) * len(plots))
        # Do TH2 histos
        plotname = 'h_%s_%s' % (plot, layer)
        if 'TH2' in plots[plot]['class']:
            c2.cd()
            legend = TLegend(0.25, 0.72, 0.80, 0.93, "")
            legend.SetNColumns(2)
            legend.SetFillColor(ROOT.kWhite)
            legend.SetLineColor(ROOT.kWhite)
            legend.SetShadowColor(ROOT.kWhite)
            for irun, run in enumerate(runs):
                for ilumisection, lumisection in enumerate(lumisections):
                    for ibx, bx in enumerate(bxs):
#                    for ibx, bx in enumerate(bx_list):
                        for k in keyList:
                            if plots[plot]['histname'] not in k:
                                continue
                            if layer not in k or str(run) not in k:
                                continue
#                        if 'LS_%i-%i_%s' % (lumisection[0], lumisection[1], layer) not in k:
                            if '_%i-%i_%s' % (lumisection[0], lumisection[1], layer) not in k:
                                continue
                            if bx not in k:
                                continue
                            h = f.Get(k)
Пример #30
0
def compareMassRes(trackType):

    fileCB = open(
        "BoosteddefaultLeadingCB/MassResolutionVsPt_%s_BE16.pkl" % trackType,
        "rb")
    fileDCB = open(
        "BoosteddefaultLeading/MassResolutionVsPt_%s_BE16.pkl" % trackType,
        "rb")
    fileCruijff = open(
        "BoosteddefaultLeadingCruijff/MassResolutionVsPt_%s_BE16.pkl" %
        trackType, "rb")

    resultsCB = pickle.load(fileCB)
    resultsDCB = pickle.load(fileDCB)
    resultsCruijff = pickle.load(fileCruijff)

    graphCB = getGraph(resultsCB, "CB", Data=True)
    graphDCB = getGraph(resultsDCB, "DCB", Data=True)
    graphCruijff = getGraph(resultsCruijff, "Cruijff", Data=True)

    ratioCB = getRatio(resultsCB, resultsDCB, "ratioCB", Data=True)
    ratioCruijff = getRatio(resultsCruijff,
                            resultsDCB,
                            "ratioCruijff",
                            Data=True)

    canv = TCanvas("c1", "c1", 800, 800)

    plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1)
    #~ ratioPad = TPad("ratioPad","ratioPad",0,0.,1,0.3)
    style = setTDRStyle()
    gStyle.SetOptStat(0)
    plotPad.UseCurrentStyle()
    #~ ratioPad.UseCurrentStyle()
    plotPad.Draw()
    #~ ratioPad.Draw()
    plotPad.cd()
    plotPad.cd()
    plotPad.SetGrid()
    gStyle.SetTitleXOffset(1.45)

    xMax = 20
    if trackType == "Inner":
        xMax = 10
    if trackType == "Outer":
        xMax = 20

    plotPad.DrawFrame(0, 0, 452, xMax, ";p_{T} [GeV]; #chi^{2}/N_{dof}")

    graphCB.Draw("samepe")
    graphDCB.Draw("samepe")
    graphCruijff.Draw("samepe")
    graphDCB.SetLineColor(kRed)
    graphDCB.SetMarkerColor(kRed)
    graphCruijff.SetLineColor(kBlue)
    graphCruijff.SetMarkerColor(kBlue)

    latex = TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatex(0.95, 0.96, "(13 TeV)")

    cmsExtra = "#splitline{Preliminary}{}"
    latexCMS.DrawLatex(0.19, 0.88, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.81
    else:
        yLabelPos = 0.84

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s BB" % trackType, "brNDC")
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    leg.AddEntry(graphCB, "Single-Sided CB", "l")
    leg.AddEntry(graphDCB, "Double-Sided CB", "l")
    leg.AddEntry(graphCruijff, "Cruijff", "l")

    leg.Draw()

    plotPad.RedrawAxis()

    #~ ratioPad.cd()

    #~ ratioBB.SetLineColor(kRed)

    #~ ratioPad.DrawFrame(0,0.5,6000,1.5,";;ratio")

    #~ ratioBB.Draw("samepe")

    canv.Print("chi2CompareVsPt_%s_BE16.pdf" % trackType)