def getHistograms(path,source,modifier,plot,runRange,isMC,backgrounds,region=""):

	treesEE = readTrees(path,"EE",source = source,modifier= modifier)
	treesEM = readTrees(path,"EMu",source = source,modifier= modifier)
	treesMM = readTrees(path,"MuMu",source = source,modifier= modifier)
		
	
	histosEE = []
	histosMM = []
	histosEM = []

		#~ print path, source, modifier
	eventCounts = totalNumberOfGeneratedEvents(path,source,modifier)	
	processes = []
	for background in backgrounds:
		processes = []

		processes.append(Process(getattr(Backgrounds,background),eventCounts))
		
		histosEE.append(TheStack(processes,runRange.lumi,plot,treesEE,"None",1.0,1.0,1.0).theHistogram)		
		histosMM.append(TheStack(processes,runRange.lumi,plot,treesMM,"None",1.0,1.0,1.0).theHistogram)
		histosEM.append(TheStack(processes,runRange.lumi,plot,treesEM,"None",1.0,1.0,1.0).theHistogram)
						

			

	
	return histosEE , histosMM, histosEM
def getHistograms(path, plot, runRange, isMC, backgrounds, region=""):

    treesEE = readTrees(path, "EE")
    treesEM = readTrees(path, "EMu")
    treesMM = readTrees(path, "MuMu")

    if isMC:

        eventCounts = totalNumberOfGeneratedEvents(path)
        processes = []
        for background in backgrounds:
            processes.append(
                Process(getattr(Backgrounds, background), eventCounts))
        histoEE = TheStack(processes, runRange.lumi, plot, treesEE, "None",
                           1.0, 1.0, 1.0).theHistogram
        histoMM = TheStack(processes, runRange.lumi, plot, treesMM, "None",
                           1.0, 1.0, 1.0).theHistogram
        histoEM = TheStack(processes, runRange.lumi, plot, treesEM, "None",
                           1.0, 1.0, 1.0).theHistogram
        histoEE.Scale(getattr(triggerEffs, region).effEE.val)
        histoEE.Scale(getattr(triggerEffs, region).effMM.val)
        histoEM.Scale(getattr(triggerEffs, region).effEM.val)

    else:
        histoEE = getDataHist(plot, treesEE)
        histoMM = getDataHist(plot, treesMM)
        histoEM = getDataHist(plot, treesEM)

    return histoEE, histoMM, histoEM
Beispiel #3
0
def getHistogram(plot,runRange,backgrounds,region):
        path = locations[runRange.era].dataSetPath
        treesEE = readTrees(path,"EE")
        treesEM = readTrees(path,"EMu")
        treesMM = readTrees(path,"MuMu")
                        
                
        eventCounts = totalNumberOfGeneratedEvents(path)        
        processes = []
        for background in backgrounds:
                processes.append(Process(getattr(Backgrounds[runRange.era],background),eventCounts))
        
        triggerSF_EE,_ = getTriggerScaleFactor("EE",   region, runRange)
        triggerSF_MM,_ = getTriggerScaleFactor("MuMu", region, runRange)
        triggerSF_EM,_ = getTriggerScaleFactor("EMu", region, runRange)
        
        histoEE = TheStack(processes,runRange.lumi,plot,treesEE,"None",1.0,triggerSF_EE,1.0,useTriggerEmulation=True).theHistogram               
        histoMM = TheStack(processes,runRange.lumi,plot,treesMM,"None",1.0,triggerSF_MM,1.0,useTriggerEmulation=True).theHistogram
        histoEM = TheStack(processes,runRange.lumi,plot,treesEM,"None",1.0,triggerSF_EM,1.0,useTriggerEmulation=True).theHistogram
        
        histSF = histoEE.Clone()
        histSF.Add(histoMM.Clone(), 1)
        histSF.Add(histoEM.Clone(), -1)

        return histSF
def getHistograms(path,plot,runRange,isMC,backgrounds,EM=False):


	treesEE = readTrees(path,"EE")
	treesEM = readTrees(path,"EMu")
	treesMM = readTrees(path,"MuMu")
		
	
	
	if isMC:
		
		eventCounts = totalNumberOfGeneratedEvents(path)	
		processes = []
		for background in backgrounds:
			processes.append(Process(getattr(Backgrounds,background),eventCounts))
		
		histoEE = TheStack(processes,runRange.lumi,plot,treesEE,"None",1.0,1.0,1.0).theHistogram		
		histoMM = TheStack(processes,runRange.lumi,plot,treesMM,"None",1.0,1.0,1.0).theHistogram

		
		if EM:
			histoEM = TheStack(processes,runRange.lumi,plot,treesEM,"None",1.0,1.0,1.0).theHistogram		
		
	else:
		histoEE = getDataHist(plot,treesEE)
		histoMM = getDataHist(plot,treesMM)
		if EM:
			histoEM = getDataHist(plot,treesEM)
	
	if EM:
		return histoEE , histoMM, histoEM
	else:
		return histoEE , histoMM
def getHistograms(path, plot, runRange, isMC, backgrounds, EM=False):

    treesEE = readTrees(path, "EE")
    treesEM = readTrees(path, "EMu")
    treesMM = readTrees(path, "MuMu")

    if isMC:

        eventCounts = totalNumberOfGeneratedEvents(path)
        processes = []
        for background in backgrounds:
            processes.append(
                Process(getattr(Backgrounds, background), eventCounts))

        histoEE = TheStack(processes, runRange.lumi, plot, treesEE, "None",
                           1.0, 1.0, 1.0).theHistogram
        histoMM = TheStack(processes, runRange.lumi, plot, treesMM, "None",
                           1.0, 1.0, 1.0).theHistogram

        if EM:
            histoEM = TheStack(processes, runRange.lumi, plot, treesEM, "None",
                               1.0, 1.0, 1.0).theHistogram

    else:
        histoEE = getDataHist(plot, treesEE)
        histoMM = getDataHist(plot, treesMM)
        if EM:
            histoEM = getDataHist(plot, treesEM)

    if EM:
        return histoEE, histoMM, histoEM
    else:
        return histoEE, histoMM
Beispiel #6
0
def cutAndCountForRegion(path,baseTreePath,selection,plots,runRange,isMC,backgrounds):
	
	#~ path = "/home/jan/Trees/sw7412v2000Trigger/"
	
	if not isMC:
		trees = getDataTrees(path)
		for label, tree in trees.iteritems():
			trees[label] = tree.CopyTree("nJets > 1")		
	else:
		treesEE = readTrees(path,"EE",source = "",modifier= "")
		treesEM = readTrees(path,"EMu",source = "",modifier= "")
		treesMM = readTrees(path,"MuMu",source = "",modifier= "")		
		trees = {
				"EE":treesEE,
				"MM":treesMM,
				"EM":treesEM,
		}
		
		

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

		counts = {}
		eventLists = {}
		#~ massRanges = ["default","edgeMass","zMass","highMass","belowZ","aboveZ"]
		massRanges = ["default","edgeMass","lowMass","zMass","highMass"]
		nLLRegions = ["lowNLL","highNLL"]
		
		counts["default"] = {}
		eventLists["default"] = {}
		for mllCut in massRanges:
			cut = plot.cuts+" && (%s)"%getattr(theCuts.massCuts,mllCut).cut
			cut = cut.replace("p4.M()","mll")
			cut = cut.replace("genWeight*weight*","")
			#~ cut = "genWeight*weight*("+cut+")"
			counts["default"][getattr(theCuts.massCuts,mllCut).name] = getCounts(trees, cut,isMC,backgrounds,plot,runRange,baseTreePath)
			eventLists["default"][getattr(theCuts.massCuts,mllCut).name] = getEventLists(trees,cut,isMC)		

		for nLLRegion in nLLRegions:		
			counts[nLLRegion] = {}
			eventLists[nLLRegion] = {}					
			
			for mllCut in massRanges:
				cut = plot.cuts+" && (%s)"%getattr(theCuts.nLLCuts,nLLRegion).cut
				cut = cut + " && (%s)"%getattr(theCuts.massCuts,mllCut).cut
				cut = cut.replace("p4.M()","mll")
				cut = cut.replace("genWeight*weight*","")
				#~ cut = "genWeight*weight*("+cut+")"
				counts[nLLRegion][getattr(theCuts.massCuts,mllCut).name] = getCounts(trees, cut,isMC,backgrounds,plot,runRange,baseTreePath)
				eventLists[nLLRegion][getattr(theCuts.massCuts,mllCut).name] = getEventLists(trees, cut,isMC)				

		
		return counts, eventLists
def getHistogramsPrompt(path, plot, runRange):

    treesMu = readTrees(path, "MuMu")
    treesE = readTrees(path, "EE")

    histoM = getDataHist(plot, treesMu, dataname="MergedData_Loose")
    histoE = getDataHist(plot, treesE, dataname="MergedData_Loose")

    return [histoE, histoM]
Beispiel #8
0
def getSignalMCHistograms(path, plot, runRange, sampleName):

    treesEE = readTrees(path, "EE")
    treesEM = readTrees(path, "EMu")
    treesMM = readTrees(path, "MuMu")

    histoEE = getDataHist(plot, treesEE, dataname=sampleName)
    histoMM = getDataHist(plot, treesMM, dataname=sampleName)
    histoEM = getDataHist(plot, treesEM, dataname=sampleName)

    return histoEE, histoMM, histoEM
def get2DHistograms(path, cut, binningPt, binningEta):

    treesMu = readTrees(path, "", "Fake", "FakemuonIso")
    treesE = readTrees(path, "", "Fake", "FakeelectronIso")

    rmList = []
    for index, tree in treesMu.iteritems():
        if "DoubleElectron" in index:
            rmList.append(index)
    for index in rmList:
        del treesMu[index]
    rmList = []
    for index, tree in treesE.iteritems():
        if "DoubleMu" in index:
            rmList.append(index)
    for index in rmList:
        del treesE[index]


#
    histoE = ROOT.TH2F("", "",
                       len(binningPt) - 1, array("f", binningPt),
                       len(binningEta) - 1, array("f", binningEta))
    histoM = ROOT.TH2F("", "",
                       len(binningPt) - 1, array("f", binningPt),
                       len(binningEta) - 1, array("f", binningEta))

    for index, tree in treesMu.iteritems():
        histoM.Add(
            create2DHistoFromTree(tree,
                                  "pt",
                                  "abs(eta)",
                                  cut,
                                  len(binningPt) - 1,
                                  binningPt[0],
                                  binningPt[-1],
                                  binning=binningPt,
                                  binning2=binningEta).Clone())
    for index, tree in treesE.iteritems():
        histoE.Add(
            create2DHistoFromTree(tree,
                                  "pt",
                                  "abs(eta)",
                                  cut,
                                  len(binningPt) - 1,
                                  binningPt[0],
                                  binningPt[-1],
                                  binning=binningPt,
                                  binning2=binningEta).Clone())

    return [histoE, histoM]
Beispiel #10
0
def getHistogram(path,plot,runRange,background):
        treesEE = readTrees(path,"EE")
        treesMM = readTrees(path,"MuMu")
        
        if "NLL" in path:
                plot.cuts = plot.cuts.replace(" && metFilterSummary > 0", "")
        
        eeSF = getTriggerScaleFactor("EE", "Inclusive", runRange)[0]
        mmSF = getTriggerScaleFactor("EE", "Inclusive", runRange)[0]
        
        eventCounts = totalNumberOfGeneratedEvents(path)        
        proc = Process(getattr(Backgrounds[runRange.era],background),eventCounts)
        histSF = proc.createCombinedHistogram(runRange.lumi,plot,treesEE,treesMM, 1.0, eeSF, mmSF)                  
        return histSF
