Exemplo n.º 1
0
    def legend4Plot(plot, left = False):
        if left:
            theLeg = TLegend(0.2, 0.62, 0.55, 0.92, "", "NDC")
        else:
            theLeg = TLegend(0.60, 0.62, 0.92, 0.92, "", "NDC")
        theLeg.SetName('theLegend')

        theLeg.SetBorderSize(0)
        theLeg.SetLineColor(0)
        theLeg.SetFillColor(0)
        theLeg.SetFillStyle(0)
        theLeg.SetLineWidth(0)
        theLeg.SetLineStyle(0)
        theLeg.SetTextFont(42)
        theLeg.SetTextSize(.045)

        entryCnt = 0
        for obj in range(0, int(plot.numItems())):
            objName = plot.nameOf(obj)
            if (not plot.getInvisible(objName)):
                theObj = plot.getObject(obj)
                objTitle = theObj.GetTitle()
                if len(objTitle) < 1:
                    objTitle = objName
                dopts = plot.getDrawOptions(objName).Data()
                # print 'obj:',theObj,'title:',objTitle,'opts:',dopts,'type:',type(dopts)
                if theObj.IsA().InheritsFrom('TNamed'):
                    theLeg.AddEntry(theObj, objTitle, dopts)
                    entryCnt += 1
        theLeg.SetY1NDC(0.9 - 0.05*entryCnt - 0.005)
        theLeg.SetY1(theLeg.GetY1NDC())
        return theLeg
Exemplo n.º 2
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
Exemplo n.º 3
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
Exemplo n.º 4
0
def ratioplot():
    for ity in range(0, 2):
        for ivar in range(0, 5):
            for ipt in range(8):
                #h1 = ReadH1(unfolddata,"Unfold2D"+"/"+"Edd_TUnfold_NoReg_typ_"+str(ity)+"_eta0_"+str(var[ivar])+"_pt"+str(ipt))
                h1 = ReadH1(
                    unfolddata, "Unfold2D" + "/" + "Edd_TUnfold_NoReg_typ_" +
                    str(ity) + "_eta0_" + str(var[ivar]) + "_pt" + str(ipt))
                h1.Scale(1 / h1.Integral())
                divBybinWidth(h1)
                h1.SetLineColor(kBlack)
                h1.SetMarkerStyle(9)
                h1.SetMarkerSize(.9)
                h1.SetLineWidth(3)
                c, pad1, pad2 = createCanvasPads()
                pad1.cd()
                sethist(h1, Esvlogx[ivar], Esvlogy[ivar], 22, 30, 25, 25)
                h1.Draw()
                hc1 = []
                legend = TLegend(0.3, .15, 0.7, 0.4)
                legend.SetFillStyle(0)
                legend.SetBorderSize(0)
                legend.AddEntry(h1, "Data")
                for index in range(len(inputroot)):
                    h2 = ReadH1(
                        inputroot[index],
                        "analyzeBasicPat" + "/" + "gen_typ_" + str(ity) +
                        "_pt" + str(ipt) + "_eta0_" + str(var[ivar]))
                    h2.Scale(1 / h2.Integral())
                    divBybinWidth(h2)
                    h2.SetLineColor(color[index])
                    h2.SetLineWidth(3)
                    legend.AddEntry(h2, modelname[index])
                    legend.SetLineWidth(0)
                    legend.Draw("same")
                    rh2 = createRatio(h1, h2, 2.0, 0.1, "MC", "Data")
                    sethist(rh2, Esvlogx[ivar], "MC/Data", 28, 28, 25, 25)
                    hc1.append(rh2)
                    pad2.cd()
                    rh2.Draw("same e hist")
                    #cantest.cd()
                    #rh2.Draw("same e")
                    #if index==2:
                    #cantest.Print("hello.pdf")
                    pad1.cd()
                    pad1.SetLogy(True)
                    h2.Draw("same hist")

                c.Print(name + "[")

    c.Print(name + "]")
Exemplo n.º 5
0
def plot_countries(ana,
                   list_of_ccountries='US',
                   list_of_hists='totc',
                   *args,
                   **kwargs):
    global c, leg
    color = [1, 2, 4, 6, 8, 9, 44, 46, 55, 67, 74, 88]

    start = kwargs.get('minx', None)  # '2020-03-20'
    end = kwargs.get('maxx', None)  # '2020-03-20'
    print_pdf = kwargs.get('pdf', None)  #
    print_png = kwargs.get('png', None)  #
    logy = kwargs.get('logy', 0)  #
    miny = kwargs.get('miny', None)  #
    maxy = kwargs.get('maxy', None)  #
    opt_glob = kwargs.get('opt', '')  #

    ntot = 0
    ccountries = list_of_ccountries.split(';')
    for ccountry in ccountries:
        print('<plot_hist::plot_countries> ccountry:' + ccountry)
        items = ccountry.split(':')
        cntr = items[0]

        if (len(items) > 1): list_of_states = items[1]
        else: list_of_states = 'total'

        nstates = len(list_of_states.split(','))

        if (nstates >
                1):  # assume state-level only histograms, no county-level ones
            ntot += nstates
        else:
            # for a single county and single state, there could be a comma-separated list of counties

            list_of_counties = 'total'
            if (len(items) > 2): list_of_counties = items[2]

            n = len(list_of_counties.split(','))
            ntot += n

    # done with the loop over the countries
    frameinfo = getframeinfo(currentframe())
    print('<plot_hist::plot_countries> line:', frameinfo.lineno, ' Ntot = ',
          ntot)

    hists = list_of_hists.split(',')

    ntot = ntot * len(hists)

    title = ''
    c = TCanvas("c_" + hists[0], "c", 1200, 800)

    leg = TLegend(0.15, 0.88 - 0.04 * ntot, 0.35, 0.88)
    leg.SetLineWidth(0)

    h = None

    ihist = 0
    for ccountry in ccountries:
        items = ccountry.split(':')
        country = items[0]

        list_of_states = 'total'
        if (len(items) > 1): list_of_states = items[1]

        states = list_of_states.split(',')
        nstates = len(states)

        print('<plot_hist::plot_countries> line:',
              getframeinfo(currentframe()).lineno, ' country=', ccountry,
              'list_of_states:', list_of_states, ' nstates:', nstates,
              ' states:', states)

        if (nstates > 1):  # assume no county-level histograms
            for state in states:
                for hist in hists:
                    ccode = country + ':' + state
                    print('<plot_hist::plot_countries> line:',
                          getframeinfo(currentframe()).lineno,
                          ' ccountry:' + ccountry, ' hist:', hist)

                    h = ana.fill(ccode, hist)
                    if (hist == 'totc'):
                        title = 'Total number of positive COVID-19 cases'

                    h.fHist.SetStats(0)

                    if (ihist == 0):
                        h.fHist.SetTitle(title)
                        if (miny): h.fHist.SetMinimum(miny)
                        if (maxy): h.fHist.SetMaximum(maxy)
                        h.Draw(opt=opt_glob,
                               dmin=start,
                               dmax=end,
                               col=color[ihist])
                    else:
                        h.Draw(opt='sames', col=color[ihist])

                    text = country
                    if (state != 'total'): text = text + ':' + state
                    # if (county != 'total'): text=text+':'+county
                    text = text + ':' + hist

                    leg.AddEntry(h.fHist.GetName(), text, 'pe')
                    ihist = ihist + 1

                # end of loop over hists
            # end of loop over states
        else:  # single state
            state = states[0]
            list_of_counties = 'total'
            if (len(items) > 2): list_of_counties = items[2]

            counties = list_of_counties.split(',')
            ncounties = len(counties)

            for county in counties:
                print('<plot_hist::plot_countries>: county=' + county)
                code = country + ':' + state + ':' + county
                for hist in hists:
                    print(
                        '<plot_hist::plot_countries>: filing histogram code=' +
                        code, ' hist=' + hist)
                    h = ana.fill(code, hist)
                    if (hist == 'totc'):
                        title = 'Total number of positive COVID-19 cases'

                    h.fHist.SetStats(0)

                    print('<plot_hist::plot_countries>: ihist=', ihist)
                    if (ihist == 0):
                        h.fHist.SetTitle(title)
                        if (miny): h.fHist.SetMinimum(miny)
                        if (maxy): h.fHist.SetMaximum(maxy)
                        h.Draw(opt=opt_glob,
                               dmin=start,
                               dmax=end,
                               col=color[ihist])
                    else:
                        h.Draw(opt='sames', col=color[ihist])

                    # histogram is filled
                    text = country
                    if (state != 'total'): text = text + ':' + state
                    if (county != 'total'): text = text + ':' + county
                    text = text + ':' + hist

                    leg.AddEntry(h.fHist.GetName(), text, 'pe')
                    ihist = ihist + 1

                # end of loop over hists
            # end of loop over counties
        #
    # end of loop over ccountries

    # leg.Print()
    leg.Draw()

    if (logy == 1): c.SetLogy(1)
    else: c.SetLogy(0)

    c.Modified()
    c.Update()

    if (print_pdf):
        fn = datetime.now().strftime(
            "%Y-%m-%d") + '-' + hist + '-countries.pdf'
        c.Print(fn)

    if (print_png):
        fn = datetime.now().strftime("%Y-%m-%d") + '-' + print_png + '.png'
        c.Print(fn)
