コード例 #1
0
def getYieldsFromFile(file):
    f = r.TFile(file)    
    tree = f.Get('eventTree')
    total = tree.GetEntries()

    scaleDict = getScales(f)
    yieldsDict = {}
    yieldsDict['1M'] = {'QCD': 0.0, 'tt': 0.0, 'VV': 0.0, 'ZTT': 0.0, 'ZLL': 0.0, 'signal': 0.0,
                        'H2hh260': 0.0, 'H2hh270': 0.0, 'H2hh280': 0.0, 'H2hh290': 0.0, 'H2hh300': 0.0,
                        'H2hh310': 0.0, 'H2hh320': 0.0, 'H2hh330': 0.0, 'H2hh340': 0.0, 'H2hh350': 0.0}
    yieldsDict['2M'] = {'QCD': 0.0, 'tt': 0.0, 'VV': 0.0, 'ZTT': 0.0, 'ZLL': 0.0, 'signal': 0.0,
                        'H2hh260': 0.0, 'H2hh270': 0.0, 'H2hh280': 0.0, 'H2hh290': 0.0, 'H2hh300': 0.0,
                        'H2hh310': 0.0, 'H2hh320': 0.0, 'H2hh330': 0.0, 'H2hh340': 0.0, 'H2hh350': 0.0}

    for iEvent in range(total):
        tool.printProcessStatus(iEvent, total, 'Looping file [%s]' % (file))
        tree.GetEntry(iEvent)
        if not makeWholeTools2.passCut(tree):
            continue
        name = getSampleName(tree.sampleName)
        if name in yieldsDict['1M'].keys():
            if tree.Category == '0M':
                continue
            yieldsDict[tree.Category][name] += getWeight(tree, tree.sampleName)
    #rescale
    for cat in ['1M', '2M']:
        yieldsDict[cat]['ZTT'] = scaleDict[cat]['ZTT']
        yieldsDict[cat]['ZLL'] = scaleDict[cat]['ZLL']
        yieldsDict[cat]['VV'] = scaleDict[cat]['VV'] + scaleDict[cat]['singleT']
        yieldsDict[cat]['QCD'] = yieldsDict[cat]['QCD']*scaleDict[cat]['QCD']
        for i in ['H2hh260', 'H2hh270', 'H2hh280', 'H2hh290', 'H2hh300', 'H2hh310', 'H2hh320', 'H2hh330', 'H2hh340', 'H2hh350']:
            yieldsDict[cat]['signal'] += yieldsDict[cat][i]

    print ''
    return yieldsDict
コード例 #2
0
def buildHisto(file, hist, sum_b, varName):
    tfile = r.TFile(file)    
    tree = tfile.Get('eventTree_test')
    nEntries = tree.GetEntries()
    nBins = hist.GetNbinsX()
    for i in range(nEntries):
        tree.GetEntry(i)
        tool.printProcessStatus(i, nEntries, 'Looping sample %s' %(file), i-1)
        if varName == 'pt_1_over_m_eff':
            if getattr(tree, 'm_eff') <= 0:
                value = 0
            else:
                value = getattr(tree, 'pt_1')/getattr(tree, 'm_eff')
        elif varName == 'pt_2_over_m_eff':
            if getattr(tree, 'm_eff') <= 0:
                value = 0
            else:
                value = getattr(tree, 'pt_2')/getattr(tree, 'm_eff')
        else:
            value = getattr(tree, varName)
        if value < hist.GetBinLowEdge(1):
            value = (hist.GetBinLowEdge(1) + hist.GetBinLowEdge(2))/2.0
        elif value > hist.GetBinLowEdge(nBins+1):
            value = (hist.GetBinLowEdge(nBins) + hist.GetBinLowEdge(nBins+1))/2.0
        hist.Fill(value, tree.weightWithPU)
        if sum_b != 0:
            sum_b.Fill(value, tree.weightWithPU)
    print ''
    return hist, sum_b
コード例 #3
0
def getBothDistribution(sigHist, bkgHist, graph, graph2, diff = 0, tauPtCut = 40.5):
    nBins = sigHist.GetNbinsX()
    sigTotal = sigHist.Integral(0, nBins+1, 0, nBins+1)
    if not (bkgHist == None):
        bkgTotal = bkgHist.Integral(0, nBins+1, 0, nBins+1)
        print bkgTotal
    for i in range(1, nBins+1, 1):
        tool.printProcessStatus(i, nBins+1, processName = 'running bothDistribution', iPrevious = i-1)
        if i + diff < nBins+1:
            sigValue = sigHist.Integral(i+diff, nBins+1, i, nBins+1)
            if not (bkgHist == None):
                bkgValue = bkgHist.Integral(i+diff, nBins+1, i, nBins+1)
        else:
            bkgValue = 0.
            sigValue = 0.
        if (sigHist.GetXaxis().GetBinCenter(i) == tauPtCut):
            print sigHist.GetXaxis().GetBinCenter(i), 1 - bkgValue/bkgTotal, sigValue/sigTotal
            if not (bkgHist == None):
                graph2.SetPoint(i, 1 - bkgValue/bkgTotal, sigValue/sigTotal)
        if not (bkgHist == None):
            graph.SetPoint(i, 1 - bkgValue/bkgTotal, sigValue/sigTotal)
        else:
            graph.SetPoint(i, sigHist.GetXaxis().GetBinCenter(i), sigValue/sigTotal)

    print ''
    return graph
コード例 #4
0
def readFile(file, hist, varName, which):
    f = r.TFile(file)
    if which == '8TeV':
        tree = f.Get('eventTree')
    else:
        tree = f.Get('Ntuple')

    nEntries = tree.GetEntries()

    if which == '13TeV':
        yields = 0.0
        scale = 0.0
    else:
        yields = 0.0
        scale = 0.0
        yields_had = 0.0
        scale_had = 0.0
        yields_semi = 0.0
        scale_semi = 0.0

    for i in range(nEntries):
        tool.printProcessStatus(i, nEntries,
                                'Looping file %s for %s' % (file, varName),
                                i - 1)
        tree.GetEntry(i)
        if not passCut(tree, which):
            continue
        if which == '13TeV':
            hist.Fill(getVarValue(tree, varName, which))
            yields += 1.0
            scale = (tree.xs + 0.0) / (tree.initEvents + 0.0)
        else:
            hist.Fill(getVarValue(tree, varName, which),
                      tree.xs / (tree.initEvents + 0.0))
            if tree.sampleName == "tt_all":
                yields += 1.0
                scale = (tree.xs + 0.0) / (tree.initEvents + 0.0)
            if tree.sampleName == "tthad_all":
                yields_had += 1.0
                scale_had = (tree.xs + 0.0) / (tree.initEvents + 0.0)
            if tree.sampleName == "ttsemi_all":
                yields_semi += 1.0
                scale_semi = (tree.xs + 0.0) / (tree.initEvents + 0.0)

    if which == '13TeV':
        hist.Sumw2()
        hist.Scale((tree.xs + 0.0) / (tree.initEvents + 0.0))
        unc = math.sqrt(yields + 0.0) * scale
    else:
        unc = math.sqrt(yields + 0.0) * scale + math.sqrt(
            yields_had + 0.0) * scale_had + math.sqrt(yields_semi +
                                                      0.0) * scale_semi

    print ''
    return unc
コード例 #5
0
def getDistribution2(sigHist, bkgHist, distHist, distHist2):
    nBins = distHist.GetNbinsX()
    for i in range(1, nBins+1, 1):
        tool.printProcessStatus(i, nBins, processName = 'running getDistribution2', iPrevious = i-1)
        for j in range(1, nBins+1, 1):
            sigValue = sigHist.Integral(i, nBins+1, j, nBins+1)
            bkgValue = bkgHist.Integral(i, nBins+1, j, nBins+1)
            if bkgValue != 0:
                distHist2.Fill(distHist.GetBinCenter(i), distHist.GetBinCenter(j), (sigValue+0.0)/(bkgValue+ 0.0))
    print ''
    return distHist2
コード例 #6
0
def dynamicBinning(iSample, Range = [46, 400], leg = "e"):
    file = r.TFile(iSample)   
    tree = file.Get('Ntuple')
    nEntries = tree.GetEntries()
    hist_barrel = r.TH1F("hist_barrel", "", Range[1]-Range[0], Range[0], Range[1])
    hist_middle = r.TH1F("hist_middle", "", Range[1]-Range[0], Range[0], Range[1])
    hist_endcap = r.TH1F("hist_endcap", "", Range[1]-Range[0], Range[0], Range[1])
    for iEntry in range(nEntries):
        tree.GetEntry(iEntry)
        tool.printProcessStatus(iEntry, nEntries, 'calculating dynamic binning %s' %(iSample), iEntry-1)
        if abs(tree.eEta) >= 2.1:
            continue
        if abs(tree.mEta) >= 2.1:
            continue
        if tree.q_1 == tree.q_2:
            continue
        if leg == "e":
            if abs(tree.eEta) >= 1.479:
                hist_endcap.Fill(tree.ePt)#, cutSampleTools.getPUWeight(tree.nTruePU))
            else:
                hist_barrel.Fill(tree.ePt)#, cutSampleTools.getPUWeight(tree.nTruePU))
        elif leg == 'mu':
            if abs(tree.mEta) >= 1.24:
                hist_endcap.Fill(tree.mPt)
            elif abs(tree.mEta) >= 0.8:
                hist_middle.Fill(tree.mPt)
            else:
                hist_barrel.Fill(tree.mPt)

    total_barrel = hist_barrel.Integral(1, Range[1]-Range[0])
    total_middle = hist_middle.Integral(1, Range[1]-Range[0])
    total_endcap = hist_endcap.Integral(1, Range[1]-Range[0])

    print total_barrel, total_middle, total_endcap
    mid_barrel = 0
    mid_middle = 0
    mid_endcap = 0
    #find half point
    for i in range(Range[1]-Range[0]):
        if total_barrel*0.48 <= hist_barrel.Integral(1, i+1) <= total_barrel*0.52:
            mid_barrel = i + Range[0]
        if total_middle*0.48 <= hist_middle.Integral(1, i+1) <= total_middle*0.52:
            mid_middle = i + Range[0]
        if total_endcap*0.48 <= hist_endcap.Integral(1, i+1) <= total_endcap*0.52:
            mid_endcap = i + Range[0]
    bins_barrel = array.array('d', [Range[0], mid_barrel, Range[1]])
    bins_middle = array.array('d', [Range[0], mid_middle, Range[1]])
    bins_endcap = array.array('d', [Range[0], mid_endcap, Range[1]])
    print bins_barrel, bins_middle, bins_endcap

    if leg == 'e':
        return bins_barrel, bins_endcap
    else:
        return bins_barrel, bins_middle, bins_endcap
コード例 #7
0
def loop_one_sample(iSample, iLocation):
    print 'making sample [%s]' % (iSample)

    if 'data' in iSample:
        isData = True
    else:
        isData = False

    pileup = r.TH1F('pileup', '', 50, 0, 50)

    if isData:
        outputFileName = "%s/data_600bins.root" % (options.location)
    else:
        outputFileName = "%s/MC_600bins.root" % (options.location)
    iFile = r.TFile(outputFileName, "recreate")

    for finalState in ['et', 'em']:  #, 'mt', 'tt']:
        print 'running final state: %s' % finalState
        iChain = r.TChain("Ntuple")
        match2 = ''
        if isData:
            match2 = 'data'
        nEntries = tool.addFiles(ch=iChain,
                                 dirName=iLocation,
                                 knownEventNumber=0,
                                 printTotalEvents=True,
                                 blackList='',
                                 match1=finalState,
                                 match2=match2)
        iChain.SetBranchStatus("*", 0)
        iChain.SetBranchStatus("nvtx", 1)

        iChain.LoadTree(0)

        for iEntry in range(nEntries):
            iChain.LoadTree(iEntry)
            iChain.GetEntry(iEntry)
            tool.printProcessStatus(iEntry, nEntries,
                                    'Saving to file %s' % (outputFileName),
                                    iEntry - 1)
            weight = 1.0
            if not isData:
                if hasattr(iChain, 'genEventWeight'):
                    if iChain.genEventWeight < 0:
                        weight = -1.0
                    pileup.Fill(iChain.nvtx, weight)

            else:
                pileup.Fill(iChain.nvtx, weight)
        print ''
    iFile.cd()

    pileup.Write()
    iFile.Close()
コード例 #8
0
def getHist(file, hist, varName):
    tfile = r.TFile(file)    
    tree = tfile.Get('Ntuple')
    nEntries = tree.GetEntries()
    for i in range(nEntries):
        tree.GetEntry(i)
        tool.printProcessStatus(i, nEntries, 'Looping sample %s' %(file), i-1)
        met.SetCoordinates(tree.pfMetEt, 0.0, tree.pfMetPhi, 0)
        l1.SetCoordinates(tree.pt_1, tree.eta_1, tree.phi_1, tree.m_1)
        l2.SetCoordinates(tree.pt_2, tree.eta_2, tree.phi_2, tree.m_2)
        hist.Fill(getVarValue(l1, l2, met, varName))
    print ''
    
    return hist
コード例 #9
0
ファイル: compare.py プロジェクト: zaixingmao/samples-plots
def readFile(file, hist, varName, which): 
    f = r.TFile(file)
    if which == '8TeV':
        tree = f.Get('eventTree')
    else:
        tree = f.Get('Ntuple')

    nEntries = tree.GetEntries()

    if which == '13TeV':
        yields = 0.0
        scale = 0.0
    else:
        yields = 0.0
        scale = 0.0
        yields_had = 0.0
        scale_had = 0.0
        yields_semi = 0.0
        scale_semi = 0.0

    for i in range(nEntries):
        tool.printProcessStatus(i, nEntries, 'Looping file %s for %s' % (file, varName), i-1)
        tree.GetEntry(i)
        if not passCut(tree, which):
            continue
        if which == '13TeV':
            hist.Fill(getVarValue(tree, varName, which))
            yields += 1.0
            scale = (tree.xs + 0.0)/(tree.initEvents + 0.0)
        else:
            hist.Fill(getVarValue(tree, varName, which), tree.xs/(tree.initEvents+0.0))
            if tree.sampleName == "tt_all":
                yields += 1.0
                scale = (tree.xs + 0.0)/(tree.initEvents + 0.0)
            if tree.sampleName == "tthad_all":
                yields_had += 1.0
                scale_had = (tree.xs + 0.0)/(tree.initEvents + 0.0)
            if tree.sampleName == "ttsemi_all":
                yields_semi += 1.0
                scale_semi = (tree.xs + 0.0)/(tree.initEvents + 0.0)

    if which == '13TeV':
        hist.Sumw2()
        hist.Scale((tree.xs+0.0)/(tree.initEvents+0.0))
        unc = math.sqrt(yields+0.0)*scale
    else:
        unc = math.sqrt(yields+0.0)*scale + math.sqrt(yields_had+0.0)*scale_had + math.sqrt(yields_semi+0.0)*scale_semi

    print ''
    return unc
コード例 #10
0
def getEventsCountInTree(iTree):
    eventCountInTree = {}
    total = iTree.GetEntries()
    for i in range(total):
        tool.printProcessStatus(iCurrent=i+1, total=total, processName = 'Looping sample ')
        iTree.GetEntry(i)
        tmpSampleName = tool.nameEnDecoder(iTree.sampleName2, 'decode')            
        if tmpSampleName not in eventCountInTree.keys():
            eventCountInTree[tmpSampleName] = 0.0
        else:
            eventCountInTree[tmpSampleName] += 1.0
    print ''

    return eventCountInTree
コード例 #11
0
def getDistribution2(sigHist, bkgHist, distHist, distHist2):
    nBins = distHist.GetNbinsX()
    for i in range(1, nBins + 1, 1):
        tool.printProcessStatus(i,
                                nBins,
                                processName='running getDistribution2',
                                iPrevious=i - 1)
        for j in range(1, nBins + 1, 1):
            sigValue = sigHist.Integral(i, nBins + 1, j, nBins + 1)
            bkgValue = bkgHist.Integral(i, nBins + 1, j, nBins + 1)
            if bkgValue != 0:
                distHist2.Fill(distHist.GetBinCenter(i),
                               distHist.GetBinCenter(j),
                               (sigValue + 0.0) / (bkgValue + 0.0))
    print ''
    return distHist2
コード例 #12
0
def getEventsCountInTree(iTree):
    eventCountInTree = {}
    total = iTree.GetEntries()
    for i in range(total):
        tool.printProcessStatus(iCurrent=i + 1,
                                total=total,
                                processName='Looping sample ')
        iTree.GetEntry(i)
        tmpSampleName = tool.nameEnDecoder(iTree.sampleName2, 'decode')
        if tmpSampleName not in eventCountInTree.keys():
            eventCountInTree[tmpSampleName] = 0.0
        else:
            eventCountInTree[tmpSampleName] += 1.0
    print ''

    return eventCountInTree
コード例 #13
0
def loop_one_sample(iSample, iLocation):
    print 'making sample [%s]' %(iSample)

    if 'data' in iSample:
        isData = True
    else:
        isData = False
        
    pileup = r.TH1F('pileup', '', 50, 0, 50)

    if isData:
        outputFileName = "%s/data_600bins.root" %(options.location)
    else:
        outputFileName = "%s/MC_600bins.root" %(options.location)
    iFile = r.TFile(outputFileName,"recreate")

    for finalState in ['et', 'em']:#, 'mt', 'tt']:
        print 'running final state: %s' %finalState
        iChain = r.TChain("Ntuple")
        match2 = ''
        if isData:
            match2 = 'data'
        nEntries = tool.addFiles(ch=iChain, dirName=iLocation, knownEventNumber=0, printTotalEvents=True, blackList='', match1 = finalState, match2 = match2)
        iChain.SetBranchStatus("*",0)
        iChain.SetBranchStatus("nvtx",1)

        iChain.LoadTree(0)

        for iEntry in range(nEntries):
            iChain.LoadTree(iEntry)
            iChain.GetEntry(iEntry)
            tool.printProcessStatus(iEntry, nEntries, 'Saving to file %s' %(outputFileName), iEntry-1)
            weight = 1.0
            if not isData:
                if hasattr(iChain, 'genEventWeight'):
                    if iChain.genEventWeight < 0:
                        weight = -1.0
                    pileup.Fill(iChain.nvtx, weight)

            else:
                pileup.Fill(iChain.nvtx, weight)
        print ''
    iFile.cd()

    pileup.Write()
    iFile.Close()
コード例 #14
0
def loop_through_files(inputFile, varsDict, FS, resolution = False):
    leg1, leg2 = getLegNames(FS)
    file = r.TFile(inputFile)    
    tree = file.Get('Ntuple')
    #eventCountWeighted = file.Get('eventCountWeighted').GetBinContent(1)
    nEntries = tree.GetEntries()
    for iEntry in range(nEntries):
        tree.GetEntry(iEntry)
        tool.printProcessStatus(iEntry, nEntries, 'Looping sample %s' %(inputFile), iEntry-1)
        if tree.q_1 == tree.q_2:
            continue
        if resolution:
            for iKey in varsDict.keys():
                varsDict[iKey][0].Fill((getVar(tree, iKey, leg1, leg2) - getVar(tree, 'mass_gen', leg1, leg2))/getVar(tree, 'mass_gen', leg1, leg2))
        else:
            for iKey in varsDict.keys():
                varsDict[iKey][0].Fill(getVar(tree, iKey, leg1, leg2))
    return varsDict
コード例 #15
0
def loop_one_sample(iCat, iLocation):
    print 'combininig sample [%s] for datacard' %(iCat)
    if 'obs' in iCat:
        isData = True
    else:
        isData = False

    if "signal" in iCat:
        isSignal = True
    else:
        isSignal = False

    iFile = r.TFile(iLocation)
    tail = "_train"
    if options.type == "train":
        iTree = iFile.Get("eventTree_train")
    else:
        iTree = iFile.Get("eventTree_test")
        tail = "_test"
    nEntries = iTree.GetEntries()
    iTree.SetBranchStatus("*",1)

    dicToFill = {}
    for iVar in defaultOrder:
        dicToFill[iVar] = 0

    if isSignal:
        dicToFill["type"] = 1

    outputName = "%s%s.csv" %(iCat, tail)
    oFile = open(outputName, 'w')

    for iEntry in range(nEntries):
        iTree.GetEntry(iEntry)
        tool.printProcessStatus(iEntry, nEntries, 'looping over file %s' %(iCat), iEntry-1)
        
        for ikey in defaultOrder:
            if ikey == 'type':
                continue
            dicToFill[ikey] = getattr(iTree, ikey)        
        writeToFile(dicToFill, oFile)
コード例 #16
0
def getBothDistribution(sigHist,
                        bkgHist,
                        graph,
                        graph2,
                        diff=0,
                        tauPtCut=40.5):
    nBins = sigHist.GetNbinsX()
    sigTotal = sigHist.Integral(0, nBins + 1, 0, nBins + 1)
    if not (bkgHist == None):
        bkgTotal = bkgHist.Integral(0, nBins + 1, 0, nBins + 1)
        print bkgTotal
    for i in range(1, nBins + 1, 1):
        tool.printProcessStatus(i,
                                nBins + 1,
                                processName='running bothDistribution',
                                iPrevious=i - 1)
        if i + diff < nBins + 1:
            sigValue = sigHist.Integral(i + diff, nBins + 1, i, nBins + 1)
            if not (bkgHist == None):
                bkgValue = bkgHist.Integral(i + diff, nBins + 1, i, nBins + 1)
        else:
            bkgValue = 0.
            sigValue = 0.
        if (sigHist.GetXaxis().GetBinCenter(i) == tauPtCut):
            print sigHist.GetXaxis().GetBinCenter(
                i), 1 - bkgValue / bkgTotal, sigValue / sigTotal
            if not (bkgHist == None):
                graph2.SetPoint(i, 1 - bkgValue / bkgTotal,
                                sigValue / sigTotal)
        if not (bkgHist == None):
            graph.SetPoint(i, 1 - bkgValue / bkgTotal, sigValue / sigTotal)
        else:
            graph.SetPoint(i,
                           sigHist.GetXaxis().GetBinCenter(i),
                           sigValue / sigTotal)

    print ''
    return graph
コード例 #17
0
def calcBDTEff2(signal, background, eff, cutContor):
    sigTotal = signal.Integral()
    bkgTotal = background.Integral()
    nBins = eff.GetNbinsX()
    nEntries = signal.GetNbinsX()
    nEntriesY = signal.GetNbinsY()
    for i in range(nEntries):
        tool.printProcessStatus(i, nEntries, 'Calcuation')
        bkgRejXsigEff = 0
        bkgRejSave = 0
        sigEffSave = 1
        jSave = 0
        for j in range(nEntriesY):
            bkgRej = background.Integral(1,i+1, 1, j+1)/bkgTotal
            sigEff = 1-signal.Integral(1,i+1, 1, j+1)/sigTotal
            if bkgRej*sigEff > bkgRejXsigEff:
                bkgRejSave = bkgRej
                sigEffSave = sigEff
                bkgRejXsigEff = bkgRej*sigEff
                jSave = j
        xBin = findBin(bkgRejSave, nBins, 0, 1)
        eff.SetBinContent(xBin+1, sigEffSave)
        cutContor.SetBinContent(i+1,jSave+1, 10)
    return eff, cutContor
コード例 #18
0
def loop_one_sample(iSample, hist, varName, varBins, FS, initEvents=0):
    file = r.TFile(iSample)
    tree = file.Get('Ntuple')
    weight = 1.0
    nEntries = tree.GetEntries()
    nPass = 0.0
    nEvents_p_n = 0.0

    for iEntry in range(nEntries):
        tree.GetEntry(iEntry)
        tool.printProcessStatus(iEntry, nEntries,
                                'Looping sample %s' % (iSample), iEntry - 1)

        if initEvents == 0:
            initEvents = tree.initEvents

        weight = lumi * tree.xs / (initEvents + 0.0)
        if tree.genEventWeight < 0:
            weight = -weight

        if tree.q_1 == tree.q_2:
            continue
        else:
            nPass += 1.0
            if tree.genEventWeight < 0:
                nEvents_p_n -= 1.0
            else:
                nEvents_p_n += 1.0
        hist.Fill(getattr(tree, varName), weight)

    if nEvents_p_n != 0:
        hist.Scale(nPass / nEvents_p_n)
    else:
        hist.Scale(0)
    print hist.Integral(0, len(varBins) + 1)
    print ''
コード例 #19
0
def makeSyncNtuples(iLocation):

    iTree = r.TChain("TauCheck/eventTree")
    print iLocation
    nEntries = tool.addFiles(ch=iTree, dirName=iLocation, knownEventNumber=0, maxFileNumber=-1, printTotalEvents = True)
    print nEntries
    iTree.SetBranchStatus("*",1)

    oFileName = iLocation[iLocation.rfind("/")+1:iLocation.find("-SUB-TT")]

    oFile = r.TFile("%s.root" %oFileName,"recreate")
    oTree = r.TTree('TauCheck', 'TauCheck')

    run  = array('i', [0])
    lumi = array('i', [0])
    evt = array('i', [0])

    npv = array('i', [0])
    npu = array('i', [0])
    rho = array('f', [0.])

    mvis = array('f', [0.])
    m_sv = array('f', [0.])
    pt_sv = array('f', [0.])
    eta_sv = array('f', [0.])
    phi_sv = array('f', [0.])
    
    pt_1 = array('f', [0.])
    phi_1 = array('f', [0.])
    eta_1 = array('f', [0.])
    m_1 = array('f', [0.])
    q_1 = array('i', [0])
    iso_1 = array('f', [0.])
    mva_1 = array('f', [0.])
    byCombinedIsolationDeltaBetaCorrRaw3Hits_1 = array('f', [0.])
    d0_1 = array('f', [0.])
    dZ_1 = array('f', [0.])
    mt_1 = array('f', [0.])

    pt_2 = array('f', [0.])
    phi_2 = array('f', [0.])
    eta_2 = array('f', [0.])
    m_2 = array('f', [0.])
    q_2 = array('i', [0])
    iso_2 = array('f', [0.])
    mva_2 = array('f', [0.])
    byCombinedIsolationDeltaBetaCorrRaw3Hits_2 = array('f', [0.])
    d0_2 = array('f', [0.])
    dZ_2 = array('f', [0.])
    mt_2 = array('f', [0.])

    againstElectronMVA3raw_1 = array('f', [0.])
    againstElectronMVA3raw_2 = array('f', [0.])
    againstMuonLoose2_1 = array('f', [0.])
    againstMuonLoose2_2 = array('f', [0.])
    againstMuonMedium2_1 = array('f', [0.])
    againstMuonMedium2_2 = array('f', [0.])
    againstMuonTight2_1 = array('f', [0.])
    againstMuonTight2_2 = array('f', [0.])

    met = array('f', [0.])
    mvamet = array('f', [0.])
    mvametphi = array('f', [0.])
    mvacov00 = array('f', [0.])
    mvacov01 = array('f', [0.])
    mvacov10 = array('f', [0.])
    mvacov11 = array('f', [0.])

    pzetavis = array('f', [0.])
    pzetamiss = array('f', [0.])

    pt_tt = array('f', [0.])
    njets = array('i', [0])
    njetspt20 = array('i', [0])

    jpt_1 = array('f', [0.])
    jeta_1 = array('f', [0.])
    jphi_1 = array('f', [0.])
    jptraw_1 = array('f', [0.])
    jptunc_1 = array('f', [0.])
    jmva_1 = array('f', [0.])
    jlrm_1 = array('f', [0.])
    jctm_1 = array('f', [0.])
    jpass_1 = array('b', [0])

    jpt_2 = array('f', [0.])
    jeta_2 = array('f', [0.])
    jphi_2 = array('f', [0.])
    jptraw_2 = array('f', [0.])
    jptunc_2 = array('f', [0.])
    jmva_2 = array('f', [0.])
    jlrm_2 = array('f', [0.])
    jctm_2 = array('f', [0.])
    jpass_2 = array('b', [0])

    bpt_1 = array('f', [0.])
    beta_1 = array('f', [0.])
    bphi_1 = array('f', [0.])
    bcsv_1 = array('f', [0.])

    bpt_2 = array('f', [0.])
    beta_2 = array('f', [0.])
    bphi_2 = array('f', [0.])
    bcsv_2 = array('f', [0.])

    bpt_3 = array('f', [0.])
    beta_3 = array('f', [0.])
    bphi_3 = array('f', [0.])
    bcsv_3 = array('f', [0.])

    m_bb = array('f', [0.])
    m_ttbb = array('f', [0.])
    nbtag = array('i', [0])

    trigweight_1 = array('f', [0.])
    trigweight_2 = array('f', [0.])
    effweight = array('f', [0.])

    oTree.Branch("run", run, "run/I")
    oTree.Branch("lumi", lumi, "lumi/I")
    oTree.Branch("evt", evt, "evt/I")

    oTree.Branch("npv", npv, "npv/I")
    oTree.Branch("npu", npu, "npu/I")
    oTree.Branch("rho", rho, "rho/F")

    oTree.Branch("mvis", mvis, "mvis/F")
    oTree.Branch("m_sv", m_sv, "m_sv/F")
    oTree.Branch("pt_sv", pt_sv, "pt_sv/F")
    oTree.Branch("eta_sv", eta_sv, "eta_sv/F")
    oTree.Branch("phi_sv", phi_sv, "phi_sv/F")

    oTree.Branch("pt_1", pt_1, "pt_1/F")
    oTree.Branch("phi_1", phi_1, "phi_1/F")
    oTree.Branch("eta_1", eta_1, "eta_1/F")
    oTree.Branch("m_1", m_1, "m_1/F")
    oTree.Branch("q_1", q_1, "q_1/I")
    oTree.Branch("iso_1", iso_1, "iso_1/F")
    oTree.Branch("mva_1", mva_1, "mva_1/F")
    oTree.Branch("byCombinedIsolationDeltaBetaCorrRaw3Hits_1", byCombinedIsolationDeltaBetaCorrRaw3Hits_1, "byCombinedIsolationDeltaBetaCorrRaw3Hits_1/F")
    oTree.Branch("d0_1", d0_1, "d0_1/F")
    oTree.Branch("dZ_1", dZ_1, "dZ_1/F")
    oTree.Branch("mt_1", mt_1, "mt_1/F")

    oTree.Branch("pt_2", pt_2, "pt_2/F")
    oTree.Branch("phi_2", phi_2, "phi_2/F")
    oTree.Branch("eta_2", eta_2, "eta_2/F")
    oTree.Branch("m_2", m_2, "m_2/F")
    oTree.Branch("q_2", q_2, "q_2/I")
    oTree.Branch("iso_2", iso_2, "iso_2/F")
    oTree.Branch("mva_2", mva_2, "mva_2/F")
    oTree.Branch("byCombinedIsolationDeltaBetaCorrRaw3Hits_2", byCombinedIsolationDeltaBetaCorrRaw3Hits_2, "byCombinedIsolationDeltaBetaCorrRaw3Hits_2/F")
    oTree.Branch("d0_2", d0_2, "d0_2/F")
    oTree.Branch("dZ_2", dZ_2, "dZ_2/F")
    oTree.Branch("mt_2", mt_2, "mt_2/F")

    oTree.Branch("againstElectronMVA3raw_1", againstElectronMVA3raw_1, "againstElectronMVA3raw_1/F")
    oTree.Branch("againstElectronMVA3raw_2", againstElectronMVA3raw_2, "againstElectronMVA3raw_2/F")
    oTree.Branch("againstMuonLoose2_1", againstMuonLoose2_1, "againstMuonLoose2_1/F")
    oTree.Branch("againstMuonLoose2_2", againstMuonLoose2_2, "againstMuonLoose2_2/F")
    oTree.Branch("againstMuonMedium2_1", againstMuonMedium2_1, "againstMuonMedium2_1/F")
    oTree.Branch("againstMuonMedium2_2", againstMuonMedium2_2, "againstMuonMedium2_2/F")
    oTree.Branch("againstMuonTight2_1", againstMuonTight2_1, "againstMuonTight2_1/F")
    oTree.Branch("againstMuonTight2_2", againstMuonTight2_2, "againstMuonTight2_2/F")

    oTree.Branch("met", met, "met/F")
    oTree.Branch("mvamet", mvamet, "mvamet/F")
    oTree.Branch("mvametphi", mvametphi, "mvametphi/F")
    oTree.Branch("mvacov00", mvacov00, "mvacov00/F")
    oTree.Branch("mvacov01", mvacov01, "mvacov01/F")
    oTree.Branch("mvacov10", mvacov10, "mvacov10/F")
    oTree.Branch("mvacov11", mvacov11, "mvacov11/F")

    oTree.Branch("pzetavis", pzetavis, "pzetavis/F")
    oTree.Branch("pzetamiss", pzetamiss, "pzetamiss/F")

    oTree.Branch("pt_tt", pt_tt, "pt_tt/F")
    oTree.Branch("njets", njets, "njets/I")
    oTree.Branch("njetspt20", njetspt20, "njetspt20/I")
    oTree.Branch("nbtag", nbtag, "nbtag/I")

    oTree.Branch("jpt_1", jpt_1, "jpt_1/F")
    oTree.Branch("jeta_1", jeta_1, "jeta_1/F")
    oTree.Branch("jphi_1", jphi_1, "jphi_1/F")
    oTree.Branch("jptraw_1", jptraw_1, "jptraw_1/F")
    oTree.Branch("jptunc_1", jptunc_1, "jptunc_1/F")
    oTree.Branch("jmva_1", jmva_1, "jmva_1/F")
    oTree.Branch("jctm_1", jctm_1, "jctm_1/F")
    oTree.Branch("jpass_1", jpass_1, "jpass_1/B")    

    oTree.Branch("jpt_2", jpt_2, "jpt_2/F")
    oTree.Branch("jeta_2", jeta_2, "jeta_2/F")
    oTree.Branch("jphi_2", jphi_2, "jphi_2/F")
    oTree.Branch("jptraw_2", jptraw_2, "jptraw_2/F")
    oTree.Branch("jptunc_2", jptunc_2, "jptunc_2/F")
    oTree.Branch("jmva_2", jmva_2, "jmva_2/F")
    oTree.Branch("jctm_2", jctm_2, "jctm_2/F")
    oTree.Branch("jpass_2", jpass_2, "jpass_2/B")    

    oTree.Branch("bpt_1", bpt_1, "bpt_1/F")
    oTree.Branch("beta_1", beta_1, "beta_1/F")
    oTree.Branch("bphi_1", bphi_1, "bphi_1/F")
    oTree.Branch("bcsv_1", bcsv_1, "bcsv_1/F")
    oTree.Branch("bpt_2", bpt_2, "bpt_2/F")
    oTree.Branch("beta_2", beta_2, "beta_2/F")
    oTree.Branch("bphi_2", bphi_2, "bphi_2/F")
    oTree.Branch("bcsv_2", bcsv_2, "bcsv_2/F")
    oTree.Branch("bpt_3", bpt_3, "bpt_3/F")
    oTree.Branch("beta_3", beta_3, "beta_3/F")
    oTree.Branch("bphi_3", bphi_3, "bphi_3/F")
    oTree.Branch("bcsv_3", bcsv_3, "bcsv_3/F")

    oTree.Branch("m_bb", m_bb, "m_bb/F")    
    oTree.Branch("m_ttbb", m_ttbb, "m_ttbb/F")    

    oTree.Branch("trigweight_1", trigweight_1, "trigweight_1/F")    
    oTree.Branch("trigweight_2", trigweight_2, "trigweight_2/F")    
    oTree.Branch("effweight", effweight, "effweight/F")    

    counter = 0
    lvClass = r.Math.LorentzVector(r.Math.PtEtaPhiM4D('double'))
    b1 = lvClass()
    b2 = lvClass()
    tau1 = lvClass()
    tau2 = lvClass()
    for iEntry in range(nEntries):
        iTree.GetEntry(iEntry)
        if iTree.charge1.at(0) == iTree.charge2.at(0):
            continue
        if iTree.eleTauPt1.size()>0:
            print 'eTauPairFound'
            continue
        if iTree.muTauPt1.size()>0:
            print 'muTauPairFound'
            continue
        if iTree.jpass_1 == 0:
#             print 'j1Pass Failed'
            continue
        if iTree.jpass_2 == 0:
#             print 'j2Pass Failed'
            continue
        eff1 = calcTrigOneTauEff(eta=iTree.eta1.at(0), pt=iTree.pt1.at(0), data = False, fitStart=25)
        eff2 = calcTrigOneTauEff(eta=iTree.eta2.at(0), pt=iTree.pt2.at(0), data = False, fitStart=25)
        trigweight_1[0] = eff1
        trigweight_2[0] = eff2        
        effweight[0] = eff1*eff2

        jetsList = [(iTree.J1CSVbtag, iTree.J1Pt, iTree.J1Eta, iTree.J1Phi, iTree.J1Mass),
                    (iTree.J2CSVbtag, iTree.J2Pt, iTree.J2Eta, iTree.J2Phi, iTree.J2Mass),
                    (iTree.J3CSVbtag, iTree.J3Pt, iTree.J3Eta, iTree.J3Phi, iTree.J3Mass),
                    (iTree.J4CSVbtag, iTree.J4Pt, iTree.J4Eta, iTree.J4Phi, iTree.J4Mass)]
        jetsList = sorted(jetsList, key=itemgetter(0), reverse=True)

        tau1.SetCoordinates(iTree.pt1.at(0), iTree.eta1.at(0), iTree.phi1.at(0), iTree.m1.at(0))
        tau2.SetCoordinates(iTree.pt2.at(0), iTree.eta2.at(0), iTree.phi2.at(0), iTree.m2.at(0))

        b1.SetCoordinates(jetsList[0][1], jetsList[0][2], jetsList[0][3], jetsList[0][4])
        b2.SetCoordinates(jetsList[1][1], jetsList[1][2], jetsList[1][3], jetsList[1][4])

        if jetsList[0][1] < 20 or jetsList[1][1] < 20:
            continue
        if abs(jetsList[0][2]) > 2.4 or abs(jetsList[1][2]) > 2.4:
            continue
        if iTree.pt1.at(0)<45 or iTree.pt2.at(0)<45:
            continue
        if iTree.iso1.at(0)>1.0 or iTree.iso2.at(0)>1.0:
            continue

        if jetsList[0][0] < 0.679 or jetsList[1][0] < 0.244:
            continue


        run[0] = iTree.RUN
        evt[0] = iTree.EVENT
        npv[0] = iTree.vertices
        npu[0] = int(iTree.puTruth)
        lumi[0] = iTree.LUMI
        rho[0] = iTree.Rho
        mvis[0] = (tau1+tau2).mass()
        m_sv[0] = iTree.svMass.at(0)
        pt_sv[0] = iTree.svPt.at(0)
        eta_sv[0] = iTree.svEta.at(0)
        phi_sv[0] = iTree.svPhi.at(0)

        pt_1[0] = iTree.pt1.at(0)
        eta_1[0] = iTree.eta1.at(0)
        phi_1[0] = iTree.phi1.at(0)
        m_1[0] = iTree.m1.at(0)
        q_1[0] = int(iTree.charge1.at(0))
        iso_1[0] = iTree.tau1MVAIso
        mva_1[0] = 0
        byCombinedIsolationDeltaBetaCorrRaw3Hits_1[0] = iTree.iso1.at(0)
        d0_1[0] = iTree.d0_1
        dZ_1[0] = iTree.l1dz
        mt_1[0] = iTree.mt1

        pt_2[0] = iTree.pt2.at(0)
        eta_2[0] = iTree.eta2.at(0)
        phi_2[0] = iTree.phi2.at(0)
        m_2[0] = iTree.m2.at(0)
        q_2[0] = int(iTree.charge2.at(0))
        iso_2[0] = iTree.tau2MVAIso
        mva_2[0] = 0
        byCombinedIsolationDeltaBetaCorrRaw3Hits_2[0] = iTree.iso2.at(0)
        d0_2[0] = iTree.d0_2
        dZ_2[0] = iTree.l2dz
        mt_2[0] = iTree.mt2

        againstElectronMVA3raw_1[0] = iTree.againstElectronMVA3raw_1
        againstElectronMVA3raw_2[0] = iTree.againstElectronMVA3raw_2
        againstMuonLoose2_1[0] = iTree.againstMuonLoose1.at(0)
        againstMuonLoose2_2[0] = iTree.againstMuonLoose2.at(0)
        againstMuonMedium2_1[0] = iTree.againstMuonMedium2_1
        againstMuonMedium2_2[0] = iTree.againstMuonMedium2_2
        againstMuonTight2_1[0] = iTree.againstMuonTight2_1
        againstMuonTight2_2[0] = iTree.againstMuonTight2_2

        met[0] = iTree.metUnc
        mvamet[0] = iTree.met.at(0)
        mvametphi[0] = iTree.metOldphi
        mvacov00[0] = iTree.mvacov00
        mvacov01[0] = iTree.mvacov01
        mvacov10[0] = iTree.mvacov10
        mvacov11[0] = iTree.mvacov11
    
        pzetavis[0] = iTree.pZV
        pzetamiss[0] = iTree.pZetaMiss

        pt_tt[0] = iTree.fullPt

        njets[0] = int(iTree.njets)
        njetspt20[0] = int(iTree.njetspt20)
        nbtag[0] = int(iTree.NBTags)

        bcsv_1[0] = jetsList[0][0]
        bpt_1[0] = jetsList[0][1]
        beta_1[0] = jetsList[0][2]
        bphi_1[0] = jetsList[0][3]
        bcsv_2[0] = jetsList[1][0]
        bpt_2[0] = jetsList[1][1]
        beta_2[0] = jetsList[1][2]
        bphi_2[0] = jetsList[1][3]
        bcsv_3[0] = jetsList[2][0]
        bpt_3[0] = jetsList[2][1]
        beta_3[0] = jetsList[2][2]
        bphi_3[0] = jetsList[2][3]

        jpt_1[0] = iTree.J1Pt
        jeta_1[0] = iTree.J1Eta
        jphi_1[0] = iTree.J1Phi
        jptraw_1[0] = iTree.J1PtUncorr
        jptunc_1[0] = iTree.J1JECUnc
        jmva_1[0] = iTree.jmva_1
        jctm_1[0] = iTree.J1Ntot
        jpass_1[0] = bool(iTree.jpass_1) 

        jpt_2[0] = iTree.J2Pt
        jeta_2[0] = iTree.J2Eta
        jphi_2[0] = iTree.J2Phi
        jptraw_2[0] = iTree.J2PtUncorr
        jptunc_2[0] = iTree.J2JECUnc
        jmva_2[0] = iTree.jmva_2
        jctm_2[0] = iTree.J2Ntot
        jpass_2[0] = bool(iTree.jpass_2)

        m_bb[0] = iTree.mJJ
        m_ttbb[0] = iTree.HMass

        oTree.Fill()
        counter += 1
        tool.printProcessStatus(iEntry, nEntries, 'Saving to file ')
    
    print ''
    oFile.cd()
    oTree.Write()
    oFile.Close()
    print 'Saved file: %s.root' %oFileName
コード例 #20
0
def makeWhole(iFileName,
              iLocation,
              weight1,
              weight2,
              sf1,
              sf2,
              sf0,
              additionalFiles=[],
              shift='normal'):
    #get event count in train/test tree
    ifile = r.TFile(iLocation)
    iTrainTree = ifile.Get('TrainTree')
    iTestTree = ifile.Get('TestTree')
    eventCountInTrainTree = getEventsCountInTree(iTrainTree)
    eventCountInTestTree = getEventsCountInTree(iTestTree)

    charVarsDict = setUpCharVarsDict()
    floatVarsDict = setUpFloatVarsDict()
    intVarsDict = setUpIntVarsDict()

    eventYieldDict = []
    eventYieldDict.append({})
    eventYieldDict.append({})
    eventYieldDict.append({})

    initEventsDict = {}
    xsDict = {}

    savedSamples = []

    oFile = r.TFile('combined_%s_%s.root' % (iFileName, shift), 'recreate')
    oTree = r.TTree('eventTree', '')

    #setup branches
    for iVar in charVarsDict.keys():
        oTree.Branch("%s" % iVar, charVarsDict[iVar], "%s[31]/C" % iVar)
    for iVar in floatVarsDict.keys():
        oTree.Branch("%s" % iVar, floatVarsDict[iVar], "%s/F" % iVar)
    for iVar in intVarsDict.keys():
        oTree.Branch("%s" % iVar, intVarsDict[iVar], "%s/I" % iVar)

    #Store additional files
    ifiles = []
    trees = []
    for iName, iFile, save0tagOnly in additionalFiles:
        last = len(ifiles)
        ifiles.append(r.TFile(iFile))
        print iName
        trees.append(ifiles[last].Get('eventTree'))
        total = trees[last].GetEntries()
        for i in range(total):
            trees[last].GetEntry(i)
            tool.printProcessStatus(iCurrent=i + 1,
                                    total=total,
                                    processName='Looping sample [%s]' % iFile)
            rightNBTags = trees[last].NBTags
            if 'embed' not in iName:
                if not makeWholeTools2.passJetTrigger(trees[last]):
                    continue
            if 'data' not in iName:
                if shift == 'bSysUp':
                    rightNBTags = trees[last].NBTagsSysUp
                if shift == 'bSysDown':
                    rightNBTags = trees[last].NBTagsSysDown
                if shift == 'bMisUp':
                    rightNBTags = trees[last].NBTagsMisUp
                if shift == 'bMisDown':
                    rightNBTags = trees[last].NBTagsMisDown
            if isWhichUseLooseForShape(iName):
                if trees[last].category2 == 1:
                    charVarsDict['Category'][:31] = '1M'
                elif trees[last].category2 == 2:
                    charVarsDict['Category'][:31] = '2M'
                else:
                    charVarsDict['Category'][:31] = '0M'
                floatVarsDict['PUWeight'][0] = 1.0
            else:
                if rightNBTags == 1:
                    charVarsDict['Category'][:31] = '1M'
                elif rightNBTags > 1:
                    charVarsDict['Category'][:31] = '2M'
                else:
                    charVarsDict['Category'][:31] = '0M'
            if save0tagOnly and rightNBTags != 0:
                continue
            elif save0tagOnly and rightNBTags == 0:
                charVarsDict['Category'][:31] = '0M'

            charVarsDict['sampleName'][:31] = iName
            if iName == 'useRealName':
                charVarsDict['sampleName'][:31] = tool.nameEnDecoder(
                    int(trees[last].sampleName2), 'decode')
            floatVarsDict['BDT'][0] = trees[last].BDT
            floatVarsDict['PUWeight'][0] = trees[last].PUWeight
            floatVarsDict['mJJ'][0] = trees[last].mJJ
            floatVarsDict['CSVJ2'][0] = trees[last].CSVJ2
            floatVarsDict['fMass'][0] = trees[last].fMass
            floatVarsDict['fMassKinFit'][0] = trees[last].fMassKinFit
            floatVarsDict['chi2KinFit'][0] = trees[last].chi2KinFit
            floatVarsDict['chi2KinFit2'][0] = trees[last].chi2KinFit2
            floatVarsDict['met'][0] = trees[last].met1
            floatVarsDict['iso1'][0] = trees[last].iso1_1
            floatVarsDict['iso2'][0] = trees[last].iso2_1
            floatVarsDict['svMass'][0] = trees[last].svMass1
            floatVarsDict['triggerEff'][0] = trees[last].triggerEff
            floatVarsDict['xs'][0] = trees[last].xs
            floatVarsDict['dRTauTau'][0] = trees[last].dRTauTau
            floatVarsDict['dRJJ'][0] = trees[last].dRJJ
            intVarsDict['NBTags'][0] = int(trees[last].NBTags)
            floatVarsDict['embeddedWeight'][0] = trees[last].embeddedWeight
            floatVarsDict['decayModeWeight'][0] = trees[last].decayModeWeight

            intVarsDict['initEvents'][0] = int(trees[last].initEvents)
            if iName not in eventYieldDict[1].keys():
                eventYieldDict[0][iName] = 0.0
                eventYieldDict[1][iName] = 0.0
                eventYieldDict[2][iName] = 0.0

            if iName == 'ZLL' and trees[last].ZLL == 0:
                continue

            if 'data' in iName:
                eventYieldDict[int(trees[last].category2)][iName] += 1.0
            elif iName == 'DY_embed':
                if trees[last].HLT_Any == 0 or trees[last].ZTT == 0:
                    continue
                eventYieldDict[int(
                    trees[last].category2
                )][iName] += floatVarsDict['triggerEff'][0] * floatVarsDict[
                    'embeddedWeight'][0] * floatVarsDict['decayModeWeight'][0]
            elif iName == 'tt_embed':
                if trees[last].HLT_Any == 0 or trees[last].ZTT == 0:
                    continue
                intVarsDict['initEvents'][0] = int(
                    embedDYYieldCalculator.tt_semi_InitEvents)
                floatVarsDict['xs'][0] = floatVarsDict['xs'][0] * 0.983
                eventYieldDict[int(
                    trees[last].category2
                )][iName] += floatVarsDict['xs'][0] * floatVarsDict[
                    'triggerEff'][0] * floatVarsDict['PUWeight'][
                        0] * floatVarsDict['embeddedWeight'][
                            0] * lumi / embedDYYieldCalculator.tt_semi_InitEvents
            else:
                if intVarsDict['NBTags'][0] > 2:
                    eventYieldDict[2][
                        iName] += floatVarsDict['xs'][0] * floatVarsDict[
                            'triggerEff'][0] * floatVarsDict['PUWeight'][
                                0] * lumi / intVarsDict['initEvents'][0]
                else:
                    eventYieldDict[intVarsDict['NBTags'][0]][
                        iName] += floatVarsDict['xs'][0] * floatVarsDict[
                            'triggerEff'][0] * floatVarsDict['PUWeight'][
                                0] * lumi / intVarsDict['initEvents'][0]

            if iName not in initEventsDict.keys():
                initEventsDict[iName] = trees[last].initEvents
                xsDict[iName] = trees[last].xs
            oTree.Fill()
            if (not save0tagOnly) and (rightNBTags == 0) and (
                    charVarsDict['Category'][:31] != "0M"
            ):  #save twice for events that must used loose for shape
                charVarsDict['Category'][:31] = '0M'
                oTree.Fill()

            if (charVarsDict['sampleName'][:31]
                    not in savedSamples) and (not save0tagOnly):
                savedSamples.append(charVarsDict['sampleName'][:31])
        print ''

    print ''

    totalTest = iTestTree.GetEntries()
    for i in range(totalTest):
        tool.printProcessStatus(iCurrent=i + 1,
                                total=totalTest,
                                processName='Looping sample [%s]' % iFileName)
        iTestTree.GetEntry(i)
        tmpSampleName = tool.nameEnDecoder(int(iTestTree.sampleName2),
                                           'decode')
        charVarsDict['sampleName'][:31] = tmpSampleName

        if ('DY' in tmpSampleName) and ('JetsToLL' in tmpSampleName):
            if iTestTree.ZLL == 0:
                continue
            charVarsDict['sampleName'][:31] = 'ZLL'

        rightNBTags = iTestTree.NBTags
        #Save values
        if isWhichUseLooseForShape(tmpSampleName):
            if iTestTree.category2 == 1:
                charVarsDict['Category'][:31] = '1M'
            elif iTestTree.category2 == 2:
                charVarsDict['Category'][:31] = '2M'
            else:
                charVarsDict['Category'][:31] = 'None'
            floatVarsDict['PUWeight'][0] = 1.0

        else:
            if rightNBTags == 1:
                charVarsDict['Category'][:31] = '1M'
            elif rightNBTags > 1:
                charVarsDict['Category'][:31] = '2M'
            else:
                charVarsDict['Category'][:31] = 'None'
            floatVarsDict['PUWeight'][0] = iTestTree.PUWeight

        floatVarsDict['BDT'][0] = iTestTree.BDT
        floatVarsDict['mJJ'][0] = iTestTree.mJJ
        floatVarsDict['CSVJ2'][0] = iTestTree.CSVJ2
        floatVarsDict['fMass'][0] = iTestTree.fMass
        floatVarsDict['fMassKinFit'][0] = iTestTree.fMassKinFit
        floatVarsDict['chi2KinFit'][0] = iTestTree.chi2KinFit
        floatVarsDict['chi2KinFit2'][0] = iTestTree.chi2KinFit2
        floatVarsDict['met'][0] = iTestTree.met1
        floatVarsDict['iso1'][0] = iTestTree.iso1_1
        floatVarsDict['iso2'][0] = iTestTree.iso2_1
        floatVarsDict['svMass'][0] = iTestTree.svMass1
        floatVarsDict['triggerEff'][0] = iTestTree.triggerEff
        floatVarsDict['xs'][0] = iTestTree.xs
        floatVarsDict['dRTauTau'][0] = iTestTree.dRTauTau
        floatVarsDict['dRJJ'][0] = iTestTree.dRJJ
        intVarsDict['NBTags'][0] = int(iTestTree.NBTags)
        intVarsDict['initEvents'][0] = int(
            (iTestTree.initEvents + 0.0) *
            eventCountInTestTree[tmpSampleName] /
            (eventCountInTestTree[tmpSampleName] +
             eventCountInTrainTree[tmpSampleName]))

        if tmpSampleName not in eventYieldDict[1].keys():
            eventYieldDict[0][tmpSampleName] = 0.0
            eventYieldDict[1][tmpSampleName] = 0.0
            eventYieldDict[2][tmpSampleName] = 0.0

        if 'data' in tmpSampleName:
            eventYieldDict[int(iTestTree.category2)][tmpSampleName] += 1.0
        else:
            if intVarsDict['NBTags'][0] > 2:
                eventYieldDict[2][tmpSampleName] += floatVarsDict['xs'][
                    0] * floatVarsDict['triggerEff'][0] * floatVarsDict[
                        'PUWeight'][0] * lumi / intVarsDict['initEvents'][0]
            else:
                eventYieldDict[intVarsDict['NBTags'][0]][
                    tmpSampleName] += floatVarsDict['xs'][0] * floatVarsDict[
                        'triggerEff'][0] * floatVarsDict['PUWeight'][
                            0] * lumi / intVarsDict['initEvents'][0]

        if tmpSampleName not in initEventsDict.keys():
            initEventsDict[tmpSampleName] = int(
                (iTestTree.initEvents + 0.0) *
                eventCountInTestTree[tmpSampleName] /
                (eventCountInTestTree[tmpSampleName] +
                 eventCountInTrainTree[tmpSampleName]))
            xsDict[tmpSampleName] = iTestTree.xs

        if charVarsDict['sampleName'][:31] in savedSamples:
            continue
        oTree.Fill()

    printYields(eventYieldDict)

    L_to_T_1M = r.TH1F('L_to_T_1M', 'L_to_T_1M', 1, 0, 1)
    L_to_T_2M = r.TH1F('L_to_T_2M', 'L_to_T_2M', 1, 0, 1)
    L_to_T_SF_0M = r.TH1F('L_to_T_SF_0M', 'L_to_T_SF_0M', 1, 0, 1)
    L_to_T_SF_1M = r.TH1F('L_to_T_SF_1M', 'L_to_T_SF_1M', 1, 0, 1)
    L_to_T_SF_2M = r.TH1F('L_to_T_SF_2M', 'L_to_T_SF_2M', 1, 0, 1)
    MC2Embed2Cat_0M = r.TH1F('MC2Embed2Cat_0M', 'MC2Embed2Cat_0M', 1, 0, 1)
    MC2Embed2Cat_1M = r.TH1F('MC2Embed2Cat_1M', 'MC2Embed2Cat_1M', 1, 0, 1)
    MC2Embed2Cat_2M = r.TH1F('MC2Embed2Cat_2M', 'MC2Embed2Cat_2M', 1, 0, 1)
    VV_1M = r.TH1F('VV_1M', 'VV_1M', 1, 0, 1)
    VV_2M = r.TH1F('VV_2M', 'VV_2M', 1, 0, 1)
    singleT_1M = r.TH1F('singleT_1M', 'singleT_1M', 1, 0, 1)
    singleT_2M = r.TH1F('singleT_2M', 'singleT_2M', 1, 0, 1)
    ZLL_1M = r.TH1F('ZLL_1M', 'ZLL_1M', 1, 0, 1)
    ZLL_2M = r.TH1F('ZLL_2M', 'ZLL_2M', 1, 0, 1)

    xsHist = r.TH1F('xs', '', len(xsDict), 0, len(xsDict))
    initEventsHist = r.TH1F('initEvents', '', len(initEventsDict), 0,
                            len(initEventsDict))
    nBtag = ''
    if 'bSys' in shift:
        shiftLocation = 'bSys'
        nBtag = shift
    elif 'bMis' in shift:
        shiftLocation = 'bMis'
        nBtag = shift
    else:
        shiftLocation = shift
    if shift == 'normal' or 'tau' in shift:
        shiftLocation2 = shift
    else:
        shiftLocation2 = 'normal'
    locationStem = '/nfs_scratch/zmao/samples_Iso'
    scaleFactor_1M, scaleFactor_2M, scaleFactor_1M2, scaleFactor_2M2, preScaleFactor = embedDYYieldCalculator.yieldCalculator(
        dy_mc='%s/tauESOn/%s/dy_OSTight.root' % (locationStem, shiftLocation),
        tt_full_mc='%s/tauESOff/%s/tt_all.root' %
        (locationStem, shiftLocation),
        dy_embed='%s/tauESOn/%s/DY_embed.root' %
        (locationStem, shiftLocation2),
        tt_embed='%s/tauESOff/%s/tt_embed_all.root' %
        (locationStem, shiftLocation),
        massWindow=False,
        pairOption='iso',
        nBtag=nBtag)

    VV_SF_1M, VV_SF_2M = embedDYYieldCalculator.l2MYieldCalculator(
        sample='%s/tauESOff/%s/Electroweak.root' %
        (locationStem, shiftLocation),
        massWindow=False,
        nBtag=nBtag)
    singleT_SF_1M, singleT_SF_2M = embedDYYieldCalculator.l2MYieldCalculator(
        sample='%s/tauESOff/%s/singleTop.root' % (locationStem, shiftLocation),
        massWindow=False,
        nBtag=nBtag)
    ZLL_SF_1M, ZLL_SF_2M = embedDYYieldCalculator.l2MYieldCalculator(
        sample='%s/tauESOn/%s/dy_OSTight.root' % (locationStem, shiftLocation),
        massWindow=False,
        nBtag=nBtag,
        ZLL=True)

    L_to_T_1M.Fill(
        0.5,
        weight1 * (eventCountInTestTree['dataOSRelax'] +
                   eventCountInTrainTree['dataOSRelax']) /
        eventCountInTestTree['dataOSRelax'])
    L_to_T_2M.Fill(
        0.5,
        weight2 * (eventCountInTestTree['dataOSRelax'] +
                   eventCountInTrainTree['dataOSRelax']) /
        eventCountInTestTree['dataOSRelax'])
    L_to_T_SF_0M.Fill(0.5, sf0)
    L_to_T_SF_1M.Fill(
        0.5,
        sf1 * (eventCountInTestTree['dataOSRelax'] +
               eventCountInTrainTree['dataOSRelax']) /
        eventCountInTestTree['dataOSRelax'])
    L_to_T_SF_2M.Fill(
        0.5,
        sf2 * (eventCountInTestTree['dataOSRelax'] +
               eventCountInTrainTree['dataOSRelax']) /
        eventCountInTestTree['dataOSRelax'])
    VV_1M.Fill(0.5, VV_SF_1M)
    VV_2M.Fill(0.5, VV_SF_2M)
    singleT_1M.Fill(0.5, singleT_SF_1M)
    singleT_2M.Fill(0.5, singleT_SF_2M)
    ZLL_1M.Fill(0.5, ZLL_SF_1M)
    ZLL_2M.Fill(0.5, ZLL_SF_2M)
    MC2Embed2Cat_0M.Fill(0.5, preScaleFactor)
    MC2Embed2Cat_1M.Fill(0.5, scaleFactor_1M)
    MC2Embed2Cat_2M.Fill(0.5, scaleFactor_2M)
    for iSample in xsDict.keys():
        xsHist.Fill(iSample, xsDict[iSample])
        initEventsHist.Fill(iSample, initEventsDict[iSample])

    oFile.cd()
    L_to_T_1M.Write()
    L_to_T_2M.Write()
    L_to_T_SF_0M.Write()
    L_to_T_SF_1M.Write()
    L_to_T_SF_2M.Write()
    MC2Embed2Cat_0M.Write()
    MC2Embed2Cat_1M.Write()
    MC2Embed2Cat_2M.Write()
    VV_1M.Write()
    VV_2M.Write()
    singleT_1M.Write()
    singleT_2M.Write()
    ZLL_1M.Write()
    ZLL_2M.Write()
    xsHist.Write()
    initEventsHist.Write()

    oTree.SetName('eventTree')
    oTree.Write()
    oFile.Close()

    print 'sampleName\ttrain\ttest'
コード例 #21
0
def checkSyncDev(options):
    location1 = options.location1
    tree1 = options.tree1
    name1 = options.name1
    location2 = options.location2
    tree2 = options.tree2
    name2 = options.name2

    if options.switch:
        location2 = options.location1
        tree2 = options.tree1
        name2 = options.name1
        location1 = options.location2
        tree1 = options.tree2
        name1 = options.name2

    eventNumber = int(options.eventNumber)
    iFile1 = r.TFile(location1)

    iTree1 = iFile1.Get(tree1)
    total1 = iTree1.GetEntries()

    iFile2 = r.TFile(location2)
    iTree2 = iFile2.Get(tree2)
    total2 = iTree2.GetEntries()

    mvaMet1 = r.TH1F('mvaMet1', '',60, 0, 6)
    mvaMet2 = r.TH1F('mvaMet2', '',60, 0, 6)


    varsDict1 = {}
    varsDict2 = {}

    for i in range(total1):
        tool.printProcessStatus(i, total1, 'reading file1', i-1)
        iTree1.GetEntry(i)
        if int(options.nTauPairs):
            varsDict1 = addVars2(iTree1, varsDict1)
        else:
            varsDict1 = addVars(iTree1, varsDict1)
    print ''
    for i in range(total2):
        tool.printProcessStatus(i, total2, 'reading file2', i-1)
        iTree2.GetEntry(i)
        if int(options.nTauPairs):
            varsDict2 = addVars2(iTree2, varsDict2)
        else:
            varsDict2 = addVars(iTree2, varsDict2)
    print ''
    indexNotFound1 = []
    indexFound2 = 0
    matchedEvents = 0
    sameEvents = 0
    differentEvents = 0
    counter = 0
    for iKey in varsDict1.keys():
        tool.printProcessStatus(counter, total1, 'looping through', counter-1)

        if iKey in varsDict2 and iKey[0] == eventNumber:
            diff = (varsDict1[iKey][3]+1.0) - (varsDict2[iKey][3]+1.0)
            printInfo(name1, varsDict1[iKey], name2, varsDict2[iKey])
        elif iKey in varsDict2 and eventNumber == -1:
            matchedEvents += 1
            diff = (varsDict1[iKey][3]+1.0) - (varsDict2[iKey][3]+1.0)
            indexFound2 += 1
            if diff != 0.0 and (options.style == 'diff' or options.style == 'all'):
                printInfo(name1, varsDict1[iKey], name2, varsDict2[iKey])
                differentEvents += 1
            elif diff == 0 and (options.style == 'same' or options.style == 'all'):
                printInfo(name1, varsDict1[iKey], name2, varsDict2[iKey])
                sameEvents += 1

            else:
                indexNotFound1.append(iKey)
        counter += 1
    print ''
    if options.style == 'all' or options.style == 'miss':
        print 'Extra events in %s **********' %name1
        for iKey in indexNotFound1:
            printSingleInfo(name1, varsDict1[iKey])
        print ' '
#         print 'Extra events in %s **********' %options.name2
#         for i_2 in range(total2):
#             if i_2 not in indexFound2:
#                 printSingleInfo(options.name2, varsList2[i_2])

    print '%s %i events' %(name1, total1)
    print '%s %i events' %(name2, total2)
    if options.style == 'diff' and not differentEvents:
        sameEvents = matchedEvents - differentEvents
    if options.style == 'same' and not sameEvents:
        differentEvents = matchedEvents - sameEvents
    if options.style == 'same' or options.style == 'diff':
        print "Out of %i matching events, %s%i\033[0m events with same MVAMet, %s%i\033[0m events with different MVAMet" %(matchedEvents, bcolors.OKGREEN, sameEvents, bcolors.FAIL, differentEvents)
    if options.style == 'miss':
        print "%s has an extra of %i events" %(name1, len(indexNotFound1))
        print "%s has an extra of %i events" %(name2, total2 - indexFound2)
    
    if eventNumber == -1:   
        return 1
    else:
        print "Event %i not found!" %eventNumber
        return 0


    c.Print('%s' %psfile)
    c.Close()
コード例 #22
0
def dynamicBinning(iSample, Range=[46, 400], leg="e"):
    file = r.TFile(iSample)
    tree = file.Get('Ntuple')
    nEntries = tree.GetEntries()
    hist_barrel = r.TH1F("hist_barrel", "", Range[1] - Range[0], Range[0],
                         Range[1])
    hist_middle = r.TH1F("hist_middle", "", Range[1] - Range[0], Range[0],
                         Range[1])
    hist_endcap = r.TH1F("hist_endcap", "", Range[1] - Range[0], Range[0],
                         Range[1])
    for iEntry in range(nEntries):
        tree.GetEntry(iEntry)
        tool.printProcessStatus(iEntry, nEntries,
                                'calculating dynamic binning %s' % (iSample),
                                iEntry - 1)
        if abs(tree.eEta) >= 2.1:
            continue
        if abs(tree.mEta) >= 2.1:
            continue
        if tree.q_1 == tree.q_2:
            continue
        if leg == "e":
            if abs(tree.eEta) >= 1.479:
                hist_endcap.Fill(
                    tree.ePt)  #, cutSampleTools.getPUWeight(tree.nTruePU))
            else:
                hist_barrel.Fill(
                    tree.ePt)  #, cutSampleTools.getPUWeight(tree.nTruePU))
        elif leg == 'mu':
            if abs(tree.mEta) >= 1.24:
                hist_endcap.Fill(tree.mPt)
            elif abs(tree.mEta) >= 0.8:
                hist_middle.Fill(tree.mPt)
            else:
                hist_barrel.Fill(tree.mPt)

    total_barrel = hist_barrel.Integral(1, Range[1] - Range[0])
    total_middle = hist_middle.Integral(1, Range[1] - Range[0])
    total_endcap = hist_endcap.Integral(1, Range[1] - Range[0])

    print total_barrel, total_middle, total_endcap
    mid_barrel = 0
    mid_middle = 0
    mid_endcap = 0
    #find half point
    for i in range(Range[1] - Range[0]):
        if total_barrel * 0.48 <= hist_barrel.Integral(
                1, i + 1) <= total_barrel * 0.52:
            mid_barrel = i + Range[0]
        if total_middle * 0.48 <= hist_middle.Integral(
                1, i + 1) <= total_middle * 0.52:
            mid_middle = i + Range[0]
        if total_endcap * 0.48 <= hist_endcap.Integral(
                1, i + 1) <= total_endcap * 0.52:
            mid_endcap = i + Range[0]
    bins_barrel = array.array('d', [Range[0], mid_barrel, Range[1]])
    bins_middle = array.array('d', [Range[0], mid_middle, Range[1]])
    bins_endcap = array.array('d', [Range[0], mid_endcap, Range[1]])
    print bins_barrel, bins_middle, bins_endcap

    if leg == 'e':
        return bins_barrel, bins_endcap
    else:
        return bins_barrel, bins_middle, bins_endcap