def getHistograms(path, plot, runRange):

    treesMu = readTrees(path, "", "Fake", "FakemuonIso")
    treesE = readTrees(path, "", "Fake", "FakeelectronIso")

    histoE = ROOT.TH1F("", "", plot.nBins, plot.firstBin, plot.lastBin)
    histoM = ROOT.TH1F("", "", plot.nBins, plot.firstBin, plot.lastBin)

    for index, tree in treesMu.iteritems():
        histoM.Add(getDataHist(plot, treesMu, dataname=index))

    for index, tree in treesE.iteritems():
        histoE.Add(getDataHist(plot, treesE, dataname=index))

    return [histoE, histoM]
def getHistograms(path,plot,runRange,backgrounds):

        treesEE = readTrees(path,"EE")
        treesEM = readTrees(path,"EMu")
        treesMM = readTrees(path,"MuMu")

        eventCounts = totalNumberOfGeneratedEvents(path)        
        processes = []
        for background in backgrounds:
                processes.append(Process(getattr(Backgrounds[runRange.era],background),eventCounts))
        histoEE = TheStack(processes,runRange.lumi,plot,treesEE,"None",1.0,1.0,1.0).theHistogram                
        histoMM = TheStack(processes,runRange.lumi,plot,treesMM,"None",1.0,1.0,1.0).theHistogram            


        return histoEE , histoMM
Beispiel #13
0
def getHistogram(path, plot, plot2, runRange, background):

    treesEE = readTrees(path, "EE")
    treesEM = readTrees(path, "EMu")
    treesMM = readTrees(path, "MuMu")

    eventCounts = totalNumberOfGeneratedEvents(path)

    proc = Process(getattr(Backgrounds[runRange.era], background), eventCounts)
    histSF = proc.createCombined2DHistogram(runRange.lumi, plot, plot2,
                                            treesEE, treesMM)

    # histoEE = TheStack(processes,runRange.lumi,plot,treesEE,"None",1.0,1.0,1.0, useTriggerEmulation=True).theHistogram
    # histoMM = TheStack(processes,runRange.lumi,plot,treesMM,"None",1.0,1.0,1.0, useTriggerEmulation=True).theHistogram

    return histSF
Beispiel #14
0
def getHistograms(path,
                  source,
                  modifier,
                  plot,
                  runRange,
                  isMC,
                  nonNormalized,
                  backgrounds,
                  region=""):

    treesEE = readTrees(path, "EE", source=source, modifier=modifier)
    treesEM = readTrees(path, "EMu", source=source, modifier=modifier)
    treesMM = readTrees(path, "MuMu", source=source, modifier=modifier)

    if isMC:
        #~ print path, source, modifier
        eventCounts = totalNumberOfGeneratedEvents(path, source, modifier)
        processes = []
        for background in backgrounds:
            if nonNormalized:
                processes.append(
                    Process(getattr(Backgrounds, background),
                            eventCounts,
                            normalized=False))
            else:
                processes.append(
                    Process(getattr(Backgrounds, background), eventCounts))

        histoEE = TheStack(processes, runRange.lumi, plot, treesEE, "None",
                           1.0, 1.0, 1.0).theHistogram
        histoMM = TheStack(processes, runRange.lumi, plot, treesMM, "None",
                           1.0, 1.0, 1.0).theHistogram
        histoEM = TheStack(processes, runRange.lumi, plot, treesEM, "None",
                           1.0, 1.0, 1.0).theHistogram

        histoEE.Scale(getattr(triggerEffs, region).effEE.val)
        histoEE.Scale(getattr(triggerEffs, region).effMM.val)
        histoEM.Scale(getattr(triggerEffs, region).effEM.val)

    else:
        histoEE = getDataHist(plot, treesEE)
        histoMM = getDataHist(plot, treesMM)
        histoEM = getDataHist(plot, treesEM)

    return histoEE, histoMM, histoEM
def getHistogram(path,plot,plot2,runRange,sample, m1, m2):

        treesEE = readTrees(path,"EE")
        treesEM = readTrees(path,"EMu")
        treesMM = readTrees(path,"MuMu")
        
        year = runRange.era
        if year == "2017":
                yearAppend = "_Fall17"
        elif year == "2016":
                yearAppend = "_Summer16"
        elif year == "2018":
                yearAppend = "_Autumn18"
        
        if sample == "T6bbllslepton":
                sampleName = "T6bbllslepton_msbottom_%s_mneutralino_%s"%(m1,m2)
        elif sample == "T6qqllslepton":
                sampleName = "T6qqllslepton_msquark_%s_mneutralino_%s"%(m1,m2)
        
        sampleName += yearAppend
        scale = getSignalScale(sampleName, runRange)
        
        
        import numpy as np
        if (plot.binning == [] or plot.binning == None):
                binning = np.linspace(plot.firstBin, plot.lastBin, plot.nBins+1)
        else:
                binning = plot.binning
        if (plot2.binning == [] or plot2.binning == None):
                binning2 = np.linspace(plot2.firstBin, plot2.lastBin, plot2.nBins+1)
        else:
                binning2 = plot2.binning
        
  
        histEE = create2DHistoFromTree(treesEE[sampleName], plot.variable, plot2.variable, plot.cuts, plot.nBins, plot.firstBin, plot.lastBin, plot2.nBins, plot2.firstBin, plot2.lastBin, binning = binning, binning2 = binning2)
        histMM = create2DHistoFromTree(treesMM[sampleName], plot.variable, plot2.variable, plot.cuts, plot.nBins, plot.firstBin, plot.lastBin, plot2.nBins, plot2.firstBin, plot2.lastBin, binning = binning, binning2 = binning2)
        histSF = histEE.Clone()
        
        histSF.Scale(scale)

        # histoEE = TheStack(processes,runRange.lumi,plot,treesEE,"None",1.0,1.0,1.0, useTriggerEmulation=True).theHistogram                
        # histoMM = TheStack(processes,runRange.lumi,plot,treesMM,"None",1.0,1.0,1.0, useTriggerEmulation=True).theHistogram            
                

        return histSF
def getTrees(path, plot, runRange, background, region):

    treesEE = readTrees(path, "EE")
    treesEM = readTrees(path, "EMu")
    treesMM = readTrees(path, "MuMu")

    for index, tree in treesEE.iteritems():
        if index == background:
            treeEE = tree
    for index, tree in treesMM.iteritems():
        if index == background:
            treeMM = tree
    for index, tree in treesEM.iteritems():
        if index == background:
            treeEM = tree

    return treeEE.CopyTree(plot.cuts), treeMM.CopyTree(
        plot.cuts), treeEM.CopyTree(plot.cuts)
def getHistograms(path,plot,runRange,backgrounds):

        treesEE = readTrees(path,"EE")
        treesEM = readTrees(path,"EMu")
        treesMM = readTrees(path,"MuMu")

        eventCounts = totalNumberOfGeneratedEvents(path)        
        processes = []
        for background in backgrounds:
                processes.append(Process(getattr(Backgrounds[runRange.era],background),eventCounts))
        tmpC = plot.cuts
        plot.cuts = plot.cuts.replace("pt > 25 &&", "pt > 25 && miniIsoEffArea1 < 0.1 && miniIsoEffArea2 < 0.1 &&")
        histoEE = TheStack(processes,runRange.lumi,plot,treesEE,"None",1.0,1.0,1.0).theHistogram                
        plot.cuts = tmpC
        plot.cuts = plot.cuts.replace("pt > 25 &&", "pt > 25 && miniIsoEffArea1 < 0.2 && miniIsoEffArea2 < 0.2 &&")
        histoMM = TheStack(processes,runRange.lumi,plot,treesMM,"None",1.0,1.0,1.0).theHistogram  

        return histoEE , histoMM
def getTrees(path, plot):

    treesEE = readTrees(path, "EE")
    treesEM = readTrees(path, "EMu")
    treesMM = readTrees(path, "MuMu")

    for index, tree in treesEE.iteritems():
        if index == "MergedData_Loose":
            treeEE = tree
    for index, tree in treesMM.iteritems():
        if index == "MergedData_Loose":
            treeMM = tree
    for index, tree in treesEM.iteritems():
        if index == "MergedData_Loose":
            treeEM = tree

    result = {}
    result["EE"] = treeEE.CopyTree(plot.cuts)
    result["MM"] = treeMM.CopyTree(plot.cuts)
    result["EM"] = treeEM.CopyTree(plot.cuts)
    return result
Beispiel #19
0
def getHistograms(path, plot, runRange, isMC, backgrounds):

    treesEE = readTrees(path, "EE")
    treesEM = readTrees(path, "EMu")
    treesMM = readTrees(path, "MuMu")

    if "NLL" in path:
        isNLL = True
        plot.cuts = plot.cuts.replace(" && metFilterSummary > 0", "")

    if isMC:
        eventCounts = totalNumberOfGeneratedEvents(path)
        processes = []
        for background in backgrounds:
            processes.append(
                Process(getattr(Backgrounds[runRange.era], background),
                        eventCounts))
        histoEE = TheStack(processes,
                           runRange.lumi,
                           plot,
                           treesEE,
                           "None",
                           1.0,
                           1.0,
                           1.0,
                           useTriggerEmulation=(not isNLL)).theHistogram
        histoMM = TheStack(processes,
                           runRange.lumi,
                           plot,
                           treesMM,
                           "None",
                           1.0,
                           1.0,
                           1.0,
                           useTriggerEmulation=(not isNLL)).theHistogram
    else:
        histoEE = getDataHist(plot, treesEE)
        histoMM = getDataHist(plot, treesMM)

    return histoEE, histoMM
def get2DHistogramsPrompt(path, cut, binningPt, binningEta):

    treesMu = readTrees(path, "MuMu")
    treesE = readTrees(path, "EE")
    #
    histoE = ROOT.TH2F("", "",
                       len(binningPt) - 1, array("f", binningPt),
                       len(binningEta) - 1, array("f", binningEta))
    histoM = ROOT.TH2F("", "",
                       len(binningPt) - 1, array("f", binningPt),
                       len(binningEta) - 1, array("f", binningEta))

    for index, tree in treesMu.iteritems():
        if index == "MergedData_Loose":
            histoM.Add(
                create2DHistoFromTree(tree,
                                      "pt1",
                                      "abs(eta1)",
                                      cut,
                                      len(binningPt) - 1,
                                      binningPt[0],
                                      binningPt[-1],
                                      binning=binningPt,
                                      binning2=binningEta).Clone())
    for index, tree in treesE.iteritems():
        if index == "MergedData_Loose":
            histoE.Add(
                create2DHistoFromTree(tree,
                                      "pt1",
                                      "abs(eta1)",
                                      cut,
                                      len(binningPt) - 1,
                                      binningPt[0],
                                      binningPt[-1],
                                      binning=binningPt,
                                      binning2=binningEta).Clone())

    print histoE.GetEntries()
    return [histoE, histoM]
	### split in mll and likelihood bins
		
	path = locations.dataSetPathSignalNLL	
	CutRegions = ["met150Cut","nJets2Cut","signalRegionCut","deltaPhiCut"]
	mllCutRegions = ["noMllCut","20To60","60To86","86To96","96To150","150To200","200To300","300To400","Above400"]
	NllCutRegions = ["inclusiveNll","lowNll","highNll"]
	
	points = ["1","2","3","4","5"]
	
	### Factor to calculate the expected number of events with at least 2 leptons
	BR_factor =  0.25      + 0.5   + 0.25*(0.13+0.06*0.124+0.0011*(0.015+0.113+0.312))
	
	triggerEffUncertainty = 0.03
	lumiUncertainty = 0.026
	
	EETrees = readTrees(path, "EE")	
	MMTrees = readTrees(path, "MuMu")	
	
	EETriggerEff = triggerEffs.inclusive.effEE.val
	EMuTriggerEff = triggerEffs.inclusive.effEM.val
	MuMuTriggerEff = triggerEffs.inclusive.effMM.val
	RSFOF = rSFOFDirect.inclusive.val

	## loop over example points
	for point in points:
		m_b = sleptonPoints[point]["m_b"]
		m_sbottom = str(m_b)
		M_SBOTTOM = "m_b_"+str(m_b)
		m_n_2 =sleptonPoints[point]["m_n"]
		m_neutralino_2 = str(m_n_2)
		
