Exemple #1
0
def plot_roc_curve(roc_b, roc_c, comp_roc_b, comp_roc_c, xlimits, ylimits,
                   type, filename):
    canv = TCanvas("c1", "c1", 800, 600)
    mg = TMultiGraph()
    roc_b.SetLineColor(1)
    roc_c.SetLineColor(4)
    comp_roc_b.SetLineColor(1)
    comp_roc_c.SetLineColor(4)
    roc_b.SetMarkerColor(1)
    roc_c.SetMarkerColor(4)
    comp_roc_b.SetMarkerColor(1)
    comp_roc_c.SetMarkerColor(4)
    roc_b.SetMarkerStyle(20)
    roc_c.SetMarkerStyle(20)
    comp_roc_b.SetMarkerStyle(22)
    comp_roc_c.SetMarkerStyle(22)
    mg.Add(roc_b)
    mg.Add(roc_c)
    mg.Add(comp_roc_b)
    mg.Add(comp_roc_c)
    mg.SetTitle("; " + type + " efficiency; " + type + " fake rate")
    mg.Draw("ALP")
    mg.GetXaxis().SetLimits(xlimits[0], xlimits[1])
    mg.SetMinimum(ylimits[0])
    mg.SetMaximum(ylimits[1])
    legend = TLegend(0.15, 0.88 - 0.08 * 4, 0.3, 0.88, '', 'NDC')
    legend.AddEntry(roc_b, "b-jets (GNN)", "lp")
    legend.AddEntry(roc_c, "c-jets (GNN)", "lp")
    legend.AddEntry(comp_roc_b, "b-jets (SV1)", "p")
    legend.AddEntry(comp_roc_c, "c-jets (SV1)", "p")
    legend.SetTextSize(0.025)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.Draw("SAME")
    canv.SaveAs(filename)
    canv.Clear()
    del canv
Exemple #2
0
def printmultigraph(grs, sortk, plotoptions, outn, title, year, doext,
                    ploterror, ymax):
    import CMS_lumi, tdrstyle
    import array
    #set the tdr style
    tdrstyle.setTDRStyle()

    #change the CMS_lumi variables (see CMS_lumi.py)
    CMS_lumi.writeExtraText = 1
    CMS_lumi.extraText = "Preliminary"
    if year == 2018:
        CMS_lumi.extraText2 = "2018 pp data"
    if year == 2017:
        CMS_lumi.extraText2 = "2017 pp data"
    if year == 2016:
        CMS_lumi.extraText2 = "2016 pp data"
    CMS_lumi.lumi_sqrtS = "13 TeV"  # used with iPeriod = 0, e.g. for simulation-only plots (default is an empty string)
    CMS_lumi.writeTitle = 1
    CMS_lumi.textTitle = title

    iPos = 11
    if (iPos == 0): CMS_lumi.relPosX = 0.12

    H_ref = 600
    W_ref = 800
    W = W_ref
    H = H_ref

    iPeriod = 0
    # references for T, B, L, R
    T = 0.08 * H_ref
    B = 0.12 * H_ref
    L = 0.12 * W_ref
    R = 0.04 * W_ref

    c = TCanvas("c", "c", 50, 50, W, H)
    #gStyle.SetOptStat(0)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)
    c.SetLeftMargin(L / W)
    c.SetRightMargin(R / W)
    c.SetTopMargin(T / H)
    c.SetBottomMargin(B / H)
    c.SetTickx(0)
    c.SetTicky(0)
    #canvassettings(c)

    mg = TMultiGraph()
    #mg  = grs['main']
    mg.SetTitle(title)
    #gStyle.SetTitleAlign(33)
    #gStyle.SetTitleX(0.99)
    leg = TLegend(
        0.345, 0.68, 0.645, 0.88
    )  #TLegend(1. - c.GetRightMargin() - 0.8, 1. - c.GetTopMargin() - 0.40,1. - c.GetRightMargin()- 0.60, 1. - c.GetTopMargin() -0.02)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)
    leg.SetMargin(0.1)
    #ymax = 0;
    ratesFromFit = {}
    evVal = 15000
    if doext:
        evVal = 50000

    #f=TFile.Open(outn+".root","RECREATE")


#  for name,value in plotoptions.iteritems():
    for name in sortk:
        if name != 'main': continue
        value = plotoptions[name]
        #print grs
        gr = grs[name]
        #print gr
        gr.SetName(title)
        #extrate = fitGraph(gr,evVal)
        #ratesFromFit[name] = extrate
        if doext:
            #print name, extrate[0], extrate[1]
            NN = gr.GetN()
            gr.Set(NN + 1)
            gr.SetPoint(NN + 1, 50000.0, extrate["rate"][0])
            yErr = extrate["rate"][1]
            if not ploterror:
                yErr = 0.0
            gr.SetPointError(NN + 1, 0.0, yErr)
        gr.SetMarkerColor(value['color'])
        gr.SetMarkerStyle(value['markst'])
        gr.SetLineColor(value['color'])
        gr.SetMarkerSize(1.15)  #1.05
        gr.SetMinimum(0.1)
        #gr.Write()
        mg.Add(gr)
        text = title  #name #+plotoptions[name]['leg']
        leg.AddEntry(gr, text, "p")
        continue

    mg.SetName(outn)
    mg.SetMinimum(0.1)
    mg.SetMaximum(ymax)  #1.6*ymax
    mg.Draw("AP")
    mg.GetXaxis().SetRangeUser(2000, 20000)
    c.Update()
    graphAxis(mg)

    CMS_lumi.CMS_lumi(c, iPeriod, iPos)
    c.cd()
    c.Update()
    frame = c.GetFrame()
    frame.Draw()

    leg.Draw()
    c.SaveAs(outn + ".png")
    #c.SaveAs(outn+".C")
    del c

    return ratesFromFit
Exemple #3
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()
Exemple #4
0
def TwoFileSAME2VsLumi(F1graph1, F1graph2, F2graph1, F2graph2, title, type):
    canvas = makeCMSCanvas(str(random.random()),"canvas",900,700)
    canvas.cd()
    F1graph1.SetMarkerColor(kBlue)#electrons
    F1graph2.SetMarkerColor(kRed)#muons
    F2graph1.SetMarkerColor(kBlue)#electrons
    F2graph2.SetMarkerColor(kRed)#muons
    F2graph1.SetMarkerStyle(kOpenStar)
    F2graph2.SetMarkerStyle(kOpenStar)
    multigraph = TMultiGraph()
    multigraph.Add(F1graph1,"AP")
    multigraph.Add(F1graph2,"AP")
    multigraph.Add(F2graph1,"AP")
    multigraph.Add(F2graph2,"AP")
    multigraph.Draw("AP")
    multigraph.GetXaxis().SetLimits(0.,40.)
    #TGaxis.SetMaxDigits(2)
    #TGaxis.SetExponentOffset(-0.06, 0.02, "y")
    multigraph.GetXaxis().SetTitle("L [fb^{-1}]")
    multigraph.GetYaxis().SetTitleOffset(1.4)
    if(type == "ISO"):
        multigraph.GetYaxis().SetTitle("Isolation")
        gPad.Modified()
        multigraph.SetMinimum(0.5*gPad.GetUymin())
        multigraph.SetMaximum(1.5*gPad.GetUymax())
    elif(type == "SIP"):
        multigraph.GetYaxis().SetTitle("SIP")
    printLumiPrelOut(canvas)
    canvas.Update()
    down = gPad.GetUymin()
    up = gPad.GetUymax()
    lineB = TLine(5.57,down,5.57, up)
    lineB.SetLineColor(kBlack)
    lineB.SetLineStyle(2)
    lineB.Draw()
    lineC = TLine(8.58,down,8.58,up)
    lineC.SetLineColor(kBlack)
    lineC.SetLineStyle(2)
    lineC.Draw()
    lineD = TLine(12.9,down,12.9,up)
    lineD.SetLineColor(kBlack)
    lineD.SetLineStyle(2)
    lineD.Draw()
    lineE = TLine(16.57,down,16.57,up)
    lineE.SetLineColor(kBlack)
    lineE.SetLineStyle(2)
    lineE.Draw()
    lineF = TLine(19.7,down,19.7,up)
    lineF.SetLineColor(kBlack)
    lineF.SetLineStyle(2)
    lineF.Draw()
    lineG = TLine(26.9,down,26.9,up)
    lineG.SetLineColor(kBlack)
    lineG.SetLineStyle(2)
    lineG.Draw()
    legend = TLegend(0.80,0.75,0.965,0.93)
    legend.AddEntry(F1graph1,"e^{+}e^{-}","P")
    legend.AddEntry(F1graph2,"#mu^{+}#mu^{-}","P")
    legend.AddEntry(F2graph1,"e^{+}e^{-} ICHEP","P")
    legend.AddEntry(F2graph2,"#mu^{+}#mu^{-} ICHEP","P")
    legend.SetTextFont(32)
    legend.Draw()

    canvas.SaveAs(title + ".pdf")
    canvas.SaveAs(title + ".png")
    return;
