W_ss_Data = FULL_mt_ss.Hist('Data - DY - TT').weighted
    W_ss_WJets.GetXaxis().SetTitle('mt')
    W_ss_Data.GetXaxis().SetTitle('mt')
    W_ss_WJets.Draw('hist')
    W_ss_Data.Draw('same')
    leg_W_ss = TLegend(0.6, 0.6, 0.9, 0.9)
    leg_W_ss.AddEntry(W_ss_Data, 'data - DY - TT', 'pl')
    leg_W_ss.AddEntry(W_ss_WJets, 'WJets', 'pl')
    leg_W_ss.Draw()

    p_ratio.cd()
    W_ss_Data_ratio = W_ss_Data.Clone('W_ss_Data_ratio')
    W_ss_WJets_ratio = W_ss_WJets.Clone('W_ss_WJets_ratio')
    W_ss_Data_ratio.Divide(W_ss_WJets)
    W_ss_WJets_ratio.Divide(W_ss_WJets)
    p_ratio.DrawFrame(W_ss_WJets_ratio.GetXaxis().GetXmin(), 0.5,
                      W_ss_WJets_ratio.GetXaxis().GetXmax(), 2)
    W_ss_Data_ratio.Draw('same')
    W_ss_WJets_ratio.SetFillStyle(4001)
    W_ss_WJets_ratio.SetFillColor(2)
    W_ss_WJets_ratio.SetMarkerStyle(9)
    W_ss_WJets_ratio.Draw('samehist')
    W_ss_WJets_ratio.Draw('sameE3')
    can0.Print('compare_W_ss.png', 'png')

    FULL_mt_ss.Group('EWK', ['WJets', 'Ztt_ZJ', 'VV'])
    FULL_mt_ss.Group('Higgs 125', ['HiggsVBF125', 'HiggsGGH125', 'HiggsVH125'])
    draw(FULL_mt_ss, False, 'TauEle', plotprefix='MT_ss')

    #PG (TEST) remake the WJets plots over the full range for OS
    #PG ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
    #PG with the binning I want
def main():


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


	for pdf in pdfs:

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


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

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

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

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

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

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

		canv.Print("pdfUncertainty_%s.pdf"%pdf)
def compareMassRes(trackType):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    leg.Draw()

    plotPad.RedrawAxis()

    #~ ratioPad.cd()

    #~ ratioBB.SetLineColor(kRed)

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

    #~ ratioBB.Draw("samepe")

    canv.Print("chi2CompareVsPt_%s_BE16.pdf" % trackType)
def signalRegion(path, selection, plots, runRange, backgrounds, cmsExtra):

    for name in plots:
        plot = getPlot(name)
        plot.addRegion(selection)
        #~ plot.cleanCuts()
        plot.cuts = plot.cuts % runRange.runCut
        plot.cuts = plot.cuts.replace("weight*", "")
        print runRange.lumi
        #~ plot.cuts = plot.cuts+"*!((abs(motherPdgId1) == 15 || abs(motherPdgId1) == 24 || abs(motherPdgId1) == 23) && (abs(motherPdgId2) == 15 || abs(motherPdgId2) == 24 || abs(motherPdgId2) == 23))"
        #~ plot.cuts = plot.cuts+"*!(abs(motherPdgId1) == 15 || abs(motherPdgId1) == 24 || abs(motherPdgId1) == 23 || abs(motherPdgId2) == 15 || abs(motherPdgId2) == 24 || abs(motherPdgId2) == 23)"
        #~ plot.cuts = plot.cuts+"*!((abs(motherPdgId1) != 15 && abs(motherPdgId1) != 24 && abs(motherPdgId1) != 23) || (abs(motherPdgId2) != 15 && abs(motherPdgId2) != 24 && abs(motherPdgId2) != 23))"
        #~ plot.cuts = plot.cuts+"*((abs(pdgId1) != 11 && abs(pdgId1) != 13 && abs(pdgId1) != 15) || ( abs(pdgId2) != 11 && abs(pdgId2) != 13 && abs(pdgId2) != 15))"
        if not "Forward" in selection.name:
            corr = rSFOF.central.val
            corrErr = rSFOF.central.err
            if "Central" in selection.name:
                region = "central"
            else:
                region = "inclusive"
        else:
            corr = rSFOF.forward.val
            corrErr = rSFOF.forward.err
            region = "forward"
        #~
        #~ eventCounts = totalNumberOfGeneratedEvents(path)


#~
#~ for background in backgrounds:
#~ process = Process(getattr(Backgrounds,background),eventCounts)
#~ for subprocess in process.samples:
#~
#~ print subprocess
#~ treeEE, treeMM, treeEM = getTrees(path,plot,runRange, subprocess,region)
#~ for ev in treeMM:
#~
#~ print ev.motherPdgId1, ev.motherPdgId2

#~ print treeEE.GetEntries(), treeMM.GetEntries(), treeEM.GetEntries()
        histEE, histMM, histOF = getHistograms(path, plot, runRange,
                                               backgrounds, region)
        print histEE.Integral(), histMM.Integral(), histOF.Integral()
        print histEE.GetEntries(), histMM.GetEntries(), histOF.GetEntries()
        hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)
        plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1)

        style = setTDRStyle()
        plotPad.UseCurrentStyle()
        plotPad.Draw()
        plotPad.cd()
        logScale = plot.log
        if plot.variable == "met" or plot.variable == "type1Met" or plot.variable == "tcMet" or plot.variable == "caloMet" or plot.variable == "mht":
            logScale = True

        yMax = histEE.GetBinContent(
            histEE.GetMaximumBin()) + histMM.GetBinContent(
                histMM.GetMaximumBin())

        if logScale:
            yMax = yMax * 1000
        else:
            yMax = yMax * 1.5

        #~ else: yMax = plot.yMax

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

        histSF = histEE.Clone("histSF")
        histSF.Add(histMM.Clone())

        histSF.SetMarkerStyle(20)
        histOF.SetLineColor(ROOT.kBlue)
        histEE.SetLineColor(ROOT.kRed)
        histMM.SetLineColor(ROOT.kGreen + 3)
        histEE.SetLineStyle(ROOT.kDashed)
        histMM.SetLineStyle(ROOT.kDashed)

        histSF.Draw("samep")
        histOF.Draw("samehist")
        histEE.Draw("samehist")
        histMM.Draw("samehist")

        latex = ROOT.TLatex()
        latex.SetTextSize(0.04)
        latex.SetNDC(True)

        legend = TLegend(0.5, 0.6, 0.95, 0.95)
        legend.SetFillStyle(0)
        legend.SetBorderSize(0)
        entryHist = TH1F()
        entryHist.SetFillColor(ROOT.kWhite)
        legend.AddEntry(entryHist, selection.latex, "h")
        legend.AddEntry(histSF, "SF", "p")
        legend.AddEntry(histEE, "EE", "l")
        legend.AddEntry(histMM, "MM", "l")
        legend.AddEntry(histOF, "OF", "l")

        legend.Draw("same")

        latex = ROOT.TLatex()
        latex.SetTextFont(42)
        latex.SetNDC(True)
        latex.SetTextAlign(31)
        latex.SetTextSize(0.04)

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

        latexCMS = ROOT.TLatex()
        latexCMS.SetTextFont(61)
        latexCMS.SetTextSize(0.06)
        latexCMS.SetNDC(True)
        latexCMSExtra = ROOT.TLatex()
        latexCMSExtra.SetTextFont(52)
        latexCMSExtra.SetTextSize(0.045)
        latexCMSExtra.SetNDC(True)

        latexCMS.DrawLatex(0.19, 0.89, "CMS")
        if "Simulation" in cmsExtra:
            yLabelPos = 0.82
        else:
            yLabelPos = 0.85

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

        plotPad.RedrawAxis()
        hCanvas.Print("fig/nonPromptMC_%s_%s_%s_%s.pdf" %
                      (selection.name, runRange.label, plot.variablePlotName,
                       plot.additionalName))