def cutAndCountForRegion(path,
                         selection,
                         plots,
                         runRange,
                         isMC,
                         backgrounds,
                         blind=False):

    if not isMC:
        trees = getDataTrees(path)
        for label, tree in trees.iteritems():
            trees[label] = tree.CopyTree("nJets > 1")
    else:
        treesEE = readTrees(path, "EE", source="", modifier="")
        treesEM = readTrees(path, "EMu", source="", modifier="")
        treesMM = readTrees(path, "MuMu", source="", modifier="")
        trees = {
            "EE": treesEE,
            "MM": treesMM,
            "EM": treesEM,
        }

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

        counts = {}
        eventLists = {}
        # ,"highMassOld","highMass","lowMass","lowMassOld", "mass60To81", "mass81To101", "mass101To150",
        massBins = [
            "mass20To60", "mass60To86", "mass86To96", "mass96To150",
            "mass150To200", "mass200To300", "mass300To400", "mass400"
        ]
        nLLRegions = ["lowNLL", "highNLL"]
        MT2Regions = ["highMT2"]  # "lowMT2",
        nBJetsRegions = ["zeroBJets", "oneOrMoreBJets"]

        counts["default"] = {}
        eventLists["default"] = {}

        if runRange.era == "2018":
            plot.cuts = plot.cuts.replace(
                "chargeProduct < 0 &&", "chargeProduct < 0 && vetoHEM == 1 &&")

        standardCut = plot.cuts
        #for mllCut in massBins:
        #        cut = standardCut + " && (%s)"%getattr(theCuts.massCuts,mllCut).cut
        #        cut = cut + " && (met / caloMet < 5. && nBadMuonJets == 0)"
        #        #~ cut = cut + " && (met / caloMet > 5. && nBadMuonJets > 0)" ### Inverse bad muon cuts
        #        if not (mllCut == "highMassOld" or mllCut == "lowMassOld"):
        #                cut = cut+" && (abs(deltaPhiJetMet1) > 0.4 && abs(deltaPhiJetMet2) > 0.4)"
        #        cut = cut.replace("p4.M()","mll")
        #        cut = cut.replace("p4.Pt()","pt")
        #        cut = cut.replace("metFilterSummary > 0 &&","")
        #        cut = cut.replace("&& metFilterSummary > 0","")
        #        cut = cut.replace("triggerSummary > 0 &&","")
        #        cut = cut.replace("genWeight*","")
        #        cut = cut.replace("prefireWeight*","")
        #        cut = cut.replace("weight*","")
        #        cut = cut.replace("leptonFullSimScaleFactor1*","")
        #        cut = cut.replace("leptonFullSimScaleFactor2*","")
        #        cut = "leptonFullSimScaleFactor1*leptonFullSimScaleFactor2*genWeight*weight*("+cut+")"
        #        if runRange.era != "2018":
        #                cut = "prefireWeight*"+cut
        #        #~ cut = "genWeight*weight*("+cut+")"
        #
        #
        #        counts["default"][getattr(theCuts.massCuts,mllCut).name] = getCounts(trees, cut,isMC,backgrounds,plot,runRange,path, blind)
        #        #~ eventLists["default"][getattr(theCuts.massCuts,mllCut).name] = getEventLists(trees,cut,isMC)

        for nLLRegion in nLLRegions:
            counts[nLLRegion] = {}
            eventLists[nLLRegion] = {}

            #for mllCut in massBins:
            #        cut = standardCut+" && (%s)"%getattr(theCuts.nLLCuts,nLLRegion).cut
            #        cut = cut + " && (%s)"%getattr(theCuts.massCuts,mllCut).cut
            #        cut = cut + " && (met / caloMet < 5. && nBadMuonJets == 0)"
            #        #~ cut = cut + " && (met / caloMet > 5. && nBadMuonJets > 0)" ### Inverse bad muon cuts
            #        if not (mllCut == "highMassOld" or mllCut == "lowMassOld"):
            #                cut = cut+" && (abs(deltaPhiJetMet1) > 0.4 && abs(deltaPhiJetMet2) > 0.4)"
            #        cut = cut.replace("p4.M()","mll")
            #        cut = cut.replace("p4.Pt()","pt")
            #        cut = cut.replace("metFilterSummary > 0 &&","")
            #        cut = cut.replace("&& metFilterSummary > 0","")
            #        cut = cut.replace("triggerSummary > 0 &&","")
            #        cut = cut.replace("genWeight*","")
            #        cut = cut.replace("prefireWeight*","")
            #        cut = cut.replace("weight*","")
            #        cut = cut.replace("leptonFullSimScaleFactor1*","")
            #        cut = cut.replace("leptonFullSimScaleFactor2*","")
            #        cut = "leptonFullSimScaleFactor1*leptonFullSimScaleFactor2*genWeight*weight*("+cut+")"
            #        if runRange.era != "2018":
            #                cut = "prefireWeight*"+cut
            #        #~ cut = "genWeight*weight*("+cut+")"
            #
            #        counts[nLLRegion][getattr(theCuts.massCuts,mllCut).name] = getCounts(trees, cut,isMC,backgrounds,plot,runRange,path, blind)

            for MT2Region in MT2Regions:
                for mllCut in massBins:
                    cut = standardCut + " && (%s)" % getattr(
                        theCuts.nLLCuts, nLLRegion).cut
                    cut = cut + " && (%s)" % getattr(theCuts.mt2Cuts,
                                                     MT2Region).cut
                    cut = cut + " && (%s)" % getattr(theCuts.massCuts,
                                                     mllCut).cut
                    cut = cut + " && (met / caloMet < 5. && nBadMuonJets == 0)"
                    #~ cut = cut + " && (met / caloMet > 5. && nBadMuonJets > 0)" ### Inverse bad muon cuts
                    if not (mllCut == "highMassOld" or mllCut == "lowMassOld"):
                        cut = cut + " && (abs(deltaPhiJetMet1) > 0.4 && abs(deltaPhiJetMet2) > 0.4)"
                    cut = cut.replace("p4.M()", "mll")
                    cut = cut.replace("p4.Pt()", "pt")
                    cut = cut.replace("metFilterSummary > 0 &&", "")
                    cut = cut.replace("&& metFilterSummary > 0", "")
                    cut = cut.replace("triggerSummary > 0 &&", "")
                    cut = cut.replace("genWeight*", "")
                    cut = cut.replace("prefireWeight*", "")
                    cut = cut.replace("weight*", "")
                    cut = cut.replace("leptonFullSimScaleFactor1*", "")
                    cut = cut.replace("leptonFullSimScaleFactor2*", "")
                    cut = "leptonFullSimScaleFactor1*leptonFullSimScaleFactor2*genWeight*weight*(" + cut + ")"
                    if runRange.era != "2018":
                        cut = "prefireWeight*" + cut
                    #~ cut = "genWeight*weight*("+cut+")"

                    counts[nLLRegion][
                        getattr(theCuts.mt2Cuts, MT2Region).name + "_" +
                        getattr(theCuts.massCuts, mllCut).name] = getCounts(
                            trees, cut, isMC, backgrounds, plot, runRange,
                            path, blind)

            for MT2Region in MT2Regions:
                for nBJetsRegion in nBJetsRegions:
                    for mllCut in massBins:
                        cut = standardCut + " && (%s)" % getattr(
                            theCuts.nLLCuts, nLLRegion).cut
                        cut = cut + " && (%s)" % getattr(
                            theCuts.nBJetsCuts, nBJetsRegion).cut
                        cut = cut + " && (%s)" % getattr(
                            theCuts.mt2Cuts, MT2Region).cut
                        cut = cut + " && (%s)" % getattr(
                            theCuts.massCuts, mllCut).cut
                        cut = cut + " && (met / caloMet < 5. && nBadMuonJets == 0)"
                        #~ cut = cut + " && (met / caloMet > 5. && nBadMuonJets > 0)" ### Inverse bad muon cuts
                        if not (mllCut == "highMassOld"
                                or mllCut == "lowMassOld"):
                            cut = cut + " && (abs(deltaPhiJetMet1) > 0.4 && abs(deltaPhiJetMet2) > 0.4)"
                        cut = cut.replace("p4.M()", "mll")
                        cut = cut.replace("p4.Pt()", "pt")
                        cut = cut.replace("metFilterSummary > 0 &&", "")
                        cut = cut.replace("&& metFilterSummary > 0", "")
                        cut = cut.replace("triggerSummary > 0 &&", "")
                        cut = cut.replace("genWeight*", "")
                        cut = cut.replace("prefireWeight*", "")
                        cut = cut.replace("weight*", "")
                        cut = cut.replace("leptonFullSimScaleFactor1*", "")
                        cut = cut.replace("leptonFullSimScaleFactor2*", "")
                        cut = "leptonFullSimScaleFactor1*leptonFullSimScaleFactor2*genWeight*weight*(" + cut + ")"
                        if runRange.era != "2018":
                            cut = "prefireWeight*" + cut
                        #~ cut = "genWeight*weight*("+cut+")"

                        counts[nLLRegion][
                            getattr(theCuts.mt2Cuts, MT2Region).name + "_" +
                            getattr(theCuts.nBJetsCuts, nBJetsRegion).name +
                            "_" + getattr(
                                theCuts.massCuts, mllCut).name] = getCounts(
                                    trees, cut, isMC, backgrounds, plot,
                                    runRange, path, blind)

        return counts
Beispiel #23
0
	cuts = "weight*(chargeProduct < 0 && %s  && abs(eta1) < 2.4 && abs(eta2) < 2.4  && p4.M() > 20 && ((abs(eta1) < 1.4 || abs(eta1) > 1.6) && (abs(eta2) < 1.4 || abs(eta2) > 1.6)))"%(ptCut)


	SampleName = "TT_Powheg"
	runRange = getRunRange("Run2015_25ns")
	
	plot = getPlot("mllPlot")
	selection = getRegion("SignalInclusive")
	plot.addRegion(selection)
	plot.cleanCuts()
	plot.cuts = plot.cuts % runRange.runCut			
	
	eventCounts = totalNumberOfGeneratedEvents(path)
	processes = [Process(getattr(Backgrounds,"TT_Powheg"),eventCounts)]

	treesEE = readTrees(path,"EE")
	treesEM = readTrees(path,"EMu")
	treesMM = readTrees(path,"MuMu")


	histoEE = TheStack(processes,runRange.lumi,plot,treesEE,"None",1.0,1.0,1.0).theHistogram		
	histoMM = TheStack(processes,runRange.lumi,plot,treesMM,"None",1.0,1.0,1.0).theHistogram
	histoEM = TheStack(processes,runRange.lumi,plot,treesEM,"None",1.0,1.0,1.0).theHistogram		
	#~ histoEE.Scale(getattr(triggerEffs,"central").effEE.valMC)
	#~ histoMM.Scale(getattr(triggerEffs,"central").effMM.valMC)	
	#~ histoEM.Scale(getattr(triggerEffs,"central").effEM.valMC)	



	histoSF = histoEE.Clone()
	histoSF.Add(histoMM)
