h_ratio_hists[entry].GetYaxis().SetTitleSize(0.12)
        #h_ratio_hists[entry].GetYaxis().SetTitleOffset(0.98)
        h_ratio_hists[entry].GetYaxis().SetTitleOffset(0.25)
        h_ratio_hists[entry].GetYaxis().SetRangeUser(0.5, 1.5)
        h_ratio_hists[entry].GetYaxis().SetNdivisions(502, kFALSE)
        h_ratio_hists[entry].GetXaxis().SetLabelSize(0.10)
        h_ratio_hists[entry].GetXaxis().SetLabelOffset(0.03)
        h_ratio_hists[entry].GetXaxis().SetTitleSize(0.12)
        h_ratio_hists[entry].GetXaxis().SetTitleOffset(1.0)
        h_ratio_hists[entry].GetYaxis().SetRangeUser(0., 2.)

    line_on_one = TLine(
        h_ratio_hists["h_ratio_2016_2017"].GetXaxis().GetXmin(), 1.,
        h_ratio_hists["h_ratio_2016_2017"].GetXaxis().GetXmax(), 1.)
    line_on_one.SetLineColor(4)
    line_on_one.SetLineStyle(2)
    h_ratio_hists["h_ratio_2016_2017"].Divide(
        h_ratio_hists["h_ratio_2016_2017"], h_signal_2017, 1., 1., "B")
    h_ratio_hists["h_ratio_2016_2018"].Divide(
        h_ratio_hists["h_ratio_2016_2018"], h_signal_2018, 1., 1., "B")
    h_ratio_hists["h_ratio_2017_2018"].Divide(
        h_ratio_hists["h_ratio_2017_2018"], h_signal_2018, 1., 1., "B")
    h_ratio_hists["h_ratio_2016_2017"].SetMarkerColor(1)
    h_ratio_hists["h_ratio_2016_2018"].SetMarkerColor(1)
    h_ratio_hists["h_ratio_2017_2018"].SetMarkerColor(1)
    h_ratio_hists["h_ratio_2016_2017"].GetYaxis().SetRangeUser(0., 2.)
    h_ratio_hists["h_ratio_2016_2018"].GetYaxis().SetRangeUser(0., 2.)
    h_ratio_hists["h_ratio_2017_2018"].GetYaxis().SetRangeUser(0., 2.)
    #h_ratio_hists["h_ratio_2016_2017"].Draw()
    #h_ratio_hists["h_ratio_2016_2018"].Draw()
    h_ratio_hists["h_ratio_2017_2018"].Draw()
Beispiel #2
0
    gRaa[iFile].SetLineColor(colors[iFile])
    gRaa[iFile].SetLineWidth(2)
    gRaa[iFile].SetFillStyle(0)
    leg.AddEntry(hRaa[iFile], legendnames[iFile], 'p')
    hRaaRatio.append(hRaa[iFile].Clone("hRaa%d" % iFile))
    hRaaRatio[iFile].SetDirectory(0)
    hRaaRatio[iFile].Divide(hRaa[iFile], hRaa[0])

ptmin = hRaa[0].GetBinLowEdge(1)
ptmax = hRaa[0].GetBinLowEdge(hRaa[0].GetNbinsX()) + hRaa[0].GetBinWidth(
    hRaa[0].GetNbinsX())

lineatone = TLine(ptmin, 1., ptmax, 1.)
lineatone.SetLineWidth(1)
lineatone.SetLineColor(kBlack)
lineatone.SetLineStyle(9)

cRaa = TCanvas('cRaa', '', 1000, 500)
cRaa.Divide(2, 1)
cRaa.cd(1).DrawFrame(ptmin, 0., ptmax, 2.,
                     ';#it{p}_{T} (GeV/#it{c}); #it{R}_{AA}')
#cRaa.SetLogx()
lineatone.Draw('same')
for iFile in range(len(inputfilenames)):
    # gRaa[iFile].Draw('2')
    hRaa[iFile].Draw('same')
leg.Draw()
cRaa.cd(2).DrawFrame(ptmin, 0., ptmax, 2.,
                     ';#it{p}_{T} (GeV/#it{c}); ratio #it{R}_{AA}')
for iFile in range(len(inputfilenames)):
    if iFile == 0:
Beispiel #3
0
def makeLimitPlot(output,obs,exp,chan,interference,printStats=False,obs2="",ratioLabel=""):

    	fileObs=open(obs,'r')
   	fileExp=open(exp,'r')

    	observedx=[]
    	observedy=[]
    	obsLimits={}
	#xSecs = getFittedXSecCurve("CI_%s"%interference,1.3)
    	for entry in fileObs:
        	massPoint=float(entry.split()[0])
        	limitEntry=float(entry.split()[1])
        	#limitEntry=float(entry.split()[1])*xSecs.Eval(int(float(entry.split()[0])))
        	if massPoint not in obsLimits: obsLimits[massPoint]=[]
        	obsLimits[massPoint].append(limitEntry)
    	if printStats: print "len obsLimits:", len(obsLimits)
    	for massPoint in sorted(obsLimits):
        	observedx.append(massPoint)
        	observedy.append(numpy.mean(obsLimits[massPoint]))
        	if (numpy.std(obsLimits[massPoint])/numpy.mean(obsLimits[massPoint])>0.05):
            		print massPoint," mean: ",numpy.mean(obsLimits[massPoint])," std dev: ",numpy.std(obsLimits[massPoint])," from: ",obsLimits[massPoint]

    	if not obs2 == "":
		fileObs2=open(obs2,'r')

		observedx2=[]
   		observedy2=[]
    		obsLimits2={}
    		for entry in fileObs2:
        		massPoint=float(entry.split()[0])
        		limitEntry=float(entry.split()[1])
        		#limitEntry=float(entry.split()[1])*xSecs.Eval(int(float(entry.split()[0])))
        		if massPoint not in obsLimits2: obsLimits2[massPoint]=[]
        		obsLimits2[massPoint].append(limitEntry)
    		if printStats: print "len obsLimits:", len(obsLimits2)
    		for massPoint in sorted(obsLimits2):
        		observedx2.append(massPoint)
        		observedy2.append(numpy.mean(obsLimits2[massPoint]))
        		if (numpy.std(obsLimits2[massPoint])/numpy.mean(obsLimits2[massPoint])>0.05):
            			print massPoint," mean: ",numpy.mean(obsLimits2[massPoint])," std dev: ",numpy.std(obsLimits2[massPoint])," from: ",obsLimits2[massPoint]





    	limits={}
    	expectedx=[]
    	expectedy=[]
    	expected1SigLow=[]
   	expected1SigHigh=[]
    	expected2SigLow=[]
    	expected2SigHigh=[]
    	for entry in fileExp:
        	massPoint=float(entry.split()[0])
        	#limitEntry=float(entry.split()[1])*xSecs.Eval(int(float(entry.split()[0])))
        	limitEntry=float(entry.split()[1])
        	if massPoint not in limits: limits[massPoint]=[]
        	limits[massPoint].append(limitEntry)

    	if printStats: print "len limits:", len(limits)
    	for massPoint in sorted(limits):
        	limits[massPoint].sort()
        	numLimits=len(limits[massPoint])
        	nrExpts=len(limits[massPoint])
        	medianNr=int(nrExpts*0.5)
        	#get indexes:
        	upper1Sig=int(nrExpts*(1-(1-0.68)*0.5))
        	lower1Sig=int(nrExpts*(1-0.68)*0.5)
        	upper2Sig=int(nrExpts*(1-(1-0.95)*0.5))
        	lower2Sig=int(nrExpts*(1-0.95)*0.5)
        	if printStats: print massPoint,":",limits[massPoint][lower2Sig],limits[massPoint][lower1Sig],limits[massPoint][medianNr],limits[massPoint][upper1Sig],limits[massPoint][upper2Sig]
    		#fill lists:
        	expectedx.append(massPoint)
		print massPoint, limits[massPoint][medianNr]
        	expectedy.append(limits[massPoint][medianNr])
        	expected1SigLow.append(limits[massPoint][lower1Sig])
        	expected1SigHigh.append(limits[massPoint][upper1Sig])
        	expected2SigLow.append(limits[massPoint][lower2Sig])
        	expected2SigHigh.append(limits[massPoint][upper2Sig])
        
    	expX=numpy.array(expectedx)
    	expY=numpy.array(expectedy)

    	values2=[]
    	xPointsForValues2=[]
    	values=[]
    	xPointsForValues=[]
    	if printStats: print "length of expectedx: ", len(expectedx)
    	if printStats: print "length of expected1SigLow: ", len(expected1SigLow)
    	if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh)

	#Here is some Voodoo via Sam:
    	for x in range (0,len(expectedx)):
        	values2.append(expected2SigLow[x])
        	xPointsForValues2.append(expectedx[x])
    	for x in range (len(expectedx)-1,0-1,-1):
        	values2.append(expected2SigHigh[x])
        	xPointsForValues2.append(expectedx[x])
    	if printStats: print "length of values2: ", len(values2)

    	for x in range (0,len(expectedx)):
        	values.append(expected1SigLow[x])
        	xPointsForValues.append(expectedx[x])
    	for x in range (len(expectedx)-1,0-1,-1):
        	values.append(expected1SigHigh[x])
        	xPointsForValues.append(expectedx[x])
    	if printStats: print "length of values: ", len(values)

    	exp2Sig=numpy.array(values2)
    	xPoints2=numpy.array(xPointsForValues2)
    	exp1Sig=numpy.array(values)
    	xPoints=numpy.array(xPointsForValues)
    	if printStats: print "xPoints2: ",xPoints2
    	if printStats: print "exp2Sig: ",exp2Sig
    	if printStats: print "xPoints: ",xPoints
    	if printStats: print "exp1Sig: ",exp1Sig
    	GraphErr2Sig=TGraphAsymmErrors(len(xPoints),xPoints2,exp2Sig)
    	GraphErr2Sig.SetFillColor(ROOT.kOrange)
    	GraphErr1Sig=TGraphAsymmErrors(len(xPoints),xPoints,exp1Sig)
    	GraphErr1Sig.SetFillColor(ROOT.kGreen+1)

    	cCL=TCanvas("cCL", "cCL",0,0,800,500)
    	gStyle.SetOptStat(0)

	if not obs2 == "":
    		plotPad = ROOT.TPad("plotPad","plotPad",0,0.3,1,1)
    		ratioPad = ROOT.TPad("ratioPad","ratioPad",0,0.,1,0.3)
    		plotPad.Draw()	
    		ratioPad.Draw()	
    		plotPad.cd()
	else:
    		plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1)
    		plotPad.Draw()	
    		plotPad.cd()


    

    	expX=numpy.array(expectedx)
    	expY=numpy.array(expectedy)
    	GraphExp=TGraph(len(expX),expX,expY)
    	GraphExp.SetLineWidth(3)
    	GraphExp.SetLineStyle(2)
    	GraphExp.SetLineColor(ROOT.kBlue)

    	obsX=numpy.array(observedx)
    	obsY=numpy.array(observedy)
    	if printStats: print "obsX: ",obsX
    	if printStats: print "obsY: ",obsY

    	if SMOOTH:
        	smooth_obs=TGraphSmooth("normal")
        	GraphObs_nonSmooth=TGraph(len(obsX),obsX,obsY)
        	GraphObs=smooth_obs.SmoothSuper(GraphObs_nonSmooth,"linear",0,0.005)
    	else:
        	GraphObs=TGraph(len(obsX),obsX,obsY)
    
    	GraphObs.SetLineWidth(3)
    	if not obs2 == "":

		ratio = []
		ratiox = []
		for index,val in enumerate(observedy):
			mass = observedx[index]
			foundIndex = -1
			for index2, mass2 in enumerate(observedx2):
				if mass == mass2:
					foundIndex = index2

			if foundIndex > 0:
				ratio.append(observedy2[foundIndex]/val)
				ratiox.append(mass)
		ratioA = numpy.array(ratio)
		ratioX = numpy.array(ratiox)
    		obsX2=numpy.array(observedx2)
    		obsY2=numpy.array(observedy2)
		ratioGraph = TGraph(len(ratioX),ratioX,ratioA)
    		if printStats: print "obsX2: ",obsX2
    		if printStats: print "obsY2: ",obsY2

    		if SMOOTH:
        		smooth_obs2=TGraphSmooth("normal")
        		GraphObs2_nonSmooth=TGraph(len(obsX2),obsX2,obsY2)
        		GraphObs2=smooth_obs2.SmoothSuper(GraphObs2_nonSmooth,"linear",0,0.005)
    		else:
        		GraphObs2=TGraph(len(obsX2),obsX2,obsY2)
    
    		GraphObs2.SetLineWidth(3)
  
	#xSecCurves = []
	#xSecCurves.append(getFittedXSecCurve("CI_%s"%interference,1.3)) 

	#Draw the graphs:
	#plotPad.SetLogy()
	DummyGraph=TH1F("DummyGraph","",100,4000,7500)
    	DummyGraph.GetXaxis().SetTitle("#Lambda [GeV]")
    	if chan=="mumu":
        	DummyGraph.GetYaxis().SetTitle("95% CL limit on singal strength #mu")
    	elif chan=="elel":
        	DummyGraph.GetYaxis().SetTitle("95% CL limit on signal strength #mu")
    	elif chan=="elmu":
        	DummyGraph.GetYaxis().SetTitle("95% CL limit on signal strength #mu")

    	gStyle.SetOptStat(0)
	#DummyGraph.GetXaxis().SetRangeUser(10,40)
	DummyGraph.GetXaxis().SetRangeUser(4000, 7500)

    	DummyGraph.SetMinimum(0)
    	DummyGraph.SetMaximum(8)
    	DummyGraph.GetXaxis().SetLabelSize(0.04)
    	DummyGraph.GetXaxis().SetTitleSize(0.045)
   	DummyGraph.GetXaxis().SetTitleOffset(1.)
    	DummyGraph.GetYaxis().SetLabelSize(0.04)
    	DummyGraph.GetYaxis().SetTitleSize(0.045)
    	DummyGraph.GetYaxis().SetTitleOffset(1.)
    	DummyGraph.Draw()
    	if (FULL):
        	GraphErr2Sig.Draw("F")
        	GraphErr1Sig.Draw("F")
        	GraphExp.Draw("lpsame")
    	else:
		if obs2 == "":
        		GraphExp.Draw("lp")
	if not EXPONLY:
    		GraphObs.Draw("plsame")
    	if not obs2 == "":
		GraphObs2.SetLineColor(ROOT.kRed)
		GraphObs2.SetLineStyle(ROOT.kDashed)
		GraphObs2.Draw("plsame")
    	#for curve in xSecCurves:
	#	print curve.Eval(28) 
        	#curve.Draw()
        	#curve.Draw("sameR")


    	plCMS=TPaveLabel(.15,.81,.25,.88,"CMS","NBNDC")
#plCMS.SetTextSize(0.8)
    	plCMS.SetTextAlign(12)
    	plCMS.SetTextFont(62)
    	plCMS.SetFillColor(0)
    	plCMS.SetFillStyle(0)
    	plCMS.SetBorderSize(0)
    
    	plCMS.Draw()

    	plPrelim=TPaveLabel(.15,.76,.275,.82,"Supplementary","NBNDC")
    	plPrelim.SetTextSize(0.6)
    	plPrelim.SetTextAlign(12)
    	plPrelim.SetTextFont(52)
    	plPrelim.SetFillColor(0)
    	plPrelim.SetFillStyle(0)
    	plPrelim.SetBorderSize(0)
    	#plPrelim.Draw()


    	cCL.SetTickx(1)
    	cCL.SetTicky(1)
    	cCL.RedrawAxis()
    	cCL.Update()
    
    	#leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC")   
    	#leg=TLegend(0.540517,0.623051,0.834885,0.878644,"","brNDC")   
    	leg=TLegend(0.15,0.473051,0.375,0.728644,"ADD model","brNDC")  
        leg.SetBorderSize(0) 