コード例 #23
0
def makeSyncNtuples(iLocation, cut, cutBTag, treepath, usePassJetTrigger, pairOption):

    if '.root' in iLocation:
        iFile = r.TFile(iLocation)
        iTree = iFile.Get(treepath)
        nEntries = iTree.GetEntries()
        oFileName = iLocation[iLocation.rfind("/")+1:iLocation.rfind(".root")]
        oFileName += '_sync'
        oFileName += '%s_%s' %(cut, cutBTag)
        if usePassJetTrigger:
            oFileName += '_jetCut'
    else:
        iTree = r.TChain(treepath)
        nEntries = tool.addFiles(ch=iTree, dirName=iLocation, knownEventNumber=0, maxFileNumber=-1, printTotalEvents = True)
        oFileName = iLocation[iLocation.rfind("/")+1:iLocation.find("-SUB-TT")]

    iTree.SetBranchStatus("*",1)
    print iLocation


    oFile = r.TFile("/nfs_scratch/zmao/samples/sync/%s.root" %oFileName,"recreate")
    oTree = r.TTree('TauCheck', 'TauCheck')

    run  = array('i', [0])
    lumi = array('i', [0])
    evt = array('I', [0])
    nTauPairs  = array('i', [0])

    npv = array('i', [0])
    npu = array('i', [0])
    rho = array('f', [0.])

    mvis = array('f', [0.])
    m_sv = array('f', [0.])
    pt_sv = array('f', [0.])
    eta_sv = array('f', [0.])
    phi_sv = array('f', [0.])
    
    pt_1 = array('f', [0.])
    phi_1 = array('f', [0.])
    eta_1 = array('f', [0.])
    m_1 = array('f', [0.])
    q_1 = array('i', [0])
    iso_1 = array('f', [0.])
    mva_1 = array('f', [0.])
    byCombinedIsolationDeltaBetaCorrRaw3Hits_1 = array('f', [0.])
    d0_1 = array('f', [0.])
    dZ_1 = array('f', [0.])
    mt_1 = array('f', [0.])

    pt_2 = array('f', [0.])
    phi_2 = array('f', [0.])
    eta_2 = array('f', [0.])
    m_2 = array('f', [0.])
    q_2 = array('i', [0])
    iso_2 = array('f', [0.])
    mva_2 = array('f', [0.])
    byCombinedIsolationDeltaBetaCorrRaw3Hits_2 = array('f', [0.])
    d0_2 = array('f', [0.])
    dZ_2 = array('f', [0.])
    mt_2 = array('f', [0.])

    againstElectronMVA3raw_1 = array('f', [0.])
    againstElectronMVA3raw_2 = array('f', [0.])
    againstMuonLoose2_1 = array('f', [0.])
    againstMuonLoose2_2 = array('f', [0.])
    againstMuonMedium2_1 = array('f', [0.])
    againstMuonMedium2_2 = array('f', [0.])
    againstMuonTight2_1 = array('f', [0.])
    againstMuonTight2_2 = array('f', [0.])

    met = array('f', [0.])
    puweight = array('f', [0.])
    mvamet = array('f', [0.])
    mvametphi = array('f', [0.])
    mvacov00 = array('f', [0.])
    mvacov01 = array('f', [0.])
    mvacov10 = array('f', [0.])
    mvacov11 = array('f', [0.])

    pzetavis = array('f', [0.])
    pzetamiss = array('f', [0.])

    pt_tt = array('f', [0.])
    njets = array('i', [0])
    njetspt20 = array('i', [0])

    jpt_1 = array('f', [0.])
    jeta_1 = array('f', [0.])
    jphi_1 = array('f', [0.])
    jptraw_1 = array('f', [0.])
    jptunc_1 = array('f', [0.])
    jmva_1 = array('f', [0.])
    jlrm_1 = array('f', [0.])
    jctm_1 = array('f', [0.])
    jpass_1 = array('b', [0])

    jpt_2 = array('f', [0.])
    jeta_2 = array('f', [0.])
    jphi_2 = array('f', [0.])
    jptraw_2 = array('f', [0.])
    jptunc_2 = array('f', [0.])
    jmva_2 = array('f', [0.])
    jlrm_2 = array('f', [0.])
    jctm_2 = array('f', [0.])
    jpass_2 = array('b', [0])

    bpt_1 = array('f', [0.])
    beta_1 = array('f', [0.])
    bphi_1 = array('f', [0.])
    bcsv_1 = array('f', [0.])

    bpt_2 = array('f', [0.])
    beta_2 = array('f', [0.])
    bphi_2 = array('f', [0.])
    bcsv_2 = array('f', [0.])

    bpt_3 = array('f', [0.])
    beta_3 = array('f', [0.])
    bphi_3 = array('f', [0.])
    bcsv_3 = array('f', [0.])

    decayModeWeight_1 = array('f', [0.])
    decayModeWeight_2 = array('f', [0.])
    embeddedWeight = array('f', [0.])
    m_bb = array('f', [0.])
    m_ttbb = array('f', [0.])
    nbtag = array('i', [0])

    trigweight_1 = array('f', [0.])
    trigweight_2 = array('f', [0.])
    effweight = array('f', [0.])
    DYWeight = array('f', [0.])
    weight = array('f', [0.])


    oTree.Branch("run", run, "run/I")
    oTree.Branch("lumi", lumi, "lumi/I")
    oTree.Branch("evt", evt, "evt/i")
    oTree.Branch("nTauPairs", nTauPairs, "nTauPairs/I")

    oTree.Branch("npv", npv, "npv/I")
    oTree.Branch("npu", npu, "npu/I")
    oTree.Branch("rho", rho, "rho/F")

    oTree.Branch("mvis", mvis, "mvis/F")
    oTree.Branch("m_sv", m_sv, "m_sv/F")
    oTree.Branch("pt_sv", pt_sv, "pt_sv/F")
    oTree.Branch("eta_sv", eta_sv, "eta_sv/F")
    oTree.Branch("phi_sv", phi_sv, "phi_sv/F")

    oTree.Branch("pt_1", pt_1, "pt_1/F")
    oTree.Branch("phi_1", phi_1, "phi_1/F")
    oTree.Branch("eta_1", eta_1, "eta_1/F")
    oTree.Branch("m_1", m_1, "m_1/F")
    oTree.Branch("q_1", q_1, "q_1/I")
    oTree.Branch("iso_1", iso_1, "iso_1/F")
    oTree.Branch("mva_1", mva_1, "mva_1/F")
    oTree.Branch("byCombinedIsolationDeltaBetaCorrRaw3Hits_1", byCombinedIsolationDeltaBetaCorrRaw3Hits_1, "byCombinedIsolationDeltaBetaCorrRaw3Hits_1/F")
    oTree.Branch("d0_1", d0_1, "d0_1/F")
    oTree.Branch("dZ_1", dZ_1, "dZ_1/F")
    oTree.Branch("mt_1", mt_1, "mt_1/F")

    oTree.Branch("pt_2", pt_2, "pt_2/F")
    oTree.Branch("phi_2", phi_2, "phi_2/F")
    oTree.Branch("eta_2", eta_2, "eta_2/F")
    oTree.Branch("m_2", m_2, "m_2/F")
    oTree.Branch("q_2", q_2, "q_2/I")
    oTree.Branch("iso_2", iso_2, "iso_2/F")
    oTree.Branch("mva_2", mva_2, "mva_2/F")
    oTree.Branch("byCombinedIsolationDeltaBetaCorrRaw3Hits_2", byCombinedIsolationDeltaBetaCorrRaw3Hits_2, "byCombinedIsolationDeltaBetaCorrRaw3Hits_2/F")
    oTree.Branch("d0_2", d0_2, "d0_2/F")
    oTree.Branch("dZ_2", dZ_2, "dZ_2/F")
    oTree.Branch("mt_2", mt_2, "mt_2/F")

    oTree.Branch("againstElectronMVA3raw_1", againstElectronMVA3raw_1, "againstElectronMVA3raw_1/F")
    oTree.Branch("againstElectronMVA3raw_2", againstElectronMVA3raw_2, "againstElectronMVA3raw_2/F")
    oTree.Branch("againstMuonLoose2_1", againstMuonLoose2_1, "againstMuonLoose2_1/F")
    oTree.Branch("againstMuonLoose2_2", againstMuonLoose2_2, "againstMuonLoose2_2/F")
    oTree.Branch("againstMuonMedium2_1", againstMuonMedium2_1, "againstMuonMedium2_1/F")
    oTree.Branch("againstMuonMedium2_2", againstMuonMedium2_2, "againstMuonMedium2_2/F")
    oTree.Branch("againstMuonTight2_1", againstMuonTight2_1, "againstMuonTight2_1/F")
    oTree.Branch("againstMuonTight2_2", againstMuonTight2_2, "againstMuonTight2_2/F")

    oTree.Branch("met", met, "met/F")
    oTree.Branch("mvamet", mvamet, "mvamet/F")
    oTree.Branch("mvametphi", mvametphi, "mvametphi/F")
    oTree.Branch("mvacov00", mvacov00, "mvacov00/F")
    oTree.Branch("mvacov01", mvacov01, "mvacov01/F")
    oTree.Branch("mvacov10", mvacov10, "mvacov10/F")
    oTree.Branch("mvacov11", mvacov11, "mvacov11/F")

    oTree.Branch("pzetavis", pzetavis, "pzetavis/F")
    oTree.Branch("pzetamiss", pzetamiss, "pzetamiss/F")

    oTree.Branch("pt_tt", pt_tt, "pt_tt/F")
    oTree.Branch("njets", njets, "njets/I")
    oTree.Branch("njetspt20", njetspt20, "njetspt20/I")
    oTree.Branch("nbtag", nbtag, "nbtag/I")

    oTree.Branch("jpt_1", jpt_1, "jpt_1/F")
    oTree.Branch("jeta_1", jeta_1, "jeta_1/F")
    oTree.Branch("jphi_1", jphi_1, "jphi_1/F")
    oTree.Branch("jptraw_1", jptraw_1, "jptraw_1/F")
    oTree.Branch("jptunc_1", jptunc_1, "jptunc_1/F")
    oTree.Branch("jmva_1", jmva_1, "jmva_1/F")
    oTree.Branch("jctm_1", jctm_1, "jctm_1/F")
    oTree.Branch("jpass_1", jpass_1, "jpass_1/B")    

    oTree.Branch("jpt_2", jpt_2, "jpt_2/F")
    oTree.Branch("jeta_2", jeta_2, "jeta_2/F")
    oTree.Branch("jphi_2", jphi_2, "jphi_2/F")
    oTree.Branch("jptraw_2", jptraw_2, "jptraw_2/F")
    oTree.Branch("jptunc_2", jptunc_2, "jptunc_2/F")
    oTree.Branch("jmva_2", jmva_2, "jmva_2/F")
    oTree.Branch("jctm_2", jctm_2, "jctm_2/F")
    oTree.Branch("jpass_2", jpass_2, "jpass_2/B")    
    oTree.Branch("puweight", puweight, "puweight/F")    

    oTree.Branch("bpt_1", bpt_1, "bpt_1/F")
    oTree.Branch("beta_1", beta_1, "beta_1/F")
    oTree.Branch("bphi_1", bphi_1, "bphi_1/F")
    oTree.Branch("bcsv_1", bcsv_1, "bcsv_1/F")
    oTree.Branch("bpt_2", bpt_2, "bpt_2/F")
    oTree.Branch("beta_2", beta_2, "beta_2/F")
    oTree.Branch("bphi_2", bphi_2, "bphi_2/F")
    oTree.Branch("bcsv_2", bcsv_2, "bcsv_2/F")
    oTree.Branch("bpt_3", bpt_3, "bpt_3/F")
    oTree.Branch("beta_3", beta_3, "beta_3/F")
    oTree.Branch("bphi_3", bphi_3, "bphi_3/F")
    oTree.Branch("bcsv_3", bcsv_3, "bcsv_3/F")
    oTree.Branch("weight", weight, "weight/F")
    oTree.Branch("embeddedWeight", embeddedWeight, "embeddedWeight/F")
    oTree.Branch("DYWeight", DYWeight, "DYWeight/F")


    oTree.Branch("m_bb", m_bb, "m_bb/F")    
    oTree.Branch("m_ttbb", m_ttbb, "m_ttbb/F")    

    oTree.Branch("trigweight_1", trigweight_1, "trigweight_1/F")    
    oTree.Branch("trigweight_2", trigweight_2, "trigweight_2/F")    
    oTree.Branch("effweight", effweight, "effweight/F")    
    oTree.Branch("decayModeWeight_1", decayModeWeight_1, "decayModeWeight_1/F")    
    oTree.Branch("decayModeWeight_2", decayModeWeight_2, "decayModeWeight_2/F")   

    counter = 0
    lvClass = r.Math.LorentzVector(r.Math.PtEtaPhiM4D('double'))
    b1 = lvClass()
    b2 = lvClass()
    tau1 = lvClass()
    tau2 = lvClass()

    eventMask = [(1, 6647,  2656734),(1, 14273, 2853418),(1, 9775, 3906872),(1, 38627, 7722260)]

    
    for iEntry in range(nEntries):
        track = False
        iTree.GetEntry(iEntry)
        tool.printProcessStatus(iEntry, nEntries, 'Saving to file %s.root' % (oFileName))
        iBestPair = makeWholeTools2.findRightPair(iTree, pairOption)

        if (iTree.RUN,iTree.LUMI, iTree.EVENT,) in eventMask:
            print ''
            print 'Event: %i Lumi: %i run: %i' %(iTree.EVENT, iTree.LUMI, iTree.RUN)
            print 'pt1: %.2f pt2: %.2f CSVJ1: %.2f CSVJ2: %.2f b1Pt: %.2f b1Eta: %.2f b2Pt: %.2f b2Eta: %.2f' %(iTree.pt1.at(iBestPair), iTree.pt2.at(iBestPair), iTree.CSVJ1, iTree.CSVJ2, iTree.CSVJ1Pt, iTree.CSVJ1Eta, iTree.CSVJ2Pt, iTree.CSVJ2Eta)
            print 'iso1: %.2f iso2: %.2f charge: %.2f' %(iTree.iso1.at(iBestPair), iTree.iso2.at(iBestPair), iTree.charge1.at(iBestPair) + iTree.charge2.at(iBestPair))
            print 'svMass: %.2f mJJ: %.2f' %(iTree.svMass.at(iBestPair), iTree.mJJ)
            print 'mvaMet: %.2f' %(iTree.met.at(iBestPair))
            print 'met: %.2f' %(iTree.metUnc)
            print 'fMass: %.2f' %(iTree.fMassKinFit)
            print 'sampleName: %s' %iTree.sampleName

            track = True
        if iTree.HLT_Any == 0:
            continue
        if not makeWholeTools2.passCut(iTree, pairOption):
            continue
        if (iTree.nElectrons > 0 or iTree.nMuons > 0):
            continue
        signSelection, isoSelection, bTagSelection = makeWholeTools2.findCategory(tree = iTree,
                                                                                  iso = 1.0, 
                                                                                  option = pairOption, 
                                                                                  isData = True,
                                                                                  relaxedRegionOption = 'one1To4',
                                                                                  isEmbed = True, 
                                                                                  usePassJetTrigger = usePassJetTrigger)
        if signSelection == None  or isoSelection == None or bTagSelection == None:
            continue
        tmpSelect = signSelection+isoSelection
        if tmpSelect != cut:
            continue
        if not (cutBTag in bTagSelection) and (cutBTag != 'inclusive'):
            continue 
        if iTree.ZTT == 0:
            continue

        trigweight_1[0] = iTree.triggerEff1
        trigweight_2[0] = iTree.triggerEff2

        effweight[0] = trigweight_1[0] * trigweight_2[0]
        nTauPairs[0] = len(iTree.pt1)
    
        run[0] = iTree.RUN
        evt[0] = iTree.EVENT
        npv[0] = iTree.vertices
        npu[0] = int(iTree.puTruth)
        lumi[0] = iTree.LUMI
        rho[0] = iTree.Rho
        mvis[0] = (tau1+tau2).mass()
        m_sv[0] = iTree.svMass.at(iBestPair)
        pt_sv[0] = iTree.svPt.at(iBestPair)
        eta_sv[0] = iTree.svEta.at(iBestPair)
        phi_sv[0] = iTree.svPhi.at(iBestPair)

        pt_1[0] = iTree.pt1.at(iBestPair)
        eta_1[0] = iTree.eta1.at(iBestPair)
        phi_1[0] = iTree.phi1.at(iBestPair)
        m_1[0] = iTree.m1.at(iBestPair)
        q_1[0] = int(iTree.charge1.at(iBestPair))
        iso_1[0] = iTree.tau1MVAIso
        mva_1[0] = 0
        byCombinedIsolationDeltaBetaCorrRaw3Hits_1[0] = iTree.iso1.at(iBestPair)
        d0_1[0] = iTree.d0_1
        dZ_1[0] = iTree.l1dz
#         mt_1[0] = iTree.mt1

        pt_2[0] = iTree.pt2.at(iBestPair)
        eta_2[0] = iTree.eta2.at(iBestPair)
        phi_2[0] = iTree.phi2.at(iBestPair)
        m_2[0] = iTree.m2.at(iBestPair)
        q_2[0] = int(iTree.charge2.at(iBestPair))
        iso_2[0] = iTree.tau2MVAIso
        mva_2[0] = 0
        byCombinedIsolationDeltaBetaCorrRaw3Hits_2[0] = iTree.iso2.at(iBestPair)
        d0_2[0] = iTree.d0_2
        dZ_2[0] = iTree.l2dz
#         mt_2[0] = iTree.mt2

        againstElectronMVA3raw_1[0] = iTree.againstElectronMVA3raw_1
        againstElectronMVA3raw_2[0] = iTree.againstElectronMVA3raw_2
        againstMuonLoose2_1[0] = iTree.againstMuonLoose1.at(iBestPair)
        againstMuonLoose2_2[0] = iTree.againstMuonLoose2.at(iBestPair)
        againstMuonMedium2_1[0] = iTree.againstMuonMedium2_1
        againstMuonMedium2_2[0] = iTree.againstMuonMedium2_2
        againstMuonTight2_1[0] = iTree.againstMuonTight2_1
        againstMuonTight2_2[0] = iTree.againstMuonTight2_2

        met[0] = iTree.metUnc
        mvamet[0] = iTree.met.at(iBestPair)
#         mvametphi[0] = iTree.metphi.at(iBestPair)
        mvacov00[0] = iTree.mvacov00
        mvacov01[0] = iTree.mvacov01
        mvacov10[0] = iTree.mvacov10
        mvacov11[0] = iTree.mvacov11
    
        pzetavis[0] = iTree.pZV
        pzetamiss[0] = iTree.pZetaMiss

#         pt_tt[0] = iTree.fullPt

        njets[0] = int(iTree.njets)
        njetspt20[0] = int(iTree.njetspt20)
        nbtag[0] = int(iTree.NBTags)

        bcsv_1[0] = iTree.CSVJ1
        bpt_1[0] = iTree.CSVJ1Pt
        beta_1[0] = iTree.CSVJ1Eta
        bphi_1[0] = iTree.CSVJ1Phi
        bcsv_2[0] = iTree.CSVJ2
        bpt_2[0] = iTree.CSVJ2Pt
        beta_2[0] = iTree.CSVJ2Eta
        bphi_2[0] = iTree.CSVJ2Phi

        jpt_1[0] = iTree.J1Pt
        jeta_1[0] = iTree.J1Eta
        jphi_1[0] = iTree.J1Phi
        jptraw_1[0] = iTree.J1PtUncorr
        jptunc_1[0] = iTree.J1JECUnc
        jmva_1[0] = iTree.jmva_1
        jctm_1[0] = iTree.J1Ntot
        jpass_1[0] = bool(iTree.jpass_1) 

        jpt_2[0] = iTree.J2Pt
        jeta_2[0] = iTree.J2Eta
        jphi_2[0] = iTree.J2Phi
        jptraw_2[0] = iTree.J2PtUncorr
        jptunc_2[0] = iTree.J2JECUnc
        jmva_2[0] = iTree.jmva_2
        jctm_2[0] = iTree.J2Ntot
        jpass_2[0] = bool(iTree.jpass_2)
#         embeddedWeight[0] = iTree.embeddedWeight
#         weight[0] = effweight[0]*iTree.decayModeWeight*iTree.embeddedWeight
        weight[0] = effweight[0]*iTree.decayModeWeight*iTree.PUWeight
        puweight[0] = iTree.PUWeight
        m_bb[0] = iTree.mJJ
#         m_ttbb[0] = iTree.HMass

#         decayModeWeight_1[0] = iTree.decayModeWeight1
#         decayModeWeight_2[0] = iTree.decayModeWeight2
#         DYWeight[0] = iTree.xs/3504000.0

        oTree.Fill()
        if track:
            print 'saved'
        counter += 1
        tool.printProcessStatus(iEntry, nEntries, 'Saving to file ')
    
    print ''
    print '%i events saved' %counter
    oFile.cd()
    oTree.Write()
    oFile.Close()
    print 'Saved file: %s.root' %oFileName
コード例 #24
0
def draw(varName, bins0, bins1, bins2, unit, yMax0, yMax1, yMax2, option, iso, predictLocation, mass, massWindowCut, drawWhichDY, Lumi = 19.7):
    predictFile = r.TFile(predictLocation)    
    predictTree = predictFile.Get('eventTree')

    predictTotal = predictTree.GetEntries()
    signalName = ''
    histDict0M, histDict1M, histDict2M = buildHistDicts(bins0, bins1, bins2)
    histDict0M_plot, histDict1M_plot, histDict2M_plot = buildHistDicts(bins0, bins1, bins2, '_plot')
    observed0M = buildObserved('observed0M', bins0)
    observed1M = buildObserved('observed1M', bins1)
    observed2M = buildObserved('observed2M', bins2)
    observed0M_plot = buildObserved('observed0M_plot', bins0)
    observed1M_plot = buildObserved('observed1M_plot', bins1)
    observed2M_plot = buildObserved('observed2M_plot', bins2)

    for iEvent in range(predictTotal):
        tool.printProcessStatus(iEvent, predictTotal, 'Looping file [%s]' % (predictLocation))
        predictTree.GetEntry(iEvent)
        if massWindowCut and (not passCutWindow(predictTree)):
            continue
        sampleCat = findBKGCategory(predictTree.sampleName, mass)
        fillValue = varFromName(predictTree, varName)
        if predictTree.Category == '0M':
            #hack
            if fillValue >= bins0[len(bins0)-1]:
                fillValue = (bins0[len(bins0)-1] + bins0[len(bins0)-2])/2
        elif predictTree.Category == '1M':
            #hack
            if fillValue >= bins1[len(bins1)-1]:
                fillValue = (bins1[len(bins1)-1] + bins1[len(bins1)-2])/2
        elif predictTree.Category == '2M':
            #hack
            if fillValue >= bins2[len(bins2)-1]:
                fillValue = (bins2[len(bins2)-1] + bins2[len(bins2)-2])/2

        if sampleCat == 'Observed':
            if dontUnblind(predictTree, varName, bins2):
                continue
            if predictTree.Category == '0M':
                observed0M.Fill(fillValue)
                observed0M_plot.Fill(fillValue)

            if predictTree.Category == '1M':
                observed1M.Fill(fillValue)
                observed1M_plot.Fill(fillValue)

            elif predictTree.Category == '2M':
                observed2M.Fill(fillValue)
                observed2M_plot.Fill(fillValue)
            continue

        if sampleCat == None:
            continue
        if sampleCat == 'QCD' and ('OSRelax' in predictTree.sampleName):
            weight1 = 1.0
            weight2 = 1.0
        elif sampleCat == 'DY_embed':
            weight1 = predictTree.triggerEff*predictTree.decayModeWeight*predictTree.embeddedWeight
            weight2 = weight1
        elif sampleCat == 'tt_embed':
            xs = predictTree.xs
            weight1 = (xs/predictTree.initEvents)*predictTree.triggerEff*Lumi*predictTree.embeddedWeight*predictTree.PUWeight
            weight2 = weight1
        else:
            xs = predictTree.xs
            weight1 = (xs/predictTree.initEvents)*predictTree.triggerEff*predictTree.PUWeight*Lumi
            if sampleCat == 'signal':
                signalName = predictTree.sampleName
                weight1 = (xs/predictTree.initEvents)*predictTree.triggerEff*predictTree.PUWeight*Lumi*predictTree.decayModeWeight
            weight2 = weight1

        if predictTree.Category == '0M':
            histDict0M[sampleCat].Fill(fillValue, weight1)
            histDict0M_plot[sampleCat].Fill(fillValue, weight1)
            if (sampleCat == 't#bar{t}') and (predictTree.sampleName != 'tt'):
                histDict0M['t#bar{t}-ttLep'].Fill(fillValue, weight1)
                histDict0M_plot['t#bar{t}-ttLep'].Fill(fillValue, weight1) 
        elif predictTree.Category == '1M':
            histDict1M[sampleCat].Fill(fillValue, weight1)
            histDict1M_plot[sampleCat].Fill(fillValue, weight1)
            if (sampleCat == 't#bar{t}') and (predictTree.sampleName != 'tt'):
                histDict1M['t#bar{t}-ttLep'].Fill(fillValue, weight1)
                histDict1M_plot['t#bar{t}-ttLep'].Fill(fillValue, weight1)
        elif predictTree.Category == '2M':
            histDict2M[sampleCat].Fill(fillValue, weight2)
            histDict2M_plot[sampleCat].Fill(fillValue, weight2)
            if (sampleCat == 't#bar{t}') and (predictTree.sampleName != 'tt'):
                histDict2M['t#bar{t}-ttLep'].Fill(fillValue, weight2)
                histDict2M_plot['t#bar{t}-ttLep'].Fill(fillValue, weight2)
        if draw_cfg.method == 'method1' and sampleCat == 'DY_embed':
            if predictTree.NBTags > 1:
                histDict2M['DY+ttLep'].Fill(fillValue, weight2/0.9)
                histDict2M_plot['DY+ttLep'].Fill(fillValue, weight2/0.9)
            if predictTree.NBTags == 1:
                histDict1M['DY+ttLep'].Fill(fillValue, weight1/0.9)
                histDict1M_plot['DY+ttLep'].Fill(fillValue, weight1/0.9)

    #Set DY + tt_lep    
    if draw_cfg.method != 'method1' and 'method' in draw_cfg.method:
        dyWithTT1M_scale = predictFile.Get('DYwithTTScale_1M')
        dyWithTT2M_scale = predictFile.Get('DYwithTTScale_2M')
        dyWithTT1M = dyWithTT1M_scale.GetBinContent(1)
        dyWithTT2M = dyWithTT2M_scale.GetBinContent(1)
        histDict1M['DY+ttLep'].Add(histDict1M['DY_embed'], dyWithTT1M/histDict1M['DY_embed'].Integral(0, len(bins1)))
        histDict1M_plot['DY+ttLep'].Add(histDict1M_plot['DY_embed'], dyWithTT1M/histDict1M_plot['DY_embed'].Integral(0, len(bins1)))
        histDict2M['DY+ttLep'].Add(histDict2M['DY_embed'], dyWithTT2M/histDict2M['DY_embed'].Integral(0, len(bins2)))
        histDict2M_plot['DY+ttLep'].Add(histDict2M_plot['DY_embed'], dyWithTT2M/histDict2M_plot['DY_embed'].Integral(0, len(bins2)))

    #Set DY
    dy0M_scale = predictFile.Get('MC2Embed2Cat_0M')
    dy1M_scale = predictFile.Get('MC2Embed2Cat_1M')
    dy2M_scale = predictFile.Get('MC2Embed2Cat_2M')
    dyScale0M = dy0M_scale.GetBinContent(1)
    dyScale1M = dy1M_scale.GetBinContent(1)
    dyScale2M = dy2M_scale.GetBinContent(1)

    histDict0M_plot = setDY(histDict0M_plot, dyScale0M, True)
    histDict1M_plot = setDY(histDict1M_plot, dyScale1M)
    histDict2M_plot = setDY(histDict2M_plot, dyScale2M)
    histDict0M = setDY(histDict0M, dyScale0M, True)
    histDict1M = setDY(histDict1M, dyScale1M)
    histDict2M = setDY(histDict2M, dyScale2M)

    #Set QCD
    predictSF0MHist = predictFile.Get('L_to_T_SF_0M')

    predictSF1MHist_weight = predictFile.Get('L_to_T_1M')
    predictSF1MHist = predictFile.Get('L_to_T_SF_1M')

    predictSF2MHist_weight = predictFile.Get('L_to_T_2M')
    predictSF2MHist = predictFile.Get('L_to_T_SF_2M')

    SF_0M = predictSF0MHist.GetBinContent(1)
    SF_1M = predictSF1MHist.GetBinContent(1)
    SF_2M = predictSF2MHist.GetBinContent(1)
    weight_1M = predictSF1MHist_weight.GetBinContent(1)
    weight_2M = predictSF2MHist_weight.GetBinContent(1)

    #Set VV
    electroweakWeightHist1M = predictFile.Get('VV_1M')
    electroweakWeightHist2M = predictFile.Get('VV_2M')
    eScale1M = electroweakWeightHist1M.GetBinContent(1)
    eScale2M = electroweakWeightHist2M.GetBinContent(1)

    singleTWeightHist1M = predictFile.Get('singleT_1M')
    singleTWeightHist2M = predictFile.Get('singleT_2M')
    sScale1M = singleTWeightHist1M.GetBinContent(1)
    sScale2M = singleTWeightHist2M.GetBinContent(1)
    tmpElectroIntegral = histDict1M_plot['Electroweak'].Integral(0, len(bins1))    
    tmpSingleTIntegral = histDict1M_plot['singleT'].Integral(0, len(bins1))
    histDict1M_plot['Electroweak'].Scale(eScale1M/tmpElectroIntegral)
    histDict1M['Electroweak'].Scale(eScale1M/tmpElectroIntegral)
    histDict1M_plot['singleT'].Scale(sScale1M/tmpSingleTIntegral)
    histDict1M['singleT'].Scale(sScale1M/tmpSingleTIntegral)
    tmpElectroIntegral = histDict2M_plot['Electroweak'].Integral(0, len(bins2))
    tmpSingleTIntegral = histDict2M_plot['singleT'].Integral(0, len(bins2))
    histDict2M_plot['Electroweak'].Scale(eScale2M/tmpElectroIntegral)
    histDict2M_plot['singleT'].Scale(sScale2M/tmpSingleTIntegral)
    histDict2M['Electroweak'].Scale(eScale2M/tmpElectroIntegral)
    histDict2M['singleT'].Scale(sScale2M/tmpSingleTIntegral)
    histDict0M['VV'].Add(histDict0M['Electroweak'], histDict0M['singleT'])
    histDict1M['VV'].Add(histDict1M['Electroweak'], histDict1M['singleT'])
    histDict2M['VV'].Add(histDict2M['Electroweak'], histDict2M['singleT'])
    histDict0M_plot['VV'].Add(histDict0M_plot['Electroweak'], histDict0M_plot['singleT'])
    histDict1M_plot['VV'].Add(histDict1M_plot['Electroweak'], histDict1M_plot['singleT'])
    histDict2M_plot['VV'].Add(histDict2M_plot['Electroweak'], histDict2M_plot['singleT'])

    #Set ZLL
    ZLLWeightHist1M = predictFile.Get('ZLL_1M')
    ZLLWeightHist2M = predictFile.Get('ZLL_2M')
    ZLLScale1M = ZLLWeightHist1M.GetBinContent(1)
    ZLLScale2M = ZLLWeightHist2M.GetBinContent(1)
    tmpIntegral = histDict1M_plot['ZLL'].Integral(0, len(bins1))
    histDict1M_plot['ZLL'].Scale(ZLLScale1M/tmpIntegral)
    histDict1M['ZLL'].Scale(ZLLScale1M/tmpIntegral)
    tmpIntegral = histDict2M_plot['ZLL'].Integral(0, len(bins2))
    histDict2M_plot['ZLL'].Scale(ZLLScale2M/tmpIntegral)
    histDict2M['ZLL'].Scale(ZLLScale2M/tmpIntegral)


    print histDict1M['QCD'].Integral(0, len(bins1))
    print ''
    print SF_1M, SF_2M
    print weight_1M, weight_2M
    print (histDict1M['QCD'].Integral(0, len(bins1))-histDict1M['MCOSRelax'].Integral(0, len(bins1)))*SF_1M, (histDict2M['QCD'].Integral(0, len(bins2))-histDict2M['MCOSRelax'].Integral(0, len(bins2)))*SF_2M
    print histDict1M['QCD'].Integral(0, len(bins1))*weight_1M, histDict2M['QCD'].Integral(0, len(bins2))*weight_2M
    print '0M: ', histDict0M['QCD'].Integral(0, len(bins0)), histDict0M['MCOSRelax'].Integral(0, len(bins0))
    print '1M: ', histDict1M['QCD'].Integral(0, len(bins1)), histDict1M['MCOSRelax'].Integral(0, len(bins1))
    print '2M: ', histDict2M['QCD'].Integral(0, len(bins2)), histDict2M['MCOSRelax'].Integral(0, len(bins2))

    histDict0M['QCD'].Add(histDict0M['MCOSRelax'],-1.0)
    histDict0M['QCD'].Scale(SF_0M)
    histDict0M_plot['QCD'].Add(histDict0M_plot['MCOSRelax'],-1.0)
    histDict0M_plot['QCD'].Scale(SF_0M)

    histDict1M['QCD'].Add(histDict1M['MCOSRelax'],-1.0)
    histDict1M['QCD'].Scale(SF_1M)
    histDict2M['QCD'].Add(histDict2M['MCOSRelax'],-1.0)
    histDict2M['QCD'].Scale(SF_2M)

    histDict1M_plot['QCD'].Add(histDict1M_plot['MCOSRelax'],-1.0)
    histDict1M_plot['QCD'].Scale(SF_1M)
    histDict2M_plot['QCD'].Add(histDict2M_plot['MCOSRelax'],-1.0)
    histDict2M_plot['QCD'].Scale(SF_2M)