def cutAndCountForRegion(path,selection,plots,runRange,isMC,backgrounds,preselection,samesign):
	
	#~ path = "/home/jan/Trees/sw7412v2000Trigger/"
	
	if not isMC:
		trees = getDataTrees(path)
		for label, tree in trees.iteritems():
			trees[label] = tree.CopyTree(preselection)		
	else:
		treesEE = readTrees(path,"EE",source = "",modifier= "")
		treesEM = readTrees(path,"EMu",source = "",modifier= "")
		treesMM = readTrees(path,"MuMu",source = "",modifier= "")		
		trees = {
				"EE":treesEE,
				"MM":treesMM,
				"EM":treesEM,
		}
		
		

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

		if samesign:
			plot.cuts = plot.cuts.replace("chargeProduct < 0","chargeProduct > 0")

		counts = {}
		eventLists = {}
		#~ massRanges = ["default","edgeMass","zMass","highMass","belowZ","aboveZ"]
		massRanges = ["default","edgeMass","lowMass","zMass","highMass"]
		counts["default"] = {}
		eventLists["default"] = {}
		for mllCut in massRanges:
			counts["default"][getattr(theCuts.massCuts,mllCut).name] = getCounts(trees, plot.cuts+"*(%s)"%getattr(theCuts.massCuts,mllCut).cut,isMC,backgrounds,plot,runRange,path)
			eventLists["default"][getattr(theCuts.massCuts,mllCut).name] = getEventLists(trees, plot.cuts+"*(%s)"%getattr(theCuts.massCuts,mllCut).cut,isMC)		

		for categoryName, category in cutNCountXChecks.cutList.iteritems():
			if categoryName == "leptonPt":
				for subcut in category:
					counts[subcut] = {}
					eventLists[subcut] = {}
					
					for mllCut in massRanges:
						cut = plot.cuts.replace("pt1 > 20 && pt2 > 20 &&","")
						cut = cut+"*(%s)"%getattr(theCuts.ptCuts,subcut).cut + "*(%s)"%getattr(theCuts.massCuts,mllCut).cut
						counts[getattr(theCuts.ptCuts,subcut).name][getattr(theCuts.massCuts,mllCut).name] = getCounts(trees, cut,isMC,backgrounds,plot,runRange,path)
						eventLists[getattr(theCuts.ptCuts,subcut).name][getattr(theCuts.massCuts,mllCut).name] = getEventLists(trees, cut,isMC)
			elif categoryName == "mets":
				for subcut in category:
					counts[subcut] = {}
					eventLists[subcut] = {}					
					
					for mllCut in massRanges:
						cut = plot.cuts.replace("met",subcut)
						cut = cut + "*(%s)"%getattr(theCuts.massCuts,mllCut).cut
						counts[subcut][getattr(theCuts.massCuts,mllCut).name] = getCounts(trees, cut,isMC,backgrounds,plot,runRange,path)
						eventLists[subcut][getattr(theCuts.massCuts,mllCut).name] = getEventLists(trees, cut,isMC)			
				
			else:
				for subcut in category:
					counts[subcut] = {}
					eventLists[subcut] = {}					
					
					for mllCut in massRanges:
						cut = plot.cuts+"*(%s)"%getattr(getattr(theCuts,categoryName),subcut).cut
						cut = cut + "*(%s)"%getattr(theCuts.massCuts,mllCut).cut
						counts[subcut][getattr(theCuts.massCuts,mllCut).name] = getCounts(trees, cut,isMC,backgrounds,plot,runRange,path)
						eventLists[subcut][getattr(theCuts.massCuts,mllCut).name] = getEventLists(trees, cut,isMC)				

		
		return counts, eventLists