Exemple #5
0
def SAME2VsLumi(g1, g2,title, ptype, dataPeriod):
    canvas = makeCMSCanvas(str(random.random()),"canvas",900,700)
    canvas.cd()
    graph1=copy.deepcopy(g1)
    graph2=copy.deepcopy(g2)
    graph1.SetMarkerColor(kBlue)#electrons
    graph2.SetMarkerColor(kRed)#muons
    multigraph = TMultiGraph()
    multigraph.Add(graph1,"AP")
    multigraph.Add(graph2,"AP")
    multigraph.Draw("AP")
    TGaxis.SetMaxDigits(2)
    TGaxis.SetExponentOffset(-0.06, 0.02, "y")
    multigraph.GetXaxis().SetTitle("L [fb^{-1}]")
    multigraph.GetYaxis().SetTitleOffset(1.4)
    if(ptype == "ISO"):
        multigraph.GetYaxis().SetTitle("Isolation")
        gPad.Modified()
        multigraph.SetMinimum(0.5*gPad.GetUymin())
        multigraph.SetMaximum(1.5*gPad.GetUymax())
    elif(ptype == "SIP"):
        multigraph.GetYaxis().SetTitle("SIP")
        multigraph.SetMinimum(min(multigraph.GetHistogram().GetMinimum(),1.))
        multigraph.SetMaximum(max(multigraph.GetHistogram().GetMinimum(),2.2))

        min(multigraph.GetHistogram().GetMinimum(),1.)
    printLumiPrelOut(canvas)

    
    # Draw legend 
    legend = TLegend(0.93,0.84,0.99,0.93)
    legend.AddEntry(graph1,"e^{+}e^{-}","P")
    legend.AddEntry(graph2,"#mu^{+}#mu^{-}","P")
    legend.SetFillColor(kWhite)
    legend.SetLineColor(kBlack)
    legend.SetTextFont(43)
    legend.SetTextSize(20)
    legend.Draw()
    canvas.Update()

    

    # Draw letters for data-taking periods
    if(dataPeriod == "data2017"):
        textLetters = TLatex()
        textLetters.SetTextColor(kGray+1)
        textLetters.SetTextSize(0.03)
        if(ptype == "ISO"):
            textLetters.DrawLatex(2.,  0.8*gPad.GetUymax(),"B")
            textLetters.DrawLatex(9.5, 0.8*gPad.GetUymax(),"C")
            textLetters.DrawLatex(16., 0.8*gPad.GetUymax(),"D")
            textLetters.DrawLatex(23., 0.8*gPad.GetUymax(),"E")
            textLetters.DrawLatex(36., 0.8*gPad.GetUymax(),"F")
        elif(ptype == "SIP"):
            textLetters.DrawLatex(2.,  1.5,"B")    
            textLetters.DrawLatex(9.5, 1.5,"C")
            textLetters.DrawLatex(16., 1.5,"D")
            textLetters.DrawLatex(23., 1.5,"E")
            textLetters.DrawLatex(36., 1.5,"F")

    if(dataPeriod == "data2018"):
        textLetters = TLatex()
        textLetters.SetTextColor(kGray+1)
        textLetters.SetTextSize(0.03)
        if(ptype == "ISO"):
            textLetters.DrawLatex(6.,   0.8*gPad.GetUymax(), "A")
            textLetters.DrawLatex(16.,  0.8*gPad.GetUymax(), "B")
            textLetters.DrawLatex(23.,  0.8*gPad.GetUymax(), "C")
            textLetters.DrawLatex(43.,  0.8*gPad.GetUymax(), "D")
        elif(ptype == "SIP"):
            textLetters.DrawLatex(6.,  1.5, "A")    
            textLetters.DrawLatex(16., 1.5, "B")
            textLetters.DrawLatex(23., 1.5, "C")
            textLetters.DrawLatex(43., 1.5, "D")
         


    # ****
    if(dataPeriod == "data2018"):
        # draw vertical lines that divide different data taking periods
        down    = gPad.GetUymin()
        up      = gPad.GetUymax()
        
        lineA = TLine(13.48, down, 13.48, up) # Run2018A up to 13.48 fb-1
        lineA.SetLineColor(kBlack)
        lineA.SetLineStyle(2)
        lineA.Draw()
        
        lineB = TLine(20.265, down, 20.265, up) # Run2018B up to 20.265 fb-1
        lineB.SetLineColor(kBlack)
        lineB.SetLineStyle(2)
        lineB.Draw()
        
        lineC = TLine(26.877, down, 26.877, up) # Run2018C up to 26.877 fb-1
        lineC.SetLineColor(kBlack)
        lineC.SetLineStyle(2)
        lineC.Draw()
        
    # ****
    if(dataPeriod == "data2017"):
        # draw vertical lines that divide different data taking periods
        down    = gPad.GetUymin()
        up      = gPad.GetUymax()
        
        lineB = TLine(4.793, down, 4.793, up) # Run2017B up to 4.793 fb-1
        lineB.SetLineColor(kBlack)
        lineB.SetLineStyle(2)
        lineB.Draw()
        
        lineC = TLine(14.549, down, 14.549, up) # Run2017C up to 14.549 fb-1
        lineC.SetLineColor(kBlack)
        lineC.SetLineStyle(2)
        lineC.Draw()
        
        lineD = TLine(18.868, down, 18.868, up) # Run2017D up to 18.868 fb-1
        lineD.SetLineColor(kBlack)
        lineD.SetLineStyle(2)
        lineD.Draw()
        
        lineE = TLine(28.293, down, 28.293, up) # Run2017E up to 28.293 fb-1
        lineE.SetLineColor(kBlack)
        lineE.SetLineStyle(2)
        lineE.Draw()
    
    # ****
    if(dataPeriod == "data2016"):
        # draw vertical lines that divide different data taking periods
        down    = gPad.GetUymin()
        up      = gPad.GetUymax()
        
        lineB = TLine(5.789, down, 5.789, up) # Run2016B up to 5.789 fb-1
        lineB.SetLineColor(kBlack)
        lineB.SetLineStyle(2)
        lineB.Draw()
        
        lineC = TLine(8.366, down, 8.366, up) # Run2016C up to 8.366 fb-1
        lineC.SetLineColor(kBlack)
        lineC.SetLineStyle(2)
        lineC.Draw() 
        
        lineD = TLine(12.616, down, 12.616, up) # Run2016D up to 12.616 fb-1
        lineD.SetLineColor(kBlack)
        lineD.SetLineStyle(2)
        lineD.Draw()    
        
        lineE = TLine(16.624, down, 16.624, up) # Run2016E up to 16.624 fb-1
        lineE.SetLineColor(kBlack)
        lineE.SetLineStyle(2)
        lineE.Draw()    
        
        lineF = TLine(19.725, down, 19.725, up) # Run2016F up to 19.725 fb-1
        lineF.SetLineColor(kBlack)
        lineF.SetLineStyle(2)
        lineF.Draw()    
        
        lineG = TLine(27.268, down, 27.268, up) # Run2016G up to 27.268 fb-1
        lineG.SetLineColor(kBlack)
        lineG.SetLineStyle(2)
        lineG.Draw()       
    # ****
    

    canvas.SaveAs(title + ".root")
    canvas.SaveAs(title + ".pdf")
    canvas.SaveAs(title + ".png")
    return;
Exemple #6
0
def SAME3VsLumi(g1, g2, g3, title, ptype, lineMC1, lineDATA1, lineMC2, lineDATA2, lineMC3, lineDATA3, DoInclusive, dataPeriod):
    canvas = makeCMSCanvas(str(random.random()),"canvas",900,700)
    canvas.cd()
    graph2=copy.deepcopy(g2)
    graph3=copy.deepcopy(g3)
    graph2.SetMarkerColor(kBlue)#electrons
    graph3.SetMarkerColor(kRed)#muons
    multigraph = TMultiGraph()
    if(DoInclusive):
        graph1=copy.deepcopy(g1)
        multigraph.Add(graph1,"AP")
    multigraph.Add(graph2,"AP")
    multigraph.Add(graph3,"AP")
    multigraph.Draw("AP")
    TGaxis.SetMaxDigits(2)
    TGaxis.SetExponentOffset(-0.05, 0.02, "y")
    multigraph.GetXaxis().SetTitle("L [fb^{-1}]")
    multigraph.GetYaxis().SetTitleOffset(1.4)
    if(ptype == "Zmass"):
        multigraph.GetYaxis().SetTitle("M_{Z} [GeV]")
        # multigraph.GetYaxis().SetTitle("M_{l^{+}l^{-}} [GeV]")
        multigraph.SetMaximum(max(multigraph.GetHistogram().GetMaximum(),91.4))
        multigraph.SetMinimum(min(multigraph.GetHistogram().GetMinimum(),89.6))
    elif(ptype == "Zwidth"):
        multigraph.GetYaxis().SetTitle("#Gamma_{Z} [GeV]")
    elif(ptype == "Zmult"):
        multigraph.GetYaxis().SetTitle("#Z / fb^{-1}")
        if(not DoInclusive) :
            multigraph.SetMaximum(max(multigraph.GetHistogram().GetMaximum(),60000.)) # set y axis minimum at 60000.
            multigraph.SetMinimum(0.)     # set y axis minimum at 0. 
            # multigraph.SetMaximum(60000.)  #second type: vs 2016 plots 
            # multigraph.SetMinimum(25000.)      
    printLumiPrelOut(canvas)

    
    # Draw legend 
    legend = TLegend(0.93,0.84,0.99,0.93)
    if(DoInclusive):
        #legend.AddEntry(graph1,"inclusive","P")
        legend.AddEntry(graph1,"BB","P")
        legend.AddEntry(graph2,"BE","P")
        legend.AddEntry(graph3,"EE","P")
    else :
        legend.AddEntry(graph2,"e^{+}e^{-}","P")
        legend.AddEntry(graph3,"#mu^{+}#mu^{-}","P")
    legend.SetFillColor(kWhite)
    legend.SetLineColor(kBlack)
    legend.SetTextFont(43)
    legend.SetTextSize(20)
    legend.Draw()
    canvas.Update()

    
    # Draw letters for data-taking periods
    if(dataPeriod == "data2017"):
        textLetters = TLatex()
        textLetters.SetTextColor(kGray+1)
        textLetters.SetTextSize(0.03)
        if(ptype == "Zmass"):
            textLetters.DrawLatex(2.,  gPad.GetUymin()+0.2,"B")
            textLetters.DrawLatex(9.5, gPad.GetUymin()+0.2,"C")
            textLetters.DrawLatex(16., gPad.GetUymin()+0.2,"D")
            textLetters.DrawLatex(23., gPad.GetUymin()+0.2,"E")
            textLetters.DrawLatex(36., gPad.GetUymin()+0.2,"F")
        elif(ptype == "Zwidth"):
            textLetters.DrawLatex(2.,  gPad.GetUymin()+0.3,"B")
            textLetters.DrawLatex(9.5, gPad.GetUymin()+0.3,"C")
            textLetters.DrawLatex(16., gPad.GetUymin()+0.3,"D")
            textLetters.DrawLatex(23., gPad.GetUymin()+0.3,"E")
            textLetters.DrawLatex(36., gPad.GetUymin()+0.3,"F")
        elif(ptype == "Zmult") :
            textLetters.DrawLatex(2.,  260000,"B")
            textLetters.DrawLatex(9.5, 260000,"C")
            textLetters.DrawLatex(16., 260000,"D")
            textLetters.DrawLatex(23., 260000,"E")
            textLetters.DrawLatex(36., 260000,"F")

    if(dataPeriod == "data2018"):
        textLetters = TLatex()
        textLetters.SetTextColor(kGray+1)
        textLetters.SetTextSize(0.03)
        if(ptype == "Zmass"):
            textLetters.DrawLatex(6.,  gPad.GetUymin() + 0.6,"A")
            textLetters.DrawLatex(16., gPad.GetUymin() + 0.6,"B")
            textLetters.DrawLatex(23., gPad.GetUymin() + 0.6,"C")
            textLetters.DrawLatex(43., gPad.GetUymin() + 0.6,"D")
        elif(ptype == "Zwidth"):
            textLetters.DrawLatex(6.,  gPad.GetUymin() +0.3,"A")
            textLetters.DrawLatex(16., gPad.GetUymin() +0.3,"B")
            textLetters.DrawLatex(23., gPad.GetUymin() +0.3,"C")
            textLetters.DrawLatex(43., gPad.GetUymin() +0.3,"D")
        elif(ptype == "Zmult") :
            textLetters.DrawLatex(6.,  260000,"A")
            textLetters.DrawLatex(16., 260000,"B")
            textLetters.DrawLatex(23., 260000,"C")
            textLetters.DrawLatex(43., 260000,"D")

    
    # ****
    if(dataPeriod == "data2018"):
        # draw vertical lines that divide different data taking periods
        down    = gPad.GetUymin()
        up      = gPad.GetUymax()
        
        lineA = TLine(13.48, down, 13.48, up) # Run2018A up to 13.48 fb-1
        lineA.SetLineColor(kBlack)
        lineA.SetLineStyle(2)
        lineA.Draw()    
        
        lineB = TLine(20.265, down, 20.265, up) # Run2018B up to 20.265 fb-1
        lineB.SetLineColor(kBlack)
        lineB.SetLineStyle(2)
        lineB.Draw()
        
        lineC = TLine(26.877, down, 26.877, up) # Run2018C up to 26.877 fb-1
        lineC.SetLineColor(kBlack)
        lineC.SetLineStyle(2)
        lineC.Draw()
        

    if(dataPeriod == "data2017"):
        # draw vertical lines that divide different data taking periods
        down    = gPad.GetUymin()
        up      = gPad.GetUymax()
        
        lineB = TLine(4.793, down, 4.793, up) # Run2017B up to 4.793 fb-1
        lineB.SetLineColor(kBlack)
        lineB.SetLineStyle(2)
        lineB.Draw()    
        
        lineC = TLine(14.549, down, 14.549, up) # Run2017C up to 14.549 fb-1
        lineC.SetLineColor(kBlack)
        lineC.SetLineStyle(2)
        lineC.Draw()
        
        lineD = TLine(18.868, down, 18.868, up) # Run2017D up to 18.868 fb-1
        lineD.SetLineColor(kBlack)
        lineD.SetLineStyle(2)
        lineD.Draw()
        
        lineE = TLine(28.293, down, 28.293, up) # Run2017E up to 28.293 fb-1
        lineE.SetLineColor(kBlack)
        lineE.SetLineStyle(2)
        lineE.Draw()

    if(dataPeriod == "data2016"):
        # draw vertical lines that divide different data taking periods
        down    = gPad.GetUymin()
        up      = gPad.GetUymax()
        
        lineB = TLine(5.789, down, 5.789, up) # Run2016B up to 5.789 fb-1
        lineB.SetLineColor(kBlack)
        lineB.SetLineStyle(2)
        lineB.Draw()
        
        lineC = TLine(8.366, down, 8.366, up) # Run2016C up to 8.366 fb-1
        lineC.SetLineColor(kBlack)
        lineC.SetLineStyle(2)
        lineC.Draw() 
        
        lineD = TLine(12.616, down, 12.616, up) # Run2016D up to 12.616 fb-1
        lineD.SetLineColor(kBlack)
        lineD.SetLineStyle(2)
        lineD.Draw()    
        
        lineE = TLine(16.624, down, 16.624, up) # Run2016E up to 16.624 fb-1
        lineE.SetLineColor(kBlack)
        lineE.SetLineStyle(2)
        lineE.Draw()    
        
        lineF = TLine(19.725, down, 19.725, up) # Run2016F up to 19.725 fb-1
        lineF.SetLineColor(kBlack)
        lineF.SetLineStyle(2)
        lineF.Draw()    
        
        lineG = TLine(27.268, down, 27.268, up) # Run2016G up to 27.268 fb-1
        lineG.SetLineColor(kBlack)
        lineG.SetLineStyle(2)
        lineG.Draw()       
    # ****
    
    # draw orizontal lines for MC and DATA fit
    if(ptype == "Zmass" or ptype == "Zwidth") :

        leftEnd  = gPad.GetUxmin()
        rightEnd = gPad.GetUxmax()

        if(DoInclusive):
            line1 = TLine(leftEnd,lineMC1,rightEnd,lineMC1)
            line1.SetLineColor(kBlack)
            line1.SetLineStyle(1) 
            line1.Draw()

            line2 = TLine(leftEnd,lineDATA1,rightEnd,lineDATA1)
            line2.SetLineColor(kBlack)
            line2.SetLineStyle(2)
            line2.Draw()
        
        # line for graph 2: color blue
        line3 = TLine(leftEnd,lineMC2,rightEnd,lineMC2)
        line3.SetLineColor(kBlue)
        line3.SetLineStyle(1) 
        line3.Draw()

        line4 = TLine(leftEnd,lineDATA2,rightEnd,lineDATA2)
        line4.SetLineColor(kBlue)
        line4.SetLineStyle(2)
        line4.Draw()
    
        # line for graph 3: color red
        line5 = TLine(leftEnd,lineMC3,rightEnd,lineMC3)
        line5.SetLineColor(kRed)
        line5.SetLineStyle(1) 
        line5.Draw()

        line6 = TLine(leftEnd,lineDATA3,rightEnd,lineDATA3)
        line6.SetLineColor(kRed)
        line6.SetLineStyle(2)
        line6.Draw()
    # ***    

    canvas.SaveAs(title + ".root")
    canvas.SaveAs(title + ".pdf")
    canvas.SaveAs(title + ".png")
    return;