#    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")   
    	leg.SetTextSize(0.032)
	if not obs2 == "":
		if ratioLabel == "":
			ratioLabel = "Variant/Default"
		ratioLabels = ratioLabel.split("/")
		print ratioLabels	
		leg.AddEntry(GraphObs, "%s Obs. 95%% CL limit"%ratioLabels[1],"l")
    		leg.AddEntry(GraphObs2,"%s Obs. 95%% CL limit"%ratioLabels[0],"l")
    	
	else:
		if not EXPONLY:
			leg.AddEntry(GraphObs,"Obs. 95% CL limit","l")
    		leg.AddEntry(GraphExp,"Exp. 95% CL limit, median","l")
        	if (FULL):
   		     	leg.AddEntry(GraphErr1Sig,"Exp. (68%)","f")
        		leg.AddEntry(GraphErr2Sig,"Exp. (95%)","f")


    	#leg1=TLegend(0.665517,0.483051,0.834885,0.623051,labels[interference],"brNDC")
	#leg1.SetTextSize(0.032)
	
        #leg1.AddEntry(xSecCurves[0],labels[interference],"l")

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

    	#leg1.SetLineWidth(0)
    	#leg1.SetLineStyle(0)
    	#leg1.SetFillStyle(0)
    	#leg1.SetLineColor(0)
    	#leg1.Draw("hist")

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

	elif "2017" in output:
         	if (chan=="mumu"): 
            		plLumi=TPaveLabel(.65,.905,.9,.99,"42.1 fb^{-1} (13 TeV, #mu#mu)","NBNDC")
        	elif (chan=="elel"):
            		plLumi=TPaveLabel(.65,.905,.9,.99,"41.5 fb^{-1} (13 TeV, ee)","NBNDC")
        	elif (chan=="elmu"):
            		plLumi=TPaveLabel(.4,.905,.9,.99,"41.5 fb^{-1} (13 TeV, ee) + 42.1 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()
    	line = TLine(10,1,40,1)
	line.SetLineColor(ROOT.kRed)
	line.SetLineWidth(2)
	line.Draw("same")



	plotPad.RedrawAxis()
	
	if not obs2 == "":

    		ratioPad.cd()

    		line = ROOT.TLine(200,1,5500,1)
    		line.SetLineStyle(ROOT.kDashed)

    		ROOT.gStyle.SetTitleSize(0.12, "Y")
    		ROOT.gStyle.SetTitleYOffset(0.35) 
    		ROOT.gStyle.SetNdivisions(000, "Y")
    		ROOT.gStyle.SetNdivisions(408, "Y")
    		ratioPad.DrawFrame(200,0.8,5500,1.2, "; ; %s"%ratioLabel)

    		line.Draw("same")

    		ratioGraph.Draw("sameP")




    
    	cCL.Update()
    	printPlots(cCL,output)
def compare(trigger, leg, data, mc, axisTitle, canvas, dataLumi, metHLTFilters):
    dataFile = TFile.Open("triggerEfficiency_" + data + ".root", "read")
    mcFile = TFile.Open("triggerEfficiency_" + mc + ".root", "read")

    dataEff = dataFile.Get(trigger + "_" + leg)
    mcEff = mcFile.Get(trigger + "_" + leg)

    SetStyle(dataEff)
    SetStyle(mcEff)
    mcEff.SetLineColor(600)
    mcEff.SetMarkerColor(600)

    oneLine = TLine(xlo, 1.0, xhi, 1.0)
    oneLine.SetLineWidth(3)
    oneLine.SetLineStyle(2)

    backgroundHist = TH1D("backgroundHist", "backgroundHist", 1, xlo, xhi)
    backgroundHist.GetYaxis().SetTitle("Trigger Efficiency")
    backgroundHist.GetYaxis().SetRangeUser(ylo, yhi)
    backgroundHist.GetXaxis().SetTitle(axisTitle)
    SetStyle(backgroundHist)

    canvas.cd()
    backgroundHist.Draw()
    dataEff.Draw("CP same")
    mcEff.Draw("CP same")
    #oneLine.Draw("same")

    pt_cmsPrelim = TPaveText(0.132832, 0.859453, 0.486216, 0.906716, "brNDC")
    pt_cmsPrelim.SetBorderSize(0)
    pt_cmsPrelim.SetFillStyle(0)
    pt_cmsPrelim.SetTextFont(62)
    pt_cmsPrelim.SetTextSize(0.0374065)
    pt_cmsPrelim.AddText("CMS Preliminary")
    pt_cmsPrelim.Draw("same")

    pt_lumi = TPaveText(0.744361, 0.92928, 0.860902, 0.977667, "brNDC")
    pt_lumi.SetBorderSize(0)
    pt_lumi.SetFillStyle(0)
    pt_lumi.SetTextFont(42)
    pt_lumi.SetTextSize(0.0374065)
    pt_lumi.AddText("{:.2f}".format(dataLumi / 1000.0) + " fb^{-1}, 13 TeV")
    pt_lumi.Draw("same")

    pt_leg = TPaveText(0.160401, 0.768657, 0.342105, 0.863184, "brNDC")
    pt_leg.SetBorderSize(0)
    pt_leg.SetFillStyle(0)
    pt_leg.SetTextFont(42)
    pt_leg.SetTextSize(0.025)
    pt_leg.SetTextAlign(12)
    if leg == "METLeg":
        legLabel = ""
        for filt in metHLTFilters[:-1]:
            legLabel = legLabel + filt + ", "
        legLabel = legLabel + metHLTFilters[-1]
        pt_leg.AddText(legLabel)
    if leg == "TrackLeg":
        pt_leg.AddText(trigger + "*")
        legLabel = ""
        for filt in metHLTFilters[:-1]:
            legLabel = legLabel + filt + ", "
        legLabel = legLabel + metHLTFilters[-1] + " applied"
        pt_leg.AddText(legLabel)
    if leg == "METPath":
        if trigger == "GrandOr":
            pt_leg.AddText("OR of Signal Paths")
        else:
            if len(trigger) > 25 and len(trigger.split("_")) > 2:
                firstLine = trigger.split("_")[0] + "_" + trigger.split("_")[1] + "_"
                pt_leg.AddText(firstLine)
                secondLine = ""
                for line in trigger.split("_")[2:-1]:
                    secondLine += line + "_"
                secondLine += trigger.split("_")[-1] + "*"
                pt_leg.AddText(secondLine)
            else:
                pt_leg.AddText(trigger + "*")
    pt_leg.Draw("same")

    dataLabel = '2015 data'
    if '2016BC' in data:
        dataLabel = '2016 B+C data'
    if '2016DEFGH' in data:
        dataLabel = '2016 D-H data'
    if '2017' in data:
        dataLabel = '2017 data'
    if '2018' in data:
        dataLabel = '2018 data'

    legendLabel = trigger

    legend = TLegend(0.65, 0.75, 0.93, 0.88)
    legend.SetBorderSize(0)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetTextFont(42)
    if leg == 'METLeg':
        legend.SetHeader('MET Leg')
    elif leg == 'TrackLeg':
        legend.SetHeader('Track Leg')
    legend.AddEntry(dataEff, dataLabel, 'P')
    legend.AddEntry(mcEff, 'W #rightarrow l#nu MC', 'P')
    legend.Draw("same")

    outputDirectory = 'plots_compare'
    if 'BC' in data:
        outputDirectory = 'plots_compareBC'
    if 'DEFGH' in data:
        outputDirectory = 'plots_compareDEFGH'

    if not os.path.exists(outputDirectory):
        os.mkdir(outputDirectory)

    canvas.SaveAs(outputDirectory + '/' + trigger + '_' + leg + '.pdf')

    mcFile.Close()
    dataFile.Close()

    return
Beispiel #5
0
c_phi.Update()

c_dist = TCanvas("c_dist")
h_dist_mc = TH1F("h_dist_mc", "", 60, 0, 60)
f = TF1("f", "landau", 0, 60)
f.SetParameters(10940, 3.8, 1.5)
h_dist_mc.FillRandom("f", int(h_dist.GetEntries()))
h_dist.Draw("ep")
gPad.SetLeftMargin(0.13)
h_dist.SetLineColor(1)
h_dist_mc.SetLineColor(kRed + 1)
h_dist_mc.Draw("same")
h_dist.SetMarkerStyle(20)
h_dist.GetYaxis().SetRangeUser(0.001, 2499)
limit = TLine(32, 0.001, 32, 2499)
limit.SetLineStyle(2)
limit.SetLineWidth(2)
limit.Draw()
leg = TLegend(0.61, 0.75, 0.84, 0.87)
leg.AddEntry(h_dist, "Data", "ep")
leg.AddEntry(h_dist_mc, "MuCS Monte Carlo", "l")
leg.Draw()
pt = TPaveText(0.1, 0.91, 0.39, 0.98, "ndc")
pt.AddText("MicroBooNE")
pt.SetFillColor(0)
pt.SetBorderSize(0)
pt.SetShadowColor(0)
pt.Draw()
c_dist.Update()

gStyle.SetCanvasPreferGL(1)
Beispiel #6
0
def plotter_triggereff(eff_type):

    if "SLT" in args.trigger:
        basepath = "$HOME/PhD/ttH_MultiLeptons/RUN2/HTopMultilepAnalysisCode/trunk/HTopMultilepAnalysis/PlotUtils/OutputPlots_TTbar_RealFakeLep_TriggerEff_SLT/EfficiencyPlots_TriggerEff/BasicPlots/"
    elif "DLT" in args.trigger:
        basepath = "$HOME/PhD/ttH_MultiLeptons/RUN2/HTopMultilepAnalysisCode/trunk/HTopMultilepAnalysis/PlotUtils/OutputPlots_TTbar_RealFakeLep_TriggerEff_DLT/EfficiencyPlots_TriggerEff/BasicPlots/"

    filename_L = "RealFake_L_TriggerEfficiency.root"
    filename_T = "RealFake_T_TriggerEfficiency.root"
    filename_AntiT = "RealFake_AntiT_TriggerEfficiency.root"

    file_L = TFile(basepath + filename_L)
    file_T = TFile(basepath + filename_T)
    file_AntiT = TFile(basepath + filename_AntiT)

    if args.flavour == "mu": flavour = "Mu"
    elif args.flavour == "el": flavour = "El"

    if eff_type == "real": efficiency = "Real"
    elif eff_type == "fake": efficiency = "Fake"

    variable = "Pt"

    append = ("_observed_sub", "_expectedbkg")[bool(args.closure)]

    histname_L = efficiency + "_" + flavour + "_" + variable + "_L_TriggerEfficiency" + append
    histname_T = efficiency + "_" + flavour + "_" + variable + "_T_TriggerEfficiency" + append
    histname_AntiT = efficiency + "_" + flavour + "_" + variable + "_AntiT_TriggerEfficiency" + append

    print("Try to get histogram:\n{0}\nfrom file:\n{1}\n".format(
        histname_L, basepath + filename_L))
    print("Try to get histogram:\n{0}\nfrom file:\n{1}\n".format(
        histname_T, basepath + filename_T))
    print("Try to get histogram:\n{0}\nfrom file:\n{1}\n".format(
        histname_AntiT, basepath + filename_AntiT))

    file_L.cd()
    hist_L = file_L.Get(histname_L)
    hist_L.SetDirectory(0)

    file_T.cd()
    hist_T = file_T.Get(histname_T)
    hist_T.SetDirectory(0)

    file_AntiT.cd()
    hist_AntiT = file_AntiT.Get(histname_AntiT)
    hist_AntiT.SetDirectory(0)

    hist_L.SetLineStyle(1)
    hist_L.SetLineColor(kBlack)

    hist_T.SetLineStyle(2)
    hist_T.SetLineColor(kBlack)
    hist_T.SetMarkerStyle(24)

    delta_eff = hist_L.Clone("DeltaEff")
    delta_eff.SetXTitle(hist_L.GetXaxis().GetTitle())
    delta_eff.SetYTitle("#Delta#varepsilon/#varepsilon [%]")
    delta_eff.GetXaxis().SetTitleSize(0.15)
    delta_eff.GetYaxis().SetTitleSize(0.15)
    delta_eff.GetXaxis().SetTitleOffset(0.90)
    delta_eff.GetYaxis().SetTitleOffset(0.35)
    delta_eff.GetXaxis().SetLabelSize(0.15)
    delta_eff.GetYaxis().SetLabelSize(0.12)
    delta_eff.GetYaxis().SetRangeUser(-50.0, 20.0)
    delta_eff.GetYaxis().SetNdivisions(505)  #(5)
    delta_eff.SetLineColor(kRed)
    delta_eff.SetMarkerColor(kRed)
    delta_eff.SetMarkerSize(1)

    delta_eff.Add(hist_T, -1)
    delta_eff.Divide(hist_T)
    delta_eff.Scale(100.0)

    legend = TLegend(
        0.6, 0.4, 0.8, 0.55
    )  # (x1,y1 (--> bottom left corner), x2, y2 (--> top right corner) )
    legend.SetHeader(flavour + " - " + efficiency)
    legend.SetBorderSize(0)  # no border
    legend.SetFillStyle(0)  # Legend transparent background
    legend.SetTextSize(0.04)  # Increase entry font size!
    legend.SetTextFont(42)  # Helvetica

    legend.AddEntry(hist_T, "Trigger efficiency - T", "P")
    legend.AddEntry(hist_L, "Trigger efficiency - L", "P")

    leg_ATLAS = TLatex()
    leg_lumi = TLatex()
    leg_ATLAS.SetTextSize(0.04)
    leg_ATLAS.SetNDC()
    leg_lumi.SetTextSize(0.04)
    leg_lumi.SetNDC()

    # ---------------------------------------------------------------

    c = TCanvas("c1", "Temp", 50, 50, 800, 600)

    pad1 = TPad("pad1", "", 0, 0.25, 1, 1)
    pad2 = TPad("pad2", "", 0, 0, 1, 0.25)
    pad1.SetBottomMargin(0.02)
    pad2.SetBottomMargin(0.4)
    pad1.Draw()
    pad2.Draw()

    pad1.cd()

    hist_L.GetXaxis().SetLabelSize(0)
    hist_L.GetXaxis().SetLabelOffset(999)

    hist_L.Draw("E0")
    hist_T.Draw("E0 SAME")

    if "SLT" in args.trigger:

        if args.flavour == "el":

            refl_vert0 = TLine(26.0, hist_L.GetMinimum(), 26.0,
                               hist_L.GetMaximum())
            refl_vert0.SetLineStyle(2)
            refl_vert0.SetLineWidth(2)
            refl_vert0.Draw("SAME")

            refl_vert1 = TLine(60.0, hist_L.GetMinimum(), 60.0,
                               hist_L.GetMaximum())
            refl_vert1.SetLineStyle(2)
            refl_vert1.SetLineWidth(2)
            refl_vert1.Draw("SAME")

            refl_vert2 = TLine(140.0, hist_L.GetMinimum(), 140.0,
                               hist_L.GetMaximum())
            refl_vert2.SetLineStyle(2)
            refl_vert2.SetLineWidth(2)
            refl_vert2.Draw("SAME")

        elif args.flavour == "mu":

            refl_vert0 = TLine(26.0, hist_L.GetMinimum(), 26.0,
                               hist_L.GetMaximum())
            refl_vert0.SetLineStyle(2)
            refl_vert0.SetLineWidth(2)
            refl_vert0.Draw("SAME")

            refl_vert1 = TLine(50.0, hist_L.GetMinimum(), 50.0,
                               hist_L.GetMaximum())
            refl_vert1.SetLineStyle(2)
            refl_vert1.SetLineWidth(2)
            refl_vert1.Draw("SAME")

    elif "DLT" in args.trigger:

        if args.flavour == "el":

            refl_vert0 = TLine(17.0, hist_L.GetMinimum(), 17.0,
                               hist_L.GetMaximum())
            refl_vert0.SetLineStyle(2)
            refl_vert0.SetLineWidth(2)
            refl_vert0.Draw("SAME")

        elif args.flavour == "mu":

            refl_vert0 = TLine(22.0, hist_L.GetMinimum(), 22.0,
                               hist_L.GetMaximum())
            refl_vert0.SetLineStyle(2)
            refl_vert0.SetLineWidth(2)
            refl_vert0.Draw("SAME")

    legend.Draw()
    leg_ATLAS.DrawLatex(0.6, 0.27, "#bf{#it{ATLAS}} Work In Progress")
    leg_lumi.DrawLatex(
        0.6, 0.2,
        "#sqrt{{s}} = 13 TeV, #int L dt = {0:.1f} fb^{{-1}}".format(args.lumi))

    pad2.cd()

    delta_eff.Draw("E0")

    refl = TLine(delta_eff.GetBinLowEdge(1), 0.0,
                 delta_eff.GetBinLowEdge(delta_eff.GetNbinsX() + 1), 0.0)
    refl.SetLineStyle(2)
    refl.SetLineWidth(2)
    refl.Draw("SAME")

    outpath = basepath
    if outpath[-1] == '/':
        outpath = outpath[:-1]

    c.SaveAs(outpath + "/TriggerEfficiencyRatio_" + efficiency + "_" +
             flavour + "_" + variable + ".png")
Beispiel #7
0
            if fit_s == None: continue
            fpf_s = fit_s.floatParsFinal()
            nuis_s = fpf_s.find('r')
            r = nuis_s.getVal()
            r_error = nuis_s.getError()
            theHist.SetBinContent(i, r)
            theHist.SetBinError(i, r_error)
            theHist.GetXaxis().SetBinLabel(i, label)
            theFile.Close()
            if igno == "full":
                y = r
                y_error = r_error
            i += 1

        theLine = TLine(1, y, l, y)
        theLine.SetLineStyle(2)
        theLine.SetLineWidth(2)
        theLine.SetLineColor(2)
        theHist.GetXaxis().SetTickLength(0)
        theHist.SetTitle("")
        theHist.GetYaxis().SetRangeUser(low, hi)
        theHist.Draw()
        theLine.Draw()
        tex.SetTextAlign(11)
        tex.SetTextSize(0.06)
        tex.DrawLatex(
            0.1, 0.9,
            "Stability of Fits (Wbb: %s, TTbar: %s)" % (wb, ttsample))
        tex.SetTextAlign(13)
        tex.SetTextSize(0.04)
        tex.DrawLatex(0.15, 0.89,
Beispiel #8
0
def drawCut(cut, ymin, ymax):
    line = TLine()
    line.SetLineWidth(2)
    line.SetLineStyle(7)
    line.SetLineColor(1)
    line.PaintLineNDC(cut, ymin, cut, ymax)
def compareMassRes(trackType):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    leg.Draw()

    plotPad.RedrawAxis()

    ratioPad.cd()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    leg.Draw()

    plotPad.RedrawAxis()

    ratioPad.cd()

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

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

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

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

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

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

    canv.Print("massResolutionCompareUL_%s_BE.pdf" % trackType)
Beispiel #10
0
    # set title and axis labels
    hist.GetXaxis().SetLabelSize(0.03)
    hist.GetXaxis().SetTitle("%s [GeV]" % (title))
    hist.GetYaxis().SetLabelSize(0.03)
    hist.GetYaxis().SetTitleOffset(1.5)
    hist.GetYaxis().SetTitle("Events / %s [GeV]" % (hist.GetBinWidth(1)))

    # fill legend
    leg = TLegend(0.7, 0.75, 0.88, 0.88)
    leg.AddEntry(hist, "TTbar", "f")
    leg.SetFillColor(0)
    leg.SetBorderSize(0)

    # line at W mass
    l = TLine(80.4, 0, 80.4, 1.05 * max_hist)
    l.SetLineStyle(3)

    # and draw
    c.cd()
    hist.Draw('hist')
    leg.Draw('sames')
    if (variable == "goodJ3J4_mass"): l.Draw()

    cpr.prelim_alt(19700, 0.05)
    tex.SetTextAlign(11)  #left, bottom
    tex.DrawLatex(0.1, 0.9, title)

    c.Update()

    c.Print(out_fname + ".png")
    print("you just finished with %s.png" % out_fname)
Beispiel #11
0
fit.SetParameters(800, 100, 0.3)
fit.SetLineColor(ROOT.kBlue)
eff.Fit(fit, 'RQ')

line = TF1('line', '1', xmin, xmax)
line.GetXaxis().SetTitle('m_{jj} (GeV)')
line.GetYaxis().SetTitle('Trigger Efficiency')
line.SetLineColor(ROOT.kBlack)
line.SetLineStyle(2)
line.SetMinimum(0.3)
line.SetMaximum(1.1)
line.Draw()
eff.Draw('samePE1')

gPad.Update()
x0 = fit.GetX(0.99)
cut = TLine(x0, gPad.GetFrame().GetY1(), x0, gPad.GetFrame().GetY2())
cut.SetLineColor(ROOT.kRed)
cut.SetLineStyle(2)
cut.Draw()

print '99% efficiency point: ' + str(round(x0, 1)) + ' GeV'

#----- keep the GUI alive ------------
if __name__ == '__main__':
    rep = ''
    while not rep in ['q', 'Q']:
        rep = raw_input('enter "q" to quit: ')
        if 1 < len(rep):
            rep = rep[0]
Beispiel #12
0
print "reco mass for n=15 :", reco_mass_n15
print " "

linex = TLine(145, 0, 205, 0)
linex.SetLineWidth(1)
linex.Draw()

liney = TLine(173, -0.00825, 173, 0.00725)
if mass == "167":
    liney = TLine(173, -0.0096, 173, 0.0059)

if nlo:
    liney = TLine(173, -0.01025, 173, 0.0055)

liney.SetLineWidth(1)
liney.SetLineStyle(2)
liney.Draw()

l = TLegend(0.6, 0.6, 0.8, 0.8)
if mass == "167":
    l = TLegend(0.6, 0.62, 0.8, 0.82)

if nlo:
    l = TLegend(0.6, 0.65, 0.80, 0.85)
l.AddEntry(final2, "n = 2", "L")
l.AddEntry(final3, "n = 3", "L")
l.AddEntry(final5, "n = 5", "L")
l.AddEntry(final15, "n = 15", "L")
l.SetTextSize(0.04)
l.SetLineColor(0)
l.SetFillColor(0)
Beispiel #13
0
def plot_qcd(
    infile,
    rebin=1,
    bkg_file="../hh2bbbb_limit/classifier_reports/reports_no_bias_corr_SM_mixing_fix/BM0/20171120-160644-bm0.root"
):
    f = TFile.Open(infile)
    f2 = TFile.Open(bkg_file)
    H_ref = 800
    W_ref = 800
    W = W_ref
    H = H_ref

    iPos = 11
    iPeriod = 4

    c1 = TCanvas("c1", "QCD MC distributions", H_ref, W_ref)
    setTDRStyle()

    T = 0.08 * H_ref
    B = 0.12 * H_ref
    L = 0.12 * W_ref
    R = 0.04 * W_ref

    c1.SetFillColor(0)
    c1.SetBorderMode(0)
    c1.SetFrameFillStyle(0)
    c1.SetFrameBorderMode(0)
    c1.SetLeftMargin(L / W)
    c1.SetRightMargin(R / W)
    c1.SetTopMargin(T / H)
    c1.SetBottomMargin(B / H)
    #c1.SetBottomMargin( 0 )

    pad1 = TPad("pad1", "pad1", 0, 0.4, 1, 1.0)
    pad1.SetTopMargin(0.1)
    pad1.SetBottomMargin(0.03)
    pad1.Draw()
    pad1.cd()
    #pad1.SetLogy()

    bkg = f2.Get("bkg_appl/classifier-20171120-160644-bm0_bkg_appl")
    bkg_corr = get_bias_corrected_histo(bkg)

    for b in range(1, bkg.GetNbinsX() + 1):
        print bkg.GetBinContent(b), bkg_corr.GetBinContent(b)

    bkg.Scale(1 / bkg.Integral())
    bkg.Rebin(rebin)
    bkg.SetMaximum(0.12)
    #bkg.SetLineWidth(2)
    #c.SetLogY()
    bkg_corr.Scale(1 / bkg_corr.Integral())
    bkg_corr.Rebin(rebin)

    bkg.GetYaxis().SetTitleSize(20)
    bkg.GetYaxis().SetTitleFont(43)
    bkg.GetYaxis().SetTitleOffset(1.40)
    bkg.GetYaxis().SetLabelFont(43)
    bkg.GetYaxis().SetLabelSize(18)
    #bkg.GetYaxis().SetTitle("Events")
    pad1.SetTickx(1)
    CMS_lumi(pad1, iPeriod, iPos)

    legend = setLegend(0.7, 0.60, 0.90, 0.85)

    #leg.SetTextSize(0.033);
    #leg.SetFillColor(0);
    #leg.SetNColumns(1);
    #pl2.SetHeader(training);

    bkg.Draw("e1")
    bkg.GetXaxis().SetTitle("BDT")
    legend.AddEntry(bkg, "Mixed data", "p")

    total_mc = f.Get(
        "QCD_HT2000toInf_m_%s/classifier-20171120-160644-bm0_QCD_HT2000toInf_m_%s"
        % ("bbbb", "bbbb"))
    total_mc.Reset()
    assert total_mc.Integral() == 0
    for state in ["bbcc", "bbll", "bbbb", "cccc"]:
        hist = f.Get(
            "QCD_HT2000toInf_m_%s/classifier-20171120-160644-bm0_QCD_HT2000toInf_m_%s"
            % (state, state))
        hist.Reset()
        assert hist.Integral() == 0
        for htrange in [
                "700to1000", "1000to1500", "1500to2000", "2000toInf",
                "200to300", "300to500", "500to700"
        ]:
            sampname = "QCD_HT%s" % htrange
            qcdname = "%s_m" % sampname

            #print "QCD_all_%s/classifier-20171120-160644-bm0_QCD_all_%s" % (state, state)
            myhist = f.Get("%s_%s/classifier-20171120-160644-bm0_%s_%s" %
                           (qcdname, state, qcdname, state))
            samples_std = samples[sampname]
            samples_ext = samples["%s_ext" % sampname]
            n_events = samples_std["nevents"] + samples_ext["nevents"]
            xs_br = samples_ext["xsec_br"]
            scalef = xs_br / n_events
            myhist.Scale(scalef)
            hist.Add(myhist)
        total_mc.Add(hist)

    total_mc.Rebin(rebin)
    total_mc.SetLineColor(ROOT.kBlue)
    total_mc.SetLineWidth(1)
    total_mc.SetMarkerStyle(8)
    total_mc.SetMarkerColor(ROOT.kBlue)
    total_mc.Scale(1 / total_mc.Integral())
    total_mc.Draw("E1 SAME")
    legend.AddEntry(total_mc, "QCD MC", "p")

    for bin in range(1, bkg.GetNbinsX() + 1):
        print bin, bkg.GetBinContent(bin), bkg_corr.GetBinContent(bin)

    bkg_corr.SetLineColor(ROOT.kRed)
    bkg_corr.SetMarkerColor(ROOT.kRed)
    bkg_corr.Draw("E1 same")
    legend.AddEntry(bkg_corr, "Mixed data bias corrected", "p")

    #ks = hlist[0][0].KolmogorovTest(hlist[1][0])
    #        print("KS: ", ks)
    #        print("Chi2: ", hlist[0][0].Chi2Test(hlist[1][0], "UU NORM"))

    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.035)
    latex.SetTextColor(1)
    latex.SetTextFont(42)
    latex.SetTextAlign(33)

    legend.Draw("same")

    #if(ymax > 1000): TGaxis.SetMaxDigits(3)
    """for i in range(len(hs)):
        hs[i].SetMaximum(ymax)
        herr[i].SetMaximum(ymax)
        plotH(hlist[i], hs[i], herr[i], dofill[i], residuals)
        if i == len(hs) - 1:
            herr[i].Draw("Esameaxis")
    """

    bkg.GetXaxis().SetLabelSize(0.)
    legend.Draw("same")

    c1.cd()
    pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.4)
    pad2.SetTopMargin(0.)
    pad2.SetBottomMargin(0.2)
    pad2.Draw()
    pad2.cd()

    ratio = bkg.Clone("ratio")
    ratio.Divide(total_mc)

    ratio.SetMinimum(0.)
    ratio.SetMaximum(2.)

    ratio_corr = bkg_corr.Clone("ratio_corr")
    ratio_corr.Divide(total_mc)
    """h_err = total_mc.Clone("error_bar")    
    
    h_err.GetXaxis().SetRangeUser(0, 1)
    #h_err.Reset()
    #herr.Rebin(rebin)
    h_err.GetXaxis().SetTitle("BDT classifier")
    h_err.SetFillStyle(3005)
    h_err.SetFillColor(ROOT.kBlue)
    h_err.SetLineColor(922)
    h_err.SetLineWidth(0)         
    h_err.SetMarkerSize(0)
    h_err.SetMarkerColor(922)
    #h_err.SetMinimum(0.)
    
    
    #h_sig.SetLineStyle(1)
    #h_sig.SetLineWidth(2)
    #h_sig.SetLineColor(sam_opt["sig"]['linecolor'])
    
    #Set error centered at zero as requested by ARC
    for ibin in range(1, h_err.GetNbinsX()+1):
        h_err.SetBinContent(ibin, 0. )

    #If not loading already morphed fit results
    if postfit_file == None:
        for ibin in range(1, h_err.GetNbinsX()+1):
            h_err.SetBinError(ibin, math.sqrt((err * h_err.GetBinContent(ibin))**2 + h_data_bkg.GetBinError(ibin)**2) )
    else:
        for ibin in range(1, h_err.GetNbinsX()+1):
            if not only_bias_unc:
                h_err.SetBinError(ibin, math.sqrt(h_sig.GetBinError(ibin)**2 + h_data_bkg.GetBinError(ibin)**2) )
            else:
                h_err.SetBinError(ibin, math.sqrt(h_data_bkg.GetBinError(ibin)**2) )
    return h_data_bkg, h_sig, h_err
    """

    ratio.Draw("e1")
    ratio_corr.Draw("e1 same")

    l = TLine(0., 1., 1., 1.)
    l.SetLineStyle(3)
    l.Draw("same")
    """leg_coords = 0.65,0.2,0.9,0.4
    if "legpos" in hsOpt:
        if hsOpt["legpos"] == "top":
            leg_coords = 0.65,0.78,0.9,1.
        elif hsOpt["legpos"] == "left" or hsOpt["legpos"] == "topleft":
            leg_coords = 0.1,0.78,0.35,1.
        elif hsOpt["legpos"] == "middle":
            leg_coords = 0.47,0.0,0.63,0.25
    leg = TLegend(*leg_coords)
    leg.SetTextSize(0.05)
    leg.AddEntry(h_data_bkg, "Data - fitted background", "p")
    leg.AddEntry(h_sig, "HH4b fitted")
    leg.AddEntry(hlist[0][-1], "HH4b fitted x5")
    leg.AddEntry(h_error, "Total uncertainty")
    leg.Draw("same")"""

    c1.SaveAs("qcd_plot.png")
    c1.SaveAs("qcd_plot.pdf")
    c1.Clear()
    f.Close()