def plot():
	import ratios
	
	import pickle
	
	signalDenominatorFile = TFile("/.automount/home/home__home4/institut_1b/schomakers/FrameWork/SignalScan/T6bbllsleptonDenominatorHisto7.root")
	denominatorHisto = TH2F(signalDenominatorFile.Get("massScan"))
	denominatorHistoLowPU = TH2F(signalDenominatorFile.Get("massScanLowPU"))
	denominatorHistoHighPU = TH2F(signalDenominatorFile.Get("massScanHighPU"))
	ISRNormalizationHisto = TH2F(signalDenominatorFile.Get("ISRNormalization"))
	ISRNormalizationHistoUp = TH2F(signalDenominatorFile.Get("ISRNormalizationUp"))
	ISRNormalizationHistoDown = TH2F(signalDenominatorFile.Get("ISRNormalizationDown"))
	
	scaleNormalizationHistos = {}
	for i in range(1,9):
		scaleNormalizationHistos["ScaleWeight"+str(i)] = TH2F(signalDenominatorFile.Get("ScaleWeight"+str(i)))
	

	path = locations.dataSetPathSignalNLL
	
	print path
	
	lumi = 35867.
		
	#~ m_b_min = 700
	m_b_min = 1000
	#~ m_b_min = 1150
	m_b_max = 1100
	#~ m_b_max = 1600
	m_n_min = 150

	
	EETrees = readTrees(path, "EE")
	EMTrees = readTrees(path, "EMu")
	MMTrees = readTrees(path, "MuMu")
		
	massRegions = ["20To60","60To86","86To96","96To150","150To200","200To300","300To400","Above400"]
	nLLRegions = ["lowNll","highNll"]
	MT2Regions = ["highMT2"]
	
	signalBins = []
	signalCuts = {}
	
	EETriggerEff = triggerEffs.inclusive.effEE.val
	EMuTriggerEff = triggerEffs.inclusive.effEM.val
	MuMuTriggerEff = triggerEffs.inclusive.effMM.val
	RSFOF = rSFOFDirect.inclusive.val
	
	triggerEffUncertainty = 0.03
	lumiUncertainty = 0.026
	
	### Loop over different mass and NLL bins

	for massRegion in massRegions:
		for nLLRegion in nLLRegions:
			for MT2Region in MT2Regions:
				signalBins.append("%s_%s_%s"%(massRegion,nLLRegion,MT2Region))
				signalCuts["%s_%s_%s"%(massRegion,nLLRegion,MT2Region)] = "%s && %s && %s"%(massCuts[massRegion],nLLCuts[nLLRegion],MT2Cuts[MT2Region])
	
	
	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:
			
			#~ print m_n
			m_neutralino_2 = str(m_n)
			counts = {}
			
			sampleName = "T6bbllslepton_msbottom_%s_mneutralino_%s"%(m_sbottom,m_neutralino_2)
			
			### Fetch default normalization and those for PU and ISR splitted/shifted parts
			
			denominator = denominatorHisto.GetBinContent(denominatorHisto.GetXaxis().FindBin(int(sampleName.split("_")[2])),denominatorHisto.GetYaxis().FindBin(int(sampleName.split("_")[4])))
			denominatorLowPU = denominatorHistoLowPU.GetBinContent(denominatorHistoLowPU.GetXaxis().FindBin(int(sampleName.split("_")[2])),denominatorHistoLowPU.GetYaxis().FindBin(int(sampleName.split("_")[4])))
			denominatorHighPU = denominatorHistoHighPU.GetBinContent(denominatorHistoHighPU.GetXaxis().FindBin(int(sampleName.split("_")[2])),denominatorHistoHighPU.GetYaxis().FindBin(int(sampleName.split("_")[4])))
						
			ISRNormalization = ISRNormalizationHisto.GetBinContent(ISRNormalizationHisto.GetXaxis().FindBin(int(sampleName.split("_")[2])),denominatorHisto.GetYaxis().FindBin(int(sampleName.split("_")[4])))
			ISRNormalizationUp = ISRNormalizationHistoUp.GetBinContent(ISRNormalizationHisto.GetXaxis().FindBin(int(sampleName.split("_")[2])),denominatorHisto.GetYaxis().FindBin(int(sampleName.split("_")[4])))
			ISRNormalizationDown = ISRNormalizationHistoDown.GetBinContent(ISRNormalizationHisto.GetXaxis().FindBin(int(sampleName.split("_")[2])),denominatorHisto.GetYaxis().FindBin(int(sampleName.split("_")[4])))
			
			scaleNormalizations = []
			
			for weightIndex in range(1,9):
				scaleNormalizations.append(scaleNormalizationHistos["ScaleWeight"+str(weightIndex)].GetBinContent(scaleNormalizationHistos["ScaleWeight"+str(weightIndex)].GetXaxis().FindBin(int(sampleName.split("_")[2])),scaleNormalizationHistos["ScaleWeight"+str(weightIndex)].GetYaxis().FindBin(int(sampleName.split("_")[4]))))
			
			xsection = getattr(sbottom_masses, M_SBOTTOM).cross_section13TeV
			scalingLumi = lumi*xsection/(denominator*ISRNormalization)
			weight = denominator*ISRNormalization
			
			for signalBin in signalBins:
				
				cuts = "bTagWeight*ISRCorrection*leptonFullSimScaleFactor1*leptonFullSimScaleFactor2*leptonFastSimScaleFactor1*leptonFastSimScaleFactor2*(met / caloMet < 5 && nBadMuonJets == 0 && pt > 25 && abs(deltaPhiJetMet1) > 0.4  && abs(deltaPhiJetMet2) > 0.4 && nJets > 1 && met > 150 && nUnmatchedJets == 0 && deltaR > 0.1 && chargeProduct < 0 && ((pt1 > 25 && pt2 > 20) || (pt1 > 20 && pt2 > 25)) && abs(eta1) < 2.4 && abs(eta2) < 2.4 && %s)"%(signalCuts[signalBin])
				unweightedCuts = "(met / caloMet < 5 && nBadMuonJets == 0 && pt > 25 && abs(deltaPhiJetMet1) > 0.4  && abs(deltaPhiJetMet2) > 0.4 && nJets > 1 && met > 150 && nUnmatchedJets == 0 && chargeProduct < 0 && deltaR > 0.1 && ((pt1 > 25 && pt2 > 20) || (pt1 > 20 && pt2 > 25)) && abs(eta1) < 2.4 && abs(eta2) < 2.4 && %s)"%(signalCuts[signalBin])
				
				histos = {}
				
				
				for sample, tree in EETrees.iteritems():
					if sample == sampleName:
						EEsignalYieldMet = signalYields(tree,cuts, EETriggerEff * scalingLumi)
						EEsignalEfficiencyMet = produceSignalEfficiency(tree, cuts, weight)
						EEMCEventsMet = MCEventYield(tree,unweightedCuts)
						EEISRUpMet,EEISRDownMet = produceISRUncertainty(tree,cuts)
						EEJESUpMet,EEJESDownMet= produceJESUncertainty(tree,cuts)
						EELeptonFastSimScaleFactorShiftedMet = produceLeptonFastSimUncertainty(tree,cuts)
						EELeptonFullSimScaleFactorShiftedMet = produceLeptonFullSimUncertainty(tree,cuts)
						EEPileupHighMet,EEPileupLowMet = producePileupUncertainty(tree,cuts)
						EEBTagHeavyMet,EEBTagLightMet = produceBTagUncertainty(tree,cuts)
						
						
						EEScaleShiftedMet = []
						for weightIndex in range(0,8):
							EEScaleShiftedMet.append(produceScaleShiftUncertainty(tree,cuts,weightIndex)/scaleNormalizations[weightIndex])
						
						if denominator > 0:
							EEISRUpMet = EEISRUpMet*ISRNormalization/ISRNormalizationUp
							EEISRDownMet = EEISRDownMet*ISRNormalization/ISRNormalizationDown
							
							EEPileupHighMet = EEPileupHighMet * denominator/denominatorHighPU
							EEPileupLowMet = EEPileupLowMet * denominator/denominatorLowPU
						
						### SUSY group recommendation: Calculate yields twice, once
						### for reco MET and once for genMet and take average (and half
						### of the difference as uncertainty.
						### Suggested since MET might not be perfectly modelled in FastSim
						
						cuts = cuts.replace("met","genMet")
						
						EEsignalYieldGenMet = signalYields(tree,cuts, EETriggerEff * scalingLumi)
						EEsignalEfficiencyGenMet = produceSignalEfficiency(tree, cuts, weight)
						EEMCEventsGenMet = MCEventYield(tree,unweightedCuts)
						EEISRUpGenMet,EEISRDownGenMet = produceISRUncertainty(tree,cuts)
						EEJESUpGenMet,EEJESDownGenMet= produceJESUncertainty(tree,cuts)
						EELeptonFastSimScaleFactorShiftedGenMet = produceLeptonFastSimUncertainty(tree,cuts)
						EELeptonFullSimScaleFactorShiftedGenMet = produceLeptonFullSimUncertainty(tree,cuts)
						EEPileupHighGenMet,EEPileupLowGenMet = producePileupUncertainty(tree,cuts)
						EEBTagHeavyGenMet,EEBTagLightGenMet = produceBTagUncertainty(tree,cuts)
						
						EEScaleShiftedGenMet = []
						for weightIndex in range(0,8):
							EEScaleShiftedGenMet.append(produceScaleShiftUncertainty(tree,cuts,weightIndex)/scaleNormalizations[weightIndex])
						
						if denominator > 0:
							EEISRUpGenMet = EEISRUpGenMet*ISRNormalization/ISRNormalizationUp
							EEISRDownGenMet = EEISRDownGenMet*ISRNormalization/ISRNormalizationDown
							
							EEPileupHighGenMet = EEPileupHighGenMet * denominator/denominatorHighPU
							EEPileupLowGenMet = EEPileupLowGenMet * denominator/denominatorLowPU						
						
						cuts = cuts.replace("genMet","met")
						
						EEsignalYield = 0.5* (EEsignalYieldMet + EEsignalYieldGenMet)
						EEsignalEfficiency = 0.5* (EEsignalEfficiencyMet + EEsignalEfficiencyGenMet)
						EEMCEvents = 0.5* (EEMCEventsMet + EEMCEventsGenMet)
						EEISRUp = 0.5* (EEISRUpMet + EEISRUpGenMet) 
						EEISRDown = 0.5* (EEISRDownMet + EEISRDownGenMet) 
						EEJESUp = 0.5* (EEJESUpMet + EEJESUpGenMet) 
						EEJESDown = 0.5* (EEJESDownMet + EEJESDownGenMet) 
						EELeptonFastSimScaleFactorShifted = 0.5* (EELeptonFastSimScaleFactorShiftedMet + EELeptonFastSimScaleFactorShiftedGenMet) 
						EELeptonFullSimScaleFactorShifted = 0.5* (EELeptonFullSimScaleFactorShiftedMet + EELeptonFullSimScaleFactorShiftedGenMet) 
						EEPileupHigh = 0.5* (EEPileupHighMet + EEPileupHighGenMet) 
						EEPileupLow = 0.5* (EEPileupLowMet + EEPileupLowGenMet) 
						EEBTagHeavy = 0.5* (EEBTagHeavyMet + EEBTagHeavyGenMet) 
						EEBTagLight = 0.5* (EEBTagLightMet + EEBTagLightGenMet)						
						
						
						EEScaleShifted = []
						for weightIndex in range(0,8):
							EEScaleShifted.append(0.5*(EEScaleShiftedMet[weightIndex]+EEScaleShiftedGenMet[weightIndex]))
						
						UnscaledYield = EEsignalYield / (EETriggerEff * scalingLumi)
						
						if UnscaledYield > 0:
							EEISRUncertainty = max(abs(EEISRUp-UnscaledYield)/UnscaledYield,abs(EEISRDown-UnscaledYield)/UnscaledYield) 
							EEJESUncertainty = max(abs(EEJESUp-UnscaledYield)/UnscaledYield,abs(EEJESDown-UnscaledYield)/UnscaledYield) 
							EEPileupUncertainty = max(abs(EEPileupHigh-UnscaledYield)/UnscaledYield,abs(EEPileupLow-UnscaledYield)/UnscaledYield) 
							EELeptonFullSimUncertainty = abs(EELeptonFullSimScaleFactorShifted-UnscaledYield)/UnscaledYield
							EELeptonFastSimUncertainty = abs(EELeptonFastSimScaleFactorShifted-UnscaledYield)/UnscaledYield
							EEBTagHeavyUncertainty = abs(EEBTagHeavy-UnscaledYield)/UnscaledYield
							EEBTagLightUncertainty = abs(EEBTagLight-UnscaledYield)/UnscaledYield
							EEMetUncertainty = abs(EEsignalYieldMet-EEsignalYield)/EEsignalYield
							EEStatUncertainty = sqrt(EEMCEvents)
							
							EEScaleUncertainty = 0
							for weightIndex in range(0,8):
								EEScaleUncertainty = max (EEScaleUncertainty, abs(EEScaleShifted[weightIndex]-UnscaledYield)/UnscaledYield)
						else:
							EEISRUncertainty = 0.
							EEJESUncertainty = 0. 
							EEPileupUncertainty = 0.
							EELeptonFullSimUncertainty = 0.
							EELeptonFastSimUncertainty = 0.
							EEBTagHeavyUncertainty = 0.
							EEBTagLightUncertainty = 0.
							EEMetUncertainty = 0.
							EEStatUncertainty = 0.
							EEScaleUncertainty = 0
						
						
						EEsystUncertainty = sqrt(EEScaleUncertainty**2+EEMetUncertainty**2+EEBTagHeavyUncertainty**2+EEBTagLightUncertainty**2+EEJESUncertainty**2+EELeptonFastSimUncertainty**2+EELeptonFullSimUncertainty**2+EEPileupUncertainty**2+EEISRUncertainty**2+triggerEffUncertainty**2+lumiUncertainty**2)
						
						counts["%s_EE"%signalBin] = {"Val":EEsignalYield,"MCEvents":EEMCEvents,"SignalEfficiency":EEsignalEfficiency,"StatUncertainty":EEStatUncertainty,"TotSystUncertainty":EEsystUncertainty,
						"JESUncertainty":EEJESUncertainty,"JESMean":UnscaledYield*EETriggerEff,"JESUp":EEJESUp*EETriggerEff,"JESDown":EEJESDown*EETriggerEff,
						"LeptonFastSimUncertainty":EELeptonFastSimUncertainty,"LeptonFastSimMean":UnscaledYield*EETriggerEff,"LeptonFastSimScaleFactorShifted":EELeptonFastSimScaleFactorShifted*EETriggerEff,
						"LeptonFullSimUncertainty":EELeptonFullSimUncertainty,"LeptonFullSimMean":UnscaledYield*EETriggerEff,"LeptonFullSimScaleFactorShifted":EELeptonFullSimScaleFactorShifted*EETriggerEff,
						"PileupUncertainty":EEPileupUncertainty,"PileupMean":UnscaledYield*EETriggerEff,"PileupHigh":EEPileupHigh*EETriggerEff,"PileupLow":EEPileupLow*EETriggerEff,
						"ISRUncertainty":EEISRUncertainty,"ISRMean":UnscaledYield*EETriggerEff,"ISRUp":EEISRUp*EETriggerEff,"ISRDown":EEISRDown*EETriggerEff,
						"MetUncertainty":EEMetUncertainty,"Met":EEsignalYieldMet,"GenMet":EEsignalYieldGenMet,
						"ScaleUncertainty":EEScaleUncertainty,"ScaleShifted1":EEScaleShifted[0]*EETriggerEff,"ScaleShifted2":EEScaleShifted[1]*EETriggerEff,"ScaleShifted3":EEScaleShifted[2]*EETriggerEff,"ScaleShifted4":EEScaleShifted[3]*EETriggerEff,"ScaleShifted5":EEScaleShifted[4]*EETriggerEff,"ScaleShifted6":EEScaleShifted[5]*EETriggerEff,"ScaleShifted7":EEScaleShifted[6]*EETriggerEff,"ScaleShifted8":EEScaleShifted[7]*EETriggerEff,
						"BTagHeavyUncertainty":EEBTagHeavyUncertainty,"BTagMean":UnscaledYield*EETriggerEff,"BTagHeavy":EEBTagHeavy*EETriggerEff,"BTagLightUncertainty":EEBTagLightUncertainty,"BTagLight":EEBTagLight*EETriggerEff}

				
				for sample, tree in EMTrees.iteritems():
					if sample == sampleName:
						EMusignalYieldMet = signalYields(tree,cuts, EMuTriggerEff * scalingLumi)
						EMusignalEfficiencyMet = produceSignalEfficiency(tree, cuts, weight)
						EMuMCEventsMet = MCEventYield(tree,unweightedCuts)
						EMuISRUpMet,EMuISRDownMet = produceISRUncertainty(tree,cuts)
						EMuJESUpMet,EMuJESDownMet= produceJESUncertainty(tree,cuts)
						EMuLeptonFastSimScaleFactorShiftedMet = produceLeptonFastSimUncertainty(tree,cuts)
						EMuLeptonFullSimScaleFactorShiftedMet = produceLeptonFullSimUncertainty(tree,cuts)
						EMuPileupHighMet,EMuPileupLowMet = producePileupUncertainty(tree,cuts)
						EMuBTagHeavyMet,EMuBTagLightMet = produceBTagUncertainty(tree,cuts)
						
						EMuScaleShiftedMet = []
						for weightIndex in range(0,8):
							EMuScaleShiftedMet.append(produceScaleShiftUncertainty(tree,cuts,weightIndex)/scaleNormalizations[weightIndex])
						
						if ISRNormalization > 0:
							EMuISRUpMet = EMuISRUpMet*ISRNormalization/ISRNormalizationUp
							EMuISRDownMet = EMuISRDownMet*ISRNormalization/ISRNormalizationDown
							
							EMuPileupHighMet = EMuPileupHighMet * denominator/denominatorHighPU
							EMuPileupLowMet = EMuPileupLowMet * denominator/denominatorLowPU
						
						
						cuts = cuts.replace("met","genMet")
						
						EMusignalYieldGenMet = signalYields(tree,cuts, EMuTriggerEff * scalingLumi)
						EMusignalEfficiencyGenMet = produceSignalEfficiency(tree, cuts, weight)
						EMuMCEventsGenMet = MCEventYield(tree,unweightedCuts)
						EMuISRUpGenMet,EMuISRDownGenMet = produceISRUncertainty(tree,cuts)
						EMuJESUpGenMet,EMuJESDownGenMet= produceJESUncertainty(tree,cuts)
						EMuLeptonFastSimScaleFactorShiftedGenMet = produceLeptonFastSimUncertainty(tree,cuts)
						EMuLeptonFullSimScaleFactorShiftedGenMet = produceLeptonFullSimUncertainty(tree,cuts)
						EMuPileupHighGenMet,EMuPileupLowGenMet = producePileupUncertainty(tree,cuts)
						EMuBTagHeavyGenMet,EMuBTagLightGenMet = produceBTagUncertainty(tree,cuts)
						
						EMuScaleShiftedGenMet = []
						for weightIndex in range(0,8):
							EMuScaleShiftedGenMet.append(produceScaleShiftUncertainty(tree,cuts,weightIndex)/scaleNormalizations[weightIndex])
						
						if ISRNormalization > 0:
							EMuISRUpGenMet = EMuISRUpGenMet*ISRNormalization/ISRNormalizationUp
							EMuISRDownGenMet = EMuISRDownGenMet*ISRNormalization/ISRNormalizationDown
							
							EMuPileupHighGenMet = EMuPileupHighGenMet * denominator/denominatorHighPU
							EMuPileupLowGenMet = EMuPileupLowGenMet * denominator/denominatorLowPU
						
						cuts = cuts.replace("genMet","met")
						
						EMusignalYield = 0.5* (EMusignalYieldMet + EMusignalYieldGenMet)
						EMusignalEfficiency = 0.5* (EMusignalEfficiencyMet + EMusignalEfficiencyGenMet)
						EMuMCEvents = 0.5* (EMuMCEventsMet + EMuMCEventsGenMet)
						EMuISRUp = 0.5* (EMuISRUpMet + EMuISRUpGenMet) 
						EMuISRDown = 0.5* (EMuISRDownMet + EMuISRDownGenMet) 
						EMuJESUp = 0.5* (EMuJESUpMet + EMuJESUpGenMet) 
						EMuJESDown = 0.5* (EMuJESDownMet + EMuJESDownGenMet) 
						EMuLeptonFastSimScaleFactorShifted = 0.5* (EMuLeptonFastSimScaleFactorShiftedMet + EMuLeptonFastSimScaleFactorShiftedGenMet) 
						EMuLeptonFullSimScaleFactorShifted = 0.5* (EMuLeptonFullSimScaleFactorShiftedMet + EMuLeptonFullSimScaleFactorShiftedGenMet) 
						EMuPileupHigh = 0.5* (EMuPileupHighMet + EMuPileupHighGenMet) 
						EMuPileupLow = 0.5* (EMuPileupLowMet + EMuPileupLowGenMet) 
						EMuBTagHeavy = 0.5* (EMuBTagHeavyMet + EMuBTagHeavyGenMet) 
						EMuBTagLight = 0.5* (EMuBTagLightMet + EMuBTagLightGenMet)
						
						EMuScaleShifted = []
						for weightIndex in range(0,8):
							EMuScaleShifted.append(0.5*(EMuScaleShiftedMet[weightIndex]+EMuScaleShiftedGenMet[weightIndex]))
						
						UnscaledYield = EMusignalYield / (EMuTriggerEff * scalingLumi)
						
						if UnscaledYield > 0:
							EMuISRUncertainty = max(abs(EMuISRUp-UnscaledYield)/UnscaledYield,abs(EMuISRDown-UnscaledYield)/UnscaledYield) 
							EMuJESUncertainty = max(abs(EMuJESUp-UnscaledYield)/UnscaledYield,abs(EMuJESDown-UnscaledYield)/UnscaledYield) 
							EMuPileupUncertainty = max(abs(EMuPileupHigh-UnscaledYield)/UnscaledYield,abs(EMuPileupLow-UnscaledYield)/UnscaledYield) 
							EMuLeptonFullSimUncertainty = abs(EMuLeptonFullSimScaleFactorShifted-UnscaledYield)/UnscaledYield
							EMuLeptonFastSimUncertainty = abs(EMuLeptonFastSimScaleFactorShifted-UnscaledYield)/UnscaledYield
							EMuBTagHeavyUncertainty = abs(EMuBTagHeavy-UnscaledYield)/UnscaledYield
							EMuBTagLightUncertainty = abs(EMuBTagLight-UnscaledYield)/UnscaledYield
							EMuMetUncertainty = abs(EMusignalYieldMet-EMusignalYield)/EMusignalYield
							EMuStatUncertainty = sqrt(EMuMCEvents)
							
							EMuScaleUncertainty = 0
							for weightIndex in range(0,8):
								EMuScaleUncertainty = max (EMuScaleUncertainty, abs(EMuScaleShifted[weightIndex]-UnscaledYield)/UnscaledYield)
								
						else:
							EMuISRUncertainty = 0.
							EMuJESUncertainty = 0. 
							EMuPileupUncertainty = 0.
							EMuLeptonFullSimUncertainty = 0.
							EMuLeptonFastSimUncertainty = 0.
							EMuBTagHeavyUncertainty = 0.
							EMuBTagLightUncertainty = 0.
							EMuMetUncertainty = 0.
							EMuStatUncertainty = 0.
							EMuScaleUncertainty = 0
						
						
						EMusystUncertainty = sqrt(EMuScaleUncertainty**2+EMuMetUncertainty**2+EMuBTagHeavyUncertainty**2+EMuBTagLightUncertainty**2+EMuJESUncertainty**2+EMuLeptonFastSimUncertainty**2+EMuLeptonFullSimUncertainty**2+EMuPileupUncertainty**2+EMuISRUncertainty**2+triggerEffUncertainty**2+lumiUncertainty**2)
						
						counts["%s_EMu"%signalBin] = {"Val":EMusignalYield,"MCEvents":EMuMCEvents,"SignalEfficiency":EMusignalEfficiency,"StatUncertainty":EMuStatUncertainty,"TotSystUncertainty":EMusystUncertainty,
						"JESUncertainty":EMuJESUncertainty,"JESMean":UnscaledYield*EMuTriggerEff,"JESUp":EMuJESUp*EMuTriggerEff,"JESDown":EMuJESDown*EMuTriggerEff,
						"LeptonFastSimUncertainty":EMuLeptonFastSimUncertainty,"LeptonFastSimMean":UnscaledYield*EMuTriggerEff,"LeptonFastSimScaleFactorShifted":EMuLeptonFastSimScaleFactorShifted*EMuTriggerEff,
						"LeptonFullSimUncertainty":EMuLeptonFullSimUncertainty,"LeptonFullSimMean":UnscaledYield*EMuTriggerEff,"LeptonFullSimScaleFactorShifted":EMuLeptonFullSimScaleFactorShifted*EMuTriggerEff,
						"PileupUncertainty":EMuPileupUncertainty,"PileupMean":UnscaledYield*EMuTriggerEff,"PileupHigh":EMuPileupHigh*EMuTriggerEff,"PileupLow":EMuPileupLow*EMuTriggerEff,
						"ISRUncertainty":EMuISRUncertainty,"ISRMean":UnscaledYield*EMuTriggerEff,"ISRUp":EMuISRUp*EMuTriggerEff,"ISRDown":EMuISRDown*EMuTriggerEff,
						"MetUncertainty":EMuMetUncertainty,"Met":EMusignalYieldMet,"GenMet":EMusignalYieldGenMet,
						"ScaleUncertainty":EMuScaleUncertainty,"ScaleShifted1":EMuScaleShifted[0]*EMuTriggerEff,"ScaleShifted2":EMuScaleShifted[1]*EMuTriggerEff,"ScaleShifted3":EMuScaleShifted[2]*EMuTriggerEff,"ScaleShifted4":EMuScaleShifted[3]*EMuTriggerEff,"ScaleShifted5":EMuScaleShifted[4]*EMuTriggerEff,"ScaleShifted6":EMuScaleShifted[5]*EMuTriggerEff,"ScaleShifted7":EMuScaleShifted[6]*EMuTriggerEff,"ScaleShifted8":EMuScaleShifted[7]*EMuTriggerEff,
						"BTagHeavyUncertainty":EMuBTagHeavyUncertainty,"BTagMean":UnscaledYield*EMuTriggerEff,"BTagHeavy":EMuBTagHeavy*EMuTriggerEff,"BTagLightUncertainty":EMuBTagLightUncertainty,"BTagLight":EMuBTagLight*EMuTriggerEff}
						
				
				for sample, tree in MMTrees.iteritems():
					if sample == sampleName:
						MuMusignalYieldMet = signalYields(tree,cuts, MuMuTriggerEff * scalingLumi)
						MuMusignalEfficiencyMet = produceSignalEfficiency(tree, cuts, weight)
						MuMuMCEventsMet = MCEventYield(tree,unweightedCuts)
						MuMuISRUpMet,MuMuISRDownMet = produceISRUncertainty(tree,cuts)
						MuMuJESUpMet,MuMuJESDownMet= produceJESUncertainty(tree,cuts)
						MuMuLeptonFastSimScaleFactorShiftedMet = produceLeptonFastSimUncertainty(tree,cuts)
						MuMuLeptonFullSimScaleFactorShiftedMet = produceLeptonFullSimUncertainty(tree,cuts)
						MuMuPileupHighMet,MuMuPileupLowMet = producePileupUncertainty(tree,cuts)
						MuMuBTagHeavyMet,MuMuBTagLightMet = produceBTagUncertainty(tree,cuts)
						
						MuMuScaleShiftedMet = []
						for weightIndex in range(0,8):
							MuMuScaleShiftedMet.append(produceScaleShiftUncertainty(tree,cuts,weightIndex)/scaleNormalizations[weightIndex])
						
						
						if ISRNormalization > 0:
							MuMuISRUpMet = MuMuISRUpMet*ISRNormalization/ISRNormalizationUp
							MuMuISRDownMet = MuMuISRDownMet*ISRNormalization/ISRNormalizationDown
							
							MuMuPileupHighMet = MuMuPileupHighMet * denominator/denominatorHighPU
							MuMuPileupLowMet = MuMuPileupLowMet * denominator/denominatorLowPU
						
						
						cuts = cuts.replace("met","genMet")
						
						MuMusignalYieldGenMet = signalYields(tree,cuts, MuMuTriggerEff * scalingLumi)
						MuMusignalEfficiencyGenMet = produceSignalEfficiency(tree, cuts, weight)
						MuMuMCEventsGenMet = MCEventYield(tree,unweightedCuts)
						MuMuISRUpGenMet,MuMuISRDownGenMet = produceISRUncertainty(tree,cuts)
						MuMuJESUpGenMet,MuMuJESDownGenMet= produceJESUncertainty(tree,cuts)
						MuMuLeptonFastSimScaleFactorShiftedGenMet = produceLeptonFastSimUncertainty(tree,cuts)
						MuMuLeptonFullSimScaleFactorShiftedGenMet = produceLeptonFullSimUncertainty(tree,cuts)
						MuMuPileupHighGenMet,MuMuPileupLowGenMet = producePileupUncertainty(tree,cuts)
						MuMuBTagHeavyGenMet,MuMuBTagLightGenMet = produceBTagUncertainty(tree,cuts)
						
						MuMuScaleShiftedGenMet = []
						for weightIndex in range(0,8):
							MuMuScaleShiftedGenMet.append(produceScaleShiftUncertainty(tree,cuts,weightIndex)/scaleNormalizations[weightIndex])
						
						
						if ISRNormalization > 0:
							MuMuISRUpGenMet = MuMuISRUpGenMet*ISRNormalization/ISRNormalizationUp
							MuMuISRDownGenMet = MuMuISRDownGenMet*ISRNormalization/ISRNormalizationDown
							
							MuMuPileupHighGenMet = MuMuPileupHighGenMet * denominator/denominatorHighPU
							MuMuPileupLowGenMet = MuMuPileupLowGenMet * denominator/denominatorLowPU
						
						cuts = cuts.replace("genMet","met")
						
						MuMusignalYield = 0.5* (MuMusignalYieldMet + MuMusignalYieldGenMet)
						MuMusignalEfficiency = 0.5* (MuMusignalEfficiencyMet + MuMusignalEfficiencyGenMet)
						MuMuMCEvents = 0.5* (MuMuMCEventsMet + MuMuMCEventsGenMet)
						MuMuISRUp = 0.5* (MuMuISRUpMet + MuMuISRUpGenMet) 
						MuMuISRDown = 0.5* (MuMuISRDownMet + MuMuISRDownGenMet) 
						MuMuJESUp = 0.5* (MuMuJESUpMet + MuMuJESUpGenMet) 
						MuMuJESDown = 0.5* (MuMuJESDownMet + MuMuJESDownGenMet) 
						MuMuLeptonFastSimScaleFactorShifted = 0.5* (MuMuLeptonFastSimScaleFactorShiftedMet + MuMuLeptonFastSimScaleFactorShiftedGenMet) 
						MuMuLeptonFullSimScaleFactorShifted = 0.5* (MuMuLeptonFullSimScaleFactorShiftedMet + MuMuLeptonFullSimScaleFactorShiftedGenMet) 
						MuMuPileupHigh = 0.5* (MuMuPileupHighMet + MuMuPileupHighGenMet) 
						MuMuPileupLow = 0.5* (MuMuPileupLowMet + MuMuPileupLowGenMet) 
						MuMuBTagHeavy = 0.5* (MuMuBTagHeavyMet + MuMuBTagHeavyGenMet) 
						MuMuBTagLight = 0.5* (MuMuBTagLightMet + MuMuBTagLightGenMet)
						
						MuMuScaleShifted = []
						for weightIndex in range(0,8):
							MuMuScaleShifted.append(0.5*(MuMuScaleShiftedMet[weightIndex]+MuMuScaleShiftedGenMet[weightIndex]))
						
						UnscaledYield = MuMusignalYield / (MuMuTriggerEff * scalingLumi)
						
						if UnscaledYield > 0:
							MuMuISRUncertainty = max(abs(MuMuISRUp-UnscaledYield)/UnscaledYield,abs(MuMuISRDown-UnscaledYield)/UnscaledYield) 
							MuMuJESUncertainty = max(abs(MuMuJESUp-UnscaledYield)/UnscaledYield,abs(MuMuJESDown-UnscaledYield)/UnscaledYield) 
							MuMuPileupUncertainty = max(abs(MuMuPileupHigh-UnscaledYield)/UnscaledYield,abs(MuMuPileupLow-UnscaledYield)/UnscaledYield) 
							MuMuLeptonFullSimUncertainty = abs(MuMuLeptonFullSimScaleFactorShifted-UnscaledYield)/UnscaledYield
							MuMuLeptonFastSimUncertainty = abs(MuMuLeptonFastSimScaleFactorShifted-UnscaledYield)/UnscaledYield
							MuMuBTagHeavyUncertainty = abs(MuMuBTagHeavy-UnscaledYield)/UnscaledYield
							MuMuBTagLightUncertainty = abs(MuMuBTagLight-UnscaledYield)/UnscaledYield
							MuMuMetUncertainty = abs(MuMusignalYieldMet-MuMusignalYield)/MuMusignalYield
							MuMuStatUncertainty = sqrt(MuMuMCEvents)
							
							MuMuScaleUncertainty = 0
							for weightIndex in range(0,8):
								MuMuScaleUncertainty = max (MuMuScaleUncertainty, abs(MuMuScaleShifted[weightIndex]-UnscaledYield)/UnscaledYield)
								
						else:
							MuMuISRUncertainty = 0.
							MuMuJESUncertainty = 0. 
							MuMuPileupUncertainty = 0.
							MuMuLeptonFullSimUncertainty = 0.
							MuMuLeptonFastSimUncertainty = 0.
							MuMuBTagHeavyUncertainty = 0.
							MuMuBTagLightUncertainty = 0.
							MuMuMetUncertainty = 0.
							MuMuStatUncertainty = 0.
							MuMuScaleUncertainty = 0.
						
						
						MuMusystUncertainty = sqrt(MuMuScaleUncertainty**2+MuMuMetUncertainty**2+MuMuBTagHeavyUncertainty**2+MuMuBTagLightUncertainty**2+MuMuJESUncertainty**2+MuMuLeptonFastSimUncertainty**2+MuMuLeptonFullSimUncertainty**2+MuMuPileupUncertainty**2+MuMuISRUncertainty**2+triggerEffUncertainty**2+lumiUncertainty**2)
						
						counts["%s_MuMu"%signalBin] = {"Val":MuMusignalYield,"MCEvents":MuMuMCEvents,"SignalEfficiency":MuMusignalEfficiency,"StatUncertainty":MuMuStatUncertainty,"TotSystUncertainty":MuMusystUncertainty,
						"JESUncertainty":MuMuJESUncertainty,"JESMean":UnscaledYield*MuMuTriggerEff,"JESUp":MuMuJESUp*MuMuTriggerEff,"JESDown":MuMuJESDown*MuMuTriggerEff,
						"LeptonFastSimUncertainty":MuMuLeptonFastSimUncertainty,"LeptonFastSimMean":UnscaledYield*MuMuTriggerEff,"LeptonFastSimScaleFactorShifted":MuMuLeptonFastSimScaleFactorShifted*MuMuTriggerEff,
						"LeptonFullSimUncertainty":MuMuLeptonFullSimUncertainty,"LeptonFullSimMean":UnscaledYield*MuMuTriggerEff,"LeptonFullSimScaleFactorShifted":MuMuLeptonFullSimScaleFactorShifted*MuMuTriggerEff,
						"PileupUncertainty":MuMuPileupUncertainty,"PileupMean":UnscaledYield*MuMuTriggerEff,"PileupHigh":MuMuPileupHigh*MuMuTriggerEff,"PileupLow":MuMuPileupLow*MuMuTriggerEff,
						"ISRUncertainty":MuMuISRUncertainty,"ISRMean":UnscaledYield*MuMuTriggerEff,"ISRUp":MuMuISRUp*MuMuTriggerEff,"ISRDown":MuMuISRDown*MuMuTriggerEff,
						"ISRUncertainty":MuMuISRUncertainty,"ISRMean":UnscaledYield*MuMuTriggerEff,"ISRUp":MuMuISRUp*MuMuTriggerEff,"ISRDown":MuMuISRDown*MuMuTriggerEff,
						"MetUncertainty":MuMuMetUncertainty,"Met":MuMusignalYieldMet,"GenMet":MuMusignalYieldGenMet,
						"ScaleUncertainty":MuMuScaleUncertainty,"ScaleShifted1":MuMuScaleShifted[0]*MuMuTriggerEff,"ScaleShifted2":MuMuScaleShifted[1]*MuMuTriggerEff,"ScaleShifted3":MuMuScaleShifted[2]*MuMuTriggerEff,"ScaleShifted4":MuMuScaleShifted[3]*MuMuTriggerEff,"ScaleShifted5":MuMuScaleShifted[4]*MuMuTriggerEff,"ScaleShifted6":MuMuScaleShifted[5]*MuMuTriggerEff,"ScaleShifted7":MuMuScaleShifted[6]*MuMuTriggerEff,"ScaleShifted8":MuMuScaleShifted[7]*MuMuTriggerEff,
						"BTagHeavyUncertainty":MuMuBTagHeavyUncertainty,"BTagMean":UnscaledYield*MuMuTriggerEff,"BTagHeavy":MuMuBTagHeavy*MuMuTriggerEff,"BTagLightUncertainty":MuMuBTagLightUncertainty,"BTagLight":MuMuBTagLight*MuMuTriggerEff}
						
			
			outFilePkl = open("shelvesSystematics/%s.pkl"%(sampleName),"w")
			pickle.dump(counts, outFilePkl)
			outFilePkl.close()
			
			m_n += stepsize
		m_b += stepsize
