Beispiel #1
0
 def __init__(self,mainConfig=None):        
     self.canvas = None
     self.plotPad = None
     self.ratioPad = None
     
     self.primaryPlot = None
     self.secondaryPlots = []
     
     self.ratioErrsSize = []
     self.ratioErrsHist = []
     
     self.ratioPairs = []
     self.nominators = []
     self.denominators = []
     setTDRStyle() 
     
     self.latexCMS      = None
     self.latexCMSExtra = None
     self.latexCuts     = None
     self.latexLumi     = None
     self.latexRegion   = None
     
     if mainConfig != None:
         self.regionName = mainConfig.plot.label2
         if hasattr(mainConfig, "jzbType"):
             self.jzbType = mainConfig.jzbType
         self.personalWork = mainConfig.personalWork
         self.preliminary = mainConfig.preliminary
         self.forTWIKI = mainConfig.forTWIKI
         self.plotData = mainConfig.plotData
         self.hasRatio = mainConfig.plotRatio
         self.lumiInt = mainConfig.runRange.printval
         self.labelX = mainConfig.plot.xaxis
         self.labelY = mainConfig.plot.yaxis
Beispiel #2
0
 def __init__(self):
     setTDRStyle()
     self.names = {}
     self.inFiles = {}
     self.labels = {}
     self.colors = {}
     self.outPath = None
     self.hasSystematics = {}
     self.systematics = {}
     self.granularity = standardGranularity
     self.title = ""