def comparePtRes(trackType):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    leg.Draw()

    plotPad.RedrawAxis()

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

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

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

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

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

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

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

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

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

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

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

    leg.Draw()

    plotPad.RedrawAxis()

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

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

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

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

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

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

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

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

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

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

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

    leg.Draw()

    plotPad.RedrawAxis()

    canv.Print("PtResolutionCompare_%s_2018.pdf" % trackType)
    canv.Print("PtResolutionCompare_%s_2018.root" % trackType)
示例#6
0
def fakeRate(path, selection, plots, runRange, cmsExtra):

    for name in plots:
        plot = getPlot(name)
        plot.addRegion(selection)
        plot.cuts = plot.cuts % runRange.runCut

        if "Pt" in name:
            plot.variable = "pt"
        elif "Eta" in name:
            plot.variable = "eta"

        if "met" in name:
            plot.cuts = "abs(eta) < 2.4 && (abs(eta) < 1.4 || abs(eta) > 1.6) && ptJet1 > 50 && mT < 20 &&  nLept == 1 && pfIso < 1.0"
        else:
            plot.cuts = "abs(eta) < 2.4 && (abs(eta) < 1.4 || abs(eta) > 1.6) && ptJet1 > 50 && mT < 20 &&  nLept == 1 && pfIso < 1.0 && met < 20"

        if not "Forward" in selection.name:
            corr = rSFOF.central.val
            corrErr = rSFOF.central.err
            if "Central" in selection.name:
                region = "central"
            else:
                region = "inclusive"
        else:
            corr = rSFOF.forward.val
            corrErr = rSFOF.forward.err
            region = "forward"

        histsLoose = getHistograms(path, plot, runRange)
        if "met" in name:
            plot.cuts = "abs(eta) < 2.4 && (abs(eta) < 1.4 || abs(eta) > 1.6) && ptJet1 > 50 && mT < 20 &&  nLept == 1 && pfIso < 0.15"
        else:
            plot.cuts = "abs(eta) < 2.4 && (abs(eta) < 1.4 || abs(eta) > 1.6) && ptJet1 > 50 && mT < 20 &&  nLept == 1 && pfIso < 0.15 && met < 20 "

        histsTight = getHistograms(path, plot, runRange)

        for index, histLoose in enumerate(histsLoose):

            histTight = histsTight[index]

            print histTight.GetEntries(), histLoose.GetEntries()

            hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)
            plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1)

            style = setTDRStyle()
            plotPad.UseCurrentStyle()
            plotPad.Draw()
            plotPad.cd()
            logScale = plot.log

            plotPad.DrawFrame(plot.firstBin, 0, plot.lastBin, 1,
                              "; %s ; %s" % (plot.xaxis, "fake rate"))

            fakeRate = TGraphAsymmErrors(histTight, histLoose, "cp")

            fakeRate.SetMarkerStyle(20)

            fakeRate.Draw("samep")

            latex = ROOT.TLatex()
            latex.SetTextSize(0.04)
            latex.SetNDC(True)

            legend = TLegend(0.55, 0.825, 0.95, 0.95)
            legend.SetFillStyle(0)
            legend.SetBorderSize(0)
            entryHist = TH1F()
            entryHist.SetFillColor(ROOT.kWhite)
            #~ legend.AddEntry(entryHist,selection.latex,"h")
            legend.AddEntry(fakeRate, "fake rate", "pe")

            #~ legend.Draw("same")

            latex = ROOT.TLatex()
            latex.SetTextFont(42)
            latex.SetNDC(True)
            latex.SetTextAlign(31)
            latex.SetTextSize(0.04)

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

            latexCMS = ROOT.TLatex()
            latexCMS.SetTextFont(61)
            latexCMS.SetTextSize(0.06)
            latexCMS.SetNDC(True)
            latexCMSExtra = ROOT.TLatex()
            latexCMSExtra.SetTextFont(52)
            latexCMSExtra.SetTextSize(0.045)
            latexCMSExtra.SetNDC(True)

            latexCMS.DrawLatex(0.19, 0.89, "CMS")
            if "Simulation" in cmsExtra:
                yLabelPos = 0.82
            else:
                yLabelPos = 0.85

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

            plotPad.RedrawAxis()
            if index == 0:
                hCanvas.Print("fig/fakeRate_ele_%s_%s_%s_%s.pdf" %
                              (selection.name, runRange.label,
                               plot.variablePlotName, plot.additionalName))
            else:
                hCanvas.Print("fig/fakeRate_mu_%s_%s_%s_%s.pdf" %
                              (selection.name, runRange.label,
                               plot.variablePlotName, plot.additionalName))