Exemplo n.º 6
0
def compare(name,
            file_list,
            name_list,
            legend_list,
            normalize=False,
            drawoption='hE',
            xtitle='',
            ytitle='',
            minx=0,
            maxx=0,
            rebin=1,
            miny=0,
            maxy=0,
            textsizefactor=1,
            logy=False,
            fit='',
            fitlow=0,
            fithigh=0,
            colors=[]):
    c = TCanvas(name, '', 600, 600)
    c.SetLeftMargin(0.15)  #
    c.SetRightMargin(0.05)  #
    c.SetBottomMargin(0.11)
    c.SetTopMargin(0.25)
    legend = TLegend(0.0, 0.76, 0.99, 1.04)

    legend.SetHeader('')
    #legend.SetTextSize(0.03)
    legend.SetBorderSize(0)
    legend.SetTextFont(42)
    legend.SetLineColor(1)
    legend.SetLineStyle(1)
    legend.SetLineWidth(1)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    histo_list = []
    # tfile_list=[]
    the_maxy = 0
    widths = []
    for i in range(len(name_list)):
        # tfile_list.append(TFile(file_list[i],'READ'))
        histo_list.append(file_list[i].Get(name_list[i]).Clone(name_list[i] +
                                                               '_' + str(i)))
        #print(histo_list)
        print(legend_list[i], histo_list[-1].Integral())
        if normalize:
            histo_list[-1].Scale(1.0 /
                                 (histo_list[-1].Integral() + 0.00000001))
        if not histo_list[-1].ClassName() == 'TGraphAsymmErrors':
            histo_list[-1].SetStats(0)
        histo_list[-1].SetLineWidth(3)
        if colors == []:
            histo_list[-1].SetLineColor(i + 1)
            if i > 6:
                histo_list[-1].SetLineColor(i + 4)
        else:
            histo_list[-1].SetLineColor(colors[i])
        histo_list[-1].SetTitle('')

        if rebin != 1:
            histo_list[-1].Rebin(rebin)
        if not histo_list[-1].ClassName() == 'TGraphAsymmErrors':
            the_maxy = max(
                the_maxy,
                histo_list[-1].GetBinContent(histo_list[-1].GetMaximumBin()) *
                1.05)
        if fit != '':
            if fitlow == 0 and fithigh == 0:
                histo_list[-1].Fit(fit)
            else:
                histo_list[-1].Fit(fit, '', '', fitlow[i], fithigh[i])
            histo_list[-1].GetFunction("gaus").SetLineColor(i + 1)
            gaus = histo_list[-1].GetFunction("gaus")
            print(i, gaus.GetParameter(0), gaus.GetParameter(1),
                  gaus.GetParameter(2))
            widths.append(gaus.GetParameter(2))
        if fit == '':
            legend.AddEntry(histo_list[-1], legend_list[i], 'l')
        else:
            legend.AddEntry(
                histo_list[-1],
                legend_list[i] + ' FWHM=' + "%.2f [GeV]" % (2.354 * widths[i]),
                'l')
    for i in range(len(name_list)):
        if i == 0:
            if not histo_list[-1].ClassName() == 'TGraphAsymmErrors':
                if miny != 0 or maxy != 0:
                    histo_list[i].SetMaximum(maxy)
                    histo_list[i].SetMinimum(miny)
                else:
                    histo_list[i].SetMaximum(the_maxy)
                    histo_list[i].SetMinimum(0.0001)
            else:
                histo_list[i].SetMaximum(1.05)
                histo_list[i].SetMinimum(0.0001)
            histo_list[i].Draw(drawoption)
            charsize = 0.05 * textsizefactor
            histo_list[i].GetYaxis().SetLabelSize(charsize)
            histo_list[i].GetYaxis().SetTitleSize(charsize)
            histo_list[i].GetYaxis().SetTitleOffset(1.6)
            histo_list[i].GetXaxis().SetLabelSize(charsize)
            histo_list[i].GetXaxis().SetTitleSize(charsize)
            histo_list[i].GetXaxis().SetTitleOffset(0.95)
            # if useOutfile:
            if xtitle != '':
                histo_list[i].GetXaxis().SetTitle(xtitle)
            if ytitle != '':
                histo_list[i].GetYaxis().SetTitle(ytitle)
            if maxx != 0 or minx != 0:
                histo_list[i].GetXaxis().SetRangeUser(minx, maxx)
            #   histo_list[i].GetYaxis().SetTitle('Efficiency')
        else:
            if histo_list[-1].ClassName() == 'TGraphAsymmErrors':
                drawoption = drawoption.replace("A", "")
            histo_list[i].Draw(drawoption + 'SAME')
    if logy:
        c.SetLogy()
    legend.Draw()
    # outfile.cd()
    #c.Write(name)
    c.SaveAs('pdf/' + name + '.pdf')
Exemplo n.º 7
0
def makeLimitPlot(output,obs,exp,chan,printStats=False):

	fileForHEPData = TFile("plots/"+output+"_forHEPData.root","RECREATE")

	obsLimits = {}
	
	for obsFile in obs:
		if 'width' in obsFile:
			width = obsFile.split('width')[-1].split('_')[0]
		else:
			width = '0.006'
		obsLimits[width] = createObsGraph(obsFile)	

        if  SMOOTH:
		for width,obsGraph in obsLimits.iteritems():
                	smooth_obs=TGraphSmooth("normal")
                	GraphObs_nonSmooth=obsGraph
                	obsLimits[width]=copy.deepcopy(smooth_obs.SmoothSuper(GraphObs_nonSmooth,"linear",0,0.005))
                	obsLimits[width].SetLineWidth(3)


	expLimits = {}
	
	for expFile in exp:
		if 'width' in expFile:
			width = expFile.split('width')[-1].split('_')[0]
		else:
			width = '0.006'	
		expLimits[width] = createExpGraph(expFile)	

    	cCL=TCanvas("cCL", "cCL",0,0,600,450)
    	gStyle.SetOptStat(0)
	gStyle.SetPadRightMargin(0.063)
	gStyle.SetPadLeftMargin(0.14)
	gStyle.SetPadBottomMargin(0.12)
	
    	plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1)
    	plotPad.Draw()	
    	plotPad.cd()


     	smoother=TGraphSmooth("normal")
    	smoother2=TGraphSmooth("normal")
	   

    
    	zprimeX=[]
    	zprimeY=[]
    	fileZPrime=open('tools/xsec_ssm.txt','r')
    	for entries in fileZPrime:
        	entry=entries.split()
        	zprimeX.append(float(entry[0]))
        	zprimeY.append(float(entry[1])/1928)
    	zpX=numpy.array(zprimeX)
    	zpY=numpy.array(zprimeY)
    	GraphZPrime=TGraph(len(zprimeX),zpX,zpY)
    	GraphZPrimeSmooth=smoother2.SmoothSuper(GraphZPrime,"linear")
    	GraphZPrimeSmooth.SetLineWidth(3)
    	GraphZPrimeSmooth.SetLineColor(ROOT.kGreen+3)
    	GraphZPrimeSmooth.SetLineStyle(2)

    	zprimePsiX=[]
    	zprimePsiY=[]
    	fileZPrimePsi=open('tools/xsec_psi.txt','r')
    	for entries in fileZPrimePsi:
        	entry=entries.split()
        	zprimePsiX.append(float(entry[0]))
        	zprimePsiY.append(float(entry[1])/1928)

   	zpPsiX=numpy.array(zprimePsiX)
	zpPsiY=numpy.array(zprimePsiY)
    	GraphZPrimePsi=TGraph(len(zprimePsiX),zpPsiX,zpPsiY)
    	GraphZPrimePsiSmooth=smoother.SmoothSuper(GraphZPrimePsi,"linear")
   	GraphZPrimePsiSmooth.SetLineWidth(3)
    	GraphZPrimePsiSmooth.SetLineColor(ROOT.kBlue)

#Draw the graphs:
    	plotPad.SetLogy()
    	DummyGraph=TH1F("DummyGraph","",100,200,5500)
    	DummyGraph.GetXaxis().SetTitle("M [GeV]")
	if SPIN2:
        		DummyGraph.GetYaxis().SetTitle("[#sigma#upoint#font[12]{B}] G_{KK} / #sigma#upoint#font[12]{B}] Z")
	else:
        		DummyGraph.GetYaxis().SetTitle("[#sigma#upoint#font[12]{B}] Z' / [#sigma#upoint#font[12]{B}] Z")

#	if SPIN2:
#	    	if chan=="mumu":
#       	 		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")
#	else:
#    		if chan=="mumu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")



    	gStyle.SetOptStat(0)
    	DummyGraph.GetXaxis().SetRangeUser(200,5500)

    	DummyGraph.SetMinimum(1e-8)
    	DummyGraph.SetMaximum(3e-4)
    	DummyGraph.GetXaxis().SetLabelSize(0.055)
    	DummyGraph.GetXaxis().SetTitleSize(0.055)
   	DummyGraph.GetXaxis().SetTitleOffset(1.05)
    	DummyGraph.GetYaxis().SetLabelSize(0.055)
    	DummyGraph.GetYaxis().SetTitleSize(0.055)
    	DummyGraph.GetYaxis().SetTitleOffset(1.3)

    	DummyGraph.Draw()

    	plCMS=TPaveLabel(.16,.76,.27,.83,"CMS","NBNDC")