File: TriggerEfficiency.py
Author: Alejandro Gomez Espinosa
Email: [email protected]
Description: Calculate the Trigger Efficiency
'''

import sys,os,time
import optparse
from collections import defaultdict
from ROOT import *
from setTDRStyle import setTDRStyle
from DataFormats.FWLite import Events, Handle

gROOT.SetBatch()
gROOT.Reset()
setTDRStyle()
gROOT.ForceStyle()
gROOT.SetStyle('tdrStyle')


###### Trick for add date or month to plots
dateKey   = time.strftime("%y%m%d%H%M")
monthKey   = time.strftime("%y%m%d")


################################################################################# Calculate Efficiency
def CalculateEff( inputFile, outputDir, sample, jetAlgo, grooming, weight, FNAL ):
	"""docstring for CalculateEff"""

	#outputFileName = monthKey+'_'+sample+'_TriggerEfficiency_'+jetAlgo+'.pdf'  
	outputFileName = monthKey+'_'+sample+'_TriggerEfficiency_'+jetAlgo+'_HT350.pdf'  
Beispiel #4
0
def plot():
	import ratios
	from ROOT import TCanvas, TPad, TH1F, TH2F,TH2D, TH1I, THStack, TLegend, TMath, TF1, TFile, TGraph2D
	from setTDRStyle import setTDRStyle
	import pickle
	from defs import sbottom_masses
	from math import sqrt
	
	from corrections import rSFOFDirect
	
	signalDenominatorFile = TFile("/.automount/home/home__home4/institut_1b/schomakers/FrameWork/SignalScan/T6bbllsleptonDenominatorHisto7.root")
	denominatorHisto = TH2F(signalDenominatorFile.Get("massScan"))
	ISRNormalizationHisto = TH2F(signalDenominatorFile .Get("ISRNormalization"))
	ISRNormalizationHistoUp = TH2F(signalDenominatorFile .Get("ISRNormalizationUp"))
	ISRNormalizationHistoDown = TH2F(signalDenominatorFile .Get("ISRNormalizationDown"))
	
	
	latex = ROOT.TLatex()
	latex.SetTextSize(0.03)
	latex.SetNDC(True)
	latexLumi = ROOT.TLatex()
	latexLumi.SetTextFont(42)
	latexLumi.SetTextAlign(31)
	latexLumi.SetTextSize(0.04)
	latexLumi.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)
	
	canv = TCanvas("canv", "canv",1024,768)
	plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1)
	setTDRStyle()
	style=setTDRStyle()	
	style.SetPadRightMargin(0.175)	
	plotPad.UseCurrentStyle()
	plotPad.Draw()	
	plotPad.cd()	
	
	nEvents = -1
	lumi = 35867.
	printLumi = "35.9"
	
	m_neutr_1_fix = False
	#~ m_neutr_1_fix = True

	
	
	path = "shelvesSystematics"
	generalSignalLabel = "T6bbllslepton"
	
	observables = ["mll"]
	leptonCombinations = ["SF-OF"]
	
	massRegions = ["20To60","60To86","86To96","96To150","150To200","200To300","300To400","Above400"]
	nLLRegions = ["lowNll","highNll"]
	MT2Regions = ["highMT2"]
	
	regionCombinations = []
	regions = []
	
	for massRegion in massRegions:
		for nLLRegion in nLLRegions:
			for MT2Region in MT2Regions:
				regions.append("%s_%s_%s"%(massRegion,nLLRegion,MT2Region))
				
	for nLLRegion in nLLRegions:
		regionCombinations.append(nLLRegion)	
			
	
	Graphs = {}
	Histograms = {}			
	uncertaintyArrays = {}
	#~ uncertaintySources = ["Yield","StatUncertainty","SystUncertainty","TotalUncertainty","Efficiency","ISRUncertainty","pileupUncertainty","JESUncertainty","LeptonUncertainty","LeptonFastSimUncertainty","LeptonFullSimUncertainty","BTagUncertaintyLight","BTagUncertaintyHeavy"]
	uncertaintySources = ["Yield","StatUncertainty","SystUncertainty","TotalUncertainty","Efficiency","EfficiencyUnscaled","ISRUncertainty","pileupUncertainty","JESUncertainty","LeptonFullSimUncertainty","LeptonFastSimUncertainty","BTagUncertaintyLight","BTagUncertaintyHeavy","MetUncertainty","ScaleUncertainty"]

	
	for uncertaintySource in uncertaintySources:
		uncertaintyArrays["%s_highNll"%(uncertaintySource)] = []
		uncertaintyArrays["%s_lowNll"%(uncertaintySource)] = []
		for region in regions:
			uncertaintyArrays["%s_%s"%(uncertaintySource,region)] = []
			
	
	
	title = "Simplified Model Scan; m(#tilde{b}) [GeV]; m(#tilde{#chi}_{2}^{0}) [GeV]"

	masses_b = []
	masses_n = []
	
	m_n_min = 150
	m_n_max = 1450
	m_b_min = 700
	m_b_max = 1500
	
	bin_size =25
	nxbins = int(min(500,(m_b_max-m_b_min)/bin_size))
	nybins = int(min(500,(m_n_max-m_n_min)/bin_size))
	
	
	TriggerEffUncertainty = 0.03
	LumiUncertainty = 0.026
	FastSimUncertainty = 0.04
					
	m_b = m_b_min
	while m_b <= m_b_max:
		print m_b
		if m_b < 800:
			stepsize = 25
		else:
			stepsize = 50
		
		M_SBOTTOM = "m_b_"+str(m_b)
		m_sbottom = str(m_b)
		xsection = getattr(sbottom_masses, M_SBOTTOM).cross_section13TeV
		
		m_n = m_n_min
		
		while m_n < m_b:
			
			if not ((m_b == 775 and m_n == 750) or (m_b == 800 and m_n == 150) or (m_b == 950 and m_n == 250) or (m_b == 950 and m_n == 300) or (m_b == 950 and m_n == 500) or (m_b == 950 and m_n == 550) or (m_b == 950 and m_n == 850) or (m_b == 950 and m_n == 900)):	
							
				
				m_neutralino_2 = str(m_n)
				
				masses_b.append(m_b)
				masses_n.append(m_n)
				
				sampleName = "T6bbllslepton_msbottom_%s_mneutralino_%s"%(m_sbottom,m_neutralino_2)
				
				denominator = denominatorHisto.GetBinContent(denominatorHisto.GetXaxis().FindBin(int(sampleName.split("_")[2])),denominatorHisto.GetYaxis().FindBin(int(sampleName.split("_")[4])))
				ISRNormalization = ISRNormalizationHisto.GetBinContent(ISRNormalizationHisto.GetXaxis().FindBin(int(sampleName.split("_")[2])),denominatorHisto.GetYaxis().FindBin(int(sampleName.split("_")[4])))
					
				
	
				Pickles = {}
				Yields = {}
				MCEvents = {}
				JES = {}
				#~ Lepton = {}
				LeptonFastSim = {}
				LeptonFullSim = {}
				Pileup = {}
				ISR= {}
				BTag = {}
				Met = {}
				ScaleShift = {}
				
				Uncertainties = {}	
				
				Pickles["%s_%s"%(m_sbottom,m_neutralino_2)] = loadPickles("%s/%s.pkl"%(path,sampleName))	
				
				
				for region in regions:
					
					if region == "edgeLegacy":
						RSFOF = rSFOFDirect.central.val
					else:
						RSFOF = rSFOFDirect.inclusive.val
	
					
					Yields["EE_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["Val"]
					Yields["EMu_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["Val"]*RSFOF
					Yields["MuMu_%s"%region] =  Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["Val"]
					Yields["SFOF_%s"%region] = Yields["EE_%s"%region] + Yields["MuMu_%s"%region] - Yields["EMu_%s"%region]
					Uncertainties["Yield_%s"%region] = max(Yields["SFOF_%s"%region],0)
					
					MCEvents["EE_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["MCEvents"]
					MCEvents["EMu_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["MCEvents"]
					MCEvents["MuMu_%s"%region] =  Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["MCEvents"]
					MCEvents["SFOF_%s"%region] = MCEvents["EE_%s"%region] + MCEvents["MuMu_%s"%region] - MCEvents["EMu_%s"%region]
					MCEvents["SFOF_%s"%region] = max(MCEvents["SFOF_%s"%region],0)
					
					Uncertainties["Efficiency_%s"%region] = Yields["SFOF_%s"%region]/(xsection*lumi*ISRNormalization)
					Uncertainties["EfficiencyUnscaled_%s"%region] = MCEvents["SFOF_%s"%region]/denominator
					
					if MCEvents["SFOF_%s"%region] > 0:
						Uncertainties["StatUncertainty_%s"%region] = sqrt(MCEvents["EE_%s"%region]+MCEvents["EMu_%s"%region]+MCEvents["MuMu_%s"%region])/MCEvents["SFOF_%s"%region]
					else:
						Uncertainties["StatUncertainty_%s"%region] = 0
					
					### JES Uncertainty
					JES["Mean_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["JESMean"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["JESMean"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["JESMean"]*RSFOF 
					
					JES["JESUp_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["JESUp"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["JESUp"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["JESUp"]*RSFOF
					JES["JESDown_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["JESDown"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["JESDown"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["JESDown"]*RSFOF
					
					### Only consider bins with a sufficient number of MC events
					### otherwise nearly empty bins will dominate the plots
					if JES["Mean_%s"%region] > 0 and MCEvents["SFOF_%s"%region] > 100:
						Uncertainties["JESUncertainty_%s"%region] = max(abs(JES["JESUp_%s"%region]-JES["Mean_%s"%region])/JES["Mean_%s"%region],abs(JES["JESDown_%s"%region]-JES["Mean_%s"%region])/JES["Mean_%s"%region])
					else:
						Uncertainties["JESUncertainty_%s"%region] = 0
					
					### Lepton FastSim Uncertainty
					
					LeptonFastSim["Mean_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EE"%region]["LeptonFastSimMean"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_MuMu"%region]["LeptonFastSimMean"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EMu"%region]["LeptonFastSimMean"] 
					LeptonFastSim["MeanShifted_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EE"%region]["LeptonFastSimMean"] * (1+FastSimUncertainty) + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_MuMu"%region]["LeptonFastSimMean"]*(1+FastSimUncertainty)  - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EMu"%region]["LeptonFastSimMean"]*(1+FastSimUncertainty)  
					
					if LeptonFastSim["Mean_%s"%region] > 0:
						Uncertainties["LeptonFastSimUncertainty_%s"%region] = abs(LeptonFastSim["MeanShifted_%s"%region]-LeptonFastSim["Mean_%s"%region])/LeptonFastSim["Mean_%s"%region]
					else:
						Uncertainties["LeptonFastSimUncertainty_%s"%region] = 0
						
					### Lepton FullSim Uncertainty
					
					LeptonFullSim["Mean_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EE"%region]["LeptonFullSimMean"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_MuMu"%region]["LeptonFullSimMean"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EMu"%region]["LeptonFullSimMean"] 
					LeptonFullSim["MeanShifted_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EE"%region]["LeptonFullSimScaleFactorShifted"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_MuMu"%region]["LeptonFullSimScaleFactorShifted"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EMu"%region]["LeptonFullSimScaleFactorShifted"] 
					
					if LeptonFullSim["Mean_%s"%region] > 0:
						Uncertainties["LeptonFullSimUncertainty_%s"%region] = abs(LeptonFullSim["MeanShifted_%s"%region]-LeptonFullSim["Mean_%s"%region])/LeptonFullSim["Mean_%s"%region]
					else:
						Uncertainties["LeptonFullSimUncertainty_%s"%region] = 0
					
					
					###  Pileup Uncertainty
					Pileup["Mean_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["PileupMean"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["PileupMean"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["PileupMean"]*RSFOF
					
					Pileup["PileupHigh_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["PileupHigh"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["PileupHigh"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["PileupHigh"]*RSFOF
					Pileup["PileupLow_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["PileupLow"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["PileupLow"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["PileupLow"]*RSFOF 
					
					if Pileup["Mean_%s"%region] > 0 and MCEvents["SFOF_%s"%region] > 100:
						Uncertainties["pileupUncertainty_%s"%region] = max(abs(Pileup["PileupHigh_%s"%region]-Pileup["Mean_%s"%region])/Pileup["Mean_%s"%region],abs(Pileup["PileupLow_%s"%region] -Pileup["Mean_%s"%region])/Pileup["Mean_%s"%region] )
					else:
						Uncertainties["pileupUncertainty_%s"%region] = 0
					
					Uncertainties["pileupUncertainty_%s"%region] = 0.02
					
					### ISR Uncertainty
					ISR["Mean_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["ISRMean"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["ISRMean"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["ISRMean"]*RSFOF
					
					ISR["ISRUp_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["ISRUp"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["ISRUp"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["ISRUp"]*RSFOF
					ISR["ISRDown_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["ISRDown"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["ISRDown"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["ISRDown"]*RSFOF  
					
					if ISR["Mean_%s"%region] > 0 and MCEvents["SFOF_%s"%region] > 100:
						Uncertainties["ISRUncertainty_%s"%region] = max(abs(ISR["ISRUp_%s"%region]-ISR["Mean_%s"%region])/ISR["Mean_%s"%region],abs(ISR["ISRDown_%s"%region]-ISR["Mean_%s"%region])/ISR["Mean_%s"%region])
					else:
						Uncertainties["ISRUncertainty_%s"%region] = 0
						
					if Yields["SFOF_%s"%region] > 0 and MCEvents["SFOF_%s"%region] > 100:
						Uncertainties["TriggerEffUncertainty_%s"%region] = sqrt((Yields["EE_%s"%region]*TriggerEffUncertainty)**2 + (Yields["MuMu_%s"%region]*TriggerEffUncertainty)**2 + (Yields["EMu_%s"%region]*TriggerEffUncertainty*RSFOF)**2)/Yields["SFOF_%s"%region]
					else:
						Uncertainties["TriggerEffUncertainty_%s"%region] = 0
							
					### BTag Uncertainty
					BTag["Mean_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["BTagMean"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["BTagMean"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["BTagMean"]*RSFOF
					
					BTag["BTagHeavy_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["BTagHeavy"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["BTagHeavy"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["BTagHeavy"]*RSFOF  
					
					BTag["BTagLight_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["BTagLight"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["BTagLight"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["BTagLight"]*RSFOF
					
					if BTag["Mean_%s"%region] > 0 and MCEvents["SFOF_%s"%region] >100:
						Uncertainties["BTagUncertaintyHeavy_%s"%region] = abs(BTag["BTagHeavy_%s"%region]-BTag["Mean_%s"%region])/BTag["Mean_%s"%region]
						Uncertainties["BTagUncertaintyLight_%s"%region] = abs(BTag["BTagLight_%s"%region]-BTag["Mean_%s"%region])/BTag["Mean_%s"%region]
					else:
						Uncertainties["BTagUncertaintyHeavy_%s"%region] = 0
						Uncertainties["BTagUncertaintyLight_%s"%region] = 0
						
					### FastSim Met Uncertainty					
					Met["Met_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["Met"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["Met"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["Met"]*RSFOF
					Met["GenMet_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["GenMet"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["GenMet"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["GenMet"]*RSFOF  
					
					if Yields["SFOF_%s"%region] > 0 and MCEvents["SFOF_%s"%region] >100:
						Uncertainties["MetUncertainty_%s"%region] = 0.5*abs(Met["Met_%s"%region]-Met["GenMet_%s"%region])/Yields["SFOF_%s"%region]
					else:
						Uncertainties["MetUncertainty_%s"%region] = 0
					
					### Scale uncertainty
					Uncertainties["ScaleUncertainty_%s"%region] = 0
					ScaleShift["Mean_%s"%region] = BTag["Mean_%s"%region]
					ScaleShift["MaxShift_%s"%region] = 0
					if BTag["Mean_%s"%region] > 0:
						
						for scaleIndex in range(1,9):
							ScaleShift["ScaleShift%s"%str(scaleIndex)] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EE"%region]["ScaleShifted%s"%str(scaleIndex)] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_MuMu"%region]["ScaleShifted%s"%str(scaleIndex)] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EMu"%region]["ScaleShifted%s"%str(scaleIndex)]
							Uncertainties["ScaleUncertainty_%s"%region] = max(Uncertainties["ScaleUncertainty_%s"%region], abs( (ScaleShift["ScaleShift%s"%str(scaleIndex)] - ScaleShift["Mean_%s"%region])/ScaleShift["Mean_%s"%region]))
							if abs( ScaleShift["ScaleShift%s"%str(scaleIndex)] - ScaleShift["Mean_%s"%region])/ScaleShift["Mean_%s"%region] > ScaleShift["MaxShift_%s"%region]:
								ScaleShift["MaxShift_%s"%region] = ScaleShift["ScaleShift%s"%str(scaleIndex)]
								
					
					#~ ### Trigger efficiency	
					#~ if Yields["SFOF_%s"%region] > 0:
						#~ Uncertainties["TriggerEffUncertainty_%s"%region] = sqrt((Yields["EE_%s"%region]*TriggerEffUncertainty)**2 + (Yields["MuMu_%s"%region]*TriggerEffUncertainty)**2 + (Yields["EMu_%s"%region]*TriggerEffUncertainty)**2)/Yields["SFOF_%s"%region]
					#~ else:
						#~ Uncertainties["TriggerEffUncertainty_%s"%region] = 0
					Uncertainties["TriggerEffUncertainty_%s"%region] = TriggerEffUncertainty
							
					### Total syst uncertainty
					Uncertainties["SystUncertainty_%s"%region] = sqrt(Uncertainties["ScaleUncertainty_%s"%region]**2 + Uncertainties["JESUncertainty_%s"%region]**2 + Uncertainties["LeptonFastSimUncertainty_%s"%region]**2 + Uncertainties["LeptonFullSimUncertainty_%s"%region]**2 + Uncertainties["pileupUncertainty_%s"%region]**2 + Uncertainties["ISRUncertainty_%s"%region]**2 + Uncertainties["BTagUncertaintyLight_%s"%region]**2 + Uncertainties["BTagUncertaintyHeavy_%s"%region]**2  + Uncertainties["TriggerEffUncertainty_%s"%region]**2 + LumiUncertainty**2)
					
					### Totalaluncertainty
					Uncertainties["TotalUncertainty_%s"%region] = sqrt(Uncertainties["SystUncertainty_%s"%region]**2 + Uncertainties["StatUncertainty_%s"%region]**2)
			
					for uncertainty in uncertaintySources:
						uncertaintyArrays["%s_%s"%(uncertainty,region)].append(Uncertainties["%s_%s"%(uncertainty,region)])
						
				for regionCombination in regionCombinations:
						
						Yields["EE_%s"%regionCombination] = 0	
						Yields["EMu_%s"%regionCombination] = 0	
						Yields["MuMu_%s"%regionCombination] = 0	
						Yields["SFOF_%s"%regionCombination] = 0
						
						Uncertainties["Yield_%s"%regionCombination] = 0
						
						MCEvents["EE_%s"%regionCombination] = 0
						MCEvents["EMu_%s"%regionCombination] = 0
						MCEvents["MuMu_%s"%regionCombination] = 0
						MCEvents["SFOF_%s"%regionCombination] = 0
						
						JES["Mean_%s"%regionCombination] =  0
						JES["JESUp_%s"%regionCombination] =  0
						JES["JESDown_%s"%regionCombination] =  0
						
						LeptonFastSim["Mean_%s"%regionCombination] =  0
						LeptonFastSim["MeanShifted_%s"%regionCombination] =  0
						
						LeptonFullSim["Mean_%s"%regionCombination] =  0
						LeptonFullSim["MeanShifted_%s"%regionCombination] =  0
						
						Pileup["Mean_%s"%regionCombination] = 0
						Pileup["PileupHigh_%s"%regionCombination] =  0
						Pileup["PileupLow_%s"%regionCombination] =  0
						
						ISR["Mean_%s"%regionCombination] = 0					
						ISR["ISRUp_%s"%regionCombination] = 0
						ISR["ISRDown_%s"%regionCombination] = 0
							
						BTag["Mean_%s"%regionCombination] = 0					
						BTag["BTagHeavy_%s"%regionCombination] = 0
						BTag["BTagLight_%s"%regionCombination] = 0
							
						Met["Met_%s"%regionCombination] = 0					
						Met["GenMet_%s"%regionCombination] = 0
						
						ScaleShift["Mean_%s"%regionCombination] = 0
						ScaleShift["MaxShift_%s"%regionCombination] = 0
						
						
					### Add information of single regions into combinations
						for region in regions:
							#~ etaBin, massBin, bTagBin = region.split('_')	
							#~ if etaBin in regionCombination or massBin in regionCombination or bTagBin in regionCombination:
								
							if regionCombination in region:
									
								Yields["EE_%s"%regionCombination] += Yields["EE_%s"%region]
								Yields["EMu_%s"%regionCombination] += Yields["EMu_%s"%region]
								Yields["MuMu_%s"%regionCombination] += Yields["MuMu_%s"%region]
								Yields["SFOF_%s"%regionCombination] += Yields["SFOF_%s"%region]
								Uncertainties["Yield_%s"%regionCombination] += Uncertainties["Yield_%s"%region]
								
								MCEvents["EE_%s"%regionCombination] += MCEvents["EE_%s"%region]
								MCEvents["EMu_%s"%regionCombination] += MCEvents["EMu_%s"%region]
								MCEvents["MuMu_%s"%regionCombination] += MCEvents["MuMu_%s"%region]
								MCEvents["SFOF_%s"%regionCombination] += MCEvents["SFOF_%s"%region]
								
								JES["Mean_%s"%regionCombination] +=  JES["Mean_%s"%region]
								JES["JESUp_%s"%regionCombination] +=  JES["JESUp_%s"%region]
								JES["JESDown_%s"%regionCombination] +=  JES["JESDown_%s"%region]
								
								LeptonFastSim["Mean_%s"%regionCombination] +=  LeptonFastSim["Mean_%s"%region]
								LeptonFastSim["MeanShifted_%s"%regionCombination] +=  LeptonFastSim["MeanShifted_%s"%region]
								
								LeptonFullSim["Mean_%s"%regionCombination] +=  LeptonFullSim["Mean_%s"%region]
								LeptonFullSim["MeanShifted_%s"%regionCombination] +=  LeptonFullSim["MeanShifted_%s"%region]
								
								Pileup["Mean_%s"%regionCombination] +=  Pileup["Mean_%s"%region]						
								Pileup["PileupHigh_%s"%regionCombination] +=  Pileup["PileupHigh_%s"%region]
								Pileup["PileupLow_%s"%regionCombination] +=  Pileup["PileupLow_%s"%region]
								
								ISR["Mean_%s"%regionCombination] += ISR["Mean_%s"%region]						
								ISR["ISRUp_%s"%regionCombination] += ISR["ISRUp_%s"%region]
								ISR["ISRDown_%s"%regionCombination] += ISR["ISRDown_%s"%region]		
						
								BTag["Mean_%s"%regionCombination] += BTag["Mean_%s"%region]						
								BTag["BTagHeavy_%s"%regionCombination] += BTag["BTagHeavy_%s"%region]
								BTag["BTagLight_%s"%regionCombination] += BTag["BTagLight_%s"%region]		
						
								Met["Met_%s"%regionCombination] += Met["Met_%s"%region]						
								Met["GenMet_%s"%regionCombination] += Met["GenMet_%s"%region]
								
								ScaleShift["Mean_%s"%regionCombination] += ScaleShift["Mean_%s"%region]
								ScaleShift["MaxShift_%s"%regionCombination] += ScaleShift["MaxShift_%s"%region]
						
						##Calculate uncertaities for combinations			
						Uncertainties["Efficiency_%s"%regionCombination] = Yields["SFOF_%s"%regionCombination]/(xsection*lumi*ISRNormalization)
						Uncertainties["EfficiencyUnscaled_%s"%regionCombination] = MCEvents["SFOF_%s"%regionCombination]/denominator
	
							
						if MCEvents["SFOF_%s"%regionCombination] > 0:
							Uncertainties["StatUncertainty_%s"%regionCombination] = sqrt(MCEvents["EE_%s"%regionCombination]+MCEvents["EMu_%s"%regionCombination]+MCEvents["MuMu_%s"%regionCombination])/MCEvents["SFOF_%s"%regionCombination]
						else:
							Uncertainties["StatUncertainty_%s"%regionCombination] = 0
						
						if JES["Mean_%s"%regionCombination] > 0 and MCEvents["SFOF_%s"%regionCombination] > 100:
						#~ if JES["Mean_%s"%regionCombination] > 0:
							Uncertainties["JESUncertainty_%s"%regionCombination] = max(abs(JES["JESUp_%s"%regionCombination]-JES["Mean_%s"%regionCombination])/JES["Mean_%s"%regionCombination],abs(JES["JESDown_%s"%regionCombination]-JES["Mean_%s"%regionCombination])/JES["Mean_%s"%regionCombination])
						else:
							Uncertainties["JESUncertainty_%s"%regionCombination] = 0
							
						if LeptonFastSim["Mean_%s"%regionCombination] > 0 and MCEvents["SFOF_%s"%regionCombination] > 100:
						#~ if LeptonFastSim["Mean_%s"%regionCombination] > 0:
							Uncertainties["LeptonFastSimUncertainty_%s"%regionCombination] = abs(LeptonFastSim["MeanShifted_%s"%regionCombination]-LeptonFastSim["Mean_%s"%regionCombination])/LeptonFastSim["Mean_%s"%regionCombination]
						else:
							Uncertainties["LeptonFastSimUncertainty_%s"%regionCombination] = 0
						
						if LeptonFullSim["Mean_%s"%regionCombination] > 0 and MCEvents["SFOF_%s"%regionCombination] > 100:
						#~ if LeptonFullSim["Mean_%s"%regionCombination] > 0:
							Uncertainties["LeptonFullSimUncertainty_%s"%regionCombination] = abs(LeptonFullSim["MeanShifted_%s"%regionCombination]-LeptonFullSim["Mean_%s"%regionCombination])/LeptonFullSim["Mean_%s"%regionCombination]
						else:
							Uncertainties["LeptonFullSimUncertainty_%s"%regionCombination] = 0
						
						if Pileup["Mean_%s"%regionCombination] > 0 and MCEvents["SFOF_%s"%regionCombination] > 100:
						#~ if Pileup["Mean_%s"%regionCombination] > 0:
							Uncertainties["pileupUncertainty_%s"%regionCombination] = max(abs(Pileup["PileupHigh_%s"%regionCombination]-Pileup["Mean_%s"%regionCombination])/Pileup["Mean_%s"%regionCombination],abs(Pileup["PileupLow_%s"%regionCombination] -Pileup["Mean_%s"%regionCombination])/Pileup["Mean_%s"%regionCombination] )
						else:
							Uncertainties["pileupUncertainty_%s"%regionCombination] = 0
							
						Uncertainties["pileupUncertainty_%s"%regionCombination] = 0.02
						
						if ISR["Mean_%s"%regionCombination] > 0 and MCEvents["SFOF_%s"%regionCombination] > 100:
						#~ if ISR["Mean_%s"%regionCombination] > 0:
							Uncertainties["ISRUncertainty_%s"%regionCombination] = max(abs(ISR["ISRUp_%s"%regionCombination]-ISR["Mean_%s"%regionCombination])/ISR["Mean_%s"%regionCombination],abs(ISR["ISRDown_%s"%regionCombination]-ISR["Mean_%s"%regionCombination])/ISR["Mean_%s"%regionCombination])
						else:
							Uncertainties["ISRUncertainty_%s"%regionCombination] = 0
							
						if BTag["Mean_%s"%regionCombination] > 0 and MCEvents["SFOF_%s"%regionCombination] > 100:
						#~ if BTag["Mean_%s"%regionCombination] > 0:
							Uncertainties["BTagUncertaintyHeavy_%s"%regionCombination] = abs(BTag["BTagHeavy_%s"%regionCombination]-BTag["Mean_%s"%regionCombination])/BTag["Mean_%s"%regionCombination]
							Uncertainties["BTagUncertaintyLight_%s"%regionCombination] = abs(BTag["BTagLight_%s"%regionCombination]-BTag["Mean_%s"%regionCombination])/BTag["Mean_%s"%regionCombination]
						else:
							Uncertainties["BTagUncertaintyHeavy_%s"%regionCombination] = 0
							Uncertainties["BTagUncertaintyLight_%s"%regionCombination] = 0
							
						if Met["Met_%s"%regionCombination] > 0  and MCEvents["SFOF_%s"%regionCombination] > 100:
						#~ if Met["Met_%s"%regionCombination] > 0:
							Uncertainties["MetUncertainty_%s"%regionCombination] = 0.5*abs(Met["Met_%s"%regionCombination]-Met["GenMet_%s"%regionCombination])/Yields["SFOF_%s"%regionCombination]
						else:
							Uncertainties["MetUncertainty_%s"%regionCombination] = 0
					
						if ScaleShift["Mean_%s"%regionCombination] > 0  and MCEvents["SFOF_%s"%regionCombination] > 100:
						#~ if ScaleShift["Mean_%s"%regionCombination] > 0:
							Uncertainties["ScaleUncertainty_%s"%regionCombination] = abs( (ScaleShift["MaxShift_%s"%regionCombination] - ScaleShift["Mean_%s"%regionCombination])/ScaleShift["Mean_%s"%regionCombination])
						else:
							Uncertainties["ScaleUncertainty_%s"%regionCombination] = 0
							
							
						#~ if Yields["SFOF_%s"%regionCombination] > 0:
							#~ Uncertainties["TriggerEffUncertainty_%s"%regionCombination] = sqrt((Yields["EE_%s"%regionCombination]*TriggerEffUncertainty)**2 + (Yields["MuMu_%s"%regionCombination]*TriggerEffUncertainty)**2 + (Yields["EMu_%s"%regionCombination]*TriggerEffUncertainty)**2)/Yields["SFOF_%s"%regionCombination]
						#~ else:
							#~ Uncertainties["TriggerEffUncertainty_%s"%regionCombination] = 0
						Uncertainties["TriggerEffUncertainty_%s"%regionCombination] = 0.05
								
						### Total syst uncertainty
						Uncertainties["SystUncertainty_%s"%regionCombination] = sqrt(Uncertainties["ScaleUncertainty_%s"%regionCombination]**2 + Uncertainties["JESUncertainty_%s"%regionCombination]**2 + Uncertainties["LeptonFastSimUncertainty_%s"%regionCombination]**2 + Uncertainties["LeptonFullSimUncertainty_%s"%regionCombination]**2 + Uncertainties["pileupUncertainty_%s"%regionCombination]**2 + Uncertainties["ISRUncertainty_%s"%regionCombination]**2 + Uncertainties["BTagUncertaintyLight_%s"%regionCombination]**2  + Uncertainties["BTagUncertaintyHeavy_%s"%regionCombination]**2  + Uncertainties["TriggerEffUncertainty_%s"%regionCombination]**2 + LumiUncertainty**2)
						
						### Total uncertainty
						Uncertainties["TotalUncertainty_%s"%regionCombination] = sqrt(Uncertainties["SystUncertainty_%s"%regionCombination]**2 + Uncertainties["StatUncertainty_%s"%regionCombination]**2)		
											
						for uncertainty in uncertaintySources:
							uncertaintyArrays["%s_%s"%(uncertainty,regionCombination)].append(Uncertainties["%s_%s"%(uncertainty,regionCombination)])					
								
			m_n += stepsize		
			
		m_b += stepsize
				
	for regionCombination in regionCombinations:
		
		for uncertainty in uncertaintySources:
			if regionCombination == "lowNll":
				regionName = "ttbar_like"
			else:
				regionName = "non_ttbar_like"
			Graphs["%s_%s"%(uncertainty,regionCombination)]=TGraph2D("%s_%s"%(uncertainty,regionName),"%s_%s"%(uncertainty,regionCombination), len(uncertaintyArrays["%s_%s"%(uncertainty,regionCombination)]), array('d',masses_b), array('d',masses_n), array('d',uncertaintyArrays["%s_%s"%(uncertainty,regionCombination)]))
			Graphs["%s_%s"%(uncertainty,regionCombination)].SetNpx(nxbins)
			Graphs["%s_%s"%(uncertainty,regionCombination)].SetNpy(nybins)
			Histograms["%s_%s"%(uncertainty,regionCombination)] = Graphs["%s_%s"%(uncertainty,regionCombination)].GetHistogram()
			Histograms["%s_%s"%(uncertainty,regionCombination)].SetTitle(";m_{#tilde{b}} [GeV]; m_{#tilde{#chi_{2}^{0}}} [GeV]")
		
		region_label = "Signal Region"
			
		if "lowNll" in regionCombination:
			region_label_2 = "ttbar like"
		elif "highNll" in region:
			region_label_2 = "non-ttbar like"		


		plotPad.SetLogz()
		Histograms["Yield_%s"%regionCombination].SetZTitle("SF-OF yield")
		Histograms["Yield_%s"%regionCombination].Draw("colz")
		latexLumi.DrawLatex(0.85, 0.96, "%s fb^{-1} (13 TeV)"%(printLumi,))
		latexCMS.DrawLatex(0.19,0.89,"CMS")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Private Work - Simulation")
		latexCMSExtra.DrawLatex(0.19,0.85,"Simulation")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Unpublished")
		latex.DrawLatex(0.175, 0.75, "#splitline{Simplified Model}{#splitline{T6bbslepton, m(#tilde{#chi}_{1}^{0})=100 GeV}{#splitline{"+region_label+"}{"+region_label_2+"}}}")
		canv.Update()
		canv.Print("fig/Yields/T6bbllslepton_%s.pdf"%(regionCombination))
		
		plotPad.SetLogz(0)
		Histograms["StatUncertainty_%s"%regionCombination].SetZTitle("SF-OF rel. stat. uncertainty")
		Histograms["StatUncertainty_%s"%regionCombination].Draw("colz")
		latexLumi.DrawLatex(0.85, 0.96, "%s fb^{-1} (13 TeV)"%(printLumi,))
		latexCMS.DrawLatex(0.19,0.89,"CMS")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Private Work - Simulation")
		latexCMSExtra.DrawLatex(0.19,0.85,"Simulation")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Unpublished")
		latex.DrawLatex(0.175, 0.75, "#splitline{Simplified Model}{#splitline{T6bbslepton, m(#tilde{#chi}_{1}^{0})=100 GeV}{#splitline{"+region_label+"}{"+region_label_2+"}}}")
		canv.Update()
		canv.Print("fig/statUncertainties/T6bbllslepton_%s_stat_err.pdf"%(regionCombination))
		
		
		Histograms["SystUncertainty_%s"%regionCombination].SetZTitle("SF-OF rel. syst. uncertainty")
		Histograms["SystUncertainty_%s"%regionCombination].Draw("colz")
		latexLumi.DrawLatex(0.85, 0.96, "%s fb^{-1} (13 TeV)"%(printLumi,))
		latexCMS.DrawLatex(0.19,0.89,"CMS")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Private Work - Simulation")
		latexCMSExtra.DrawLatex(0.19,0.85,"Simulation")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Unpublished")
		latex.DrawLatex(0.175, 0.75, "#splitline{Simplified Model}{#splitline{T6bbslepton, m(#tilde{#chi}_{1}^{0})=100 GeV}{#splitline{"+region_label+"}{"+region_label_2+"}}}")
		canv.Update()
		canv.Print("fig/sysUncertainties/T6bbllslepton_%s_syst_err.pdf"%(regionCombination))
		
		
		Histograms["TotalUncertainty_%s"%regionCombination].SetZTitle("SF-OF total rel. uncertainty")
		Histograms["TotalUncertainty_%s"%regionCombination].Draw("colz")
		latexLumi.DrawLatex(0.85, 0.96, "%s fb^{-1} (13 TeV)"%(printLumi,))
		latexCMS.DrawLatex(0.19,0.89,"CMS")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Private Work - Simulation")
		latexCMSExtra.DrawLatex(0.19,0.85,"Simulation")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Unpublished")
		latex.DrawLatex(0.175, 0.75, "#splitline{Simplified Model}{#splitline{T6bbslepton, m(#tilde{#chi}_{1}^{0})=100 GeV}{#splitline{"+region_label+"}{"+region_label_2+"}}}")
		canv.Update()
		canv.Print("fig/totUncertainties/T6bbllslepton_%s_tot_err.pdf"%(regionCombination))
		
		Histograms["Efficiency_%s"%regionCombination].SetZTitle("acceptance #times efficiency")
		Histograms["Efficiency_%s"%regionCombination].Draw("colz")
		latexLumi.DrawLatex(0.85, 0.96, "%s fb^{-1} (13 TeV)"%(printLumi,))
		latexCMS.DrawLatex(0.19,0.89,"CMS")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Private Work - Simulation")
		latexCMSExtra.DrawLatex(0.19,0.85,"Simulation")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Unpublished")
		latex.DrawLatex(0.175, 0.75, "#splitline{Simplified Model}{#splitline{T6bbslepton, m(#tilde{#chi}_{1}^{0})=100 GeV}{#splitline{"+region_label+"}{"+region_label_2+"}}}")
		canv.Update()
		canv.Print("fig/Efficiencies/T6bbllslepton_%s_signalEfficiency.pdf"%(regionCombination))
		
		Histograms["EfficiencyUnscaled_%s"%regionCombination].SetZTitle("acceptance #times efficiency")
		Histograms["EfficiencyUnscaled_%s"%regionCombination].Draw("colz")
		latexLumi.DrawLatex(0.85, 0.96, "%s fb^{-1} (13 TeV)"%(printLumi,))
		latexCMS.DrawLatex(0.19,0.89,"CMS")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Private Work - Simulation")
		latexCMSExtra.DrawLatex(0.19,0.85,"Simulation")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Unpublished")
		latex.DrawLatex(0.175, 0.75, "#splitline{Simplified Model}{#splitline{T6bbslepton, m(#tilde{#chi}_{1}^{0})=100 GeV}{#splitline{"+region_label+"}{"+region_label_2+"}}}")
		canv.Update()
		canv.Print("fig/Efficiencies/T6bbllslepton_%s_signalEfficiencyUnscaled.pdf"%(regionCombination))
		
		
		
			
		for uncertainty in uncertaintySources:
			if not ( uncertainty == "Yield" or uncertainty == "StatUncertainty" or uncertainty == "SystUncertainty" or uncertainty == "TotalUncertainty" or uncertainty == "Efficiency" or uncertainty == "EfficiencyUnscaled"):			
				Histograms["%s_%s"%(uncertainty,regionCombination)].SetZTitle("%s"%uncertainty)
				Histograms["%s_%s"%(uncertainty,regionCombination)].Draw("colz")
				latexLumi.DrawLatex(0.85, 0.96, "%s fb^{-1} (13 TeV)"%(printLumi,))
				latexCMS.DrawLatex(0.19,0.89,"CMS")
				#~ latexCMSExtra.DrawLatex(0.19,0.85,"Private Work - Simulation")
				latexCMSExtra.DrawLatex(0.19,0.85,"Simulation")
				#~ latexCMSExtra.DrawLatex(0.19,0.85,"Unpublished")
				latex.DrawLatex(0.175, 0.75, "#splitline{Simplified Model}{#splitline{T6bbslepton, m(#tilde{#chi}_{1}^{0})=100 GeV}{#splitline{"+region_label+"}{"+region_label_2+"}}}")
				canv.Update()
				canv.Print("fig/%s/T6bbllslepton_%s_%s.pdf"%(uncertainty,regionCombination,uncertainty))
	
	histoFile = TFile("fig/T6bbllslepton_XSecUpperLimit_and_ExclusionContours.root")
	
	histoXSection = TH2D(histoFile.Get("XSecUpperLimit"))
	graphExpectedUpperLimit = TGraph2D(histoFile.Get("ExpectedUpperLimit"))
	graphExpectedUpperLimitUp = TGraph2D(histoFile.Get("ExpectedUpperLimitUp"))
	graphExpectedUpperLimitDown = TGraph2D(histoFile.Get("ExpectedUpperLimitDown"))
	graphExpectedUpperLimitUp2 = TGraph2D(histoFile.Get("ExpectedUpperLimitUp2"))
	graphExpectedUpperLimitDown2 = TGraph2D(histoFile.Get("ExpectedUpperLimitDown2"))
	graphObservedUpperLimit = TGraph2D(histoFile.Get("ObservedUpperLimit"))
	graphObservedUpperLimitUp = TGraph2D(histoFile.Get("ObservedUpperLimitUp"))
	graphObservedUpperLimitDown = TGraph2D(histoFile.Get("ObservedUpperLimitDown"))
		
	f1 = TFile("fig/SummaryFile.root","RECREATE")
	for regionCombination in regionCombinations:
		Histograms["Yield_%s"%regionCombination].Write()
		Histograms["Efficiency_%s"%regionCombination].Write()
		Histograms["StatUncertainty_%s"%regionCombination].Write()
		Histograms["SystUncertainty_%s"%regionCombination].Write()
		Histograms["TotalUncertainty_%s"%regionCombination].Write()
		
	histoXSection.Write()
	graphExpectedUpperLimit.Write()
	graphExpectedUpperLimitUp.Write()
	graphExpectedUpperLimitDown.Write()
	graphExpectedUpperLimitUp2.Write()
	graphExpectedUpperLimitDown2.Write()
	graphObservedUpperLimit.Write()
	graphObservedUpperLimitUp.Write()
	graphObservedUpperLimitDown.Write()	
	
	f1.Close()			
def someOtherFunction():    
    gROOT.SetBatch()
    gStyle.SetOptStat(0)
    gStyle.SetOptTitle(0)
    gStyle.SetErrorX(0)
    setTDRStyle()

    labelcms  = TPaveText(0.12,0.88,0.5,0.94,"NDCBR")
    labelcms.SetTextAlign(12)
    labelcms.SetTextSize(0.045)
    labelcms.SetFillColor(kWhite)
    labelcms.AddText("CMS Preliminary, #sqrt{s} = 8 TeV")
    labelcms.SetBorderSize(0)

    labelcms2  = TPaveText(0.12,0.85,0.5,0.88,"NDCBR")
    labelcms2.SetTextAlign(12)
    labelcms2.SetTextSize(0.045)
    labelcms2.SetFillColor(kWhite)

    if options.cutMode == "ee":
        labelcms2.AddText("12.2 fb^{-1}, ee channel")
    if options.cutMode == "emu":
        labelcms2.AddText("12.2 fb^{-1}, e#mu channel")
    if options.cutMode == "mumu":
        labelcms2.AddText("12.2 fb^{-1}, #mu#mu channel")

#    labelcms2.AddText("12.2 fb^{-1}, ee,e#mu,#mu#mu channels")

    labelcms2.SetBorderSize(0)

    gStyle.SetPalette(1)
    gStyle.SetCanvasBorderMode(0)
    gStyle.SetCanvasColor(kWhite)
    gStyle.SetCanvasDefH(600)
    gStyle.SetCanvasDefW(600)
    gStyle.SetLabelFont(18,"")
    
    gStyle.SetTitleXOffset(1.2)
    gStyle.SetTitleYOffset(1.2)
    
    mcDists = THStack("mcDists", "MC Distributions")
    cutFlows['other'].SetFillColor(kGreen-3)
    cutFlows['other'].SetLineColor(kBlack)
    mcDists.Add(cutFlows['other'])
    cutFlows['zPlusJets'].SetFillColor(kAzure-2)
    cutFlows['zPlusJets'].SetLineColor(kBlack)
    mcDists.Add(cutFlows['zPlusJets'])
    cutFlows['ttbar'].SetFillColor(kRed+1)
    cutFlows['ttbar'].SetLineColor(kBlack)
    mcDists.Add(cutFlows['ttbar'])
    cutFlows['tW'].SetLineColor(kBlack)
    mcDists.Add(cutFlows['tW'])
    canvy = TCanvas("Control Region Plots", "Control Region Plots")
    canvy.cd()
    leg = TLegend(0.7,0.7,0.94,0.94)
    leg.SetFillStyle(1001)
    leg.SetFillColor(kWhite)
    leg.SetBorderSize(1)
    leg.AddEntry(cutFlows['data'], 'Data', 'p')
    leg.AddEntry(cutFlows['tW'], 'tW','f')
    leg.AddEntry(cutFlows['ttbar'], 't#bar{t}','f')
    leg.AddEntry(cutFlows['zPlusJets'], 'Z/#gamma*+jets','f')
    leg.AddEntry(cutFlows['other'], 'Other','f')
    cutFlows['data'].SetMarkerStyle(20)
    cutFlows['data'].SetMarkerSize(1.2)
    cutFlows['data'].SetLineWidth(1)
    cutFlows['data'].SetMarkerColor(kBlack)
    cutFlows['data'].SetLineColor(kBlack)
    max = TMath.Max(mcDists.GetMaximum(), cutFlows['data'].GetMaximum())
    mcDists.Draw('')
    mcDists.SetMaximum(max * 1.2)
    mcDists.SetMinimum(0)
    mcDists.GetXaxis().SetBinLabel(1,"Lepton Selection")
    mcDists.GetXaxis().SetBinLabel(2,"m_{ll}")
    mcDists.GetXaxis().SetBinLabel(3,"E_{T}^{miss}")
    mcDists.GetXaxis().SetBinLabel(4,"1 jet")
    mcDists.GetXaxis().SetBinLabel(5,"b-tag")
    mcDists.GetXaxis().SetBinLabel(6,"H_{T}")

    mcDists.GetYaxis().SetTitle("events / 12.2 fb^{-1}")
    mcDists.GetYaxis().CenterTitle()
    cutFlows['data'].Draw("e, sames")
    leg.Draw()
    labelcms.Draw()
    labelcms2.Draw()

    canvy.SaveAs(options.outFolder  + "cutFlow_" + options.cutMode + options.postfix + ".png")
    canvy.SaveAs(options.outFolder  + "cutFlow_" + options.cutMode + options.postfix + ".pdf")
    canvy.SaveAs(options.outFolder  + "cutFlow_" + options.cutMode + options.postfix + ".root")
    mcDists.SetMinimum(1)
    mcDists.SetMaximum(10*max)
    canvy.SetLogy()

    canvy.SaveAs(options.outFolder  + "cutFlow_" + options.cutMode + options.postfix + "_log.png")
    canvy.SaveAs(options.outFolder  + "cutFlow_" + options.cutMode + options.postfix + "_log.pdf")
    canvy.SaveAs(options.outFolder  + "cutFlow_" + options.cutMode + options.postfix + "_log.root")

    
    canvy.SetLogy(0)

    hextra =TH1F( cutFlows['other'].Clone())
    hextra.Add(cutFlows['zPlusJets'])
    hextra.Add(cutFlows['ttbar'])
    hextra.Add(cutFlows['tW'])
    hextra.Sumw2()
    setex2 = TExec("setex2","gStyle.SetErrorX(0.5)")
    setex2.Draw()
    hextra.Sumw2()
    GE = TGraphAsymmErrors(hextra)
    
    GE.SetFillColor(28)
    GE.SetFillStyle(3018)
    GE.SetMarkerSize(0)
    GE.SetLineWidth(0)
    GE.SetLineColor(kWhite)
    leg.AddEntry(GE,"uncertainty","f")
    mcDists.SetMaximum(max*1.2)
    mcDists.SetMinimum(0)
    GE.Draw("sames, e2")
    setex1 = TExec("setex1","gStyle.SetErrorX(0)")
    setex1.Draw()
    cutFlows['data'].Draw("e, sames")

    canvy.SaveAs(options.outFolder  + "error_cutFlow_" + options.cutMode + options.postfix + ".png")
    canvy.SaveAs(options.outFolder  + "error_cutFlow_" + options.cutMode + options.postfix + ".pdf")
    canvy.SaveAs(options.outFolder  + "error_cutFlow_" + options.cutMode + options.postfix + ".root")

    mcDists.SetMaximum(max * 10)
    mcDists.SetMinimum(1)
    canvy.SetLogy()

    canvy.SaveAs(options.outFolder  + "error_cutFlow_" + options.cutMode + options.postfix + "_log.png")
    canvy.SaveAs(options.outFolder  + "error_cutFlow_" + options.cutMode + options.postfix + "_log.pdf")
    canvy.SaveAs(options.outFolder  + "error_cutFlow_" + options.cutMode + options.postfix + "_log.root")
Beispiel #6
0
    def plot(self) :
        if len(self.data_) == 0 :
            print "No data!"
            return

        setTDRStyle()
        
        leg = TLegend( 0.15, 0.91-(0.045*(len(self.data_)+1)), 0.35, 0.91 )
        leg.SetFillColor(0)
        leg.SetLineColor(0) 
        leg.SetShadowColor(0) 
        leg.SetTextSize(0.035)
        
        mg = TMultiGraph()

        plot = self.fill(self.systematics(),systematics=True)
        plot.SetLineColor(kGray)
        plot.SetFillColor(kGray)
        mg.Add(plot,"2")
        leg.AddEntry(plot,"Systematic uncertainty","f")

        fit0 = []
        fit1 = []
        for idx,key in enumerate(self.data_.keys()) :
            #print "'%s'"%self.titles_[key]
            plot = self.fill(self.data_[key],index=idx)
            plot.SetTitle("")
            plot.SetMarkerStyle(self.markers_[idx])
            plot.SetMarkerSize(self.size_[idx])
            plot.SetLineColor(1)
            plot.SetLineWidth(2)
            mg.Add(plot,"pZ")
            leg.AddEntry(plot,self.titles_[key],"p")
            f0,f1 = self.fit(plot)
            fit0.append(f0)
            fit1.append(f1)

        self.pvalues([i[4] for i in fit0],"p-values from constant fits")
        print "'%s': p0 = %.2f+/-%.2f, chi2/dof = %.2f/%i, p-value = %.2f" \
            %(self.titles_[key],f0[0],f0[1],f0[2],f0[3],f0[4])

        self.pvalues([i[6] for i in fit1],"p-values from linear fits")
        print "'%s': p0 = %.2f+/-%.2f, p1 = %.4f+/-%.4f, chi2/dof = %.2f/%i, p-value = %.2f" \
            %(self.titles_[key],f1[0],f1[1],f1[2],f1[3],f1[4],f1[5],f1[6])
            
        canvas = TCanvas("Closure tests","",900,600)
        mg.Draw("ap")
        mg.GetXaxis().SetTitle("H_{T} (GeV)")
        mg.GetYaxis().SetTitle("( N_{obs} - N_{pred} ) / N_{pred}")
        #mg.GetYaxis().SetRangeUser(-1.25,2.25)
        mg.GetYaxis().SetRangeUser(-2.,4.)
        mg.GetXaxis().SetRangeUser(self.bins_[0],self.bins_[self.nbins_])
        mg.GetXaxis().SetNdivisions(510)
        leg.Draw("same")
        prelim = "CMS Preliminary" if self.prelim_ else "CMS"
        str1 = "#splitline{%s}{L_{int} = %s fb^{-1}, #sqrt{s} = %s TeV}" % ( prelim, self.lumi_, self.energy_ )
        txt1 = TLatex(0.62,(0.91-0.06),str1)
        txt1.SetNDC()
        txt1.SetTextSize(0.04)
        txt1.Draw("same")

        str2 = ""
        temp = self.data_.keys()[0]
        if temp.count("_all") > 0 :
            str2 = "n_{jet} #geq 2"
        elif temp.count("_2") > 0 :
            str2 = "2 #leq n_{jet} #leq 3"
        elif temp.count("_3") > 0 :
            str2 = "n_{jet} #geq 4"
        else :
            str2 = "n_{jet} ERROR!"
        txt2 = TLatex(0.62,0.76,str2)
        txt2.SetNDC()
        txt2.SetTextSize(0.04)
        txt2.Draw()

        canvas.Update()
        canvas.SaveAs(self.label_+"/summary_plot.pdf")
        if not self.batch_ : input("Press any key to continue...")
Beispiel #7
0
def doPUCorrection(plotData=True,nJets=2,direction="Central",extraArg=""):
    dilepton = "SF"
    bkg = getBackgrounds("TT","DY","DYTauTau")

    nPoints = 0
    setTDRStyle()
    ROOT.gStyle.SetOptFit(111)
    ROOT.gStyle.SetErrorX(0.5)
    
    bins = array('f',[0,7,10,15,31])
    nBins = len(bins)-1
    pointsHist = ROOT.TH1F("h","", nBins,bins)
    
    nVCuts = ["nVert06", "nVert79", "nVert1014", "nVert1530"]
    
    for nVCut in nVCuts:       
        mainConfig = dataMCConfig.dataMCConfig(plot="jzbPlot_puCorr_%dj#jzb50#%s"%(nJets,nVCut),region=direction,runName="Run2015_25ns",plotData=plotData,normalizeToData=False,plotRatio=False,signals=False,useTriggerEmulation=True,personalWork=True,preliminary=False,forPAS=False,forTWIKI=False,backgrounds=bkg,dontScaleTrig=False,plotSyst=False,doPUWeights=False, responseCorr=False)
        
        histSF = produceHistogram("SF", mainConfig)
        histEM = produceHistogram("EMu", mainConfig)
        if mainConfig.plotData:
            R = getattr(mainConfig.rSFOF, direction.lower()).val
        else:
            R = getattr(mainConfig.rSFOF, direction.lower()).valMC
        histSF.Add(histEM,-R)

        tempHist = histSF.Clone()
        tempHist.Scale(1./tempHist.Integral())
        tempHist.SetMinimum(0)
        can = ROOT.TCanvas()
        tempFunc = ROOT.TF1("temf","gaus",-50,50)
        tempHist.Fit(tempFunc,"RQ")
        tempHist.Draw()
        tempFunc.Draw("same")
        ensurePathExists("fig/%s/PUCorr/%d/%dj/%s/"%(mainConfig.jzbType, mainConfig.correctionMode,nJets,direction))
        can.SaveAs("fig/%s/PUCorr/%d/%dj/%s/%s.pdf"%(mainConfig.jzbType, mainConfig.correctionMode,nJets,direction,nVCut.split("nVert")[1]))
        

        ymean = tempFunc.GetParameter(1)
        yerr = tempFunc.GetParError(1)
        
        nPoints+=1
        pointsHist.SetBinContent(nPoints, ymean)
        pointsHist.SetBinError(nPoints, yerr)
        
     
    template = plotTemplate(mainConfig)
    ROOT.gStyle.SetOptFit(111)
    ROOT.gStyle.SetErrorX(0.5)
    template.dilepton = dilepton
    template.changeScale = False
    fitLine = TF1("fitLine", "pol1",0,31)
    fitLine.SetParName(1, "#beta")
    fitLine.SetParameter(1,0.1747)
    fitLine.SetParameter(0,3.78)
    pointsHist.Fit(fitLine, "R%s"%(extraArg))
    
    with open("shelves/%s_%d.pkl"%(mainConfig.jzbType,mainConfig.correctionMode), "r+") as corrFile:        
        corrs = pickle.load(corrFile)
        corrFile.seek(0) 
        corrFile.truncate()
        
        corrs[mainConfig.plotData][direction]["pu"][nJets==2] = fitLine.GetParameter(1)
        pickle.dump(corrs, corrFile)
        corrFile.close()
    
    jetInd = "#geq3j" if nJets == 3 else "=2j"
    template.cutsText = jetInd
    template.labelX = "N_{Vertices}"
    template.labelY = "JZB Peak Position [GeV]"
    template.regionName = direction

    template.setPrimaryPlot(pointsHist, "pe")
    template.addSecondaryPlot(fitLine,"")
    
    template.draw()
    
    template.canvas.Update()
    pointsHist.GetListOfFunctions()
    panel = pointsHist.GetListOfFunctions().FindObject("stats")
    panel.SetX1NDC(0.65)
    panel.SetX2NDC(0.95)
    panel.SetY1NDC(0.14)
    panel.SetY2NDC(0.38)
    template.draw()
    
    template.setFolderName("PUCorr/%d"%(mainConfig.correctionMode))
    dataInd = "Data" if plotData else "MC"
    template.saveAs("puSlope_%dj_%s_%s"%(nJets, direction, dataInd))
Beispiel #8
0
def makePlots(inputfiles,draw,title,legends,outname):
    style = setTDRStyle()
    ROOT.gStyle.SetTitleYOffset(1.45)
    ROOT.gStyle.SetTitleXOffset(1.45)
    ROOT.gStyle.SetOptFit(0)
    ROOT.gStyle.SetStatX(.9)
    ROOT.gStyle.SetStatY(.9)

    c1 = ROOT.TCanvas('c1')
    
    _files=[]
    for i in inputfiles:
        print "Opening %s..." %(i)
        _files.append(ROOT.TFile(i))
        

    _hists=[]
    _hist = ROOT.TH1F()
    _hist.SetDirectory(0)

    if logY: outname+="_log"
    
    o = open(outname+'.txt', 'w')
    for i,f in enumerate(_files):
        for k,p in enumerate(draw):
            histname = "%s" %(p)
            _hist = f.Get(histname).Clone()
            _hist.SetDirectory(0)
            _hists.append(_hist)
            if "Eff" in p:
                o.write('%s \t %5.4f + %5.4f - %5.4f\n' %(legends[i],_hist.GetEfficiency(1),_hist.GetEfficiencyErrorLow(1),_hist.GetEfficiencyErrorUp(1)))            
    o.close()
 
    leg = ROOT.TLegend(0.30,0.15,0.70,0.3);
#    leg = ROOT.TLegend(0.55,0.65,0.90,0.80);
    leg.SetLineColor(0);
    leg.SetFillStyle(0);
    leg.SetBorderSize(0)
    
    k=0
    for hist in _hists:
        if "h_" in draw[0]:
            hist.Scale(1./hist.GetEntries())
        hist.SetLineWidth(2)
        hist.SetLineColor(k+1)
        hist.SetTitle(title)
        
        if k==0 :
            if logY: c1.SetLogy()
            if logX: c1.SetLogx()
            if "Vs" in draw[0]:
                hist.Draw("BOX")
            else: 
                hist.Draw("")
            
            if "h_" not in draw[0]:
                ROOT.gPad.Update()
                graph = hist.GetPaintedGraph()
                graph.SetMinimum(YMIN)
                graph.SetMaximum(YMAX)
                ROOT.gPad.Update()
        else:
            hist.Draw("SAME")

        leg.AddEntry(hist,legends[k],"l")
        k+=1
    
    if len(_hists)>1:
        leg.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, "(13 TeV)")
    
    cmsExtra = "Private" 
    latexCMS.DrawLatex(0.78,0.88,"CMS")
    yLabelPos = 0.84
    latexCMSExtra.DrawLatex(0.78,yLabelPos,"%s"%(cmsExtra))
    
    c1.SaveAs(outname+".root");
    c1.SaveAs(outname+".pdf");
    c1.SaveAs(outname+".png");
def plot(path,selection,plots,runRange,isMC,backgrounds,cmsExtra):
	

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


		if isMC:
			histEE, histMM = getHistograms(path,plot,runRange,True, backgrounds)	
		else:
			histEE, histMM = getHistograms(path,plot,runRange,False, backgrounds)	
			
		
		hCanvas = TCanvas("hCanvas", "Distribution", 800,800)
		
		plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1)
		setTDRStyle()
		plotPad.UseCurrentStyle()
		
		plotPad.Draw()	
		plotPad.cd()	
				
			
		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.06)
		latexCMS.SetNDC(True)
		latexCMSExtra = ROOT.TLatex()
		latexCMSExtra.SetTextFont(52)
		latexCMSExtra.SetTextSize(0.045)
		latexCMSExtra.SetNDC(True)		

		intlumi = ROOT.TLatex()
		intlumi.SetTextAlign(12)
		intlumi.SetTextSize(0.03)
		intlumi.SetNDC(True)					
		

		logScale = plot.log

		if logScale == True:
			plotPad.SetLogy()
			
	
		yMax = histMM.GetBinContent(histMM.GetMaximumBin())
		if plot.yMax == 0:
			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))
		
		legend = ROOT.TLegend(0.65,0.7,0.9,0.9)
		legend.SetFillStyle(0)
		legend.SetBorderSize(0)	
		legend.AddEntry(histMM,"#mu#mu events","p")
		legend.AddEntry(histEE,"ee events","p")
		histMM.SetMarkerColor(ROOT.kRed)
		histMM.SetLineColor(ROOT.kRed)
		histMM.SetMarkerStyle(20)
		histEE.SetMarkerStyle(21)
		histMM.Draw("samepe")
		histEE.Draw("samepe")
		legend.Draw("same")
		ROOT.gPad.SetLogy(1)
		
		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.81	
		else:
			yLabelPos = 0.84	

		latexCMSExtra.DrawLatex(0.19,yLabelPos,"%s"%(cmsExtra))
		
		
		
		hCanvas.Print("fig/testPlots_%s_%s_%s_%s.pdf"%(selection.name,runRange.label,plot.variablePlotName,plot.additionalName))	
def plot():
	import re
	import ratios
	from ROOT import TCanvas, TPad, TH1F, TH2F, TH1I, THStack, TLegend, TMath, TF1, TGraph, TGraph2D, TFile, TObjArray, gROOT
	from setTDRStyle import setTDRStyle
	import pickle
	from defs import sbottom_masses
	from math import sqrt
	
	canv = TCanvas("canv", "canv",800,800)
	plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1)
	style=setTDRStyle()	
	style.SetPadRightMargin(0.18)		
	style.SetTitleYOffset(1.54)	
	plotPad.UseCurrentStyle()
	plotPad.Draw()	
	plotPad.cd()
	
	Graphs = {}
	Histograms = {}
	
	printLumi = "35.9"
	
	m_n_min = 150
	m_n_max = 1550
	m_b_min = 700
	m_b_max = 1600
	
		
	masses_b = []
	masses_n = []
	significances = []
		
	m_b = m_b_min
	while m_b <= m_b_max:
		if m_b < 800:
			stepsize = 25
		else:
			stepsize = 50
			
		m_n = m_n_min
		
		while m_n < m_b:
			
			#~ if not ((m_b == 775 and m_n == 750) or (m_b == 800 and m_n == 150) or (m_b == 950 and m_n == 250) or (m_b == 950 and m_n == 300) or (m_b == 950 and m_n == 500) or (m_b == 950 and m_n == 550) or (m_b == 950 and m_n == 850) or (m_b == 950 and m_n == 900)):	
				
			#~ print "Limits/T6bbllslepton_%s_%s.result.txt"%(str(m_b),str(m_n))
			limitFile = open("Significances/T6bbllslepton_%s_%s.result.txt"%(str(m_b),str(m_n)),"r")
			masses_b.append(m_b)
			masses_n.append(m_n)
			M_SBOTTOM = "m_b_"+str(m_b)
			
			for line in limitFile:
				
				if "observed significance" in line:
					#~ significance = float(re.findall("\d+\.\d+",line)[0])
					significance = float(re.findall(r"[-+]?\d*\.\d+|\d+",line)[0])
					#~ print significance
					
					if significance < -3.5:
						significance = -3.49

					significances.append(significance)
					
			m_n += stepsize		
		m_b += stepsize
		
	bin_size =12.5
	nxbins = int(min(500,(m_b_max-m_b_min)/bin_size))
	nybins = int(min(500,(m_n_max-m_n_min)/bin_size))
	
	
	Graph = TGraph2D("Graph_significance","Local significance", len(significances), array('d',masses_b), array('d',masses_n), array('d',significances))
	Graph.SetNpx(nxbins)
	Graph.SetNpy(nybins)
	
	
	
	Histogram = Graph.GetHistogram()
	Histogram.SetTitle(";m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	Histogram.GetZaxis().SetRangeUser(-3.5,3.5)
	
	
	latex = ROOT.TLatex()
	latex.SetTextSize(0.03)
	latex.SetNDC(True)
	latexLumi = ROOT.TLatex()
	latexLumi.SetTextFont(42)
	latexLumi.SetTextAlign(31)
	latexLumi.SetTextSize(0.04)
	latexLumi.SetNDC(True)
	latexCMS = ROOT.TLatex()
	latexCMS.SetTextFont(61)
	latexCMS.SetTextSize(0.05)
	latexCMS.SetNDC(True)
	latexCMSExtra = ROOT.TLatex()
	latexCMSExtra.SetTextFont(52)
	latexCMSExtra.SetTextSize(0.0375)
	latexCMSExtra.SetNDC(True)
	
	latexLegendHeader = ROOT.TLatex() 
	latexLegendHeader.SetTextSize(0.032)
	latexLegendHeader.SetTextFont(42)
	latexLegendHeader.SetNDC(True)
	
	Overlay = ROOT.TGraph(0)
	Overlay.SetPoint(0, 700, 625)
	Overlay.SetPoint(1, 1650, 1575)
	Overlay.SetPoint(2, 700, 1575)
	Overlay.SetPoint(3, 700, 625)
	Overlay.SetFillColor(0)
	
	oneLine = ROOT.TLine(400, 375, 950, 900)
	oneLine.SetLineStyle(9)
	oneLine.SetLineWidth(2)
	
	leg1 = ROOT.TLegend(0.19,0.78,0.83,0.92)
	leg1.SetBorderSize(1)
	leg1.SetLineWidth(2)
	
	leg = ROOT.TLegend(0.195,0.785,0.825,0.82)
	leg.SetTextSize(0.025)
	leg.SetBorderSize(0)
	leg.SetLineWidth(0)
	
	plotPad.SetTopMargin(0.08)
	plotPad.SetBottomMargin(0.16)
	plotPad.SetLeftMargin(0.19)
	plotPad.SetRightMargin(0.17)
	
	plotPad.DrawFrame(700,150,1600,1750,";m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	
	Histogram.SetZTitle("Observed Local Significance (#sigma)")
	Histogram.GetZaxis().SetLabelSize(0.045)
	Histogram.GetZaxis().SetTitleSize(0.045)
	Histogram.GetZaxis().SetTitleOffset(1.1)
	Histogram.Draw("SAME COLZ")
	Overlay.Draw("f")
	
	
	latexLumi.DrawLatex(0.83, 0.94, "%s fb^{-1} (13 TeV)"%(printLumi))
	latexCMS.DrawLatex(0.185,0.94,"CMS")
	latexCMSExtra.DrawLatex(0.289,0.94,"Preliminary")
	plotPad.RedrawAxis()
	leg1.Draw("same")
	leg.Draw("same")
	latexLegendHeader.DrawLatex(0.2, 0.84, "#splitline{pp #rightarrow #tilde{b} #tilde{b}, #tilde{b} #rightarrow #tilde{#chi}_{2}^{0} b, #tilde{#chi}_{2}^{0} #rightarrow #tilde{l} l / Z #tilde{#chi}_{1}^{0}, #tilde{l} #rightarrow #tilde{#chi}_{1}^{0} l}{m_{#tilde{#chi_{1}}^{0}} = 100 GeV, m_{#tilde{l}} = 0.5 (m_{#tilde{#chi}_{2}^{0}} + m_{#tilde{#chi}_{1}^{0}})}")
	canv.Update()
	canv.Print("fig/Significances.pdf")
	
	
	
	Histogram.SetName("ObsSignificance")
	
	Graph.SetName("ObsSignificance")
	
	Graph.SetTitle("Observed Local Significance in #sigma")
	
	f1 = TFile("fig/T6bbllslepton_Significance.root","RECREATE")
	Histogram.Write()
	f1.Close()
Beispiel #11
0
def plot():
	import re
	import ratios
	from ROOT import TCanvas, TPad, TH1F, TH2F, TH1I, THStack, TLegend, TMath, TF1, TGraph, TGraph2D, TFile, TObjArray, gROOT
	from setTDRStyle import setTDRStyle
	import pickle
	from defs import sbottom_masses
	from math import sqrt
	
	canv = TCanvas("canv", "canv",800,800)
	plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1)
	style=setTDRStyle()	
	style.SetPadRightMargin(0.18)	
	style.SetTitleYOffset(1.54)	
	plotPad.UseCurrentStyle()
	plotPad.Draw()	
	plotPad.cd()
	
	exclusionContours = ["obsR","obsR_up","obsR_down","expR","expR_up","expR_down","expR_2up","expR_2down","obsXsecLimit"]
	Graphs = {}
	Histograms = {}
	
	printLumi = "35.9"
	
	m_n_min = 150
	m_n_max = 1550
	#~ m_n_max = 1450
	m_b_min = 700
	m_b_max = 1600
	#~ m_b_max = 1450
	
	
	Exclusions = {}	
	
	for exclusionContour in exclusionContours:
		Exclusions[exclusionContour] = []
		
	masses_b = []
	masses_n = []
	cross_sections = []
		
	m_b = m_b_min
	while m_b <= m_b_max:
		if m_b < 800:
			stepsize = 25
		else:
			stepsize = 50
			
		m_n = m_n_min
		
		while m_n < m_b:
			
			### Privately produced points that were missing before have less statistics
			### than the surrounding points -> cause some strange effects in plot
			### better to ignore them and let root interpolate the histogram
			if not ((m_b == 775 and m_n == 750) or (m_b == 800 and m_n == 150) or (m_b == 950 and m_n == 250) or (m_b == 950 and m_n == 300) or (m_b == 950 and m_n == 500) or (m_b == 950 and m_n == 550) or (m_b == 950 and m_n == 850) or (m_b == 950 and m_n == 900)):	
				limitFile = open("Limits/T6bbllslepton_%s_%s.result.txt"%(str(m_b),str(m_n)),"r")
				masses_b.append(m_b)
				masses_n.append(m_n)
				M_SBOTTOM = "m_b_"+str(m_b)
				xSection = getattr(sbottom_masses, M_SBOTTOM).cross_section13TeV
				xsectionUncert = getattr(sbottom_masses, M_SBOTTOM).cross_sectionUncertainty
				cross_sections.append(xSection)
				
				for line in limitFile:
					
					if "CLs observed asymptotic" in line:
						observed_R = float(re.findall("\d+\.\d+",line)[0])
	
						Exclusions["obsR"].append(observed_R)
						Exclusions["obsR_up"].append(observed_R*(1+xsectionUncert))
						Exclusions["obsR_down"].append(observed_R*(1-xsectionUncert))
						
						Exclusions["obsXsecLimit"].append(observed_R*xSection)
											
					if "CLs expected asymptotic" in line:
						Exclusions["expR"].append(float(re.findall("\d+\.\d+",line)[0]))
						
					if "CLs expected m1sigma asymptotic" in line:
						Exclusions["expR_down"].append(float(re.findall("\d+\.\d+",line)[0]))
						
					if "CLs expected p1sigma asymptotic" in line:
						Exclusions["expR_up"].append(float(re.findall("\d+\.\d+",line)[0]))
					
					if "CLs expected m2sigma asymptotic" in line:
						Exclusions["expR_2down"].append(float(re.findall("\d+\.\d+",line)[0]))
						
					if "CLs expected p2sigma asymptotic" in line:
						Exclusions["expR_2up"].append(float(re.findall("\d+\.\d+",line)[0]))
				
			m_n += stepsize		
		m_b += stepsize
		
	bin_size =12.5
	nxbins = int(min(500,(m_b_max-m_b_min)/bin_size))
	nybins = int(min(500,(m_n_max-m_n_min)/bin_size))
	
	for exclusionContour in exclusionContours:
		Graphs[exclusionContour] = TGraph2D("Graph_%s"%(exclusionContour),exclusionContour, len(Exclusions[exclusionContour]), array('d',masses_b), array('d',masses_n), array('d',Exclusions[exclusionContour]))
	
	dots = TGraph(len(masses_b), array('d',masses_b), array('d',masses_n))
	
	contours = array('d',[1.0])
	
	Histograms["obsXsecLimit"] = Graphs["obsXsecLimit"].GetHistogram()
	Histograms["obsXsecLimit"].SetTitle("Observed cross section limit;m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	Histograms["obsXsecLimit"].GetZaxis().SetRangeUser(0.0002,0.05)
		
	Histograms["expR"] = Graphs["expR"].GetHistogram()	
	Histograms["expR"].SetContour(1,contours)
	Histograms["expR"].SetLineWidth(4)
	Histograms["expR"].SetLineStyle(2)
	Histograms["expR"].SetLineColor(2)
	Histograms["expR"].Smooth()
		
	Histograms["expR_up"] = Graphs["expR_up"].GetHistogram()	
	Histograms["expR_up"].SetContour(1,contours)
	Histograms["expR_up"].SetLineWidth(2)
	Histograms["expR_up"].SetLineStyle(2)
	Histograms["expR_up"].SetLineColor(2)
	Histograms["expR_up"].Smooth()
	
	Histograms["expR_down"] = Graphs["expR_down"].GetHistogram()	
	Histograms["expR_down"].SetContour(1,contours)
	Histograms["expR_down"].SetLineWidth(2)
	Histograms["expR_down"].SetLineStyle(2)
	Histograms["expR_down"].SetLineColor(2)
	Histograms["expR_down"].Smooth()
	
	Histograms["expR_2up"] = Graphs["expR_2up"].GetHistogram()	
	Histograms["expR_2up"].SetContour(1,contours)
	Histograms["expR_2up"].SetLineWidth(2)
	Histograms["expR_2up"].SetLineStyle(2)
	Histograms["expR_2up"].SetLineColor(2)
	Histograms["expR_2up"].Smooth()
	
	Histograms["expR_2down"] = Graphs["expR_2down"].GetHistogram()	
	Histograms["expR_2down"].SetContour(1,contours)
	Histograms["expR_2down"].SetLineWidth(2)
	Histograms["expR_2down"].SetLineStyle(2)
	Histograms["expR_2down"].SetLineColor(2)
	Histograms["expR_2down"].Smooth()
	
	Histograms["obsR"] = Graphs["obsR"].GetHistogram()	
	Histograms["obsR"].SetContour(1,contours)
	Histograms["obsR"].SetLineWidth(4)
	Histograms["obsR"].SetLineStyle(1)
	Histograms["obsR"].SetLineColor(1)
	Histograms["obsR"].Smooth()
	
	Histograms["obsR_up"] = Graphs["obsR_up"].GetHistogram()	
	Histograms["obsR_up"].SetContour(1,contours)
	Histograms["obsR_up"].SetLineWidth(2)
	Histograms["obsR_up"].SetLineStyle(1)
	Histograms["obsR_up"].SetLineColor(1)
	Histograms["obsR_up"].Smooth()
	
	Histograms["obsR_down"] = Graphs["obsR_down"].GetHistogram()	
	Histograms["obsR_down"].SetContour(1,contours)
	Histograms["obsR_down"].SetLineWidth(2)
	Histograms["obsR_down"].SetLineStyle(1)
	Histograms["obsR_down"].SetLineColor(1)
	Histograms["obsR_down"].Smooth()
	
	
	
	latex = ROOT.TLatex()
	latex.SetTextSize(0.03)
	latex.SetNDC(True)
	latexLumi = ROOT.TLatex()
	latexLumi.SetTextFont(42)
	latexLumi.SetTextAlign(31)
	latexLumi.SetTextSize(0.04)
	latexLumi.SetNDC(True)
	latexCMS = ROOT.TLatex()
	latexCMS.SetTextFont(61)
	latexCMS.SetTextSize(0.05)
	latexCMS.SetNDC(True)
	latexCMSExtra = ROOT.TLatex()
	latexCMSExtra.SetTextFont(52)
	latexCMSExtra.SetTextSize(0.0375)
	latexCMSExtra.SetNDC(True)
	
	latexLegendHeader = ROOT.TLatex() 
	latexLegendHeader.SetTextSize(0.025)
	latexLegendHeader.SetNDC(True)
	
	Overlay = ROOT.TGraph(0)
	Overlay.SetPoint(0, 700, 625)
	Overlay.SetPoint(1, 1650, 1575)
	Overlay.SetPoint(2, 700, 1575)
	Overlay.SetPoint(3, 700, 625)
	Overlay.SetFillColor(0)
	
	leg1 = ROOT.TLegend(0.19,0.72,0.83,0.92)
	leg1.SetBorderSize(1)
	leg1.SetLineWidth(2)
	
	leg = ROOT.TLegend(0.195,0.725,0.825,0.82)
	leg.SetTextSize(0.025)
	leg.SetBorderSize(0)
	leg.SetLineWidth(0)
	leg.AddEntry(Histograms["expR"], "Expected limit, #pm 1 (2) #sigma_{exp.}","l")
	leg.AddEntry(Histograms["obsR"], "Observed limit, #pm 1 #sigma_{theory}","l")
	
	plotPad.SetTopMargin(0.08)
	plotPad.SetBottomMargin(0.13)
	plotPad.SetLeftMargin(0.19)
	plotPad.SetRightMargin(0.17)
	
	
	
	
	plotPad.DrawFrame(700,150,1600,1750,";m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	
	plotPad.SetLogz()
	#~ Histograms["obsXsecLimit"].GetYaxis().SetTitleOffset(1.5)
	Histograms["obsXsecLimit"].SetZTitle("95% CL upper limit on #sigma [pb]")
	Histograms["obsXsecLimit"].GetZaxis().SetLabelSize(0.035)
	Histograms["obsXsecLimit"].GetZaxis().SetTitleOffset(1.0)
	Histograms["obsXsecLimit"].Draw("SAME COLZ")
	Histograms["expR_2up"].Draw("SAMECONT3")
	Histograms["expR_2down"].Draw("SAMECONT3")
	Histograms["expR_up"].Draw("SAMECONT3")
	Histograms["expR_down"].Draw("SAMECONT3")
	Histograms["expR"].Draw("SAMECONT3")
	Histograms["obsR_up"].Draw("SAMECONT3")
	Histograms["obsR_down"].Draw("SAMECONT3")
	Histograms["obsR"].Draw("SAMECONT3")
	Overlay.Draw("f")
	
	latexLumi.DrawLatex(0.83, 0.94, "%s fb^{-1} (13 TeV)"%(printLumi))
	latexCMS.DrawLatex(0.185,0.94,"CMS")
	#~ latexCMSExtra.DrawLatex(0.29,0.94,"Preliminary")
	plotPad.RedrawAxis()
	leg1.Draw("same")
	leg.Draw("same")
	latexLegendHeader.DrawLatex(0.2, 0.85, "#splitline{pp#rightarrow#tilde{b}#tilde{b}, #tilde{b}#rightarrow#tilde{#chi}_{2}^{0}b, #tilde{#chi}_{2}^{0}#rightarrow#tilde{l}l/Z#tilde{#chi}_{1}^{0}, #tilde{l}#rightarrow#tilde{#chi}_{1}^{0}l; m_{#tilde{#chi_{1}}^{0}}= 100 GeV}{m_{#tilde{l}} = 0.5(m_{#tilde{#chi}_{2}^{0}}+ m_{#tilde{#chi}_{1}^{0}}); NLO+NLL exclusion}")
	canv.Update()
	canv.Print("fig/LimitPlot.pdf")
	canv.Print("fig/LimitPlot.png")
	
	
	
	Histograms["obsXsecLimit"].SetName("XSecUpperLimit")
	Histograms["expR"].SetName("ExpectedUpperLimit")
	Histograms["expR_up"].SetName("ExpectedUpperLimitUp")
	Histograms["expR_down"].SetName("ExpectedUpperLimitDown")
	Histograms["expR_2up"].SetName("ExpectedUpperLimitUp2")
	Histograms["expR_2down"].SetName("ExpectedUpperLimitDown2")
	Histograms["obsR"].SetName("ObservedUpperLimit")
	Histograms["obsR_up"].SetName("ObservedUpperLimitUp")
	Histograms["obsR_down"].SetName("ObservedUpperLimitDown")
	
	Graphs["expR"].SetName("ExpectedUpperLimit")
	Graphs["expR_up"].SetName("ExpectedUpperLimitUp")
	Graphs["expR_down"].SetName("ExpectedUpperLimitDown")
	Graphs["expR_2up"].SetName("ExpectedUpperLimitUp2")
	Graphs["expR_2down"].SetName("ExpectedUpperLimitDown2")
	Graphs["obsR"].SetName("ObservedUpperLimit")
	Graphs["obsR_up"].SetName("ObservedUpperLimitUp")
	Graphs["obsR_down"].SetName("ObservedUpperLimitDown")
	
	Histograms["expR"].SetTitle("Expected Upper Limit;m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	Histograms["expR_up"].SetTitle("Expected Upper Limit + 1 #sigma;m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	Histograms["expR_down"].SetTitle("Expected Upper Limit - 1 #sigma;m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	Histograms["expR_2up"].SetTitle("Expected Upper Limit + 2 #sigma;m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	Histograms["expR_2down"].SetTitle("Expected Upper Limit - 2 #sigma;m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	Histograms["obsR"].SetTitle("Observed Upper Limit;m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	Histograms["obsR_up"].SetTitle("Observed Upper Limit + 1 #sigma;m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	Histograms["obsR_down"].SetTitle("Observed Upper Limit - 1 #sigma;m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	
	f1 = TFile("fig/T6bbllslepton_XSecUpperLimit_and_ExclusionContours.root","RECREATE")
	Histograms["obsXsecLimit"].Write()
	Histograms["expR"].Write()
	Histograms["expR_up"].Write()
	Histograms["expR_down"].Write()
	Histograms["expR_2up"].Write()
	Histograms["expR_2down"].Write()
	Histograms["obsR"].Write()
	Histograms["obsR_up"].Write()
	Histograms["obsR_down"].Write()
	f1.Close()