示例#7
0
def promptRateCentral(path, selection, plots, runRange, cmsExtra):

    f = TFile("promptRates.root", "RECREATE")

    ptBins = [20, 25, 30, 35, 40, 50, 60, 70, 10000]
    etaBins = [0, 0.3, 0.6, 0.9, 1.2, 1.442, 1.562, 1.9, 2.2, 2.4]

    promptRateE = ROOT.TH2F("promptRateE", "",
                            len(ptBins) - 1, array("f", ptBins),
                            len(etaBins) - 1, array("f", etaBins))
    promptRateM = ROOT.TH2F("promptRateM", "",
                            len(ptBins) - 1, array("f", ptBins),
                            len(etaBins) - 1, array("f", etaBins))

    plot = getPlot("trailingPtPlot")
    plot.addRegion(selection)
    plot.cuts = plot.cuts % runRange.runCut

    #~ plot.variable = "pt1"

    plot.cuts = plot.cuts + "*(ht > 80 && id1 < 1.0 && id2 < 0.15 && nLightLeptons == 2 && p4.M() > 76 && p4.M() < 106 && met < 20)"

    histsLoose = get2DHistogramsPrompt(path, plot.cuts, ptBins, etaBins)

    plot.cuts = plot.cuts + "*(ht > 80 && id1 < 0.15 && id2 < 0.15 && nLightLeptons == 2 && p4.M() > 76 && p4.M() < 106 && met < 20)"

    histsTight = get2DHistogramsPrompt(path, plot.cuts, ptBins, etaBins)

    histsTight[0].Divide(histsLoose[0])
    histsTight[1].Divide(histsLoose[1])

    promptRateE.Add(histsTight[0].Clone())
    promptRateM.Add(histsTight[1].Clone())

    hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)
    plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1)

    style = setTDRStyle()
    style.SetPadRightMargin(0.2)
    plotPad.UseCurrentStyle()
    plotPad.Draw()
    plotPad.cd()
    logScale = plot.log

    plotPad.DrawFrame(0., 0., 200, 2.4,
                      "; %s ; %s" % ("trailing p_{T} [GeV]", "trailing #eta"))

    histsTight[0].Draw("samecolz")

    latex = ROOT.TLatex()
    latex.SetTextFont(42)
    latex.SetNDC(True)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)

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

    latexCMS = ROOT.TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.06)
    latexCMS.SetNDC(True)
    latexCMSExtra = ROOT.TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.045)
    latexCMSExtra.SetNDC(True)

    latexCMS.DrawLatex(0.19, 0.89, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.82
    else:
        yLabelPos = 0.85

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

    plotPad.RedrawAxis()
    hCanvas.Print("fig/promptRate_ele.pdf")

    plotPad.DrawFrame(0., 0., 200, 2.4,
                      "; %s ; %s" % ("trailing p_{T} [GeV]", "trailing #eta"))

    histsTight[1].Draw("samecolz")

    latex = ROOT.TLatex()
    latex.SetTextFont(42)
    latex.SetNDC(True)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)

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

    latexCMS = ROOT.TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.06)
    latexCMS.SetNDC(True)
    latexCMSExtra = ROOT.TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.045)
    latexCMSExtra.SetNDC(True)

    latexCMS.DrawLatex(0.19, 0.89, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.82
    else:
        yLabelPos = 0.85

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

    plotPad.RedrawAxis()
    hCanvas.Print("fig/promptRate_mu.pdf")

    f.Write()
    f.Close()
示例#8
0
def makeTwoScalesGraph(file):
    print(file)
    ch1 = OPData.fromPath('../data/part3/%s' % file, 1)
    ch2 = OPData.fromPath('../data/part3/%s' % file, 2)

    print('make canvas + pad')
    c = TCanvas('c-%s' % file, '', 1280, 720)
    pad = TPad('pad-%s' % file, '', 0, 0, 1, 1)
    pad.Draw()
    pad.cd()

    print('frame')
    frame = pad.DrawFrame(0,
                          min(ch1.getY()) * 1.1, 0.051,
                          max(ch1.getY()) * 1.1)
    frame.SetXTitle('Zeit t / s')
    frame.GetXaxis().CenterTitle()
    frame.SetYTitle('Spannung Spule 2: U_{2} / V')
    frame.GetYaxis().CenterTitle()
    frame.GetYaxis().SetLabelColor(4)
    frame.GetYaxis().SetTitleColor(4)

    print('g1')
    g1 = ch1.makeGraph('g1-%s' % file)
    prepareGraph(g1)
    g1.Draw('PX')

    print('overlay')
    c.cd()
    overlay = TPad('overlay-%s' % file, '', 0, 0, 1, 1)
    overlay.SetFillStyle(4000)  # transparent
    overlay.SetFillColor(0)  # white
    overlay.SetFrameFillStyle(4000)  # transparent
    overlay.Draw()
    overlay.cd()

    print('g2')
    g2 = ch2.makeGraph('g2-%s' % file)
    prepareGraph(g2, 2)
    g2ymin = min(ch2.getY())
    xmin = pad.GetUxmin()
    xmax = pad.GetUxmax()
    ymin = 1.1 * g2ymin
    ymax = abs(ymin)
    if file == '07.tab':  # same scale like 06.tab
        ymin, ymax = -0.07128, 0.07128
    oframe = overlay.DrawFrame(xmin, ymin, xmax, ymax)
    oframe.GetXaxis().SetLabelOffset(99)
    oframe.GetYaxis().SetLabelOffset(99)
    oframe.GetYaxis().SetTickLength(0)
    g2.Draw('PX')

    print('axis')
    axis = TGaxis(xmax, ymin, xmax, ymax, ymin, ymax, 510, "+L")
    axis.SetTitle('Spannung Photodiode: U_{ph} / V')
    axis.CenterTitle()
    axis.SetTitleOffset(1.2)
    axis.Draw()

    print('print')
    c.Update()
    c.Print('../img/part3/%s.pdf' % file[:-4], 'pdf')
IDHist3.SetLineColor(kBlack)
IDHist4.SetLineColor(kOrange + 1)
IDHist5.SetLineColor(kGreen + 3)

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

plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1)
#~ ratioPad = ROOT.TPad("ratioPad","ratioPad",0,0.,1,0.3)
setTDRStyle()
plotPad.UseCurrentStyle()
#~ ratioPad.UseCurrentStyle()
plotPad.Draw()
#~ ratioPad.Draw()
plotPad.cd()

plotPad.DrawFrame(0.9, 0, 1.1, 20,
                  "; impact of scale systematic; Signal models")

scaleHist1.Draw("samehist")
scaleHist2.Draw("samehist")
scaleHist3.Draw("samehist")
scaleHist4.Draw("samehist")
scaleHist5.Draw("samehist")