#plCMS.SetTextSize(0.8)
    	plCMS.SetTextAlign(12)
    	plCMS.SetTextFont(62)
    	plCMS.SetFillColor(0)
    	plCMS.SetBorderSize(0)
    
    	plCMS.Draw()

    	plPrelim=TPaveLabel(.16,.76,.27,.82,"Preliminary","NBNDC")
    	plPrelim.SetTextSize(0.6)
    	plPrelim.SetTextAlign(12)
    	plPrelim.SetTextFont(52)
    	plPrelim.SetFillColor(0)
    	plPrelim.SetBorderSize(0)
#    	plPrelim.Draw()

    	leg=TLegend(0.420517,0.7,0.85,0.878644,"","brNDC")   
    	legWidth=TLegend(0.625,0.5,0.9,0.7,"width","brNDC")   
#    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")   
    	leg.SetTextSize(0.0425)
    	legWidth.SetTextSize(0.0425)
	colors = {'01':ROOT.kBlue,'03':ROOT.kRed,'05':ROOT.kGreen+3,'10':ROOT.kOrange}
#	for width in sorted(obsLimits):
#		obsGraph = obsLimits[width]
#		if colors.has_key(width):
#			obsGraph.SetLineColor(colors[width])
#		obsGraph.Draw("lsame")
#		if width == '0.006':
#			leg.AddEntry(obsGraph,"Observed 95% CL limit width 0.6%","l")
#		else:	
#			leg.AddEntry(obsGraph,"Observed 95%% CL limit width %d%%"%int(width),"l")
#
#	for width  in sorted(expLimits):
#		expGraph = expLimits[width]
#		if colors.has_key(width):
#			expGraph.SetLineColor(colors[width])
#		expGraph.Draw("lsame")
#		if width == '0.006':
#			leg.AddEntry(expGraph,"Expected 95% CL limit width 0.6%, median","l")
#		else:	
#			leg.AddEntry(expGraph,"Expected 95%% CL limit width %d%%, median"%(int(width)),"l")

	
	for width in sorted(obsLimits):
		obsGraph = obsLimits[width]
		if colors.has_key(width):
			obsGraph.SetLineColor(colors[width])
		obsGraph.Draw("lsame")
		if width == '0.006':
			leg.AddEntry(obsGraph,"Obs. 95% CL limit","l")

	for width  in sorted(expLimits):
		expGraph = expLimits[width]
		if colors.has_key(width):
			expGraph.SetLineColor(colors[width])
		expGraph.Draw("lsame")
		if width == '0.006':
			leg.AddEntry(expGraph,"Exp. 95% CL limit, median","l")
	for width in sorted(obsLimits):
		obsGraph = obsLimits[width]
		if colors.has_key(width):
			obsGraph.SetLineColor(colors[width])
		if width == '0.006':
			legWidth.AddEntry(obsGraph,"0.6%","l")
		else:	
			legWidth.AddEntry(obsGraph,"%d%%"%int(width),"l")


    	if not SPIN2:
        	GraphZPrimeSmooth.Draw("lsame")
        	GraphZPrimePsiSmooth.Draw("lsame")

	leg1=TLegend(0.625,0.35,0.825,0.5,"","brNDC")
	leg1.SetTextSize(0.0375)
	leg1.AddEntry(GraphZPrimeSmooth,"Z'_{SSM} (width 2.97%)","l")	
	leg1.AddEntry(GraphZPrimePsiSmooth,"Z'_{#Psi} (width 0.53%)","l")	
	
    	leg1.SetLineWidth(0)
    	leg1.SetLineStyle(0)
    	leg1.SetLineColor(0)
    	leg1.SetFillStyle(0)
    	leg1.SetBorderSize(0)

	leg1.Draw()

    	cCL.SetTickx(1)
    	cCL.SetTicky(1)
    	cCL.RedrawAxis()
    	cCL.Update()
    
    	#plCMS.Draw()
  	plotPad.SetTicks(1,1)
	plotPad.RedrawAxis()	

	

    	leg.SetLineWidth(0)
    	leg.SetLineStyle(0)
    	leg.SetLineColor(0)
    	leg.Draw("hist")
    	legWidth.SetLineWidth(0)
    	legWidth.SetLineStyle(0)
    	legWidth.SetLineColor(0)
    	legWidth.SetFillStyle(0)
	legWidth.SetNColumns(2)
    	legWidth.Draw("hist")


	if "Moriond" in output:
         	if (chan=="mumu"): 
            		plLumi=TPaveLabel(.65,.885,.9,.99,"36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})","NBNDC")
        	elif (chan=="elel"):
            		plLumi=TPaveLabel(.65,.885,.9,.99,"35.9 fb^{-1} (13 TeV, ee)","NBNDC")
        	elif (chan=="elmu"):
            		plLumi=TPaveLabel(.27,.885,.9,.99,"35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})","NBNDC")
	else:
 	      	if (chan=="mumu"): 
            		plLumi=TPaveLabel(.65,.905,.9,.99,"13.0 fb^{-1} (13 TeV, #mu#mu)","NBNDC")
        	elif (chan=="elel"):
            		plLumi=TPaveLabel(.65,.905,.9,.99,"2.7 fb^{-1} (13 TeV, ee)","NBNDC")
        	elif (chan=="elmu"):
            		plLumi=TPaveLabel(.4,.905,.9,.99,"12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)","NBNDC")

    	plLumi.SetTextSize(0.5)
    	plLumi.SetTextFont(42)
    	plLumi.SetFillColor(0)
    	plLumi.SetBorderSize(0)
    	plLumi.Draw()
    

	plotPad.RedrawAxis()
	for width in sorted(obsLimits):
		obsGraph = obsLimits[width]
		obsGraph.SetName("graphObs%s"%width)
		obsGraph.Write("graphObs%s"%width)
	for width in sorted(expLimits):
		expGraph = expLimits[width]
		expGraph.SetName("graphExp%s"%width)
		expGraph.Write("graphExp%s"%width)


   	fileForHEPData.Write()
	fileForHEPData.Close() 


    
    	cCL.Update()
    	printPlots(cCL,output)