#     histDict1M['QCD'].Scale(weight_1M)
#     histDict2M['QCD'].Scale(weight_2M)
#     histDict1M_plot['QCD'].Scale(weight_1M)
#     histDict2M_plot['QCD'].Scale(weight_2M)

    bkgStack0M = buildStackFromDict(histDict0M_plot, '0M', unit, option, drawWhichDY, '0M')
    bkgStack1M = buildStackFromDict(histDict1M_plot, '1M', unit, option, drawWhichDY)
    bkgStack2M = buildStackFromDict(histDict2M_plot, '2M', unit, option, drawWhichDY)
    
    print ''
    position = (0.6, 0.9 - 0.06*6, 0.87, 0.9)

    if draw_cfg.addIntegrals:
        position = (0.47, 0.9 - 0.06*6, 0.87, 0.9)

    legend0M = setLegend(position, histDict0M, observed0M, bins0, signalName, drawWhichDY, '0M')
    legend1M = setLegend(position, histDict1M, observed1M, bins1, signalName, drawWhichDY)
    legend2M = setLegend(position, histDict2M, observed2M, bins2, signalName, drawWhichDY)

    psfile = '%s_%s_%s_%s.pdf' %(varName, mass, drawWhichDY, draw_cfg.method)
    c = r.TCanvas("c","Test", 600, 800)

    p0 = r.TPad("p0","p0",0.,1,1.,0.4)
    p0_r = r.TPad("p0_r","p0_r",0.,0.39,1.,0.06)
    p0.SetMargin(1, 1, 0, 1)
    p0_r.SetMargin(1, 1, 0.2, 1)
    p0.Draw()
    p0_r.Draw()
    p0.cd()
    r.gPad.SetTicky()
    bkgStack0M.SetMaximum(yMax0)
    bkgStack0M.Draw()
    observed0M_plot.Sumw2()
    observed0M_plot.Scale(1, option)
    observed0M_plot.Draw('PE same')
    legend0M.Draw('same')
    histDict0M_plot['signal'].Scale(1, option)
    histDict0M_plot['signal'].Draw('same')
    p0_r.cd()
    r.gPad.SetTicky()
    r.gPad.SetTickx()
    p0_r.SetGridy(1)
    delta0M = buildDelta('delta0M', histDict0M, observed0M, bins0, varName, unit, drawWhichDY)
    delta0M.Draw()
    c.Update()
    c.Print('%s(' %psfile)
    c.Clear()

    p1 = r.TPad("p1","p1",0.,1,1.,0.4)
    p1_r = r.TPad("p1_r","p1_r",0.,0.39,1.,0.06)
    p1.SetMargin(1, 1, 0, 1)
    p1_r.SetMargin(1, 1, 0.2, 1)
    p1.Draw()
    p1_r.Draw()
    p1.cd()
    r.gPad.SetTicky()
    bkgStack1M.SetMaximum(yMax1)
    bkgStack1M.Draw()
    observed1M_plot.Sumw2()
    observed1M_plot.Scale(1, option)
    observed1M_plot.Draw('PE same')
    legend1M.Draw('same')
    histDict1M_plot['signal'].Scale(1, option)
    histDict1M_plot['signal'].Draw('same')
    p1_r.cd()
    r.gPad.SetTicky()
    r.gPad.SetTickx()
    p1_r.SetGridy(1)
    delta1M = buildDelta('delta1M', histDict1M, observed1M, bins1, varName, unit, drawWhichDY)
    delta1M.Draw()
    c.Update()
    c.Print('%s' %psfile)
    c.Clear()
    p2 = r.TPad("p2","p2",0.,1,1.,0.4)
    p2_r = r.TPad("p2_r","p2_r",0.,0.39,1.,0.06)
    p2.SetMargin(1, 1, 0, 1)
    p2_r.SetMargin(1, 1, 0.2, 0.1)
    p2.Draw()
    p2_r.Draw()
    p2.cd()
    r.gPad.SetTicky()
    bkgStack2M.SetMaximum(yMax2)
    bkgStack2M.Draw()
    observed2M_plot.Sumw2()
    observed2M_plot.Scale(1, option)
    observed2M_plot.Draw('PE same')
    legend2M.Draw('same')
    histDict2M_plot['signal'].Scale(1, option)
    histDict2M_plot['signal'].Draw('same')
    p2_r.cd()
    r.gPad.SetTicky()
    r.gPad.SetTickx()
    p2_r.SetGridy(1)
    delta2M = buildDelta('delta2M', histDict2M, observed2M, bins2, varName, unit, drawWhichDY)
    delta2M.Draw()    
    c.Print('%s)' %psfile)
    print "Plot saved at %s" %(psfile)
    c.Close()
    print sampleNameList
    print 'data in 0M %i' %observed0M.Integral(0, len(bins0))
    print 'data in 1M %i' %observed1M.Integral(0, len(bins1))
    print 'data in 2M %i' %observed2M.Integral(0, len(bins2))
コード例 #25
0
def loop_one_sample(iSample, iCategory, histDict, varName, varBins, FS, scanPoints):
    if options.antiIso:
        iSample += "%s_antiIso.root" %FS
    elif options.antiEIso:
        iSample += "%s_antiEIso.root" %FS
    elif options.antiMIso:
        iSample += "%s_antiMIso.root" %FS
    elif options.noIso:
        iSample += "%s_noIso.root" %FS
    elif options.BSM3G:
        iSample += "%s_noIso.root" %FS 
    else:
        iSample += "%s_inclusive.root" %FS 
    file = r.TFile(iSample)    
    tree = file.Get('Ntuple')
    eventCount = file.Get('eventCount')
    eventCountWeighted = file.Get('eventCountWeighted')

    sumPtWeights = -1
    if "TT" in iSample and options.sys == 'topPt':
        sumPtWeights = file.Get('eventCountPtWeighted').GetBinContent(1)

    nEntries = tree.GetEntries()
#     if nEntries > 100:
#         nEntries = 100
    
    tmpHist = r.TH1F("tmp_%s_%s" %(iCategory, varName), '', len(varBins)-1, varBins)
    tmpHist.Sumw2()
    tmpHist_forROOTFile = r.TH1F("%s" %(varName), '', len(varBins)-1, varBins)
    tmpHist_forROOTFile.Sumw2()
    isData = False
    isSignal = False

    if eventCount:
        initEvents = eventCount.GetBinContent(1)
    else:    
        initEvents = tree.initEvents
    if eventCountWeighted:
        sumWeights = eventCountWeighted.GetBinContent(1)
    else:    
        sumWeights = tree.initWeightedEvents

    if iCategory == 'Observed':
        isData = True
    for iEntry in range(nEntries):
        tree.GetEntry(iEntry)
        tool.printProcessStatus(iEntry, nEntries, 'Looping sample %s' %(iSample), iEntry-1)
        weight = 1.0
        QCD_weight = 1.0

        if not passCut(tree, FS, isData, options.sys):
            continue
        if not isData:
            xs  = tree.xs
            if (80.94 < xs < 80.96) or (136.01 < xs < 136.03):
                xs = xs*0.108*3
            if options.sys == 'topPt' and sumPtWeights != -1.0:
                sumWeights = sumPtWeights
                weight = Lumi*xs*tree.genEventWeight*tree.trigweight_1*tree.trigweight_2*tree.topPtWeight/(sumWeights+0.0)
            else:
                weight = Lumi*xs*tree.genEventWeight*tree.trigweight_1*tree.trigweight_2/(sumWeights+0.0)
            if options.PUWeight:
                weight = weight*cutSampleTools.getPUWeight(tree.nTruePU)

        if 'WJets' in iSample:
            weight = 1.0*weight
        if 'ZPrime' in iSample:
            weight = getZPrimeXS(iSample[iSample.rfind("/")+8:iSample.rfind("_all")])*weight
            isSignal =  True
        if varName == 'm_withMET':
            value = tree.m_eff
        elif varName == 'mVis':
            value = tree.m_vis
        elif varName == 'pZeta - 3.1pZetaVis':
            value = tree.ZetaCut
        elif varName == "nCSVL":
            value = tree.nCSVL
        elif varName == "cos_phi_tau1_tau2":
            value = math.cos(tree.phi_1 - tree.phi_2)
        elif varName == "j1Pt":
            jets = getJets(tree)
            if len(jets)>0:
                value = jets[0].pt()
            else:
                value = -1
        elif varName == 'm_gen':
            if tree.eGenTauMass < 0  or tree.tGenMass < 0:
                continue
            l1.SetCoordinates(tree.eGenTauPt, tree.eGenTauEta, tree.eGenTauPhi, tree.eGenTauMass)
            l2.SetCoordinates(tree.tGenPt, tree.tGenEta, tree.tGenPhi, tree.tGenMass)
            value = (l1 + l2).mass()
        else:
            if hasattr(tree, varName):
                value = getattr(tree, varName)
            else:
                value = -1

        if options.overFlow:
            if value > varBins[len(varBins)-1]:
                value = (varBins[len(varBins)-1]+varBins[len(varBins)-2]+0.0)/2.0

        if regionSelection(tree, FS, "OSsignal", plots_cfg.scanRange[0], plots_cfg.scanRange[1]):
            fill = True
            if isData:
                fill = False
                if options.unblind or (options.unblindPartial and passUnblindPartial(varName, value)):
                    fill = True
                    histDict['WJets_OSsignal'].Fill(value, weight)  

            if fill:
                tmpHist.Fill(value, weight)
                tmpHist_forROOTFile.Fill(value, weight)
                if iCategory != 'WJets' and (not isData) and (not isSignal):
                    histDict['WJets_OSsignal'].Fill(value, -weight)
        else:
            if isSignal:
                continue
            #region B
            if regionSelection(tree, FS, "SSsignal", plots_cfg.scanRange[0], plots_cfg.scanRange[1]):
                if not isData:
                    histDict['QCD_B'].Fill(value, -weight*QCD_weight)
                else:
                    histDict['QCD_B'].Fill(value, weight*QCD_weight)  
            #region C
            if regionSelection(tree, FS, "OScontrol", plots_cfg.scanRange[0], plots_cfg.scanRange[1]):
                if not isData:
                    histDict['QCD_C'].Fill(value, -weight*QCD_weight)
                    if iCategory != 'WJets':
                        histDict['WJets_OScontrol'].Fill(value, -weight)  
                else:
                    histDict['QCD_C'].Fill(value, weight*QCD_weight)
                    histDict['WJets_OScontrol'].Fill(value, weight)
            #region D
            if regionSelection(tree, FS, "SScontrol", plots_cfg.scanRange[0], plots_cfg.scanRange[1]):
                if not isData:
                    histDict['QCD_D'].Fill(value, -weight*QCD_weight)
                    histDict['QCD_D_for_C'].Fill(value, -weight*QCD_weight)
                    histDict['QCD_D_for_A'].Fill(value, -weight*QCD_weight)
                else:
                    histDict['QCD_D'].Fill(value, weight*QCD_weight)
                    histDict['QCD_D_for_C'].Fill(value, weight*QCD_weight)
                    histDict['QCD_D_for_A'].Fill(value, weight*QCD_weight)


    print iCategory, tmpHist.Integral(0, len(varBins)+1)
    histDict[iCategory].Add(tmpHist)            

    del tmpHist

    print ''
コード例 #26
0
def runOneFile(iFS, inputFile, signSelect, isoSelect, output_dir, split):
    inputFile = inputFile + "%s_noIso.root" %iFS
    ifile = r.TFile(inputFile)
    iTree = ifile.Get("Ntuple")
    eventCountWeighted = ifile.Get('eventCountWeighted')

    oString = signSelect + isoSelect

    outputFile = "%s_%s.root" %(output_dir+inputFile[inputFile.rfind("/"):inputFile.find(".root")], oString)
    oFile = r.TFile(outputFile,"recreate")

    iTree.SetBranchStatus("*",1)

    oTree = r.TTree('eventTree','')
    oTree_train = r.TTree('eventTree_train','')
    oTree_test = r.TTree('eventTree_test','')

    total = iTree.GetEntries()

    Lumi = plots.lumi
    isData = False
    isSignal = False

    floatVarsDict = setUpFloatVarsDict()

    for iVar in floatVarsDict.keys():
        oTree.Branch("%s" %iVar, floatVarsDict[iVar], "%s/f" %iVar)
        oTree_train.Branch("%s" %iVar, floatVarsDict[iVar], "%s/f" %iVar)
        oTree_test.Branch("%s" %iVar, floatVarsDict[iVar], "%s/f" %iVar)

    isoSelection = 'control'
    if isoSelect == 'Tight':
        isoSelection = 'signal'

    for i in range(total):
        r.gStyle.SetOptStat(0)
        tool.printProcessStatus(iCurrent=i, total=total, processName = 'Looping sample %s' %inputFile)
        iTree.GetEntry(i)

        if 'data' in iTree.sampleName:
            isData = True
        if 'ZPrime' in iTree.sampleName:
            isSignal = True

        if signSelect == 'OS' and iTree.q_1 == iTree.q_2:
            continue
        elif signSelect == 'SS' and iTree.q_1 != iTree.q_2:
            continue
        if plots.regionSelection(iTree, iFS, isoSelection, 'Loose', plots_cfg.scanRange[0], plots_cfg.scanRange[1]):
            if isData:
                floatVarsDict['weightWithPU'][0] = 1.0            
            else:
                floatVarsDict['weightWithPU'][0] = cutSampleTools.getPUWeight(iTree.nTruePU)*iTree.xs*Lumi*iTree.genEventWeight/(int(eventCountWeighted.GetBinContent(1)))
                if split:
                    floatVarsDict['weightWithPU'][0] = 2*floatVarsDict['weightWithPU'][0]

            met.SetCoordinates(iTree.pfMetEt, 0.0, iTree.pfMetPhi, 0)
            l1.SetCoordinates(iTree.pt_1, iTree.eta_1, iTree.phi_1, iTree.m_1)
            l2.SetCoordinates(iTree.pt_2, iTree.eta_2, iTree.phi_2, iTree.m_2)

            floatVarsDict['pt_1'][0] = iTree.pt_1
            floatVarsDict['eta_1'][0] = iTree.eta_1
            floatVarsDict['phi_1'][0] = iTree.phi_1
            floatVarsDict['m_1'][0] = iTree.m_1
            floatVarsDict['pt_2'][0] = iTree.pt_2
            floatVarsDict['eta_2'][0] = iTree.eta_2
            floatVarsDict['phi_2'][0] = iTree.phi_2
            floatVarsDict['m_2'][0] = iTree.m_2
            floatVarsDict['met'][0] = iTree.pfMetEt
            floatVarsDict['met_phi'][0] = iTree.pfMetPhi
            floatVarsDict['jpt_1'][0] = iTree.jpt_1
            if iTree.jpt_1 > 0:
                floatVarsDict['jeta_1'][0] = iTree.jeta_1
                floatVarsDict['jphi_1'][0] = iTree.jphi_1
            else:
                floatVarsDict['jeta_1'][0] = -999.0
                floatVarsDict['jphi_1'][0] = -999.0
            floatVarsDict['jpt_2'][0] = iTree.jpt_2
            if iTree.jpt_2 > 0:
                floatVarsDict['jeta_2'][0] = iTree.jeta_2
                floatVarsDict['jphi_2'][0] = iTree.jphi_2
            else:
                floatVarsDict['jeta_2'][0] = -999.0
                floatVarsDict['jphi_2'][0] = -999.0
            floatVarsDict['pZetaCut'][0] = iTree.pZetaCut
            floatVarsDict['m_eff'][0] = iTree.m_eff
            oTree.Fill()
            if random.random() < 0.5:
                oTree_train.Fill()
            else:
                oTree_test.Fill()

    print ''
    oFile.cd()
    if not split:
        oTree.Write()
        nSaved = oTree.GetEntries()
        print 'saved %i events out of %i at: %s' %(nSaved,total,outputFile)
    else:
        oTree_train.Write()
        nSaved = oTree_train.GetEntries()
        print 'for training: saved %i events out of %i at: %s' %(nSaved,total,outputFile)
        oTree_test.Write()
        nSaved = oTree_test.GetEntries()
        print 'for testing: saved %i events out of %i at: %s' %(nSaved,total,outputFile)
    oFile.Close()
コード例 #27
0
def calculateSF(fileList, location0, out, sigRegionOption = 'tight', relaxedRegionOption = 'relaxed', usePU = False, verbose = False, iso = 1.5):
    files = []
    trees = []

    MC_SS_TT_cat1 = 0
    MC_SS_LL_cat1 = 0
    MC_OS_LL_cat1 = 0
    DATA_SS_TT_cat1 = 0
    DATA_SS_LL_cat1 = 0
    DATA_OS_LL_cat1 = 0

    MC_SS_TT_cat2 = 0
    MC_SS_LL_cat2 = 0
    MC_OS_LL_cat2 = 0
    DATA_SS_TT_cat2 = 0
    DATA_SS_LL_cat2 = 0
    DATA_OS_LL_cat2 = 0

    MC_SS_TT_cat1_veto = 0
    MC_SS_LL_cat1_veto = 0
    MC_OS_LL_cat1_veto = 0
    DATA_SS_TT_cat1_veto = 0
    DATA_SS_LL_cat1_veto = 0
    DATA_OS_LL_cat1_veto = 0

    MC_SS_TT_cat2_veto = 0
    MC_SS_LL_cat2_veto = 0
    MC_OS_LL_cat2_veto = 0
    DATA_SS_TT_cat2_veto = 0
    DATA_SS_LL_cat2_veto = 0
    DATA_OS_LL_cat2_veto = 0

    MC_SS_TT_catNone_veto = 0
    MC_SS_LL_catNone_veto = 0
    MC_OS_LL_catNone_veto = 0
    DATA_SS_TT_catNone_veto = 0
    DATA_SS_LL_catNone_veto = 0
    DATA_OS_LL_catNone_veto = 0

    for fileName, location, in fileList:

        files.append(r.TFile(location0+location))
        trees.append(files[len(files)-1].Get("eventTree"))
        total = trees[len(trees)-1].GetEntries()
        if 'data' in fileName:
            isData = True
        else:
            isData = False
        if 'H2hh' in fileName:
            continue
        for i in range(total):
            tool.printProcessStatus(iCurrent=i+1, total=total, processName = 'Looping sample [%s]' %fileName)
            trees[len(trees)-1].GetEntry(i)
            if usePU and (not isData):
                puWeight = trees[len(trees)-1].PUWeight
            else:
                puWeight = 1.0
#             if trees[len(trees)-1].category == '1M1NonM':
            if trees[len(trees)-1].NBTags == 1:
                if passCut(trees[len(trees)-1], '%sSS' %sigRegionOption, iso):
                    if isData:
                        DATA_SS_TT_cat1+=1
                    else:
                        MC_SS_TT_cat1+=trees[len(trees)-1].xs*(lumi/trees[len(trees)-1].initEvents)*trees[len(trees)-1].triggerEff*puWeight
                elif passCut(trees[len(trees)-1], '%sOS' %relaxedRegionOption, iso):
                    if isData:
                        DATA_OS_LL_cat1+=1
                    else:
                        MC_OS_LL_cat1+=trees[len(trees)-1].xs*(lumi/trees[len(trees)-1].initEvents)*trees[len(trees)-1].triggerEff*puWeight
                elif passCut(trees[len(trees)-1], '%sSS' %relaxedRegionOption, iso):
                    if isData:
                        DATA_SS_LL_cat1+=1
                    else:
                        MC_SS_LL_cat1 +=trees[len(trees)-1].xs*(lumi/trees[len(trees)-1].initEvents)*trees[len(trees)-1].triggerEff*puWeight
#             elif trees[len(trees)-1].category == '2M':
            elif trees[len(trees)-1].NBTags > 1:

                if passCut(trees[len(trees)-1], '%sSS' %sigRegionOption, iso):
                    if isData:
                        DATA_SS_TT_cat2 += 1
                    else:
                        MC_SS_TT_cat2 += trees[len(trees)-1].xs*(lumi/trees[len(trees)-1].initEvents)*trees[len(trees)-1].triggerEff*puWeight
                elif passCut(trees[len(trees)-1], '%sOS' %relaxedRegionOption, iso):
                    if isData:
                        DATA_OS_LL_cat2 += 1
                    else:
                        MC_OS_LL_cat2 += trees[len(trees)-1].xs*(lumi/trees[len(trees)-1].initEvents)*trees[len(trees)-1].triggerEff*puWeight
                elif passCut(trees[len(trees)-1], '%sSS' %relaxedRegionOption, iso):
                    if isData:
                        DATA_SS_LL_cat2 += 1
                    else:
                        MC_SS_LL_cat2 += trees[len(trees)-1].xs*(lumi/trees[len(trees)-1].initEvents)*trees[len(trees)-1].triggerEff*puWeight


            if trees[len(trees)-1].nElectrons == 0 and trees[len(trees)-1].nMuons == 0:
#                 if trees[len(trees)-1].category == '1M1NonM':
                if trees[len(trees)-1].NBTags == 1:
                    if passCut(trees[len(trees)-1], '%sSS' %sigRegionOption, iso):
                        if isData:
                            DATA_SS_TT_cat1_veto+=1
                        else:
                            MC_SS_TT_cat1_veto+=trees[len(trees)-1].xs*(lumi/trees[len(trees)-1].initEvents)*trees[len(trees)-1].triggerEff*puWeight
                    elif passCut(trees[len(trees)-1], '%sOS' %relaxedRegionOption, iso):
                        if isData:
                            DATA_OS_LL_cat1_veto+=1
                        else:
                            MC_OS_LL_cat1_veto+=trees[len(trees)-1].xs*(lumi/trees[len(trees)-1].initEvents)*trees[len(trees)-1].triggerEff*puWeight
                    elif passCut(trees[len(trees)-1], '%sSS' %relaxedRegionOption, iso):
                        if isData:
                            DATA_SS_LL_cat1_veto+=1
                        else:
                            MC_SS_LL_cat1_veto +=trees[len(trees)-1].xs*(lumi/trees[len(trees)-1].initEvents)*trees[len(trees)-1].triggerEff*puWeight
#                 elif trees[len(trees)-1].category == '2M':
                elif trees[len(trees)-1].NBTags > 1:

                    if passCut(trees[len(trees)-1], '%sSS' %sigRegionOption, iso):
                        if isData:
                            DATA_SS_TT_cat2_veto += 1
                        else:
                            MC_SS_TT_cat2_veto += trees[len(trees)-1].xs*(lumi/trees[len(trees)-1].initEvents)*trees[len(trees)-1].triggerEff*puWeight
                    elif passCut(trees[len(trees)-1], '%sOS' %relaxedRegionOption, iso):
                        if isData:
                            DATA_OS_LL_cat2_veto += 1
                        else:
                            MC_OS_LL_cat2_veto += trees[len(trees)-1].xs*(lumi/trees[len(trees)-1].initEvents)*trees[len(trees)-1].triggerEff*puWeight
                    elif passCut(trees[len(trees)-1], '%sSS' %relaxedRegionOption, iso):
                        if isData:
                            DATA_SS_LL_cat2_veto += 1
                        else:
                            MC_SS_LL_cat2_veto += trees[len(trees)-1].xs*(lumi/trees[len(trees)-1].initEvents)*trees[len(trees)-1].triggerEff*puWeight
#                 elif trees[len(trees)-1].category == 'none':
                elif trees[len(trees)-1].NBTags == 0:
                    if passCut(trees[len(trees)-1], '%sSS' %sigRegionOption, iso):
                        if isData:
                            DATA_SS_TT_catNone_veto += 1
                        else:
                            MC_SS_TT_catNone_veto += trees[len(trees)-1].xs*(lumi/trees[len(trees)-1].initEvents)*trees[len(trees)-1].triggerEff*puWeight
                    elif passCut(trees[len(trees)-1], '%sOS' %relaxedRegionOption, iso):
                        if isData:
                            DATA_OS_LL_catNone_veto += 1
                        else:
                            MC_OS_LL_catNone_veto += trees[len(trees)-1].xs*(lumi/trees[len(trees)-1].initEvents)*trees[len(trees)-1].triggerEff*puWeight
                    elif passCut(trees[len(trees)-1], '%sSS' %relaxedRegionOption, iso):
                        if isData:
                            DATA_SS_LL_catNone_veto += 1
                        else:
                            MC_SS_LL_catNone_veto += trees[len(trees)-1].xs*(lumi/trees[len(trees)-1].initEvents)*trees[len(trees)-1].triggerEff*puWeight


        print ''

    QCD_SS_LL_cat1 = DATA_SS_LL_cat1 - MC_SS_LL_cat1
    QCD_SS_TT_cat1 = DATA_SS_TT_cat1 - MC_SS_TT_cat1
    QCD_OS_LL_cat1 = DATA_OS_LL_cat1 - MC_OS_LL_cat1

    QCD_SS_LL_cat2 = DATA_SS_LL_cat2 - MC_SS_LL_cat2
    QCD_SS_TT_cat2 = DATA_SS_TT_cat2 - MC_SS_TT_cat2
    QCD_OS_LL_cat2 = DATA_OS_LL_cat2 - MC_OS_LL_cat2


    QCD_SS_LL_cat0 = QCD_SS_LL_cat1 + QCD_SS_LL_cat2
    QCD_SS_TT_cat0 = QCD_SS_TT_cat1 + QCD_SS_TT_cat2
    QCD_OS_LL_cat0 = QCD_OS_LL_cat1 + QCD_OS_LL_cat2
    DATA_OS_LL_cat0 = DATA_OS_LL_cat1 + DATA_OS_LL_cat2

    SF_cat0 = QCD_SS_TT_cat0/QCD_SS_LL_cat0
    sf_cat0 = QCD_OS_LL_cat0/DATA_OS_LL_cat0
    weight0 = SF_cat0*sf_cat0

    SF_cat1 = QCD_SS_TT_cat1/QCD_SS_LL_cat1
    sf_cat1 = QCD_OS_LL_cat1/DATA_OS_LL_cat1
    weight1 = SF_cat1*sf_cat1
    
    SF_cat2 = QCD_SS_TT_cat2/QCD_SS_LL_cat2
    sf_cat2 = QCD_OS_LL_cat2/DATA_OS_LL_cat2
    weight2 = SF_cat2*sf_cat2


    QCD_SS_LL_cat1_veto = DATA_SS_LL_cat1_veto - MC_SS_LL_cat1_veto
    QCD_SS_TT_cat1_veto = DATA_SS_TT_cat1_veto - MC_SS_TT_cat1_veto
    QCD_OS_LL_cat1_veto = DATA_OS_LL_cat1_veto - MC_OS_LL_cat1_veto

    QCD_SS_LL_cat2_veto = DATA_SS_LL_cat2_veto - MC_SS_LL_cat2_veto
    QCD_SS_TT_cat2_veto = DATA_SS_TT_cat2_veto - MC_SS_TT_cat2_veto
    QCD_OS_LL_cat2_veto = DATA_OS_LL_cat2_veto - MC_OS_LL_cat2_veto

    QCD_SS_LL_catNone_veto = DATA_SS_LL_catNone_veto - MC_SS_LL_catNone_veto
    QCD_SS_TT_catNone_veto = DATA_SS_TT_catNone_veto - MC_SS_TT_catNone_veto
    QCD_OS_LL_catNone_veto = DATA_OS_LL_catNone_veto - MC_OS_LL_catNone_veto

    QCD_SS_LL_cat0_veto = QCD_SS_LL_cat1_veto + QCD_SS_LL_cat2_veto
    QCD_SS_TT_cat0_veto = QCD_SS_TT_cat1_veto + QCD_SS_TT_cat2_veto
    QCD_OS_LL_cat0_veto = QCD_OS_LL_cat1_veto + QCD_OS_LL_cat2_veto
    DATA_SS_LL_cat0_veto = DATA_SS_LL_cat1_veto + DATA_SS_LL_cat2_veto
    DATA_SS_TT_cat0_veto = DATA_SS_TT_cat1_veto + DATA_SS_TT_cat2_veto
    DATA_OS_LL_cat0_veto = DATA_OS_LL_cat1_veto + DATA_OS_LL_cat2_veto

    SF_cat0_veto = QCD_SS_TT_cat0_veto/QCD_SS_LL_cat0_veto
    sf_cat0_veto = QCD_OS_LL_cat0_veto/DATA_OS_LL_cat0_veto
    weight0_veto = SF_cat0_veto*sf_cat0_veto

    un_SF_cat0_veto = calcSysUnc(SF_cat0_veto, QCD_SS_TT_cat0_veto, QCD_SS_LL_cat0_veto)
    un_sf_cat0_veto = calcSysUnc(1-sf_cat0_veto, DATA_OS_LL_cat0_veto - QCD_SS_TT_cat0_veto, DATA_OS_LL_cat0_veto)
    un_weight0_veto = calcSysUnc(weight0_veto, SF_cat0_veto, sf_cat0_veto, un_SF_cat0_veto, un_sf_cat0_veto)

    SF_cat1_veto = QCD_SS_TT_cat1_veto/QCD_SS_LL_cat1_veto
    sf_cat1_veto = QCD_OS_LL_cat1_veto/DATA_OS_LL_cat1_veto
    weight1_veto = SF_cat1_veto*sf_cat1_veto
    
    un_SF_cat1_veto = calcSysUnc(SF_cat1_veto, QCD_SS_TT_cat1_veto, QCD_SS_LL_cat1_veto)
    un_sf_cat1_veto = calcSysUnc(1-sf_cat1_veto, MC_OS_LL_cat1_veto, DATA_OS_LL_cat1_veto)
    un_weight1_veto = calcSysUnc(weight1_veto, SF_cat1_veto, sf_cat1_veto, un_SF_cat1_veto, un_sf_cat1_veto)

    SF_cat2_veto = QCD_SS_TT_cat2_veto/QCD_SS_LL_cat2_veto
    sf_cat2_veto = QCD_OS_LL_cat2_veto/DATA_OS_LL_cat2_veto
    weight2_veto = SF_cat2_veto*sf_cat2_veto

    un_SF_cat2_veto = calcSysUnc(SF_cat2_veto, QCD_SS_TT_cat2_veto, QCD_SS_LL_cat2_veto)
    un_sf_cat2_veto = calcSysUnc(1-sf_cat2_veto, MC_OS_LL_cat2_veto, DATA_OS_LL_cat2_veto)
    un_weight2_veto = calcSysUnc(weight2_veto, SF_cat2_veto, sf_cat2_veto, un_SF_cat2_veto, un_sf_cat2_veto)

    SF_catNone_veto = QCD_SS_TT_catNone_veto/QCD_SS_LL_catNone_veto
    sf_catNone_veto = QCD_OS_LL_catNone_veto/DATA_OS_LL_catNone_veto
    weightNone_veto = SF_catNone_veto*sf_catNone_veto

    un_SF_catNone_veto = calcSysUnc(SF_catNone_veto, QCD_SS_TT_catNone_veto, QCD_SS_LL_catNone_veto)
    un_sf_catNone_veto = calcSysUnc(1-sf_catNone_veto, MC_OS_LL_catNone_veto, DATA_OS_LL_catNone_veto)
    un_weightNone_veto = calcSysUnc(weightNone_veto, SF_catNone_veto, sf_catNone_veto, un_SF_catNone_veto, un_sf_catNone_veto)

    if verbose:
        
        print 'MC/QCD/Data'
        print 'Category 0tag'
        print '\t\t\t%.1f/%.1f/%.0f' %(MC_SS_TT_catNone_veto,QCD_SS_TT_catNone_veto, DATA_SS_TT_catNone_veto)
        print '%.1f/%.1f/%.0f\t%.1f/%.1f/%.0f'%(MC_OS_LL_catNone_veto, QCD_OS_LL_catNone_veto, DATA_OS_LL_catNone_veto, 
                                                MC_SS_LL_catNone_veto, QCD_SS_LL_catNone_veto, DATA_SS_LL_catNone_veto)        
        print ''
        print 'Category 1+2tag'
        print '\t\t\t%.1f/%.1f/%.0f' %(DATA_SS_TT_cat0_veto-QCD_SS_TT_cat0_veto,QCD_SS_TT_cat0_veto, DATA_SS_TT_cat0_veto)
        print '%.1f/%.1f/%.0f\t%.1f/%.1f/%.0f'%(DATA_OS_LL_cat0_veto-QCD_OS_LL_cat0_veto, QCD_OS_LL_cat0_veto, DATA_OS_LL_cat0_veto, 
                                                DATA_SS_LL_cat0_veto-QCD_SS_LL_cat0_veto, QCD_SS_LL_cat0_veto, DATA_SS_LL_cat0_veto) 
        print ''
        print 'Category 1tag'
        print '\t\t\t%.1f/%.1f/%.0f' %(MC_SS_TT_cat1_veto,QCD_SS_TT_cat1_veto, DATA_SS_TT_cat1_veto)
        print '%.1f/%.1f/%.0f\t%.1f/%.1f/%.0f'%(MC_OS_LL_cat1_veto, QCD_OS_LL_cat1_veto, DATA_OS_LL_cat1_veto, 
                                                MC_SS_LL_cat1_veto, QCD_SS_LL_cat1_veto, DATA_SS_LL_cat1_veto)
        print ''
        print 'Category 2tag'
        print '\t\t\t%.1f/%.1f/%.0f' %(MC_SS_TT_cat2_veto,QCD_SS_TT_cat2_veto, DATA_SS_TT_cat2_veto)
        print '%.1f/%.1f/%.0f\t\t%.1f/%.1f/%.0f'%(MC_OS_LL_cat2_veto, QCD_OS_LL_cat2_veto, DATA_OS_LL_cat2_veto, 
                                                MC_SS_LL_cat2_veto, QCD_SS_LL_cat2_veto, DATA_SS_LL_cat2_veto)

        print 'Results__________________________________'
        print 'Category\t1+2tag_veto\t\t1tag_veto\t\t2tag_veto\t\t0tag_veto'
        print 'SF\t\t%.3f +/- %.3f (%.f%%)\t%.3f +/- %.3f (%.f%%)\t%.3f +/- %.3f (%.f%%)\t%.3f +/- %.3f (%.f%%)' %(SF_cat0_veto, un_SF_cat0_veto, 100*un_SF_cat0_veto/SF_cat0_veto,
                                                                                                                   SF_cat1_veto, un_SF_cat1_veto, 100*un_SF_cat1_veto/SF_cat1_veto,
                                                                                                                   SF_cat2_veto, un_SF_cat2_veto, 100*un_SF_cat2_veto/SF_cat2_veto,
                                                                                                                   SF_catNone_veto, un_SF_catNone_veto, 100*un_SF_catNone_veto/SF_catNone_veto)
        print 'OCD/Data\t%.3f +/- %.3f (%.f%%)\t%.3f +/- %.3f (%.f%%)\t%.3f +/- %.3f (%.f%%)\t%.3f +/- %.3f (%.f%%)' %(sf_cat0_veto, un_sf_cat0_veto, 100*un_sf_cat0_veto/sf_cat0_veto,
                                                                                                   sf_cat1_veto, un_sf_cat1_veto, 100*un_sf_cat1_veto/sf_cat1_veto,
                                                                                                   sf_cat2_veto, un_sf_cat2_veto, 100*un_sf_cat2_veto/sf_cat2_veto,
                                                                                                   sf_catNone_veto, un_sf_catNone_veto, 100*un_sf_catNone_veto/sf_catNone_veto)
        print 'Weights\t\t%.3f +/- %.3f (%.f%%)\t%.3f +/- %.3f (%.f%%)\t%.3f +/- %.3f (%.f%%)\t%.3f +/- %.3f (%.f%%)' %(weight0_veto, un_weight0_veto, 100*un_weight0_veto/weight0_veto,
                                                                                                    weight1_veto, un_weight1_veto, 100*un_weight1_veto/weight1_veto,
                                                                                                    weight2_veto, un_weight2_veto, 100*un_weight2_veto/weight2_veto,
                                                                                                    weightNone_veto, un_weightNone_veto, 100*un_weightNone_veto/weightNone_veto)


    output = []
    if 'SF' not in out:
        if 'veto' in out:
            if '0' in out:
                output.append(weight0_veto) 
            if '1' in out:
                output.append(weight1_veto) 
            if '2' in out:
                output.append(weight2_veto)
            if 'None' in out:
                output.append(weightNone_veto)
        else:
            if '0' in out:
                output.append(weight0) 
            if '1' in out:
                output.append(weight1) 
            if '2' in out:
                output.append(weight2) 
        return output
    else:
        if 'veto' in out:
            if '0' in out:
                output.append(SF_cat0_veto) 
            if '1' in out:
                output.append(SF_cat1_veto) 
            if '2' in out:
                output.append(SF_cat2_veto)
            if 'None' in out:
                output.append(SF_catNone_veto)
        else:
            if '0' in out:
                output.append(SF_cat0) 
            if '1' in out:
                output.append(SF_cat1) 
            if '2' in out:
                output.append(SF_cat2) 
        return output