legend = TLegend(0.5, 0.7, 0.925, 0.925)
legend.SetFillStyle(0)
legend.SetBorderSize(0)
legend.SetTextFont(42)
legend.AddEntry(scaleHist1, "400-500 GeV", "l")
legend.AddEntry(scaleHist2, "500-700 GeV", "l")
legend.AddEntry(scaleHist3, "700-1100 GeV", "l")
legend.AddEntry(scaleHist4, "1100-1900 GeV", "l")
示例#10
0
def signalRegion(path, selection, plots, runRange, isMC, backgrounds,
                 cmsExtra):
    plots = ["mllPlotRMuESignal"]
    for name in plots:
        plot = getPlot(name)
        plot.addRegion(selection)
        #~ plot.cleanCuts()
        plot.cuts = plot.cuts % runRange.runCut

        if not "Forward" in selection.name:
            corr = rSFOF.central.val
            corrErr = rSFOF.central.err
            if "Central" in selection.name:
                region = "central"
            else:
                region = "inclusive"
        else:
            corr = rSFOF.forward.val
            corrErr = rSFOF.forward.err
            region = "forward"

        histEE, histMM, histEM = getHistograms(path,
                                               plot,
                                               runRange,
                                               isMC,
                                               backgrounds,
                                               region,
                                               EM=True)

        rMuEMeasured = rMuEMeasure(histEE, histMM)
        rMuE, rMuEUncert = rMuEFromSFOF(histEE, histMM, histEM, corr, corrErr)

        hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)
        plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1)

        style = setTDRStyle()
        plotPad.UseCurrentStyle()
        plotPad.Draw()
        plotPad.cd()

        plotPad.DrawFrame(plot.firstBin, 0, plot.lastBin, 5,
                          "; %s ; %s" % (plot.xaxis, "r_{#mu e}"))
        latex = ROOT.TLatex()
        latex.SetTextSize(0.04)
        latex.SetNDC(True)

        if "Central" in selection.name:
            centralName = "ZPeakControlCentral"
        elif "Forward" in selection.name:
            centralName = "ZPeakControlForward"
        else:
            centralName = "ZPeakControl"

        if os.path.isfile("shelves/rMuE_%s_%s.pkl" %
                          (centralName, runRange.label)):
            centralVals = pickle.load(
                open("shelves/rMuE_%s_%s.pkl" % (centralName, runRange.label),
                     "rb"))
        else:
            centralVals = centralValues(path, getRegion(centralName), runRange,
                                        False, backgrounds)

        x = array("f", [plot.firstBin, plot.lastBin])
        y = array("f", [centralVals["rMuE"], centralVals["rMuE"]])
        ex = array("f", [0., 0.])
        ey = array("f",
                   [centralVals["rMuESystErr"], centralVals["rMuESystErr"]])
        ge = ROOT.TGraphErrors(2, x, y, ex, ey)
        ge.SetFillColor(ROOT.kOrange - 9)
        ge.SetFillStyle(1001)
        ge.SetLineColor(ROOT.kWhite)
        ge.Draw("SAME 3")

        rmueLine = ROOT.TF1("rmueline", "%f" % centralVals["rMuE"],
                            plot.firstBin, plot.lastBin)
        rmueLine.SetLineColor(ROOT.kOrange + 3)
        rmueLine.SetLineWidth(3)
        rmueLine.SetLineStyle(2)
        rmueLine.Draw("SAME")

        arrayRMuEHigh = array("f", rMuE["up"])
        arrayRMuELow = array("f", rMuE["down"])
        arrayRMuEMeasured = array("f", rMuEMeasured["vals"])
        arrayRMuEHighUncert = array("f", rMuEUncert["up"])
        arrayRMuELowUncert = array("f", rMuEUncert["down"])
        arrayRMuEMeasuredUncert = array("f", rMuEMeasured["errs"])
        xValues = []
        xValuesUncert = []

        for x in range(0, histEE.GetNbinsX()):
            xValues.append(plot.firstBin +
                           (plot.lastBin - plot.firstBin) / plot.nBins + x *
                           ((plot.lastBin - plot.firstBin) / plot.nBins))
            xValuesUncert.append(0)

        arrayXValues = array("f", xValues)
        arrayXValuesUncert = array("f", xValuesUncert)

        graphHigh = ROOT.TGraphErrors(histEE.GetNbinsX(), arrayXValues,
                                      arrayRMuEHigh, arrayXValuesUncert,
                                      arrayRMuEHighUncert)
        graphLow = ROOT.TGraphErrors(histEE.GetNbinsX(), arrayXValues,
                                     arrayRMuELow, arrayXValuesUncert,
                                     arrayRMuEHighUncert)
        graphMeasured = ROOT.TGraphErrors(histEE.GetNbinsX(), arrayXValues,
                                          arrayRMuEMeasured,
                                          arrayXValuesUncert,
                                          arrayRMuEMeasuredUncert)

        graphHigh.SetMarkerStyle(21)
        graphLow.SetMarkerStyle(22)
        graphMeasured.SetMarkerStyle(23)
        graphHigh.SetMarkerColor(ROOT.kRed)
        graphLow.SetMarkerColor(ROOT.kBlue)
        graphHigh.SetLineColor(ROOT.kRed)
        graphLow.SetLineColor(ROOT.kBlue)

        graphHigh.Draw("sameEP0")
        graphLow.Draw("sameEP0")
        graphMeasured.Draw("sameEP0")

        legend = TLegend(0.5, 0.6, 0.95, 0.95)
        legend.SetFillStyle(0)
        legend.SetBorderSize(0)
        entryHist = TH1F()
        entryHist.SetFillColor(ROOT.kWhite)
        legend.AddEntry(entryHist, selection.latex, "h")
        legend.AddEntry(
            graphHigh,
            "r_{#mu e} = N_{SF}/N_{OF} + #sqrt{(N_{SF}/N_{OF})^{2} -1}", "p")
        legend.AddEntry(
            graphLow,
            "r_{#mu e} = N_{SF}/N_{OF} - #sqrt{(N_{SF}/N_{OF})^{2} -1}", "p")
        legend.AddEntry(rmueLine, "r_{#mu e} from Z peak", "l")
        legend.AddEntry(ge, "Syst. Uncert. of r_{#mu e}", "f")
        legend.AddEntry(
            graphMeasured,
            "r_{#mu e} = #sqrt{N_{#mu#mu}/N_{ee}} in SF signal region", "p")

        legend.Draw("same")

        latex = ROOT.TLatex()
        latex.SetTextFont(42)
        latex.SetNDC(True)
        latex.SetTextAlign(31)
        latex.SetTextSize(0.04)

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

        latexCMS = ROOT.TLatex()
        latexCMS.SetTextFont(61)
        latexCMS.SetTextSize(0.06)
        latexCMS.SetNDC(True)
        latexCMSExtra = ROOT.TLatex()
        latexCMSExtra.SetTextFont(52)
        latexCMSExtra.SetTextSize(0.045)
        latexCMSExtra.SetNDC(True)

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

        plotPad.RedrawAxis()
        if isMC:
            hCanvas.Print("fig/rMuESignal_%s_%s_%s_%s_MC.pdf" %
                          (selection.name, runRange.label,
                           plot.variablePlotName, plot.additionalName))
        else:
            hCanvas.Print("fig/rMuESignal_%s_%s_%s_%s.pdf" %
                          (selection.name, runRange.label,
                           plot.variablePlotName, plot.additionalName))