Beispiel #14
0
class Property:
    def __init__(self, name, bkg_hists, data_hist, signal_hists, sample_hists):
        self.Name = name
        self.Bkg = bkg_hists
        self.Data = data_hist
        self.Signal = signal_hists
        self.Samples = sample_hists

    @staticmethod
    def AddOFUF(h):
        UF = h.GetBinContent(0)
        UF_E = h.GetBinError(0)

        b1 = h.GetBinContent(1)
        b1_e = h.GetBinError(1)

        h.SetBinContent(1, UF + b1)
        h.SetBinError(1, sqrt(UF_E * UF_E + b1_e * b1_e))

        h.SetBinContent(0, 0.0)
        h.SetBinError(0, 0.0)

        lastBin = h.GetNbinsX()
        OF = h.GetBinContent(lastBin + 1)
        OF_E = h.GetBinError(lastBin + 1)

        bL = h.GetBinContent(lastBin)
        bL_e = h.GetBinError(lastBin)

        h.SetBinContent(lastBin, OF + bL)
        h.SetBinError(lastBin, sqrt(OF_E * OF_E + bL_e * bL_e))

        h.SetBinContent(lastBin + 1, 0.0)
        h.SetBinError(lastBin + 1, 0.0)

    def AddOF_UF_Bins(self):
        Property.AddOFUF(self.Data)
        for s in self.Signal:
            Property.AddOFUF(s)
        for s in self.Bkg:
            Property.AddOFUF(self.Bkg[s])
        for s in self.Samples:
            Property.AddOFUF(s)

    def GetBkgFromCR(self, CRProp, Bkgs, replacement, yieldsMethod=1):
        """ 
        extract the shape of bkg from CRProp using data minus all Bkgs
        for the normalization in SR (which is the current property) several methods are foreseen :
        yieldsMethod = 1 : sum of the integral of Bkgs in CR (so taken from the simulation and cross section of backgrounds, trusted in signal region)
        yieldsMethod = 2 : data minus other MC's except Bkgs
        yieldsMethod = 3 : template fit

        replacement is a list with this format : [ NewName , NewColor ]
        """

        notInBkg = [item for item in self.Bkg if item not in Bkgs]
        template = CRProp.SubtractDataMC(notInBkg, self.Name)
        if template.Integral() == 0:
            return -1
        nMCBkgsSR = 0
        nDataMinusBkgsSR = self.Data.Integral()
        for bkg in Bkgs:
            nMCBkgsSR += self.Bkg.pop(bkg).Integral()
        for bkg in self.Bkg:
            nDataMinusBkgsSR -= self.Bkg[bkg].Integral()

        nNormalization = 0
        if yieldsMethod == 1:
            nNormalization = nMCBkgsSR
        elif yieldsMethod == 2:
            nNormalization = nDataMinusBkgsSR
        elif yieldsMethod == 3:
            nFit = 1.0
            var = RooRealVar(self.Name, self.Name,
                             self.Data.GetXaxis().GetXmin(),
                             self.Data.GetXaxis().GetXmax())
            templatehist = RooDataHist("%s_bkg_templateHist" % (self.Name),
                                       self.Name, RooArgList(var), template)
            templatepdf = RooHistPdf("%s_bkg_templatePDF" % (self.Name),
                                     self.Name, RooArgSet(var), templatehist)

            SumNonBkg = self.Data.Clone("sum_%s_%s_th1" %
                                        (self.Name, "_".join(notInBkg)))
            SumNonBkg.Reset()
            for bkg in notInBkg:
                SumNonBkg.Add(self.Bkg[bkg])
            SumNonBkgHist = RooDataHist(
                "sum_%s_%s_Hist" % (self.Name, "_".join(notInBkg)), self.Name,
                RooArgList(var), SumNonBkg)
            SumNonBkgpdf = RooHistPdf(
                "sum_%s_%s_PDF" % (self.Name, "_".join(notInBkg)), self.Name,
                RooArgSet(var), SumNonBkgHist)

            DataHist = RooDataHist("data_%s_Hist" % (self.Name), self.Name,
                                   RooArgList(var), self.Data)

            nBkgs = None
            if nDataMinusBkgsSR > 0:
                nBkgs = RooRealVar("nBkgs", "NBkgs", nDataMinusBkgsSR,
                                   0.5 * nDataMinusBkgsSR,
                                   2 * nDataMinusBkgsSR)
            elif nDataMinusBkgsSR < 0:
                nBkgs = RooRealVar("nBkgs", "NBkgs", nDataMinusBkgsSR,
                                   2 * nDataMinusBkgsSR, -2 * nDataMinusBkgsSR)
            else:
                nBkgs = RooRealVar("nBkgs", "NBkgs", nDataMinusBkgsSR, -10, 10)
            nFixed = RooRealVar("nFixed", "NFIXED", SumNonBkg.Integral(),
                                SumNonBkg.Integral(), SumNonBkg.Integral())
            model = RooAddPdf("model", "model",
                              RooArgList(SumNonBkgpdf, templatepdf),
                              RooArgList(nFixed, nBkgs))
            res = model.fitTo(DataHist, RooFit.Extended(True),
                              RooFit.Save(True), RooFit.SumW2Error(True))
            nNormalization = nBkgs.getVal()

        template.Scale(nNormalization / template.Integral())
        template.SetLineWidth(2)
        template.SetLineColor(1)
        template.SetFillColor(replacement[1])
        template.SetFillStyle(1001)
        self.Bkg[replacement[0]] = template

        return nNormalization

    def Rebin(self, newbins):
        bins = sorted(newbins)
        runArray = array('d', bins)
        self.Data = self.Data.Rebin(
            len(newbins) - 1,
            self.Data.GetName() + "_rebined", runArray)
        if self.Signal:
            for i in range(0, len(self.Signal)):
                self.Signal[i] = self.Signal[i].Rebin(
                    len(newbins) - 1, self.Signal[i].GetName() + "_rebined",
                    runArray)
        for bkg in self.Bkg:
            self.Bkg[bkg] = self.Bkg[bkg].Rebin(
                len(newbins) - 1, self.Bkg[bkg].GetName() + "_rebined",
                runArray)

    @staticmethod
    def addLabels(histo, labels):
        if not histo:
            return
        for i in range(1, histo.GetNbinsX() + 1):
            if not i > len(labels):
                histo.GetXaxis().SetBinLabel(i, labels[i - 1])

    def SetLabels(self, labels):
        Property.addLabels(self.Data, labels)
        for s in self.Signal:
            Property.addLabels(s, labels)
        for bkg in self.Bkg:
            Property.addLabels(self.Bkg[bkg], labels)
        for smpl in self.Samples:
            Property.addLabels(smpl, labels)

    def Clone(self, newname, allsamples=False):
        ret = Property(newname, {}, None, None, [])
        ret.Data = self.Data.Clone(
            string.replace(self.Data.GetName(), self.Name, newname))
        if self.Signal:
            ret.Signal = []
            for i in range(0, len(self.Signal)):
                ret.Signal.append(self.Signal[i].Clone(
                    string.replace(self.Signal[i].GetName(), self.Name,
                                   newname)))
        for bkg in self.Bkg:
            ret.Bkg[bkg] = self.Bkg[bkg].Clone(
                string.replace(self.Bkg[bkg].GetName(), self.Name, newname))
        if allsamples:
            ret.Samples = [
                h.Clone(string.replace(h.GetName(), self.Name, newname))
                for h in self.Samples
            ]

        return ret

    def SubtractDataMC(self, tosubtract, appendix=""):
        tokeep = [item for item in self.Bkg if item not in tosubtract]
        ret = self.Data.Clone("%s_%s_template_%s" %
                              (self.Name, "_".join(tokeep), appendix))
        for bkg in tosubtract:
            ret.Add(self.Bkg[bkg], -1)
        return ret

    def GetStack(self, normtodata=False):
        if not hasattr(self, "Stack"):
            stackname = "%s_stack" % (self.Name)
            scale = 1.0
            if normtodata:
                totalmc = 0.
                for st in self.Bkg:
                    totalmc += self.Bkg[st].Integral()
                if totalmc > 0.000001:
                    scale = self.Data.Integral() / totalmc
                else:
                    print "\t%s was not normalized to data as the mc yield is %.2f" % (
                        self.Name, totalmc)
            #print "in getStack, normtodata = %s and scale is %f" % (str(normtodata) , scale)
            self.Stack = THStack(stackname, self.Name)
            for st in self.Bkg:
                if normtodata:
                    self.Bkg[st].Scale(scale)
                self.Stack.Add(self.Bkg[st])

        return self.Stack

    def GetSignalCanvas(self):
        canvasname = "%s_signal_canvas" % (self.Name)
        if not hasattr(self, "SignalCanvas"):
            self.SignalCanvas = TCanvas(canvasname)

            if self.Signal:
                for s in self.Signal:
                    s.DrawNormalized("E SAME HIST")
                self.GetSLegend().Draw()
        return self.SignalCanvas

    def GetCanvas(self, padid, padOrCanvas=0):
        canvasname = "%s_canvas" % (self.Name)
        pad1name = "%s_pad1" % (self.Name)
        pad2name = "%s_pad2" % (self.Name)
        if not hasattr(self, "Canvas"):
            #print canvasname
            if padOrCanvas == 0:
                self.Canvas = TCanvas(canvasname)
            else:
                self.Canvas = gPad
            self.Canvas.cd()
            self.Pad1 = TPad(pad1name, pad1name, 0, 0.25, 1, 1)
            self.Pad1.SetBottomMargin(0.1)
            self.Pad1.Draw()

            self.Canvas.cd()

            self.Pad2 = TPad(pad2name, pad2name, 0, 0, 1, 0.24)
            self.Pad2.SetTopMargin(0.1)
            self.Pad2.SetBottomMargin(0.1)
            self.Pad2.Draw()

        if padid == 0:
            self.Canvas.cd()
        elif padid == 1:
            self.Pad1.cd()
        if padid == 2:
            self.Pad2.cd()

        return self.Canvas

    def GetLegend(self):
        legendname = "%s_legend" % (self.Name)
        if not hasattr(self, "Legend"):
            self.Legend = TLegend(0.7, 0.6, 0.9, 0.9, "", "brNDC")
            self.Legend.SetName(legendname)
            self.Legend.AddEntry(self.Data, "Data", "lp")
            for st in reversed(self.Bkg.keys()):
                self.Legend.AddEntry(self.Bkg[st], st, "f")

        return self.Legend

    def GetSLegend(self):
        legendname = "%s_Slegend" % (self.Name)
        if not hasattr(self, "SLegend"):
            self.SLegend = TLegend(0.6, 0.6, 0.7, 0.9, "", "brNDC")
            self.SLegend.SetName(legendname)
            for st in self.Signal:
                self.SLegend.AddEntry(st, st.GetTitle(), "l")

        return self.SLegend

    def GetRatioPlot(self):
        rationame = "%s_Ratio" % (self.Name)
        if not hasattr(self, "Ratio"):
            self.Ratio = self.Data.Clone(rationame)
            self.Ratio.SetStats(0)
            self.Ratio.Divide(self.GetStack().GetStack().Last())
            for i in range(1, self.Data.GetNbinsX() + 1):
                self.Ratio.GetXaxis().SetBinLabel(i, "")
            self.Ratio.SetMarkerStyle(20)
            self.Ratio.GetYaxis().SetRangeUser(0, 2)
            self.Ratio.GetXaxis().SetLabelSize(0.)
            self.Ratio.GetYaxis().SetTitle("Data / MC")
            self.Ratio.GetXaxis().SetTitleSize(0.2)
            self.Ratio.GetXaxis().SetTitleOffset(0.25)
            self.Ratio.GetYaxis().SetLabelSize(0.1)
            self.Ratio.GetXaxis().SetTickLength(0.09)
            self.Ratio.GetYaxis().SetTitleSize(0.18)
            self.Ratio.GetYaxis().SetNdivisions(509)
            self.Ratio.GetYaxis().SetTitleOffset(0.25)
            self.Ratio.SetFillStyle(3001)

        return self.Ratio

    def GetRatioUnc(self):
        rationame = "%s_RatioUncert" % (self.Name)
        if not hasattr(self, "RatioUncert"):
            mc = self.GetStack().GetStack().Last()
            self.RatioUncert = mc.Clone(rationame)
            self.RatioUncert.SetStats(0)
            self.RatioUncert.Divide(mc)
            for i in range(1, self.Data.GetNbinsX() + 1):
                self.RatioUncert.GetXaxis().SetBinLabel(i, "")
            #self.RatioUncert.SetMarkerStyle(20)
            self.RatioUncert.GetYaxis().SetRangeUser(0, 2)
            #self.RatioUncert.GetXaxis().SetLabelSize( 0.)
            self.RatioUncert.GetYaxis().SetTitle("Data / MC")
            self.RatioUncert.GetXaxis().SetTitleSize(0.2)
            self.RatioUncert.GetXaxis().SetTitleOffset(0.25)
            self.RatioUncert.GetYaxis().SetLabelSize(0.1)
            self.RatioUncert.GetXaxis().SetTickLength(0.09)
            self.RatioUncert.GetYaxis().SetTitleSize(0.18)
            self.RatioUncert.GetYaxis().SetNdivisions(509)
            self.RatioUncert.GetYaxis().SetTitleOffset(0.25)
            self.RatioUncert.SetFillStyle(3001)
            self.RatioUncert.SetFillColor(1)

        return self.RatioUncert

    def GetLineOne(self):
        linename = "%s_lineone" % (self.Name)
        if not hasattr(self, "LineOne"):
            self.LineOne = TLine(self.GetRatioPlot().GetXaxis().GetXmin(),
                                 1.00,
                                 self.GetRatioPlot().GetXaxis().GetXmax(),
                                 1.00)
            self.LineOne.SetLineWidth(2)
            self.LineOne.SetLineStyle(7)

        return self.LineOne

    def Draw(self, normalizetodata=False, padOrCanvas=0):
        gStyle.SetOptTitle(0)
        #self.AddOF_UF_Bins()
        self.GetCanvas(1, padOrCanvas)
        self.Data.Draw("E")
        #if normalizetodata:
        #    print "Norm to data"
        self.GetStack(normalizetodata).Draw("HIST SAME")
        self.Data.Draw("E SAME P")
        if self.Signal:
            for s in self.Signal:
                s.Draw("E SAME HIST")
            self.GetSLegend().Draw()
        self.GetLegend().Draw()

        self.GetCanvas(2)
        self.GetRatioUnc().Draw("E2")
        self.GetRatioPlot().Draw("ep same")
        self.GetLineOne().Draw()

    def Write(self, propdir, normtodata, mkdir=False):
        if mkdir:
            propdir = propdir.mkdir(self.Name)
        propdir.cd()
        catdir = propdir.mkdir("cats")
        catdir.cd()
        self.Data.Write()
        for bkg in self.Bkg:
            self.Bkg[bkg].Write()
        self.GetStack(normtodata).GetStack().Last().Write("SumMC")

        if self.Signal:
            sigdir = propdir.mkdir("signals")
            sigdir.cd()
            for i in range(0, len(self.Signal)):
                self.Signal[i].Write()

        sampledir = propdir.mkdir("samples")
        sampledir.cd()
        for ss in self.Samples:
            ss.Write()

        propdir.cd()
        self.Draw(normtodata)
        self.GetCanvas(0).Write()
def plot_ratio(ih_,max_val_,xbins__,comb_ID_):

#    // Define two gaussian histograms. Note the X and Y title are defined
#    // at booking time using the convention "Hist_title ; X_title ; Y_title"
#    TH1F *h1 = new TH1F("h1", "Two gaussian plots and their ratio;x title; h1 and h2 gaussian histograms", 100, -5, 5);
#    TH1F *h2 = new TH1F("h2", "h2", 100, -5, 5);
#    h1.FillRandom("gaus");
#    h2.FillRandom("gaus");

#    // Define the Canvas
    #TCanvas *c = new TCanvas("c", "canvas", 800, 800);

    cc = TCanvas("cc", "canvas", 800, 800)

    h1 = ih_[0][0]
    h2 = ih_[1][0]

    #print 'h1 = ',h1
    #print 'h2 = ',h2 

    #print'h1.GetMaximum() = ' ,h1.GetMaximum() 

    #// Upper plot will be in pad1
    pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0)
    pad1.SetBottomMargin(0) # Upper and lower plot are joined
    #pad1.SetGridx()         #Vertical grid, dashed lines 

    pad1.Draw()            #Draw the upper pad: pad1
    pad1.cd()               # pad1 becomes the current pad
    h1.SetStats(0)          # No statistics on upper plot
    h1.GetXaxis().SetNdivisions(xbins__)
    h1.Draw()               # Draw h1

    # pad1.Update()
    # lline = TLine(pad1.GetUxmin(),20,pad1.GetUxmax(),20)
    # #lline.SetNDC(1)
    # lline.SetLineStyle(3)
    # lline.Draw('same')

    h2.Draw("same")         # Draw h2 on top of h1

    #    // Do not draw the Y axis label on the upper plot and redraw a small
    #    // axis instead, in order to avoid the first label (0) to be clipped.
    h1.GetYaxis().SetLabelSize(0.)
    #TGaxis *axis = new TGaxis( -5, 20, -5, 220, 20,220,510,"");
    #axis = TGaxis( -5, 20, -5, 220, 20,220,510,"") #xmin ymin xmax ymax 
    axis = TGaxis( 0, 0, 0, max_val_, 0.001,max_val_,510,"")
    axis.SetLabelFont(43) #Absolute font size in pixel (precision 3)
    axis.SetLabelSize(15)
    axis.Draw()

    #lower plot will be in pad
    cc.cd()           # Go back to the main canvas before defining pad2
    #TPad *pad2 = new TPad("pad2", "pad2", 0, 0.05, 1, 0.3)
    pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3)
    pad2.SetTopMargin(0) # can change to separate top and bottom 
    #pad2.SetBottomMargin(0.2)
    #pad2.SetBottomMargin(0)
    #pad2.SetGridx() # vertical grid, dashed lines 
    
    pad2.Draw()
    pad2.cd()      # pad2 becomes the current pad

    # Define the ratio plot
    #TH1F *h3 = (TH1F*)h1.Clone("h3");
    h3 = h2.Clone("h3")
    h3.SetLineColor(1)
    h3.SetMinimum(0.5)  # Define Y ..
    h3.SetMaximum(1.5) # .. range
    h3.Sumw2()
    h3.SetStats(0)     # No statistics on lower plot
    h3.Divide(h1)
    h3.SetMarkerStyle(21)

    #gPad.Modified()
    #gPad.Update()

    h3.Draw("ep")     # Draw the ratio plot

    pad2.Update()
    lline = TLine(pad2.GetUxmin(),1,pad2.GetUxmax(),1)
    #lline.SetNDC(1)
    lline.SetLineStyle(1)
    lline.Draw('same')


    #// h1 settings
    h1.SetLineColor(600+1)
    h1.SetLineWidth(2)

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

    #print 'xbins__ = ',xbins__ 
    
    h1.GetXaxis().SetNdivisions(xbins__)
    #h1.GetXaxis().SetNdivisions(0)

    #// h2 settings
    h2.SetLineColor(632)
    h2.SetLineWidth(2)

   # // Ratio plot (h3) settings
    h3.SetTitle("") # Remove the ratio title

    #// Y axis ratio plot settings
    h3.GetYaxis().SetTitle("Reco/Gen")
    h3.GetYaxis().SetNdivisions(505)
    h3.GetYaxis().SetTitleSize(20)
    h3.GetYaxis().SetTitleFont(43)
    h3.GetYaxis().SetTitleOffset(1.55)
    h3.GetYaxis().SetLabelFont(43) #Absolute font size in pixel (precision 3)
    h3.GetYaxis().SetLabelSize(15)

  #  // X axis ratio plot settings
    #h3.GetXaxis().SetNdivisions(xbins__)
    h3.GetXaxis().SetNdivisions(xbins__)
    #h3.GetXaxis().SetNdivisions(0)
    h3.GetXaxis().SetTitleSize(20)
    h3.GetXaxis().SetTitleFont(43)
    h3.GetXaxis().SetTitleOffset(4.)
    h3.GetXaxis().SetLabelFont(43) # Absolute font size in pixel (precision 3)
    h3.GetXaxis().SetLabelSize(15)

    

    pad1.cd()

    leg_ = TLegend(0.6, 0.75, 0.89, 0.89)
    #for hi_,h_ in enumerate(hists_):
    a = ih_[:]
    #print'a = ',a
    #for i,hist_info_ in enumerate(a):
    for hist_info_ in a:
        this_h = hist_info_[0]
        this_label = hist_info_[1]
        
        leg_.AddEntry(this_h,this_label,'lf') # histo object, ID 
    #leg.SetTextSize(0.02)
    leg_.Draw('same')
    
    #cc.SaveAs(output_Loc + "Gen_Reco_" + comb_ID_ + ".png")
    cc.SaveAs(output_Loc + "Gen_Reco_" + comb_ID_ + ".pdf")
    cc.SaveAs(output_Loc + "Gen_Reco_" + comb_ID_ + ".png")

    return 0 