コード例 #28
0
def loop_one_sample(iSample, iCategory, histDict, varName, varBins, FS,
                    scanPoints):
    if options.antiIso:
        iSample += "%s_antiIso.root" % FS
    elif options.antiEIso:
        iSample += "%s_antiEIso.root" % FS
    elif options.antiMIso:
        iSample += "%s_antiMIso.root" % FS
    elif options.noIso:
        iSample += "%s_noIso.root" % FS
    elif options.BSM3G:
        iSample += "%s_noIso.root" % FS
    else:
        iSample += "%s_inclusive.root" % FS
    file = r.TFile(iSample)
    tree = file.Get('Ntuple')
    eventCount = file.Get('eventCount')
    eventCountWeighted = file.Get('eventCountWeighted')

    sumPtWeights = -1
    if "TT" in iSample and options.sys == 'topPt':
        sumPtWeights = file.Get('eventCountPtWeighted').GetBinContent(1)

    nEntries = tree.GetEntries()
    #     if nEntries > 100:
    #         nEntries = 100

    tmpHist = r.TH1F("tmp_%s_%s" % (iCategory, varName), '',
                     len(varBins) - 1, varBins)
    tmpHist.Sumw2()
    tmpHist_forROOTFile = r.TH1F("%s" % (varName), '',
                                 len(varBins) - 1, varBins)
    tmpHist_forROOTFile.Sumw2()
    isData = False
    isSignal = False

    if eventCount:
        initEvents = eventCount.GetBinContent(1)
    else:
        initEvents = tree.initEvents
    if eventCountWeighted:
        sumWeights = eventCountWeighted.GetBinContent(1)
    else:
        sumWeights = tree.initWeightedEvents

    if iCategory == 'Observed':
        isData = True
    for iEntry in range(nEntries):
        tree.GetEntry(iEntry)
        tool.printProcessStatus(iEntry, nEntries,
                                'Looping sample %s' % (iSample), iEntry - 1)
        weight = 1.0
        QCD_weight = 1.0

        if not passCut(tree, FS, isData, options.sys):
            continue
        if not isData:
            xs = tree.xs
            if (80.94 < xs < 80.96) or (136.01 < xs < 136.03):
                xs = xs * 0.108 * 3
            if options.sys == 'topPt' and sumPtWeights != -1.0:
                sumWeights = sumPtWeights
                weight = Lumi * xs * tree.genEventWeight * tree.trigweight_1 * tree.trigweight_2 * tree.topPtWeight / (
                    sumWeights + 0.0)
            else:
                weight = Lumi * xs * tree.genEventWeight * tree.trigweight_1 * tree.trigweight_2 / (
                    sumWeights + 0.0)
            if options.PUWeight:
                weight = weight * cutSampleTools.getPUWeight(tree.nTruePU)

        if 'WJets' in iSample:
            weight = 1.0 * weight
        if 'ZPrime' in iSample:
            weight = getZPrimeXS(
                iSample[iSample.rfind("/") + 8:iSample.rfind("_all")]) * weight
            isSignal = True
        if varName == 'm_withMET':
            value = tree.m_eff
        elif varName == 'mVis':
            value = tree.m_vis
        elif varName == 'pZeta - 3.1pZetaVis':
            value = tree.ZetaCut
        elif varName == "nCSVL":
            value = tree.nCSVL
        elif varName == "cos_phi_tau1_tau2":
            value = math.cos(tree.phi_1 - tree.phi_2)
        elif varName == "j1Pt":
            jets = getJets(tree)
            if len(jets) > 0:
                value = jets[0].pt()
            else:
                value = -1
        elif varName == 'm_gen':
            if tree.eGenTauMass < 0 or tree.tGenMass < 0:
                continue
            l1.SetCoordinates(tree.eGenTauPt, tree.eGenTauEta, tree.eGenTauPhi,
                              tree.eGenTauMass)
            l2.SetCoordinates(tree.tGenPt, tree.tGenEta, tree.tGenPhi,
                              tree.tGenMass)
            value = (l1 + l2).mass()
        else:
            if hasattr(tree, varName):
                value = getattr(tree, varName)
            else:
                value = -1

        if options.overFlow:
            if value > varBins[len(varBins) - 1]:
                value = (varBins[len(varBins) - 1] +
                         varBins[len(varBins) - 2] + 0.0) / 2.0

        if regionSelection(tree, FS, "OSsignal", plots_cfg.scanRange[0],
                           plots_cfg.scanRange[1]):
            fill = True
            if isData:
                fill = False
                if options.unblind or (options.unblindPartial
                                       and passUnblindPartial(varName, value)):
                    fill = True
                    histDict['WJets_OSsignal'].Fill(value, weight)

            if fill:
                tmpHist.Fill(value, weight)
                tmpHist_forROOTFile.Fill(value, weight)
                if iCategory != 'WJets' and (not isData) and (not isSignal):
                    histDict['WJets_OSsignal'].Fill(value, -weight)
        else:
            if isSignal:
                continue
            #region B
            if regionSelection(tree, FS, "SSsignal", plots_cfg.scanRange[0],
                               plots_cfg.scanRange[1]):
                if not isData:
                    histDict['QCD_B'].Fill(value, -weight * QCD_weight)
                else:
                    histDict['QCD_B'].Fill(value, weight * QCD_weight)
            #region C
            if regionSelection(tree, FS, "OScontrol", plots_cfg.scanRange[0],
                               plots_cfg.scanRange[1]):
                if not isData:
                    histDict['QCD_C'].Fill(value, -weight * QCD_weight)
                    if iCategory != 'WJets':
                        histDict['WJets_OScontrol'].Fill(value, -weight)
                else:
                    histDict['QCD_C'].Fill(value, weight * QCD_weight)
                    histDict['WJets_OScontrol'].Fill(value, weight)
            #region D
            if regionSelection(tree, FS, "SScontrol", plots_cfg.scanRange[0],
                               plots_cfg.scanRange[1]):
                if not isData:
                    histDict['QCD_D'].Fill(value, -weight * QCD_weight)
                    histDict['QCD_D_for_C'].Fill(value, -weight * QCD_weight)
                    histDict['QCD_D_for_A'].Fill(value, -weight * QCD_weight)
                else:
                    histDict['QCD_D'].Fill(value, weight * QCD_weight)
                    histDict['QCD_D_for_C'].Fill(value, weight * QCD_weight)
                    histDict['QCD_D_for_A'].Fill(value, weight * QCD_weight)

    print iCategory, tmpHist.Integral(0, len(varBins) + 1)
    histDict[iCategory].Add(tmpHist)

    del tmpHist

    print ''
コード例 #29
0
def loop_one_sample(iSample, iCategory, histDict, varName, varBins, FS, scanPoints):
    if options.antiIso:
        iSample += "%s_antiIso.root" %FS
    elif options.antiEIso:
        iSample += "%s_antiEIso.root" %FS
    elif options.antiMIso:
        iSample += "%s_antiMIso.root" %FS
    elif options.noIso:
        iSample += "%s_noIso.root" %FS
    elif options.BSM3G:
        iSample += "%s_noIso.root" %FS 
    else:
        iSample += "%s_inclusive.root" %FS 
    file = r.TFile(iSample)    
    tree = file.Get('Ntuple')
    eventCount = file.Get('eventCount')
    eventCountWeighted = file.Get('eventCountWeighted')

    nEntries = tree.GetEntries()
#     if nEntries > 100:
#         nEntries = 100
    
    tmpHist = r.TH1F("tmp_%s_%s" %(iCategory, varName), '', len(varBins)-1, varBins)
    tmpHist.Sumw2()
    tmpHist_forROOTFile = r.TH1F("%s" %(varName), '', len(varBins)-1, varBins)
    tmpHist_forROOTFile.Sumw2()
    isData = False
    isSignal = False
    if iCategory == 'Observed':
        isData = True
    for iEntry in range(nEntries):
        tree.GetEntry(iEntry)
        tool.printProcessStatus(iEntry, nEntries, 'Looping sample %s' %(iSample), iEntry-1)
        weight = 1.0
        QCD_weight = 1.0

        if options.sys == 'jetECUp' and not isData:
            met.SetCoordinates(tree.pfMet_jesUp_Et, 0.0, tree.pfMet_jesUp_Phi, 0)
        elif options.sys == 'jetECDown' and not isData:
            met.SetCoordinates(tree.pfMet_jesDown_Et, 0.0, tree.pfMet_jesDown_Phi, 0)
        elif options.sys == 'tauECUp' and not isData:
            met.SetCoordinates(tree.pfMet_tesUp_Et, 0.0, tree.pfMet_tesUp_Phi, 0)
        elif options.sys == 'tauECDown' and not isData:
            met.SetCoordinates(tree.pfMet_tesDown_Et, 0.0, tree.pfMet_tesDown_Phi, 0)
        else:
            met.SetCoordinates(tree.pfMetEt, 0.0, tree.pfMetPhi, 0)

        l1.SetCoordinates(tree.pt_1, tree.eta_1, tree.phi_1, tree.m_1)
        l2.SetCoordinates(tree.pt_2, tree.eta_2, tree.phi_2, tree.m_2)

        if eventCount:
            initEvents = eventCount.GetBinContent(1)
        else:    
            initEvents = tree.initEvents
        if eventCountWeighted:
            sumWeights = eventCountWeighted.GetBinContent(1)
        else:    
            sumWeights = tree.initWeightedEvents
        if not passCut(tree, FS, isData, l1, l2, met, options.sys):
            continue
        if not isData:
            xs  = tree.xs
            if (80.94 < xs < 80.96) or (136.01 < xs < 136.03):
                xs = xs*0.108*3
            weight = Lumi*xs*tree.genEventWeight*tree.trigweight_1*tree.trigweight_2/(sumWeights+0.0)
            if options.PUWeight:
                weight = weight*cutSampleTools.getPUWeight(tree.nTruePU)
        if options.diffQCD:
            if tree.tDecayMode < 4:
                QCD_weight = plots_cfg.SF_prong1[0]
            elif tree.tDecayMode > 8:
                QCD_weight = plots_cfg.SF_prong3[0]

        if 'WJets' in iSample:
            weight = 1.0*weight
        if 'ZPrime' in iSample:
            weight = getZPrimeXS(iCategory[7:])*weight
            isSignal =  True
        if varName == 'm_withMET':
            value = (l1 + l2 + met).mass()
        elif varName == 'mVis':
            value = (l1 + l2).mass()
        elif varName == 'pZeta - 3.1pZetaVis':
            value = pZetaCut(l1, l2, met)
        elif varName == "nCSVL":
            value = getNCSVLJets(tree, options.sys, isData, True)
        elif varName == "cos_phi_tau1_tau2":
            value = math.cos(tree.phi_1 - tree.phi_2)
        elif varName == "j1Pt":
            jets = getJets(tree)
            if len(jets)>0:
                value = jets[0].pt()
            else:
                value = -1
        elif varName == 'm_gen':
            if tree.eGenTauMass < 0  or tree.tGenMass < 0:
                continue

            l1.SetCoordinates(tree.eGenTauPt, tree.eGenTauEta, tree.eGenTauPhi, tree.eGenTauMass)
            l2.SetCoordinates(tree.tGenPt, tree.tGenEta, tree.tGenPhi, tree.tGenMass)
            value = (l1 + l2).mass()
        else:
            if hasattr(tree, varName):
                value = getattr(tree, varName)
            else:
                value = -1

        if options.overFlow:
            if value > varBins[len(varBins)-1]:
                value = (varBins[len(varBins)-1]+varBins[len(varBins)-2]+0.0)/2.0

        if regionSelection(tree, FS, "OSsignal", plots_cfg.scanRange[0], plots_cfg.scanRange[1]):
            fill = True
            if isData:
                fill = False
                if options.unblind or (options.unblindPartial and passUnblindPartial(varName, value)):
                    fill = True
                    histDict['WJets_OSsignal'].Fill(value, weight)  

            if fill:
                tmpHist.Fill(value, weight)
                tmpHist_forROOTFile.Fill(value, weight)
                if iCategory != 'WJets' and (not isData) and (not isSignal):
                    histDict['WJets_OSsignal'].Fill(value, -weight)
        else:
            if isSignal:
                continue
            #region B
            if regionSelection(tree, FS, "SSsignal", plots_cfg.scanRange[0], plots_cfg.scanRange[1]):
                if not isData:
                    histDict['QCD_B'].Fill(value, -weight*QCD_weight)
                else:
                    histDict['QCD_B'].Fill(value, weight*QCD_weight)  
            #region C
            if regionSelection(tree, FS, "OScontrol", plots_cfg.scanRange[0], plots_cfg.scanRange[1]):
                if not isData:
                    histDict['QCD_C'].Fill(value, -weight*QCD_weight)
                    histDict['QCD_C_for_A'].Fill(value, -weight*QCD_weight)
                    if iCategory != 'WJets':
                        histDict['WJets_OScontrol'].Fill(value, -weight)  
                else:
                    histDict['QCD_C'].Fill(value, weight*QCD_weight)
                    histDict['QCD_C_for_A'].Fill(value, weight*QCD_weight)
                    histDict['WJets_OScontrol'].Fill(value, weight)
            #region D
            if regionSelection(tree, FS, "SScontrol", plots_cfg.scanRange[0], plots_cfg.scanRange[1]):
                if not isData:
                    histDict['QCD_D'].Fill(value, -weight*QCD_weight)
                    histDict['QCD_D_for_C'].Fill(value, -weight*QCD_weight)
                    histDict['QCD_D_for_A'].Fill(value, -weight*QCD_weight)
                else:
                    histDict['QCD_D'].Fill(value, weight*QCD_weight)
                    histDict['QCD_D_for_C'].Fill(value, weight*QCD_weight)
                    histDict['QCD_D_for_A'].Fill(value, weight*QCD_weight)
            #highMT signal region 
            if regionSelection(tree, FS, "OSsignal", plots_cfg.scanRange[0], plots_cfg.scanRange[1], True):
                if not isData:
                    if iCategory != 'WJets':
                        histDict['WJets_A_'].Fill(value, -weight)
                    else:
                        histDict['WJets_MC_A_'].Fill(value, weight)
                else:
                    histDict['WJets_A_'].Fill(value, weight)

            #highMT C region 
            if regionSelection(tree, FS, "OScontrol", plots_cfg.scanRange[0], plots_cfg.scanRange[1], True):
                if not isData:
                    histDict['QCD_C_for_A_'].Fill(value, -weight*QCD_weight)
                else:
                    histDict['QCD_C_for_A_'].Fill(value, weight*QCD_weight)

    print iCategory, tmpHist.Integral(0, len(varBins)+1)
    histDict[iCategory].Add(tmpHist)            

    del tmpHist

    if options.saveHisto:
        oFile = r.TFile('/user_data/zmao/ZPrimeHistos/%s/%s_%s.root' %(FS, iSample[iSample.rfind('/'): iSample.rfind('_SYNC')], varName),"recreate")
        oFile.cd()
        tmpHist_forROOTFile = fixNegativBins(tmpHist_forROOTFile)
        tmpHist_forROOTFile.Write()
        oFile.Close()
    del tmpHist_forROOTFile

    print ''
コード例 #30
0
    initEvents.Fill(name, tmpHist.GetBinContent(1))
    isData = False
    if 'data' in name:
        isData = True
    eventsSaved = 0.

    scale = xsValue/tmpHist.GetBinContent(1)*lumi

    if isData:
        xsValue = xsValue*tmpHist.GetBinContent(1)/lumi
    skip = 0
    trainedMassPoint = ifile[len(preFix0):len(preFix0)+3]
    if trainedMassPoint == '300' or trainedMassPoint == '350':
        skip = 1
    for i in range(0, total):
        tool.printProcessStatus(iCurrent=i+1, total=total, processName = 'Looping sample [%s_%s]' %(name, trainedMassPoint))
        iTree.GetEntry(i)
        if trainedMassPoint == '260':
            BDT_260[0] = iTree.BDT_both
            if passCut(iTree, 'OSrelaxedbTag') and (not ("H2hh" in name)):
                if isData:
                    scaleBDT_260.Fill(iTree.BDT_both, iTree.triggerEff)
                    scaleSVMass.Fill(iTree.svMass.at(0), iTree.triggerEff)
                    scaleMJJReg.Fill(iTree.mJJReg, iTree.triggerEff)
                else:
                    scaleBDTMC_260.Fill(iTree.BDT_both, iTree.triggerEff*scale)
                    scaleSVMassMC.Fill(iTree.svMass.at(0), iTree.triggerEff*scale)
                    scaleMJJRegMC.Fill(iTree.mJJReg, iTree.triggerEff*scale)
            if not passCut(iTree, option):
                continue
            mJJReg[0] = iTree.mJJReg
コード例 #31
0
def getPtDistribution(file, hist, hist2 = None, hist3 = None, jetPt = 0, type ='central', Print = False, counter = False):
    f = r.TFile(file)
    tree = f.Get("Events")
    nEntries = tree.GetEntries()

    if Print:
        output = open('evtDump.txt', "w")  #opens & write the file
        output2 = open('matched.txt', "w")  #opens & write the file

    totalTaus = 0
    foundMatch = 0
    if counter:
        passed_30 = 0.0
        passed_35 = 0.0
        total = 0.0

    for i in range(nEntries):
#     for i in range(500):
        tool.printProcessStatus(i, nEntries, processName = 'Looping %s' %file, iPrevious = i-1)
        tree.GetEntry(i)

        #loop over pat taus in an event
        nTaus = (tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO).size()
        nJet = (tree.l1extraL1JetParticles_l1extraParticles_Central_RECO).size()

        totalTaus += nTaus

        if Print and i < 20:
            output.writelines('nTaus: %i ----------------\n' %nTaus)
            for j in range(nTaus):
                output.writelines('pt: %.2f, eta: %.2f, phi: %.2f\n' %((tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO).at(j).pt(),
                                                                    (tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO).at(j).eta(),
                                                                    (tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO).at(j).phi()))

            output.writelines('nJets: %i ----------------\n' %nJet)
            for j in range(nJet):
                output.writelines('pt: %.2f, eta: %.2f, phi: %.2f\n' %((tree.l1extraL1JetParticles_l1extraParticles_Central_RECO).at(j).pt(),
                                                                     (tree.l1extraL1JetParticles_l1extraParticles_Central_RECO).at(j).eta(),
                                                                     (tree.l1extraL1JetParticles_l1extraParticles_Central_RECO).at(j).phi()))
            output.writelines('-------------------------------------\n')
            
        failed = False
        Found = False
        foundJetPt = 0.0

        if jetPt > 5.0:
            failed = True
            if type == 'central':
                if nJet != 0:
                    for j in range(nJet):
                        pt = (tree.l1extraL1JetParticles_l1extraParticles_Central_RECO).at(j).pt()
                        eta = (tree.l1extraL1JetParticles_l1extraParticles_Central_RECO).at(j).eta()
                        phi = (tree.l1extraL1JetParticles_l1extraParticles_Central_RECO).at(j).phi()
                        found = False
                        if nTaus != 0:
                            for k in range(nTaus):
                                if eta == (tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO).at(k).eta():
                                    if phi == (tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO).at(k).phi():
                                        found = True
                        if not found and (pt > jetPt):
                            failed = False
                            foundJetPt = pt
                            break
                        if found:
                            foundMatch += 1
                            Found = True

        if Found and Print:
            output2.writelines('nTaus: %i ----------------\n' %nTaus)
            for j in range(nTaus):
                output2.writelines('pt: %.2f, eta: %.2f, phi: %.2f\n' %((tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO).at(j).pt(),
                                                                    (tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO).at(j).eta(),
                                                                    (tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO).at(j).phi()))

            output2.writelines('nJets: %i ----------------\n' %nJet)
            for j in range(nJet):
                output2.writelines('pt: %.2f, eta: %.2f, phi: %.2f\n' %((tree.l1extraL1JetParticles_l1extraParticles_Central_RECO).at(j).pt(),
                                                                     (tree.l1extraL1JetParticles_l1extraParticles_Central_RECO).at(j).eta(),
                                                                     (tree.l1extraL1JetParticles_l1extraParticles_Central_RECO).at(j).phi()))
            output2.writelines('-------------------------------------\n')

        weight = (tree.GenEventInfoProduct_generator__SIM).weights()[0]
        if hist2 != None:
            if (tree.GenEventInfoProduct_generator__SIM).hasBinningValues():
                hist2.Fill(200000.0*math.pow((tree.GenEventInfoProduct_generator__SIM).binningValues()[0], -4.5), (tree.GenEventInfoProduct_generator__SIM).weights()[0])
                if hist3 != None:
                    hist3.Fill((tree.GenEventInfoProduct_generator__SIM).binningValues()[0], (tree.GenEventInfoProduct_generator__SIM).weights()[0])

        xValue = foundJetPt            
        if (nTaus != 0):
            xValue = (tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO).at(0).pt()
        else:
            xValue = -1
        if nTaus < 2:
            yValue = -1
        else:
            yValue = (tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO).at(1).pt()

#             print xValue, yValue, weight
        if not failed:
            hist.Fill(xValue, yValue, weight)
        else:
            hist.Fill(-1, -1, weight)

        if counter:
            total += weight
            if (yValue >= 40.0) or ((yValue > 35.0) and (foundJetPt > 30.0)):
                passed_35 += weight
            if (yValue >= 40.0) or ((yValue > 30.0) and (foundJetPt > 30.0)):
                passed_30 += weight

    if Print:
        output.close()
        output2.writelines('totalTaus: %i, foundMatch: %i' %(totalTaus,foundMatch))
        output2.close()


    if counter:
        if hist2 != None:
            print ''
            print 'pass_30: %.8f, %.8f' %(1.0 - passed_30/total, passed_30/total)
            print 'pass_35: %.8f, %.8f' %(1.0 - passed_35/total, passed_35/total)
        else:
            print ''
            print 'pass_30: %.8f' %(passed_30/total)
            print 'pass_35: %.8f' %(passed_35/total)

    print ''

    if hist2 == None:
        return hist
    elif hist3 == None:
        return hist, hist2
    else:
        return hist, hist2, hist3
コード例 #32
0
def checkSyncDev(options):
    location1 = options.location1
    tree1 = options.tree1
    name1 = options.name1
    location2 = options.location2
    tree2 = options.tree2
    name2 = options.name2

    if options.switch:
        location2 = options.location1
        tree2 = options.tree1
        name2 = options.name1
        location1 = options.location2
        tree1 = options.tree2
        name1 = options.name2

    eventNumber = int(options.eventNumber)
    iFile1 = r.TFile(location1)

    iTree1 = iFile1.Get(tree1)
    total1 = iTree1.GetEntries()

    iFile2 = r.TFile(location2)
    iTree2 = iFile2.Get(tree2)
    total2 = iTree2.GetEntries()

    mvaMet1 = r.TH1F('mvaMet1', '', 60, 0, 6)
    mvaMet2 = r.TH1F('mvaMet2', '', 60, 0, 6)

    varsDict1 = {}
    varsDict2 = {}

    for i in range(total1):
        tool.printProcessStatus(i, total1, 'reading file1', i - 1)
        iTree1.GetEntry(i)
        if int(options.nTauPairs):
            varsDict1 = addVars2(iTree1, varsDict1)
        else:
            varsDict1 = addVars(iTree1, varsDict1)
    print ''
    for i in range(total2):
        tool.printProcessStatus(i, total2, 'reading file2', i - 1)
        iTree2.GetEntry(i)
        if int(options.nTauPairs):
            varsDict2 = addVars2(iTree2, varsDict2)
        else:
            varsDict2 = addVars(iTree2, varsDict2)
    print ''
    indexNotFound1 = []
    indexFound2 = 0
    matchedEvents = 0
    sameEvents = 0
    differentEvents = 0
    counter = 0
    for iKey in varsDict1.keys():
        tool.printProcessStatus(counter, total1, 'looping through',
                                counter - 1)

        if iKey in varsDict2 and iKey[0] == eventNumber:
            diff = (varsDict1[iKey][3] + 1.0) - (varsDict2[iKey][3] + 1.0)
            printInfo(name1, varsDict1[iKey], name2, varsDict2[iKey])
        elif iKey in varsDict2 and eventNumber == -1:
            matchedEvents += 1
            diff = (varsDict1[iKey][3] + 1.0) - (varsDict2[iKey][3] + 1.0)
            indexFound2 += 1
            if diff != 0.0 and (options.style == 'diff'
                                or options.style == 'all'):
                printInfo(name1, varsDict1[iKey], name2, varsDict2[iKey])
                differentEvents += 1
            elif diff == 0 and (options.style == 'same'
                                or options.style == 'all'):
                printInfo(name1, varsDict1[iKey], name2, varsDict2[iKey])
                sameEvents += 1

            else:
                indexNotFound1.append(iKey)
        counter += 1
    print ''
    if options.style == 'all' or options.style == 'miss':
        print 'Extra events in %s **********' % name1
        for iKey in indexNotFound1:
            printSingleInfo(name1, varsDict1[iKey])
        print ' '


#         print 'Extra events in %s **********' %options.name2
#         for i_2 in range(total2):
#             if i_2 not in indexFound2:
#                 printSingleInfo(options.name2, varsList2[i_2])

    print '%s %i events' % (name1, total1)
    print '%s %i events' % (name2, total2)
    if options.style == 'diff' and not differentEvents:
        sameEvents = matchedEvents - differentEvents
    if options.style == 'same' and not sameEvents:
        differentEvents = matchedEvents - sameEvents
    if options.style == 'same' or options.style == 'diff':
        print "Out of %i matching events, %s%i\033[0m events with same MVAMet, %s%i\033[0m events with different MVAMet" % (
            matchedEvents, bcolors.OKGREEN, sameEvents, bcolors.FAIL,
            differentEvents)
    if options.style == 'miss':
        print "%s has an extra of %i events" % (name1, len(indexNotFound1))
        print "%s has an extra of %i events" % (name2, total2 - indexFound2)

    if eventNumber == -1:
        return 1
    else:
        print "Event %i not found!" % eventNumber
        return 0

    c.Print('%s' % psfile)
    c.Close()
コード例 #33
0
ファイル: makeWhole.py プロジェクト: zaixingmao/H2hh2bbTauTau
    iTree = iFile.Get('eventTree')
    total = iTree.GetEntries()
    tmpHist = iFile.Get('preselection')
    initEvents.Fill(name, tmpHist.GetBinContent(1))
    isData = False
    if 'data' in name:
        isData = True
    eventsSaved = 0.

    scale = xsValue/tmpHist.GetBinContent(1)*lumi

    if isData:
        xsValue = xsValue*tmpHist.GetBinContent(1)/lumi

    for i in range(0, total):
        tool.printProcessStatus(iCurrent=i+1, total=total, processName = 'Looping sample [%s]' %name)
        iTree.GetEntry(i)
        #Fill Histograms
        if passCut(iTree, 'OSrelaxedbTag') and (not ("H2hh" in name)):
            if isData:
                scaleSVMass.Fill(iTree.svMass.at(0), iTree.triggerEff)
                scaleMJJReg.Fill(iTree.mJJReg, iTree.triggerEff)
                scaleBDT.Fill(iTree.BDT_both, iTree.triggerEff)
            else:
                scaleSVMassMC.Fill(iTree.svMass.at(0), iTree.triggerEff*scale)
                scaleMJJRegMC.Fill(iTree.mJJReg, iTree.triggerEff*scale)
                scaleBDTMC.Fill(iTree.BDT_both, iTree.triggerEff*scale)

        if not passCut(iTree, option):
            continue
        BDT[0] = iTree.BDT_both
コード例 #34
0
def loop_one_sample(iSample, iLocation, iCat, iFS):
    print 'combininig sample [%s] for datacard' %(iSample)
    if 'data' in iSample:
        isData = True
    else:
        isData = False
    if 'emb' in iSample:
        isEmbedded = True
    else:
        isEmbedded = False
    if ('H2hh' in iSample) or ('ggH' in iSample) or ('Zprime' in iSample):
        isSignal = True
    else:
        isSignal = False

    iFile = r.TFile(iLocation)
    iTree = iFile.Get("Ntuple")
    nEntries = iTree.GetEntries()
    iTree.SetBranchStatus("*",1)
    iTree.SetBranchStatus("sampleName",0)

    dicToFill = {}
    for iVar in defaultOrder:
        dicToFill[iVar] = 0

    if isSignal:
        dicToFill["type"] = 1
    met = lvClass()

    outputName = "%s.csv" %iSample
    oFile = open(outputName, 'w')

    for iEntry in range(nEntries):
        iTree.GetEntry(iEntry)
        tool.printProcessStatus(iEntry, nEntries, 'looping over file %s' %(iSample), iEntry-1)
        uncWeight = 1.0
        region = 'none'
        if options.sys == 'jetECUp' and not isData:
            met.SetCoordinates(iTree.pfMet_jesUp_Et, 0.0, iTree.pfMet_jesUp_Phi, 0)
        elif options.sys == 'jetECDown' and not isData:
            met.SetCoordinates(iTree.pfMet_jesDown_Et, 0.0, iTree.pfMet_jesDown_Phi, 0)
        elif (options.sys == 'tauECUp' or options.sys == 'tauECDown') and (not isData) and iTree.tIsTauh:
            met.SetCoordinates(iTree.pfMetEt, 0.0, iTree.pfMetPhi, 0)
            if iTree.pt_2 - iTree.tPt > 0:
                deltaTauES.SetCoordinates(abs(iTree.pt_2 - iTree.tPt), 0.0, -iTree.tPhi, 0)
            else:
                deltaTauES.SetCoordinates(abs(iTree.pt_2 - iTree.tPt), 0.0, iTree.tPhi, 0)
            met = met + deltaTauES
        else:
            met.SetCoordinates(iTree.pfMetEt, 0.0, iTree.pfMetPhi, 0)

        l1.SetCoordinates(iTree.pt_1, iTree.eta_1, iTree.phi_1, iTree.m_1)
        l2.SetCoordinates(iTree.pt_2, iTree.eta_2, iTree.phi_2, iTree.m_2)

        if not plots.passCut(iTree, iFS, isData, l1, l2, met, options.sys):
            continue
        if options.method != 'SS' and iTree.q_1 == iTree.q_2 and (not options.dataDrivenWJets):
            continue

        if plots.regionSelection(iTree, iFS, "signal", options.method, plots_cfg.scanRange[0], plots_cfg.scanRange[1]):
            if iTree.q_1 == iTree.q_2: #we don't need region B
                continue
            region = 'A'

        elif plots.regionSelection(iTree, iFS, "control", options.method, plots_cfg.scanRange[0], plots_cfg.scanRange[1]):
            if isSignal:
                continue
            if options.dataDrivenWJets and iTree.q_1 == iTree.q_2: #D region
                region = 'D'

            elif options.dataDrivenWJets and iTree.q_1 == -iTree.q_2: #C region
                if "WJets" in iSample:
                    continue
                region = 'C'

            elif (not options.dataDrivenWJets) and iTree.q_1 == -iTree.q_2: #C region
                region = 'C'
            else:
                continue
        else:
            continue

        dicToFill["met"] = met.pt()
        dicToFill["pZetaCut"] = getattr(iTree, "%s_%s_PZeta" %(iFS[0], iFS[1])) - 3.1*getattr(iTree, "%s_%s_PZetaVis" %(iFS[0], iFS[1]))
        dicToFill["cosDPhi"] = math.cos(iTree.phi_1 - iTree.phi_2)
        dicToFill["m_eff"] = (l1 + l2 + met).mass()

        if region == 'none':
            print "ERROR!!!!!"

        if region == "A":
            writeToFile(dicToFill, oFile)
        if options.dataDrivenWJets and region == "D": #get QCD in C region
            writeToFile(dicToFill, oFile) 
        elif options.dataDrivenWJets and region == "C":
            writeToFile(dicToFill, oFile)
        elif (not options.dataDrivenWJets) and (region == 'C'):
            writeToFile(dicToFill, oFile)