def compareMassRes(trackType):

    file2016BB = open("default/MassResolutionVsMass_%s_BB.pkl" % trackType,
                      "rb")
    file2016BE = open("default/MassResolutionVsMass_%s_BE.pkl" % trackType,
                      "rb")
    file2017BB = open("cruijff/MassResolutionVsMass_%s_BB.pkl" % trackType,
                      "rb")
    file2017BE = open("cruijff/MassResolutionVsMass_%s_BE.pkl" % trackType,
                      "rb")
    fileCBB = open("crystal/MassResolutionVsMass_%s_BB.pkl" % trackType, "rb")
    fileCBE = open("crystal/MassResolutionVsMass_%s_BE.pkl" % trackType, "rb")

    results2016BB = pickle.load(file2016BB)
    results2016BE = pickle.load(file2016BE)
    results2017BB = pickle.load(file2017BB)
    results2017BE = pickle.load(file2017BE)
    resultsCBB = pickle.load(fileCBB)
    resultsCBE = pickle.load(fileCBE)

    graph2016BB = getGraph(results2016BB, "DCBBB")
    graph2016BE = getGraph(results2016BE, "DCBBE")
    graph2017BB = getGraph(results2017BB, "CruijffBB")
    graph2017BE = getGraph(results2017BE, "CruijffBE")
    graphCBB = getGraph(resultsCBB, "CBB")
    graphCBE = getGraph(resultsCBE, "CBE")

    ratioBB = getRatio(results2016BB, results2017BB, "ratioBB")
    ratioBE = getRatio(results2016BE, results2017BE, "ratioBE")
    ratioCBB = getRatio(results2016BB, resultsCBB, "ratioCBB")
    ratioCBE = getRatio(results2016BE, resultsCBE, "ratioCBE")

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

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

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

    plotPad.DrawFrame(0, 0, 6000, xMax, ";M [GeV]; mass resolution")

    graph2016BB.Draw("samepe")
    graph2017BB.Draw("samepe")
    graphCBB.Draw("samepe")
    graph2017BB.SetLineColor(kRed)
    graph2017BB.SetMarkerColor(kRed)
    graphCBB.SetLineColor(kBlue)
    graphCBB.SetMarkerColor(kBlue)

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

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

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

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

    leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s BB" % trackType, "brNDC")
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    leg.AddEntry(graph2016BB, "Cruijff", "l")
    leg.AddEntry(graph2017BB, "Double CB", "l")
    leg.AddEntry(graphCBB, "Crystal Ball", "l")

    leg.Draw()

    plotPad.RedrawAxis()

    ratioPad.cd()

    ratioBB.SetLineColor(kRed)
    ratioCBB.SetLineColor(kBlue)

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

    ratioBB.Draw("samepe")
    ratioCBB.Draw("samepe")

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

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

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

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

    plotPad.DrawFrame(0, 0, 6000, xMax, ";M [GeV]; mass resolution")

    graph2016BE.Draw("samepe")
    graph2017BE.Draw("samepe")
    graphCBE.Draw("samepe")
    graph2017BE.SetLineColor(kRed)
    graph2017BE.SetMarkerColor(kRed)
    graphCBE.SetLineColor(kBlue)
    graphCBE.SetMarkerColor(kBlue)

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

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

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

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

    leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s BE" % trackType, "brNDC")
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    leg.AddEntry(graph2016BE, "Cruijff", "l")
    leg.AddEntry(graph2017BE, "Double CB", "l")
    leg.AddEntry(graphCBE, "Crystal Ball", "l")

    leg.Draw()

    plotPad.RedrawAxis()

    ratioPad.cd()

    ratioBE.SetLineColor(kRed)
    ratioCBE.SetLineColor(kBlue)

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

    ratioBE.Draw("samepe")
    ratioCBE.Draw("samepe")

    canv.Print("massResolutionCompareFunc_%s_BE.pdf" % trackType)
示例#12
0
def plotMllSpectra(SFhist, EMuhist, runRange, selection, suffix, cmsExtra,
                   additionalLabel):

    SFhist.Rebin(5)
    EMuhist.Rebin(5)

    hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)
    plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1)

    style = setTDRStyle()
    style.SetTitleYOffset(1.6)
    style.SetPadLeftMargin(0.19)
    plotPad.UseCurrentStyle()
    plotPad.Draw()
    plotPad.cd()

    plotPad.DrawFrame(20, 0, 300,
                      SFhist.GetBinContent(SFhist.GetMaximumBin()) * 1.5,
                      "; %s ; %s" % ("m_{ll} [GeV]", "Events / 5 GeV"))

    SFhist.SetMarkerStyle(20)
    SFhist.SetMarkerColor(ROOT.kBlack)

    EMuhist.Draw("samehist")
    SFhist.Draw("samepe")
    EMuhist.SetFillColor(855)
    legend = TLegend(0.6, 0.7, 0.95, 0.95)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    ROOT.gStyle.SetOptStat(0)
    legend.AddEntry(SFhist, "%s events" % suffix, "p")
    legend.AddEntry(EMuhist, "OF events", "f")
    legend.Draw("same")

    line1 = ROOT.TLine(mllBins.lowMass.low, 0, mllBins.lowMass.low,
                       SFhist.GetBinContent(SFhist.GetMaximumBin()))
    line2 = ROOT.TLine(mllBins.lowMass.high, 0, mllBins.lowMass.high,
                       SFhist.GetBinContent(SFhist.GetMaximumBin()))
    line3 = ROOT.TLine(mllBins.onZ.low, 0, mllBins.onZ.low,
                       SFhist.GetBinContent(SFhist.GetMaximumBin()))
    line4 = ROOT.TLine(mllBins.onZ.high, 0, mllBins.onZ.high,
                       SFhist.GetBinContent(SFhist.GetMaximumBin()))
    line5 = ROOT.TLine(mllBins.highMass.low, 0, mllBins.highMass.low,
                       SFhist.GetBinContent(SFhist.GetMaximumBin()))
    line1.SetLineColor(ROOT.kBlack)
    line2.SetLineColor(ROOT.kBlack)
    line3.SetLineColor(ROOT.kRed + 2)
    line4.SetLineColor(ROOT.kRed + 2)
    line5.SetLineColor(ROOT.kBlack)
    line1.SetLineWidth(2)
    line2.SetLineWidth(2)
    line3.SetLineWidth(2)
    line4.SetLineWidth(2)
    line5.SetLineWidth(2)
    line1.Draw("same")
    line2.Draw("same")
    line3.Draw("same")
    line4.Draw("same")
    line5.Draw("same")

    Labelin = ROOT.TLatex()
    Labelin.SetTextAlign(12)
    Labelin.SetTextSize(0.04)
    Labelin.SetTextColor(ROOT.kRed + 2)
    Labelout = ROOT.TLatex()
    Labelout.SetTextAlign(12)
    Labelout.SetTextSize(0.04)
    Labelout.SetTextColor(ROOT.kBlack)

    Labelin.DrawLatex(80.75,
                      SFhist.GetBinContent(SFhist.GetMaximumBin()) / 1.5, "In")
    Labelout.DrawLatex(27.25,
                       SFhist.GetBinContent(SFhist.GetMaximumBin()) / 1.5,
                       "Out")
    Labelout.DrawLatex(150.25,
                       SFhist.GetBinContent(SFhist.GetMaximumBin()) / 1.5,
                       "Out")

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

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

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

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

    plotPad.RedrawAxis()
    if additionalLabel is not "":
        hCanvas.Print(
            "fig/rOutIn_NoLog_%s_%s_%s_%s.pdf" %
            (selection.name, suffix, runRange.label, additionalLabel))
    else:
        hCanvas.Print("fig/rOutIn_NoLog_%s_%s_%s.pdf" %
                      (selection.name, suffix, runRange.label))

    hCanvas.Clear()

    plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1)

    style = setTDRStyle()
    plotPad.UseCurrentStyle()
    plotPad.Draw()
    plotPad.cd()

    plotPad.DrawFrame(mllBins.lowMass.low, 1, 300,
                      SFhist.GetBinContent(SFhist.GetMaximumBin()) * 10,
                      "; %s ; %s" % ("m_{ll} [GeV]", "Events / 5 GeV"))

    plotPad.SetLogy()

    EMuhist.Draw("samehist")
    SFhist.Draw("samepe")
    legend.Draw("same")

    line1.SetY2(SFhist.GetBinContent(SFhist.GetMaximumBin()))
    line2.SetY2(SFhist.GetBinContent(SFhist.GetMaximumBin()))
    line3.SetY2(SFhist.GetBinContent(SFhist.GetMaximumBin()))
    line4.SetY2(SFhist.GetBinContent(SFhist.GetMaximumBin()))
    line5.SetY2(SFhist.GetBinContent(SFhist.GetMaximumBin()))
    line1.Draw("same")
    line2.Draw("same")
    line3.Draw("same")
    line4.Draw("same")
    line5.Draw("same")
    Labelin.SetTextAngle(90)
    Labelin.DrawLatex(89.35,
                      SFhist.GetBinContent(SFhist.GetMaximumBin()) / 18,
                      "on Z")
    Labelout.SetTextAngle(90)
    Labelout.DrawLatex(47.25,
                       SFhist.GetBinContent(SFhist.GetMaximumBin()) / 18,
                       "low mass")
    #~ Labelout.DrawLatex(75.25,SFhist.GetBinContent(SFhist.GetMaximumBin())/18,"below Z")
    #~ Labelout.DrawLatex(109.25,SFhist.GetBinContent(SFhist.GetMaximumBin())/18,"above Z")
    Labelout.DrawLatex(150.25,
                       SFhist.GetBinContent(SFhist.GetMaximumBin()) / 18,
                       "high mass")
    latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (13 TeV)" % runRange.printval)

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

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))
    plotPad.RedrawAxis()
    if additionalLabel is not "":
        hCanvas.Print(
            "fig/rOutIn_%s_%s_%s_%s.pdf" %
            (suffix, selection.name, runRange.label, additionalLabel))
    else:
        hCanvas.Print("fig/rOutIn_%s_%s_%s.pdf" %
                      (suffix, selection.name, runRange.label))