Beispiel #16
0
def draw(hist,
         var_type,
         log='',
         plotdir=None,
         plotname='foop',
         more_hists=None,
         write_csv=False,
         stats=None,
         bounds=None,
         errors=False,
         shift_overflows=False,
         csv_fname=None,
         scale_errors=None,
         rebin=None,
         plottitle='',
         colors=None,
         linestyles=None,
         cwidth=None,
         cheight=None,
         imagetype='svg',
         xtitle=None,
         ytitle=None,
         xline=None,
         yline=None,
         draw_str=None,
         normalize=False,
         normalization_bounds=None,
         linewidths=None,
         markersizes=None,
         no_labels=False,
         graphify=False,
         translegend=(0.0, 0.0)):
    assert os.path.exists(plotdir)
    if not has_root:
        return

    if normalization_bounds is not None:
        assert bounds is None
    if bounds is not None:
        assert normalization_bounds is None

    cvn = TCanvas('cvn-' + plotname, '', 700 if cwidth is None else cwidth,
                  600 if cheight is None else cheight)

    hists = [
        hist,
    ]
    if more_hists != None:
        hists = hists + more_hists

    xmin, xmax, ymax = None, None, None
    ih = 0
    for htmp in hists:
        if rebin is not None:
            htmp.Rebin(rebin)
        if scale_errors is not None:
            factor = float(
                scale_errors[0]) if len(scale_errors) == 1 else float(
                    scale_errors[ih])
            for ibin in range(htmp.GetNbinsX() + 2):
                htmp.SetBinError(ibin, htmp.GetBinError(ibin) * factor)

        if not normalize:
            assert normalization_bounds is None
            if bounds is not None:
                ibin_start = htmp.FindBin(bounds[0])
                ibin_end = htmp.FindBin(bounds[1])
                this_y_max = GetMaximumWithBounds(
                    htmp,
                    htmp.GetXaxis().GetBinLowEdge(ibin_start),
                    htmp.GetXaxis().GetBinUpEdge(ibin_end))
            else:
                this_y_max = htmp.GetMaximum()
        else:  # renormalize the hist within these bounds
            if normalization_bounds is None:
                factor = 1. / htmp.Integral() if htmp.Integral() > 0.0 else 0.0
                htmp.Scale(factor)
                this_y_max = htmp.GetMaximum()
            else:
                ibin_start = 0 if normalization_bounds[
                    0] is None else htmp.FindBin(normalization_bounds[0])
                ibin_end = htmp.GetNbinsX(
                ) if normalization_bounds[1] is None else htmp.FindBin(
                    normalization_bounds[1])
                factor = htmp.Integral(ibin_start, ibin_end) if htmp.Integral(
                    ibin_start, ibin_end
                ) > 0.0 else 0.0  # NOTE this is inclusive, i.e. includes <ibin_end>
                htmp.Scale(factor)
                this_y_max = GetMaximumWithBounds(
                    htmp,
                    htmp.GetXaxis().GetBinLowEdge(ibin_start),
                    htmp.GetXaxis().GetBinUpEdge(ibin_end))

        if ymax is None or this_y_max > ymax:
            ymax = this_y_max

        if xmin is None or htmp.GetBinLowEdge(1) < xmin:
            xmin = htmp.GetBinLowEdge(1)
        if xmax is None or htmp.GetXaxis().GetBinUpEdge(
                htmp.GetNbinsX()) > xmax:
            xmax = htmp.GetXaxis().GetBinUpEdge(htmp.GetNbinsX())

        ih += 1

    if bounds is not None:
        xmin, xmax = bounds
    hframe = TH1D('hframe', '', hist.GetNbinsX(), xmin, xmax)
    if not no_labels and (var_type == 'string' or var_type == 'bool'):
        for ib in range(1, hframe.GetNbinsX() + 1):
            hframe.GetXaxis().SetBinLabel(ib, hist.GetXaxis().GetBinLabel(ib))

    if 'y' in log:
        hframe.SetMaximum(3 * ymax)
    else:
        hframe.SetMaximum(1.2 * ymax)
    if var_type == 'bool':
        hframe.GetXaxis().SetLabelSize(0.1)

    if plottitle == '':
        plottitle = plotname

    if xtitle is None:
        xtitle = hist.GetXaxis().GetTitle()
    if ytitle is None:
        ytitle = hframe.GetYaxis().GetTitle()

    hframe.SetTitle(plottitle + ';' + xtitle + ';' + ytitle)
    # gStyle.SetTitleFontSize(.075)
    # gStyle.SetTitleY(gStyle.GetTitleY() + .0004)
    if cwidth is not None:
        gStyle.SetTitleOffset(0.99 * gStyle.GetTitleOffset('y'), 'y')
    # gStyle.SetTitleFillStyle(0)
    # hframe.SetTitleSize(gStyle.GetTitleSize())
    # hframe.SetTitleFont(gStyle.GetTitleFont())
    hframe.Draw('txt')

    if shift_overflows:
        for htmp in hists:
            if htmp == None:
                continue
            underflows, overflows = 0.0, 0.0
            first_shown_bin, last_shown_bin = -1, -1
            for ib in range(0, htmp.GetXaxis().GetNbins() + 2):
                if htmp.GetXaxis().GetBinCenter(ib) <= xmin:
                    underflows += htmp.GetBinContent(ib)
                    htmp.SetBinContent(ib, 0.0)
                elif first_shown_bin == -1:
                    first_shown_bin = ib
                else:
                    break
            for ib in reversed(range(0, htmp.GetXaxis().GetNbins() + 2)):
                if htmp.GetXaxis().GetBinCenter(ib) >= xmax:
                    overflows += htmp.GetBinContent(ib)
                    htmp.SetBinContent(ib, 0.0)
                elif last_shown_bin == -1:
                    last_shown_bin = ib
                else:
                    break

            if 'd_hamming' in plotname:
                print htmp.GetTitle()
                print '  underflow', underflows, htmp.GetBinContent(
                    first_shown_bin)
                print '  overflow', overflows, htmp.GetBinContent(
                    last_shown_bin)
                print '  first', htmp.GetXaxis().GetBinCenter(first_shown_bin)
                print '  last', htmp.GetXaxis().GetBinCenter(last_shown_bin)
            htmp.SetBinContent(
                first_shown_bin,
                underflows + htmp.GetBinContent(first_shown_bin))
            htmp.SetBinContent(last_shown_bin,
                               overflows + htmp.GetBinContent(last_shown_bin))

    if colors is None:
        assert len(hists) < 5
        colors = (kRed, kBlue - 4, kGreen + 2, kOrange + 1
                  )  # 632, 596, 418, 801
    else:
        assert len(hists) <= len(colors)
    if linestyles is None:
        # assert len(hists) < 5
        linestyles = [1 for _ in range(len(hists))]
    else:
        assert len(hists) <= len(linestyles)

    # legends
    x0, y0, x1, y1 = 0.57 + translegend[0], 0.66 + translegend[
        1], 0.99 + translegend[0], 0.88 + translegend[1]
    if len(hists) < 5:
        leg = TLegend(x0, y0, x1, y1)
    else:
        leg = TLegend(x0, y0 - 0.05, x1, y1)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)

    # draw
    if graphify:
        graphs = []
        for ih in range(len(hists)):
            n_bins = hists[ih].GetNbinsX()
            xvals, yvals, xerrs, yerrs = array(
                'f', [0 for i in range(n_bins)]), array(
                    'f', [0 for i in range(n_bins)]), array(
                        'f', [0 for i in range(n_bins)]), array(
                            'f', [0 for i in range(n_bins)])
            for ib in range(1, n_bins + 1):  # NOTE ignoring overflows
                xvals[ib - 1] = hists[ih].GetXaxis().GetBinCenter(ib)
                xerrs[ib - 1] = 0.0
                yvals[ib - 1] = hists[ih].GetBinContent(ib)
                yerrs[ib - 1] = hists[ih].GetBinError(ib) if errors else 0.0
            gr = TGraphErrors(n_bins, xvals, yvals, xerrs, yerrs)

            if markersizes is not None:
                imark = ih if len(markersizes) > 1 else 0
                gr.SetMarkerSize(markersizes[imark])
            gr.SetMarkerColor(colors[ih])
            if linewidths is None:
                if ih < 6:  # and len(hists) < 5:
                    gr.SetLineWidth(6 - ih)
            else:
                ilw = ih if len(linewidths) > 1 else 0
                gr.SetLineWidth(linewidths[ilw])
            gr.SetLineColor(colors[ih])
            # if int(linewidth) == 1:
            #     gr.SetLineColorAlpha(colors[ih], 0.4)
            gr.SetLineStyle(linestyles[ih])

            if draw_str is None:
                draw_str = 'lpz'
            if hists[ih].Integral() != 0.0:
                gr.Draw(draw_str + ' same')
                leg.AddEntry(gr, hists[ih].GetTitle(), 'pl')
            graphs.append(
                gr
            )  # yes, you really do have to do this to keep root from giving you only one graph
    else:
        if draw_str is None:
            draw_str = 'hist same'
        else:
            draw_str += ' same'
        if errors:
            draw_str += ' e'
        for ih in range(len(hists)):
            htmp = hists[ih]

            if stats is not None:
                if 'rms' in stats:
                    htmp.SetTitle(htmp.GetTitle() +
                                  (' (%.2f)' % htmp.GetRMS()))
                if 'mean' in stats:
                    htmp.SetTitle(htmp.GetTitle() +
                                  (' (%.2f)' % htmp.GetMean()))
                if '0-bin' in stats:
                    htmp.SetTitle(htmp.GetTitle() +
                                  (' (%.2f)' % htmp.GetBinContent(1)))

            htmp.SetLineColor(colors[ih])
            if markersizes is not None:
                imark = ih if len(markersizes) > 1 else 0
                htmp.SetMarkerSize(markersizes[imark])
            htmp.SetMarkerColor(colors[ih])
            htmp.SetLineStyle(linestyles[ih])
            if linewidths is None:
                if ih < 6:  # and len(hists) < 5:
                    htmp.SetLineWidth(6 - ih)
            else:
                ilw = ih if len(linewidths) > 1 else 0
                htmp.SetLineWidth(linewidths[ilw])

            leg.AddEntry(htmp, htmp.GetTitle(), 'l')
            htmp.Draw(draw_str)

    leg.Draw()

    if xline is not None:
        if xline <= hframe.GetXaxis().GetXmin() or xline >= hframe.GetXaxis(
        ).GetXmax():  # make sure we got valid a x position for the line
            print 'WARNING plotting x line at %f out of bounds (%f, %f)' % (
                float(xmin), hframe.GetXaxis().GetXmin(),
                hframe.GetXaxis().GetXmax())
        # xl = TLine(xline, hframe.GetYaxis().GetXmin(), xline, 0.5*ymax)
        xl = TLine(xline, -0.1 * ymax, xline, 0.5 * ymax)
        xl.SetLineStyle(2)
        xl.Draw()
    if yline is not None:
        if yline <= hframe.GetYaxis().GetXmin() or xline >= hframe.GetYaxis(
        ).GetXmax():  # make sure we got valid a x position for the line
            print 'WARNING plotting y line at %f out of bounds (%f, %f)' % (
                float(ymin), hframe.GetYaxis().GetXmin(),
                hframe.GetYaxis().GetXmax())
        yl = TLine(hframe.GetXaxis().GetXmin(), yline,
                   hframe.GetXaxis().GetXmax(), yline)
        yl.Draw()

    cvn.SetLogx('x' in log)
    cvn.SetLogy('y' in log)
    if not os.path.exists(plotdir + '/plots'):
        print 'ERROR dir \'' + plotdir + '/plots\' d.n.e.'
        assert False

    if write_csv:
        assert more_hists == None
        if csv_fname == None:
            write_hist_to_file(plotdir + '/plots/' + plotname + '.csv', hist)
        else:
            write_hist_to_file(csv_fname, hist)
    cvn.SaveAs(plotdir + '/plots/' + plotname + '.' + imagetype)
Beispiel #17
0
def plotter_flavours(eff_type):

    if eff_type == "real":
        hist_eff_type = "Real"
    elif eff_type == "fake":
        hist_eff_type = "Fake"

    basepath = "$HOME/PhD/ttH_MultiLeptons/RUN2/HTopMultilepAnalysisCode/trunk/HTopMultilepAnalysis/PlotUtils/"

    # ---------------------------
    # HTop Tag & Probe efficiency
    # ---------------------------

    file_TP_path = basepath + "blahblah"

    if args.closure:
        if "SLT" in args.trigger:
            file_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_HTopTP/OutputPlots_MMClosureRates_HTopTagProbe_NoCorr_SLT_SFmuSFel_25ns_v23/LeptonEfficiencies.root"
        elif "DLT" in args.trigger:
            #file_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_HTopTP/OutputPlots_MMClosureRates_HTopTagProbe_NoCorr_DLT_SFmuSFel_25ns_v23/LeptonEfficiencies.root"
            file_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_DLT_SFmuSFel_Pt_AMBISOLVING_25ns_v23/LeptonEfficiencies.root"

    print(
        "------------------------------------------------------------------------------------------"
    )
    print("HTop Tag & Probe efficiency - Opening file:\n{0}".format(
        file_TP_path))
    print(
        "------------------------------------------------------------------------------------------"
    )

    file_TP = TFile(file_TP_path)

    if args.closure:
        hist_TP = (file_TP.Get(hist_eff_type +
                               "_El_Pt_Efficiency_expectedbkg"),
                   file_TP.Get(hist_eff_type +
                               "_Mu_Pt_Efficiency_expectedbkg"))[bool(
                                   args.flavour == "mu")]
    else:
        hist_TP = (file_TP.Get(hist_eff_type +
                               "_El_Pt_Efficiency_observed_sub"),
                   file_TP.Get(hist_eff_type +
                               "_Mu_Pt_Efficiency_observed_sub"))[bool(
                                   args.flavour == "mu")]

    print("Reading histogram {0} from file {1}".format(hist_TP.GetName(),
                                                       file_TP_path))

    hist_TP.SetLineWidth(2)
    hist_TP.SetMarkerSize(1.0)

    hist_TP.GetXaxis().SetTitleOffset(1.0)
    hist_TP.GetYaxis().SetTitleOffset(1.0)

    lepton = ("e", "#mu")[bool(args.flavour == "mu")]

    hist_TP.GetXaxis().SetTitle("p_{T}^{" + lepton + "} [GeV]")
    hist_TP.GetYaxis().SetTitle("efficiency")

    hist_TP.GetYaxis().SetRangeUser(0.0, 1.0)

    hist_TP.SetLineColor(kRed)
    hist_TP.SetMarkerColor(kRed)

    #c = TCanvas("c1","Temp",50,50,1000,900)
    c = TCanvas("c1", "Temp", 50, 50, 1300, 800)

    legend = TLegend(
        0.45, 0.5, 0.925, 0.8
    )  # (x1,y1 (--> bottom left corner), x2, y2 (--> top right corner) )
    legend.SetHeader("#epsilon_{" + eff_type + "}")
    legend.SetBorderSize(0)  # no border
    legend.SetFillStyle(0)  # Legend transparent background
    legend.SetTextSize(0.04)  # Increase entry font size!
    legend.SetTextFont(42)  # Helvetica
    leg_ATLAS = TLatex()
    leg_lumi = TLatex()
    leg_ATLAS.SetTextSize(0.03)
    leg_ATLAS.SetNDC()
    leg_lumi.SetTextSize(0.03)
    leg_lumi.SetNDC()

    #hist_TP.Draw("E0")
    #legend.AddEntry(hist_TP, "HTop Tag & Probe (ICHEP)", "P")

    # ---------------------------
    # New Tag & Probe efficiency
    # ---------------------------

    file_SUSY_TP_path = basepath + "blahblah"

    if args.closure:
        if "SLT" in args.trigger:
            #file_SUSY_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_SFmuSFel_Pt_AMBISOLVING_25ns_v23/LeptonEfficiencies.root"
            #file_SUSY_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_OFmuOFel_Pt_AMBISOLVING_25ns_v23/LeptonEfficiencies.root"
            #file_SUSY_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_SFmuSFel_massClosestBJet_AMBISOLVING_25ns_v23/LeptonEfficiencies.root"
            #file_SUSY_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_SFmuSFel_deltaRClosestBJet_AMBISOLVING_25ns_v23/LeptonEfficiencies.root"
            #file_SUSY_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_OF_AMBISOLVING_25ns_v23/LeptonEfficiencies.root"
            #file_SUSY_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_OF_AMBISOLVING_25ns_v23_OLD_EL_BINNING/LeptonEfficiencies.root"
            #
            #file_SUSY_TP_path = basepath + "PLOTS_25ns_v24/MMClosure_v24_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_OF_AMBISOLVING_25ns_v24/LeptonEfficiencies.root"
            #file_SUSY_TP_path = basepath + "PLOTS_25ns_v24/MMClosure_v24_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_OF_AMBISOLVING_25ns_v24_ForceProbeToBeFake/LeptonEfficiencies.root"
            #file_SUSY_TP_path = basepath + "PLOTS_25ns_v24/MMClosure_v24_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_OF_AMBISOLVING_25ns_v24_TightTagIso/LeptonEfficiencies.root"
            #file_SUSY_TP_path = basepath + "PLOTS_25ns_v24/MMClosure_v24_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_OF_AMBISOLVING_25ns_v24_TightTagIsoTagPt30/LeptonEfficiencies.root"
            file_SUSY_TP_path = basepath + "PLOTS_25ns_v24/MMClosure_v24_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_OF_AMBISOLVING_25ns_v24_TightTagIsoTagPt30_ForceProbeToBeFake/LeptonEfficiencies.root"
        elif "DLT" in args.trigger:
            #file_SUSY_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_DLT_SFmuSFel_Pt_AMBISOLVING_25ns_v23/LeptonEfficiencies.root"
            #file_SUSY_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_DLT_SFmuSFel_massClosestBJet_AMBISOLVING_25ns_v23/LeptonEfficiencies.root"
            file_SUSY_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_SUSYTP/OutputPlots_MMClosureRates_SUSYTagProbe_NoCorr_DLT_SFmuSFel_deltaRClosestBJet_AMBISOLVING_25ns_v23/LeptonEfficiencies.root"

    print(
        "------------------------------------------------------------------------------------------"
    )
    print("New Tag & Probe efficiency - Opening file:\n{0}".format(
        file_SUSY_TP_path))
    print(
        "------------------------------------------------------------------------------------------"
    )

    file_SUSY_TP = TFile(file_SUSY_TP_path)

    if args.closure:
        hist_SUSY_TP = (
            file_SUSY_TP.Get(hist_eff_type + "_El_Pt_Efficiency_expectedbkg"),
            file_SUSY_TP.Get(hist_eff_type +
                             "_Mu_Pt_Efficiency_expectedbkg"))[bool(
                                 args.flavour == "mu")]
    else:
        hist_SUSY_TP = (
            file_SUSY_TP.Get(hist_eff_type + "_El_Pt_Efficiency_observed_sub"),
            file_SUSY_TP.Get(hist_eff_type +
                             "_Mu_Pt_Efficiency_observed_sub"))[bool(
                                 args.flavour == "mu")]

    print("Reading histogram {0} from file {1}".format(hist_SUSY_TP.GetName(),
                                                       file_SUSY_TP_path))

    hist_SUSY_TP.SetLineColor(kMagenta)
    hist_SUSY_TP.SetMarkerColor(kMagenta)

    hist_SUSY_TP.GetXaxis().SetTitle("p_{T}^{" + lepton + "} [GeV]")
    hist_SUSY_TP.GetYaxis().SetTitle("#varepsilon")

    if eff_type == "real":
        hist_SUSY_TP.GetYaxis().SetRangeUser(0.5, 1.0)
    elif eff_type == "fake":
        if args.flavour == "el":
            hist_SUSY_TP.GetYaxis().SetRangeUser(0.0, 0.7)
        if args.flavour == "mu":
            hist_SUSY_TP.GetYaxis().SetRangeUser(0.0, 0.5)

    hist_SUSY_TP.Draw("E0")
    legend.AddEntry(hist_SUSY_TP, "Tag & Probe", "P")

    # ----------------------------
    # TRUTH Tag & Probe efficiency
    # ----------------------------

    file_TRUTH_TP_path = basepath + "blahblah"

    if args.closure:
        if "SLT" in args.trigger:
            #file_TRUTH_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_TruthTP/OutputPlots_MMClosureRates_TruthTagProbe_NoCorr_SLT_SFmuSFel_25ns_v23/LeptonEfficiencies.root"
            #file_TRUTH_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_TruthTP/OutputPlots_MMClosureRates_TruthTagProbe_NoCorr_SLT_OFmuOFel_25ns_v23/LeptonEfficiencies.root"
            #file_TRUTH_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_TruthTP/OutputPlots_MMClosureRates_TruthTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_25ns_v23/LeptonEfficiencies.root"
            #file_TRUTH_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_TruthTP/OutputPlots_MMClosureRates_TruthTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_25ns_v23_OLD_EL_BINNING/LeptonEfficiencies.root"
            #
            file_TRUTH_TP_path = basepath + "PLOTS_25ns_v24/MMClosure_v24_TruthTP/OutputPlots_MMClosureRates_TruthTagProbe_NoCorr_SLT_RealOFmuOFel_FakeSFmuOFel_25ns_v24/LeptonEfficiencies.root"
        elif "DLT" in args.trigger:
            file_TRUTH_TP_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_TruthTP/OutputPlots_MMClosureRates_TruthTagProbe_NoCorr_DLT_SFmuSFel_25ns_v23/LeptonEfficiencies.root"

    print(
        "------------------------------------------------------------------------------------------"
    )
    print("TRUTH Tag & Probe efficiency - Opening file:\n{0}".format(
        file_TRUTH_TP_path))
    print(
        "------------------------------------------------------------------------------------------"
    )

    file_TRUTH_TP = TFile(file_TRUTH_TP_path)

    if args.closure:
        hist_TRUTH_TP = (
            file_TRUTH_TP.Get(hist_eff_type + "_El_Pt_Efficiency_expectedbkg"),
            file_TRUTH_TP.Get(hist_eff_type +
                              "_Mu_Pt_Efficiency_expectedbkg"))[bool(
                                  args.flavour == "mu")]
    else:
        hist_TRUTH_TP = (
            file_TRUTH_TP.Get(hist_eff_type +
                              "_El_Pt_Efficiency_observed_sub"),
            file_TRUTH_TP.Get(hist_eff_type +
                              "_Mu_Pt_Efficiency_observed_sub"))[bool(
                                  args.flavour == "mu")]

    print("Reading histogram {0} from file {1}".format(hist_TRUTH_TP.GetName(),
                                                       file_TRUTH_TP_path))

    hist_TRUTH_TP.SetLineWidth(2)
    hist_TRUTH_TP.SetLineColor(kBlack)
    hist_TRUTH_TP.SetLineStyle(2)
    hist_TRUTH_TP.SetMarkerSize(1.0)
    hist_TRUTH_TP.SetMarkerColor(kBlack)
    hist_TRUTH_TP.SetMarkerStyle(24)

    hist_TRUTH_TP.Draw("E0 SAME")
    legend.AddEntry(hist_TRUTH_TP, "Truth", "P")

    # ---------------------
    # Likelihood efficiency
    # ---------------------

    #"""
    LH_init_path = basepath + "blahblah"

    if args.closure:
        if "SLT" in args.trigger:
            #LH_init_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_LikelihoodFit/OutputPlots_MMClosureRates_LHFit_NoCorr_SFmuSFel_SLT_25ns_v21/LeptonEfficiencies_LH/"
            #LH_init_path = basepath + "PLOTS_25ns_v24/MMClosure_v24_LikelihoodFit/OutputPlots_MMClosureRates_LHFit_NoCorr_INCLUSIVE_FLAV_SLT_25ns_v24/LeptonEfficiencies_LH/"
            LH_init_path = basepath + "PLOTS_25ns_v24/MMClosure_v24_LikelihoodFit/OutputPlots_MMClosureRates_LHFit_NoCorr_INCLUSIVE_FLAV_DLT_25ns_v24/LeptonEfficiencies_LH/"
        elif "DLT" in args.trigger:
            LH_init_path = basepath + "PLOTS_25ns_v23/MMClosure_v23_LikelihoodFit/OutputPlots_MMClosureRates_LHFit_NoCorr_SFmuSFel_DLT_25ns_v21/LeptonEfficiencies_LH/"

    hist_LH_list = []

    if eff_type == "real":
        flav_comp_list = args.flavRealCR
    elif eff_type == "fake":
        flav_comp_list = args.flavFakeCR

    if (args.flavour == "mu" and "elel" in flav_comp_list):
        flav_comp_list.remove("elel")
    if (args.flavour == "el" and "mumu" in flav_comp_list):
        flav_comp_list.remove("mumu")

    for idx, flavcomp in enumerate(flav_comp_list, start=0):

        file_LH_path = LH_init_path + "LH_" + flavcomp + "/LH_efficiencies_" + eff_type + "_" + args.flavour + "_" + flavcomp + ".root"

        print(
            "\t------------------------------------------------------------------------------------------"
        )
        print("\tLikelihood efficiency - Opening file:\n{0}".format(
            file_LH_path))
        print(
            "\t------------------------------------------------------------------------------------------"
        )

        file_LH = TFile(file_LH_path)

        if eff_type == "real":
            hist_LH_name = "r_hist"
        elif eff_type == "fake":
            hist_LH_name = "f_hist"

        hist_LH = file_LH.Get(hist_LH_name)

        print("Reading histogram {0} from file {1} - index : {2}".format(
            hist_LH.GetName(), file_LH_path, idx))

        # A dirty hack to make multiple plots superimposed with a small offset

        offsets = []
        for ibin in range(0, hist_LH.GetNbinsX() + 1):
            offset = (idx + 1) * 0.15 * hist_LH.GetBinWidth(ibin)
            # hardcoded...so ugly, any better ideas?
            if ibin == 4:
                offset = (idx + 1) * 0.05 * hist_LH.GetBinWidth(ibin)
            if ibin == 5:
                offset = (idx + 1) * 0.01 * hist_LH.GetBinWidth(ibin)
            offsets.append(offset)

        print("offsets per bin: {0}".format(offsets))

        binlist = []
        for ibin in range(0, hist_LH.GetNbinsX() + 1):
            binlist.append(hist_LH.GetXaxis().GetBinUpEdge(ibin) +
                           offsets[ibin])

        print("shifted bins: {0}".format(binlist))

        binlist_arr = array.array("d", binlist)

        shiftedhist = TH1D(hist_LH.GetName() + "_shift", hist_LH.GetTitle(),
                           len(binlist) - 1, binlist_arr)

        for ibin in range(1, hist_LH.GetNbinsX() + 1):
            shiftedhist.SetBinContent(ibin, hist_LH.GetBinContent(ibin))
            shiftedhist.SetBinError(ibin, hist_LH.GetBinError(ibin))

        shiftedhist.SetLineWidth(2)
        shiftedhist.SetMarkerSize(1.0)

        lepton = ("e", "#mu")[bool(args.flavour == "mu")]
        shiftedhist.GetXaxis().SetTitle("p_{T}^{" + lepton + "} [GeV]")
        shiftedhist.GetYaxis().SetTitle("efficiency")

        shiftedhist.GetXaxis().SetTitleOffset(1.0)
        shiftedhist.GetYaxis().SetTitleOffset(1.0)

        shiftedhist.GetYaxis().SetRangeUser(0.0, 1.0)

        if idx == 0:
            shiftedhist.SetLineColor(kBlue)
            shiftedhist.SetMarkerColor(kBlue)
        elif idx == 1:
            shiftedhist.SetLineColor(kBlue + 3)
            shiftedhist.SetMarkerColor(kBlue + 3)
        elif idx == 2:
            shiftedhist.SetLineColor(kAzure + 1)
            shiftedhist.SetMarkerColor(kAzure + 1)
        elif idx == 3:
            shiftedhist.SetLineColor(kCyan)
            shiftedhist.SetMarkerColor(kCyan)

        shiftedhist.SetDirectory(0)

        pair = (flavcomp, shiftedhist)
        hist_LH_list.append(pair)

    #gPad.SetLogx()
    #hist_TP.GetXaxis().SetMoreLogLabels()

    for idx, histpair in enumerate(hist_LH_list, start=0):
        #histpair[1].GetXaxis().SetMoreLogLabels()
        #if idx == 0:
        #  histpair[1].Draw("E0")
        #else:
        #  histpair[1].Draw("E0,SAME")

        # TEMP: plot LH efficiency only for fake muon
        if not (eff_type == "fake" and args.flavour == "mu"): continue

        histpair[1].Draw("E0,SAME")

        if histpair[0] == "mumu": flag = "#mu#mu"
        else: flag = histpair[0]

        legend.AddEntry(histpair[1], "Likelihood - " + flag, "P")

    #"""

    legend.Draw()

    leg_ATLAS.DrawLatex(0.6, 0.35, "#bf{#it{ATLAS}} Work In Progress")
    leg_lumi.DrawLatex(
        0.6, 0.27,
        "#sqrt{{s}} = 13 TeV, #int L dt = {0:.1f} fb^{{-1}}".format(args.lumi))

    # Add a vertical line to highlight relevant bins

    if eff_type == "real":
        low_y_edge = 0.5
        up_y_edge = 1.0
    elif eff_type == "fake":
        low_y_edge = 0.0
        if args.flavour == "el":
            up_y_edge = 0.7
        elif args.flavour == "mu":
            up_y_edge = 0.5

    if "SLT" in args.trigger:

        if args.flavour == "el":

            refl_vert0 = TLine(26.0, 0, 26.0, up_y_edge)
            refl_vert0.SetLineStyle(2)
            refl_vert0.SetLineWidth(2)
            refl_vert0.Draw("SAME")

            refl_vert1 = TLine(60.0, low_y_edge, 60.0, up_y_edge)
            refl_vert1.SetLineStyle(2)
            refl_vert1.SetLineWidth(2)
            refl_vert1.Draw("SAME")

            refl_vert2 = TLine(140.0, low_y_edge, 140.0, up_y_edge)
            refl_vert2.SetLineStyle(2)
            refl_vert2.SetLineWidth(2)
            refl_vert2.Draw("SAME")

        elif args.flavour == "mu":

            refl_vert0 = TLine(26.0, low_y_edge, 26.0, up_y_edge)
            refl_vert0.SetLineStyle(2)
            refl_vert0.SetLineWidth(2)
            refl_vert0.Draw("SAME")

            refl_vert1 = TLine(50.0, low_y_edge, 50.0, up_y_edge)
            refl_vert1.SetLineStyle(2)
            refl_vert1.SetLineWidth(2)
            refl_vert1.Draw("SAME")

    elif "DLT" in args.trigger:

        if args.flavour == "el":

            refl_vert0 = TLine(17.0, low_y_edge, 17.0, up_y_edge)
            refl_vert0.SetLineStyle(2)
            refl_vert0.SetLineWidth(2)
            refl_vert0.Draw("SAME")

        elif args.flavour == "mu":

            refl_vert0 = TLine(22.0, low_y_edge, 22.0, up_y_edge)
            refl_vert0.SetLineStyle(2)
            refl_vert0.SetLineWidth(2)
            refl_vert0.Draw("SAME")

    canvasname = (eff_type + "_eff_el_TP_LH",
                  eff_type + "_eff_mu_TP_LH")[bool(args.flavour == "mu")]
    c.SaveAs(canvasname + "_" + args.trigger[0] + ".png")