def train_and_apply():

    np.random.seed(1)
    ROOT.gROOT.SetBatch()

    #Extract data from root file
    tree = uproot.open("out_all.root")["outA/Tevts"]
    branch_mc = [
        "MC_B_P", "MC_B_eta", "MC_B_phi", "MC_B_pt", "MC_D0_P", "MC_D0_eta",
        "MC_D0_phi", "MC_D0_pt", "MC_Dst_P", "MC_Dst_eta", "MC_Dst_phi",
        "MC_Dst_pt", "MC_Est_mu", "MC_M2_miss", "MC_mu_P", "MC_mu_eta",
        "MC_mu_phi", "MC_mu_pt", "MC_pis_P", "MC_pis_eta", "MC_pis_phi",
        "MC_pis_pt", "MC_q2"
    ]
    branch_rec = [
        "B_P", "B_eta", "B_phi", "B_pt", "D0_P", "D0_eta", "D0_phi", "D0_pt",
        "Dst_P", "Dst_eta", "Dst_phi", "Dst_pt", "Est_mu", "M2_miss", "mu_P",
        "mu_eta", "mu_phi", "mu_pt", "pis_P", "pis_eta", "pis_phi", "pis_pt",
        "q2"
    ]
    nvariable = len(branch_mc)
    x_train = tree.array(branch_mc[0], entrystop=options.maxevents)
    for i in range(1, nvariable):
        x_train = np.vstack(
            (x_train, tree.array(branch_mc[i], entrystop=options.maxevents)))
    x_test = tree.array(branch_rec[0], entrystop=options.maxevents)
    for i in range(1, nvariable):
        x_test = np.vstack(
            (x_test, tree.array(branch_rec[i], entrystop=options.maxevents)))
    x_train = x_train.T
    x_test = x_test.T
    x_test = array2D_float(x_test)
    #Different type of reconstruction variables

    #BN normalization
    gamma = 0
    beta = 0.2

    ar = np.array(x_train)
    a = K.constant(ar[:, 0])
    mean = K.mean(a)
    var = K.var(a)
    x_train = K.eval(K.batch_normalization(a, mean, var, gamma, beta))
    for i in range(1, nvariable):
        a = K.constant(ar[:, i])
        mean = K.mean(a)
        var = K.var(a)
        a = K.eval(K.batch_normalization(a, mean, var, gamma, beta))
        x_train = np.vstack((x_train, a))
    x_train = x_train.T

    ar = np.array(x_test)
    a = K.constant(ar[:, 0])
    mean = K.mean(a)
    var = K.var(a)
    x_test = K.eval(K.batch_normalization(a, mean, var, gamma, beta))
    for i in range(1, nvariable):
        a = K.constant(ar[:, i])
        mean = K.mean(a)
        var = K.var(a)
        a = K.eval(K.batch_normalization(a, mean, var, gamma, beta))
        x_test = np.vstack((x_test, a))
    x_test = x_test.T

    #Add noise, remain to be improved
    noise = np.random.normal(loc=0.0, scale=0.01, size=x_train.shape)
    x_train_noisy = x_train + noise
    noise = np.random.normal(loc=0.0, scale=0.01, size=x_test.shape)
    x_test_noisy = x_test + noise
    x_train = np.clip(x_train, -1., 1.)
    x_test = np.clip(x_test, -1., 1.)
    x_train_noisy = np.clip(x_train_noisy, -1., 1.)
    x_test_noisy = np.clip(x_test_noisy, -1., 1.)

    # Network parameters
    input_shape = (x_train.shape[1], )
    batch_size = 128
    latent_dim = 2

    # Build the Autoencoder Model
    # First build the Encoder Model
    inputs = Input(shape=input_shape, name='encoder_input')
    x = inputs

    # Shape info needed to build Decoder Model
    shape = K.int_shape(x)

    # Generate the latent vector
    latent = Dense(latent_dim, name='latent_vector')(x)

    # Instantiate Encoder Model
    encoder = Model(inputs, latent, name='encoder')
    encoder.summary()

    # Build the Decoder Model
    latent_inputs = Input(shape=(latent_dim, ), name='decoder_input')
    x = Dense(shape[1])(latent_inputs)
    x = Reshape((shape[1], ))(x)
    outputs = Activation('tanh', name='decoder_output')(x)

    # Instantiate Decoder Model
    decoder = Model(latent_inputs, outputs, name='decoder')
    decoder.summary()

    # Autoencoder = Encoder + Decoder
    # Instantiate Autoencoder Model
    autoencoder = Model(inputs, decoder(encoder(inputs)), name='autoencoder')
    autoencoder.summary()

    autoencoder.compile(loss='mse', optimizer='adam')

    # Train the autoencoder
    autoencoder.fit(x_train_noisy,
                    x_train,
                    validation_data=(x_test_noisy, x_test),
                    epochs=options.epochs,
                    batch_size=batch_size)

    # Predict the Autoencoder output from corrupted test imformation
    x_decoded = autoencoder.predict(x_test_noisy)

    # Draw Comparision Plots
    c = TCanvas("c", "c", 700, 700)
    fPads1 = TPad("pad1", "Run2", 0.0, 0.29, 1.00, 1.00)
    fPads2 = TPad("pad2", "", 0.00, 0.00, 1.00, 0.29)
    fPads1.SetBottomMargin(0.007)
    fPads1.SetLeftMargin(0.10)
    fPads1.SetRightMargin(0.03)
    fPads2.SetLeftMargin(0.10)
    fPads2.SetRightMargin(0.03)
    fPads2.SetBottomMargin(0.25)
    fPads1.Draw()
    fPads2.Draw()
    fPads1.cd()
    nbin = 50
    min = -1.
    max = 1.
    variable = "P^{B}"
    lbin = (max - min) / nbin
    lbin = str(float((max - min) / nbin))
    xtitle = branch_rec[options.branch - 1]
    ytitle = "Events/" + lbin + "GeV"
    h_rec = TH1D("h_rec", "" + ";%s;%s" % (xtitle, ytitle), nbin, min, max)
    h_rec.Sumw2()
    h_pre = TH1D("h_pre", "" + ";%s;%s" % (xtitle, ytitle), nbin, min, max)
    h_pre.Sumw2()
    for i in range(x_test_noisy.shape[0]):
        h_rec.Fill(x_test_noisy[i][options.branch - 1])
        h_pre.Fill(x_decoded[i][options.branch - 1])
    h_rec = UnderOverFlow1D(h_rec)
    h_pre = UnderOverFlow1D(h_pre)
    maxY = TMath.Max(h_rec.GetMaximum(), h_pre.GetMaximum())
    h_rec.SetLineColor(2)
    h_rec.SetFillStyle(0)
    h_rec.SetLineWidth(2)
    h_rec.SetLineStyle(1)
    h_pre.SetLineColor(3)
    h_pre.SetFillStyle(0)
    h_pre.SetLineWidth(2)
    h_pre.SetLineStyle(1)
    h_rec.SetStats(0)
    h_pre.SetStats(0)
    h_rec.GetYaxis().SetRangeUser(0, maxY * 1.1)
    h_rec.Draw("HIST")
    h_pre.Draw("same HIST")
    h_rec.GetYaxis().SetTitleSize(0.06)
    h_rec.GetYaxis().SetTitleOffset(0.78)
    theLeg = TLegend(0.5, 0.45, 0.95, 0.82, "", "NDC")
    theLeg.SetName("theLegend")
    theLeg.SetBorderSize(0)
    theLeg.SetLineColor(0)
    theLeg.SetFillColor(0)
    theLeg.SetFillStyle(0)
    theLeg.SetLineWidth(0)
    theLeg.SetLineStyle(0)
    theLeg.SetTextFont(42)
    theLeg.SetTextSize(.05)
    theLeg.AddEntry(h_rec, "Reconstruction", "L")
    theLeg.AddEntry(h_pre, "Prediction", "L")
    theLeg.SetY1NDC(0.9 - 0.05 * 6 - 0.005)
    theLeg.SetY1(theLeg.GetY1NDC())
    fPads1.cd()
    theLeg.Draw()
    title = TLatex(
        0.91, 0.93, "AE prediction compare with reconstruction, epochs=" +
        str(options.epochs))
    title.SetNDC()
    title.SetTextSize(0.05)
    title.SetTextFont(42)
    title.SetTextAlign(31)
    title.SetLineWidth(2)
    title.Draw()
    fPads2.cd()
    h_Ratio = h_pre.Clone("h_Ratio")
    h_Ratio.Divide(h_rec)
    h_Ratio.SetLineColor(1)
    h_Ratio.SetLineWidth(2)
    h_Ratio.SetMarkerStyle(8)
    h_Ratio.SetMarkerSize(0.7)
    h_Ratio.GetYaxis().SetRangeUser(0, 2)
    h_Ratio.GetYaxis().SetNdivisions(504, 0)
    h_Ratio.GetYaxis().SetTitle("Pre/Rec")
    h_Ratio.GetYaxis().SetTitleOffset(0.35)
    h_Ratio.GetYaxis().SetTitleSize(0.13)
    h_Ratio.GetYaxis().SetTitleSize(0.13)
    h_Ratio.GetYaxis().SetLabelSize(0.11)
    h_Ratio.GetXaxis().SetLabelSize(0.1)
    h_Ratio.GetXaxis().SetTitleOffset(0.8)
    h_Ratio.GetXaxis().SetTitleSize(0.14)
    h_Ratio.SetStats(0)
    axis1 = TGaxis(min, 1, max, 1, 0, 0, 0, "L")
    axis1.SetLineColor(1)
    axis1.SetLineWidth(1)
    for i in range(1, h_Ratio.GetNbinsX() + 1, 1):
        D = h_rec.GetBinContent(i)
        eD = h_rec.GetBinError(i)
        if D == 0: eD = 0.92
        B = h_pre.GetBinContent(i)
        eB = h_pre.GetBinError(i)
        if B < 0.1 and eB >= B:
            eB = 0.92
            Err = 0.
        if B != 0.:
            Err = TMath.Sqrt((eD * eD) / (B * B) + (D * D * eB * eB) /
                             (B * B * B * B))
            h_Ratio.SetBinContent(i, D / B)
            h_Ratio.SetBinError(i, Err)
        if B == 0.:
            Err = TMath.Sqrt((eD * eD) / (eB * eB) + (D * D * eB * eB) /
                             (eB * eB * eB * eB))
            h_Ratio.SetBinContent(i, D / 0.92)
            h_Ratio.SetBinError(i, Err)
        if D == 0 and B == 0:
            h_Ratio.SetBinContent(i, -1)
            h_Ratio.SetBinError(i, 0)
        h_Ratio.Draw("e0")
        axis1.Draw()

    c.SaveAs(branch_rec[options.branch - 1] + "_comparision.png")