Exemple #7
0
gr1 = TGraph(n, xx, yy)
gr1.SetLineColor(1)
gr1.SetLineWidth(1)
gr1.SetLineStyle(3)
gr1.SetMarkerColor(1)
gr1.SetMarkerStyle(21)
##gr1.SetTitle( 'a simple graph' )
##gr1.GetXaxis().SetTitle( 'X title' )
##gr1.GetYaxis().SetTitle( 'Y title' )
#gr1.Draw( 'CP' )

mg.Add(gr)
mg.Add(gr1)
mg.SetMaximum(0.55)
mg.SetMinimum(-0.55)

#mg.GetXaxis().SetTitle("M_{WW} (GeV) CutOff Scale")
#mg.GetYaxis().SetTitle("FT0 (95% CL)")
mg.SetTitle(";M_{VV} cut-off scale (TeV);FT0 (#times 10^{-12} TeV^{-4})")

from ROOT import TPad, TH1F

pad1 = TPad("pad1", "pad1", 0.0, 0.0, 0.8, 1.0)
pad1.SetTopMargin(0.07)  # joins upper and lower plot
pad1.SetBottomMargin(0.13)  # joins upper and lower plot
pad1.SetLeftMargin(0.15)
pad1.SetRightMargin(0.0)
#pad1.SetLogy(1)
#pad1.SetGridx()
pad1.SetTickx(1)
os.chdir("..")

theCanvas = TCanvas()

if (graphHolder.GetListOfGraphs().GetSize() == 1):
    graphHolder.SetTitle(
        "#omega vs. #eta_{i} (%s %s);#eta_{i};#omega(#eta_{i})" %
        (taggerType, originSuffix))
else:
    graphHolder.SetTitle(
        "#omega vs. #eta_{i} (%d data sets) (%s %s);#eta_{i};#omega(#eta_{i})"
        % (numP, taggerType, originSuffix))

graphHolder.Draw("ap")
graphHolder.GetXaxis().SetLimits(0.0, 0.5)
graphHolder.SetMinimum(0.0)
graphHolder.SetMaximum(0.5)
#graphHolder.Draw("ap")

graphHolder.GetYaxis().SetTitleSize(0.05)
graphHolder.GetXaxis().SetTitleSize(0.05)

leg = TLegend(0.1, 0.7, 0.4, 0.9)
#,"a f*****g header","tlNDC");
ROOT.SetOwnership(leg, False)
#leg.AddEntry(TObject(),"crap");

p0E = pDataSet.meanVar(pDataSet.get().find('p0Var')).getError()
p0V = pDataSet.meanVar(pDataSet.get().find('p0Var')).getValV()
p1E = pDataSet.meanVar(pDataSet.get().find('p1Var')).getError()
p1V = pDataSet.meanVar(pDataSet.get().find('p1Var')).getValV()
Exemple #9
0
    coutn += 1

gr1 = TGraph(n, xx, yy)
gr1.SetLineColor(2)
gr1.SetLineWidth(4)
gr1.SetMarkerColor(4)
gr1.SetMarkerStyle(21)
##gr1.SetTitle( 'a simple graph' )
##gr1.GetXaxis().SetTitle( 'X title' )
##gr1.GetYaxis().SetTitle( 'Y title' )
#gr1.Draw( 'CP' )

mg.Add(gr)
mg.Add(gr1)
mg.SetMaximum(0.4)
mg.SetMinimum(-0.4)

#mg.GetXaxis().SetTitle("M_{WW} (GeV) CutOff Scale")
#mg.GetYaxis().SetTitle("FT0 (95% CL)")
mg.SetTitle(";M_{WW} (GeV) CutOff Scale;FT0 (95% CL)")

from ROOT import TPad, TH1F

pad1 = TPad("pad1", "pad1", 0.0, 0.0, 0.8, 1.0)
pad1.SetTopMargin(0.07)  # joins upper and lower plot
pad1.SetBottomMargin(0.13)  # joins upper and lower plot
pad1.SetLeftMargin(0.15)
pad1.SetRightMargin(0.0)
#pad1.SetLogy(1)
pad1.SetGridx()
pad1.SetTickx(1)
Exemple #10
0
                )
            elif (args.EFT):
                mg.SetTitle(
                    "Non-Resonant Signal Efficiency Cut Flow;;Efficiency")
            elif (args.NMSSM):
                mg.SetTitle("NMSSM Signal Efficiency Cut Flow;;Efficiency")

            if (args.NMSSM) or (args.EFT): drawOption = "P2"
            else: drawOption = "PL"

            mg.Add(sig_eff_g_00)
            for i in range(5):
                # eval("mg.Add(sig_eff_g_%d,'%s')"%(i,drawOption))
                eval("mg.Add(sig_eff_g_%d,)" % (i))

            mg.SetMinimum(0)

            # outName = ol + 'CutFlow' + '_' + args.campaign
            outName = ol + 'CutFlow' + '_' + campaign
            if args.log: outName += 'Log'
            if args.note is not "": outName += '_' + str(args.note)
            outName += '.png'

            if (args.NMSSM) or (args.EFT):
                DrawNonResHistogram(mg, "AP", outName, args.log, Npoints,
                                    plotLabels)
                outName = outName.replace("png", "pdf")
                DrawNonResHistogram(mg, "AP", outName, args.log, Npoints,
                                    plotLabels)
            else:
                Draw_Histogram(mg, "APL", outName, args.log)
Exemple #11
0
            # for display ...
            for i in range(len(eU)):
                if eU[i] < eD[i]:  # eU < 0
                    eU[i], eD[i] = eD[i], eU[i]
            gSyst = TGraphAsymmErrors(len(x), xHere, y, eL, eH, eU, eU)
            gSyst.SetName(nm)
            gSyst.SetMarkerStyle(mc[j][0])
            gSyst.SetMarkerColor(mc[j][1])
            gSyst.SetLineColor(mc[j][1])
            leg.AddEntry(gSyst, nm, "lep")
            mg.Add(gSyst, "p")

        mg.Add(gNomGeV, "p")
        mg.Draw("ap")
        mg.GetXaxis().SetTitle("#tau p_{T} [GeV]")
        mg.SetMinimum(0.)

        text = TLatex()
        text.SetNDC()
        text.SetTextFont(72)
        text.SetTextSize(0.045)
        # text.DrawLatex(0.51, 0.86, "ATLAS")
        # text.SetTextFont(42)
        # text.DrawLatex(0.51 + 0.16, 0.86, "Internal")
        # text.SetTextSize(0.040)
        # text.DrawLatex(0.51, 0.80, "#sqrt{s} = 13 TeV, 139 fb^{-1}")
        text.SetTextFont(42)
        text.SetTextSize(0.040)
        text.DrawLatex(0.46, 0.86, f"trigger: {trig}, prong: {prong}")

        leg.Draw("SAME")