def drawHistsWithRatio(hists, name, **kwargs):
    """Draw histograms with ratios."""

    title = kwargs.get('title', "")
    xtitle = kwargs.get('xtitle', "")
    ytitle = kwargs.get('ytitle', "")
    rtitle = kwargs.get('rtitle', "Ratio")
    xmin = kwargs.get('xmin', hists[0].GetXaxis().GetXmin())
    xmax = kwargs.get('xmax', hists[0].GetXaxis().GetXmax())
    ymin = kwargs.get('ymin', None)
    ymax = kwargs.get('ymax', None)
    rmin = kwargs.get('rmin', 0.45)
    rmax = kwargs.get('rmax', 1.55)
    logx = kwargs.get('logx', False)
    logy = kwargs.get('logy', False)
    denom = kwargs.get('denom', 1) - 1  # denominator for ratio
    textsize = kwargs.get('textsize', 0.045)
    texts = kwargs.get('text', [])
    width = kwargs.get('width', 0.26)
    #textheight = kwargs.get('textheight',   1.09                 )
    #ctext      = kwargs.get('ctext',        [ ]                  ) # corner text
    #cposition  = kwargs.get('cposition',    'topleft'            ).lower() # cornertext
    #ctextsize  = kwargs.get('ctextsize',    1.4*legendtextsize   )
    colors = kwargs.get('colors', linecolors)
    if not isinstance(texts, list) or isinstance(texts, tuple):
        texts = [texts]
    if ymax == None:
        ymax = 1.12 * max(h.GetMaximum() for h in hists)

    # MAIN plot
    canvas = TCanvas('canvas', 'canvas', 100, 100, 800, 800)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetFrameBorderMode(0)
    canvas.Divide(2)
    canvas.SetMargin(0.0, 0.0, 0.0, 0.0)
    canvas.cd(1)
    gPad.SetPad('pad1', 'pad1', 0, 0.33, 1, 1)
    gPad.SetMargin(0.12, 0.04, 0.02, 0.08)
    gPad.SetFillColor(0)
    gPad.SetBorderMode(0)
    gPad.SetTickx(0)
    gPad.SetTicky(0)
    gPad.SetGrid()
    gPad.Draw()
    canvas.cd(2)
    gPad.SetPad('pad2', 'pad2', 0, 0, 1, 0.33)
    gPad.SetMargin(0.12, 0.04, 0.30, 0.03)
    gPad.SetFillColor(0)
    gPad.SetFillStyle(4000)
    gPad.SetFrameFillStyle(0)
    gPad.SetBorderMode(0)
    gPad.Draw()

    # MAIN plot
    canvas.cd(1)
    for i, hist in enumerate(hists):
        color = colors[i % len(colors)]
        hist.SetLineColor(color)
        hist.SetLineWidth(2)
        hist.Draw('HIST SAME')
    frame = hists[0]
    frame.GetYaxis().SetTitleSize(0.060)
    frame.GetXaxis().SetTitleSize(0)
    frame.GetXaxis().SetLabelSize(0)
    frame.GetYaxis().SetLabelSize(0.052)
    frame.GetXaxis().SetLabelOffset(0.010)
    frame.GetXaxis().SetTitleOffset(0.98)
    frame.GetYaxis().SetTitleOffset(1.05)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().SetTitle(ytitle)
    frame.GetXaxis().SetTitle(xtitle)
    if logx:
        gPad.Update()
        gPad.SetLogx()
    if logy:
        gPad.Update()
        gPad.SetLogy()
    if ymin: frame.SetMinimum(ymin)
    if ymax: frame.SetMaximum(ymax)

    height = 1.1 * textsize * len([l for l in texts + hists if l])
    x1, y1 = 0.90, 0.88
    x2, y2 = x1 - width, y1 - height
    legend = TLegend(x1, y1, x2, y2)
    legend.SetTextSize(textsize)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    legend.SetFillColor(0)
    legend.SetMargin(0.05 / width)
    if title:
        legend.SetTextFont(62)
        legend.SetHeader(title)
    legend.SetTextFont(42)
    for hist in hists:
        legend.AddEntry(hist, hist.GetTitle(), 'l')
    for text in texts:
        legend.AddEntry(0, text, '')
    legend.Draw()

    gPad.SetTicks(1, 1)
    gPad.Modified()
    frame.Draw('AXIS SAME')
    CMS_style.CMS_lumi(gPad, 13, 0)

    # RATIO plot
    canvas.cd(2)
    ratios = []
    for i, hist in enumerate(hists):
        if i == denom: continue
        ratio = hist.Clone(hist.GetName() + "_ratio")
        ratio.Divide(hists[denom])
        for ibin in xrange(1, hist.GetXaxis().GetNbins() + 1):
            if hists[denom].GetBinContent(ibin) == 0:
                if hist.GetBinContent(ibin) == 0:
                    ratio.SetBinContent(ibin, 1)
                else:
                    ratio.SetBinContent(ibin, rmax + 1e5)
        ratio.Draw('HIST SAME')
        ratios.append(ratio)
    frame_ratio = ratios[0]
    frame_ratio.GetYaxis().SetRangeUser(rmin, rmax)
    frame_ratio.GetYaxis().CenterTitle()
    frame_ratio.GetYaxis().SetTitleSize(0.13)
    frame_ratio.GetXaxis().SetTitleSize(0.13)
    frame_ratio.GetXaxis().SetLabelSize(0.12)
    frame_ratio.GetYaxis().SetLabelSize(0.11)
    frame_ratio.GetXaxis().SetLabelOffset(0.012)
    frame_ratio.GetXaxis().SetTitleOffset(1.02)
    frame_ratio.GetYaxis().SetTitleOffset(0.48)
    frame_ratio.GetXaxis().SetNdivisions(508)
    frame_ratio.GetYaxis().CenterTitle(True)
    frame_ratio.GetYaxis().SetTitle(rtitle)
    frame_ratio.GetXaxis().SetTitle(xtitle)
    frame_ratio.GetYaxis().SetNdivisions(505)
    if logx:
        gPad.Update()
        gPad.SetLogx()
    line = TLine(xmin, 1., xmax, 1.)
    line.SetLineColor(hists[denom].GetLineColor())
    line.SetLineWidth(hists[denom].GetLineWidth())
    line.SetLineStyle(1)
    line.Draw('SAME')
    gPad.SetTicks(1, 1)
    gPad.Update()
    gPad.SetGrid()
    gPad.Modified()
    frame_ratio.Draw('SAME AXIS')

    canvas.SaveAs(name + ".png")
    canvas.SaveAs(name + ".pdf")
    canvas.Close()