示例#13
0
def dependencies(path, selection, plots, runRange, mc, backgrounds, cmsExtra):
    hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)
    legend = TLegend(0.6, 0.7, 0.9, 0.9)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    ROOT.gStyle.SetOptStat(0)

    for name in plots:
        hCanvas.Clear()

        plot = getPlot(name)
        plot.addRegion(selection)
        plot.cleanCuts()
        plot.cuts = plot.cuts % runRange.runCut

        if not "Forward" in selection.name:
            relSyst = systematics.rOutIn.central.val
            if "Central" in selection.name:
                region = "central"
            else:
                region = "inclusive"
        else:
            relSyst = systematics.rOutIn.forward.val
            region = "forward"

        if len(plot.binning) == 0:
            bins = [
                plot.firstBin + (plot.lastBin - plot.firstBin) / plot.nBins * i
                for i in range(plot.nBins + 1)
            ]
        else:
            bins = plot.binning
        #~ rOutIn = {"LowMass":{"EE":[],"MM":[],"SF":[]},"HighMass":{"EE":[],"MM":[],"SF":[]},"BelowZ":{"EE":[],"MM":[],"SF":[]},"AboveZ":{"EE":[],"MM":[],"SF":[]}}
        #~ rOutInErr = {"LowMass":{"EE":[],"MM":[],"SF":[]},"HighMass":{"EE":[],"MM":[],"SF":[]},"BelowZ":{"EE":[],"MM":[],"SF":[]},"AboveZ":{"EE":[],"MM":[],"SF":[]}}
        rOutIn = {
            "EdgeMass": {
                "EE": [],
                "MM": [],
                "SF": []
            },
            "LowMass": {
                "EE": [],
                "MM": [],
                "SF": []
            },
            "HighMass": {
                "EE": [],
                "MM": [],
                "SF": []
            },
        }
        rOutInErr = {
            "EdgeMass": {
                "EE": [],
                "MM": [],
                "SF": []
            },
            "LowMass": {
                "EE": [],
                "MM": [],
                "SF": []
            },
            "HighMass": {
                "EE": [],
                "MM": [],
                "SF": []
            }
        }

        binningErrs = []
        plotBinning = []
        for i in range(0, len(bins) - 1):
            binningErrs.append((bins[i + 1] - bins[i]) / 2)
            if i == 0:
                plotBinning.append((bins[i + 1] - abs(bins[i])) / 2)
            else:
                plotBinning.append(plotBinning[i - 1] +
                                   (bins[i + 1] - bins[i]) / 2 +
                                   binningErrs[i - 1])

            tmpCuts = selection.cut
            cuts = selection.cut.split("&&")
            cutsUp = []
            cutsDown = []
            cutsEqual = []
            for cut in cuts:
                if "%s >" % plot.variable in cut:
                    cutsUp.append(cut + "&&")
                elif "%s <" % plot.variable in cut:
                    cutsDown.append(cut + "&&")
                elif "%s ==" % plot.variable in cut:
                    cutsEqual.append(cut + "&&")
            for cut in cutsUp:
                selection.cut = selection.cut.replace(cut, "")
            for cut in cutsDown:
                selection.cut = selection.cut.replace(cut, "")
            for cut in cutsEqual:
                selection.cut = selection.cut.replace(cut, "")
            selection.cut = selection.cut + " && %s > %f && %s < %f" % (
                plot.variable, bins[i], plot.variable,
                bins[i + 1]) + " && %s" % runRange.runCut

            additionalLabel = "%s_%.2f_%.2f" % (plot.variable, bins[i],
                                                bins[i + 1])
            centralVal = centralValues(path, selection, runRange, mc,
                                       backgrounds, cmsExtra, additionalLabel)
            for combination in ["EE", "MM", "SF"]:
                #~ for region in ["LowMass","HighMass","BelowZ","AboveZ"]:
                for region in ["EdgeMass", "LowMass", "HighMass"]:
                    rOutIn[region][combination].append(
                        centralVal["rOutIn%s%s" % (region, combination)])
                    rOutInErr[region][combination].append(
                        centralVal["rOutIn%sErr%s" % (region, combination)])

            selection.cut = tmpCuts
        if mc:
            if os.path.isfile("shelves/rOutIn_%s_%s_MC.pkl" %
                              (selection.name, runRange.label)):
                centralVals = pickle.load(
                    open(
                        "shelves/rOutIn_%s_%s_MC.pkl" %
                        (selection.name, runRange.label), "rb"))
            else:
                centralVals = centralValues(path, selection, runRange, mc,
                                            backgrounds, cmsExtra)
        else:
            if os.path.isfile("shelves/rOutIn_%s_%s.pkl" %
                              (selection.name, runRange.label)):
                centralVals = pickle.load(
                    open(
                        "shelves/rOutIn_%s_%s.pkl" %
                        (selection.name, runRange.label), "rb"))
            else:
                centralVals = centralValues(path, selection, runRange, mc,
                                            backgrounds, cmsExtra)

        for combination in ["EE", "MM", "SF"]:
            relSystSave = relSyst
            #~ for region in ["LowMass","HighMass","BelowZ","AboveZ"]:
            for region in ["EdgeMass", "LowMass", "HighMass"]:
                relSyst = relSystSave
                hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)

                plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1)

                style = setTDRStyle()
                style.SetTitleYOffset(1.3)
                style.SetPadLeftMargin(0.16)
                plotPad.UseCurrentStyle()
                plotPad.Draw()
                plotPad.cd()

                plotPad.DrawFrame(plot.firstBin, 0.0, plot.lastBin, 0.15,
                                  "; %s ; %s" % (plot.xaxis, "R_{out/in}"))

                bandX = array("f", [plot.firstBin, plot.lastBin])
                bandY = array("f", [
                    centralVals["rOutIn%s%s" % (region, combination)],
                    centralVals["rOutIn%s%s" % (region, combination)]
                ])
                bandYErr = array("f", [
                    centralVals["rOutIn%s%s" %
                                (region, combination)] * relSyst,
                    centralVals["rOutIn%s%s" % (region, combination)] * relSyst
                ])
                bandXErr = array("f", [0, 0])

                errorband = ROOT.TGraphErrors(2, bandX, bandY, bandXErr,
                                              bandYErr)
                errorband.GetYaxis().SetRangeUser(0.0, 0.15)
                errorband.GetXaxis().SetRangeUser(-5, 105)
                errorband.Draw("3same")
                errorband.SetFillColor(ROOT.kOrange - 9)
                rOutInLine = ROOT.TLine(
                    plot.firstBin,
                    centralVals["rOutIn%s%s" % (region, combination)],
                    plot.lastBin,
                    centralVals["rOutIn%s%s" % (region, combination)])
                rOutInLine.SetLineStyle(ROOT.kDashed)
                rOutInLine.SetLineWidth(2)
                rOutInLine.Draw("same")

                binning = array("f", plotBinning)
                rOutInVals = array("f", rOutIn[region][combination])
                binningErrs = array("f", binningErrs)
                rOutInValsErrs = array("f", rOutInErr[region][combination])
                graph = ROOT.TGraphErrors(len(binning), binning, rOutInVals,
                                          binningErrs, rOutInValsErrs)
                graph.Draw("Psame0")
                legend.Clear()

                if mc:
                    legend.AddEntry(graph, "r_{out,in} MC", "p")
                else:
                    legend.AddEntry(graph, "r_{out,in} Data", "p")
                legend.AddEntry(
                    rOutInLine, "Mean r_{out,in} = %.3f" %
                    centralVals["rOutIn%s%s" % (region, combination)], "l")
                legend.AddEntry(errorband,
                                "Mean r_{out,in} #pm %d %%" % (relSyst * 100),
                                "f")
                legend.Draw("same")

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

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

                latexCMS.DrawLatex(0.19, 0.89, "CMS")
                if "Simulation" in cmsExtra:
                    yLabelPos = 0.83
                else:
                    yLabelPos = 0.85

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

                ROOT.gPad.RedrawAxis()
                if mc:
                    hCanvas.Print(
                        "fig/rOutInSyst_%s_%s_%s_%s_%s_%s_MC.pdf" %
                        (selection.name, runRange.label, plot.variablePlotName,
                         region, combination, plot.additionalName))
                else:
                    hCanvas.Print(
                        "fig/rOutInSyst_%s_%s_%s_%s_%s_%s.pdf" %
                        (selection.name, runRange.label, plot.variablePlotName,
                         region, combination, plot.additionalName))