Exemple #12
0
class PlotGraphs:
    def __init__(self,
                 data,
                 xlow,
                 xhigh,
                 ylow,
                 yhigh,
                 xlabel="",
                 ylabel="",
                 xLegend=.45,
                 yLegend=.60,
                 legendWidth=0.20,
                 legendHeight=0.45,
                 fillStyle=3395,
                 drawOption='APL3',
                 make_tfile=False):

        self.graph_index = {}
        self.ngraphs = 0

        self.data = data
        self.drawOption = drawOption
        self.xlow = xlow
        self.xhigh = xhigh
        self.ylow = ylow
        self.yhigh = yhigh
        self.xlabel = xlabel
        self.ylabel = ylabel
        self.multigraph = TMultiGraph("MultiGraph", "")
        self.legend_type = {}

        if make_tfile:
            self.tfile = TFile('tgraphs.root', 'recreate')

        self.legend = TLegend(xLegend, yLegend, xLegend + legendWidth,
                              yLegend + legendHeight)

        self.g_ = {}
        self.g2_ = {}
        self.g3_ = {}
        for cat in data.cat:
            if data.type[cat] == 'observed':
                #self.g_[cat] = TGraph(len(data.x[cat]), data.x[cat], data.y[cat])
                self.g_[cat] = TGraphAsymmErrors(len(data.x[cat]), data.x[cat],
                                                 data.y[cat], data.exl[cat],
                                                 data.exh[cat], data.eyl[cat],
                                                 data.eyh[cat])
                self.g_[cat].SetName(cat)
                if make_tfile:
                    _gcopy = self.g_[cat].Clone()
                    self.tfile.Append(_gcopy)
                if data.dofit[cat]:
                    #self.g_[cat].Fit("pol3", "M", "", data.fit_min[cat], data.fit_max[cat])
                    f1 = TF1(
                        "f1",
                        "[0]+[1]*(x-1000.0)/1000.0+[2]*(x-1000.0)*(x-1000.0)/1000000.0+[3]*(x-1000.0)*(x-1000.0)*(x-1000.0)/1000000000.0",
                        data.fit_min[cat], data.fit_max[cat])
                    f2 = TF1(
                        "f2",
                        "[0]+[1]*(x-1000.0)/1000.0+[2]*(x-1000.0)*(x-1000.0)/1000000.0",
                        data.fit_min[cat], data.fit_max[cat])
                    f3 = TF1("f3", "[0]+[1]*(x-1000.0)/1000.0",
                             data.fit_min[cat], data.fit_max[cat])
                    _fr = self.g_[cat].Fit("f2", "MEWS", "", data.fit_min[cat],
                                           data.fit_max[cat])
                    _fr.Print()

            elif data.type[cat] == 'expected':
                self.g_[cat] = TGraphAsymmErrors(len(data.x[cat]), data.x[cat],
                                                 data.y[cat], data.exl[cat],
                                                 data.exh[cat], data.eyl[cat],
                                                 data.eyh[cat])
                self.g2_[cat] = TGraphAsymmErrors(
                    len(data.x[cat]), data.x[cat], data.y[cat], data.exl2[cat],
                    data.exh2[cat], data.eyl2[cat], data.eyh2[cat])

                self.g3_[cat] = TGraphAsymmErrors(len(data.x[cat]),
                                                  data.x[cat], data.y[cat],
                                                  data.exl2[cat],
                                                  data.exh2[cat], data.y[cat],
                                                  data.exl2[cat])
                self.g3_[cat].SetFillStyle(1002)
                #self.g3_[cat].SetFillStyle(3008)

                # 95% quantile
                self.g2_[cat].SetMarkerColor(data.fill2_color[cat])
                self.g2_[cat].SetMarkerStyle(data.marker_style[cat])
                self.g2_[cat].SetMarkerSize(data.marker_size[cat])
                self.g2_[cat].SetLineColor(data.fill2_color[cat])
                self.g2_[cat].SetLineStyle(data.line_style[cat])
                self.g2_[cat].SetLineWidth(data.line_width[cat])
                #self.g2_[cat].SetFillColor(data.marker_color[cat]+2)
                self.g2_[cat].SetFillColor(data.fill2_color[cat])
                #self.g2_[cat].SetFillStyle(3008)
                #self.g2_[cat].SetFillStyle(3003)
                self.g2_[cat].SetFillStyle(data.fill2_style[cat])

            self.g_[cat].SetMarkerColor(data.marker_color[cat])
            self.g_[cat].SetMarkerStyle(data.marker_style[cat])
            self.g_[cat].SetMarkerSize(data.marker_size[cat])
            self.g_[cat].SetLineColor(data.line_color[cat])
            self.g_[cat].SetLineStyle(data.line_style[cat])
            self.g_[cat].SetLineWidth(data.line_width[cat])
            self.g_[cat].SetFillColor(data.fill_color[cat])
            if data.fill_style[cat] == None:
                self.g_[cat].SetFillStyle(fillStyle)
            else:
                self.g_[cat].SetFillStyle(data.fill_style[cat])

            if data.type[cat] == 'observed':
                # only the main observed limit is a line,
                # everything else is a filled area
                if cat[0:3] == 'obs':
                    _legend_type = 'lp'
                    if 'PC' in drawOption:
                        _draw_option = 'PC'
                    else:
                        _draw_option = 'PL'
                    self.multigraph.Add(self.g_[cat], _draw_option)
                elif cat[0:3] == 'SSM':
                    _legend_type = 'lp'
                    _draw_option = '3'
                    self.multigraph.Add(self.g_[cat], _draw_option)
                    # print theory curve
                    #self.g_[cat].Print()
                elif cat[0:3] == 'Psi':
                    _legend_type = 'lp'
                    _draw_option = '3'
                    self.multigraph.Add(self.g_[cat], _draw_option)
                elif cat[0:3] == 'Stu':
                    _legend_type = 'lp'
                    _draw_option = '3'
                    self.multigraph.Add(self.g_[cat], _draw_option)
                elif cat[0:2] == 'RS':
                    _legend_type = 'f'
                    _draw_option = '3'
                    self.multigraph.Add(self.g_[cat], _draw_option)
                else:
                    _legend_type = 'f'
                    self.multigraph.Add(self.g_[cat])

                #self.multigraph.Add(self.g_[cat])
                self.graph_index[cat] = self.ngraphs
                self.ngraphs += 1

                #self.legend . AddEntry( self.g_[cat], data.tlegend[cat], _legend_type);
                self.legend_type[cat] = _legend_type

            elif data.type[cat] == 'expected':
                self.g3_[cat].SetFillColor(0)
                self.g3_[cat].SetMinimum(self.ylow)
                self.g3_[cat].SetMaximum(self.yhigh)
                self.g3_[cat].GetXaxis().SetLimits(self.xlow, self.xhigh)
                self.multigraph.Add(self.g3_[cat], 'C3')
                self.ngraphs += 1

                # 95 expected band
                self.multigraph.Add(self.g2_[cat], 'C4L')
                self.ngraphs += 1

                self.multigraph.Add(self.g_[cat], 'C4L')
                self.graph_index[cat] = self.ngraphs
                self.ngraphs += 1

                # median line
                gline = self.g_[cat].Clone()
                gline.SetLineWidth(3)
                gline.SetLineColor(ROOT.kBlue)
                gline.SetLineStyle(2)
                # median expected marker
                gline.SetMarkerStyle(8)
                gline.SetMarkerSize(1)
                # print graph contents
                #gline.Print()
                #self.multigraph.Add(gline, 'LXC')
                self.multigraph.Add(gline, 'C3X')

                self.ngraphs += 1

                # median expected legend
                #self.legend . AddEntry( gline, 'median expected', "l");
                self.legend_type[cat] = "l"
                _g = self.g_[cat]
                self.g_[cat] = gline

                # 68% expected band legend
                #self.legend . AddEntry( self.g_[cat], '68% expected', "f");
                self.legend_type[cat + '1sig'] = "f"
                self.g_[cat + '1sig'] = _g

                # 95% expected band legend
                #self.legend . AddEntry( self.g2_[cat], '95% expected', "f");
                self.legend_type[cat + '2sig'] = "f"
                self.g_[cat + '2sig'] = self.g2_[cat]

        keylist = data.legend_index.keys()  # keys are indices
        keylist.sort()
        for key in keylist:
            print key, data.legend_index[key]
            self.legend.AddEntry(self.g_[data.legend_index[key]],
                                 data.tlegend[data.legend_index[key]],
                                 self.legend_type[data.legend_index[key]])

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

        if make_tfile:
            self.tfile.Write()
            self.tfile.Close()

    def draw(self, yLabelSize=0.055):

        self.multigraph.SetMinimum(self.ylow)
        self.multigraph.SetMaximum(self.yhigh)
        self.multigraph.Draw(self.drawOption)

        self.multigraph.GetXaxis().SetNdivisions(405)
        self.multigraph.GetYaxis().SetNdivisions(405)

        self.multigraph.GetXaxis().SetLimits(self.xlow, self.xhigh)
        #self.multigraph.GetYaxis().SetTitle("")

        self.multigraph.GetYaxis().SetLabelSize(yLabelSize)
        self.multigraph.GetXaxis().SetLabelSize(yLabelSize)

        latex = TLatex()
        latex.SetNDC()
        #latex.SetTextSize(0.04)
        latex.SetTextSize(yLabelSize)
        latex.SetTextAlign(31)  # align right

        latex.DrawLatex(0.95, 0.01, self.xlabel)

        latex.SetTextAngle(90)

        latex.DrawLatex(0.03, 0.9, self.ylabel)

        self.legend.SetFillStyle(0)
        self.legend.SetBorderSize(0)
        #self.legend.SetTextSize(0.04)
        #self.legend.SetTextSize(yLabelSize)
        self.legend.SetTextSize(yLabelSize * 0.7)
        self.legend.SetTextFont(42)
        self.legend.SetTextAlign(11)
        self.legend.Draw()

        return self.multigraph

    def draw_line(self, xline, ymin=-0.02, ymax=0.20):

        if xline == None:
            return

        #print 'XXXX', xline
        _x = array('d')
        _y = array('d')
        _x.append(xline)
        _y.append(ymin)
        _x.append(float(xline))
        _y.append(ymax)
        g_ = TGraph(len(_x), _x, _y)
        self.multigraph.Add(g_, 'L')

    def print_values(self, cat1, cat2):

        legend = 'PlotGraphs::print_values():'

        if cat1 in self.data.cat:
            graph1 = self.multigraph.GetListOfGraphs().At(
                self.graph_index[cat1])
        else:
            return None

        if cat2 in self.data.cat:
            graph2 = self.multigraph.GetListOfGraphs().At(
                self.graph_index[cat2])
        else:
            return None

        for x in range(750, 1150, 50):
            dmax = 0.0
            drelmax = 0.0
            v1 = graph1.Eval(x)
            v2 = graph2.Eval(x)
            d = math.fabs(v2 - v1)
            drel = math.fabs((v2 - v1) / v1)
            if d > dmax:
                dmax = d
            if drel > drelmax:
                drelmax = drel
            print legend, 'x =', x
            print legend, cat1, 'value =', v1
            print legend, cat2, 'value =', v2
            print legend, 'abs diff =', d
            print legend, 'abs relative diff =', drel

        print legend, 'max abs diff =', dmax
        print legend, 'max abs relative diff =', drelmax

    def find_intersection(self,
                          cat1,
                          cat2,
                          xmin=350,
                          xmax=3500,
                          precision=0.000000001):
        legend = 'PlotGraphs::find_intersection(%s,%s):' % (cat1, cat2)
        #always put "exp" or "obs" in cat1
        if cat1 is "exp" or cat1 is "obs":
            if cat1 in self.data.cat:
                graph1 = self.multigraph.GetListOfGraphs().At(
                    self.graph_index[cat1])
            else:
                print "Failed to get ", cat1
                return ["None"]
        else:
            print cat1, " is not obs/exp limit."
            return ["None"]
        if cat2 in self.data.cat:
            graph2 = self.multigraph.GetListOfGraphs().At(
                self.graph_index[cat2])
            #graph2.Print()
        else:
            print "Failed to get ", cat2
            return ["None"]

        _x = xmin

        print legend, graph1.Eval(_x) - graph2.Eval(_x)

        if graph1.Eval(_x) > graph2.Eval(_x):
            result = ["lowlimit"]
        else:
            result = []

        _interval = 1

        _sign1 = graph1.Eval(_x) > graph2.Eval(_x)
        while _x < xmax:
            _x += _interval
            _sign2 = graph1.Eval(_x) > graph2.Eval(_x)
            if _sign1 != _sign2:
                _d = 100000
                _step = -0.5 * _interval
                _crosspt = _x

                while abs(_d) > precision:

                    _crosspt += _step
                    _d = graph1.Eval(_crosspt) - graph2.Eval(_crosspt)
                    _sign2 = _d > 0
                    if _sign1 != _sign2:
                        _step = -0.5 * abs(_step)
                    else:
                        _step = 0.5 * abs(_step)
                _sign1 = not (_sign1)
                result.append(_crosspt)
        if result:
            print "Allowed region:",
            _x = 0
            while _x < len(result):
                if _x + 1 < len(result):
                    print "[", result[_x], ",", result[_x + 1], "];",
                else:
                    if _x + 1 == len(result):
                        print "[", result[_x], ", inf ];"
                if _x + 2 == len(result):
                    print
                _x += 2
        else:
            print "[", xmin, "~", xmax, "] is excluded."
        del graph1
        del graph2
        return result