コード例 #35
0
def l2MYieldCalculator(sample, massWindow, pairOption = 'iso', nBtag = '', ZLL = False):

    yieldForMediumCat = {}
    yieldForLooseCat = {}
    eventCounterForMediumCat = {}
    eventCounterForLooseCat = {}

    iFile =  r.TFile(sample)
    iTree = iFile.Get('eventTree')
    yieldForMediumCat['1M'] = 0.0
    yieldForMediumCat['2M'] = 0.0
    yieldForLooseCat['1L'] = 0.0
    yieldForLooseCat['2L'] = 0.0
    eventCounterForMediumCat['1M'] = 0.0
    eventCounterForMediumCat['2M'] = 0.0
    eventCounterForLooseCat['1L'] = 0.0
    eventCounterForLooseCat['2L'] = 0.0

    total = iTree.GetEntries()

    for i in range(0, total):
        tool.printProcessStatus(iCurrent=i+1, total=total, processName = 'Looping sample [%s]' %sample, iPrevious=i)
        iTree.GetEntry(i)
            
        #get the right pair of taus based on isoMin or ptMax
        if (iTree.nElectrons > 0 or iTree.nMuons > 0):
            continue
        if not makeWholeTools2.passJetTrigger(iTree):
            continue

        if ZLL and iTree.ZLL == 0:
            continue
        #get event category
        signSelection, isoSelection, bTagSelection = makeWholeTools2.findCategory(tree = iTree, 
                                                                                  iso = makeWholeSample_cfg.iso, 
                                                                                  option = pairOption,
                                                                                  isData = False,
                                                                                  relaxedRegionOption = makeWholeSample_cfg.Relax,
                                                                                  isEmbed = False,
                                                                                  usePassJetTrigger = makeWholeSample_cfg.usePassJetTrigger,
                                                                                  nBtag = nBtag)

        if signSelection == None or isoSelection == None:
            continue
        looseTag, mediumTag = getRightBTagCatName(bTagSelection)

        if  massWindow and not makeWholeTools2.passCut(iTree, pairOption):
            continue
        #calculate category yield
        if (signSelection == "OS") and (isoSelection == "Tight") and (mediumTag != '0M'):
            yieldForMediumCat[mediumTag] += iTree.triggerEff*iTree.xs*lumi*iTree.PUWeight/iTree.initEvents
            eventCounterForMediumCat[mediumTag] += 1

        #calculate loose cat yield for embed samples
        if (signSelection == "OS") and (isoSelection == "Tight") and (looseTag != '0L'):
            yieldForLooseCat[looseTag] += iTree.triggerEff*iTree.xs*lumi*iTree.PUWeight/iTree.initEvents
            eventCounterForLooseCat[looseTag] += 1
    print ''


    scaleFactor_1M = yieldForMediumCat['1M']/yieldForLooseCat['1L']
    scaleFactor_2M = yieldForMediumCat['2M']/yieldForLooseCat['2L']

    print '[%s] (1L): %.2f  %.0f'%(sample, yieldForLooseCat['1L'], eventCounterForLooseCat['1L'])
    print '[%s] (2L): %.2f  %.0f'%(sample, yieldForLooseCat['2L'], eventCounterForLooseCat['2L'])
    print '[%s] (1M): %.2f  %.0f'%(sample, yieldForMediumCat['1M'], eventCounterForMediumCat['1M'])
    print '[%s] (2M): %.2f  %.0f'%(sample, yieldForMediumCat['2M'], eventCounterForMediumCat['2M'])

    unc_1M = calcSysUncSingle(yieldForMediumCat['1M'], eventCounterForMediumCat['1M'])
    unc_2M = calcSysUncSingle(yieldForMediumCat['2M'], eventCounterForMediumCat['2M'])

    print '1M: %.2f +/- %.1f%%' %(yieldForMediumCat['1M'], unc_1M*100/yieldForMediumCat['1M'])
    print '2M: %.2f +/- %.1f%%' %(yieldForMediumCat['2M'], unc_2M*100/yieldForMediumCat['2M'])

    return yieldForMediumCat['1M'], yieldForMediumCat['2M']
コード例 #36
0
        pZV_new2[0] = iChain.pZV/fullMass[0]

        dRTauTau[0] = r.Math.VectorUtil.DeltaR(tau1, tau2)
        dRhh[0] = r.Math.VectorUtil.DeltaR(bb, sv4Vec)

        metTau1DPhi[0], metTau2DPhi[0], metJ1DPhi[0], metJ2DPhi[0], metTauPairDPhi[0], metJetPairDPhi[0], metSvTauPairDPhi[0] = calcdPhiMetValues(iChain.phi1.at(0), iChain.phi2.at(0), CSVJet1.phi(), CSVJet2.phi(), iChain.metphi.at(0), (tau1+tau2).phi(), bb.phi(), iChain.svPhi.at(0))

        eff1 = calcTrigOneTauEff(eta=iChain.eta1.at(0), pt=iChain.pt1.at(0), data = True, fitStart=25)
        eff2 = calcTrigOneTauEff(eta=iChain.eta2.at(0), pt=iChain.pt2.at(0), data = True, fitStart=25)

        triggerEff1[0] = eff1
        triggerEff2[0] = eff2        
        triggerEff[0] = eff1*eff2
        if isData:
            triggerEff[0] = 1
            triggerEff1[0] = 1
            triggerEff2[0] = 1

        #For Kinematic Fit
        chi2KinFit[0], fMassKinFit[0] = kinfit.fit(iChain, CSVJet1, CSVJet2)

        iTree.Fill()
        counter += 1
        tool.printProcessStatus(iEntry, nEntries, 'Saving to file %s.root' %(iSample))
    print '  -- saved %d events' %(counter)
    tool.addEventsCount2Hist(hist = cutFlow, count = counter, labelName = 'myCut')
    iFile.cd()
    cutFlow.Write()
    iTree.Write()
    iFile.Close()
コード例 #37
0
def makeTestOnly(iLocation, iMass, iFileList, shift):
    ifile = r.TFile(iLocation)
    iTestTree = ifile.Get('TestTree')
    totalTest = iTestTree.GetEntries()
    iTrainTree = ifile.Get('TrainTree')
    totalTrain = iTrainTree.GetEntries()
    EventList = []
    EventList2 = []
    sampleName2 = array('i', [0])
    category2 = array('i', [0])
    svMass1 = array('f', [0.])
    met1 = array('f', [0.])
    sampleNameList = []
    category_char = bytearray(30)

    for i in range(totalTest):
        tool.printProcessStatus(iCurrent=i + 1,
                                total=totalTest,
                                processName='Looping sample [%s]' % iLocation)
        iTestTree.GetEntry(i)
        tmpSampleName = tool.nameEnDecoder(iTestTree.sampleName2, 'decode')
        if 'data' not in tmpSampleName:
            #             EventList.append((int(iTestTree.EVENT), tmpSampleName))
            EventList.append(fingerPrintSet(iTestTree, tmpSampleName, shift))
        if tmpSampleName not in sampleNameList:
            sampleNameList.append(tmpSampleName)
    print ' --- events in test tree: %i' % len(EventList)
    if not passCheckReoccur(EventList):
        return 0

    for i in range(totalTrain):
        tool.printProcessStatus(iCurrent=i + 1,
                                total=totalTrain,
                                processName='Looping sample [%s]' % iLocation)
        iTrainTree.GetEntry(i)
        tmpSampleName = tool.nameEnDecoder(iTrainTree.sampleName2, 'decode')
        if tmpSampleName not in sampleNameList:
            sampleNameList.append(tmpSampleName)
        if 'data' not in tmpSampleName:
            EventList2.append(fingerPrintSet(iTrainTree, tmpSampleName, shift))
    print ' --- events in train tree: %i' % len(EventList2)
    if not passCheckReoccur(EventList2):
        return 0

    if not passCheckSame(EventList, EventList2):
        return 0

    for iFile in iFileList:
        tmpFile = r.TFile(iFile)
        tmpTree = tmpFile.Get('eventTree')
        oFileName = iFile[0:iFile.find('.root')]
        oFileName += '_%s_testOnly.root' % iMass
        oFile = r.TFile(oFileName, 'recreate')
        oTree = tmpTree.CloneTree(0)
        #         oTree.Branch("sampleName2", sampleName2, "sampleName2/I")
        #         oTree.Branch("category2", category2, "category2/I")
        #         oTree.Branch("Category", category_char, "Category[31]/C")
        #         oTree.Branch("svMass1", svMass1, "svMass1/F")
        #         oTree.Branch("met1", met1, "met1/F")

        total = tmpTree.GetEntries()
        counter = 0
        for i in range(total):
            tool.printProcessStatus(iCurrent=i + 1,
                                    total=total,
                                    processName='Looping sample [%s]' % iFile)
            tmpTree.GetEntry(i)
            if '_semi' in tmpTree.sampleName:
                tmpName = tmpTree.sampleName[0:tmpTree.sampleName.find('_semi'
                                                                       ) + 5]
            elif '_' in tmpTree.sampleName:
                tmpName = tmpTree.sampleName[0:tmpTree.sampleName.find('_')]
            else:
                tmpName = tmpTree.sampleName
            if tmpName not in sampleNameList:
                continue
            sampleName2[0] = tool.nameEnDecoder(tmpName, 'encode')
            svMass1[0] = tmpTree.svMass.at(0)
            met1[0] = tmpTree.met.at(0)

            category2[0] = 0
            if tmpTree.category == '1M1NonM':
                category_char[:31] = '1M'
            else:
                category_char[:31] = tmpTree.category
            if not passCut(tmpTree):
                continue
            if fingerPrintSet(tmpTree, tmpName, shift) in EventList:
                oTree.Fill()
                counter += 1
            elif fingerPrintSet(tmpTree, tmpName, shift) not in EventList2:
                oTree.Fill()
                counter += 1

        print ' --- saved %i' % counter
        oFile.cd()
        oTree.Write()
        oFile.Close()
コード例 #38
0
def loop_one_sample(iSample, iLocation, iCat, iFS):
    print 'combininig sample [%s] for datacard' % (iSample)
    if 'data' in iSample:
        isData = True
    else:
        isData = False
    if 'emb' in iSample:
        isEmbedded = True
    else:
        isEmbedded = False
    if ('H2hh' in iSample) or ('ggH' in iSample) or ('Zprime' in iSample):
        isSignal = True
    else:
        isSignal = False

    iFile = r.TFile(iLocation)
    iTree = iFile.Get("Ntuple")
    nEntries = iTree.GetEntries()
    iTree.SetBranchStatus("*", 1)
    iTree.SetBranchStatus("sampleName", 0)

    dicToFill = {}
    for iVar in defaultOrder:
        dicToFill[iVar] = 0

    if isSignal:
        dicToFill["type"] = 1
    met = lvClass()

    outputName = "%s.csv" % iSample
    oFile = open(outputName, 'w')

    for iEntry in range(nEntries):
        iTree.GetEntry(iEntry)
        tool.printProcessStatus(iEntry, nEntries,
                                'looping over file %s' % (iSample), iEntry - 1)
        uncWeight = 1.0
        region = 'none'
        if options.sys == 'jetECUp' and not isData:
            met.SetCoordinates(iTree.pfMet_jesUp_Et, 0.0,
                               iTree.pfMet_jesUp_Phi, 0)
        elif options.sys == 'jetECDown' and not isData:
            met.SetCoordinates(iTree.pfMet_jesDown_Et, 0.0,
                               iTree.pfMet_jesDown_Phi, 0)
        elif (options.sys == 'tauECUp' or options.sys
              == 'tauECDown') and (not isData) and iTree.tIsTauh:
            met.SetCoordinates(iTree.pfMetEt, 0.0, iTree.pfMetPhi, 0)
            if iTree.pt_2 - iTree.tPt > 0:
                deltaTauES.SetCoordinates(abs(iTree.pt_2 - iTree.tPt), 0.0,
                                          -iTree.tPhi, 0)
            else:
                deltaTauES.SetCoordinates(abs(iTree.pt_2 - iTree.tPt), 0.0,
                                          iTree.tPhi, 0)
            met = met + deltaTauES
        else:
            met.SetCoordinates(iTree.pfMetEt, 0.0, iTree.pfMetPhi, 0)

        l1.SetCoordinates(iTree.pt_1, iTree.eta_1, iTree.phi_1, iTree.m_1)
        l2.SetCoordinates(iTree.pt_2, iTree.eta_2, iTree.phi_2, iTree.m_2)

        if not plots.passCut(iTree, iFS, isData, l1, l2, met, options.sys):
            continue
        if options.method != 'SS' and iTree.q_1 == iTree.q_2 and (
                not options.dataDrivenWJets):
            continue

        if plots.regionSelection(iTree, iFS, "signal", options.method,
                                 plots_cfg.scanRange[0],
                                 plots_cfg.scanRange[1]):
            if iTree.q_1 == iTree.q_2:  #we don't need region B
                continue
            region = 'A'

        elif plots.regionSelection(iTree, iFS, "control", options.method,
                                   plots_cfg.scanRange[0],
                                   plots_cfg.scanRange[1]):
            if isSignal:
                continue
            if options.dataDrivenWJets and iTree.q_1 == iTree.q_2:  #D region
                region = 'D'

            elif options.dataDrivenWJets and iTree.q_1 == -iTree.q_2:  #C region
                if "WJets" in iSample:
                    continue
                region = 'C'

            elif (not options.dataDrivenWJets
                  ) and iTree.q_1 == -iTree.q_2:  #C region
                region = 'C'
            else:
                continue
        else:
            continue

        dicToFill["met"] = met.pt()
        dicToFill["pZetaCut"] = getattr(iTree, "%s_%s_PZeta" %
                                        (iFS[0], iFS[1])) - 3.1 * getattr(
                                            iTree, "%s_%s_PZetaVis" %
                                            (iFS[0], iFS[1]))
        dicToFill["cosDPhi"] = math.cos(iTree.phi_1 - iTree.phi_2)
        dicToFill["m_eff"] = (l1 + l2 + met).mass()

        if region == 'none':
            print "ERROR!!!!!"

        if region == "A":
            writeToFile(dicToFill, oFile)
        if options.dataDrivenWJets and region == "D":  #get QCD in C region
            writeToFile(dicToFill, oFile)
        elif options.dataDrivenWJets and region == "C":
            writeToFile(dicToFill, oFile)
        elif (not options.dataDrivenWJets) and (region == 'C'):
            writeToFile(dicToFill, oFile)
コード例 #39
0
def yieldCalculator(dy_mc, tt_full_mc, dy_embed, tt_embed, massWindow, pairOption = 'iso', nBtag = '', doDraw = False):

    yieldForMediumCat = {}
    eventCounterForMediumCat = {}
    yieldForLooseCat = {}
    eventCounterForLooseCat = {}
    inclusiveYields = {}
    eventCounterForInclusive = {}

    bins = [19, 225, 700]
    dy_embed_1M = r.TH1F('dy_embed_1M', '', bins[0], bins[1], bins[2])
    dy_embed_2M = r.TH1F('dy_embed_2M', '', bins[0], bins[1], bins[2])
    tt_embed_1M = r.TH1F('tt_embed_1M', '', bins[0], bins[1], bins[2])
    tt_embed_2M = r.TH1F('tt_embed_2M', '', bins[0], bins[1], bins[2])

    fileList = [('DY_inclusive', dy_mc), ('tt_inclusive', tt_full_mc), ('DY_embed', dy_embed), ('tt_embed', tt_embed)]

    for indexFile in range(len(fileList)):
        name = fileList[indexFile][0]
        iFile =  r.TFile(fileList[indexFile][1])
        iTree = iFile.Get('eventTree')
        yieldForMediumCat[name+'_1M'] = 0.0
        yieldForMediumCat[name+'_2M'] = 0.0
        yieldForLooseCat[name+'_1L'] = 0.0
        yieldForLooseCat[name+'_2L'] = 0.0
        eventCounterForInclusive[name] = 0
        eventCounterForMediumCat[name+'_1M'] = 0
        eventCounterForMediumCat[name+'_2M'] = 0
        eventCounterForLooseCat[name+'_1L'] = 0
        eventCounterForLooseCat[name+'_2L'] = 0
        total = iTree.GetEntries()
        inclusiveYields[name] = 0.0
        counter = 0
        counter_0 = 0
        isEmbed = False
        isData = False
        if 'emb' in name:
            isEmbed = True
        if name == 'DY_embed':
            isData = True

        for i in range(0, total):
            tool.printProcessStatus(iCurrent=i+1, total=total, processName = 'Looping sample [%s]' %name, iPrevious=i)
            #Fill Histograms
            iTree.GetEntry(i)

            #get the right pair of taus based on isoMin or ptMax
            if (iTree.nElectrons > 0 or iTree.nMuons > 0):
                continue

            #get event category
            signSelection, isoSelection, bTagSelection = makeWholeTools2.findCategory(tree = iTree, 
                                                                                      iso = makeWholeSample_cfg.iso, 
                                                                                      option = pairOption,
                                                                                      isData = isData,
                                                                                      relaxedRegionOption = makeWholeSample_cfg.Relax,
                                                                                      isEmbed = isEmbed,
                                                                                      usePassJetTrigger = makeWholeSample_cfg.usePassJetTrigger,
                                                                                      nBtag = nBtag)
            if signSelection == None or isoSelection == None or bTagSelection == None:
                continue
            looseTag, mediumTag = getRightBTagCatName(bTagSelection)

            if iTree.HLT_Any == 0:
                continue
            if iTree.ZTT == 0:
                continue
            if 'tt' not in name:
                tmpEventYield = iTree.triggerEff*iTree.decayModeWeight
            else:
                tmpEventYield = iTree.triggerEff

            if  massWindow and not makeWholeTools2.passCut(iTree, pairOption):
                continue

            #calculate inclusiveYield
            if (signSelection == "OS") and (isoSelection == "Tight"):
                eventCounterForInclusive[name] += 1
                if 'data' in iTree.sampleName:
                    inclusiveYields[name] += tmpEventYield*iTree.embeddedWeight
                elif isEmbed:
                    inclusiveYields[name] += iTree.triggerEff*iTree.xs*0.983*(lumi/tt_semi_InitEvents)*iTree.embeddedWeight*iTree.PUWeight
                else:
                    if not makeWholeTools2.passJetTrigger(iTree):
                        continue
                    inclusiveYields[name] += tmpEventYield*iTree.xs*lumi*iTree.PUWeight/(iTree.initEvents+0.0)
            else:
                continue
                
            fillValue = iTree.fMassKinFit

            #calculate category yield
            if mediumTag != '0M':
                if isEmbed:
                    if 'data' in iTree.sampleName:
                        yieldForMediumCat["%s_%s" %(name, mediumTag)] += tmpEventYield*iTree.embeddedWeight
                        if mediumTag == '1M':
                            dy_embed_1M.Fill(fillValue, tmpEventYield*iTree.embeddedWeight)
                        else:
                            dy_embed_2M.Fill(fillValue, tmpEventYield*iTree.embeddedWeight)
                    else:
                        yieldForMediumCat["%s_%s" %(name, mediumTag)] += tmpEventYield*iTree.xs*0.983*(lumi/tt_semi_InitEvents)*iTree.embeddedWeight*iTree.PUWeight
                        if mediumTag == '1M':
                            tt_embed_1M.Fill(fillValue, tmpEventYield*iTree.xs*0.983*(lumi/tt_semi_InitEvents)*iTree.embeddedWeight*iTree.PUWeight)
                        else:
                            tt_embed_2M.Fill(fillValue, tmpEventYield*iTree.xs*0.983*(lumi/tt_semi_InitEvents)*iTree.embeddedWeight*iTree.PUWeight)

                else:
                    yieldForMediumCat["%s_%s" %(name, mediumTag)] += tmpEventYield*iTree.xs*lumi*iTree.PUWeight/iTree.initEvents
                eventCounterForMediumCat["%s_%s" %(name, mediumTag)] += 1


            #calculate loose cat yield for embed samples
            if isEmbed and (looseTag != '0L'):
                if 'data' in iTree.sampleName:
                    yieldForLooseCat["%s_%s" %(name, looseTag)] += tmpEventYield*iTree.embeddedWeight
                else:
                    yieldForLooseCat["%s_%s" %(name, looseTag)] += tmpEventYield*iTree.embeddedWeight*iTree.xs*0.983*lumi/tt_semi_InitEvents
                eventCounterForLooseCat["%s_%s" %(name, looseTag)] += 1

        print ''

        if isEmbed:
            print name
            print 'inclusive yield for %s: %.2f +/- %.2f' %(name, inclusiveYields[name], calcSysUncSingle(inclusiveYields[name], eventCounterForInclusive[name]))
            print '1-Medium %s yield: %.2f +/- %.2f \t events: %i' %(name, yieldForMediumCat[name+'_1M'], calcSysUncSingle(yieldForMediumCat[name+'_1M'], eventCounterForMediumCat[name+'_1M']), eventCounterForMediumCat[name+'_1M'])
            print '1-Loose %s yield: %.2f  +/- %.2f \t events: %i' %(name, yieldForLooseCat[name+'_1L'], calcSysUncSingle(yieldForLooseCat[name+'_1L'], eventCounterForLooseCat[name+'_1L']), eventCounterForLooseCat[name+'_1L'])
            print '2-Medium %s yield: %.2f +/- %.2f \t events: %i' %(name, yieldForMediumCat[name+'_2M'], calcSysUncSingle(yieldForMediumCat[name+'_2M'], eventCounterForMediumCat[name+'_2M']), eventCounterForMediumCat[name+'_2M'])
            print '2-Loose %s yield: %.2f +/- %.2f \t events: %i' %(name, yieldForLooseCat[name+'_2L'], calcSysUncSingle(yieldForLooseCat[name+'_2L'], eventCounterForLooseCat[name+'_2L']), eventCounterForLooseCat[name+'_2L'])

        else:
            print 'inclusive yield for %s: %.2f' %(name, inclusiveYields[name])

    delta_dy_inclusive = calcSysUncSingle(inclusiveYields['DY_embed'], eventCounterForInclusive['DY_embed'])
    delta_tt_inclusive = calcSysUncSingle(inclusiveYields['tt_embed'], eventCounterForInclusive['tt_embed'])
    delta_dy_1M = calcSysUncSingle(yieldForMediumCat['DY_embed_1M'], eventCounterForMediumCat['DY_embed_1M'])
    delta_tt_1M = calcSysUncSingle(yieldForMediumCat['tt_embed_1M'], eventCounterForMediumCat['tt_embed_1M'])
    delta_dy_2M = calcSysUncSingle(yieldForMediumCat['DY_embed_2M'], eventCounterForMediumCat['DY_embed_2M'])
    delta_tt_2M = calcSysUncSingle(yieldForMediumCat['tt_embed_2M'], eventCounterForMediumCat['tt_embed_2M'])

    sysUnc_1M = calcSysUnc(sf = (yieldForMediumCat['DY_embed_1M']-yieldForMediumCat['tt_embed_1M'])/(inclusiveYields['DY_embed'] - inclusiveYields['tt_embed']), 
                        numA = yieldForMediumCat['DY_embed_1M'], 
                        numB = yieldForMediumCat['tt_embed_1M'],
                        denomA = inclusiveYields['DY_embed'],
                        denomB = inclusiveYields['tt_embed'],
                        delta_numA = delta_dy_1M,
                        delta_numB = delta_tt_1M,
                        delta_denomA = delta_dy_inclusive,
                        delta_denomB = delta_tt_inclusive)

    sysUnc_2M = calcSysUnc(sf = (yieldForMediumCat['DY_embed_2M']-yieldForMediumCat['tt_embed_2M'])/(inclusiveYields['DY_embed'] - inclusiveYields['tt_embed']), 
                        numA = yieldForMediumCat['DY_embed_2M'], 
                        numB = yieldForMediumCat['tt_embed_2M'],
                        denomA = inclusiveYields['DY_embed'],
                        denomB = inclusiveYields['tt_embed'],
                        delta_numA = delta_dy_2M,
                        delta_numB = delta_tt_2M,
                        delta_denomA = delta_dy_inclusive,
                        delta_denomB = delta_tt_inclusive)

    sysUnc_xs_1M = calcSysUnc(sf = (yieldForMediumCat['DY_embed_1M']-yieldForMediumCat['tt_embed_1M'])/(inclusiveYields['DY_embed'] - inclusiveYields['tt_embed']), 
                        numA = yieldForMediumCat['DY_embed_1M'], 
                        numB = yieldForMediumCat['tt_embed_1M'],
                        denomA = inclusiveYields['DY_embed'],
                        denomB = inclusiveYields['tt_embed'],
                        delta_numA = 0,
                        delta_numB = yieldForMediumCat['tt_embed_1M']*0.1,
                        delta_denomA = 0,
                        delta_denomB = inclusiveYields['tt_embed']*0.1)

    sysUnc_xs_2M = calcSysUnc(sf = (yieldForMediumCat['DY_embed_2M']-yieldForMediumCat['tt_embed_2M'])/(inclusiveYields['DY_embed'] - inclusiveYields['tt_embed']), 
                        numA = yieldForMediumCat['DY_embed_2M'], 
                        numB = yieldForMediumCat['tt_embed_2M'],
                        denomA = inclusiveYields['DY_embed'],
                        denomB = inclusiveYields['tt_embed'],
                        delta_numA = 0,
                        delta_numB = yieldForMediumCat['tt_embed_2M']*0.1,
                        delta_denomA = 0,
                        delta_denomB = inclusiveYields['tt_embed']*0.1)

    preScaleFactor = inclusiveYields['DY_inclusive']/(inclusiveYields['DY_embed'] - inclusiveYields['tt_embed'])
    scaleFactor_1M = preScaleFactor*(yieldForMediumCat['DY_embed_1M']-yieldForMediumCat['tt_embed_1M'])
    scaleFactor_2M = preScaleFactor*(yieldForMediumCat['DY_embed_2M']-yieldForMediumCat['tt_embed_2M'])

    preScaleFactor2 = (inclusiveYields['DY_inclusive']+inclusiveYields['tt_inclusive'])/(inclusiveYields['DY_embed'])
    scaleFactor_1M2 = preScaleFactor2*(yieldForMediumCat['DY_embed_1M'])
    scaleFactor_2M2 = preScaleFactor2*(yieldForMediumCat['DY_embed_2M'])

    print ''
    print 'predicted DY in 1M: %.2fx(%.2f +/- %.2f - %.2f +/- %.2f)/(%.2f +/- %.2f - %.2f +/- %.2f) = %.2f +/- %.2f%% (statistical)' %(inclusiveYields['DY_inclusive'],
                                                                         yieldForMediumCat['DY_embed_1M'],
                                                                         calcSysUncSingle(yieldForMediumCat['DY_embed_1M'], eventCounterForMediumCat['DY_embed_1M']),
                                                                         yieldForMediumCat['tt_embed_1M'],
                                                                         calcSysUncSingle(yieldForMediumCat['tt_embed_1M'], eventCounterForMediumCat['tt_embed_1M']),
                                                                         inclusiveYields['DY_embed'],
                                                                         calcSysUncSingle(inclusiveYields['DY_embed'], eventCounterForInclusive['DY_embed']),
                                                                         inclusiveYields['tt_embed'],
                                                                         calcSysUncSingle(inclusiveYields['tt_embed'], eventCounterForInclusive['tt_embed']),
                                                                         scaleFactor_1M,
                                                                         sysUnc_1M*inclusiveYields['DY_inclusive']/scaleFactor_1M*100
                                                                        )
    print 'predicted DY in 2M: %.2fx(%.2f +/- %.2f - %.2f +/- %.2f)/(%.2f +/- %.2f - %.2f +/- %.2f) = %.2f +/- %.2f%% (statistical)' %(inclusiveYields['DY_inclusive'],
                                                                         yieldForMediumCat['DY_embed_2M'],
                                                                         calcSysUncSingle(yieldForMediumCat['DY_embed_2M'], eventCounterForMediumCat['DY_embed_2M']),
                                                                         yieldForMediumCat['tt_embed_2M'],
                                                                         calcSysUncSingle(yieldForMediumCat['tt_embed_2M'], eventCounterForMediumCat['tt_embed_2M']),
                                                                         inclusiveYields['DY_embed'],
                                                                         calcSysUncSingle(inclusiveYields['DY_embed'], eventCounterForInclusive['DY_embed']),
                                                                         inclusiveYields['tt_embed'],
                                                                         calcSysUncSingle(inclusiveYields['tt_embed'], eventCounterForInclusive['tt_embed']),
                                                                         scaleFactor_2M,
                                                                         sysUnc_2M*inclusiveYields['DY_inclusive']/scaleFactor_2M*100
                                                                        )
    print ''
    print 'predicted DY in 1M: %.2fx(%.2f - %.2f +/- %.2f)/(%.2f - %.2f +/- %.2f) = %.2f +/- %.2f%% (tt_xs)' %(inclusiveYields['DY_inclusive'],
                                                                         yieldForMediumCat['DY_embed_1M'],
                                                                         yieldForMediumCat['tt_embed_1M'],
                                                                         yieldForMediumCat['tt_embed_1M']*0.1,
                                                                         inclusiveYields['DY_embed'],
                                                                         inclusiveYields['tt_embed'],
                                                                         inclusiveYields['tt_embed']*0.1,
                                                                         scaleFactor_1M,
                                                                         sysUnc_xs_1M*inclusiveYields['DY_inclusive']/scaleFactor_1M*100
                                                                        )
    print 'predicted DY in 2M: %.2fx(%.2f - %.2f +/- %.2f)/(%.2f - %.2f +/- %.2f) = %.2f +/- %.2f%% (tt_xs)' %(inclusiveYields['DY_inclusive'],
                                                                         yieldForMediumCat['DY_embed_2M'],
                                                                         yieldForMediumCat['tt_embed_2M'],
                                                                         yieldForMediumCat['tt_embed_2M']*0.1,
                                                                         inclusiveYields['DY_embed'],
                                                                         inclusiveYields['tt_embed'],
                                                                         inclusiveYields['tt_embed']*0.1,
                                                                         scaleFactor_2M,
                                                                         sysUnc_xs_2M*inclusiveYields['DY_inclusive']/scaleFactor_2M*100
                                                                        )
    print ''
    print 'DY MC in 1M: %.2f' %yieldForMediumCat['DY_inclusive_1M']
    print 'DY MC in 2M: %.2f' %yieldForMediumCat['DY_inclusive_2M']
#     print 'predicted DY+tt in 1M: %.2f' %scaleFactor_1M2
#     print 'predicted DY+tt in 2M: %.2f' %scaleFactor_2M2


    if doDraw:
        position = (0.6, 0.9 - 0.06*2, 0.87, 0.9)
        l1 = tool.setMyLegend(position, [(dy_embed_1M, 'dy_embed_1M'), (tt_embed_1M, 'tt_embed_1M')])
        l2 = tool.setMyLegend(position, [(dy_embed_2M, 'dy_embed_2M'), (tt_embed_2M, 'tt_embed_2M')])

        psfile = 'DY_embed_tauUp.pdf'
        c = r.TCanvas("c","Test", 800, 600)
        dy_embed_1M.Draw()
        dy_embed_1M.SetTitle(';fMassKinFit;')
        tt_embed_1M.SetLineStyle(2)
        tt_embed_1M.SetLineColor(r.kRed)
        tt_embed_1M.Draw('same')
        l1.Draw('same')

        c.Print('%s(' %psfile)
        dy_embed_2M.Draw()
        dy_embed_2M.SetTitle(';fMassKinFit;')

        tt_embed_2M.SetLineStyle(2)
        tt_embed_2M.SetLineColor(r.kRed)
        tt_embed_2M.Draw('same')
        l2.Draw('same')

        c.Print('%s)' %psfile)


    return scaleFactor_1M, scaleFactor_2M, scaleFactor_1M2, scaleFactor_2M2, preScaleFactor