def signalRegion(path, selection, plots, runRange, backgrounds, cmsExtra):
    plots = ["mllPlot"]
    for name in plots:
        plot = getPlot(name)
        plot.addRegion(selection)
        #~ plot.cleanCuts()
        plot.cuts = plot.cuts % runRange.runCut
        #~ plot.cuts = plot.cuts.replace("2.4","1.4")
        #~ plot.cuts = plot.cuts.replace("weight*","")
        print runRange.lumi
        if "Signal" in selection.name:
            plot.nBins = int(plot.nBins / 2)
            plot.yaxis = "Events / 10 GeV"
        fake = "!(pdgIdETH1*pdgIdETH2==-11*11 || pdgIdETH1*pdgIdETH2==-13*13 || pdgIdETH1*pdgIdETH2==-11*13)"

        dilep = "(motherPdgIdETH1*motherPdgIdETH2==-24*24 || motherPdgIdETH1*grandMotherPdgIdETH2==-24*24 || grandMotherPdgIdETH1*motherPdgIdETH2==-24*24 || grandMotherPdgIdETH1*grandMotherPdgIdETH2==-24*24)"
        #~ plot.cuts = plot.cuts+"*!(!(motherPdgIdETH1*motherPdgIdETH2==-24*24 || grandMotherPdgIdETH1*grandMotherPdgIdETH2==-24*24 || motherPdgIdETH1*grandMotherPdgIdETH2==-24*24 || grandMotherPdgIdETH1*motherPdgIdETH2==-24*24) || !(pdgIdETH1*pdgIdETH2==-11*11 || pdgIdETH1*pdgIdETH2==-13*13 || pdgIdETH1*pdgIdETH2==-11*13))"
        #~ plot.cuts = plot.cuts+"*!((motherPdgIdETH1 == grandMotherPdgIdETH1) || (motherPdgIdETH2 == grandMotherPdgIdETH2))"
        #~ plot.cuts = plot.cuts+"*!((motherPdgIdETH1 == grandMotherPdgIdETH1) || (motherPdgIdETH2 == grandMotherPdgIdETH2) || (abs(motherPdgIdETH1) == 24 && abs(motherPdgIdETH2) == 24  )) "
        #~ plot.cuts = plot.cuts+"*!((abs(motherPdgIdETH1) == 15 && abs(motherPdgIdETH2) == 24) || (abs(motherPdgIdETH2) == 15 && abs(motherPdgIdETH1) == 24) || (abs(motherPdgIdETH1) == 15 && abs(motherPdgIdETH2) == 15) || (abs(motherPdgIdETH1) == 24 && abs(motherPdgIdETH2) == 24  )) "

        #~ plot.cuts = plot.cuts+"*(!(abs(motherPdgIdETH1*motherPdgIdETH2)==24*24 || abs(motherPdgIdETH1*motherPdgIdETH2)==15*24 || abs(motherPdgIdETH1*motherPdgIdETH2)==15*15) || !(pdgIdETH1*pdgIdETH2==-11*11 || pdgIdETH1*pdgIdETH2==-13*13 || pdgIdETH1*pdgIdETH2==-11*13))"

        #~ plot.cuts = plot.cuts+"*(!(abs(motherPdgId1*motherPdgId2)==24*24 || abs(motherPdgId1*motherPdgId2)==15*24 || abs(motherPdgId1*motherPdgId2)==15*15) || !(pdgId1*pdgId2==-11*11 || pdgId1*pdgId2==-13*13 || pdgId1*pdgId2==-11*13))"
        #~ plot.cuts = plot.cuts+"*!(%s && !%s)"%(dilep,fake)
        plot.cuts = plot.cuts + "*!(%s && !%s)" % (dilep, fake)
        print plot.cuts

        if not "Forward" in selection.name:
            corr = rSFOF.central.val
            corrErr = rSFOF.central.err
            if "Central" in selection.name:
                region = "central"
            else:
                region = "inclusive"
        else:
            corr = rSFOF.forward.val
            corrErr = rSFOF.forward.err
            region = "forward"
        #~
        eventCounts = totalNumberOfGeneratedEvents(path)
        print eventCounts
        #~ for background in backgrounds:
        #~ process = Process(getattr(Backgrounds,background),eventCounts)
        #~ for subprocess in process.samples:
        #~
        #~ print subprocess
        #~ treeEE, treeMM, treeEM = getTrees(path,plot,runRange, subprocess,region)
        #~ for ev in treeMM:

        #~ print ev.pdgIdETH1, ev.motherPdgIdETH1, ev.grandMotherPdgIdETH1, "--", ev.pdgIdETH2, ev.motherPdgIdETH2, ev.grandMotherPdgIdETH2

        #~ print treeEE.GetEntries(), treeMM.GetEntries(), treeEM.GetEntries()
        histEE, histMM, histOF = getHistograms(path, plot, runRange,
                                               backgrounds, region)
        print histEE.Integral(1, histEE.GetNbinsX()), histMM.Integral(
            1, histEE.GetNbinsX()), histOF.Integral(1, histEE.GetNbinsX())
        print histEE.GetEntries(), histMM.GetEntries(), histOF.GetEntries()

        nEEScaledErr = ROOT.Double()
        nMMScaledErr = ROOT.Double()
        nEMScaledErr = ROOT.Double()

        nEEScaled = histEE.IntegralAndError(1, histEE.GetNbinsX(),
                                            nEEScaledErr)
        nMMScaled = histMM.IntegralAndError(1, histEE.GetNbinsX(),
                                            nMMScaledErr)
        nEMScaled = histOF.IntegralAndError(1, histEE.GetNbinsX(),
                                            nEMScaledErr)

        result = {
            "nEE": histEE.GetEntries(),
            "nMM": histMM.GetEntries(),
            "nEM": histOF.GetEntries(),
            "nEEScaled": nEEScaled,
            "nEEScaledErr": float(nEEScaledErr),
            "nMMScaled": nMMScaled,
            "nMMScaledErr": float(nMMScaledErr),
            "nEMScaled": nEMScaled,
            "nEMScaledErr": float(nEMScaledErr)
        }

        outFilePkl = open(
            "shelves/nonPromptMC_%s_%s" % (selection.name, runRange.label),
            "w")
        pickle.dump(result, outFilePkl)
        outFilePkl.close()

        hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)
        plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1)

        style = setTDRStyle()
        plotPad.UseCurrentStyle()
        plotPad.Draw()
        plotPad.cd()
        logScale = plot.log
        if plot.variable == "met" or plot.variable == "type1Met" or plot.variable == "tcMet" or plot.variable == "caloMet" or plot.variable == "mht":
            logScale = True

        yMax = histEE.GetBinContent(
            histEE.GetMaximumBin()) + histMM.GetBinContent(
                histMM.GetMaximumBin())

        if logScale:
            yMax = yMax * 1.5
        else:
            yMax = yMax * 1.5