Exemple #13
0
gr1 = TGraph(n, xx, yy)
gr1.SetLineColor(1)
gr1.SetLineWidth(1)
gr1.SetLineStyle(3)
gr1.SetMarkerColor(1)
gr1.SetMarkerStyle(21)
##gr1.SetTitle( 'a simple graph' )
##gr1.GetXaxis().SetTitle( 'X title' )
##gr1.GetYaxis().SetTitle( 'Y title' )
#gr1.Draw( 'CP' )

mg.Add(gr)
mg.Add(gr1)
mg.SetMaximum(8.0)
mg.SetMinimum(-8.0)

#mg.GetXaxis().SetTitle("M_{WW} (GeV) CutOff Scale")
#mg.GetYaxis().SetTitle("FS0 (95% CL)")
mg.SetTitle(";M_{VV} cut-off scale (TeV);FS0 (#times 10^{-12} TeV^{-4})")

from ROOT import TPad, TH1F

pad1 = TPad("pad1", "pad1", 0.0, 0.0, 0.8, 1.0)
pad1.SetTopMargin(0.07)  # joins upper and lower plot
pad1.SetBottomMargin(0.13)  # joins upper and lower plot
pad1.SetLeftMargin(0.15)
pad1.SetRightMargin(0.0)
#pad1.SetLogy(1)
#pad1.SetGridx()
pad1.SetTickx(1)
#histos["h_xi_acc_phase2_trident"].Draw("e1p")
#histos["h_xi_acc_jeti40_trident"].Draw("e1p same")
#histos["h_xi_acc_phase2_bppp"].Draw("e1p same")
#histos["h_xi_acc_jeti40_bppp"].Draw("e1p same")

g_jeti40_trident.SetMaximum(5e+4)
g_jeti40_trident.SetMinimum(5e-4)

mgr = TMultiGraph()
mgr.Add(g_jeti40_trident, "p0")
mgr.Add(g_phase2_trident, "p0")
mgr.Add(g_jeti40_bppp, "p0")
mgr.Add(g_phase2_bppp, "p0")
mgr.Draw("ap0")
mgr.SetMaximum(5e+4)
mgr.SetMinimum(5e-4)
mgr.GetXaxis().SetTitle(g_jeti40_trident.GetXaxis().GetTitle())
mgr.GetYaxis().SetTitle(g_jeti40_trident.GetYaxis().GetTitle())
mgr.GetXaxis().SetRangeUser(0., 6.1)

#g_jeti40_trident.Draw("AP0")
#g_phase2_trident.Draw("AC")
#g_jeti40_bppp.Draw("AC")
#g_phase2_bppp.Draw("AC")

leg_xi_trident.Draw("same")

LUXE(0.18, 0.85, ROOT.kBlack)

#s = TLatex()
#s.SetNDC(1);
Exemple #15
0
class PlotGraphs:
    def __init__(self, data,
                 xlow, xhigh, ylow, yhigh,
                 xlabel = "", ylabel = "",
                 xLegend = .45, yLegend = .60,
                 legendWidth = 0.20, legendHeight = 0.45,
                 fillStyle = 3395,
                 drawOption = 'APL3',
                 make_tfile = False):

        self.graph_index = {}
        self.ngraphs = 0

        self.data = data
        self.drawOption = drawOption
        self.xlow=xlow
        self.xhigh=xhigh
        self.ylow=ylow
        self.yhigh=yhigh
        self.xlabel = xlabel
        self.ylabel = ylabel
        self.multigraph=TMultiGraph("MultiGraph", "")
        self.legend_type = {}

        if make_tfile:
            self.tfile = TFile('tgraphs.root', 'recreate')

        self.legend = TLegend(xLegend, yLegend,
                              xLegend + legendWidth, yLegend + legendHeight)

        self.g_ = {}
        self.g2_ = {}
        self.g3_ = {}
        for cat in data.cat:
            if data.type[cat] == 'observed':
                #self.g_[cat] = TGraph(len(data.x[cat]), data.x[cat], data.y[cat])
                self.g_[cat] = TGraphAsymmErrors(len(data.x[cat]), data.x[cat], data.y[cat], data.exl[cat], data.exh[cat], data.eyl[cat], data.eyh[cat])
                self.g_[cat].SetName(cat)
                if make_tfile:
                    _gcopy = self.g_[cat].Clone()
                    self.tfile.Append(_gcopy)
                if data.dofit[cat]:
                    #self.g_[cat].Fit("pol3", "M", "", data.fit_min[cat], data.fit_max[cat])
                    f1 = TF1("f1", "[0]+[1]*(x-1000.0)/1000.0+[2]*(x-1000.0)*(x-1000.0)/1000000.0+[3]*(x-1000.0)*(x-1000.0)*(x-1000.0)/1000000000.0", data.fit_min[cat], data.fit_max[cat])
                    f2 = TF1("f2", "[0]+[1]*(x-1000.0)/1000.0+[2]*(x-1000.0)*(x-1000.0)/1000000.0", data.fit_min[cat], data.fit_max[cat])
                    f3 = TF1("f3", "[0]+[1]*(x-1000.0)/1000.0", data.fit_min[cat], data.fit_max[cat])
                    _fr = self.g_[cat].Fit("f2", "MEWS", "", data.fit_min[cat], data.fit_max[cat])
                    _fr.Print()
                    
            elif data.type[cat] == 'expected':
                self.g_[cat] = TGraphAsymmErrors(len(data.x[cat]), data.x[cat], data.y[cat], data.exl[cat], data.exh[cat], data.eyl[cat], data.eyh[cat])
                self.g2_[cat] = TGraphAsymmErrors(len(data.x[cat]), data.x[cat], data.y[cat], data.exl2[cat], data.exh2[cat], data.eyl2[cat], data.eyh2[cat])

                self.g3_[cat] = TGraphAsymmErrors(len(data.x[cat]), data.x[cat], data.y[cat], data.exl2[cat], data.exh2[cat], data.y[cat], data.exl2[cat])
                self.g3_[cat].SetFillStyle(1002)
                #self.g3_[cat].SetFillStyle(3008)

                # 95% quantile 
                self.g2_[cat].SetMarkerColor(data.fill2_color[cat])
                self.g2_[cat].SetMarkerStyle(data.marker_style[cat])
                self.g2_[cat].SetMarkerSize(data.marker_size[cat])
                self.g2_[cat].SetLineColor(data.fill2_color[cat])
                self.g2_[cat].SetLineStyle(data.line_style[cat])
                self.g2_[cat].SetLineWidth(data.line_width[cat])
                #self.g2_[cat].SetFillColor(data.marker_color[cat]+2)
                self.g2_[cat].SetFillColor(data.fill2_color[cat])
                #self.g2_[cat].SetFillStyle(3008)
                #self.g2_[cat].SetFillStyle(3003)
                self.g2_[cat].SetFillStyle(data.fill2_style[cat])

                
            self.g_[cat].SetMarkerColor(data.marker_color[cat])
            self.g_[cat].SetMarkerStyle(data.marker_style[cat])
            self.g_[cat].SetMarkerSize(data.marker_size[cat])
            self.g_[cat].SetLineColor(data.line_color[cat])
            self.g_[cat].SetLineStyle(data.line_style[cat])
            self.g_[cat].SetLineWidth(data.line_width[cat])
            self.g_[cat].SetFillColor(data.fill_color[cat])
            if data.fill_style[cat] == None:
                self.g_[cat].SetFillStyle(fillStyle)
            else:
                self.g_[cat].SetFillStyle(data.fill_style[cat])

            if data.type[cat] == 'observed':
                # only the main observed limit is a line,
                # everything else is a filled area
                if cat[0:3] == 'obs':
                    _legend_type = 'lp'
                    if 'PC' in drawOption:
                        _draw_option = 'PC'
                    else:
                        _draw_option = 'PL'
                    self.multigraph.Add(self.g_[cat], _draw_option)
                elif cat[0:3] == 'SSM':
                    _legend_type = 'lp'
                    _draw_option = '3'
                    self.multigraph.Add(self.g_[cat], _draw_option)
                    # print theory curve
                    #self.g_[cat].Print()
                elif cat[0:3] == 'Psi':
                    _legend_type = 'lp'
                    _draw_option = '3'
                    self.multigraph.Add(self.g_[cat], _draw_option)
                elif cat[0:2] == 'RS':
                    _legend_type = 'f'
                    _draw_option = '3'
                    self.multigraph.Add(self.g_[cat], _draw_option)
                else:
                    _legend_type = 'f'
                    self.multigraph.Add(self.g_[cat])

                #self.multigraph.Add(self.g_[cat])
                self.graph_index[cat] = self.ngraphs
                self.ngraphs += 1

                #self.legend . AddEntry( self.g_[cat], data.tlegend[cat], _legend_type);
                self.legend_type[cat] = _legend_type
                
            elif data.type[cat] == 'expected':
                self.g3_[cat].SetFillColor(0)
                self.g3_[cat].SetMinimum(self.ylow)
                self.g3_[cat].SetMaximum(self.yhigh)
                self.g3_[cat].GetXaxis().SetLimits(self.xlow, self.xhigh)
                self.multigraph.Add(self.g3_[cat], 'C3')
                self.ngraphs += 1

                # 95 expected band
                self.multigraph.Add(self.g2_[cat])
                self.ngraphs += 1

                self.multigraph.Add(self.g_[cat], 'C3L')
                self.graph_index[cat] = self.ngraphs
                self.ngraphs += 1

                # median line
                gline = self.g_[cat].Clone()
                gline.SetLineWidth(3)
                gline.SetLineColor(ROOT.kBlue)
                gline.SetLineStyle(2)
                # print graph contents
                #gline.Print()
                #self.multigraph.Add(gline, 'LXC')
                self.multigraph.Add(gline, 'C3X')
                self.legend . AddEntry( gline, 'median expected', "l");
                self.ngraphs += 1

                #self.legend . AddEntry( self.g_[cat], data.tlegend[cat], "f");
                self.legend . AddEntry( self.g_[cat], '68% expected', "f");

                # 95% expected band legend
                self.legend . AddEntry( self.g2_[cat], '95% expected', "f");


        keylist = data.legend_index.keys() # keys are indices
        keylist.sort()
        for key in keylist:
            self.legend . AddEntry( self.g_[data.legend_index[key]],
                                    data.tlegend[data.legend_index[key]],
                                    self.legend_type[data.legend_index[key]]);

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

        if make_tfile:
            self.tfile.Write()
            self.tfile.Close()



    def draw(self, yLabelSize = 0.045):

        self.multigraph.SetMinimum(self.ylow)
        self.multigraph.SetMaximum(self.yhigh)
        self.multigraph . Draw(self.drawOption)

        self.multigraph.GetXaxis().SetNdivisions(405)
        self.multigraph.GetYaxis().SetNdivisions(405)

        self.multigraph.GetXaxis().SetLimits(self.xlow, self.xhigh)
        #self.multigraph.GetYaxis().SetTitle("")

        #self.multigraph.GetYaxis().SetLabelSize(yLabelSize)
        #self.multigraph.GetXaxis().SetLabelSize(yLabelSize)

        # axis labels
        #latex = TLatex()
        #latex.SetNDC()
        ##latex.SetTextSize(0.04)
        #latex.SetTextSize(yLabelSize)
        #latex.SetTextAlign(31) # align right
        #latex.DrawLatex(0.95,0.01, self.xlabel)
        #latex.SetTextAngle(90)
        #latex.DrawLatex(0.04,0.95, self.ylabel)
        XLabel(self.xlabel, 0.95, 0.03, text_size = 0.07)
        YLabel(self.ylabel, 0.04,0.9, text_size = 0.07)

        self.legend.SetFillStyle(0)
        self.legend.SetBorderSize(0)
        #self.legend.SetTextSize(0.04)
        self.legend.SetTextSize(yLabelSize)
        self.legend.SetTextFont(22)
        self.legend . Draw()

        return self.multigraph


    def draw_line(self, xline, ymin = -0.02, ymax = 0.20):

        if xline == None:
            return
        
        #print 'XXXX', xline
        _x = array('d')
        _y = array('d')
        _x.append(xline)
        _y.append(ymin)
        _x.append(float(xline))
        _y.append(ymax)
        g_ = TGraph(len(_x), _x, _y)
        self.multigraph.Add(g_, 'L')



    def print_values(self, cat1, cat2):

        legend = 'PlotGraphs::print_values():'

        if cat1 in self.data.cat:
            graph1 = self.multigraph.GetListOfGraphs().At(self.graph_index[cat1])
        else:
            return None

        if cat2 in self.data.cat:
            graph2 = self.multigraph.GetListOfGraphs().At(self.graph_index[cat2])
        else:
            return None

        for x in range (750, 1150, 50):
            dmax = 0.0
            drelmax = 0.0
            v1 = graph1.Eval(x)
            v2 = graph2.Eval(x)
            d = math.fabs(v2-v1)
            drel = math.fabs((v2-v1)/v1)
            if d>dmax:
                dmax = d
            if drel>drelmax:
                drelmax = drel
            print legend, 'x =', x
            print legend, cat1, 'value =', v1
            print legend, cat2, 'value =', v2
            print legend, 'abs diff =', d
            print legend, 'abs relative diff =', drel
            
        print legend, 'max abs diff =', dmax
        print legend, 'max abs relative diff =', drelmax


    def find_intersection(self, cat1, cat2,
                          xmin = 250, xmax = 2500,
                          precision = 0.00001):

        legend = 'PlotGraphs::find_intersection():'

        if cat1 in self.data.cat:
            graph1 = self.multigraph.GetListOfGraphs().At(self.graph_index[cat1])
        else:
            return None

        if cat2 in self.data.cat:
            graph2 = self.multigraph.GetListOfGraphs().At(self.graph_index[cat2])
            #graph2.Print()
        else:
            return None

        _x = xmin

        print legend, graph1.Eval(_x) - graph2.Eval(_x)

        _d = graph1.Eval(_x) - graph2.Eval(_x)
        _step = xmax - xmin

        
        while abs(_d) > precision:
            
            _x += _step

            if _x > xmax or _x < xmin:
                return None
            
            _d2 = graph1.Eval(_x) - graph2.Eval(_x)

            _sign1 = _d > 0
            _sign2 = _d2 > 0

            if _sign1 != _sign2:
                _step = -0.5*_step

            _d = _d2

            if abs(_d2) < precision:

                return _x