def getHistograms(path, plot, runRange, isMC, backgrounds, source):

    if not isMC:
        treesEE = readTrees(path, "EE", modifier="TriggerPFHT")
        treesMuMu = readTrees(path, "MuMu", modifier="TriggerPFHT")
        treesEMu = readTrees(path, "EMu", modifier="TriggerPFHT")

        denominatorHistoEE = TH1F("", "", plot.nBins, plot.firstBin,
                                  plot.lastBin)
        for name, tree in treesEE.iteritems():
            if name == "MergedData":
                denominatorHistoEE.Add(
                    createHistoFromTree(tree,
                                        plot.variable,
                                        plot.cuts,
                                        plot.nBins,
                                        plot.firstBin,
                                        plot.lastBin,
                                        binning=plot.binning).Clone())
        denominatorHistoMuMu = TH1F("", "", plot.nBins, plot.firstBin,
                                    plot.lastBin)
        for name, tree in treesMuMu.iteritems():
            if name == "MergedData":
                denominatorHistoMuMu.Add(
                    createHistoFromTree(tree,
                                        plot.variable,
                                        plot.cuts,
                                        plot.nBins,
                                        plot.firstBin,
                                        plot.lastBin,
                                        binning=plot.binning).Clone())
        denominatorHistoMuEG = TH1F("", "", plot.nBins, plot.firstBin,
                                    plot.lastBin)
        for name, tree in treesEMu.iteritems():
            if name == "MergedData":
                denominatorHistoMuEG.Add(
                    createHistoFromTree(tree,
                                        plot.variable,
                                        plot.cuts,
                                        plot.nBins,
                                        plot.firstBin,
                                        plot.lastBin,
                                        binning=plot.binning).Clone())

        cutsEE = plot.cuts.replace(
            "chargeProduct < 0",
            "chargeProduct < 0 && %s" % theCuts.triggerCuts.EE.cut)
        cutsOF = plot.cuts.replace(
            "chargeProduct < 0",
            "chargeProduct < 0 && %s" % theCuts.triggerCuts.EM.cut)
        cutsMuMu = plot.cuts.replace(
            "chargeProduct < 0",
            "chargeProduct < 0 && %s" % theCuts.triggerCuts.MM.cut)

        nominatorHistoEE = TH1F("", "", plot.nBins, plot.firstBin,
                                plot.lastBin)
        for name, tree in treesEE.iteritems():
            if name == "MergedData":
                nominatorHistoEE.Add(
                    createHistoFromTree(tree,
                                        plot.variable,
                                        cutsEE,
                                        plot.nBins,
                                        plot.firstBin,
                                        plot.lastBin,
                                        binning=plot.binning).Clone())
        nominatorHistoMuMu = TH1F("", "", plot.nBins, plot.firstBin,
                                  plot.lastBin)
        for name, tree in treesMuMu.iteritems():
            if name == "MergedData":
                nominatorHistoMuMu.Add(
                    createHistoFromTree(tree,
                                        plot.variable,
                                        cutsMuMu,
                                        plot.nBins,
                                        plot.firstBin,
                                        plot.lastBin,
                                        binning=plot.binning).Clone())
        nominatorHistoMuEG = TH1F("", "", plot.nBins, plot.firstBin,
                                  plot.lastBin)
        for name, tree in treesEMu.iteritems():
            if name == "MergedData":
                nominatorHistoMuEG.Add(
                    createHistoFromTree(tree,
                                        plot.variable,
                                        cutsOF,
                                        plot.nBins,
                                        plot.firstBin,
                                        plot.lastBin,
                                        binning=plot.binning).Clone())
    else:
        treesEE = readTrees(path, "EE")
        treesMuMu = readTrees(path, "MuMu")
        treesEMu = readTrees(path, "EMu")

        eventCounts = totalNumberOfGeneratedEvents(path)
        processes = []
        for background in backgrounds:
            processes.append(
                Process(getattr(Backgrounds, background), eventCounts))

        nominatorStackEE = TheStack(processes,
                                    runRange.lumi,
                                    plot,
                                    treesEE,
                                    "None",
                                    1.0,
                                    1.0,
                                    1.0,
                                    useTriggerEmulation=True)
        nominatorStackMuMu = TheStack(processes,
                                      runRange.lumi,
                                      plot,
                                      treesMuMu,
                                      "None",
                                      1.0,
                                      1.0,
                                      1.0,
                                      useTriggerEmulation=True)
        nominatorStackMuEG = TheStack(processes,
                                      runRange.lumi,
                                      plot,
                                      treesEMu,
                                      "None",
                                      1.0,
                                      1.0,
                                      1.0,
                                      useTriggerEmulation=True)

        denominatorStackEE = TheStack(processes, runRange.lumi, plot, treesEE,
                                      "None", 1.0, 1.0, 1.0)
        denominatorStackMuMu = TheStack(processes, runRange.lumi, plot,
                                        treesMuMu, "None", 1.0, 1.0, 1.0)
        denominatorStackMuEG = TheStack(processes, runRange.lumi, plot,
                                        treesEMu, "None", 1.0, 1.0, 1.0)

        denominatorHistoEE = denominatorStackEE.theHistogram
        denominatorHistoMuMu = denominatorStackMuMu.theHistogram
        denominatorHistoMuEG = denominatorStackMuEG.theHistogram

        nominatorHistoEE = nominatorStackEE.theHistogram
        nominatorHistoMuMu = nominatorStackMuMu.theHistogram
        nominatorHistoMuEG = nominatorStackMuEG.theHistogram

    return {
        "EE": denominatorHistoEE,
        "MuMu": denominatorHistoMuMu,
        "MuEG": denominatorHistoMuEG
    }, {
        "EE": nominatorHistoEE,
        "MuMu": nominatorHistoMuMu,
        "MuEG": nominatorHistoMuEG
    }