#~

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

        histSF = histEE.Clone("histSF")
        histSF.Add(histMM.Clone())

        histSF.SetMarkerStyle(20)
        histOF.SetLineColor(ROOT.kBlue)
        histOF.SetMarkerSize(0)
        histEE.SetLineColor(ROOT.kRed)
        histMM.SetLineColor(ROOT.kGreen + 3)
        histEE.SetLineStyle(ROOT.kDashed)
        histMM.SetLineStyle(ROOT.kDashed)

        histSF.Draw("samep")
        histOF.Draw("samehiste")
        histEE.Draw("samehist")
        histMM.Draw("samehist")

        latex = ROOT.TLatex()
        latex.SetTextSize(0.04)
        latex.SetNDC(True)

        legend = TLegend(0.5, 0.55, 0.95, 0.9)
        legend.SetFillStyle(0)
        legend.SetBorderSize(0)
        entryHist = TH1F()
        entryHist.SetFillColor(ROOT.kWhite)
        legend.AddEntry(entryHist, selection.latex, "h")
        legend.AddEntry(histSF, "SF", "p")
        legend.AddEntry(histEE, "EE", "l")
        legend.AddEntry(histMM, "MM", "l")
        legend.AddEntry(histOF, "OF", "l")

        legend.Draw("same")

        latex = ROOT.TLatex()
        latex.SetTextFont(42)
        latex.SetNDC(True)
        latex.SetTextAlign(31)
        latex.SetTextSize(0.04)

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

        latexCMS = ROOT.TLatex()
        latexCMS.SetTextFont(61)
        latexCMS.SetTextSize(0.06)
        latexCMS.SetNDC(True)
        latexCMSExtra = ROOT.TLatex()
        latexCMSExtra.SetTextFont(52)
        latexCMSExtra.SetTextSize(0.045)
        latexCMSExtra.SetNDC(True)

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

        plotPad.RedrawAxis()
        hCanvas.Print("fig/nonPromptMC_%s_%s_%s_%s.pdf" %
                      (selection.name, runRange.label, plot.variablePlotName,
                       plot.additionalName))