Beispiel #19
0
    def plot(self, **kw):

        from ROOT import kRed
        dirname = retrieve_kw(kw, 'dirname', 'Distribution')
        basecolor = retrieve_kw(kw, 'basecolor', kRed - 7)
        pdftitle = retrieve_kw(kw, 'pdftitle', 'Distributions')
        pdfoutput = retrieve_kw(kw, 'pdfoutput', 'distributions')

        import os
        # Organize outputs (.py and .pdf)
        prefix = self._basepath.split('/')[-1]
        localpath = os.getcwd() + '/' + dirname + '/' + prefix

        try:
            if not os.path.exists(localpath):
                os.makedirs(localpath)
        except:
            self._logger.warning('The director %s exist.', localpath)

        hist_names = [
            'et', 'eta', 'mu', 'nvtx', 'reta', 'eratio', 'weta2', 'rhad',
            'rphi', 'f1', 'f3'
        ]
        hist_labels = [
            'E_{T}', "#eta", "<#mu>", 'N_{vtx}', 'R_{eta}', 'E_{ratio}',
            'W_{eta2}', 'R_{had}', 'R_{phi}', 'f_{1}', 'f_{3}'
        ]

        from ROOT import TCanvas, TH1F, gStyle, TLegend, TPad
        from ROOT import kGreen, kRed, kBlue, kBlack, kGray, gPad, kAzure
        from TrigEgammaDevelopments.plots.AtlasStyle import AtlasStyle, atlas_template, setLegend1

        canvas1 = TCanvas('canvas1', 'canvas1', 2500, 1600)
        canvas1.Divide(4, 3)

        # Concatenate distributions for all regions
        def sumAllRegions(histname):
            h = None
            for etBinIdx in range(len(self._etBins) - 1):
                for etaBinIdx in range(len(self._etaBins) - 1):
                    binningname = ('et%d_eta%d') % (etBinIdx, etaBinIdx)
                    path = self._basepath + '/' + self.currentDir(
                    ) + '/' + binningname
                    if h:
                        h += self.storeSvc().histogram(path + '/' + histname)
                    else:
                        h = self.storeSvc().histogram(path + '/' +
                                                      histname).Clone()
            return h

        collector = []
        figures = {
            'rings': [],
            'rnnOutput': [],
            'ringer_profile': str(),
            'shower_shapes': str()
        }
        """
      Plot all shower shapes distributins
    """
        for idx, histname in enumerate(hist_names):
            self.setDir('Data')
            h_data = sumAllRegions(histname)
            self.setDir('MonteCarlo')
            h_mc = sumAllRegions(histname)
            #h_mc, h_data =  self.__scale_histograms(h_mc, h_data, 100, 0.01, 0.01)

            pad = canvas1.cd(idx + 1)
            gStyle.SetOptStat(110011)
            collector.append(pad)

            h_mc.SetFillColor(basecolor)
            h_mc.SetLineColor(basecolor)
            h_data.SetLineColor(kBlack)
            h_mc.Scale(1. / h_mc.GetMaximum())
            h_data.Scale(1. / h_data.GetMaximum())
            h_mc.Draw()
            h_data.Draw('same')
            leg1 = TLegend(0.2, 0.75, 0.5, 0.95)
            setLegend1(leg1)
            leg1.AddEntry(h_mc, 'MC')
            leg1.AddEntry(h_data, 'Data')
            leg1.Draw()
            collector[-1].Update()
            collector.append(h_mc)
            collector.append(h_data)
            collector.append(leg1)

        canvas1.SaveAs(localpath + '/shower_shapes_distributions.pdf')
        figures[
            'shower_shapes'] = localpath + '/shower_shapes_distributions.pdf'
        """
      Plot all shower ringer shapes for each ring
    """
        ratio_size_as_fraction = 0.35
        from RingerCore import progressbar

        rings_localpath = []

        for r in progressbar(range(100),
                             100,
                             step=1,
                             logger=self._logger,
                             prefix="Looping over rings (Plotting...) "):
            canvas2 = TCanvas('canvas2', 'canvas2', 2500, 1600)
            drawopt = 'pE1'
            canvas2.cd()
            top = TPad("pad_top", "This is the top pad", 0.0,
                       ratio_size_as_fraction, 1.0, 1.0)
            top.SetBottomMargin(0.0)
            top.SetBottomMargin(0.06 / float(top.GetHNDC()))
            #top.SetTopMargin   (0.04/float(top.GetHNDC()))
            top.SetRightMargin(0.05)
            top.SetLeftMargin(0.16)
            top.SetFillColor(0)
            top.Draw(drawopt)

            canvas2.cd()
            bot = TPad("pad_bot", "This is the bottom pad", 0.0, 0.0, 1.0,
                       ratio_size_as_fraction)
            bot.SetBottomMargin(0.10 / float(bot.GetHNDC()))
            #bot.SetTopMargin   (0.02/float(bot.GetHNDC()))
            bot.SetTopMargin(0.0)
            bot.SetRightMargin(0.05)
            bot.SetLeftMargin(0.16)
            bot.SetFillColor(0)
            bot.Draw(drawopt)

            self.setDir('MonteCarlo')
            h_mc = sumAllRegions('rings/ring_' + str(r))
            self.setDir('Data')
            h_data = sumAllRegions('rings/ring_' + str(r))
            gStyle.SetOptStat(000000)

            h_mc, h_data = self.__scale_histograms(h_mc, h_data, 100, 0.0001,
                                                   0.025)
            h_mc.Scale(1. / h_mc.GetMaximum())
            h_data.Scale(1. / h_data.GetMaximum())

            from ROOT import TH1, kGray
            divide = ""
            drawopt = 'pE1'
            bot.cd()
            ref = h_mc.Clone()
            h = h_data.Clone()

            ref.Sumw2()
            h.Sumw2()
            ratioplot = h.Clone()
            ratioplot.Sumw2()
            ratioplot.SetName(h.GetName() + '_ratio')
            ratioplot.Divide(h, ref, 1., 1., '')
            ratioplot.SetFillColor(0)
            ratioplot.SetFillStyle(0)
            ratioplot.SetMarkerColor(1)
            ratioplot.SetLineColor(kGray)
            ratioplot.SetMarkerStyle(24)
            ratioplot.SetMarkerSize(1.2)
            ratioplot.GetYaxis().SetTitleSize(0.10)
            ratioplot.GetXaxis().SetTitleSize(0.10)
            ratioplot.GetXaxis().SetLabelSize(0.10)
            ratioplot.GetYaxis().SetLabelSize(0.10)
            ratioplot.GetYaxis().SetRangeUser(-1.6, 3.7)
            ratioplot.GetYaxis().SetTitleOffset(0.7)
            ratioplot.GetYaxis().SetTitle('Data/MC')
            ratioplot.GetXaxis().SetTitle('Ring #' + str(r + 1) + ' [MeV]')
            ratioplot.Draw(drawopt)
            from ROOT import TLine

            nbins = h_data.GetNbinsX()
            xmin = h_data.GetXaxis().GetBinLowEdge(1)
            xmax = h_data.GetXaxis().GetBinLowEdge(nbins + 1)
            l1 = TLine(xmin, 1, xmax, 1)
            l1.SetLineColor(kRed)
            l1.SetLineStyle(2)
            l1.Draw()
            bot.Update()

            top.cd()

            h_mc.SetFillColor(basecolor)
            h_mc.SetLineWidth(1)
            h_mc.SetLineColor(basecolor)
            h_data.SetLineColor(kBlack)
            h_data.SetLineWidth(1)
            h_mc.GetYaxis().SetTitle('Count')
            h_mc.Draw()
            h_data.Draw('same')

            leg1 = TLegend(0.8, 0.70, 0.95, 0.95)
            setLegend1(leg1)
            leg1.AddEntry(h_mc, 'MC')
            leg1.AddEntry(h_data, 'Data')
            leg1.Draw()
            atlas_template(top)
            top.Update()
            canvas2.SaveAs(localpath + '/distribution_ring_' + str(r + 1) +
                           '.pdf')
            figures['rings'].append(localpath + '/distribution_ring_' +
                                    str(r + 1) + '.pdf')
        """
      Plot ringer mean shapes
    """
        h_mean_data = TH1F('h_mean_data', '', 100, 0, 100)
        h_mean_mc = TH1F('h_mean_mc', '', 100, 0, 100)

        for bin in range(100):
            self.setDir('MonteCarlo')
            h_mc = sumAllRegions('rings/ring_' + str(bin))
            self.setDir('Data')
            h_data = sumAllRegions('rings/ring_' + str(bin))
            h_mean_data.SetBinContent(bin + 1, h_data.GetMean())
            h_mean_mc.SetBinContent(bin + 1, h_mc.GetMean())
        canvas3 = TCanvas('canvas3', 'canvas3', 2500, 1600)

        drawopt = 'pE1'
        canvas3.cd()
        top = TPad("pad_top", "This is the top pad", 0.0,
                   ratio_size_as_fraction, 1.0, 1.0)
        top.SetBottomMargin(0.0)
        top.SetBottomMargin(0.06 / float(top.GetHNDC()))
        #top.SetTopMargin   (0.04/float(top.GetHNDC()))
        top.SetRightMargin(0.05)
        top.SetLeftMargin(0.16)
        top.SetFillColor(0)
        top.Draw(drawopt)

        canvas3.cd()
        bot = TPad("pad_bot", "This is the bottom pad", 0.0, 0.0, 1.0,
                   ratio_size_as_fraction)
        bot.SetBottomMargin(0.10 / float(bot.GetHNDC()))
        #bot.SetTopMargin   (0.02/float(bot.GetHNDC()))
        bot.SetTopMargin(0.0)
        bot.SetRightMargin(0.05)
        bot.SetLeftMargin(0.16)
        bot.SetFillColor(0)
        bot.Draw(drawopt)

        gStyle.SetOptStat(000000)
        from ROOT import TH1, kGray
        divide = ""
        drawopt = 'pE1'
        bot.cd()
        ref = h_mean_mc.Clone()
        h = h_mean_data.Clone()
        ref.Sumw2()
        h.Sumw2()
        ratioplot = h.Clone()
        ratioplot.Sumw2()
        ratioplot.SetName(h.GetName() + '_ratio')
        ratioplot.Divide(h, ref, 1., 1., '')
        ratioplot.SetFillColor(0)
        ratioplot.SetFillStyle(0)
        ratioplot.SetMarkerColor(1)
        ratioplot.SetLineColor(kGray)
        ratioplot.SetMarkerStyle(24)
        ratioplot.SetMarkerSize(1.2)
        ratioplot.GetYaxis().SetTitleSize(0.10)
        ratioplot.GetXaxis().SetTitleSize(0.10)
        ratioplot.GetXaxis().SetLabelSize(0.10)
        ratioplot.GetYaxis().SetLabelSize(0.10)
        ratioplot.GetYaxis().SetRangeUser(-1.6, 3.7)
        ratioplot.GetYaxis().SetTitleOffset(0.7)
        ratioplot.GetYaxis().SetTitle('Data/MC')
        ratioplot.GetXaxis().SetTitle('Rings')
        ratioplot.Draw(drawopt)
        from ROOT import TLine

        nbins = h_mean_data.GetNbinsX()
        xmin = h_mean_data.GetXaxis().GetBinLowEdge(1)
        xmax = h_mean_data.GetXaxis().GetBinLowEdge(nbins + 1)
        l1 = TLine(xmin, 1, xmax, 1)
        l1.SetLineColor(kRed)
        l1.SetLineStyle(2)
        l1.Draw()
        bot.Update()

        top.cd()
        h_mean_mc.SetFillColor(basecolor)
        h_mean_mc.SetLineWidth(1)
        h_mean_mc.SetLineColor(basecolor)
        h_mean_data.SetLineColor(kBlack)
        h_mean_data.SetLineWidth(1)
        #h_mean_mc.Scale( 1./h_mean_mc.GetEntries() )
        #h_mean_data.Scale( 1./h_mean_data.GetEntries() )

        if h_mean_mc.GetMaximum() > h_mean_data.GetMaximum():
            ymin = h_mean_mc.GetMinimum()
            ymax = h_mean_mc.GetMaximum()
            h_mean_mc.Draw()
            h_mean_mc.GetYaxis().SetTitle('E[Ring] MeV')
            h_mean_data.Draw('same')
        else:
            ymin = h_mean_data.GetMinimum()
            ymax = h_mean_data.GetMaximum()
            h_mean_data.GetYaxis().SetTitle('E[Ring] MeV')
            h_mean_data.Draw()
            h_mean_mc.Draw('same')

        h_mean_data.Draw('same')

        # prepare ringer lines
        def gen_line_90(x, ymin, ymax, text):
            from ROOT import TLine, TLatex
            ymax = 1.05 * ymax
            l = TLine(x, ymin, x, ymax)
            l.SetLineStyle(2)
            l.Draw()
            txt = TLatex()
            txt.SetTextFont(12)
            txt.SetTextAngle(90)
            txt.SetTextSize(0.04)
            txt.DrawLatex(x - 1, (ymax - ymin) / 2., text)
            return l, txt

        l_ps, t_ps = gen_line_90(8, ymin, ymax, 'presampler')
        l_em1, t_em1 = gen_line_90(72, ymin, ymax, 'EM.1')
        l_em2, t_em2 = gen_line_90(80, ymin, ymax, 'EM.2')
        l_em3, t_em3 = gen_line_90(88, ymin, ymax, 'EM.3')
        l_had1, t_had1 = gen_line_90(92, ymin, ymax, 'Had.1')
        l_had2, t_had2 = gen_line_90(96, ymin, ymax, 'Had.2')
        l_had3, t_had3 = gen_line_90(100, ymin, ymax, 'Had.3')

        leg1 = TLegend(0.8, 0.70, 0.95, 0.95)
        setLegend1(leg1)
        leg1.AddEntry(h_mean_mc, 'MC')
        leg1.AddEntry(h_mean_data, 'Data')
        leg1.Draw()
        atlas_template(top)
        top.Update()

        canvas3.SaveAs(localpath + '/ringer_profile.pdf')
        figures['ringer_profile'] = localpath + '/ringer_profile.pdf'
        """
      Plot all NN distributions for each calo region
    """
        for algname in self._discrList:
            for etBinIdx in range(len(self._etBins) - 1):
                for etaBinIdx in range(len(self._etaBins) - 1):

                    binningname = ('et%d_eta%d') % (etBinIdx, etaBinIdx)
                    path = self._basepath + '/MonteCarlo/' + binningname
                    h_mc = self.storeSvc().histogram(
                        path + '/' + algname +
                        '/discriminantVsMu').ProjectionX().Clone()
                    path = self._basepath + '/Data/' + binningname
                    h_data = self.storeSvc().histogram(
                        path + '/' + algname +
                        '/discriminantVsMu').ProjectionX().Clone()
                    h_mc.Rebin(10)
                    h_data.Rebin(10)
                    h_mc.Scale(1. / h_mc.GetMaximum())
                    h_data.Scale(1. / h_data.GetMaximum())

                    canvas4 = TCanvas('canvas4', 'canvas4', 2500, 1600)
                    drawopt = 'pE1'
                    canvas4.cd()
                    top = TPad("pad_top", "This is the top pad", 0.0,
                               ratio_size_as_fraction, 1.0, 1.0)
                    top.SetBottomMargin(0.0)
                    top.SetBottomMargin(0.06 / float(top.GetHNDC()))
                    #top.SetTopMargin   (0.04/float(top.GetHNDC()))
                    top.SetRightMargin(0.05)
                    top.SetLeftMargin(0.16)
                    top.SetFillColor(0)
                    top.Draw(drawopt)

                    canvas4.cd()
                    bot = TPad("pad_bot", "This is the bottom pad", 0.0, 0.0,
                               1.0, ratio_size_as_fraction)
                    bot.SetBottomMargin(0.10 / float(bot.GetHNDC()))
                    bot.SetTopMargin(0.0)
                    bot.SetRightMargin(0.05)
                    bot.SetLeftMargin(0.16)
                    bot.SetFillColor(0)
                    bot.Draw(drawopt)

                    gStyle.SetOptStat(000000)

                    from ROOT import TH1, kGray
                    divide = ""
                    drawopt = 'pE1'
                    bot.cd()
                    ref = h_mc.Clone()
                    h = h_data.Clone()
                    ref.Sumw2()
                    h.Sumw2()
                    ratioplot = h.Clone()
                    ratioplot.Sumw2()
                    ratioplot.SetName(h.GetName() + '_ratio')
                    ratioplot.Divide(h, ref, 1., 1., '')
                    ratioplot.SetFillColor(0)
                    ratioplot.SetFillStyle(0)
                    ratioplot.SetMarkerColor(1)
                    ratioplot.SetLineColor(kGray)
                    ratioplot.SetMarkerStyle(24)
                    ratioplot.SetMarkerSize(1.2)
                    ratioplot.GetYaxis().SetTitleSize(0.10)
                    ratioplot.GetXaxis().SetTitleSize(0.10)
                    ratioplot.GetXaxis().SetLabelSize(0.10)
                    ratioplot.GetYaxis().SetLabelSize(0.10)
                    ratioplot.GetYaxis().SetRangeUser(-1.6, 3.7)
                    ratioplot.GetYaxis().SetTitleOffset(0.7)
                    ratioplot.GetYaxis().SetTitle('Data/MC')
                    ratioplot.GetXaxis().SetTitle(
                        'Neural Network (Discriminant)')
                    ratioplot.Draw(drawopt)
                    from ROOT import TLine

                    nbins = h_data.GetNbinsX()
                    xmin = h_data.GetXaxis().GetBinLowEdge(1)
                    xmax = h_data.GetXaxis().GetBinLowEdge(nbins + 1)
                    l1 = TLine(xmin, 1, xmax, 1)
                    l1.SetLineColor(kRed)
                    l1.SetLineStyle(2)
                    l1.Draw()
                    bot.Update()

                    top.cd()
                    h_mc.SetFillColor(basecolor)
                    h_mc.SetLineWidth(1)
                    h_mc.SetLineColor(basecolor)
                    h_data.SetLineColor(kBlack)
                    h_data.SetLineWidth(1)
                    h_mc.Scale(1. / h_mc.GetMaximum())
                    h_data.Scale(1. / h_data.GetMaximum())
                    h_mc.GetYaxis().SetTitle(
                        ('Counts (%s)') % (binningname.replace('_', ',')))
                    h_mc.Draw()
                    h_data.Draw('same')

                    leg1 = TLegend(0.8, 0.70, 0.95, 0.95)
                    setLegend1(leg1)
                    leg1.AddEntry(h_mc, 'MC')
                    leg1.AddEntry(h_data, 'Data')
                    leg1.Draw()
                    atlas_template(top)
                    top.Update()
                    canvas4.SaveAs(localpath + '/' + algname + '_rnnOutput_' +
                                   binningname + '.pdf')
                    figures['rnnOutput'].append(localpath + '/' + algname +
                                                '_rnnOutput_' + binningname +
                                                '.pdf')

        #from RingerCore.tex.TexAPI import *
        from RingerCore.tex.BeamerAPI import BeamerTexReportTemplate1, BeamerSection, BeamerMultiFigureSlide, BeamerFigureSlide
        with BeamerTexReportTemplate1(theme='Berlin',
                                      _toPDF=True,
                                      title=pdftitle,
                                      outputFile=pdfoutput,
                                      font='structurebold'):

            with BeamerSection(name='Shower Shapes'):
                BeamerMultiFigureSlide(
                    title='Shower Shapes (MC and Data)',
                    paths=[figures['shower_shapes']],
                    nDivWidth=1  # x
                    ,
                    nDivHeight=1  # y
                    ,
                    texts=None,
                    fortran=False,
                    usedHeight=0.8,
                    usedWidth=1.1)

            with BeamerSection(name='Ringer Shapes Profile'):
                BeamerMultiFigureSlide(
                    title='Ringer Profile (MC and Data)',
                    paths=[figures['ringer_profile']],
                    nDivWidth=1  # x
                    ,
                    nDivHeight=1  # y
                    ,
                    texts=None,
                    fortran=False,
                    usedHeight=0.8,
                    usedWidth=1.1)

            with BeamerSection(name='Ringer Shapes'):
                for s in range(4):
                    paths1 = [
                        path for path in figures['rings'][s * 25:s * 25 + 25]
                    ]
                    BeamerMultiFigureSlide(
                        title='Ringer Shapes (MC and Data)',
                        paths=paths1,
                        nDivWidth=5  # x
                        ,
                        nDivHeight=5  # y
                        ,
                        texts=None,
                        fortran=False,
                        usedHeight=0.8,
                        usedWidth=1.1)

            for algname in self._discrList:
                with BeamerSection(name=('%s Neural Network Output') %
                                   (algname.replace('_', '\_'))):
                    paths2 = []
                    for etBinIdx in range(len(self._etBins) - 1):
                        for etaBinIdx in range(len(self._etaBins) - 1):
                            binningname = ('et%d_eta%d') % (etBinIdx,
                                                            etaBinIdx)
                            paths2.append(localpath + '/' + algname +
                                          '_rnnOutput_' + binningname + '.pdf')
                    BeamerMultiFigureSlide(
                        title=algname.replace('_', '\_'),
                        paths=paths2,
                        nDivWidth=len(self._etaBins)  # x
                        ,
                        nDivHeight=len(self._etBins)  # y
                        ,
                        texts=None,
                        fortran=False,
                        usedHeight=1.0,
                        usedWidth=1.1)

        return StatusCode.SUCCESS
Beispiel #20
0
def plot_2D(sign,
            var,
            nbins=50,
            minimum=0,
            maximum=2000,
            bins=np.array([]),
            filename="",
            string="",
            part_var="GenBquarks",
            particle="#pi",
            norm=False):
    chain = {}
    hist = {}
    r_ecal = 129
    r_hcal = 179
    r_magnet = 295
    r_mb1 = 402
    r_mb4 = 738

    z_ecal = 300
    z_hcal = 376
    z_magnet = 0
    z_mb1 = 560

    if var == "radius2D":
        v_ecal = TLine(r_ecal, minimum, r_ecal, maximum)
        v_hcal = TLine(r_hcal, minimum, r_hcal, maximum)
        v_magnet = TLine(r_magnet, minimum, r_magnet, maximum)
        v_mb1 = TLine(r_mb1, minimum, r_mb1, maximum)
        v_mb4 = TLine(r_mb4, minimum, r_mb4, maximum)
        h_ecal = TLine(minimum, r_ecal, maximum, r_ecal)
        h_hcal = TLine(minimum, r_hcal, maximum, r_hcal)
        h_magnet = TLine(minimum, r_magnet, maximum, r_magnet)
        h_mb1 = TLine(minimum, r_mb1, maximum, r_mb1)
        h_mb4 = TLine(minimum, r_mb4, maximum, r_mb4)
    elif var == "z":
        v_ecal = TLine(z_ecal, minimum, z_ecal, maximum)
        v_hcal = TLine(z_hcal, minimum, z_hcal, maximum)
        v_magnet = TLine(z_magnet, minimum, z_magnet, maximum)
        v_mb1 = TLine(z_mb1, minimum, z_mb1, maximum)
        h_ecal = TLine(minimum, z_ecal, maximum, z_ecal)
        h_hcal = TLine(minimum, z_hcal, maximum, z_hcal)
        h_magnet = TLine(minimum, z_magnet, maximum, z_magnet)
        h_mb1 = TLine(minimum, z_mb1, maximum, z_mb1)
    else:
        v_ecal = TLine(r_ecal, minimum, r_ecal, maximum)
        v_hcal = TLine(r_hcal, minimum, r_hcal, maximum)
        v_magnet = TLine(r_magnet, minimum, r_magnet, maximum)
        v_mb1 = TLine(r_mb1, minimum, r_mb1, maximum)
        v_mb4 = TLine(r_mb4, minimum, r_mb4, maximum)
        h_ecal = TLine(minimum, r_ecal, maximum, r_ecal)
        h_hcal = TLine(minimum, r_hcal, maximum, r_hcal)
        h_magnet = TLine(minimum, r_magnet, maximum, r_magnet)
        h_mb1 = TLine(minimum, r_mb1, maximum, r_mb1)
        h_mb4 = TLine(minimum, r_mb4, maximum, r_mb4)

    v_ecal.SetLineColor(2)
    h_ecal.SetLineColor(2)
    v_hcal.SetLineColor(881)
    h_hcal.SetLineColor(881)
    v_magnet.SetLineColor(1)
    h_magnet.SetLineColor(1)
    v_mb1.SetLineColor(801)
    v_mb4.SetLineColor(4)
    h_mb1.SetLineColor(801)
    h_mb4.SetLineColor(4)

    v_ecal.SetLineWidth(4)
    h_ecal.SetLineWidth(4)
    v_hcal.SetLineWidth(4)
    h_hcal.SetLineWidth(4)
    v_magnet.SetLineWidth(4)
    h_magnet.SetLineWidth(4)
    v_mb1.SetLineWidth(4)
    h_mb1.SetLineWidth(4)
    v_mb4.SetLineWidth(3)
    h_mb4.SetLineWidth(3)

    v_ecal.SetLineStyle(3)
    h_ecal.SetLineStyle(3)
    v_hcal.SetLineStyle(2)
    h_hcal.SetLineStyle(2)
    v_magnet.SetLineStyle(4)
    h_magnet.SetLineStyle(4)
    v_mb1.SetLineStyle(8)
    h_mb1.SetLineStyle(8)
    v_mb4.SetLineStyle(9)
    h_mb4.SetLineStyle(9)

    leg = TLegend(1 - 0.9, 0.75, 1 - 0.75, 0.9)
    leg.AddEntry(v_ecal, "ECAL", "L")
    leg.AddEntry(v_hcal, "HCAL", "L")
    leg.AddEntry(v_magnet, "solenoid", "L")
    leg.AddEntry(v_mb1, "MB1", "L")
    leg.AddEntry(v_mb4, "MB4", "L")

    #pal= 68 #kAvocado
    #pal= 64 #kAquamarine, very readable
    #pal= 75 #kCherry 75, awful
    #pal= 85 #kIsland 85, not beautiful but readable
    #pal= 86 #kLake 86, too violet
    #pal= 87 #kLightTemperature 87, used for trigger
    #pal= 91 #kPastel 91, too purple
    #pal= 100 #kSolar 100, very red and orange
    pal = 98  #kSandyTerrain 98, quite fine
    #pal= 99 #kSienna 99, a bit hard to read
    gStyle.SetPalette(pal)
    gStyle.SetPaintTextFormat(".f")

    if part_var == "GenBquarks":
        cutstring = "isMC"
        cutstring = "(EventWeight * PUReWeight) * ( (HLT_PFMETNoMu120_PFMHTNoMu120_IDTight_v) && nMuonsPassing==0 && nElectronsPassing==0 && nPhotonsPassing==0 && nTausPassing==0 && MEt.pt>200 )"
        #cutstring = "(EventWeight * PUReWeight) * (HLT_PFMETNoMu120_PFMHTNoMu120_IDTight_v && MEt.pt>200 && nMuonsPassing==0 && nElectronsPassing==0 && nPhotonsPassing==0 && nTausPassing==0)"
        #cutstring = "(EventWeight * PUReWeight)"
    #else:
    #    cutstring = "(EventWeight * PUReWeight) * ( (HLT_PFMETNoMu120_PFMHTNoMu120_IDTight_v && Flag2_globalSuperTightHalo2016Filter && Flag2_goodVertices && Flag2_EcalDeadCellTriggerPrimitiveFilter && Flag2_HBHENoiseFilter && Flag2_HBHEIsoNoiseFilter && Flag2_ecalBadCalibFilter && Flag2_eeBadScFilter && Flag2_BadPFMuonFilter) && nMuonsPassing==0 && nElectronsPassing==0 && nPhotonsPassing==0 && nTausPassing==0 && MEt.pt>200 )"

    for i, s in enumerate(sign):
        chain[s] = TChain("tree")
        if filename == "":
            for p, ss in enumerate(samples[s]['files']):
                chain[s].Add(NTUPLEDIR + ss + ".root")
        else:
            chain[s].Add(NTUPLEDIR + filename + ".root")
        print "Entries: ", chain[s].GetEntries()
        #filename[s] = TFile("VBFH_HToSSTobbbb_MH-125_MS-30_ctauS-1000.root", "READ")
        if len(bins) == 0:
            hist[s] = TH2F(s, "", nbins, minimum, maximum, nbins, minimum,
                           maximum)
        else:
            hist[s] = TH2F(s, "", len(bins) - 1, bins, len(bins) - 1, bins)
        hist[s].Sumw2()
        if var == "z":
            #sign of eta for getting the right z value!
            chain[s].Project(
                s, "sqrt(pow(" + part_var + "[0].radius,2) - pow(" + part_var +
                "[0].radius2D,2)):sqrt(pow(" + part_var +
                "[2].radius,2) - pow(" + part_var + "[2].radius2D,2))",
                cutstring)
        else:
            if part_var == "GenBquarks":
                chain[s].Project(
                    s, "" + part_var + "[0]." + var + ":" + part_var + "[2]." +
                    var + "", cutstring)
            else:
                chain[s].Project(
                    s, "" + part_var + "[0]." + var + ":" + part_var + "[1]." +
                    var + "", cutstring)
        hist[s].SetOption("%s" % chain[s].GetTree().GetEntriesFast())
        if norm:
            hist[s].Scale(100. / hist[s].Integral())
            gStyle.SetPaintTextFormat('5.1f')
        c1 = TCanvas("c1", "c1", 1000, 1000)
        c1.cd()
        #c1.SetGrid()
        #c1.SetLogz()
        c1.SetLogx()
        c1.SetLogy()
        hist[s].GetYaxis().SetTitle(
            "Leading " + particle +
            " transverse decay length (cm)")  #(""+part_var+"[0] "+var+" (cm)")
        hist[s].GetYaxis().SetTitleOffset(1.4)
        hist[s].GetXaxis().SetTitle(
            "Sub-leading " + particle +
            " transverse decay length (cm)")  #(""+part_var+"[2] "+var+" (cm)")
        hist[s].SetTitle(samples[s]['label'] if filename == "" else filename)
        hist[s].SetMarkerColor(0)  #(2)#
        hist[s].Draw("colz")  #()#
        v_ecal.Draw("sames")
        h_ecal.Draw("sames")
        v_hcal.Draw("sames")
        h_hcal.Draw("sames")
        v_magnet.Draw("sames")
        h_magnet.Draw("sames")
        v_mb1.Draw("sames")
        h_mb1.Draw("sames")
        v_mb4.Draw("sames")
        h_mb4.Draw("sames")
        hist[s].SetMarkerSize(1.2)  #(2)#
        hist[s].Draw("text,sames")  #()#
        leg.Draw("sames")
        c1.Print(OUTPUTDIR + "2D_gen_b_quark_" + var + "_" +
                 (s if filename == "" else filename) + string + ".png")
        c1.Print(OUTPUTDIR + "2D_gen_b_quark_" + var + "_" +
                 (s if filename == "" else filename) + string + ".pdf")

        if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
        c1.Close()