def getYields(runRange):
    import ratios

    import pickle

    path = locations[runRange.era].dataSetPathNLL

    EE = readTrees(path, "EE")
    EM = readTrees(path, "EMu")
    MM = readTrees(path, "MuMu")

    ### Mass bins for Morion 2017 SRs, summed low and high mass regions + legacy regions
    massRegions = [
        "mass20To60", "mass60To86", "mass86To96", "mass96To150",
        "mass150To200", "mass200To300", "mass300To400", "mass400"
    ]

    ### Two likelihood bins and MT2 cut
    nLLRegions = ["lowNLL", "highNLL"]
    MT2Regions = ["highMT2"]
    nBJetsRegions = ["zeroBJets", "oneOrMoreBJets"]

    signalBins = []
    signalCuts = {}

    plot = getPlot("mllPlotROutIn")

    for massRegion in massRegions:
        for nLLRegion in nLLRegions:
            for MT2Region in MT2Regions:
                for nBJetsRegion in nBJetsRegions:
                    signalBins.append(
                        "%s_%s_%s_%s" %
                        (massRegion, nLLRegion, MT2Region, nBJetsRegion))
                    signalCuts["%s_%s_%s_%s" %
                               (massRegion, nLLRegion, MT2Region,
                                nBJetsRegion)] = "%s && %s && %s && %s" % (
                                    massCuts[massRegion], nLLCuts[nLLRegion],
                                    MT2Cuts[MT2Region],
                                    NBJetsCuts[nBJetsRegion])

    selection = getRegion("SignalHighMT2DeltaPhiJetMet")
    backgrounds = [
        "RareWZOnZ", "RareZZLowMassOnZ", "RareTTZOnZ", "RareRestOnZ"
    ]

    plot.addRegion(selection)
    plot.addRunRange(runRange)
    plot.cuts = plot.cuts.replace("p4.M()", "mll")
    plot.variable = plot.variable.replace("p4.M()", "mll")

    if runRange.era == "2018":
        plot.cuts = plot.cuts.replace("chargeProduct < 0 &&",
                                      "chargeProduct < 0 && vetoHEM == 1 &&")

    counts = {}

    eventCounts = totalNumberOfGeneratedEvents(path)

    defaultCut = plot.cuts

    ### loop over signal regions
    for signalBin in signalBins:

        ### Add signal cut and remove those that are renamed or already applied
        ### on NLL datasets
        plot.cuts = defaultCut.replace(
            "chargeProduct < 0",
            "chargeProduct < 0 && %s" % (signalCuts[signalBin]))
        plot.cuts = plot.cuts.replace("metFilterSummary > 0 &&", "")
        plot.cuts = plot.cuts.replace("&& metFilterSummary > 0", "")
        plot.cuts = plot.cuts.replace("triggerSummary > 0 &&", "")
        plot.cuts = plot.cuts.replace("p4.Pt()", "pt")

        plot.cuts = "bTagWeight*" + plot.cuts

        #print plot.cuts

        eventCountSF = 0
        eventYieldSF = 0
        eventYieldEE = 0
        eventYieldMM = 0
        eventYieldSFTotErr = 0
        eventYieldSFStatErr = 0
        eventYieldEEStatErr = 0
        eventYieldMMStatErr = 0
        eventYieldSFSystErr = 0
        eventYieldSFUp = 0
        eventYieldEEUp = 0
        eventYieldMMUp = 0
        eventYieldSFDown = 0
        eventYieldEEDown = 0
        eventYieldMMDown = 0

        eventYieldOF = 0
        eventYieldOFTotErr = 0
        eventYieldOFStatErr = 0
        eventYieldOFSystErr = 0
        eventYieldOFUp = 0
        eventYieldOFDown = 0

        counts["%s_bySample" % signalBin] = {}

        processes = []
        for background in backgrounds:
            proc = Process(getattr(Backgrounds[runRange.era], background),
                           eventCounts)
            processes.append(proc)

            picklePath = "/home/home4/institut_1b/teroerde/Doktorand/SUSYFramework/frameWorkBase/shelves/scaleFactor_{runRange}_{background}.pkl"
            sf = 1.0
            sferr = 0.0
            if proc.label in ["WZ", "ZZ", "TTZ"]:
                if proc.label == "WZ":
                    backgroundName = "WZTo3LNu"
                elif proc.label == "ZZ":
                    backgroundName = "ZZTo4L"
                elif proc.label == "TTZ":
                    backgroundName = "ttZToLL"
                import pickle
                with open(
                        picklePath.format(runRange=runRange.label,
                                          background=backgroundName),
                        "r") as fi:
                    scaleFac = pickle.load(fi)
                sf = scaleFac["scaleFac"]
                sferr = scaleFac["scaleFacErr"]
            else:
                sferr = proc.uncertainty

            sfErrRel = sferr / sf

            saveCut = plot.cuts

            histoEE = proc.createCombinedHistogram(
                runRange.lumi,
                plot,
                EE,
                "None",
                1.0,
                getTriggerScaleFactor("EE", "inclusive", runRange)[0] * sf,
                1.0,
                TopWeightUp=False,
                TopWeightDown=False,
                signal=False,
                doTopReweighting=True,
                doPUWeights=False,
                normalizeToBinWidth=False,
                useTriggerEmulation=False)
            histoMM = proc.createCombinedHistogram(
                runRange.lumi,
                plot,
                MM,
                "None",
                1.0,
                getTriggerScaleFactor("MM", "inclusive", runRange)[0] * sf,
                1.0,
                TopWeightUp=False,
                TopWeightDown=False,
                signal=False,
                doTopReweighting=True,
                doPUWeights=False,
                normalizeToBinWidth=False,
                useTriggerEmulation=False)

            # RSFOF weighted EMu sample with rMuE parametrization
            rMuEPars = corrections[runRange.era].rMuELeptonPt.inclusive
            RT = corrections[runRange.era].rSFOFTrig.inclusive.val
            corrMap = {}
            corrMap["offset"] = rMuEPars.ptOffsetMC
            corrMap["falling"] = rMuEPars.ptFallingMC
            corrMap["etaParabolaBase"] = rMuEPars.etaParabolaBaseMC
            corrMap["etaParabolaMinus"] = rMuEPars.etaParabolaMinusMC
            corrMap["etaParabolaPlus"] = rMuEPars.etaParabolaPlusMC
            corrMap["norm"] = rMuEPars.normMC

            rMuEDummy = "({norm:.3f}*(({offset:.3f} + {falling:.3f}/{pt})*({etaParabolaBase} + ({eta}<-1.6)*{etaParabolaMinus:.3f}*pow({eta}+1.6, 2)+({eta}>1.6)*{etaParabolaPlus:.3f}*pow({eta}-1.6,2) )))"
            rMuE_El = rMuEDummy.format(pt="pt1", eta="eta1", **corrMap)
            rMuE_Mu = rMuEDummy.format(pt="pt2", eta="eta2", **corrMap)
            rMuEWeight = "(0.5*(%s + pow(%s, -1)))*%.3f" % (rMuE_Mu, rMuE_El,
                                                            RT)

            #tmpCut = plot.cuts
            plot.cuts = "%s*%s" % (rMuEWeight, plot.cuts)
            histoEM = proc.createCombinedHistogram(
                runRange.lumi,
                plot,
                EM,
                "None",
                1.0,
                getTriggerScaleFactor("EM", "inclusive", runRange)[0] * sf,
                1.0,
                TopWeightUp=False,
                TopWeightDown=False,
                signal=False,
                doTopReweighting=True,
                doPUWeights=False,
                normalizeToBinWidth=False,
                useTriggerEmulation=False)
            #plot.cuts = tmpCut

            plot.cuts = saveCut

            statErrEE = ROOT.Double()
            statErrMM = ROOT.Double()
            statErrEM = ROOT.Double()

            eventCountSF += histoEE.GetEntries() + histoMM.GetEntries()

            procYield = histoEE.IntegralAndError(
                0, -1, statErrEE) + histoMM.IntegralAndError(0, -1, statErrMM)
            procYield_EE = histoEE.IntegralAndError(0, -1, statErrEE)
            procYield_MM = histoMM.IntegralAndError(0, -1, statErrMM)

            #if "mass20To60" in signalBin and proc.label == "ZZ":
            #print signalBin, procYield

            eventYieldSF += procYield
            eventYieldSFUp += (procYield) * (1 + sfErrRel)
            eventYieldSFDown += (procYield) * (1 - sfErrRel)

            eventYieldEE += procYield_EE
            eventYieldEEUp += (procYield_EE) * (1 + sfErrRel)
            eventYieldEEDown += (procYield_EE) * (1 - sfErrRel)

            eventYieldMM += procYield_MM
            eventYieldMMUp += (procYield_MM) * (1 + sfErrRel)
            eventYieldMMDown += (procYield_MM) * (1 - sfErrRel)

            eventYieldSFStatErr = (eventYieldSFStatErr**2 + statErrEE**2 +
                                   statErrMM**2)**0.5
            eventYieldEEStatErr = (eventYieldEEStatErr**2 + statErrEE**2)**0.5
            eventYieldMMStatErr = (eventYieldMMStatErr**2 + statErrMM**2)**0.5
            eventYieldSFSystErr = (eventYieldSFSystErr**2 +
                                   (eventYieldSF * sfErrRel)**2)**0.5

            eventYieldOF += histoEM.IntegralAndError(0, -1, statErrEM)
            eventYieldOFUp += histoEM.Integral(0, -1) * (1 + proc.uncertainty)
            eventYieldOFDown += histoEM.Integral(0,
                                                 -1) * (1 - proc.uncertainty)

            eventYieldOFStatErr = (eventYieldOFStatErr**2 + statErrEM**2)**0.5
            eventYieldOFSystErr = (eventYieldOFSystErr**2 +
                                   (eventYieldOF * sfErrRel)**2)**0.5

            counts["%s_bySample" % signalBin][proc.label] = procYield

            if proc.label in ["WZ", "ZZ", "TTZ", "Rare"]:
                # uncertainty from just this one sample. Used to treat uncertainties uncorrelated between WZ,ZZ,TTZ,Rare
                counts["%s_SingleErr%s" % (signalBin, proc.label)] = (
                    ((procYield) * sfErrRel)**2 + statErrEE**2 +
                    statErrMM**2)**0.5

            #if proc.label == "ZZ" and "highNLL" in signalBin:
            #print signalBin, gotten

        eventYieldSFTotErr = (eventYieldSFStatErr**2 +
                              eventYieldSFSystErr**2)**0.5
        eventYieldOFTotErr = (eventYieldOFStatErr**2 +
                              eventYieldOFSystErr**2)**0.5

        eventCountSF = histoEE.GetEntries() + histoMM.GetEntries()

        counts["%s_SF" % signalBin] = eventYieldSF
        counts["%s_EE" % signalBin] = eventYieldEE
        counts["%s_MM" % signalBin] = eventYieldMM
        counts["%s_SF_Stat" % signalBin] = eventYieldSFStatErr
        counts["%s_EE_Stat" % signalBin] = eventYieldEEStatErr
        counts["%s_MM_Stat" % signalBin] = eventYieldMMStatErr
        counts["%s_SF_Syst" % signalBin] = eventYieldSFSystErr
        counts["%s_SF_Up" % signalBin] = eventYieldSFUp
        counts["%s_EE_Up" % signalBin] = eventYieldEEUp
        counts["%s_MM_Up" % signalBin] = eventYieldMMUp
        counts["%s_SF_Down" % signalBin] = eventYieldSFDown
        counts["%s_EE_Down" % signalBin] = eventYieldEEDown
        counts["%s_MM_Down" % signalBin] = eventYieldMMDown
        counts["MCEvents_%s_SF" % signalBin] = eventCountSF

        counts["%s_OF" % signalBin] = eventYieldOF
        counts["%s_OF_Stat" % signalBin] = eventYieldOFStatErr
        counts["%s_OF_Syst" % signalBin] = eventYieldOFSystErr
        counts["%s_OF_Err" % signalBin] = eventYieldOFTotErr
        counts["%s_OF_Up" % signalBin] = eventYieldOFUp
        counts["%s_OF_Down" % signalBin] = eventYieldOFDown

    fileName = "RareOnZBG_%s" % (runRange.label)

    outFilePkl = open("shelves/%s.pkl" % fileName, "w")
    pickle.dump(counts, outFilePkl)
    outFilePkl.close()