Exemplo n.º 9
0
class Canvas:
    'Common base class for all Samples'

    def __init__(self, name, _format, x1, y1, x2, y2, c, ww=0, hh=0, lsize=0):
        self.name = name
        self.format = _format
        self.plotNames = [name + "." + i for i in _format.split(',')]
        self.plotNamesLog = [name + "_log." + i for i in _format.split(',')]
        self.myCanvas = TCanvas(name, name) if not ww else TCanvas(
            name, name, ww, hh)
        self.ToDraw = []
        self.orderForLegend = []
        self.histos = []
        self.lines = []
        self.arrows = []
        self.ellipses = []
        self.latexs = []
        self.bands = []
        self.options = []
        self.labels = []
        self.labelsOption = []
        self.myLegend = TLegend(x1, y1, x2, y2)
        self.myLegend.SetFillStyle(0)
        self.myLegend.SetTextFont(42)
        if lsize:
            self.myLegend.SetTextSize(lsize)
        else:
            self.myLegend.SetTextSize(0.03)
        self.myLegend.SetLineWidth(0)
        self.myLegend.SetBorderSize(0)
        self.myLegend.SetNColumns(c)

    def changeLabelsToNames(self):
        newlabels = []
        for il, lab in enumerate(self.labels):
            print('changing label %s to %s' % (lab, self.histos[il].GetName()))
            newlabels.append(self.histos[il].GetName())
        self.labels = newlabels

    def banner(self, isData, lumi, scy, inProgress=False):

        latex = TLatex()
        latex.SetNDC()
        latex.SetTextAngle(0)
        latex.SetTextColor(r.kBlack)
        latex.SetTextFont(42)
        latex.SetTextAlign(31)
        latex.SetTextSize(0.06)
        if not scy:
            latex.DrawLatex(0.25, 0.93, "#bf{CMS}")
        else:
            latex.DrawLatex(0.34, 0.93, "#bf{CMS}")

        latexb = TLatex()
        latexb.SetNDC()
        latexb.SetTextAngle(0)
        latexb.SetTextColor(r.kBlack)
        latexb.SetTextFont(42)
        latexb.SetTextAlign(31)
        latexb.SetTextSize(0.04)

        if (isData):
            if not scy:
                latexb.DrawLatex(0.44, 0.93, "#it{Preliminary}")
            else:
                latexb.DrawLatex(0.53, 0.93, "#it{Preliminary}")
        else:
            if not inProgress:
                if not scy:
                    latexb.DrawLatex(0.44, 0.93, "#it{Simulation}")
                else:
                    latexb.DrawLatex(0.53, 0.93, "#it{Simulation}")
            else:
                if not scy:
                    latexb.DrawLatex(0.54, 0.93, "#it{Work in progress}")
                else:
                    latexb.DrawLatex(0.63, 0.93, "#it{Work in progress}")

        text_lumi = ''
        #if isData:
        #    text_lumi = str(lumi)+" fb^{-1}  (13 TeV)"
        if lumi: text_lumi = str(lumi) + " fb^{-1}  (13 TeV)"

        latexc = TLatex()
        latexc.SetNDC()
        latexc.SetTextAngle(0)
        latexc.SetTextColor(r.kBlack)
        latexc.SetTextFont(42)
        latexc.SetTextAlign(31)
        latexc.SetTextSize(0.04)
        latexc.DrawLatex(0.90, 0.93, text_lumi)

    def banner2(self, isData, lumi, scy=False, inProgress=False):

        latex = TLatex()
        latex.SetNDC()
        latex.SetTextAngle(0)
        latex.SetTextColor(r.kBlack)
        latex.SetTextFont(42)
        latex.SetTextAlign(31)
        latex.SetTextSize(0.06)
        latex.DrawLatex(0.23, 0.93, "#bf{CMS}")

        latexb = TLatex()
        latexb.SetNDC()
        latexb.SetTextAngle(0)
        latexb.SetTextColor(r.kBlack)
        latexb.SetTextFont(42)
        latexb.SetTextAlign(31)
        latexb.SetTextSize(0.04)

        #if(isData):
        latexb.DrawLatex(0.38, 0.93, "#it{Preliminary}")
        #else:
        #  latexb.DrawLatex(0.38, 0.93, "#it{Simulation}")

        text_lumi = str(lumi) + " fb^{-1} (13 TeV)"
        latexc = TLatex()
        latexc.SetNDC()
        latexc.SetTextAngle(0)
        latexc.SetTextColor(r.kBlack)
        latexc.SetTextFont(42)
        latexc.SetTextAlign(31)
        latexc.SetTextSize(0.05)
        if lumi != '': latexc.DrawLatex(0.90, 0.93, text_lumi)

    def bannerRatio(self, isData, lumi, scy=False, inProgress=False):

        latex = TLatex()
        latex.SetNDC()
        latex.SetTextAngle(0)
        latex.SetTextColor(r.kBlack)
        latex.SetTextFont(42)
        latex.SetTextAlign(31)
        latex.SetTextSize(0.068)

        if not scy:
            latex.DrawLatex(0.23, 0.88, "#bf{CMS}")
        else:
            latex.DrawLatex(0.30, 0.88, "#bf{CMS}")

        latexb = TLatex()
        latexb.SetNDC()
        latexb.SetTextAngle(0)
        latexb.SetTextColor(r.kBlack)
        latexb.SetTextFont(42)
        latexb.SetTextAlign(31)
        latexb.SetTextSize(0.045)

        if (isData):
            if not scy:
                latexb.DrawLatex(0.39, 0.88, "#it{Preliminary}")
            else:
                latexb.DrawLatex(0.46, 0.88, "#it{Preliminary}")
        else:
            if not inProgress:
                if not scy:
                    latexb.DrawLatex(0.37, 0.88, "#it{Simulation}")
                else:
                    latexb.DrawLatex(0.44, 0.88, "#it{Simulation}")
            else:
                if not scy:
                    latexb.DrawLatex(0.37, 0.88, "#it{Work in progress}")
                else:
                    latexb.DrawLatex(0.44, 0.88, "#it{Work in progress}")

        text_lumi = str(lumi) + " fb^{-1} (13 TeV)"
        latexc = TLatex()
        latexc.SetNDC()
        latexc.SetTextAngle(0)
        latexc.SetTextColor(r.kBlack)
        latexc.SetTextFont(42)
        latexc.SetTextAlign(31)
        latexc.SetTextSize(0.05)
        if lumi != '': latexc.DrawLatex(0.90, 0.88, text_lumi)

    def banner3(self, isData, lumi):

        latex = TLatex()
        latex.SetNDC()
        latex.SetTextAngle(0)
        latex.SetTextColor(r.kBlack)
        latex.SetTextFont(42)
        latex.SetTextAlign(31)
        latex.SetTextSize(0.07)
        latex.DrawLatex(0.1, 1.22, "#bf{CMS}")

        latexb = TLatex()
        latexb.SetNDC()
        latexb.SetTextAngle(0)
        latexb.SetTextColor(r.kBlack)
        latexb.SetTextFont(42)
        latexb.SetTextAlign(31)
        latexb.SetTextSize(0.05)

        #if(isData):
        #  latexb.DrawLatex(0.34, 1.22, "#it{Preliminary}")
        #else:
        #  latexb.DrawLatex(0.34, 1.22, "#it{Simulation}")

        text_lumi = str(lumi) + " fb^{-1} (13 TeV)"
        latexc = TLatex()
        latexc.SetNDC()
        latexc.SetTextAngle(0)
        latexc.SetTextColor(r.kBlack)
        latexc.SetTextFont(42)
        latexc.SetTextAlign(31)
        latexc.SetTextSize(0.05)

    def addBand(self, x1, y1, x2, y2, color, opacity):

        grshade = TGraph(4)
        grshade.SetPoint(0, x1, y1)
        grshade.SetPoint(1, x2, y1)
        grshade.SetPoint(2, x2, y2)
        grshade.SetPoint(3, x1, y2)
        #grshade.SetFillStyle(3001)
        grshade.SetFillColorAlpha(color, opacity)
        self.bands.append(grshade)

    def addLine(self, x1, y1, x2, y2, color, thickness=0.):
        line = TLine(x1, y1, x2, y2)
        line.SetLineColor(color)
        line.SetLineStyle(2)
        if thickness:
            line.SetLineWidth(thickness)
        self.lines.append(line)

    def addArrow(self, x1, y1, x2, y2, color, option, thickness=0.):
        arrow = TArrow(x1, y1, x2, y2, 0.05, option)
        arrow.SetLineColor(color)
        if thickness:
            arrow.SetLineWidth(thickness)
        self.arrows.append(arrow)

    def addEllipse(self, x0, y0, r1, r2, color, fillcolor=False, thickness=0.):
        ellipse = TEllipse(x0, y0, r1, r2)
        ellipse.SetLineColor(color)
        if fillcolor:
            ellipse.SetFillColor(fillcolor)
        else:
            ellipse.SetFillStyle(0)
        if thickness:
            ellipse.SetLineWidth(thickness)
        self.ellipses.append(ellipse)

    def addLatex(self,
                 x1,
                 y1,
                 text,
                 font=42,
                 size=0.04,
                 align=11,
                 color=r.kBlack):
        lat = [x1, y1, text, font, size, align, color]
        self.latexs.append(lat)

    def makeOFHisto(self, histo):
        nbinsx = histo.GetNbinsX()
        xmin = histo.GetXaxis().GetXmin()
        xmax = histo.GetXaxis().GetXmax()
        newhisto = r.TH1F(histo.GetName() + '_withOFBin',
                          histo.GetTitle() + '_withOFBin', nbinsx + 1, xmin,
                          xmax + (xmax - xmin) / nbinsx)
        newhisto.Sumw2()
        newhisto.SetMarkerColor(histo.GetMarkerColor())
        newhisto.SetMarkerStyle(histo.GetMarkerStyle())
        newhisto.SetMarkerSize(histo.GetMarkerSize())
        newhisto.SetLineColor(histo.GetLineColor())
        newhisto.SetLineStyle(histo.GetLineStyle())
        newhisto.SetLineWidth(histo.GetLineWidth())
        newhisto.SetMaximum(histo.GetMaximum())
        newhisto.SetMinimum(histo.GetMinimum())
        newhisto.GetXaxis().SetTitle(histo.GetXaxis().GetTitle())
        newhisto.GetYaxis().SetTitle(histo.GetYaxis().GetTitle())
        for i in range(1, nbinsx + 2):
            newhisto.SetBinContent(i, histo.GetBinContent(i))
            newhisto.SetBinError(i, histo.GetBinError(i))
        return newhisto

    def makeRate(self, eff, option):

        eff.Draw(option)
        self.myCanvas.Update()

        _h = eff.GetTotalHistogram()
        xmax = _h.GetXaxis().GetBinUpEdge(_h.GetNbinsX())
        xmin = _h.GetXaxis().GetBinLowEdge(1)

        _g = eff.GetPaintedGraph()
        _g.SetMinimum(0.0)
        _g.SetMaximum(1.2)
        _g.GetXaxis().SetLimits(xmin, xmax)

        return eff

    def addHisto(self,
                 h,
                 option,
                 label,
                 labelOption,
                 color,
                 ToDraw,
                 orderForLegend,
                 marker=False,
                 doOF=False,
                 normed=False):

        if (color != ""):
            h.SetLineColor(color)
            h.SetMarkerColor(color)
            h.SetFillColorAlpha(r.kWhite, 0)
        if (label == ""):
            label = h.GetTitle()

        if normed:
            h.Scale(1.0 / h.Integral())
        if marker:
            h.SetMarkerStyle(marker)
        self.histos.append(h if not doOF else self.makeOFHisto(h))
        self.options.append(option)
        self.labels.append(label)
        self.labelsOption.append(labelOption)
        self.ToDraw.append(ToDraw)
        self.orderForLegend.append(orderForLegend)

    def addRate(self,
                eff,
                option,
                label,
                labelOption,
                color,
                ToDraw,
                orderForLegend,
                marker=False):

        if (label == ""):
            label = eff.GetTitle()

        _eff = copy.deepcopy(eff)
        if marker:
            _eff.SetMarkerStyle(marker)
        else:
            _eff.SetMarkerStyle(21)

        if color:
            _eff.SetMarkerColor(color)

        _eff.SetLineWidth(2)
        _eff.SetLineColor(color)
        _eff.SetMarkerSize(1.0)

        self.histos.append(_eff)
        self.options.append(option)
        self.labels.append(label)
        self.labelsOption.append(labelOption)
        self.ToDraw.append(ToDraw)
        self.orderForLegend.append(orderForLegend)

    def add2DRate(self, eff, option):

        _eff = copy.deepcopy(eff)
        self.histos.append(_eff)
        self.options.append(option)
        self.labels.append('')
        self.labelsOption.append('')
        self.ToDraw.append(True)
        self.orderForLegend.append(0)

    def addProf(self,
                prof,
                option,
                label,
                labelOption,
                color,
                ToDraw,
                orderForLegend,
                marker=False):

        if (label == ""):
            label = prof.GetTitle()

        _prof = copy.deepcopy(prof)
        if marker:
            _prof.SetMarkerStyle(marker)
        else:
            _prof.SetMarkerStyle(21)
        _prof.SetMarkerColor(color)
        _prof.SetLineWidth(2)
        _prof.SetLineColor(color)
        _prof.SetMarkerSize(1.0)

        self.histos.append(_prof)
        self.options.append(option)
        self.labels.append(label)
        self.labelsOption.append(labelOption)
        self.ToDraw.append(ToDraw)
        self.orderForLegend.append(orderForLegend)

    def addGraph(self, h, option, label, labelOption, color, ToDraw,
                 orderForLegend):

        if (color != ""):
            h.SetLineColor(color)
            h.SetMarkerColor(color)
        if (label == ""):
            label = h.GetTitle()

        self.histos.append(h)
        self.options.append(option)
        self.labels.append(label)
        self.labelsOption.append(labelOption)
        self.ToDraw.append(ToDraw)
        self.orderForLegend.append(orderForLegend)

    def addStack(self, h, option, ToDraw, orderForLegend):

        legendCounter = orderForLegend
        if (orderForLegend < len(self.orderForLegend)):
            legendCounter = len(self.orderForLegend)

        self.addHisto(h, option, "", "", "", ToDraw, -1)
        for h_c in h.GetHists():
            self.addHisto(h_c, "H", h_c.GetTitle(), "F", "", 0, legendCounter)
            legendCounter = legendCounter + 1

    def addPies(self, h, option, ToDraw, orderForLegend):

        legendCounter = orderForLegend
        if (orderForLegend < len(self.orderForLegend)):
            legendCounter = len(self.orderForLegend)

        self.addHisto(h, option, "", "", "", ToDraw, -1)
        for h_c in h.GetHists():
            self.addHisto(h_c, "H", h_c.GetTitle(), "F", "", 0, legendCounter)
            legendCounter = legendCounter + 1

    def makeLegend(self):

        for i in range(0, len(self.histos)):
            for j in range(0, len(self.orderForLegend)):
                if (self.orderForLegend[j] != -1
                        and self.orderForLegend[j] == i):
                    self.myLegend.AddEntry(self.histos[j], self.labels[j],
                                           self.labelsOption[j])

    def ensurePath(self, _path):

        ## Enter a while loop to avoid race conditions
        while True:
            d = os.path.dirname(_path)
            try:
                if not os.path.exists(d):
                    os.makedirs(d)
                break
            except OSError as e:
                if e.errno != os.errno.EEXIST:
                    raise
                print("Sleeping...")
                time.sleep(1.0)
                pass

    def saveRatio(self,
                  legend,
                  isData,
                  log,
                  lumi,
                  hdata,
                  hMC,
                  r_ymin=0,
                  r_ymax=2,
                  label="Data/Prediction",
                  outputDir='plots/',
                  xlog=False,
                  maxYnumbers=False,
                  inProgress=False):

        self.myCanvas.cd()

        pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0)
        pad1.SetBottomMargin(0.015)
        pad1.SetTopMargin(0.13)
        pad1.Draw()
        pad2 = TPad("pad2", "pad2", 0, 0.01, 1, 0.3)
        pad2.SetTopMargin(0.05)
        pad2.SetBottomMargin(0.4)
        pad2.SetGridy(1)
        pad2.Draw()

        pad1.cd()
        if (log):
            pad1.SetLogy(1)
        if (xlog):
            pad1.SetLogx(1)
            pad2.SetLogx(1)

        for i in range(0, len(self.histos)):
            if (self.ToDraw[i] != 0):
                if str(type(self.histos[i])) == "<class 'ROOT.TEfficiency'>":
                    self.makeRate(self.histos[i], self.options[i])
                else:
                    self.histos[i].GetYaxis().SetTitleSize(0.045)
                    self.histos[i].GetYaxis().SetTitleOffset(1.25)
                    self.histos[i].GetXaxis().SetLabelSize(0)
                    self.histos[i].GetYaxis().SetLabelSize(0.04)
                    self.histos[i].Draw(self.options[i])

        if (legend):
            self.makeLegend()
            self.myLegend.SetTextSize(0.04)  # Modify the legend size
            self.myLegend.Draw()

        for band in self.bands:
            band.Draw('f')

        for line in self.lines:
            line.Draw()

        for arrow in self.arrows:
            arrow.Draw()

        for latex in self.latexs:
            lat = TLatex()
            lat.SetNDC()
            lat.SetTextColor(latex[-1])
            lat.SetTextAlign(latex[-2])
            lat.SetTextSize(latex[-3])
            lat.SetTextFont(latex[-4])
            lat.DrawLatex(latex[0], latex[1], latex[2])

        if type(hMC) != list:
            hMClist = [hMC]
        else:
            hMClist = hMC

        ratios = []

        for tmp_hMC in hMClist:
            ind = hMClist.index(tmp_hMC)

            if str(type(tmp_hMC)) == "<class 'ROOT.TEfficiency'>":
                tmp_den = tmp_hMC.GetTotalHistogram().Clone()
                tmp_num = hdata.GetTotalHistogram().Clone()
                for n in range(0, tmp_num.GetNbinsX()):
                    tmp_den.SetBinContent(n + 1, tmp_hMC.GetEfficiency(n + 1))
                    tmp_num.SetBinContent(n + 1, hdata.GetEfficiency(n + 1))
                    tmp_den.SetBinError(n + 1,
                                        tmp_hMC.GetEfficiencyErrorLow(n + 1))
                    tmp_num.SetBinError(n + 1,
                                        hdata.GetEfficiencyErrorLow(n + 1))
                tmp_ratio = tmp_num.Clone(tmp_hMC.GetName() + '_ratio')
                tmp_ratio.Divide(tmp_den)
            else:
                tmp_ratio = hdata.Clone(tmp_hMC.GetName() + '_ratio')
                tmp_ratio.Divide(tmp_hMC)

            ## Ratio tunning
            tmp_ratio.SetTitle("")
            tmp_ratio.GetYaxis().SetRangeUser(r_ymin, r_ymax)
            tmp_ratio.GetYaxis().SetTitle(label)
            tmp_ratio.GetYaxis().CenterTitle()
            tmp_ratio.GetYaxis().SetLabelSize(0.10)
            tmp_ratio.GetYaxis().SetNdivisions(4)
            tmp_ratio.GetYaxis().SetTitleOffset(0.5)
            tmp_ratio.GetXaxis().SetLabelSize(0.10)
            tmp_ratio.GetYaxis().SetTitleSize(0.11)
            tmp_ratio.GetXaxis().SetTitleSize(0.12)
            tmp_ratio.GetXaxis().SetLabelOffset(0.02)
            tmp_ratio.GetXaxis().SetTitle(self.histos[0].GetXaxis().GetTitle())
            tmp_ratio.SetMarkerStyle(20)
            tmp_ratio.SetMarkerColor(r.kBlack)
            tmp_ratio.SetMarkerSize(0.8)
            tmp_ratio.SetMarkerColor(r.kBlack if len(hMClist) ==
                                     1 else tmp_hMC.GetMarkerColor())
            tmp_ratio.SetLineColor(r.kBlack if len(hMClist) ==
                                   1 else tmp_hMC.GetLineColor())
            tmp_ratio.SetLineColor(r.kBlack)
            tmp_ratio.SetLineStyle(tmp_hMC.GetLineStyle())

            ratios.append(tmp_ratio)
            xmin = tmp_ratio.GetBinLowEdge(1)
            xmax = tmp_ratio.GetBinLowEdge(tmp_ratio.GetNbinsX() + 1)

        pad2.cd()
        for rat in ratios:
            rat.Draw('P E0 E1,same')

        line = TLine(xmin, 1, xmax, 1)
        line.SetLineColor(r.kGray + 2)
        line.Draw('')

        pad1.cd()

        if maxYnumbers:
            r.TGaxis().SetMaxDigits(maxYnumbers)
            self.bannerRatio(isData, lumi, scy=True, inProgress=inProgress)
        else:
            self.bannerRatio(isData, lumi, scy=False, inProgress=inProgress)

        if not outputDir[-1] == '/': dirName = outputDir + '/'
        else: dirName = outputDir

        for i, plotName in enumerate(self.plotNames):
            pad1.cd()
            pad1.SetLogy(0)
            path = dirName + plotName
            pathlog = dirName + self.plotNamesLog[i]
            self.ensurePath(path)
            self.myCanvas.SaveAs(path)
            if not '.root' in pathlog:
                if self.histos[0].GetMinimum() == 0:
                    self.histos[0].SetMinimum(0.1)  ### log y axis consistency
                #self.histos[0].SetMaximum(100.0*self.histos[0].GetMaximum()) ### log y axis consistency
                pad1.cd()
                pad1.SetLogy()
                self.myCanvas.SaveAs(pathlog)

        pad1.IsA().Destructor(pad1)
        pad2.IsA().Destructor(pad2)
        self.myLegend.IsA().Destructor(self.myLegend)
        self.myCanvas.IsA().Destructor(self.myCanvas)

    def save(self,
             legend,
             isData,
             log,
             lumi,
             labelx,
             ymin=0,
             ymax=0,
             outputDir='plots/',
             xlog=False,
             zlog=False,
             maxYnumbers=False,
             inProgress=False):

        self.myCanvas.cd()

        if (log):
            self.myCanvas.GetPad(0).SetLogy(1)
        if (xlog):
            self.myCanvas.GetPad(0).SetLogx(1)
        if (zlog):
            self.myCanvas.GetPad(0).SetLogz(1)

        for i in range(0, len(self.histos)):
            if (self.ToDraw[i] != 0):
                if ymin and ymax:
                    self.histos[i].GetYaxis().SetRangeUser(ymin, ymax)
                    #self.histos[i].SetMaximum(ymax)

                if 'TEfficiency' in str(type(
                        self.histos[i])) and 'colz' not in self.options[
                            i] and 'COLZ' not in self.options[i]:
                    self.makeRate(self.histos[i], self.options[i])
                else:
                    self.histos[i].Draw(self.options[i])

        ## Draw axis:
        #self.histos[0].Draw('same axis')

        for band in self.bands:
            band.Draw('f')

        for line in self.lines:
            line.Draw()

        for ellipse in self.ellipses:
            ellipse.Draw()

        for arrow in self.arrows:
            arrow.Draw()

        for latex in self.latexs:
            lat = TLatex()
            lat.SetNDC()
            lat.SetTextColor(latex[-1])
            lat.SetTextAlign(latex[-2])
            lat.SetTextSize(latex[-3])
            lat.SetTextFont(latex[-4])
            lat.DrawLatex(latex[0], latex[1], latex[2])

        if (legend):
            self.makeLegend()
            self.myLegend.Draw()

        lat = TLatex()
        lat.SetNDC()
        lat.SetTextSize(0.05)
        lat.SetTextFont(42)
        lat.DrawLatex(0.46, 0.04, labelx)

        r.gPad.RedrawAxis()

        if maxYnumbers:
            r.TGaxis().SetMaxDigits(maxYnumbers)
            self.banner(isData, lumi, scy=True, inProgress=inProgress)
        else:
            self.banner(isData, lumi, scy=False, inProgress=inProgress)

        if not outputDir[-1] == '/': dirName = outputDir + '/'
        else: dirName = outputDir

        for plotName in self.plotNames:
            path = dirName + plotName
            self.ensurePath(path)
            self.myCanvas.SaveAs(path)

        #for _h in self.histos: del _h
        self.myLegend.IsA().Destructor(self.myLegend)
        self.myCanvas.IsA().Destructor(self.myCanvas)

    def savePie(self, legend, lumi, labelx):

        cpie = TCanvas("cpie", "TPie test", 700, 700)

        pad1 = TPad("pad1", "pad1", 0.1, 0.1, 0.75, 0.75)
        pad1.SetBottomMargin(0.12)
        pad1.Draw()

        pad1.cd()

        colors = []
        names = []
        vals = []

        for i in range(0, len(self.histos)):
            vals.append(self.histos[i].Integral())
            colors.append(self.histos[i].GetLineColor())
            names.append(self.histos[i].GetName())
        v = array('d', vals)
        c = array('i', colors)
        pie4 = TPie("p4", "", len(v), v, c)

        pie4.SetRadius(.45)
        pie4.SetLabelsOffset(.01)
        pie4.SetLabelsOffset(100)
        pie4.SetEntryLineWidth(1, 2)
        pie4.SetEntryLineWidth(2, 2)
        pie4.SetEntryLineWidth(3, 2)
        pie4.SetEntryLineWidth(4, 2)
        pie4.SetEntryLineWidth(5, 2)
        pie4.SetEntryLineWidth(6, 2)
        pie4.SetEntryLineWidth(7, 2)
        pie4.Draw()

        self.makeLegend()
        self.myLegend.Draw()

        lat = TLatex()
        lat.SetNDC()
        lat.SetTextSize(0.06)
        lat.SetTextFont(42)
        lat.DrawLatex(0.12, -0.1, "Slepton signal region, " + labelx)

        self.banner3(True, lumi)
        for plotName in self.plotNames:
            path = 'plots/' + plotName
            #self.ensurePath(path)
            cpie.SaveAs(path)

        self.myLegend.IsA().Destructor(self.myLegend)