コード例 #40
0
    #     MC_Data_svMass.append(files[ifile].Get('MC_Data_svMass'))
    #     MC_Data_svMass[ifile].SetName('MC_Data_svMass_%s' %inputFiles[ifile][0])
    finalEventsWithXS.append(files[ifile].Get('finalEventsWithXS'))
    finalEventsWithXS[ifile].SetName('finalEventsWithXS_%s' %
                                     inputFiles[ifile][0])

# xs = files[0].Get('xs')
# initEvents= files[0].Get('initEvents')

for ifile in range(len(inputFiles)):

    total = trees[ifile].GetEntries()
    for i in range(0, total):
        tool.printProcessStatus(iCurrent=i + 1,
                                total=total,
                                processName='Looping sample')
        trees[ifile].GetEntry(i)
        #         BDT[0] = trees[ifile].BDT_both
        xs[0] = trees[ifile].xs
        initEvents[0] = trees[ifile].initEvents

        mJJ[0] = trees[ifile].mJJ
        fMass[0] = trees[ifile].fMass
        fMassKinFit[0] = trees[ifile].fMassKinFit
        chi2KinFit[0] = trees[ifile].chi2KinFit
        chi2KinFit2[0] = trees[ifile].chi2KinFit2

        svMass[0] = trees[ifile].svMass
        CSVJ2[0] = trees[ifile].CSVJ2
        PUWeight[0] = trees[ifile].PUWeight
コード例 #41
0
def loop_one_sample(iSample,                    #sample name (DY)
                    iLocation,                  #input file location
                    iXS,                        #sample xs
                    finalState,                 #final state (et, em, mt, tt)
                    type = enVars.type,         #selection type (baseline, inclusive)
                    category = enVars.category, #ZLL splitting (all, ZTT, ZL, ZJ)
                    location = '',              #output location, will be overwritten if outPutFileName != None
                    pairChoice = enVars.pairChoice,         #pair selection method (iso, pt)
                    nevents = '-1',             #n entries to loop over
                    chain = None,               #input TChain
                    outPutFileName = None,      #output file name,
                    histos = None,              #input histograms, preferred to be a list
                    ):
    print 'Ntuplizing sample [%s] for channel [%s]' %(iSample, finalState)

    if 'data' in iSample:
        isData = True
    else:
        isData = False
    if 'emb' in iSample:
        isEmbedded = True
    else:
        isEmbedded = False
    if 'H2hh' in iSample:
        isSignal = True
    else:
        isSignal = False

    sync = True

    #histograms
    if chain:
        iChain = chain
        nEntries = iChain.GetEntries()
    else:
        cutFlow = r.TH1D('cutFlow', '', len(xLabels), 0, len(xLabels))
        eventCount = r.TH1D('eventCount', '', 1, -0.5, 0.5)
        eventWeights = r.TH1D('eventWeights', '', 2, 0, 2)
        eventCountWeighted = r.TH1D('eventCountWeighted', '', 1, -0.5, 0.5)
        if not isData:
            tool.addHistFromFiles(dirName=iLocation, histName = "%s/eventCount" %finalState, hist = eventCount, xAxisLabels=['eventCount'])
            print 'initEvents: %i' %eventCount.GetBinContent(1)
            tool.addHistFromFiles(dirName=iLocation, histName = "%s/eventCountWeighted" %finalState, hist = eventCountWeighted, xAxisLabels=['eventCountWeighted'])
            print 'initWeightedEvents: %i' %eventCountWeighted.GetBinContent(1)
        iChain = r.TChain("%s/final/Ntuple" %finalState)
        nEntries = tool.addFiles(ch=iChain, dirName=iLocation, knownEventNumber=0, printTotalEvents=True, blackList='')

    iChain.SetBranchStatus("*",1)

    #set up vars dict
    charVarsDict = setUpCharVarsDict()
    floatVarsDict = setUpFloatVarsDict()
    intVarsDict = setUpIntVarsDict()
    syncVarsDict = None

    cat = ''
    if category != 'all':
        cat = '_%s' %category
    
    iChain.LoadTree(0)
    oTree = iChain.GetTree().CloneTree(0)
    
    if outPutFileName:
        outputFileName = outPutFileName
        iFile = r.TFile(outputFileName, "update")
    else:
        iSample = iSample + '_%s' %('all' if nevents == "-1" else nevents)
        if sync:
            outputFileName = "%s/%s%s_SYNC_%s_%s.root" %(location, iSample, cat, finalState, type)
        else:
            outputFileName = "%s/%s%s_%s_%s.root" %(location, iSample, cat, finalState, type)
        iFile = r.TFile(outputFileName, "recreate")

    #setup branches
    for iVar in charVarsDict.keys():
        oTree.Branch("%s" %iVar, charVarsDict[iVar], "%s[31]/C" %iVar)
    for iVar in floatVarsDict.keys():
        oTree.Branch("%s" %iVar, floatVarsDict[iVar], "%s/F" %iVar)
    for iVar in intVarsDict.keys():
        oTree.Branch("%s" %iVar, intVarsDict[iVar], "%s/L" %iVar)
    
    if sync:
        syncVarsDict = setUpSyncVarsDict()
        for iVar in syncVarsDict.keys():
            oTree.Branch("%s" %iVar, syncVarsDict[iVar], "%s/F" %iVar)

    charVarsDict['sampleName'][:31] = iSample
#     intVarsDict['initEvents'][0] = int(eventCount.GetBinContent(1))
#     intVarsDict['sumWeights'][0] = int(eventCountWeighted.GetBinContent(1))

    floatVarsDict['xs'][0] = iXS
    
    counter = 0

    preEvt = -1
    preLumi = -1
    preRun = -1
    bestPair = -1
    ptValue = -1.0
    ptValue_1 = -1.0

    isoValue = 9999.0
    isoValue_1 = 9999.0

    preEvt = 0
    preLumi = 0
    preRun = 0
    weightedNEvents = 0

    cutCounter = {}

    for iEntry in range(nEntries):
        iChain.LoadTree(iEntry)
        iChain.GetEntry(iEntry)
        if not chain:
            tool.printProcessStatus(iEntry, nEntries, 'Saving to file %s' %(outputFileName), iEntry-1)

        if not isData:
            if iChain.genEventWeight < 0:
                weightedNEvents -= 1
            else:
                weightedNEvents += 1

        passSelection =  passCatSelection(iChain, category, finalState)
        passCuts, comment = passCut(iChain, finalState, isData)
        passCuts = passCuts*passSelection

        if comment not in cutCounter.keys():
            cutCounter[comment] = 1
        else:
            cutCounter[comment] += 1

        if not chain:
            if iEntry == int(nevents):
                break

        if (not passCuts) and (iEntry != nEntries - 1):
            continue

        if (preEvt == 0 and preLumi == 0 and preRun == 0) or (preEvt == iChain.evt and preLumi == iChain.lumi and preRun == iChain.run):
            if passCuts:
                bestPair, isoValue_1, isoValue, ptValue_1, ptValue = findRightPair(iChain, iEntry, bestPair, isoValue_1, isoValue, ptValue_1, ptValue, pairChoice, finalState)

            if (iEntry == nEntries - 1): #save last event
                iChain.LoadTree(bestPair)
                iChain.GetEntry(bestPair)
                passAdditional, comments = passAdditionalCuts(iChain, finalState, type, isData)
                if passAdditional:
                    syncTools.saveExtra(iChain, floatVarsDict, syncVarsDict, intVarsDict, sync, finalState)
                    oTree.Fill()
                    counter += 1

        elif bestPair != -1:
            #store best pair
            iChain.LoadTree(bestPair)
            iChain.GetEntry(bestPair)
            passAdditional, comments = passAdditionalCuts(iChain, finalState, type, isData)
            if passAdditional:
                syncTools.saveExtra(iChain, floatVarsDict, syncVarsDict, intVarsDict, sync, finalState)
                oTree.Fill()
                counter += 1

            #reset best pair info
            bestPair = -1
            ptValue = -1.0
            isoValue = 999.0
            ptValue_1 = -1.0
            isoValue_1 = 999.0

            #reload to current entry
            iChain.LoadTree(iEntry)
            iChain.GetEntry(iEntry)
            bestPair, isoValue_1, isoValue, ptValue_1, ptValue = findRightPair(iChain, iEntry, bestPair, isoValue_1, isoValue, ptValue_1, ptValue, pairChoice, finalState)

            if (iEntry == nEntries - 1) and passCuts:  #save last event, it's already loaded with the current value
                passAdditional, comments = passAdditionalCuts(iChain, finalState, type, isData)
                if passAdditional:
                    syncTools.saveExtra(iChain, floatVarsDict, syncVarsDict, intVarsDict, sync, finalState)
                    oTree.Fill()
                    counter += 1

        preEvt = iChain.evt
        preLumi = iChain.lumi
        preRun = iChain.run

    print '  -- saved %d events' %(counter)
    print cutCounter
#     tool.addEventsCount2Hist(hist = cutFlow, count = counter, labelName = 'myCut')
    iFile.cd()
    if not histos:
        eventWeights.Fill(0.5, nEntries)
        eventWeights.Fill(1.5, weightedNEvents)
        eventWeights.Write()
        eventCountWeighted.Write()
        eventCount.Write()
    else:
        for iHist in histos:
            iHist.Write()
    oTree.Write()
    iFile.Close()
コード例 #42
0
tHist1.SetLineColor(r.kAzure+9)
tHist1.SetFillColor(r.kAzure+9)
tHist1.SetFillStyle(3003) 
tHist2 = r.TH1F() 
tHist2.SetLineColor(2)
tHist2.SetLineWidth(2)
tHist2.SetLineStyle(2)

legendPosition = (0.5, 0.75, 0.9, 0.85)
legendHistos = [(tHist1,"%s with %d events" %(options.file1, tree1.GetEntries())),
                (tHist2,"%s with %d events" %(options.file2, tree2.GetEntries()))]
listBranch = tree1.GetListOfBranches()

oFileName = "diff.root"
ofile = r.TFile(oFileName, "RECREATE")

nBranches = listBranch.GetEntries()

for i in range(nBranches):
    iBranchName = listBranch.At(i).GetName()
    tmpCanvas = r.TCanvas(iBranchName,"c",800,600)

    tree1.Draw("%s" %(iBranchName), "")
    tree2.Draw("%s" %(iBranchName), "", "same")
    l = tool.setMyLegend(lPosition=legendPosition, lHistList=legendHistos)
    l.Draw("same")
    tmpCanvas.Write()
    tool.printProcessStatus(i+1, nBranches, 'Saving to file %s.root' %(oFileName))
print '  -- saved %d branches' %(nBranches)
    
コード例 #43
0
ファイル: drawLTau.py プロジェクト: zaixingmao/H2hh2bbTauTau
data = r.TH1F('data','', ran[0], ran[1], ran[2])

dataFile = r.TFile('/nfs_scratch/ojalvo/LTau_12_2/DATA.root')


lepton = options.lep
LEPTON = "ET"
if lepton == "mu":
    LEPTON = "MT"

dataTree = dataFile.Get("%sTauEventTreeFinal/eventTree" %lepton)
totalData = dataTree.GetEntries()

for i in range(totalData):
    r.gStyle.SetOptStat(0)
    tool.printProcessStatus(iCurrent=i, total=totalData, processName = 'Looping sample')
    dataTree.GetEntry(i)
    if not passCut(dataTree):
        continue
    data.Fill(dataTree.pt2)
legendHistos.append((data, 'data (%.0f)' %data.Integral()))
print ''

legendPosition = (0.5, 0.7, 0.90, 0.88)

i = 0
for iSample, iFile, iXS, iColor in fileList:
    background.append(r.TH1F(iSample,'', ran[0], ran[1], ran[2]))
    files.append(r.TFile(iFile))
    trees.append(files[i].Get("%sTauEventTreeFinal/eventTree" %lepton))
    inits.append(files[i].Get("%s/results" %LEPTON).GetBinContent(1))
コード例 #44
0
def loop_one_sample(iSample,
                    varName,
                    hist1,
                    hist2,
                    category='mt',
                    isData=False,
                    region='barrel',
                    triggerLeg='e'):
    file = r.TFile(iSample)
    tree = file.Get('Ntuple')
    nEntries = tree.GetEntries()
    hist1.Sumw2()
    hist2.Sumw2()
    eventCountWeighted = file.Get('eventCountWeighted')
    #     if not isData and nEntries > 50000:
    #         nEntries = 50000
    for iEntry in range(nEntries):
        tree.GetEntry(iEntry)
        tool.printProcessStatus(iEntry, nEntries,
                                'Looping sample %s' % (iSample), iEntry - 1)
        weight = 1.0

        if not isData:
            puweight = cutSampleTools.getPUWeight(tree.nTruePU)
            sumWeights = eventCountWeighted.GetBinContent(1)
            weight = 10000 * tree.xs * tree.genEventWeight * puweight / (
                sumWeights + 0.0)

        if category == 'mt':
            if tree.mPt <= 25:
                continue
            if not (tree.singleMu24Pass and tree.mIsoMu24):
                continue
        elif category == 'et':
            if tree.ePt <= 33:
                continue
            if isData:
                if not (tree.singleETightPass and tree.eSingleEleTight):
                    continue
            else:
                if not (tree.singleEPass and tree.eSingleEle):
                    continue
        elif category == 'ee':
            if isData:
                if 'e2' in varName:
                    if tree.singleETightPass and tree.e1SingleEleTight:
                        if tree.e1Pt <= 34:
                            continue
                    else:
                        continue
                if 'e1' in varName:
                    if tree.singleETightPass and tree.e2SingleEleTight:
                        if tree.e2Pt <= 34:
                            continue
                    else:
                        continue
            else:
                if 'e2' in varName:
                    if tree.singleEPass and tree.e1SingleEle:
                        if tree.e1Pt <= 34:
                            continue
                    else:
                        continue
                if 'e1' in varName:
                    if tree.singleEPass and tree.e2SingleEle:
                        if tree.e2Pt <= 34:
                            continue
                    else:
                        continue
        elif category == 'em':
            if abs(tree.eEta) >= 2.1:
                continue
            if abs(tree.mEta) >= 2.1:
                continue
            if triggerLeg == 'e':
                if tree.mPt <= 24:
                    continue
                if region == 'barrel' and abs(tree.eEta) > 1.479:
                    continue
                elif region == 'endcap' and abs(tree.eEta) <= 1.479:
                    continue
            else:
                if region == 'barrel' and abs(tree.mEta) > 0.8:
                    continue
                elif region == 'middle' and not (0.8 < abs(tree.mEta) < 1.24):
                    continue
                elif region == 'endcap' and not (1.24 < abs(tree.mEta) < 2.4):
                    continue
                if tree.ePt <= 28:
                    continue

        if tree.q_1 == tree.q_2:
            continue

        value = getattr(tree, varName)

        hist1.Fill(value)
        if category == 'mt':
            if tree.muTauPass and tree.mMuTau and tree.mMuTauOverlap and tree.tTau20AgainstMuon and tree.tTauOverlapMu:
                hist2.Fill(value)
        elif category == 'et':
            if isData:
                if tree.eTau_WPLoosePass and tree.eEle22Loose and tree.eOverlapEle22Loose and tree.tTau20 and tree.tTauOverlapEleLoose:
                    hist2.Fill(value)
            else:
                if tree.eTauPass and tree.eEle22 and tree.eOverlapEle22 and tree.tTau20 and tree.tTauOverlapEle:
                    hist2.Fill(value)
        elif category == 'ee':
            if isData:
                if tree.doubleE_WPLoosePass:
                    if (tree.e1DoubleE_WPLooseLeg1
                            and tree.e2DoubleE_WPLooseLeg2) or (
                                tree.e1DoubleE_WPLooseLeg2
                                and tree.e2DoubleE_WPLooseLeg1):
                        if tree.e2Pt > 25 and tree.e1Pt > 25:
                            hist2.Fill(value)
            else:
                if tree.doubleE_WP75Pass:
                    if (tree.e1DoubleE_WP75Leg1 and tree.e2DoubleE_WP75Leg2
                        ) or (tree.e1DoubleE_WP75Leg2
                              and tree.e2DoubleE_WP75Leg1):
                        if tree.e2Pt > 25 and tree.e1Pt > 25:
                            hist2.Fill(value)
        elif category == 'em':
            if triggerLeg == 'e':
                if tree.singleE27_2p1_WPTightPass and tree.eSingleEle27_2p1_WPTight:
                    hist2.Fill(value)
            elif triggerLeg == 'mu':
                if tree.singleMu24Pass and tree.mIsoMu24:
                    hist2.Fill(value)

    print ''
コード例 #45
0
def merge(dir= "", type = "DY", cut = '', massWindow = False):
    if type == 'DY' or type == 'ZLL':
        fileNames = {'inclusive': 'DYJetsToLL_all.root',
                     '1jet': 'DY1JetsToLL_all.root',
                     '2jet': 'DY2JetsToLL_all.root',
                     '3jet': 'DY3JetsToLL_all.root',
                     '4jet': 'DY4JetsToLL_all.root',
                    }
    else:
        fileNames = {'inclusive': 'WJetsToLNu_all.root',
                     '1jet': 'W1JetsToLNu_all.root',
                     '2jet': 'W2JetsToLNu_all.root',
                     '3jet': 'W3JetsToLNu_all.root',
                     '4jet': 'W4JetsToLNu_all.root',
                    }
    #first get the right ratios
    if cut == '':
        scales, xsDict = getScales(dir, fileNames)
    else:
        scales, xsDict = getScalesWithCut(dir, fileNames, cut, massWindow, type)

    #fill the tree with fixed xs
    outName = dir
    appendName = ''
    if cut != '':
        appendName += "_%s" %cut
    if massWindow:
        appendName += "_massWindow"

    if type == 'DY':
        outName += "dy%s.root" %appendName
    elif type == 'ZLL':
        outName += "ZLL%s.root" %appendName
    else:
        outName += "WJets%s.root" %appendName

    chain = r.TChain("eventTree")
    for cat in fileNames.keys():
        chain.Add("%s/%s" %(dir, fileNames[cat]), 0)
    chain.SetBranchStatus("*",1)
    chain.SetBranchStatus("xs",0)
    chain.LoadTree(0)
    oTree = chain.GetTree().CloneTree(0)
    xs = array('f', [0.])
    oTree.Branch("xs", xs, "xs/F")
    oFile = r.TFile(outName, 'recreate')
    nEntries = chain.GetEntries()
    for iEntry in range(nEntries):
        chain.LoadTree(iEntry)
        chain.GetEntry(iEntry)
        tool.printProcessStatus(iEntry, nEntries, 'Combining multiple jet files %s' %outName, iEntry-1)
        if ('DYJetsToLL' in chain.sampleName) or ('WJetsToLNu' in chain.sampleName):
            if chain.LHEProduct != 5:
                continue
            xs[0] = xsDict['inclusive']
        else:
            cat = chain.sampleName[chain.sampleName.find("Jets") - 1: chain.sampleName.find("Jets")] + 'jet'
            xs[0] = xsDict[cat]*scales[cat]
        oTree.Fill()
    print xsDict, scales

    oFile.cd()
    oTree.Write()
    oFile.Close()
コード例 #46
0
for i in range(len(fileList)):
    fList.append(r.TFile(fileList[i]))
    treeList.append(fList[i].Get("eventTree"))
    histList.append(r.TH1F())
    histList[i].SetLineColor(i+1)
    treeList[i].SetLineColor(i+1)
    legendHistos.append((histList[i],"%s with %d events" %(fileList[i], treeList[i].GetEntries())))

legendPosition = (0.5, 0.75, 0.9, 0.85)


listBranch = treeList[0].GetListOfBranches()

oFileName = "test.root"
ofile = r.TFile(oFileName, "RECREATE")

nBranches = listBranch.GetEntries()

for i in range(nBranches):
    iBranchName = listBranch.At(i).GetName()
    tmpCanvas = r.TCanvas(iBranchName,"c",800,600)

    treeList[0].Draw("%s" %(iBranchName), "")
    for i in range(1, len(fileList)):
        treeList[i].Draw("%s" %(iBranchName), "", "same")
    l = tool.setMyLegend(lPosition=legendPosition, lHistList=legendHistos)
    l.Draw("same")
    tmpCanvas.Write()
    tool.printProcessStatus(i+1, nBranches, 'Saving to file %s.root' %(oFileName))
print '  -- saved %d branches' %(nBranches)
コード例 #47
0
def loop_one_sample(iSample, iLocation, iCat, oTree, oTree_tmp, floatVarsDict,
                    intVarsDict, charVarsDict, iFS, yieldDict, histDict):
    print 'combininig sample [%s] for datacard' % (iSample)
    if 'data' in iSample:
        isData = True
    else:
        isData = False
    if 'emb' in iSample:
        isEmbedded = True
    else:
        isEmbedded = False
    if ("Z'" in iSample):
        isSignal = True
    else:
        isSignal = False

    iFile = r.TFile(iLocation)
    iTree = iFile.Get("Ntuple")
    nEntries = iTree.GetEntries()
    iTree.SetBranchStatus("*", 1)
    iTree.SetBranchStatus("sampleName", 0)

    eventCount = iFile.Get('eventCount')
    eventCountWeighted = iFile.Get('eventCountWeighted')

    sumPtWeights = -1.0
    if "TTJets" in iSample:
        sumPtWeights = iFile.Get('eventCountPtWeighted').GetBinContent(1)

    yieldEstimator_OS = 0.0
    yieldEstimator_SS = 0.0
    fillcounter = 0
    met = lvClass()
    for iEntry in range(nEntries):
        iTree.GetEntry(iEntry)
        tool.printProcessStatus(iEntry, nEntries,
                                'looping over file %s' % (iSample), iEntry - 1)
        uncWeight = 1.0
        region = 'none'
        met.SetCoordinates(iTree.met, 0.0, iTree.metphi, 0)

        l1.SetCoordinates(iTree.pt_1, iTree.eta_1, iTree.phi_1, iTree.m_1)
        l2.SetCoordinates(iTree.pt_2, iTree.eta_2, iTree.phi_2, iTree.m_2)

        if not plots_dataDrivenQCDandWJ.passCut(iTree, iFS, isData,
                                                options.sys):
            continue

        if plots_dataDrivenQCDandWJ.regionSelection(iTree, iFS, "signal",
                                                    plots_cfg.scanRange[0],
                                                    plots_cfg.scanRange[1]):
            if isData:
                charVarsDict['sampleName'][:31] = 'data' + signalRegionName
            else:
                charVarsDict['sampleName'][:31] = iSample
                if isSignal:
                    charVarsDict['sampleName'][:31] = "Zprime_%s" % iSample[
                        iSample.find("(") + 1:iSample.find(")")]
            if iTree.q_1 != iTree.q_2:
                region = 'A'
            else:
                if isSignal:
                    continue
                region = 'B'

        elif plots_dataDrivenQCDandWJ.regionSelection(iTree, iFS,
                                                      "control_iso",
                                                      plots_cfg.scanRange[0],
                                                      plots_cfg.scanRange[1]):
            if isSignal:
                continue
            if iTree.q_1 == -iTree.q_2:  #C region
                if iFS != "em":
                    if "WJets" in iSample:
                        continue
                region = 'C'
            else:  #D region
                charVarsDict['sampleName'][:31] = 'QCD_in_D'
                region = 'D'

        elif iFS != 'em' and plots_dataDrivenQCDandWJ.regionSelection(
                iTree, iFS, "control_anti_iso", plots_cfg.scanRange[0],
                plots_cfg.scanRange[1]):
            if isSignal:
                continue
            if not isData:
                continue
            if iTree.q_1 == -iTree.q_2:  #E region
                charVarsDict['sampleName'][:31] = 'QCDLoose'
                region = 'E'
            else:
                charVarsDict['sampleName'][:31] = 'QCD_in_F'
                region = 'F'
        else:
            continue

        floatVarsDict['pt_1'][0] = iTree.pt_1
        floatVarsDict['pt_2'][0] = iTree.pt_2
        floatVarsDict['eta_1'][0] = iTree.eta_1
        floatVarsDict['eta_2'][0] = iTree.eta_2
        floatVarsDict['mt_1'][0] = iTree.mt_1

        floatVarsDict['genMass'][0] = 0.0
        if hasattr(iTree, 'X_to_ll'):
            floatVarsDict['genMass'][0] = iTree.X_to_ll

        if hasattr(iTree, 'BDT_both'):
            floatVarsDict['BDT'][0] = iTree.BDT_both
        else:
            floatVarsDict['BDT'][0] = -999

        floatVarsDict['triggerEff'][
            0] = iTree.trigweight_1 * iTree.trigweight_2
        charVarsDict['Category'][:31] = iFS

        floatVarsDict['xs'][0] = iTree.xs

        if 'WJets' in iSample:
            floatVarsDict['xs'][
                0] = floatVarsDict['xs'][0] * plots_cfg.WJetsScanRange[0]
        if "Zprime" in iSample:
            floatVarsDict['xs'][0] = plots.getZPrimeXS(iSample[7:])

        if eventCount:
            intVarsDict['initEvents'][0] = int(eventCount.GetBinContent(1))
        else:
            intVarsDict['initEvents'][0] = int(iTree.initEvents)
        if eventCountWeighted:
            intVarsDict['initSumWeights'][0] = int(
                eventCountWeighted.GetBinContent(1))
        else:
            intVarsDict['initSumWeights'][0] = int(iTree.initWeightedEvents)


#         floatVarsDict['m_svfit'][0] = iTree.pfmet_svmc_mass
        floatVarsDict['m_effective'][0] = (l1 + l2 + met).mass()
        floatVarsDict['m_vis'][0] = (l1 + l2).mass()
        #         floatVarsDict['m_tt'][0] = iTree.m_tt

        if (options.sys == 'up' or options.sys == 'down') and (not isData):
            floatVarsDict['xs'][0] = floatVarsDict['xs'][0] * getPDFWeight(
                iFS, iSample, iCat, options.sys,
                floatVarsDict['m_effective'][0])

        intVarsDict['nCSVL'][0] = int(iTree.nCSVL)
        if iFS == 'et' or iFS == "mt":
            intVarsDict['tauDecayMode'][0] = int(iTree.tDecayMode)
            floatVarsDict['tauTightIso'][
                0] = iTree.tByTightCombinedIsolationDeltaBetaCorr3Hits
            floatVarsDict['tauMediumIso'][
                0] = iTree.tByMediumCombinedIsolationDeltaBetaCorr3Hits
            floatVarsDict['tauLooseIso'][
                0] = iTree.tByLooseCombinedIsolationDeltaBetaCorr3Hits
            if options.sys == 'tauUncUp':
                uncWeight += 0.05 * iTree.pt_2 / 1000.
            if options.sys == 'tauUncDown':
                uncWeight -= 0.35 * iTree.pt_2 / 1000.
        floatVarsDict['cosDPhi'][0] = math.cos(iTree.phi_1 - iTree.phi_2)
        floatVarsDict['pZetaCut'][0] = getattr(
            iTree, "%s_%s_PZeta" % (iFS[0], iFS[1])) - 3.1 * getattr(
                iTree, "%s_%s_PZetaVis" % (iFS[0], iFS[1]))

        floatVarsDict['pfMEt'][0] = iTree.met
        #         floatVarsDict['eleRelIso'][0] = iTree.eRelIso

        if options.PUWeight and not isData:
            floatVarsDict['PUWeight'][0] = cutSampleTools.getPUWeight(
                iTree.nTruePU)
            floatVarsDict['npv'][0] = iTree.nTruePU

        else:
            floatVarsDict['PUWeight'][0] = 1.0
            floatVarsDict['npv'][0] = 0

        if isData:
            floatVarsDict['genEventWeight'][0] = 1.0
            intVarsDict['initSumWeights'][0] = 1
            floatVarsDict['xs'][0] = 1.0 / plots.lumi
            floatVarsDict['triggerEff'][0] = 1.0
        else:
            floatVarsDict['genEventWeight'][
                0] = uncWeight * iTree.genEventWeight
            if options.topPt and sumPtWeights != -1.0:
                intVarsDict['initSumWeights'][0] = int(sumPtWeights)
                floatVarsDict['genEventWeight'][
                    0] = iTree.topPtWeight * floatVarsDict['genEventWeight'][0]
            if (iFS == 'et' or iFS == 'mt') and not isData:
                floatVarsDict['genEventWeight'][
                    0] = floatVarsDict['genEventWeight'][0] * 0.95  #tauID

            if options.againstLeptonSF:
                if iFS == 'et':
                    if (iTree.tIsPromptElectron):
                        floatVarsDict['genEventWeight'][
                            0] = floatVarsDict['genEventWeight'][
                                0] * plots_dataDrivenQCDandWJ.getAgainstLeptonSF(
                                    'electron', 'Tight', abs(iTree.eta_2))
                    if (iTree.tIsPromptMuon):
                        floatVarsDict['genEventWeight'][
                            0] = floatVarsDict['genEventWeight'][
                                0] * plots_dataDrivenQCDandWJ.getAgainstLeptonSF(
                                    'muon', 'Loose', abs(iTree.eta_2))
                if iFS == 'mt':
                    if (iTree.tIsPromptElectron):
                        floatVarsDict['genEventWeight'][
                            0] = floatVarsDict['genEventWeight'][
                                0] * plots_dataDrivenQCDandWJ.getAgainstLeptonSF(
                                    'electron', 'VLoose', abs(iTree.eta_2))
                    if (iTree.tIsPromptMuon):
                        floatVarsDict['genEventWeight'][
                            0] = floatVarsDict['genEventWeight'][
                                0] * plots_dataDrivenQCDandWJ.getAgainstLeptonSF(
                                    'muon', 'Tight', abs(iTree.eta_2))

        if region == 'none':
            print "ERROR!!!!!"

        if region == "A":
            if charVarsDict['sampleName'][:31] in yieldDict.keys():
                yieldDict[str(
                    charVarsDict['sampleName']
                    [:31])] += floatVarsDict['triggerEff'][0] * floatVarsDict[
                        'PUWeight'][0] * floatVarsDict['genEventWeight'][
                            0] * floatVarsDict['xs'][0] * plots.lumi / (
                                intVarsDict['initSumWeights'][0] + 0.0)
            else:
                yieldDict[str(
                    charVarsDict['sampleName']
                    [:31])] = floatVarsDict['triggerEff'][0] * floatVarsDict[
                        'PUWeight'][0] * floatVarsDict['genEventWeight'][
                            0] * floatVarsDict['xs'][0] * plots.lumi / (
                                intVarsDict['initSumWeights'][0] + 0.0)
            if "WJets" in iSample:
                histDict["WJetsOSTight_MC"].Fill(
                    1, floatVarsDict['triggerEff'][0] *
                    floatVarsDict['PUWeight'][0] *
                    floatVarsDict['genEventWeight'][0] *
                    floatVarsDict['xs'][0] * plots.lumi /
                    (intVarsDict['initSumWeights'][0] + 0.0))
                yieldDict["WJetsOSTight_MC"] += floatVarsDict['triggerEff'][
                    0] * floatVarsDict['PUWeight'][0] * floatVarsDict[
                        'genEventWeight'][0] * floatVarsDict['xs'][
                            0] * plots.lumi / (
                                intVarsDict['initSumWeights'][0] + 0.0)
            oTree.Fill()

        elif region == "B":
            weight = 1
            if not isData:
                weight = -floatVarsDict['triggerEff'][0] * floatVarsDict[
                    'PUWeight'][0] * floatVarsDict['genEventWeight'][
                        0] * floatVarsDict['xs'][0] * plots.lumi / (
                            intVarsDict['initSumWeights'][0] + 0.0)
            yieldDict["QCD_in_B"] += weight
            histDict["QCD_in_B"].Fill(1, weight)

        elif region == "C":
            if iFS == "em":
                charVarsDict['sampleName'][:31] = 'QCDLoose'
                if isData:
                    yieldDict["QCDLoose"] += 1
                else:
                    yieldDict["QCDLoose"] -= floatVarsDict['triggerEff'][
                        0] * floatVarsDict['PUWeight'][0] * floatVarsDict[
                            'genEventWeight'][0] * floatVarsDict['xs'][
                                0] * plots.lumi / (
                                    intVarsDict['initSumWeights'][0] + 0.0)
                    floatVarsDict['genEventWeight'][
                        0] = -1.0 * floatVarsDict['genEventWeight'][0]
                oTree.Fill()
                if "WJets" in iSample:
                    floatVarsDict['genEventWeight'][
                        0] = -1.0 * floatVarsDict['genEventWeight'][0]
                    yieldDict['WJets' + controlRegionName] += floatVarsDict[
                        'triggerEff'][0] * floatVarsDict['PUWeight'][
                            0] * floatVarsDict['genEventWeight'][
                                0] * floatVarsDict['xs'][0] * plots.lumi / (
                                    intVarsDict['initSumWeights'][0] + 0.0)
                    histDict["WJetsOSLoose_MC"].Fill(
                        1, floatVarsDict['triggerEff'][0] *
                        floatVarsDict['PUWeight'][0] *
                        floatVarsDict['genEventWeight'][0] *
                        floatVarsDict['xs'][0] * plots.lumi /
                        (intVarsDict['initSumWeights'][0] + 0.0))
                    charVarsDict[
                        'sampleName'][:31] = 'WJets' + controlRegionName
                    oTree.Fill()
            else:
                charVarsDict['sampleName'][:31] = 'WJetsLoose'
                if isData:
                    yieldDict['WJetsLoose'] += 1
                else:
                    floatVarsDict['genEventWeight'][
                        0] = -1.0 * floatVarsDict['genEventWeight'][0]
                    yieldDict['WJetsLoose'] += floatVarsDict['triggerEff'][
                        0] * floatVarsDict['PUWeight'][0] * floatVarsDict[
                            'genEventWeight'][0] * floatVarsDict['xs'][
                                0] * plots.lumi / (
                                    intVarsDict['initSumWeights'][0] + 0.0)
                oTree.Fill()

        elif region == "D":
            weight = 1
            if not isData:
                weight = -floatVarsDict['triggerEff'][0] * floatVarsDict[
                    'PUWeight'][0] * floatVarsDict['genEventWeight'][
                        0] * floatVarsDict['xs'][0] * plots.lumi / (
                            intVarsDict['initSumWeights'][0] + 0.0)
            yieldDict["QCD_in_D"] += weight
            histDict["QCD_in_D"].Fill(1, weight)

        elif region == "E" and iFS != 'em' and isData:
            yieldDict["QCDLoose"] += 1
            oTree_tmp.Fill()
            oTree.Fill()

        elif region == "F" and iFS != 'em' and isData:
            yieldDict["QCD_in_F"] += 1
            histDict["QCD_in_F"].Fill(1, 1)

    return yieldDict, histDict