Exemple #16
0
def main():
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-i", "--inputfile", dest="inputfile")
    parser.add_option("-m", "--model", dest="model", type="string")
    (options, args) = parser.parse_args()

    from ROOT import TFile, TMultiGraph, TCanvas, TLegend
    from Styles import formatXsecCL
    import configurations as config
    from ROOT import gStyle

    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadRightMargin(0.05)

    infile = TFile(options.inputfile, "READ")
    infile_xsec = TFile(config.bh_xsec, "READ")

    store = []
    for n in config.extraDim_list:
        c = TCanvas("%s-n%d" % (options.model,n),\
              "%s-n%d" % (options.model,n),\
              500, 500)
        store.append(c)

        graphs = TMultiGraph()
        store.append(graphs)

        legend = TLegend(0.5266129, 0.5360169, 0.9476613, 0.9364407)
        legend.SetTextSize(0.02966102)
        legend.SetFillColor(0)
        legend.SetLineColor(0)
        legend.SetHeader("n = %d" % n)
        store.append(legend)

        for i, MD in enumerate(config.MD_list):
            gCL95 = infile.Get("%s-MD%.1f_n%d-CL95" % (options.model, MD, n))
            gXsec = infile_xsec.Get("%s-MD%.1f_n%d" % (options.model, MD, n))

            if gCL95 and gXsec:
                legend.AddEntry(gCL95, "M_{D} = %.1f TeV Observed" % MD, "l")
                formatXsecCL(gCL95, i, 1)
                graphs.Add(gCL95, "l")

                legend.AddEntry(gXsec, "M_{D} = %.1f TeV Theoretical" % MD,
                                "l")
                formatXsecCL(gXsec, i, 2)
                graphs.Add(gXsec, "c")

        graphs.Draw("a")
        graphs.GetXaxis().SetTitle("M_{BH}^{ min} (TeV)")
        graphs.GetYaxis().SetTitle("#sigma (pb)")
        graphs.GetYaxis().SetTitleOffset(1.2)
        graphs.GetXaxis().SetRangeUser(4.5, 7.5)
        graphs.SetMinimum(1e-4)
        graphs.SetMaximum(1)
        c.SetLogy()
        legend.Draw("plain")
        c.Print("MassLimit_%s_n%d.pdf" % (options.model, n))
        c.Print("MassLimit_%s_n%d.png" % (options.model, n))
        c.Update()

    raw_input("Press Enter to continue...")