def compareDatasets(trigger, leg, datasets, lineColors, legendLabels, axisTitle, canvas, dataLumi, metHLTFilters, outputSuffix = None):

    inputFiles = [TFile.Open("triggerEfficiency_" + x + ".root") for x in datasets]
    efficiencies = [x.Get(trigger + "_" + leg) for x in inputFiles]

    for iEff in range(len(efficiencies)):
        SetStyle(efficiencies[iEff])
        efficiencies[iEff].SetLineColor(lineColors[iEff])
        efficiencies[iEff].SetMarkerColor(lineColors[iEff])

    oneLine = TLine(xlo, 1.0, xhi, 1.0)
    oneLine.SetLineWidth(3)
    oneLine.SetLineStyle(2)

    backgroundHist = TH1D("backgroundHist", "backgroundHist", 1, xlo, xhi)
    backgroundHist.GetYaxis().SetTitle("Trigger Efficiency")
    backgroundHist.GetYaxis().SetRangeUser(ylo, yhi)
    backgroundHist.GetXaxis().SetTitle(axisTitle)
    SetStyle(backgroundHist)

    canvas.cd()
    backgroundHist.Draw()
    for eff in efficiencies:
        eff.Draw("CP same")
    #oneLine.Draw("same")

    pt_cmsPrelim = TPaveText(0.132832, 0.859453, 0.486216, 0.906716, "brNDC")
    pt_cmsPrelim.SetBorderSize(0)
    pt_cmsPrelim.SetFillStyle(0)
    pt_cmsPrelim.SetTextFont(62)
    pt_cmsPrelim.SetTextSize(0.0374065)
    if dataLumi > 0:
        pt_cmsPrelim.AddText("CMS Preliminary")
    else:
        pt_cmsPrelim.AddText("CMS Simulation")
    pt_cmsPrelim.Draw("same")

    if dataLumi > 0:
        pt_lumi = TPaveText(0.744361, 0.92928, 0.860902, 0.977667, "brNDC")
        pt_lumi.SetBorderSize(0)
        pt_lumi.SetFillStyle(0)
        pt_lumi.SetTextFont(42)
        pt_lumi.SetTextSize(0.0374065)
        pt_lumi.AddText("{:.2f}".format(dataLumi / 1000.0) + " fb^{-1}, 13 TeV")
        pt_lumi.Draw("same")

    pt_leg = TPaveText(0.160401, 0.768657, 0.342105, 0.863184, "brNDC")
    pt_leg.SetBorderSize(0)
    pt_leg.SetFillStyle(0)
    pt_leg.SetTextFont(42)
    pt_leg.SetTextSize(0.025)
    pt_leg.SetTextAlign(12)
    if leg == "METLeg":
        legLabel = ""
        for filt in metHLTFilters[:-1]:
            legLabel = legLabel + filt + ", "
        legLabel = legLabel + metHLTFilters[-1]
        pt_leg.AddText(legLabel)
    if leg == "TrackLeg":
        pt_leg.AddText(trigger + "*")
        legLabel = ""
        for filt in metHLTFilters[:-1]:
            legLabel = legLabel + filt + ", "
        legLabel = legLabel + metHLTFilters[-1] + " applied"
        pt_leg.AddText(legLabel)
    if leg == "METPath":
        if trigger == "GrandOr":
            pt_leg.AddText("OR of Signal Paths")
        else:
            if len(trigger) > 25 and len(trigger.split("_")) > 2:
                firstLine = trigger.split("_")[0] + "_" + trigger.split("_")[1] + "_"
                pt_leg.AddText(firstLine)
                secondLine = ""
                for line in trigger.split("_")[2:-1]:
                    secondLine += line + "_"
                secondLine += trigger.split("_")[-1] + "*"
                pt_leg.AddText(secondLine)
            else:
                pt_leg.AddText(trigger + "*")
    pt_leg.Draw("same")

    legendLabel = trigger

    legend = TLegend(0.65, 0.75, 0.93, 0.88)
    legend.SetBorderSize(0)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetTextFont(42)
    if leg == 'METLeg':
        legend.SetHeader('MET Leg')
    elif leg == 'TrackLeg':
        legend.SetHeader('Track Leg')
    for iEff in range(len(efficiencies)):
        legend.AddEntry(efficiencies[iEff], legendLabels[iEff], 'P')
    legend.Draw("same")

    if outputSuffix is not None:
        canvas.SaveAs('compareDatasets_' + trigger + '_' + leg + '_' + outputSuffix + '.pdf')
    else:
        canvas.SaveAs('compareDatasets_' + trigger + '_' + leg + '_.pdf')

    for inputFile in inputFiles:
        inputFile.Close()

    return
Beispiel #22
0
def limit_canvas(limits_, signal_, oname_):

    m = [mp.mass for mp in limits_]
    exp = [mp.exp for mp in limits_]
    exp68up = [mp.exp68up for mp in limits_]
    exp68dn = [mp.exp68dn for mp in limits_]
    exp95up = [mp.exp95up for mp in limits_]
    exp95dn = [mp.exp95dn for mp in limits_]
    obs = [mp.obs for mp in limits_]

    N = len(limits_)
    gExp = TGraph()
    g68 = TGraph(2*N)
    g95 = TGraph(2*N)
    gObs = TGraph()
    gTH = get_theory_XsecBR_graph(signal_)

    for a in range(0,N):
        gExp.SetPoint(a,m[a],exp[a])
        gObs.SetPoint(a,m[a],obs[a])
        g68.SetPoint(a,m[a],exp68dn[a])
        g95.SetPoint(a,m[a],exp95dn[a])
        g68.SetPoint(N+a,m[N-a-1],exp68up[N-a-1])
        g95.SetPoint(N+a,m[N-a-1],exp95up[N-a-1])

    trans = 0
    up = 0
    if signal_ == 'n':
        trans = 0.770776
        up = 3
    if signal_ == 'w':
        trans = 0.836432
        up = 10
    if signal_ == 'r':
        trans = 0.899902
        up = 4

    gExp.SetLineStyle(2)
    gExp.SetLineWidth(4)
    gExp.SetLineColor(TColor.GetColor('#112288'))
    #gExp.Print()

    g68.SetLineStyle(1)
    g68.SetLineWidth(0)
    g68.SetLineColor(kBlack)
    g68.SetFillColor(TColor.GetColor('#4488dd'))

    g95.SetLineStyle(1)
    g95.SetLineWidth(0)
    g95.SetLineColor(kBlack)
    g95.SetFillColor(TColor.GetColor('#99bbff'))

    gObs.SetLineStyle(1)
    gObs.SetLineWidth(4)
    gObs.SetLineColor(kBlack)
    gObs.SetMarkerStyle(21)
    gObs.SetMarkerSize(0.8)

    gTH.SetLineStyle(7)
    gTH.SetLineWidth(4)
    gTH.SetMarkerSize(0)
    gTH.SetMarkerColor(kRed+1)
    gTH.SetLineColor(kRed+1)

    leg = TLegend(0.58,0.633,0.969,0.908)
    leg.SetFillColor(0)
    leg.SetBorderSize(0)
    leg.AddEntry(gExp,'Expected (95% CL)','l')
    leg.AddEntry(gObs,'Observed (95% CL)','l')
    leg.AddEntry(gTH,signal_dict[signal_][1],'l')
    leg.AddEntry(g68,'#pm1#sigma Expected','f')
    leg.AddEntry(g95,'#pm2#sigma Expected','f')

    text_TL = TPaveText(0.18,0.830,0.44,0.900,'NDC')
    text_TL.AddText(label_TL)
    text_TL.SetFillColor(0)
    text_TL.SetTextAlign(12)
    text_TL.SetTextSize(0.06)
    text_TL.SetTextFont(42)

    text_TR = TPaveText(0.586,0.923,0.999,0.997,'NDC')
    text_TR.AddText(label_TR)
    text_TR.SetFillColor(0)
    text_TR.SetTextAlign(32)
    text_TR.SetTextSize(0.055)
    text_TR.SetTextFont(42)

    c = TCanvas('c','c',950,750)
    c.SetTopMargin(0.08)
    c.SetRightMargin(0.02)
    c.SetBottomMargin(0.135)
    c.SetLeftMargin(0.11)
    #c.SetGrid()
    c.SetLogy()

    #hr = c.DrawFrame(0.401,0.001,3.999,1000)
    #hr = c.DrawFrame(0.401,0.001,4.199,1000)
    hr = c.DrawFrame(0.401,0.001,5.199,1000)
    gExp.Sort()
    gTH.Print()
    g95.Draw('f')
    g95.Print()
    g68.Draw('f')
    gTH.Draw('L')
    gExp.Draw('L')

#Don't draw observed for blind analysis
#    gObs.Sort()
#    gObs.Draw('L')

    hr.GetXaxis().SetTitle('M_{'+signal_dict[signal_][0]+'} [TeV]')
    hr.GetYaxis().SetTitle('Upper limit on #sigma_{'+signal_dict[signal_][0]+'} #times B('+signal_dict[signal_][0]+' #rightarrow t#bar{t}) [pb]')
    #hr.GetYaxis().SetTitle('\\mathrm{Upper~limit~on~}\\sigma_{'+signal_dict[signal_][0]+'}\\times\\mathscr{B}('+signal_dict[signal_][0]+' \\rightarrow t\\bar{t}) [pb]')
    hr.GetXaxis().SetTitleSize(0.055)
    hr.GetYaxis().SetTitleSize(0.055)
    hr.GetXaxis().SetTitleFont(42)
    hr.GetYaxis().SetTitleFont(42)
    hr.GetXaxis().SetTitleOffset(1.00)
    hr.GetYaxis().SetTitleOffset(0.98)
    hr.GetXaxis().SetLabelSize(0.045)
    hr.GetYaxis().SetLabelSize(0.045)

    name = TString(oname_)
    if name.Contains("com"):
        tl = TLine(trans, 1e-3, trans, up)
        tl.SetLineStyle(ROOT.kDashed)
        tl.SetLineColor(kGray+1)
        tl.SetLineWidth(3)
        tl.Draw()

    c.Update()
    text_TL.Draw('same')
    text_TR.Draw('same')
    leg.Draw()

    c.SaveAs(oname_+'.pdf')
    c.Close()
    def plotEfficiency(self, doFit = False):
        if hasattr(self, "Denominator") and hasattr(self, "Numerator"):
            if self._rebinFactor != 1:
                self.Denominator["hist"].Rebin(self._rebinFactor)
                self.Numerator["hist"].Rebin(self._rebinFactor)
		
            for ibin in range(-1, self.Numerator["hist"].GetNbinsX()+1):
                if self.Numerator["hist"].GetBinContent(ibin+1) > self.Denominator["hist"].GetBinContent(ibin+1):
                    print('Fixing bad bin:', (ibin+1))
                    self.Numerator["hist"].SetBinContent(ibin+1, self.Denominator["hist"].GetBinContent(ibin+1))
                    self.Numerator["hist"].SetBinError(ibin+1, self.Denominator["hist"].GetBinError(ibin+1))

            efficiencyGraph = TGraphAsymmErrors(self.Numerator["hist"], self.Denominator["hist"], "cp")

            pt_cmsPrelim = TPaveText(0.132832, 0.859453, 0.486216, 0.906716, "brNDC")
            pt_cmsPrelim.SetBorderSize(0)
            pt_cmsPrelim.SetFillStyle(0)
            pt_cmsPrelim.SetTextFont(62)
            pt_cmsPrelim.SetTextSize(0.0374065)
            pt_cmsPrelim.AddText("CMS Preliminary")

            pt_lumi = TPaveText(0.744361, 0.92928, 0.860902, 0.977667, "brNDC")
            pt_lumi.SetBorderSize(0)
            pt_lumi.SetFillStyle(0)
            pt_lumi.SetTextFont(42)
            pt_lumi.SetTextSize(0.0374065)
            pt_lumi.AddText(self._luminosityLabel)

            pt_leg = TPaveText(0.160401, 0.768657, 0.342105, 0.863184, "brNDC")
            pt_leg.SetBorderSize(0)
            pt_leg.SetFillStyle(0)
            pt_leg.SetTextFont(42)
            pt_leg.SetTextSize(0.0349127)
            pt_leg.SetTextAlign(12)
            if self._leg == "METLeg":
                legLabel = ""
                for filt in self._metHLTFilters[:-1]:
                    legLabel = legLabel + filt + ", "
                legLabel = legLabel + self._metHLTFilters[-1]
                pt_leg.AddText(legLabel)
                pt_leg.AddText(self._datasetLabel)
            if self._leg == "TrackLeg":
                pt_leg.AddText(self._path + "*")
                pt_leg.AddText(self._datasetLabel)
                legLabel = ""
                for filt in self._metHLTFilters[:-1]:
                    legLabel = legLabel + filt + ", "
                legLabel = legLabel + self._metHLTFilters[-1] + " applied"
                pt_leg.AddText(legLabel)
            if self._leg == "METPath":
                if self._path == "GrandOr":
                    pt_leg.AddText("OR of Signal Paths")
                else:
                    pt_leg.AddText(self._path + "*")
                pt_leg.AddText(self._datasetLabel)

            lumiLabel = TPaveText(0.66416, 0.937339, 0.962406, 0.992894, "brNDC")
            lumiLabel.SetBorderSize(0)
            lumiLabel.SetFillStyle(0)
            lumiLabel.SetTextFont(42)
            lumiLabel.SetTextSize(0.0387597)
            lumiLabel.AddText(str (self._luminosityLabel))

            oneLine = TLine(xlo, 1.0, xhi, 1.0)
            oneLine.SetLineWidth(3)
            oneLine.SetLineStyle(2)

            backgroundHist = TH1D("backgroundHist", "backgroundHist", 1, xlo, xhi)
            backgroundHist.GetYaxis().SetTitle("Trigger Efficiency")
            backgroundHist.GetYaxis().SetRangeUser(ylo, yhi)
            if self._leg == "METLeg" or self._leg == "METPath":
                backgroundHist.GetXaxis().SetTitle(self._metLegAxisTitle)
            elif self._leg == "TrackLeg":
                backgroundHist.GetXaxis().SetTitle(self._trackLegAxisTitle)

            SetStyle(backgroundHist)
            SetStyle(efficiencyGraph)

            self._canvas.cd()
            backgroundHist.Draw()
            efficiencyGraph.Draw("P")
            pt_cmsPrelim.Draw("same")
            pt_lumi.Draw("same")
            pt_leg.Draw("same")
            oneLine.Draw("same")

            if doFit:
                (fitFunc, fitText) = self.PlotFit(efficiencyGraph)
                fitFunc.Draw("same")
                fitText.Draw("same")

            if not os.path.exists('plots_' + self.Denominator["sample"]):
                os.mkdir('plots_' + self.Denominator["sample"])

            if self._leg == "METPath":
                self._canvas.SaveAs('plots_' + self.Denominator["sample"] + '/' + self._path + "_Efficiency.pdf")
            else:
                self._canvas.SaveAs('plots_' + self.Denominator["sample"] + '/' + self._path + "_" + self._leg + ".pdf")
            self._fout.cd()
            if self._tgraphSuffix is not None:
                efficiencyGraph.Write(self._path + "_" + self._leg + "_" + self._tgraphSuffix)
                if doFit:
                    fitFunc.Write(self._path + "_" + self._leg + "_" + self._tgraphSuffix + "_fitResult")
            else:
                efficiencyGraph.Write(self._path + "_" + self._leg)
                if doFit:
                    fitFunc.Write(self._path + "_" + self._leg + "_fitResult")

        else:
            print("Denominator and Numerator must be defined for path ", self._path, ", leg ", self._leg)
            return 0.0
Beispiel #24
0
    def printSystematic(self):
        fakeRate3, fakeRate3Error, ratio3, ratio3Error = self.printFakeRateRatio(
            3)
        fakeRate4, fakeRate4Error, ratio4, ratio4Error = self.printFakeRateRatio(
            4)
        fakeRate5, fakeRate5Error, ratio5, ratio5Error = self.printFakeRateRatio(
            5)
        fakeRate6, fakeRate6Error, ratio6, ratio6Error = self.printFakeRateRatio(
            6)

        print("systematic uncertainty: " +
              str((abs(ratio5 - 1.0) + ratio5Error) * 100.0) + "%")

        basicFakeRate = TH1D("basicFakeRate", ";number of hits", 400, 2.5, 6.5)
        zToMuMuFakeRate = TH1D("zToMuMuFakeRate", ";number of hits", 400, 2.5,
                               6.5)
        ratio = TH1D("ratio", ";number of hits", 400, 2.5, 6.5)

        basicFakeRate.SetBinContent(basicFakeRate.FindBin(3.0), fakeRate3[0])
        basicFakeRate.SetBinError(basicFakeRate.FindBin(3.0),
                                  fakeRate3Error[0])
        basicFakeRate.SetBinContent(basicFakeRate.FindBin(4.0), fakeRate4[0])
        basicFakeRate.SetBinError(basicFakeRate.FindBin(4.0),
                                  fakeRate4Error[0])
        basicFakeRate.SetBinContent(basicFakeRate.FindBin(5.0), fakeRate5[0])
        basicFakeRate.SetBinError(basicFakeRate.FindBin(5.0),
                                  fakeRate5Error[0])
        basicFakeRate.SetBinContent(basicFakeRate.FindBin(6.0), fakeRate6[0])
        basicFakeRate.SetBinError(basicFakeRate.FindBin(6.0),
                                  fakeRate6Error[0])

        zToMuMuFakeRate.SetBinContent(zToMuMuFakeRate.FindBin(3.0),
                                      fakeRate3[1])
        zToMuMuFakeRate.SetBinError(zToMuMuFakeRate.FindBin(3.0),
                                    fakeRate3Error[1])
        zToMuMuFakeRate.SetBinContent(zToMuMuFakeRate.FindBin(4.0),
                                      fakeRate4[1])
        zToMuMuFakeRate.SetBinError(zToMuMuFakeRate.FindBin(4.0),
                                    fakeRate4Error[1])
        zToMuMuFakeRate.SetBinContent(zToMuMuFakeRate.FindBin(5.0),
                                      fakeRate5[1])
        zToMuMuFakeRate.SetBinError(zToMuMuFakeRate.FindBin(5.0),
                                    fakeRate5Error[1])
        zToMuMuFakeRate.SetBinContent(zToMuMuFakeRate.FindBin(6.0),
                                      fakeRate6[1])
        zToMuMuFakeRate.SetBinError(zToMuMuFakeRate.FindBin(6.0),
                                    fakeRate6Error[1])

        ratio.SetBinContent(ratio.FindBin(3.0), ratio3)
        ratio.SetBinError(ratio.FindBin(3.0), ratio3Error)
        ratio.SetBinContent(ratio.FindBin(4.0), ratio4)
        ratio.SetBinError(ratio.FindBin(4.0), ratio4Error)
        ratio.SetBinContent(ratio.FindBin(5.0), ratio5)
        ratio.SetBinError(ratio.FindBin(5.0), ratio5Error)
        ratio.SetBinContent(ratio.FindBin(6.0), ratio6)
        ratio.SetBinError(ratio.FindBin(6.0), ratio6Error)

        cmsLabel = TPaveText(0.134085, 0.937984, 0.418546, 0.984496, "brNDC")
        cmsLabel.SetBorderSize(0)
        cmsLabel.SetFillStyle(0)
        cmsLabel.SetTextFont(62)
        cmsLabel.SetTextSize(0.0387597)
        cmsLabel.AddText("CMS Preliminary")

        lumiLabel = TPaveText(0.66416, 0.937339, 0.962406, 0.992894, "brNDC")
        lumiLabel.SetBorderSize(0)
        lumiLabel.SetFillStyle(0)
        lumiLabel.SetTextFont(42)
        lumiLabel.SetTextSize(0.0387597)
        lumiLabel.AddText(str(self._luminosityLabel))

        leg = TLegend(0.7550251, 0.7759067, 0.9459799, 0.8795337)
        leg.SetBorderSize(0)
        leg.SetTextSize(0.0388601)
        leg.SetTextFont(42)
        leg.SetLineColor(1)
        leg.SetLineStyle(1)
        leg.SetLineWidth(1)
        leg.SetFillColor(0)
        leg.SetFillStyle(0)
        leg.AddEntry(zToMuMuFakeRate, "Z#rightarrow#mu#mu", "p")
        leg.AddEntry(basicFakeRate, "basic", "p")

        setStyle(basicFakeRate, 632)
        setStyle(zToMuMuFakeRate, 600)
        setAxisStyle(basicFakeRate, yTitle="P_{fake}")
        setAxisStyle(zToMuMuFakeRate, yTitle="P_{fake}")
        self._canvas.cd()
        self._canvas.SetLogy()
        zToMuMuFakeRate.Draw()
        basicFakeRate.Draw("same")
        leg.Draw("same")
        cmsLabel.Draw("same")
        lumiLabel.Draw("same")
        self._fout.cd()
        self._canvas.Write("fakeRate")

        line = TLine(2.5, 1.0, 6.5, 1.0)
        line.SetLineStyle(2)
        line.SetLineWidth(2)
        line.SetLineColor(1)

        setStyle(ratio)
        setAxisStyle(
            ratio,
            yTitle=("P_{fake}^{Z#rightarrow#mu#mu} / P_{fake}^{basic}"
                    if not self._plotDiff else
                    "P_{fake}^{Z#rightarrow#mu#mu} - P_{fake}^{basic}"))
        self._canvas.cd()
        self._canvas.SetLogy(False)
        ratio.Draw()
        line.Draw("same")
        cmsLabel.Draw("same")
        lumiLabel.Draw("same")
        self._fout.cd()
        self._canvas.Write("fakeRateRatio")