コード例 #48
0
def getPtDistribution(file,
                      hist,
                      hist2=None,
                      hist3=None,
                      jetPt=0,
                      type='central',
                      Print=False,
                      counter=False):
    f = r.TFile(file)
    tree = f.Get("Events")
    nEntries = tree.GetEntries()

    if Print:
        output = open('evtDump.txt', "w")  #opens & write the file
        output2 = open('matched.txt', "w")  #opens & write the file

    totalTaus = 0
    foundMatch = 0
    if counter:
        passed_30 = 0.0
        passed_35 = 0.0
        total = 0.0

    for i in range(nEntries):
        #     for i in range(500):
        tool.printProcessStatus(i,
                                nEntries,
                                processName='Looping %s' % file,
                                iPrevious=i - 1)
        tree.GetEntry(i)

        #loop over pat taus in an event
        nTaus = (tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO).size()
        nJet = (
            tree.l1extraL1JetParticles_l1extraParticles_Central_RECO).size()

        totalTaus += nTaus

        if Print and i < 20:
            output.writelines('nTaus: %i ----------------\n' % nTaus)
            for j in range(nTaus):
                output.writelines(
                    'pt: %.2f, eta: %.2f, phi: %.2f\n' %
                    ((tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO
                      ).at(j).pt(),
                     (tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO
                      ).at(j).eta(),
                     (tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO
                      ).at(j).phi()))

            output.writelines('nJets: %i ----------------\n' % nJet)
            for j in range(nJet):
                output.writelines(
                    'pt: %.2f, eta: %.2f, phi: %.2f\n' %
                    ((tree.l1extraL1JetParticles_l1extraParticles_Central_RECO
                      ).at(j).pt(),
                     (tree.l1extraL1JetParticles_l1extraParticles_Central_RECO
                      ).at(j).eta(),
                     (tree.l1extraL1JetParticles_l1extraParticles_Central_RECO
                      ).at(j).phi()))
            output.writelines('-------------------------------------\n')

        failed = False
        Found = False
        foundJetPt = 0.0

        if jetPt > 5.0:
            failed = True
            if type == 'central':
                if nJet != 0:
                    for j in range(nJet):
                        pt = (
                            tree.
                            l1extraL1JetParticles_l1extraParticles_Central_RECO
                        ).at(j).pt()
                        eta = (
                            tree.
                            l1extraL1JetParticles_l1extraParticles_Central_RECO
                        ).at(j).eta()
                        phi = (
                            tree.
                            l1extraL1JetParticles_l1extraParticles_Central_RECO
                        ).at(j).phi()
                        found = False
                        if nTaus != 0:
                            for k in range(nTaus):
                                if eta == (
                                        tree.
                                        l1extraL1JetParticles_l1extraParticles_Tau_RECO
                                ).at(k).eta():
                                    if phi == (
                                            tree.
                                            l1extraL1JetParticles_l1extraParticles_Tau_RECO
                                    ).at(k).phi():
                                        found = True
                        if not found and (pt > jetPt):
                            failed = False
                            foundJetPt = pt
                            break
                        if found:
                            foundMatch += 1
                            Found = True

        if Found and Print:
            output2.writelines('nTaus: %i ----------------\n' % nTaus)
            for j in range(nTaus):
                output2.writelines(
                    'pt: %.2f, eta: %.2f, phi: %.2f\n' %
                    ((tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO
                      ).at(j).pt(),
                     (tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO
                      ).at(j).eta(),
                     (tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO
                      ).at(j).phi()))

            output2.writelines('nJets: %i ----------------\n' % nJet)
            for j in range(nJet):
                output2.writelines(
                    'pt: %.2f, eta: %.2f, phi: %.2f\n' %
                    ((tree.l1extraL1JetParticles_l1extraParticles_Central_RECO
                      ).at(j).pt(),
                     (tree.l1extraL1JetParticles_l1extraParticles_Central_RECO
                      ).at(j).eta(),
                     (tree.l1extraL1JetParticles_l1extraParticles_Central_RECO
                      ).at(j).phi()))
            output2.writelines('-------------------------------------\n')

        weight = (tree.GenEventInfoProduct_generator__SIM).weights()[0]
        if hist2 != None:
            if (tree.GenEventInfoProduct_generator__SIM).hasBinningValues():
                hist2.Fill(
                    200000.0 * math.pow(
                        (tree.GenEventInfoProduct_generator__SIM
                         ).binningValues()[0], -4.5),
                    (tree.GenEventInfoProduct_generator__SIM).weights()[0])
                if hist3 != None:
                    hist3.Fill(
                        (tree.GenEventInfoProduct_generator__SIM
                         ).binningValues()[0],
                        (tree.GenEventInfoProduct_generator__SIM).weights()[0])

        xValue = foundJetPt
        if (nTaus != 0):
            xValue = (tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO
                      ).at(0).pt()
        else:
            xValue = -1
        if nTaus < 2:
            yValue = -1
        else:
            yValue = (tree.l1extraL1JetParticles_l1extraParticles_Tau_RECO
                      ).at(1).pt()


#             print xValue, yValue, weight
        if not failed:
            hist.Fill(xValue, yValue, weight)
        else:
            hist.Fill(-1, -1, weight)

        if counter:
            total += weight
            if (yValue >= 40.0) or ((yValue > 35.0) and (foundJetPt > 30.0)):
                passed_35 += weight
            if (yValue >= 40.0) or ((yValue > 30.0) and (foundJetPt > 30.0)):
                passed_30 += weight

    if Print:
        output.close()
        output2.writelines('totalTaus: %i, foundMatch: %i' %
                           (totalTaus, foundMatch))
        output2.close()

    if counter:
        if hist2 != None:
            print ''
            print 'pass_30: %.8f, %.8f' % (1.0 - passed_30 / total,
                                           passed_30 / total)
            print 'pass_35: %.8f, %.8f' % (1.0 - passed_35 / total,
                                           passed_35 / total)
        else:
            print ''
            print 'pass_30: %.8f' % (passed_30 / total)
            print 'pass_35: %.8f' % (passed_35 / total)

    print ''

    if hist2 == None:
        return hist
    elif hist3 == None:
        return hist, hist2
    else:
        return hist, hist2, hist3
コード例 #49
0
varList = []
listBranch = tree1.GetListOfBranches()
for i in range(listBranch.GetEntries()):
    varList.append(array('f', [0.]))
    oTree.Branch(listBranch.At(i).GetName(), varList[i], "%s/F" %(listBranch.At(i).GetName()))

#get event number list for each tree
for i in range(tree1.GetEntries()):
    tree1.GetEntry(i)
    evnNumList1.append(tree1.EVENT)

nEntries = tree2.GetEntries()
counter = 0

for i in range(nEntries):
    tool.printProcessStatus(i, nEntries, 'Comparing root files')
    tree2.GetEntry(i)
    if tree2.EVENT in evnNumList1:
        continue
    #print setVarList[1][0]
    getBranchVal(varList = varList, tree = tree2, entry = i)
    oTree.Fill()
    counter+=1
print '  -- saved %d events' %(counter)

oFile.cd()
oTree.Write()
oFile.Close()
    
    
コード例 #50
0
J4 = lvClass()

ChainHistList = [(HChain, signalLocation, signalEntries, jetCSV1_signal, jetCSV2_signal),
                 (ttChain, ttLocation, ttEntries, jetCSV1_tt, jetCSV2_tt),
                 (ZZChain, ZZLocation, ZZEntries, jetCSV1_ZZ, jetCSV2_ZZ)]

#for normalization
HistNameList = [jetCSV1_signal, jetCSV2_signal, jetCSV1_tt, jetCSV2_tt, jetCSV1_ZZ, jetCSV2_ZZ]

for iChain, iLocation, iEntries, iHist1, iHist2 in ChainHistList:
    total = iEntries if iEntries else iChain.GetEntriesFast()
    key =  "found" if not iEntries else "has"
    print "[%s] %s %d events" %(iLocation, key, total)
    for i in range(0, total):
        iChain.GetEntry(i)
        tool.printProcessStatus(iCurrent=i, total=total, processName = 'Looping signal sample')
        jetsList = [(iChain.J1CSVbtag, J1.SetCoordinates(iChain.J1Pt, iChain.J1Eta, iChain.J1Phi, iChain.J1Mass)),
                    (iChain.J2CSVbtag, J2.SetCoordinates(iChain.J2Pt, iChain.J2Eta, iChain.J2Phi, iChain.J2Mass)),
                    (iChain.J3CSVbtag, J3.SetCoordinates(iChain.J3Pt, iChain.J3Eta, iChain.J3Phi, iChain.J3Mass)),
                    (iChain.J4CSVbtag, J4.SetCoordinates(iChain.J4Pt, iChain.J4Eta, iChain.J4Phi, iChain.J4Mass))]
        jetsList = sorted(jetsList, key=itemgetter(0), reverse=True)
        if jetsList[0][1].pt() < 20 or abs(jetsList[0][1].eta()) > 2.4:
            continue
        if jetsList[1][1].pt() < 20 or abs(jetsList[1][1].eta()) > 2.4:
            continue
        iHist1.Fill(jetsList[0][0])
        iHist2.Fill(jetsList[1][0])
    print ''


tool.unitNormHists(HistNameList)
コード例 #51
0
def merge(dir="", type="DY", cut='', massWindow=False):
    if type == 'DY' or type == 'ZLL':
        fileNames = {
            'inclusive': 'DYJetsToLL_all.root',
            '1jet': 'DY1JetsToLL_all.root',
            '2jet': 'DY2JetsToLL_all.root',
            '3jet': 'DY3JetsToLL_all.root',
            '4jet': 'DY4JetsToLL_all.root',
        }
    else:
        fileNames = {
            'inclusive': 'WJetsToLNu_all.root',
            '1jet': 'W1JetsToLNu_all.root',
            '2jet': 'W2JetsToLNu_all.root',
            '3jet': 'W3JetsToLNu_all.root',
            '4jet': 'W4JetsToLNu_all.root',
        }
    #first get the right ratios
    if cut == '':
        scales, xsDict = getScales(dir, fileNames)
    else:
        scales, xsDict = getScalesWithCut(dir, fileNames, cut, massWindow,
                                          type)

    #fill the tree with fixed xs
    outName = dir
    appendName = ''
    if cut != '':
        appendName += "_%s" % cut
    if massWindow:
        appendName += "_massWindow"

    if type == 'DY':
        outName += "dy%s.root" % appendName
    elif type == 'ZLL':
        outName += "ZLL%s.root" % appendName
    else:
        outName += "WJets%s.root" % appendName

    chain = r.TChain("eventTree")
    for cat in fileNames.keys():
        chain.Add("%s/%s" % (dir, fileNames[cat]), 0)
    chain.SetBranchStatus("*", 1)
    chain.SetBranchStatus("xs", 0)
    chain.LoadTree(0)
    oTree = chain.GetTree().CloneTree(0)
    xs = array('f', [0.])
    oTree.Branch("xs", xs, "xs/F")
    oFile = r.TFile(outName, 'recreate')
    nEntries = chain.GetEntries()
    for iEntry in range(nEntries):
        chain.LoadTree(iEntry)
        chain.GetEntry(iEntry)
        tool.printProcessStatus(iEntry, nEntries,
                                'Combining multiple jet files %s' % outName,
                                iEntry - 1)
        if ('DYJetsToLL' in chain.sampleName) or ('WJetsToLNu'
                                                  in chain.sampleName):
            if chain.LHEProduct != 5:
                continue
            xs[0] = xsDict['inclusive']
        else:
            cat = chain.sampleName[chain.sampleName.find("Jets") -
                                   1:chain.sampleName.find("Jets")] + 'jet'
            xs[0] = xsDict[cat] * scales[cat]
        oTree.Fill()
    print xsDict, scales

    oFile.cd()
    oTree.Write()
    oFile.Close()
コード例 #52
0
def loop_one_sample(iSample, iLocation, iCat, oTree, oTree_tmp, 
                    floatVarsDict, intVarsDict, charVarsDict, 
                    iFS, yieldDict, histDict):
    print 'combininig sample [%s] for datacard' %(iSample)
    if 'data' in iSample:
        isData = True
    else:
        isData = False
    if 'emb' in iSample:
        isEmbedded = True
    else:
        isEmbedded = False
    if ("Z'" in iSample):
        isSignal = True
    else:
        isSignal = False

    iFile = r.TFile(iLocation)
    iTree = iFile.Get("Ntuple")
    nEntries = iTree.GetEntries()
    iTree.SetBranchStatus("*",1)
    iTree.SetBranchStatus("sampleName",0)

    eventCount = iFile.Get('eventCount')
    eventCountWeighted = iFile.Get('eventCountWeighted')

    sumPtWeights = -1.0
    if "TTJets" in iSample:
        sumPtWeights = iFile.Get('eventCountPtWeighted').GetBinContent(1)

    yieldEstimator_OS = 0.0
    yieldEstimator_SS = 0.0
    fillcounter=0
    met = lvClass()
    for iEntry in range(nEntries):
        iTree.GetEntry(iEntry)
        tool.printProcessStatus(iEntry, nEntries, 'looping over file %s' %(iSample), iEntry-1)
        uncWeight = 1.0
        region = 'none'
        met.SetCoordinates(iTree.met, 0.0, iTree.metphi, 0)

        l1.SetCoordinates(iTree.pt_1, iTree.eta_1, iTree.phi_1, iTree.m_1)
        l2.SetCoordinates(iTree.pt_2, iTree.eta_2, iTree.phi_2, iTree.m_2)

        if not plots_dataDrivenQCDandWJ.passCut(iTree, iFS, isData, options.sys):
            continue

        if plots_dataDrivenQCDandWJ.regionSelection(iTree, iFS, "signal", plots_cfg.scanRange[0], plots_cfg.scanRange[1]):
            if isData:
                charVarsDict['sampleName'][:31] = 'data' + signalRegionName
            else:
                charVarsDict['sampleName'][:31] = iSample
                if isSignal:
                    charVarsDict['sampleName'][:31] = "Zprime_%s" %iSample[iSample.find("(")+1: iSample.find(")")]
            if iTree.q_1 != iTree.q_2:
                region = 'A'
            else:
                if isSignal:
                    continue
                region = 'B'

        elif plots_dataDrivenQCDandWJ.regionSelection(iTree, iFS, "control_iso", plots_cfg.scanRange[0], plots_cfg.scanRange[1]):
            if isSignal:
                continue
            if iTree.q_1 == -iTree.q_2: #C region
                if iFS != "em":
                    if "WJets" in iSample:
                        continue
                region = 'C'
            else: #D region
                charVarsDict['sampleName'][:31] = 'QCD_in_D'
                region = 'D'

        elif iFS != 'em' and plots_dataDrivenQCDandWJ.regionSelection(iTree, iFS, "control_anti_iso", plots_cfg.scanRange[0], plots_cfg.scanRange[1]):
            if isSignal:
                continue
            if not isData:
                continue
            if iTree.q_1 == -iTree.q_2: #E region
                charVarsDict['sampleName'][:31] = 'QCDLoose'
                region = 'E'
            else:
                charVarsDict['sampleName'][:31] = 'QCD_in_F'
                region = 'F'
        else:
            continue

        floatVarsDict['pt_1'][0] = iTree.pt_1
        floatVarsDict['pt_2'][0] = iTree.pt_2
        floatVarsDict['eta_1'][0] = iTree.eta_1
        floatVarsDict['eta_2'][0] = iTree.eta_2
        floatVarsDict['mt_1'][0] = iTree.mt_1

        floatVarsDict['genMass'][0] = 0.0
        if hasattr(iTree, 'X_to_ll'):
            floatVarsDict['genMass'][0] = iTree.X_to_ll

        if hasattr(iTree, 'BDT_both'):
            floatVarsDict['BDT'][0] = iTree.BDT_both
        else:
            floatVarsDict['BDT'][0] = -999

        floatVarsDict['triggerEff'][0] = iTree.trigweight_1*iTree.trigweight_2
        charVarsDict['Category'][:31] = iFS

        floatVarsDict['xs'][0] = iTree.xs

        if 'WJets' in iSample:
            floatVarsDict['xs'][0] = floatVarsDict['xs'][0]*plots_cfg.WJetsScanRange[0]
        if "Zprime" in iSample:
            floatVarsDict['xs'][0] = plots.getZPrimeXS(iSample[7:])

        if eventCount:
            intVarsDict['initEvents'][0] = int(eventCount.GetBinContent(1))
        else:    
            intVarsDict['initEvents'][0] = int(iTree.initEvents)
        if eventCountWeighted:
            intVarsDict['initSumWeights'][0] = int(eventCountWeighted.GetBinContent(1))
        else:    
            intVarsDict['initSumWeights'][0] = int(iTree.initWeightedEvents)

#         floatVarsDict['m_svfit'][0] = iTree.pfmet_svmc_mass
        floatVarsDict['m_effective'][0] = (l1 + l2 + met).mass()
        floatVarsDict['m_vis'][0] = (l1 + l2).mass()
#         floatVarsDict['m_tt'][0] = iTree.m_tt

        if (options.sys == 'up' or options.sys == 'down') and (not isData):
            floatVarsDict['xs'][0] = floatVarsDict['xs'][0]*getPDFWeight(iFS, iSample, iCat, options.sys, floatVarsDict['m_effective'][0])

        intVarsDict['nCSVL'][0] = int(iTree.nCSVL)
        if iFS == 'et' or iFS == "mt":
            intVarsDict['tauDecayMode'][0] = int(iTree.tDecayMode)
            floatVarsDict['tauTightIso'][0] = iTree.tByTightCombinedIsolationDeltaBetaCorr3Hits
            floatVarsDict['tauMediumIso'][0] = iTree.tByMediumCombinedIsolationDeltaBetaCorr3Hits
            floatVarsDict['tauLooseIso'][0] = iTree.tByLooseCombinedIsolationDeltaBetaCorr3Hits
            if options.sys == 'tauUncUp':
                uncWeight += 0.05*iTree.pt_2/1000.
            if options.sys == 'tauUncDown':
                uncWeight -= 0.35*iTree.pt_2/1000.
        floatVarsDict['cosDPhi'][0] =  math.cos(iTree.phi_1 - iTree.phi_2)
        floatVarsDict['pZetaCut'][0] =  getattr(iTree, "%s_%s_PZeta" %(iFS[0], iFS[1])) - 3.1*getattr(iTree, "%s_%s_PZetaVis" %(iFS[0], iFS[1]))

        floatVarsDict['pfMEt'][0] = iTree.met
#         floatVarsDict['eleRelIso'][0] = iTree.eRelIso

        if options.PUWeight and not isData:
            floatVarsDict['PUWeight'][0] = cutSampleTools.getPUWeight(iTree.nTruePU)
            floatVarsDict['npv'][0] = iTree.nTruePU

        else:
            floatVarsDict['PUWeight'][0] = 1.0
            floatVarsDict['npv'][0] = 0

        if isData:
            floatVarsDict['genEventWeight'][0] = 1.0
            intVarsDict['initSumWeights'][0] = 1
            floatVarsDict['xs'][0] = 1.0/plots.lumi
            floatVarsDict['triggerEff'][0] = 1.0
        else:
            floatVarsDict['genEventWeight'][0] = uncWeight*iTree.genEventWeight
            if options.topPt and sumPtWeights != -1.0:
                intVarsDict['initSumWeights'][0] = int(sumPtWeights)
                floatVarsDict['genEventWeight'][0] = iTree.topPtWeight*floatVarsDict['genEventWeight'][0]
            if (iFS == 'et' or iFS == 'mt') and not isData:
                floatVarsDict['genEventWeight'][0] = floatVarsDict['genEventWeight'][0]*0.95 #tauID

            if options.againstLeptonSF:
                if iFS == 'et':
                    if (iTree.tIsPromptElectron):
                        floatVarsDict['genEventWeight'][0] = floatVarsDict['genEventWeight'][0]*plots_dataDrivenQCDandWJ.getAgainstLeptonSF('electron', 'Tight', abs(iTree.eta_2))
                    if (iTree.tIsPromptMuon):
                        floatVarsDict['genEventWeight'][0] = floatVarsDict['genEventWeight'][0]*plots_dataDrivenQCDandWJ.getAgainstLeptonSF('muon', 'Loose', abs(iTree.eta_2))
                if iFS == 'mt':
                    if (iTree.tIsPromptElectron):
                        floatVarsDict['genEventWeight'][0] = floatVarsDict['genEventWeight'][0]*plots_dataDrivenQCDandWJ.getAgainstLeptonSF('electron', 'VLoose', abs(iTree.eta_2))
                    if (iTree.tIsPromptMuon):
                        floatVarsDict['genEventWeight'][0] = floatVarsDict['genEventWeight'][0]*plots_dataDrivenQCDandWJ.getAgainstLeptonSF('muon', 'Tight', abs(iTree.eta_2))



        if region == 'none':
            print "ERROR!!!!!"

        if region == "A":
            if charVarsDict['sampleName'][:31] in yieldDict.keys():
                yieldDict[str(charVarsDict['sampleName'][:31])] += floatVarsDict['triggerEff'][0]*floatVarsDict['PUWeight'][0]*floatVarsDict['genEventWeight'][0]*floatVarsDict['xs'][0]*plots.lumi/(intVarsDict['initSumWeights'][0]+ 0.0)
            else:
                yieldDict[str(charVarsDict['sampleName'][:31])] = floatVarsDict['triggerEff'][0]*floatVarsDict['PUWeight'][0]*floatVarsDict['genEventWeight'][0]*floatVarsDict['xs'][0]*plots.lumi/(intVarsDict['initSumWeights'][0]+ 0.0)
            if "WJets" in iSample:
                histDict["WJetsOSTight_MC"].Fill(1, floatVarsDict['triggerEff'][0]*floatVarsDict['PUWeight'][0]*floatVarsDict['genEventWeight'][0]*floatVarsDict['xs'][0]*plots.lumi/(intVarsDict['initSumWeights'][0]+ 0.0))
                yieldDict["WJetsOSTight_MC"] += floatVarsDict['triggerEff'][0]*floatVarsDict['PUWeight'][0]*floatVarsDict['genEventWeight'][0]*floatVarsDict['xs'][0]*plots.lumi/(intVarsDict['initSumWeights'][0]+ 0.0)
            oTree.Fill()

        elif region == "B":
            weight = 1
            if not isData:
                weight = -floatVarsDict['triggerEff'][0]*floatVarsDict['PUWeight'][0]*floatVarsDict['genEventWeight'][0]*floatVarsDict['xs'][0]*plots.lumi/(intVarsDict['initSumWeights'][0]+ 0.0)
            yieldDict["QCD_in_B"] += weight
            histDict["QCD_in_B"].Fill(1, weight)

        elif region == "C":
            if iFS == "em":
                charVarsDict['sampleName'][:31] = 'QCDLoose'
                if isData:
                    yieldDict["QCDLoose"] += 1
                else:
                    yieldDict["QCDLoose"] -= floatVarsDict['triggerEff'][0]*floatVarsDict['PUWeight'][0]*floatVarsDict['genEventWeight'][0]*floatVarsDict['xs'][0]*plots.lumi/(intVarsDict['initSumWeights'][0]+ 0.0)
                    floatVarsDict['genEventWeight'][0] = -1.0*floatVarsDict['genEventWeight'][0]
                oTree.Fill()
                if "WJets" in iSample:
                    floatVarsDict['genEventWeight'][0] = -1.0*floatVarsDict['genEventWeight'][0]
                    yieldDict['WJets' + controlRegionName] += floatVarsDict['triggerEff'][0]*floatVarsDict['PUWeight'][0]*floatVarsDict['genEventWeight'][0]*floatVarsDict['xs'][0]*plots.lumi/(intVarsDict['initSumWeights'][0]+ 0.0)
                    histDict["WJetsOSLoose_MC"].Fill(1, floatVarsDict['triggerEff'][0]*floatVarsDict['PUWeight'][0]*floatVarsDict['genEventWeight'][0]*floatVarsDict['xs'][0]*plots.lumi/(intVarsDict['initSumWeights'][0]+ 0.0))
                    charVarsDict['sampleName'][:31] = 'WJets' + controlRegionName
                    oTree.Fill()
            else:
                charVarsDict['sampleName'][:31] = 'WJetsLoose'
                if isData:
                    yieldDict['WJetsLoose'] += 1
                else:
                    floatVarsDict['genEventWeight'][0] = -1.0*floatVarsDict['genEventWeight'][0]
                    yieldDict['WJetsLoose'] += floatVarsDict['triggerEff'][0]*floatVarsDict['PUWeight'][0]*floatVarsDict['genEventWeight'][0]*floatVarsDict['xs'][0]*plots.lumi/(intVarsDict['initSumWeights'][0]+ 0.0)
                oTree.Fill()

        elif region == "D":
            weight = 1
            if not isData:
                weight = -floatVarsDict['triggerEff'][0]*floatVarsDict['PUWeight'][0]*floatVarsDict['genEventWeight'][0]*floatVarsDict['xs'][0]*plots.lumi/(intVarsDict['initSumWeights'][0]+ 0.0)
            yieldDict["QCD_in_D"] += weight
            histDict["QCD_in_D"].Fill(1, weight)

        elif region == "E" and iFS != 'em' and isData:
            yieldDict["QCDLoose"] += 1
            oTree_tmp.Fill()
            oTree.Fill()

        elif region == "F" and iFS != 'em' and isData:
            yieldDict["QCD_in_F"] += 1
            histDict["QCD_in_F"].Fill(1, 1)

    return yieldDict, histDict
コード例 #53
0
def loop(iSample, hist, t_hist):
    file = r.TFile(iSample)
    tree = file.Get('Ntuple')
    nEntries = tree.GetEntries()
    counter = 0
    for iEntry in range(nEntries):
        tree.GetEntry(iEntry)
        tool.printProcessStatus(iEntry, nEntries,
                                'Looping sample %s' % (iSample), iEntry - 1)

        if not (tree.tByTightIsolationMVArun2v1DBnewDMwLT > 0.5):
            continue
#         if not ( 0. < tree.cosDPhi_MEt_1 < 0.9 and 70 < tree.mt_1):
#             continue
#         if (tree.cosDPhi_MEt_2 > 0.9):
#             continue

        if not (tree.cosDPhi_MEt_1 > 0.9 or
                (tree.cosDPhi_MEt_2 > 0.9 and tree.mt_1 > 120)):
            continue
        if tree.q_1 == tree.q_2:
            continue

        electronVar = 'm_eff'  #'mPt'
        #electron
        if tree.eIsPromptElectron:
            hist.Fill(getattr(tree, electronVar), 0)
        elif tree.eIsPromptMuon:
            hist.Fill(getattr(tree, electronVar), 1)
        elif tree.eIsTau2Electron:
            hist.Fill(getattr(tree, electronVar), 2)
        elif tree.eIsTau2Muon:
            hist.Fill(getattr(tree, electronVar), 3)
        elif tree.eIsTauh:
            hist.Fill(getattr(tree, electronVar), 4)
        else:
            hist.Fill(getattr(tree, electronVar), 5)


#          if counter < 10:
#             print ''
#             print 'lumi: %i, event: %i' %(tree.lumi, tree.evt)
#             print "ePt: %.3f, eEta: %.3f, ePhi: %.3f" %(tree.ePt, tree.eEta, tree.ePhi)
#             print "tPt: %.3f, tEta: %.3f, tPhi: %.3f" %(tree.tPt, tree.tEta, tree.tPhi)
#             print "********************************"
#             counter += 1

        muonVar = 'm_eff'  #'mPt'
        #         muon
        #         if tree.mIsPromptElectron:
        #             hist.Fill(getattr(tree, muonVar), 0)
        #         elif tree.mIsPromptMuon:
        #             hist.Fill(getattr(tree, muonVar), 1)
        #         elif tree.mIsTau2Electron:
        #             hist.Fill(getattr(tree, muonVar), 2)
        #         elif tree.mIsTau2Muon:
        #             hist.Fill(getattr(tree, muonVar), 3)
        #         elif tree.mIsTauh:
        #             hist.Fill(getattr(tree, muonVar), 4)
        #         else:
        #             hist.Fill(getattr(tree, muonVar), 5)

        tauVar = 'm_eff'  #'tPt'
        #         tau
        if tree.tIsPromptElectron:
            t_hist.Fill(getattr(tree, tauVar), 0)
        elif tree.tIsPromptMuon:
            t_hist.Fill(getattr(tree, tauVar), 1)
        elif tree.tIsTau2Electron:
            t_hist.Fill(getattr(tree, tauVar), 2)
        elif tree.tIsTau2Muon:
            t_hist.Fill(getattr(tree, tauVar), 3)
        elif tree.tIsTauh:
            t_hist.Fill(getattr(tree, tauVar), 4)
        else:
            t_hist.Fill(getattr(tree, tauVar), 5)

    for i in range(len(labels)):
        hist.GetYaxis().SetBinLabel(i + 1, labels[i])
        t_hist.GetYaxis().SetBinLabel(i + 1, t_labels[i])

    return hist, t_hist  #, hist_eIsTau2E, hist_eIsTauh, hist_eIsTau2E_withTrigger, hist_eIsTauh_withTrigger
コード例 #54
0
    runRanges = {'A': (0,193621),
                'B': (193621,196531),
                'C': (196531,203742),
                'D': (203742,208686)}
    if runRanges[cut][0] < iTree.run <= runRanges[cut][1]:
        return True
    else:
        return False

options = opts()
iFile = options.inputFile
ifile = r.TFile('%s.root' %iFile)
iTree = ifile.Get(options.tree)
oFile = r.TFile("%s_%s.root" %(options.inputFile, options.cut),"recreate")
oTree = iTree.CloneTree(0)
total = iTree.GetEntries()
sigYeild = 0
for i in range(total):
    r.gStyle.SetOptStat(0)
    tool.printProcessStatus(iCurrent=i, total=total, processName = 'Looping sample %s' %iFile)
    iTree.GetEntry(i)
    if passCut(iTree, options.cut):
        oTree.Fill()
print ''

oFile.cd()
oTree.Write()
nSaved = oTree.GetEntries()
oFile.Close()

print 'saved %i events out of %i at: %s_%s.root' %(nSaved,total,options.inputFile, options.cut)
コード例 #55
0
def getYieldsFromFile(file):
    f = r.TFile(file)
    tree = f.Get('eventTree')
    total = tree.GetEntries()

    scaleDict = getScales(f)
    yieldsDict = {}
    yieldsDict['1M'] = {
        'QCD': 0.0,
        'tt': 0.0,
        'VV': 0.0,
        'ZTT': 0.0,
        'ZLL': 0.0,
        'signal': 0.0,
        'H2hh260': 0.0,
        'H2hh270': 0.0,
        'H2hh280': 0.0,
        'H2hh290': 0.0,
        'H2hh300': 0.0,
        'H2hh310': 0.0,
        'H2hh320': 0.0,
        'H2hh330': 0.0,
        'H2hh340': 0.0,
        'H2hh350': 0.0
    }
    yieldsDict['2M'] = {
        'QCD': 0.0,
        'tt': 0.0,
        'VV': 0.0,
        'ZTT': 0.0,
        'ZLL': 0.0,
        'signal': 0.0,
        'H2hh260': 0.0,
        'H2hh270': 0.0,
        'H2hh280': 0.0,
        'H2hh290': 0.0,
        'H2hh300': 0.0,
        'H2hh310': 0.0,
        'H2hh320': 0.0,
        'H2hh330': 0.0,
        'H2hh340': 0.0,
        'H2hh350': 0.0
    }

    for iEvent in range(total):
        tool.printProcessStatus(iEvent, total, 'Looping file [%s]' % (file))
        tree.GetEntry(iEvent)
        if not makeWholeTools2.passCut(tree):
            continue
        name = getSampleName(tree.sampleName)
        if name in yieldsDict['1M'].keys():
            if tree.Category == '0M':
                continue
            yieldsDict[tree.Category][name] += getWeight(tree, tree.sampleName)
    #rescale
    for cat in ['1M', '2M']:
        yieldsDict[cat]['ZTT'] = scaleDict[cat]['ZTT']
        yieldsDict[cat]['ZLL'] = scaleDict[cat]['ZLL']
        yieldsDict[cat][
            'VV'] = scaleDict[cat]['VV'] + scaleDict[cat]['singleT']
        yieldsDict[cat]['QCD'] = yieldsDict[cat]['QCD'] * scaleDict[cat]['QCD']
        for i in [
                'H2hh260', 'H2hh270', 'H2hh280', 'H2hh290', 'H2hh300',
                'H2hh310', 'H2hh320', 'H2hh330', 'H2hh340', 'H2hh350'
        ]:
            yieldsDict[cat]['signal'] += yieldsDict[cat][i]

    print ''
    return yieldsDict