Exemple #17
0
def calc_punzi_FOM_vs_ctau(cutlist, labellist=[],mass_point=40,additional_string="",alpha=2,CL=5,FOM='punzi',header=""):
    file = {}
    nevt = {}
    tree = {}
    effs = {}
    chain = {}
    hist = {}
    eff_dict = { k:{} for k in cutlist}
    back_int = { k:{} for k in cutlist}
    back_int_weight = { k:{} for k in cutlist}
    back_eff = { k:{} for k in cutlist}
    punzi_dict = { k:{} for k in cutlist}
    graph = {}
    back_graph = {}
    ncuts = len(cutlist)
    if labellist == []:
        labellist=cutlist
    print NTUPLEDIR
    print "............."
    #prepare ctau ordered array for 1D plot                                                                
    mass_array = []
    ctau_array = []


    #for signal we have the normal efficiency                                                               
    for i, s in enumerate(sign):
        file[s] = TFile(NTUPLEDIR + samples[s]['files'][0] + ".root", "READ") # Read TFile                  
        tree[s] = file[s].Get("ntuple/tree") # Read TTree       
        nevt[s] = (file[s].Get('counter/c_nEvents')).GetBinContent(1)# all gen events before cuts!
        #tree[s] = file[s].Get("skim") # Read TTree       
        #nevt[s] = tree[s].GetEntries("")#if the tree is skimmed, this becomes a relative denominator
        #nevt[s] = (file[s].Get('c_nEvents')).GetBinContent(1)# all gen events before cuts!
        filename = TFile(NTUPLEDIR + samples[s]['files'][0] + ".root", "READ")
        if verbose_add: print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        if verbose_add: print filename
        if verbose_add: print "x-check: n gen events in counter, first bin:"
        if verbose_add: print (filename.Get('c_nEvents')).GetBinContent(1)
        if verbose_add: print "x-check: n entries in counter:"
        if verbose_add: print (filename.Get('c_nEvents')).GetEntries()
        effs[s] = [0]*(ncuts+1)
        effs[s] = [0]*(ncuts+1)
        weight = "1"#"EventWeight"
        var = "isMC"

        if samples[s]['mass'] not in mass_array:
            mass_array.append(samples[s]['mass'])
        if samples[s]['ctau'] not in ctau_array:
            ctau_array.append(samples[s]['ctau'])
        for j, c in enumerate(cutlist):
            tot_gen = nevt[s]
            n = tree[s].GetEntries("(" + cutlist[j] + ")")

            #wat?#test_op = cutlist[j] + " && number_of_matched_Jets>=1"
            #wat?#n = tree[s].GetEntries("(" + test_op + ")")

            ###BUGFIX: efficiency should be computed w.r.t. histo integral
            #hist[s+"_cut"+str(j)] = TH1F(s+"_cut"+str(j), ";"+variable[var]['title'], variable[var]['nbins'], variable[var]['min'], variable[var]['max'])
            #hist[s+"_cut"+str(j)].Sumw2()
            #cutstring = "("+weight+")" + ("*("+cutlist[j]+")" if len(cutlist[j])>0 else "")
            #tree[s].Project(s+"_cut"+str(j), var, cutstring)
            #hist[s+"_cut"+str(j)].SetOption("%s" % tree[s].GetTree().GetEntriesFast())


            if verbose_add: print '\n'
            if verbose_add: print '**********************************************'
            if verbose_add: print "cut: ", c
            if verbose_add: print 'over signal ', s
            if verbose_add: print '\n'
            if verbose_add: print "signal num: ", n
            if verbose_add: print "signal den: ", tot_gen
            #if verbose_add: print "BUGFIX!!!!!!!!!!!"
            #if verbose: print "BUGFIX!!!!!!!!!!!"
            #if verbose_add: print "signal num from integral: ", hist[s+"_cut"+str(j)].Integral()
            #if verbose_add: print "signal den from generator: ", tot_gen
            #if verbose: print "BUGFIX!!!!!!!!!!!"
            if verbose_add: print ("signal eff %.2f") % (float(n)/(tot_gen)*100)
            if tot_gen==0:
                effs[s][j] = float(0.)
            else:
                effs[s][j] = (float(n)/(tot_gen))
            eff_dict[c][s] = {'mass' : samples[s]['mass'], 'ctau' : samples[s]['ctau'], 'eff' :effs[s][j], 'nevents' : n}


    #sort mass array
    masses = np.array(mass_array)
    masses.sort()

    ctaus = np.array(ctau_array)
    ctaus.sort()


    #define multigraph
    mg = TMultiGraph()
    #leg = TLegend(0.78, 0.7, 0.98, 0.98)
    #leg2 = TLegend(0., 0.4, 0.98, 0.98)
    #leg2 = TLegend(0.3, 0.11, 0.65, 0.45)#DCMS,gen matching
    leg2 = TLegend(0.4, 0.11, 0.85, 0.45)#DCMS,summary plot
    leg2 = TLegend(0.4-0.3, 0.11+0.43, 0.85+0.05-0.3, 0.45+0.43)#EXO,summary plot
    leg2 = TLegend(0.4, 0.11, 0.85+0.05, 0.45)#EXO,summary plot

    leg3 = TLegend(0., 0.5, 0.5, 1.)#2 plots

    leg = TLegend(0., 0.4, 0.98, 0.98)
    leg.SetTextSize(0.03)
    leg2.SetTextSize(0.03)
    leg2.SetTextSize(0.025)
    leg.SetBorderSize(0)
    leg2.SetBorderSize(0)
    leg.SetHeader("Signal: m_{#pi}=" +str(mass_point)+" GeV")
    leg2.SetHeader("Signal: m_{#pi}=" +str(mass_point)+" GeV")

    leg3.SetTextSize(0.03)
    leg3.SetTextSize(0.025)
    leg3.SetBorderSize(0)
    leg3.SetHeader("Signal: m_{#pi}=" +str(mass_point)+" GeV")


    #for background let's first consider the cut
    for j, c in enumerate(cutlist):
        print '\n'
        print "cut: ", c
        print 'over background'
        print '\n'
        #then loop over background
        integral = 0
        weighted_integral = 0
        back_tot_events = 0
        for i, s in enumerate(back):
            chain[s] = TChain("ntuple/tree")
            #chain[s] = TChain("skim")
            #print "back: ", s
            back_file = {}
            for p, ss in enumerate(samples[s]['files']):
                back_file[ss] = TFile(NTUPLEDIR + ss + ".root", "READ") # Read TFile                  
                #?#if verbose: print "file: ", ss
                #?#if verbose: print "gen events: ", (back_file[ss].Get('counter/c_nEvents')).GetBinContent(1)
                #?#if verbose: print "tree events: ", (back_file[ss].Get('ntuple/tree')).GetEntries()
                back_tot_events += (back_file[ss].Get('counter/c_nEvents')).GetBinContent(1)
                #back_tot_events += (back_file[ss].Get('c_nEvents')).GetBinContent(1)
                chain[s].Add(NTUPLEDIR + ss + ".root")
            #print "MODIFIED WEIGHT!!!!!!"
            #weight = ("EventWeight*%s/5000." % str(back_tot_events))
            weight = "EventWeight"
            #var = "nCHSJets"
            var = "isMC"
            hist[s] = TH1F(s, ";"+variable[var]['title'], variable[var]['nbins'], variable[var]['min'], variable[var]['max'])
            hist[s].Sumw2()
            cutstring = "("+weight+")" + ("*("+cutlist[j]+")" if len(cutlist[j])>0 else "")
            chain[s].Project(s, var, "")#"1*"+"("+weight+")")
            hist[s].SetOption("%s" % chain[s].GetTree().GetEntriesFast())
            #if verbose: print "Hist content, no cut:"
            #if verbose: print hist[s].Print()
            #?#if verbose: print "events in the histo with get entries with empty project: ", hist[s].GetEntries()
            #?#if verbose: print "area under histo with empty project: ", hist[s].Integral()
            chain[s].Project(s, var, cutstring)#"1*"+"("+weight+")")
            hist[s].SetOption("%s" % chain[s].GetTree().GetEntriesFast())
            hist[s].Scale(samples[s]['weight'] if hist[s].Integral() >= 0 else 0)
            #?#if verbose: print "events in the histo with get entries after project: ", hist[s].GetEntries()
            #?#if verbose: print "area under histo after project: ", hist[s].Integral()
            if verbose: print "Hist content, with cut:"
            if verbose: print hist[s].Print()
            integral += hist[s].GetEntries()
            weighted_integral += hist[s].Integral()
        back_int[c] = integral
        back_int_weight[c] = weighted_integral
        if back_tot_events==0:
            back_eff[c] = float(0.)
        else:
            back_eff[c] = float(integral)/float(back_tot_events)
        if verbose: print "cut: ", c
        if verbose: print "back tot events (unweighted):", back_tot_events
        if verbose: print "back integral (unweighted): ", back_int[c]
        if verbose: print "back integral (weighted): ", back_int_weight[c]
        if verbose: print "back eff (unweighted): ", back_eff[c]*100
        if FOM=="signaleff":
            punzi_dict[c]['back'] = {'back' : back_eff[c]*100}
        for i, s in enumerate(sign):
            if verbose: print "signal efficiency: ", eff_dict[c][s]['eff']*100
            if FOM=="punzi":
                punzi_dict[c][s] = {'sign': eff_dict[c][s]['eff']/(CL**2/2. + alpha*math.sqrt(back_int_weight[c]) + (CL/2.)*math.sqrt(CL**2 + 4*alpha*math.sqrt(back_int_weight[c]) + 4*back_int_weight[c]))}
            elif FOM=="signaleff":
                punzi_dict[c][s] = {'sign': eff_dict[c][s]['eff']*100}
            elif FOM=="entries":
                punzi_dict[c][s] = {'sign': eff_dict[c][s]['nevents']}
            else:
                print "not punzi FOM, aborting!"
                exit()

    if FOM=="signaleff":
        dummy = TGraph()#len(ct),ct, np.array(ct))
        dummy.SetMarkerStyle(0)
        dummy.SetLineWidth(2)
        dummy.SetMarkerSize(1.)
        dummy.SetLineColor(15)
        dummy.SetLineStyle(2)
        if header!="":
            leg2.AddEntry(dummy, header,'')
            leg3.AddEntry(dummy, header,'')


    #for each cut, we need a graph                                                                          
    for j, c in enumerate(cutlist):
    #first let's build the ordered punzi vector w.r.t. masses, for a chosen ctau                            
        punzi_array = []
        back_array = []
        for la in ctaus:
            #la = str(a)
            if la== 0.001:
                st = CHANNEL+"_M"+str(mass_point)+"_ctau0"
            elif la==0.05 or la==0.1:
                st = CHANNEL+"_M"+str(mass_point)+"_ctau"+str(str(la).replace("0.","0p"))
            else:
                st = CHANNEL+"_M"+str(mass_point)+"_ctau"+str(int(la))
            #st = "VBFH_M"+str(mass_point)+"_ctau"+str(a)                                                        
            punzi_array.append(punzi_dict[c][st]['sign'])
        mass = array('d', masses)
        ct = array('d', ctaus)
        p_array = array('d',punzi_array)
        #graph[c] = TGraph(len(mass),mass, np.array(p_array))                                                   
        graph[c] = TGraph(len(ct),ct, np.array(p_array))
        graph[c].SetMarkerStyle(markers[j])#21
        graph[c].SetLineWidth(3)
        graph[c].SetMarkerSize(1.2)
        graph[c].SetMarkerColor(colors[j])
        graph[c].SetLineColor(colors[j])
        graph[c].SetFillColor(colors[j])
        #graph[c].SetLogx()                                                                                 

        leg.AddEntry(graph[c],labellist[j],'PL')
        leg2.AddEntry(graph[c],labellist[j],'PL')
        leg3.AddEntry(graph[c],labellist[j],'PL')
        mg.Add(graph[c])

        if FOM=="signaleff":
        #add plot for background                                                                            
            for a in ctaus:
                back_array.append(punzi_dict[c]['back']['back'])
            mass = array('d', masses)
            ct = array('d', ctaus)
            e_array = array('d',back_array)
            #back_graph[c] = TGraph(len(mass),mass, np.array(e_array))
            back_graph[c] = TGraph(len(ct),ct, np.array(e_array))
            back_graph[c].SetMarkerStyle(0)
            back_graph[c].SetLineWidth(2)
            back_graph[c].SetMarkerSize(1.)
            back_graph[c].SetMarkerColor(colors[j])
            back_graph[c].SetLineColor(colors[j])
            back_graph[c].SetLineStyle(2)
            back_graph[c].SetFillColor(colors[j])
            #back_graph[c].SetLogx()                                                                        
            #leg.AddEntry(back_graph[c],labellist[j]+" bkg.",'PL')
            #w#leg2.AddEntry(back_graph[c],labellist[j]+" bkg.",'PL')                                         
            #w#mg.Add(back_graph[c])

    if FOM=="signaleff":
        dummy = TGraph(len(ct),ct, np.array(e_array))
        dummy.SetMarkerStyle(0)
        dummy.SetLineWidth(2)
        dummy.SetMarkerSize(1.)
        dummy.SetLineColor(15)
        dummy.SetLineStyle(2)
        #w#leg2.AddEntry(dummy, 'cuts on bkg.','PL')


    #cmg = TCanvas("cmg", "cmg", 2000, 1400)
    #cmg = TCanvas("cmg", "cmg", 2000, 800)#best
    #cmg = TCanvas("cmg", "cmg", 1200, 1000)
    cmg = TCanvas("cmg", "cmg", 1300, 800)#DCMS
    cmg.cd()
    cmg.SetGrid()
    cmg.SetLogx()
    #if FOM=="signaleff":
    #    cmg.SetLogx()
    #pad1 = TPad("pad1", "pad1", 0, 0., 0.85, 1.0)
    #pad1 = TPad("pad1", "pad1", 0, 0., 0.7, 1.0)
    #pad1.SetGrid()
    #pad1.SetLogx()
    if FOM=="signaleff":
        print "LOL"
        #pad1.SetLogy()
    #pad1.SetLogy()
    #pad1.Draw()
    #pad1.cd()

    #W#if FOM=="signaleff":
        #w#mg.SetMaximum(101)
        #mg.SetMinimum(1.e-50)
    mg.SetMinimum(0.)#!!
    mg.Draw("APL")
    mg.GetXaxis().SetTitleSize(0.05)
    mg.GetYaxis().SetTitleSize(0.05)
    mg.GetXaxis().SetTitle('c#tau_{#pi} (mm)')
    mg.GetYaxis().SetTitleOffset(0.9);
    if FOM=="punzi":
        mg.GetYaxis().SetTitle('Punzi significance @ '+str(alpha)+' #sigma, '+CHANNEL+' cuts')
        #mg.GetYaxis().SetTitleOffset(1.5)
    elif FOM=="signaleff":
        #mg.GetYaxis().SetTitle('Signal efficiency, '+CHANNEL+' cuts (%)')
        mg.GetYaxis().SetTitle('Signal gen-matching efficiency, '+CHANNEL+' (%)')
    elif FOM=="entries":
        mg.GetYaxis().SetTitle('Signal entries surviving cuts')
    else:
        print "not punzi FOM, aborting"

    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.05)
    latex.SetTextColor(1)
    latex.SetTextFont(42)
    latex.SetTextAlign(33)
    latex.SetTextFont(62)
    latex.DrawLatex(0.25, 0.96, "CMS")
    latex.SetTextFont(52)
    latex.DrawLatex(0.66, 0.96, "Simulation Preliminary")
    cmg.Update()

    cmg.cd()
    leg2.SetTextSize(0.04)
    #leg.Clear()#?????????
    #w#leg2.Draw()

    cmgL = TCanvas("cmgL", "cmgL", 2000, 800)#DCMS
    cmgL.cd()

    #pad2 = TPad("pad2", "pad2", 0.85, 0., 1, 1.0)
    #pad2 = TPad("pad2", "pad2", 0.7, 0., 1, 1.0)
    #pad2.SetGrid()
    #pad2.SetLogx()macro/VBF_punzi_LLP_AOD.py
    #pad2.Draw()
    #pad2.cd()
    leg3.SetTextSize(0.04)
    #leg.Clear()#?????????
    leg3.Draw()
    cmgL.Update()


    if FOM=="punzi":
        cmg.Print(OUTPUTDIR + "Punzi_correct_"+CHANNEL+"_m"+str(mass_point)+"_"+str(alpha)+"sigma"+additional_string+".pdf")
        cmg.Print(OUTPUTDIR + "Punzi_correct_"+CHANNEL+"_m"+str(mass_point)+"_"+str(alpha)+"sigma"+additional_string+".png")
        cmgL.Print(OUTPUTDIR + "Punzi_correct_"+CHANNEL+"_m"+str(mass_point)+"_"+str(alpha)+"sigma"+additional_string+"_L.pdf")
        cmgL.Print(OUTPUTDIR + "Punzi_correct_"+CHANNEL+"_m"+str(mass_point)+"_"+str(alpha)+"sigma"+additional_string+"_L.png")
    elif FOM=="signaleff":
        cmg.Print(OUTPUTDIR + "SignalEff_"+CHANNEL+"_m"+str(mass_point)+additional_string+".pdf")
        cmg.Print(OUTPUTDIR + "SignalEff_"+CHANNEL+"_m"+str(mass_point)+additional_string+".png")
        cmgL.Print(OUTPUTDIR + "SignalEff_"+CHANNEL+"_m"+str(mass_point)+additional_string+"_L.pdf")
        cmgL.Print(OUTPUTDIR + "SignalEff_"+CHANNEL+"_m"+str(mass_point)+additional_string+"_L.png")
    elif FOM=="entries":
        cmg.Print(OUTPUTDIR + "SignalEntries_"+CHANNEL+"_m"+str(mass_point)+additional_string+".pdf")
        cmg.Print(OUTPUTDIR + "SignalEntries_"+CHANNEL+"_m"+str(mass_point)+additional_string+".png")
        cmgL.Print(OUTPUTDIR + "SignalEntries_"+CHANNEL+"_m"+str(mass_point)+additional_string+"_L.pdf")
        cmgL.Print(OUTPUTDIR + "SignalEntries_"+CHANNEL+"_m"+str(mass_point)+additional_string+"_L.png")
    else:
        print "not punzi FOM, aborting"

    if not options.bash: raw_input("Press Enter to continue...")
    cmg.Close()