Exemplo n.º 10
0
class Canvas:
    'Common base class for all Samples'

    def __init__(self, name, _format, x1, y1, x2, y2, ww=0, hh=0):
        self.name = name
        self.format = _format
        self.plotNames = [name + "." + i for i in _format.split(',')]
        self.plotNamesLog = [name + "_log." + i for i in _format.split(',')]
        self.myCanvas = TCanvas(name, name) if not ww else TCanvas(
            name, name, ww, hh)
        self.ToDraw = []
        self.orderForLegend = []
        self.histos = []
        self.lines = []
        self.arrows = []
        self.latexs = []
        self.bands = []
        self.options = []
        self.labels = []
        self.labelsOption = []
        self.myLegend = TLegend(x1, y1, x2, y2)
        self.myLegend.SetFillColor(r.kWhite)
        self.myLegend.SetTextFont(42)
        self.myLegend.SetTextSize(0.04)
        self.myLegend.SetLineWidth(0)
        self.myLegend.SetBorderSize(0)
        r.gStyle.SetPadRightMargin(0.05)

    def changeLabelsToNames(self):
        newlabels = []
        for il, lab in enumerate(self.labels):
            print 'changing label %s to %s' % (lab, self.histos[il].GetName())
            newlabels.append(self.histos[il].GetName())
        self.labels = newlabels

    def banner(self, isData, lumi):

        latex = TLatex()
        latex.SetNDC()
        latex.SetTextAngle(0)
        latex.SetTextColor(r.kBlack)
        latex.SetTextFont(42)
        latex.SetTextAlign(31)
        latex.SetTextSize(0.06)
        latex.DrawLatex(0.25, 0.93, "#bf{CMS}")

        latexb = TLatex()
        latexb.SetNDC()
        latexb.SetTextAngle(0)
        latexb.SetTextColor(r.kBlack)
        latexb.SetTextFont(42)
        latexb.SetTextAlign(31)
        latexb.SetTextSize(0.04)

        if (isData):
            latexb.DrawLatex(0.47, 0.93, "#it{Preliminary}")
        else:
            latexb.DrawLatex(0.47, 0.93, "#it{Simulation}")

        text_lumi = str(lumi) + " fb^{-1} (13 TeV)"
        latexc = TLatex()
        latexc.SetNDC()
        latexc.SetTextAngle(0)
        latexc.SetTextColor(r.kBlack)
        latexc.SetTextFont(42)
        latexc.SetTextAlign(31)
        latexc.SetTextSize(0.04)
        latexc.DrawLatex(0.90, 0.93, text_lumi)

    def banner2(self, isData, lumi):

        latex = TLatex()
        latex.SetNDC()
        latex.SetTextAngle(0)
        latex.SetTextColor(r.kBlack)
        latex.SetTextFont(42)
        latex.SetTextAlign(31)
        latex.SetTextSize(0.06)
        latex.DrawLatex(0.23, 0.93, "#bf{CMS}")

        latexb = TLatex()
        latexb.SetNDC()
        latexb.SetTextAngle(0)
        latexb.SetTextColor(r.kBlack)
        latexb.SetTextFont(42)
        latexb.SetTextAlign(31)
        latexb.SetTextSize(0.04)

        if (isData):
            latexb.DrawLatex(0.38, 0.93, "#it{Preliminary}")
        else:
            latexb.DrawLatex(0.38, 0.93, "#it{Simulation}")

        text_lumi = str(lumi) + " fb^{-1} (13 TeV)"
        latexc = TLatex()
        latexc.SetNDC()
        latexc.SetTextAngle(0)
        latexc.SetTextColor(r.kBlack)
        latexc.SetTextFont(42)
        latexc.SetTextAlign(31)
        latexc.SetTextSize(0.05)
        latexc.DrawLatex(0.90, 0.93, text_lumi)

    def addBand(self, x1, y1, x2, y2, color, opacity):

        grshade = TGraph(4)
        grshade.SetPoint(0, x1, y1)
        grshade.SetPoint(1, x2, y1)
        grshade.SetPoint(2, x2, y2)
        grshade.SetPoint(3, x1, y2)
        #grshade.SetFillStyle(3001)
        grshade.SetFillColorAlpha(color, opacity)
        self.bands.append(grshade)

    def addLine(self, x1, y1, x2, y2, color, thickness=0.):
        line = TLine(x1, y1, x2, y2)
        line.SetLineColor(color)
        if thickness:
            line.SetLineWidth(thickness)
        self.lines.append(line)

    def addArrow(self, x1, y1, x2, y2, color, option, thickness=0.):
        arrow = TArrow(x1, y1, x2, y2, 0.05, option)
        arrow.SetLineColor(color)
        if thickness:
            arrow.SetLineWidth(thickness)
        self.arrows.append(arrow)

    def addLatex(self, x1, y1, text, font=42, size=0.04):
        lat = [x1, y1, text, font, size]
        self.latexs.append(lat)

    def makeOFHisto(self, histo):
        nbinsx = histo.GetNbinsX()
        xmin = histo.GetXaxis().GetXmin()
        xmax = histo.GetXaxis().GetXmax()
        newhisto = r.TH1F(histo.GetName() + '_withOFBin',
                          histo.GetTitle() + '_withOFBin', nbinsx + 1, xmin,
                          xmax + (xmax - xmin) / nbinsx)
        newhisto.Sumw2()
        newhisto.SetMarkerColor(histo.GetMarkerColor())
        newhisto.SetMarkerStyle(histo.GetMarkerStyle())
        newhisto.SetMarkerSize(histo.GetMarkerSize())
        newhisto.SetLineColor(histo.GetLineColor())
        newhisto.SetLineStyle(histo.GetLineStyle())
        newhisto.SetMaximum(histo.GetMaximum())
        for i in range(1, nbinsx + 2):
            newhisto.SetBinContent(i, histo.GetBinContent(i))
            newhisto.SetBinError(i, histo.GetBinError(i))
        return newhisto

    def addHisto(self,
                 h,
                 option,
                 label,
                 labelOption,
                 color,
                 ToDraw,
                 orderForLegend,
                 doOF=False):

        if (color != ""):
            h.SetLineColor(color)
            h.SetMarkerColor(color)
        if (label == ""):
            label = h.GetTitle()

        self.histos.append(h if not doOF else self.makeOFHisto(h))
        self.options.append(option)
        self.labels.append(label)
        self.labelsOption.append(labelOption)
        self.ToDraw.append(ToDraw)
        self.orderForLegend.append(orderForLegend)

    def addGraph(self, h, option, label, labelOption, color, ToDraw,
                 orderForLegend):

        if (color != ""):
            h.SetLineColor(color)
            h.SetMarkerColor(color)
        if (label == ""):
            label = h.GetTitle()

        self.histos.append(h)
        self.options.append(option)
        self.labels.append(label)
        self.labelsOption.append(labelOption)
        self.ToDraw.append(ToDraw)
        self.orderForLegend.append(orderForLegend)

    def addStack(self, h, option, ToDraw, orderForLegend):

        legendCounter = orderForLegend
        if (orderForLegend < len(self.orderForLegend)):
            legendCounter = len(self.orderForLegend)

        self.addHisto(h, option, "", "", "", ToDraw, -1)
        for h_c in h.GetHists():
            self.addHisto(h_c, "H", h_c.GetTitle(), "F", "", 0, legendCounter)
            legendCounter = legendCounter + 1

    def makeLegend(self):

        for i in range(0, len(self.histos)):
            for j in range(0, len(self.orderForLegend)):
                if (self.orderForLegend[j] != -1
                        and self.orderForLegend[j] == i):
                    self.myLegend.AddEntry(self.histos[j], self.labels[j],
                                           self.labelsOption[j])

    def ensurePath(self, _path):
        d = os.path.dirname(_path)
        if not os.path.exists(d):
            os.makedirs(d)

    def saveRatio(self,
                  legend,
                  isData,
                  log,
                  lumi,
                  hdata,
                  hMC,
                  r_ymin=0,
                  r_ymax=2,
                  label="Data/Prediction"):

        self.myCanvas.cd()

        pad1 = TPad("pad1", "pad1", 0, 0.25, 1, 1.0)
        pad1.SetBottomMargin(0.12)
        pad1.Draw()
        pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.25)
        pad2.SetTopMargin(0.1)
        pad2.SetBottomMargin(0.3)
        pad2.Draw()

        pad1.cd()
        if (log):
            pad1.SetLogy(1)

        for i in range(0, len(self.histos)):
            if (self.ToDraw[i] != 0):
                self.histos[i].Draw(self.options[i])

        if (legend):
            self.makeLegend()
            self.myLegend.Draw()

        for band in self.bands:
            band.Draw('f')

        for line in self.lines:
            line.Draw()

        for arrow in self.arrows:
            arrow.Draw()

        for latex in self.latexs:
            lat = TLatex()
            lat.SetNDC()
            lat.SetTextSize(latex[-1])
            lat.SetTextFont(latex[-2])
            lat.DrawLatex(latex[0], latex[1], latex[2])

        if type(hMC) != list:
            hMClist = [hMC]
        else:
            hMClist = hMC

        ratios = []

        for tmp_hMC in hMClist:
            ind = hMClist.index(tmp_hMC)
            tmp_ratio = hdata.Clone(tmp_hMC.GetName() + '_ratio')
            tmp_ratio.Divide(tmp_hMC)

            tmp_ratio.SetTitle("")
            tmp_ratio.GetYaxis().SetRangeUser(r_ymin, r_ymax)
            tmp_ratio.GetYaxis().SetTitle(label)
            tmp_ratio.GetYaxis().CenterTitle()
            tmp_ratio.GetYaxis().SetLabelSize(0.12)
            tmp_ratio.GetXaxis().SetLabelSize(0.12)
            tmp_ratio.GetYaxis().SetTitleOffset(0.3)
            tmp_ratio.GetYaxis().SetNdivisions(4)
            tmp_ratio.GetYaxis().SetTitleSize(0.14)
            tmp_ratio.GetXaxis().SetTitleSize(0.14)
            tmp_ratio.GetXaxis().SetTitle('')
            tmp_ratio.SetMarkerStyle(tmp_hMC.GetMarkerStyle())
            tmp_ratio.SetFillColorAlpha(r.kBlue - 3, 0.9)
            tmp_ratio.SetFillStyle(3017)
            tmp_ratio.SetMarkerColor(r.kBlack)
            tmp_ratio.SetMarkerSize(0.6)
            #tmp_ratio.SetMarkerColor(r.kBlack if len(hMClist) == 1 else tmp_hMC.GetMarkerColor());
            #tmp_ratio.SetLineColor  (r.kBlack if len(hMClist) == 1 else tmp_hMC.GetLineColor  ());
            tmp_ratio.SetLineColor(tmp_hMC.GetLineColor())
            tmp_ratio.SetLineStyle(tmp_hMC.GetLineStyle())
            ratios.append(tmp_ratio)
            xmin = tmp_ratio.GetBinLowEdge(1)
            xmax = tmp_ratio.GetBinLowEdge(tmp_ratio.GetNbinsX() + 1)

        #tmp_ratio.Draw("E,SAME");
        pad2.cd()
        for rat in ratios:
            rat.Draw('PE2,same')

        line = TLine(xmin, 1, xmax, 1)
        line.SetLineColor(r.kGray + 2)
        line.Draw('')

        pad1.cd()
        self.banner2(isData, lumi)
        for i, plotName in enumerate(self.plotNames):
            pad1.cd()
            pad1.SetLogy(0)
            path = 'plots/' + plotName
            pathlog = 'plots/' + self.plotNamesLog[i]
            self.ensurePath(path)
            self.myCanvas.SaveAs(path)
            if not '.root' in pathlog:
                pad1.cd()
                pad1.SetLogy()
                self.myCanvas.SaveAs(pathlog)

        pad1.IsA().Destructor(pad1)
        pad2.IsA().Destructor(pad2)
        self.myLegend.IsA().Destructor(self.myLegend)
        self.myCanvas.IsA().Destructor(self.myCanvas)

    def save(self, legend, isData, log, lumi, ymin=0, ymax=0):

        self.myCanvas.cd()

        if (log):
            self.myCanvas.GetPad(0).SetLogy(1)

        for i in range(0, len(self.histos)):
            if (self.ToDraw[i] != 0):
                if ymin and ymax:
                    self.histos[i].GetYaxis().SetRangeUser(ymin, ymax)
                self.histos[i].Draw(self.options[i])

        for band in self.bands:
            band.Draw('f')

        for line in self.lines:
            line.Draw()

        for arrow in self.arrows:
            arrow.Draw()

        for latex in self.latexs:
            lat = TLatex()
            lat.SetNDC()
            lat.SetTextSize(latex[-1])
            lat.SetTextFont(latex[-2])
            lat.DrawLatex(latex[0], latex[1], latex[2])

        ## ps = self.histos[0].GetListOfFunctions().FindObject('stat')
        ## if ps:
        ##   ps.SetX1NDC(0.15)
        ##   ps.SetX2NDC(0.55)

        ##   ps.SetY1NDC(0.15)
        ##   ps.SetY2NDC(0.25)

        if (legend):
            self.makeLegend()
            self.myLegend.Draw()

        self.banner(isData, lumi)
        for plotName in self.plotNames:
            path = 'plots/' + plotName
            self.ensurePath(path)
            self.myCanvas.SaveAs(path)

        self.myLegend.IsA().Destructor(self.myLegend)
        self.myCanvas.IsA().Destructor(self.myCanvas)