Beispiel #25
0
class vertex_displayer(object):
    """Debug class for displaying vertices, tracks and impact parameters on the transverse plane, based on ROOT classes.
    """
    def __init__(self,
                 name,
                 title,
                 lenght,
                 time_min,
                 time_max,
                 helix,
                 n_points=100,
                 ip_algorithm='complex'):
        """
        Constructor providing:
        name: string used to identify ROOT objects
        title: string used as title of canvases and graphs
        lenght: half of the axis dimension
        time_min and time_max: defining the time interval for which the track is shown
        helix: helix object to be shown; having the ip attributes is mandatory
        n_points: number of points that show the track
        ip_algorithm: if 'complex' it shows also the distance of
        closest approach to the jet direction, and the linearized track at
        that point. It requires to have run the function compute_IP_wrt_direction
        on the helix object.
        """
        self.name = name
        self.title = title
        self.helix = helix
        self.ip_algorithm = ip_algorithm

        self.gr_transverse = TGraph()
        self.gr_transverse.SetNameTitle("g_tr_" + name, title)
        self.gr_transverse.SetPoint(0, 0., 0.)
        self.gr_transverse.SetPoint(1, 0., lenght)
        self.gr_transverse.SetPoint(2, 0., -lenght)
        self.gr_transverse.SetPoint(3, lenght, 0.)
        self.gr_transverse.SetPoint(4, -lenght, 0.)
        self.gr_transverse.SetMarkerStyle(22)
        self.gr_transverse.SetMarkerColor(3)
        self.gr_transverse.GetXaxis().SetTitle("X axis")
        self.gr_transverse.GetYaxis().SetTitle("Y axis")

        # Origin
        self.gr_transverse.SetPoint(5, helix.origin.X(), helix.origin.Y())

        # Track
        self.ell_transverse = TGraph()
        self.ell_transverse.SetNameTitle("g_ellipse_" + name, title)
        self.ell_transverse.SetMarkerStyle(7)
        self.ell_transverse.SetMarkerColor(1)

        for i in range(n_points):
            time_coord = time_min + i * (time_max - time_min) / n_points
            point = helix.point_at_time(time_coord)
            self.ell_transverse.SetPoint(i, point.X(), point.Y())

        # Jet direction
        jet_dir_x1 = self.helix.primary_vertex.X(
        ) - lenght * self.helix.jet_direction.X()
        jet_dir_x2 = self.helix.primary_vertex.X(
        ) + lenght * self.helix.jet_direction.X()
        jet_dir_y1 = self.helix.primary_vertex.Y(
        ) - lenght * self.helix.jet_direction.Y()
        jet_dir_y2 = self.helix.primary_vertex.Y(
        ) + lenght * self.helix.jet_direction.Y()

        self.jet_dir = TLine(jet_dir_x1, jet_dir_y1, jet_dir_x2, jet_dir_y2)
        self.jet_dir.SetLineColor(6)
        self.jet_dir.SetLineStyle(1)
        self.jet_dir.SetLineWidth(1)

        # Impact Parameter D
        impact_parameter_x1 = self.helix.primary_vertex.X()
        impact_parameter_y1 = self.helix.primary_vertex.Y()
        impact_parameter_x2 = self.helix.vector_impact_parameter.X()
        impact_parameter_y2 = self.helix.vector_impact_parameter.Y()

        self.impact_parameter = TLine(impact_parameter_x1, impact_parameter_y1,
                                      impact_parameter_x2, impact_parameter_y2)
        self.impact_parameter.SetLineColor(4)
        self.impact_parameter.SetLineStyle(6)
        self.impact_parameter.SetLineWidth(4)

        if self.ip_algorithm == 'complex':
            # Linearized_track
            lin_track_x1 = self.helix.linearized_track.origin.X() \
                         - lenght * self.helix.linearized_track.direction.X()
            lin_track_x2 = self.helix.linearized_track.origin.X() \
                         + lenght * self.helix.linearized_track.direction.X()
            lin_track_y1 = self.helix.linearized_track.origin.Y() \
                         - lenght * self.helix.linearized_track.direction.Y()
            lin_track_y2 = self.helix.linearized_track.origin.Y() \
                         + lenght * self.helix.linearized_track.direction.Y()

            self.lin_track = TLine(lin_track_x1, lin_track_y1, lin_track_x2,
                                   lin_track_y2)
            self.lin_track.SetLineColor(2)
            self.lin_track.SetLineStyle(9)
            self.lin_track.SetLineWidth(2)

            # Jet-track distance D_j: vector from S_j to S_t
            jet_track_distance_x1 = self.helix.jet_point_min_approach.X()
            jet_track_distance_y1 = self.helix.jet_point_min_approach.Y()
            jet_track_distance_x2 = self.helix.point_min_approach.X()
            jet_track_distance_y2 = self.helix.point_min_approach.Y()

            self.jet_track_distance = TLine(jet_track_distance_x1,
                                            jet_track_distance_y1,
                                            jet_track_distance_x2,
                                            jet_track_distance_y2)
            self.jet_track_distance.SetLineColor(3)
            self.jet_track_distance.SetLineStyle(3)
            self.jet_track_distance.SetLineWidth(4)

    def draw(self):
        """Draw the canvas showing the transverse plane to the beam axis.

        In particular it shows the x-y axis, the track, the jet direction and
        the impact parameter.
        If the ip_algorithm 'complex' is enabled it also shows the distance of
        closest approach to the jet direction, and the linearized track at
        that point.
        """
        self.c_transverse = TCanvas("c_tr_" + self.name, self.title, 800, 600)
        self.c_transverse.cd()
        self.c_transverse.SetGrid()
        self.gr_transverse.Draw("AP")
        self.ell_transverse.Draw("same LP")
        self.jet_dir.Draw("same")
        self.impact_parameter.Draw("same")

        if self.ip_algorithm == 'complex':
            self.lin_track.Draw("same")
            self.jet_track_distance.Draw("same")
Beispiel #26
0
def plot_dir(dlist,
             binfo,
             outfile,
             prefix,
             infix,
             color=[kBlack],
             legend=[],
             norm=False):
    c = TCanvas()
    c.SetGrid(0)
    bnarr = binfo.keys()
    bnarr.sort()
    bncode = reduce(lambda x, y: x + y, bnarr)
    namex = bnarr[-2]
    namey = bnarr[-1]
    xarr = binfo[namex]
    yarr = binfo[namey]

    c.GetPad(0).SetMargin(0.2, 0.15, 0.2, 0.15)
    c.Divide(len(xarr) - 1, len(yarr) - 1, 0.0, 0.0)
    #CanvasPartition(c,len(xarr)-1,len(yarr)-1)
    Ntot = 1
    for k in range(len(bnarr) - 2):
        Ntot *= len(binfo[bnarr[k]]) - 1

    for k in range(Ntot):
        indarr = []
        fact = 1
        for n in range(len(bnarr) - 2):
            edg = binfo[bnarr[n]]
            indarr.append((k / fact) % (len(edg) - 1))
            fact *= len(binfo[bnarr[n]]) - 1

        for j in range(len(yarr) - 1, 0, -1):
            YMAX = -100000000.
            YMIN = 100000000.
            row = j
            for i in range(len(xarr) - 1):
                col = i + 1
                bcode = reduce(lambda x, y: str(x) + str(y), indarr)
                bcode = str(bcode) + str(col - 1) + str(row - 1)
                cnt = 0
                for d in dlist:
                    h = d.Get(prefix[cnt] + bncode + "_" + bcode)
                    maxb = h.GetMaximumBin()
                    minb = h.GetMinimumBin()
                    ymaxtest = h.GetBinContent(maxb)
                    ymintest = h.GetBinContent(minb)
                    #                    if True:
                    #                        print "before::" + d.GetPath() + "/" + h.GetName() + "::row::" + str(row) + ":: ymax / integral / bin / content(bin): " + str(ymaxtest) + " / " + str(h.Integral()) + " / " + str( maxb) +  " / " + str( h.GetBinContent(maxb))
                    if norm and h.Integral() != 0:
                        ymaxtest = ymaxtest / h.Integral()
                        ymintest = ymintest / h.Integral()
                    if norm and h.Integral() == 0:
                        ymaxtest = 0
                        ymintest = 0
                    if ymaxtest > YMAX:
                        YMAX = ymaxtest
                    if ymintest < YMIN:
                        YMIN = ymintest
                    cnt += 1

#               if norm:
#                   print bncode + "::row::" + str(row) + "::ymax: " + str(YMAX)

            for i in range(len(xarr) - 1):
                col = i + 1

                pad = c.cd(col + (len(yarr) - 1 - row) * (len(xarr) - 1))
                pad.SetGridy(0)
                #pad.SetGridx(0)
                pad.SetTicks(0, 0)
                bcode = reduce(lambda x, y: str(x) + str(y), indarr)
                bcode = str(bcode) + str(col - 1) + str(row - 1)
                cnt = 0
                leg = TLegend(0.77, 0.64, 0.95, 0.89)
                leg.SetTextSize(0.15)

                for d in dlist:
                    h = d.Get(prefix[cnt] + bncode + "_" + bcode)
                    h.GetYaxis().SetRangeUser(YMIN, YMAX * 1.1)
                    if "ac" in prefix[cnt] or "Acceptance" in d.GetPath():
                        h.GetYaxis().SetRangeUser(0, 1)
                    h.GetYaxis().SetLabelSize(0.15)
                    h.GetXaxis().SetLabelSize(0.1)
                    h.GetYaxis().SetLabelSize(0.15)
                    xtitle = str(
                        binfo[namex][col - 1]) + '<' + namex + '<' + str(
                            binfo[namex][col]) + "     " + prefix[cnt].split(
                                '_')[0][1:]
                    h.GetXaxis().SetTitle(xtitle)
                    h.GetXaxis().CenterTitle()
                    h.GetXaxis().SetTitleSize(0.12)
                    ytitle = str(
                        binfo[namey][row - 1]) + '<' + namey + '<' + str(
                            binfo[namey][row])
                    h.GetXaxis().SetNdivisions(505)
                    h.GetYaxis().SetNdivisions(505)
                    h.SetLineWidth(3)
                    h.SetLineColor(color[cnt])
                    h.SetMarkerColor(color[cnt])
                    if (legend != []):
                        le = leg.AddEntry(h, legend[cnt], 'lp')
                        le.SetTextColor(color[cnt])
                    if cnt == 0:
                        if not norm: h.DrawCopy()
                        elif (h.Integral() != 0):
                            hnorm = h.DrawNormalized("e")
                            hnorm.GetYaxis().SetRangeUser(YMIN, YMAX * 1.1)
                        else:
                            h.DrawCopy()
                        if 'hM_' in h.GetName():
                            rhopeak = TLine(0.77, 0, 0.77, YMAX)
                            rhopeak.SetLineStyle(kDashed)
                            rhopeak.SetLineWidth(1)
                            rhopeak.SetLineColor(kRed)
                            rhopeak.DrawLine(0.77, 0, 0.77, YMAX)
                        pad.Update()
                        pt = pad.FindObject("title")
                        pt.SetX1NDC(0.15)
                        pt.SetTextSizePixels(12)
                        if col == len(xarr) - 1:
                            yaxis = TGaxis(pad.GetUxmax(), pad.GetUymin(),
                                           pad.GetUxmax(), pad.GetUymax(), 0,
                                           1, 1, "U+-")
                            yaxis.SetTitle(ytitle + "     ")
                            yaxis.SetTitleSize(0.12)
                            yaxis.SetTitleOffset(-0.25)
                            yaxis.SetName(h.GetName() + "_ax_y")
                            yaxis.Draw("")
                            pad.GetListOfPrimitives().Add(yaxis)
                            pad.Update()
                    else:
                        if not norm: h.DrawCopy("same")
                        elif (h.Integral() != 0):
                            hnorm = h.DrawNormalized("samee")
                            hnorm.GetYaxis().SetRangeUser(YMIN, YMAX * 1.1)
                        else:
                            h.DrawCopy("samee")
                    cnt += 1
                if (legend != []):
                    leg.Draw()
                    pad.GetListOfPrimitives().Add(leg)
        outfile.cd()
        bcode = reduce(lambda x, y: str(x) + str(y), indarr)
        cncode = reduce(lambda x, y: x + y, bnarr[-3])
        c.Write("can_" + infix + "_" + str(cncode) + "_" + str(bcode),
                TObject.kOverwrite)
Beispiel #27
0
def runMCStudy():

    # load workspace
    f = TFile("./data/fitWorkspace.root")
    fitWorkspace = f.Get("fitWorkspace")
    fEnergy = fitWorkspace.var("energy_keV")
    model = fitWorkspace.pdf("model")
    fitResult = fitWorkspace.allGenericObjects().front()
    fitValsFinal = getRooArgDict(fitResult.floatParsFinal())
    pdfList = fitWorkspace.allPdfs()  # RooArgSet
    nExpected = int(model.expectedEvents(pdfList))

    # thank you, lindsey gray. http://www.hep.wisc.edu/~lgray/toyMC.py
    nSamples = 10
    args = [
        # RF.Binned(True),
        RF.Silence(),
        RF.FitOptions(RF.PrintEvalErrors(0),
                      RF.NumCPU(2))  # not sure numCPU is doing anything
    ]
    mcStudy = ROOT.RooMCStudy(model, ROOT.RooArgSet(fEnergy), *args)
    start = time.time()
    mcStudy.generateAndFit(
        nSamples, nExpected)  # nSamples (nToys), nEvtPerSample (nEvents)
    print "MC Study Complete. %i samples, %.2f seconds." % (
        nSamples, time.time() - start)

    parName = "amp-36Cl"
    parVal = fitResult.floatParsFinal().find(parName).getValV()
    parErr = fitResult.floatParsFinal().find(parName).getError()
    parVar = fitWorkspace.var(parName)

    # make 4 rooplot frames
    fParam = mcStudy.plotParam(parVar, RF.Bins(50))
    fError = mcStudy.plotError(
        parVar, RF.FrameRange(parErr - 0.5 * parErr, parErr + 0.5 * parErr),
        RF.Bins(50))
    fPull = mcStudy.plotPull(parVar, RF.FrameRange(-5, 5), RF.Bins(50))
    fNLL = mcStudy.plotNLL(RF.Bins(50))

    line = TLine()
    line.SetLineColor(ROOT.kBlue)
    line.SetLineWidth(2)
    line.SetLineStyle(3)

    c = TCanvas("c", "c", 1100, 800)
    c.Divide(2, 2)
    c.cd(1)
    fParam.SetTitle(parName)
    fParam.Draw()
    line.DrawLine(parVal, fParam.GetMinimum(), parVal,
                  fParam.GetMaximum())  # best fit

    c.cd(2)
    fError.SetTitle(parName + " Error")
    fError.Draw()
    line.DrawLine(parErr, fError.GetMinimum(), parErr, fError.GetMaximum())

    c.cd(3)
    fPull.SetTitle(parName + " Pull")
    fPull.Draw()

    c.cd(4)
    fNLL.SetTitle("-log(likelihood)")
    fNLL.Draw()
    line.DrawLine(fitResult.minNll(), fNLL.GetMinimum(), fitResult.minNll(),
                  fNLL.GetMaximum())

    c.Print("plots/mcStudy.pdf")
    """
Beispiel #28
0
def drawLine(x1, y1, x2, y2):
    line = TLine(x1, y1, x2, y2)
    line.SetLineStyle(2)
    line.SetLineWidth(2)
    line.Draw()
    return line
    # ____________________________________________________________________________
    # Setup basic drawer
    gROOT.LoadMacro("tdrstyle.C")
    gROOT.ProcessLine("setTDRStyle();")
    #gROOT.SetBatch(True)
    gStyle.SetPadGridX(True)
    gStyle.SetPadGridY(True)
    #gStyle.SetPadRightMargin(0.05)
    #gStyle.SetTitleOffset(0.9, "Y")
    #gStyle.SetTitleOffset(1.2, "Y")
    gROOT.ForceStyle()

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

    tlatexCMS1 = TLatex()
    tlatexCMS1.SetNDC()
    tlatexCMS1.SetTextFont(61)
    tlatexCMS1.SetTextSize(0.75 * 0.05)

    tlatexCMS2 = TLatex()
    tlatexCMS2.SetNDC()
    tlatexCMS2.SetTextFont(52)
    tlatexCMS2.SetTextSize(0.60 * 0.05)

    tlatexCMS3 = TLatex()
    tlatexCMS3.SetNDC()
    tlatexCMS3.SetTextFont(42)
    tlatexCMS3.SetTextSize(0.60 * 0.05)
Beispiel #30
0
    def __plot_profiles_in_same_canvas(self, hist_objs, hist_names, legends,
                                       y_limits, **kwargs):

        legend_position = retrieve_kw(kwargs, 'legend_position',
                                      (0.36, 0.20, 0.66, 0.36))
        legend_prefix = retrieve_kw(kwargs, 'legend_prefix',
                                    'Z#rightarrowee, ')
        legend_header = retrieve_kw(kwargs, 'legend_header', 'Trigger step')
        ylabel = retrieve_kw(kwargs, 'ylabel', 'Trigger Efficiency')
        title = retrieve_kw(kwargs, 'title', 'Trigger Efficiency')
        oname = retrieve_kw(kwargs, 'oname', 'plot_efficiencys')
        column = retrieve_kw(kwargs, 'column', 2)
        doRatio = retrieve_kw(kwargs, 'doRatio', False)
        canvas_size = retrieve_kw(kwargs, 'canvas_size', (1800, 1500))
        # FIXME: This must be disable for now, there is some problem into the xaxis scale
        # The top and bot axis must be match!
        tobject_collector = []
        ratio_size_as_fraction = 0.35

        from ROOT import TCanvas, TLegend, TProfile, TPad
        rows = int(round(len(hist_objs) / float(column)))
        canvas = TCanvas('canvas', 'canvas', canvas_size[0], canvas_size[1])
        canvas.Divide(rows, column)
        leg_holder = []
        for index, hist_str in enumerate(hist_names):
            hists = hist_objs[hist_str]
            pad = canvas.cd(index + 1)
            # Force disable if != of 2
            if len(hists) != 2:
                doRatio = False

            if doRatio:
                drawopt = 'pE1'
                pad.cd()
                top = TPad("pad_top", "This is the top pad", 0.0,
                           ratio_size_as_fraction, 1.0, 1.0)
                top.SetBottomMargin(0.0)
                top.SetBottomMargin(0.06 / float(top.GetHNDC()))
                #top.SetTopMargin   (0.04/float(top.GetHNDC()))
                top.SetRightMargin(0.05)
                top.SetLeftMargin(0.16)
                top.SetFillColor(0)
                top.Draw(drawopt)
                tobject_collector.append(top)
                pad.cd()
                bot = TPad("pad_bot", "This is the bottom pad", 0.0, 0.0, 1.0,
                           ratio_size_as_fraction)
                bot.SetBottomMargin(0.10 / float(bot.GetHNDC()))
                #bot.SetTopMargin   (0.02/float(bot.GetHNDC()))
                bot.SetTopMargin(0.0)
                bot.SetRightMargin(0.05)
                bot.SetLeftMargin(0.16)
                bot.SetFillColor(0)
                bot.Draw(drawopt)
                tobject_collector.append(bot)

            if type(legend_prefix) is not list:
                legend_prefix = [legend_prefix] * len(legends)

            if doRatio:
                top.cd()

            leg = TLegend(legend_position[0], legend_position[1],
                          legend_position[2], legend_position[3])

            from AtlasStyle import setLegend1, atlas_template
            setLegend1(leg)
            leg.SetHeader(legend_header)

            for i, eff in enumerate(hists):
                eff.SetLineColor(self._curve_color[i])
                eff.SetMarkerColor(self._curve_color[i])
                eff.SetMarkerStyle(self._marker_style[i])
                if type(eff) is TProfile: eff.SetStats(0)
                leg.AddEntry(eff, legend_prefix[i] + legends[i], 'p')
                if i is 0: eff.Draw()
                else: eff.Draw('same')

            leg.SetTextSize(0.03)
            leg.SetBorderSize(0)
            leg.Draw()

            if doRatio:
                top.Modified()
                top.Update

            pad.Modified()
            pad.Update()

            from ROOT import TProfile, TEfficiency, kFALSE
            xmin = 0
            xmax = 999

            if type(hists[0]) is TProfile:
                hists[0].GetYaxis().SetRangeUser(y_limits[index][0],
                                                 y_limits[index][1])
            elif type(hists[0]) is TEfficiency:
                hists[0].GetPaintedGraph().GetYaxis().SetRangeUser(
                    y_limits[index][0], y_limits[index][1])
                hists[0].GetPaintedGraph().GetYaxis().SetTitle('A')

                # Fix the X axis
                nbins = hists[0].GetTotalHistogram().GetNbinsX()
                xmin = hists[0].GetTotalHistogram().GetXaxis().GetBinLowEdge(1)
                xmax = hists[0].GetTotalHistogram().GetXaxis().GetBinLowEdge(
                    nbins + 1)
                hists[0].GetPaintedGraph().GetXaxis().SetLimits(xmin, xmax)
            else:
                hists[0].GetYaxis().SetRangeUser(y_limits[index][0],
                                                 y_limits[index][1])

            pad.Modified()
            pad.Update()
            tobject_collector.append(leg)

            if doRatio:
                atlas_template(top, **kwargs)
                top.Update()
                from ROOT import TH1
                divide = ""
                drawopt = 'pE1'
                bot.cd()
                ref = hists[0].GetPassedHistogram().Clone()
                h = hists[1].GetPassedHistogram().Clone()
                #ref = hists[0].Clone()
                #h = hists[1].Clone()
                ref.Sumw2()
                h.Sumw2()
                ref.Divide(hists[0].GetTotalHistogram().Clone())
                h.Divide(hists[1].GetTotalHistogram().Clone())
                #ratioplot = TEfficiency(h,ref)
                ratioplot = h.Clone()
                ratioplot.Sumw2()
                ratioplot.SetName(h.GetName() + '_ratio')
                ratioplot.Divide(h, ref, 1., 1., '')
                #ratioplot.Divide(ref)
                ratioplot.SetFillColor(0)
                ratioplot.SetFillStyle(0)
                ratioplot.SetMarkerColor(1)
                ratioplot.SetLineColor(kBlack)
                ratioplot.SetMarkerStyle(24)
                ratioplot.SetMarkerSize(1.2)
                ratioplot.GetYaxis().SetTitle('trigger / ref')
                ratioplot.GetYaxis().SetTitleSize(0.10)
                ratioplot.GetXaxis().SetTitleSize(0.10)
                ratioplot.GetXaxis().SetLabelSize(0.10)
                ratioplot.GetYaxis().SetLabelSize(0.10)
                ratioplot.GetYaxis().SetRangeUser(0.9, 1.07)
                ratioplot.Draw(drawopt)
                tobject_collector.append(ratioplot)
                #atlas_template(bot, **kwargs)
                from ROOT import TLine
                l1 = TLine(xmin, 1, xmax, 1)
                l1.SetLineColor(kRed)
                l1.SetLineStyle(2)
                l1.Draw()
                tobject_collector.append(l1)
                bot.Update()
            else:
                atlas_template(pad, **kwargs)
            pad.Update()

        canvas.SaveAs(oname + '.pdf')