Exemple #18
0
def draw_syst_unc_envelope(unc_type, added):
    print "Drawing uncertainty vs mass"
    with open(OUT + "signal_" + unc_type + "_unc" + added + ".yaml", "r") as f:
        results = yaml.load(f, Loader=yaml.Loader)
        f.close()
    samp = results.keys()
    masses = []
    ctaus = []
    for s in samp:
        masses.append(samples[s]['mass'])
        ctaus.append(samples[s]['ctau'])
    masses = np.unique(np.sort(np.array(masses)))
    ctaus = np.unique(np.sort(np.array(ctaus)))
    print masses
    print ctaus

    mg = TMultiGraph()
    leg1 = TLegend(0.6, 0.2, 0.9, 0.5)
    #leg1 = TLegend(0.15+0.5, 0.6+0.2, 0.3+0.5, 0.9)
    colors = [2, 418, 801, 856, 602, 920, 881]
    diff_up = {}
    diff_down = {}
    count_c = 0
    print "$c \\tau$ (m) & $m_{\chi}$ (GeV) & uncertainty (\%)" + "\\" + "\\"
    for m in masses:
        string = ""
        nt = 0
        for c in ctaus:
            for s in samp:
                if "mh" + str(m) + "_ctau" + str(c) in s:
                    string += str(c / 1000.) + " & " + str(m) + " & " + str(
                        "%.1f" % results[s]['diff_y2_up'])
                    if nt == 0: string += " & "
            nt += 1
        print string + "\\" + "\\"

    for c in ctaus:
        diff_up[c] = TGraph()
        n = 0
        for m in masses:
            for s in samp:
                if "mh" + str(m) + "_ctau" + str(c) in s:
                    diff_up[c].SetPoint(n, m, results[s]['diff_y2_up'])
                    n += 1
        diff_up[c].SetMarkerStyle(24)
        diff_up[c].SetMarkerColor(colors[count_c])
        diff_up[c].SetLineColor(colors[count_c])
        diff_up[c].SetLineWidth(2)
        diff_up[c].GetXaxis().SetTitle("m_{#chi} (GeV)")
        diff_up[c].GetYaxis().SetTitle("Uncertainty (%)")
        diff_up[c].GetYaxis().SetTitleSize(0.05)
        diff_up[c].SetMinimum(0)
        if unc_type == "PDF":
            leg1.AddEntry(diff_up[c],
                          "c_{#tau} = " + str(c / 1000.) + " m; PDF envelope",
                          "PL")
        if unc_type == "QCD_scales":
            leg1.AddEntry(
                diff_up[c],
                "c_{#tau} = " + str(c / 1000.) + " m; QCD scales envelope",
                "PL")
        mg.Add(diff_up[c])
        count_c += 1

    c1 = TCanvas("c1", "c1", 800, 600)
    c1.SetGrid()
    c1.SetTopMargin(0.06)
    c1.SetBottomMargin(0.12)
    c1.SetRightMargin(0.05)
    c1.SetLeftMargin(0.12)
    c1.SetTicks(1, 1)
    mg.GetXaxis().SetTitle("m_{#chi} (GeV)")
    mg.GetYaxis().SetTitle("Uncertainty (%)")
    mg.GetXaxis().SetTitleSize(0.05)
    mg.GetYaxis().SetTitleSize(0.05)
    mg.SetMinimum(0.)
    mg.SetMaximum(16.)
    mg.Draw("APL")
    leg1.Draw()
    drawCMS_simple(LUMI, "Preliminary", ERA=ERA, onTop=True)
    #drawAnalysis("LL"+CHAN)
    drawRegion(SEL)
    #c1.SetLogx()
    c1.Print(OUT + "signal_" + unc_type + "_uncertainty" + added + ".pdf")
    c1.Print(OUT + "signal_" + unc_type + "_uncertainty" + added + ".png")
    c1.Close()
Exemple #19
0
def Draw_2D_Comp(rootfile_name,
                 var_x,
                 var_y,
                 min,
                 max,
                 WP_list,
                 leg,
                 isTgraph=False):
    gStyle.SetErrorX(0.5)

    ## Creating a multigraph for the canvas if we are looking at TGraphs
    if isTgraph:
        stack = TMultiGraph()
        args = "AP"

    ## Creating a stack for the canvas if we are looking at TPofiles
    else:
        stack = THStack("stack", var_x.name + var_y.name)
        args = "nostack "

    stack.SetMinimum(min)
    stack.SetMaximum(max)

    for wp in WP_list:

        ## Generating the graph name
        graph_name = "{}_vs_{}_{}".format(var_x.name, var_y.name, wp.name)
        if isTgraph:
            graph_name += "_res"

        ## Loading the graph using its name and file location
        graph = GetGraphFromFile(rootfile_name, graph_name)
        if graph == -1:
            continue

        ## Setting the colors specific to the working point
        graph.SetLineColor(wp.colour)
        graph.SetMarkerColor(wp.colour)
        graph.SetMarkerStyle(wp.marker)

        ## Adding the legend entry
        leg.AddEntry(graph, wp.name, "p")

        ## Adding the object to the stack
        stack.Add(graph)
        del graph

    ## Checking to see if any graphs were found for this variable
    nhists = stack.GetListOfGraphs().GetSize(
    ) if isTgraph else stack.GetNhists()
    if nhists == 0:
        print("\n\n\nNo graphs found for working point {}\n\n\n".format(
            wp.name))
        return -1

    ## Drawing the stack on the currrent canvas
    stack.Draw(args)
    leg.Draw()

    ## Setting axis labels
    stack.GetXaxis().SetTitle(var_x.x_label + " " + var_x.units)
    stack.GetYaxis().SetTitle(var_y.x_label + " " + var_y.units)

    ## Moving axis tick marks
    stack.GetYaxis().SetMaxDigits(3)
    stack.GetXaxis().SetLabelOffset(0.017)

    return stack
Exemple #20
0
def combinedDraw(frescoGraph, goodPID, badPID, goodCORR, badCORR):
    #print "combinedDraw start"
    canvas = TCanvas('canvas', 'shouldnotseethis', 0, 0, 1280, 720)

    MG = TMultiGraph()
    legend = ROOT.TLegend(0.55, .55, .9, .9)
    ##legend.SetBorderSize(0)
    #underHisto.SetLineColor(ROOT.kBlack)
    #underHisto.SetMinimum(0)
    ##underHisto.SetMaximum(underHisto.GetMaximum() * 1.5)
    #underHisto.GetXaxis().SetRangeUser(0,180)
    #underHisto.SetTitle(title)
    #underHisto.SetLineColor(ROOT.kBlack)
    #underHisto.SetTitle(title)
    #underHisto.GetYaxis().SetTitle("Counts in Arb. Units")
    #legend.AddEntry(underHisto,"Simulated Angular Distribution")
    #underHisto.SetStats(ROOT.kFALSE)
    #underHisto.Draw()

    if frescoGraph:
        #print "frescoGraph"
        frescoGraph.SetMarkerColor(ROOT.kBlack)
        frescoGraph.SetLineColor(ROOT.kBlack)
        frescoGraph.SetFillColor(ROOT.kBlack)
        #frescoGraph.SetMarkerStyle(33)
        MG.Add(frescoGraph, "L")
        legend.AddEntry(frescoGraph, "Fresco Output")
    else:
        print "No FrescoGraph!!!"
        return

    if goodPID:
        #print "goodPID"
        goodPID.SetMarkerColor(ROOT.kGreen)
        goodPID.SetLineColor(ROOT.kGreen)
        goodPID.SetFillColor(ROOT.kGreen)
        #goodPID.SetMarkerStyle(33)
        MG.Add(goodPID, "P")
        legend.AddEntry(goodPID, "ScaledPID")
    else:
        print "No goodPID in Draw()"

    if goodCORR:
        #print "goodCORR"
        goodCORR.SetMarkerColor(TColor.GetColorDark(ROOT.kGreen))
        goodCORR.SetLineColor(TColor.GetColorDark(ROOT.kGreen))
        goodCORR.SetFillColor(TColor.GetColorDark(ROOT.kGreen))
        goodCORR.SetMarkerStyle(21)
        #afterHisto.Draw("PLsame")
        MG.Add(goodCORR, "P")
        legend.AddEntry(goodCORR, "Good Dual Det")
    else:
        print "No goodCORR in Draw()"

    if badPID:
        #print "badPID"
        badPID.SetMarkerColor(ROOT.kRed)
        badPID.SetLineColor(ROOT.kRed)
        badPID.SetFillColor(ROOT.kRed)
        badPID.SetMarkerStyle(33)
        MG.Add(badPID, "P")
        legend.AddEntry(badPID, "Discard PID")
    else:
        print "No badPID in Draw()"

    if badCORR:
        #print "badCORR"
        badCORR.SetMarkerColor(TColor.GetColorDark(ROOT.kRed))
        badCORR.SetLineColor(TColor.GetColorDark(ROOT.kRed))
        badCORR.SetFillColor(TColor.GetColorDark(ROOT.kRed))
        badCORR.SetMarkerStyle(21)
        MG.Add(badCORR, "P")
        legend.AddEntry(badCORR, "Discard Dual Det")
    else:
        print "No badCORR in Draw()"

    MG.SetTitle(
        "Scaled Elastic Distribution for detector {};Center of Mass Angle in Degrees;Cross section in mb/sr"
        .format(det))
    MG.SetName("MG_d{}".format(det))
    MG.Draw("AP")
    legend.Draw()
    MG.Write()
    MG.SetMaximum(500)
    MG.SetMinimum(0)

    canvas.SetLogy()
    #MG.GetYaxis().SetRangeUser(0,500)

    MG.Draw()
    canvas.SaveAs(MG.GetName() + '.png')