Exemplo n.º 1
0
    def makeNonIsoLeptons( data ):

        goodLeptons = getGoodLeptons( data, collVars = leptonVars )
        allExtraLeptons = sorted( \
            [l for l in getLeptons( data, collVars = leptonVars ) if l not in goodLeptons] + getOtherLeptons( data , collVars = leptonVars ), 
                        key=lambda l: -l['pt'] )

        # print len(allLeptons), len(goodLeptons), len(allExtraLeptons) 
        assert len(goodLeptons)==2, "Analysis leptons not found!"
        l1, l2 = goodLeptons
        #print l1['pt'] - data.l1_pt, l2['pt'] - data.l2_pt
        data.allExtraLeptons = allExtraLeptons

        nonIsoMus  = filter(lambda l: abs(l['pdgId'])==13 and l['miniRelIso']>0.2 and l['pt']>5, allExtraLeptons )
        nonIsoEles = filter(lambda l: abs(l['pdgId'])==11 and l['miniRelIso']>0.2 and l['pt']>7, allExtraLeptons )
        #print nonIsoMus, nonIsoEles

        data.nonIsoMu  = nonIsoMus[-1] if len(nonIsoMus)>0 else None 
        data.nonIsoEle = nonIsoEles[-1] if len(nonIsoEles)>0 else None 

        # extra ele
        if data.nonIsoEle is not None:
            makeSwappedMT2ll( data, l1, l2, data.nonIsoEle, verbose = verbose)
        if data.nonIsoMu is not None:
            makeSwappedMT2ll( data, l1, l2, data.nonIsoMu, verbose = verbose)
        if verbose: print
Exemplo n.º 2
0
    def makeNonIsoLeptons(data):

        goodLeptons = getGoodLeptons(data, collVars=leptonVars)
        allExtraLeptons = sorted( \
            [l for l in getLeptons( data, collVars = leptonVars ) if l not in goodLeptons] + getOtherLeptons( data , collVars = leptonVars ),
                        key=lambda l: -l['pt'] )

        # print len(allLeptons), len(goodLeptons), len(allExtraLeptons)
        assert len(goodLeptons) == 2, "Analysis leptons not found!"
        l1, l2 = goodLeptons
        #print l1['pt'] - data.l1_pt, l2['pt'] - data.l2_pt
        data.allExtraLeptons = allExtraLeptons

        nonIsoMus = filter(
            lambda l: abs(l['pdgId']) == 13 and l['miniRelIso'] > 0.2 and l[
                'pt'] > 5, allExtraLeptons)
        nonIsoEles = filter(
            lambda l: abs(l['pdgId']) == 11 and l['miniRelIso'] > 0.2 and l[
                'pt'] > 7, allExtraLeptons)
        #print nonIsoMus, nonIsoEles

        data.nonIsoMu = nonIsoMus[-1] if len(nonIsoMus) > 0 else None
        data.nonIsoEle = nonIsoEles[-1] if len(nonIsoEles) > 0 else None

        # extra ele
        if data.nonIsoEle is not None:
            makeSwappedMT2ll(data, l1, l2, data.nonIsoEle, verbose=verbose)
        if data.nonIsoMu is not None:
            makeSwappedMT2ll(data, l1, l2, data.nonIsoMu, verbose=verbose)
        if verbose: print
        def makeLeptons( data ):
            goodLeptons = getGoodLeptons( data, collVars = leptonVars + extraLepVars )
            extraLeptons = sorted( \
                [l for l in getLeptons( data, collVars = leptonVars + extraLepVars) if l not in goodLeptons] \
                + getOtherLeptons( data , collVars = leptonVars + extraLepVars), 
                            key=lambda l: -l['pt'] )
            #print len(goodLeptons), len(getLeptons( data, collVars = leptonVars + extraLepVars)), len(getOtherLeptons( data , collVars = leptonVars + extraLepVars)), len(extraLeptons) 
            if len(goodLeptons)==2: 
                setattr( data, "goodLeptons", goodLeptons )
                setattr( data, "extraLeptons", extraLeptons )

                extraMu  = filter(lambda l: abs(l['pdgId'])==13 and l['relIso04']>0.5, extraLeptons )
                extraEle = filter(lambda l: abs(l['pdgId'])==11 and l['relIso04']>0.5, extraLeptons )

                setattr( data, "extraMu", extraMu[-1] if len(extraMu)>0 else None )
                setattr( data, "extraEle", extraEle[-1] if len(extraEle)>0 else None )

                # MT2ll
                mt2Calc.reset()
                l1, l2 = goodLeptons[0], goodLeptons[1]
                mt2Calc.setLeptons(l1["pt"], l1["eta"], l1["phi"], l2["pt"], l2["eta"], l2["phi"])
                mt2Calc.setMet(data.met_pt, data.met_phi)
                setattr( data, "mt2ll", mt2Calc.mt2ll())
                #print data.mt2ll
            else:
                setattr( data, "goodLeptons", None)
                setattr( data, "extraLeptons", None)
                setattr( data, "extraMu", None)
                setattr( data, "extraEle", None)
                setattr( data, "mt2ll", None)
Exemplo n.º 4
0
        def makeLeptons( data ):
            goodLeptons = getGoodLeptons( data, collVars = leptonVars + extraLepVars )
            extraLeptons = sorted( \
                [l for l in getLeptons( data, collVars = leptonVars + extraLepVars) if l not in goodLeptons] \
                + getOtherLeptons( data , collVars = leptonVars + extraLepVars), 
                            key=lambda l: -l['pt'] )
            setattr( data, "goodLeptons", goodLeptons )
            setattr( data, "extraLeptons", extraLeptons )

            extraMu  = filter(lambda l: abs(l['pdgId'])==13 and l['relIso04']>0.5, extraLeptons )
            extraEle = filter(lambda l: abs(l['pdgId'])==11 and l['relIso04']>0.5, extraLeptons )

            setattr( data, "extraMu", extraMu[-1] if len(extraMu)>0 else None )
            setattr( data, "extraEle", extraEle[-1] if len(extraEle)>0 else None )
Exemplo n.º 5
0
        def makeLeptons(data):
            goodLeptons = getGoodLeptons(data,
                                         collVars=leptonVars + extraLepVars)
            extraLeptons = sorted( \
                [l for l in getLeptons( data, collVars = leptonVars + extraLepVars) if l not in goodLeptons] \
                + getOtherLeptons( data , collVars = leptonVars + extraLepVars),
                            key=lambda l: -l['pt'] )
            setattr(data, "goodLeptons", goodLeptons)
            setattr(data, "extraLeptons", extraLeptons)

            extraMu = filter(
                lambda l: abs(l['pdgId']) == 13 and l['relIso04'] > 0.5,
                extraLeptons)
            extraEle = filter(
                lambda l: abs(l['pdgId']) == 11 and l['relIso04'] > 0.5,
                extraLeptons)

            setattr(data, "extraMu", extraMu[-1] if len(extraMu) > 0 else None)
            setattr(data, "extraEle",
                    extraEle[-1] if len(extraEle) > 0 else None)
Exemplo n.º 6
0
			isElecElec[0] = 1
		if not s["name"].find("DoubleMuon") and triggerMuMu :
			trigger = 1
			isMuonMuon[0] = 1
		if not s["name"].find("DoubleMuon") and triggerMuMu==0 :
			trigger = 0
			isMuonMuon[0] = 1
		if not s["name"].find("MuonEG") and triggerMuEle :
			trigger = 1
			isMuonElec[0] = 1
		if not s["name"].find("MuonEG") and triggerMuEle==0 :
			trigger = 0
			isMuonElec[0] = 1


		leptons = filter(lambda l: looseMuID(l) or looseEleID(l), getLeptons(chain))
		jets = filter(lambda j:j['pt']>30 and abs(j['eta'])<2.4 and j['id'], getJets(chain))
		bjets = filter(lambda j:j['btagCSV']>0.890, jets)

		nbjets[0] = len(bjets)
		njets[0] = len(jets)
		nleptons[0] = len(leptons)
		Process[:200] = s["name"]
		HT[0] = sum([j['pt'] for j in jets])


		PhiMetJet1 = deltaPhi(metPhi,getVarValue(chain, "Jet_phi",0))
		PhiMetJet2 = deltaPhi(metPhi,getVarValue(chain, "Jet_phi",1))

		if PhiMetJet1 <= PhiMetJet2: PhiMetJet_small = PhiMetJet1
		else:                        PhiMetJet_small = PhiMetJet2
Exemplo n.º 7
0
            chain, "weight") * lumiScale if not s['isData'] else 1
        mt2ll = getVarValue(chain, "dl_mt2ll")
        met = getVarValue(chain, "met_pt")
        metPhi = getVarValue(chain, "met_phi")
        genMet = getVarValue(chain, "met_genPt")
        genMetPhi = getVarValue(chain, "met_genPhi")
        deltaMet = sqrt((met * cos(metPhi) - genMet * cos(genMetPhi))**2 +
                        (met * sin(metPhi) - genMet * sin(genMetPhi))**2)
        jets = filter(
            lambda j: j['pt'] > 30 and abs(j['eta']) < 2.4 and j['id'],
            getJets(chain))

        allLeptons = getLeptons(
            chain,
            collVars=leptonVars + [
                'mcMatchId', 'mcMatchAny', 'mcMatchTau', 'mcPt', 'ip3d',
                'relIso03', 'relIso04', 'jetPtRatiov1', 'jetPtRelv1',
                'jetPtRelv2', 'jetPtRatiov2', 'jetBTagCSV', 'jetDR'
            ])
        leptons = filter(lambda l: looseMuID(l) or looseEleID(l), allLeptons)

        #LepGood_mcMatchId Match to source from hard scatter (pdgId of heaviest particle in chain, 25 for H, 6 for t, 23/24 for W/Z), zero if non-prompt or fake for Leptons after the preselection
        #LepGood_mcMatchAny  Match to any final state leptons: 0 if unmatched, 1 if light flavour (including prompt), 4 if charm, 5 if bottom for Leptons after the preselection
        #LepGood_mcMatchTau True if the leptons comes from a tau for Leptons after the preselection

        #    for l in leptons:
        #      if (l['mcMatchAny']==0 and (not (l['mcMatchId']==0))) or ( (not l['mcMatchAny']==0) and (l['mcMatchId']==0)):
        #        print "Match?",l

        #RECO
        looseMu = filter(
Exemplo n.º 8
0
def cutflow(sig):
    #######################################################
    #        SELECT WHAT YOU WANT TO DO HERE              #
    #######################################################
    reduceStat = 100  #recude the statistics, i.e. 10 is ten times less samples to look at

    #######################################################
    #         Define cutflow you want to make             #
    #######################################################
    mt2llcut = 80.
    metcut = 40.
    lumi = 10000.

    baselineamount = {
        'samples': {},
        'SoverB': None,
    }

    cutflow = {\
      'metsig':{'baseline': 0.,
                'cuts': {\
                  3:{'samples':{}, 'SoverB': None},
                  4:{'samples':{}, 'SoverB': None},
                  5:{'samples':{}, 'SoverB': None},
                  6:{'samples':{}, 'SoverB': None},
                  7:{'samples':{}, 'SoverB': None},
                  8:{'samples':{}, 'SoverB': None},
                  9:{'samples':{}, 'SoverB': None},
                  10:{'samples':{}, 'SoverB': None},
                  10:{'samples':{}, 'SoverB': None},
                  },
                'event': None,
                },
      'nbjets':{'baseline': 1.,
                'cuts': {\
                  0:{'samples':{}, 'SoverB': None},
                  1:{'samples':{}, 'SoverB': None},
                  2:{'samples':{}, 'SoverB': None},
                  3:{'samples':{}, 'SoverB': None},
                  4:{'samples':{}, 'SoverB': None},
                  5:{'samples':{}, 'SoverB': None},
                  },
                'event': None,
                },
      'njets': {'baseline': 2.,
                'cuts': {\
                  1:{'samples':{}, 'SoverB': None},
                  2:{'samples':{}, 'SoverB': None},
                  3:{'samples':{}, 'SoverB': None},
                  4:{'samples':{}, 'SoverB': None},
                  5:{'samples':{}, 'SoverB': None},
                  6:{'samples':{}, 'SoverB': None},
                  7:{'samples':{}, 'SoverB': None},
                  },
                'event': None,
                },
      'ht':    {'baseline': 0.,
                'cuts': {\
                  50: {'samples':{}, 'SoverB': None},
                  100:{'samples':{}, 'SoverB': None},
                  200:{'samples':{}, 'SoverB': None},
                  300:{'samples':{}, 'SoverB': None},
                  400:{'samples':{}, 'SoverB': None},
                  500:{'samples':{}, 'SoverB': None},
                  },
                'event': None,
                },
    }

    #preselection: MET>40, njets>=2, n_bjets>=1, n_lep>=2
    #For now see here for the Sum$ syntax: https://root.cern.ch/root/html/TTree.html#TTree:Draw@2
    preselection = 'met_pt>' + str(metcut) + '&&Sum$(LepGood_pt>20)==2'

    #######################################################
    #                 load all the samples                #
    #######################################################
    backgrounds = [singleTop_50ns, DY_50ns, TTJets_50ns]
    #signals = [SMS_T2tt_2J_mStop425_mLSP325, SMS_T2tt_2J_mStop500_mLSP325, SMS_T2tt_2J_mStop650_mLSP325, SMS_T2tt_2J_mStop850_mLSP100]
    signal = [sig]

    #######################################################
    #            get the TChains for each sample          #
    #######################################################
    for s in backgrounds + signal:
        s['chain'] = getChain(s, histname="")

    #######################################################
    #            Start filling in the histograms          #
    #######################################################
    for s in backgrounds + signal:
        for cuttype in cutflow.keys():
            for cut in cutflow[cuttype]['cuts'].keys():
                cutflow[cuttype]['cuts'][cut]['samples'][s["name"]] = 0

        baselineamount['samples'][s['name']] = 0

        chain = s["chain"]
        #Using Event loop
        #get EList after preselection
        print "Looping over %s" % s["name"]
        eList = getEList(chain, preselection)
        nEvents = eList.GetN() / reduceStat
        print "Found %i events in %s after preselection %s, looping over %i" % (
            eList.GetN(), s["name"], preselection, nEvents)

        for ev in range(nEvents):
            increment = 50
            if nEvents > increment and ev % (nEvents / increment) == 0:
                sys.stdout.write(
                    '\r' + "=" * (ev / (nEvents / increment)) + " " *
                    ((nEvents - ev) / (nEvents / increment)) + "]" +
                    str(round((ev + 1) / (float(nEvents) / 100), 2)) + "%")
                sys.stdout.flush()
                sys.stdout.write('\r')
            chain.GetEntry(eList.GetEntry(ev))
            mt2Calc.reset()
            #event weight (L= 4fb^-1)
            weight = reduceStat * getVarValue(chain, "weight")

            weight = weight * (lumi / 4000.)

            #MET
            met = getVarValue(chain, "met_pt")
            metPhi = getVarValue(chain, "met_phi")
            #jetpt
            leadingjetpt = getVarValue(chain, "Jet_pt", 0)
            subleadingjetpt = getVarValue(chain, "Jet_pt", 1)
            #Leptons
            allLeptons = getLeptons(chain)
            muons = filter(looseMuID, allLeptons)
            electrons = filter(looseEleID, allLeptons)
            nlep = len(allLeptons)

            #SF and OF channels
            leptons = {\
              'mu':   {'name': 'mumu', 'file': muons},
              'e':   {'name': 'ee', 'file': electrons},
              'emu': {'name': 'emu', 'file': [electrons,muons]},
              }
            for lep in leptons.keys():
                twoleptons = False
                #Same Flavor
                if lep != 'emu':
                    if len(leptons[lep]['file']) == 2 and leptons[lep]['file'][
                            0]['pdgId'] * leptons[lep]['file'][1]['pdgId'] < 0:

                        twoleptons = True
                        l0pt, l0eta, l0phi = leptons[lep]['file'][0][
                            'pt'], leptons[lep]['file'][0]['eta'], leptons[
                                lep]['file'][0]['phi']
                        l1pt, l1eta, l1phi = leptons[lep]['file'][1][
                            'pt'], leptons[lep]['file'][1]['eta'], leptons[
                                lep]['file'][1]['phi']
                        leadingleptonpt = l0pt
                        subleadingleptonpt = l1pt
                        mll = sqrt(2. * l0pt * l1pt *
                                   (cosh(l0eta - l1eta) - cos(l0phi - l1phi)))
                        zveto = True
                #Opposite Flavor
                if lep == 'emu':
                    if len(leptons[lep]['file'][0]) == 1 and len(
                            leptons[lep]['file']
                        [1]) == 1 and leptons[lep]['file'][0][0][
                            'pdgId'] * leptons[lep]['file'][1][0]['pdgId'] < 0:

                        twoleptons = True
                        l0pt, l0eta, l0phi = leptons[lep]['file'][0][0][
                            'pt'], leptons[lep]['file'][0][0]['eta'], leptons[
                                lep]['file'][0][0]['phi']
                        l1pt, l1eta, l1phi = leptons[lep]['file'][1][0][
                            'pt'], leptons[lep]['file'][1][0]['eta'], leptons[
                                lep]['file'][1][0]['phi']
                        if l1pt > l0pt:
                            leadingleptonpt = l1pt
                            subleadingleptonpt = l0pt
                        else:
                            leadingleptonpt = l0pt
                            subleadingleptonpt = l1pt
                        mll = sqrt(2. * l0pt * l1pt *
                                   (cosh(l0eta - l1eta) - cos(l0phi - l1phi)))
                        zveto = False
                if (twoleptons and mll > 20
                        and not zveto) or (twoleptons and mll > 20 and zveto
                                           and abs(mll - 91.2) > 15):
                    mt2Calc.setMet(met, metPhi)
                    mt2Calc.setLeptons(l0pt, l0eta, l0phi, l1pt, l1eta, l1phi)
                    mt2ll = mt2Calc.mt2ll()
                    jets = filter(
                        lambda j: j['pt'] > 30 and abs(j['eta']) < 2.4 and j[
                            'id'], getJets(chain))
                    bjetspt = filter(lambda j: j['btagCSV'] > 0.89, jets)
                    nobjets = filter(lambda j: j['btagCSV'] <= 0.89, jets)
                    nmuons = len(muons)
                    nelectrons = len(electrons)
                    ht = sum([j['pt'] for j in jets])

                    if len(jets) < 1: continue
                    if mt2ll < mt2llcut: continue

                    cutflow['metsig']['event'] = met / sqrt(ht)
                    cutflow['nbjets']['event'] = len(bjetspt)
                    cutflow['njets']['event'] = len(jets)
                    cutflow['ht']['event'] = ht

                    for cuttype in cutflow.keys():
                        eventisgood = True
                        for cuttype2 in cutflow.keys():
                            if cuttype2 != cuttype:
                                if cutflow[cuttype2]['event'] < cutflow[
                                        cuttype2]['baseline']:
                                    eventisgood = False
                        if eventisgood:
                            for cut in cutflow[cuttype]['cuts']:
                                if cutflow[cuttype]['event'] >= cut:
                                    cutflow[cuttype]['cuts'][cut]['samples'][
                                        s['name']] += weight

                    baselineisgood = True
                    for cuttype in cutflow.keys():
                        if cutflow[cuttype]['event'] < cutflow[cuttype][
                                'baseline']:
                            baselineisgood = False
                    if baselineisgood:
                        baselineamount['samples'][s['name']] += weight

        del eList

    sigtot = baselineamount['samples'][signal[0]['name']]
    bkgtot = sum(baselineamount['samples'].values()) - sigtot

    if bkgtot > 0: baselineamount['SoverB'] = 100 * (sigtot / sqrt(bkgtot))
    else: baselineamount['SoverB'] = 0.

    for cuttype in cutflow.keys():
        for cut in cutflow[cuttype]['cuts']:
            sigtot = cutflow[cuttype]['cuts'][cut]['samples'][signal[0]
                                                              ['name']]
            bkgtot = sum(
                cutflow[cuttype]["cuts"][cut]['samples'].values()) - sigtot
            if bkgtot > 0:
                cutflow[cuttype]['cuts'][cut]['SoverB'] = 100 * (sigtot /
                                                                 sqrt(bkgtot))
            else:
                cutflow[cuttype]['cuts'][cut]['SoverB'] = 0.

    maketable(baselineamount, cutflow, mt2llcut, metcut, signal, lumi)
Exemplo n.º 9
0
            isElecElec[0] = 1
        if not s["name"].find("DoubleMuon") and triggerMuMu:
            trigger = 1
            isMuonMuon[0] = 1
        if not s["name"].find("DoubleMuon") and triggerMuMu == 0:
            trigger = 0
            isMuonMuon[0] = 1
        if not s["name"].find("MuonEG") and triggerMuEle:
            trigger = 1
            isMuonElec[0] = 1
        if not s["name"].find("MuonEG") and triggerMuEle == 0:
            trigger = 0
            isMuonElec[0] = 1

        leptons = filter(lambda l: looseMuID(l) or looseEleID(l),
                         getLeptons(chain))
        jets = filter(
            lambda j: j['pt'] > 30 and abs(j['eta']) < 2.4 and j['id'],
            getJets(chain))
        bjets = filter(lambda j: j['btagCSV'] > 0.890, jets)

        nbjets[0] = len(bjets)
        njets[0] = len(jets)
        nleptons[0] = len(leptons)
        Process[:200] = s["name"]
        HT[0] = sum([j['pt'] for j in jets])
        METSqrtHT[0] = met / HT[0]
        ptLeadingBJet[0] = bjets[0]['pt']
        etaLeadingBJet[0] = bjets[0]['eta']

        PhiMetJet1 = deltaPhi(metPhi, getVarValue(chain, "Jet_phi", 0))
Exemplo n.º 10
0
			isElecElec[0] = 1
		if not s["name"].find("DoubleMuon") and triggerMuMu :
			trigger = 1
			isMuonMuon[0] = 1
		if not s["name"].find("DoubleMuon") and triggerMuMu==0 :
			trigger = 0
			isMuonMuon[0] = 1
		if not s["name"].find("MuonEG") and triggerMuEle :
			trigger = 1
			isMuonElec[0] = 1
		if not s["name"].find("MuonEG") and triggerMuEle==0 :
			trigger = 0
			isMuonElec[0] = 1


		leptons = filter(lambda l: looseMuID(l) or looseEleID(l), getLeptons(chain))
		jets = filter(lambda j:j['pt']>30 and abs(j['eta'])<2.4 and j['id'], getJets(chain))
		bjets = filter(lambda j:j['btagCSV']>0.890, jets)

		nbjets[0] = len(bjets)
		njets[0] = len(jets)
		nleptons[0] = len(leptons)
		Process[:200] = s["name"]
		HT[0] = sum([j['pt'] for j in jets])
		METSqrtHT[0] = met/HT[0]
		ptLeadingBJet[0] = bjets[0]['pt'] 
		etaLeadingBJet[0] = bjets[0]['eta'] 

		PhiMetJet1 = deltaPhi(metPhi,getVarValue(chain, "Jet_phi",0))
		PhiMetJet2 = deltaPhi(metPhi,getVarValue(chain, "Jet_phi",1))
Exemplo n.º 11
0
    counterRecoGen_allMatched[mode]={}
    counterRecoGen_oneMuMatchedToB[mode]={}
    counterRecoGen_oneEleMatchedToB[mode]={}
    counterRecoGen_oneMuMatchedToTau[mode]={}
    counterRecoGen_oneEleMatchedToTau[mode]={}
  for ev in range(nEvents):
    ntot+=1
    if ev%10000==0:print "At %i/%i"%(ev,nEvents)
    chain.GetEntry(eList.GetEntry(ev))
    mt2Calc.reset()
    weight = reduceStat*getVarValue(chain, "weight")*lumiScale if not s['isData'] else 1
    met = getVarValue(chain, "met_pt")
    metPhi = getVarValue(chain, "met_phi")
    jets = filter(lambda j:j['pt']>30 and abs(j['eta'])<2.4 and j['id'], getJets(chain))

    leptons = filter(lambda l: looseMuID(l) or looseEleID(l), getLeptons(chain, collVars=leptonVars+['mcMatchId','mcMatchAny','mcMatchTau','mcPt']))
#LepGood_mcMatchId Match to source from hard scatter (pdgId of heaviest particle in chain, 25 for H, 6 for t, 23/24 for W/Z), zero if non-prompt or fake for Leptons after the preselection 
#LepGood_mcMatchAny  Match to any final state leptons: 0 if unmatched, 1 if light flavour (including prompt), 4 if charm, 5 if bottom for Leptons after the preselection
#LepGood_mcMatchTau True if the leptons comes from a tau for Leptons after the preselection

#    for l in leptons:
#      if (l['mcMatchAny']==0 and (not (l['mcMatchId']==0))) or ( (not l['mcMatchAny']==0) and (l['mcMatchId']==0)):
#        print "Match?",l

#RECO
    mu      = filter(lambda l: abs(l['pdgId'])==13, leptons)
    ele     = filter(lambda l: abs(l['pdgId'])==11, leptons)

#RECO mathes
    muMatched   = filter(lambda l: abs(l['mcMatchAny'])==1, mu)
    eleMatched  = filter(lambda l: abs(l['mcMatchAny'])==1, ele)
Exemplo n.º 12
0
        ntot += 1
        if ev % 10000 == 0: print "At %i/%i" % (ev, nEvents)
        chain.GetEntry(eList.GetEntry(ev))
        mt2Calc.reset()
        weight = reduceStat * getVarValue(
            chain, "weight") * lumiScale if not s['isData'] else 1
        met = getVarValue(chain, "met_pt")
        metPhi = getVarValue(chain, "met_phi")
        jets = filter(
            lambda j: j['pt'] > 30 and abs(j['eta']) < 2.4 and j['id'],
            getJets(chain))

        leptons = filter(
            lambda l: looseMuID(l) or looseEleID(l),
            getLeptons(chain,
                       collVars=leptonVars +
                       ['mcMatchId', 'mcMatchAny', 'mcMatchTau', 'mcPt']))
        #LepGood_mcMatchId Match to source from hard scatter (pdgId of heaviest particle in chain, 25 for H, 6 for t, 23/24 for W/Z), zero if non-prompt or fake for Leptons after the preselection
        #LepGood_mcMatchAny  Match to any final state leptons: 0 if unmatched, 1 if light flavour (including prompt), 4 if charm, 5 if bottom for Leptons after the preselection
        #LepGood_mcMatchTau True if the leptons comes from a tau for Leptons after the preselection

        #    for l in leptons:
        #      if (l['mcMatchAny']==0 and (not (l['mcMatchId']==0))) or ( (not l['mcMatchAny']==0) and (l['mcMatchId']==0)):
        #        print "Match?",l

        #RECO
        mu = filter(lambda l: abs(l['pdgId']) == 13, leptons)
        ele = filter(lambda l: abs(l['pdgId']) == 11, leptons)

        #RECO mathes
        muMatched = filter(lambda l: abs(l['mcMatchAny']) == 1, mu)
Exemplo n.º 13
0
#    lhe[i].GetXaxis().SetBinLabel(j+1, getBinName(bins[j]))


def getLHEWeights(c):
    res = {}
    for i in range(110):  #c.GetLeaf("nLHEweight").GetValue()):
        res[int(c.GetLeaf("LHEweight_id").GetValue(i))] = c.GetLeaf(
            "LHEweight_wgt").GetValue(i)
    return res


for ev in range(nEvents)[:maxN]:
    if ev % 10000 == 0: print "At %i/%i" % (ev, nEvents)
    c.GetEntry(eList.GetEntry(ev))
    weight = c.GetLeaf('genWeight').GetValue() * lumiScaleFactor
    leptons = getLeptons(c, leptonVars + ['relIso03']) + getOtherLeptons(
        c, leptonVars + ['relIso03'])
    ele = filter(lambda l: looseEleID(l), leptons)
    mu = filter(lambda l: looseMuID(l), leptons)
    ele = filter(lambda e: min([999] + [deltaR(m, e) for m in mu]) > 0.1, ele)
    lep = mu + ele
    lep.sort(key=lambda l: -l['pt'])
    if not (len(lep) == 3 and abs(closestOSDLMassToMZ(lep) - mZ) < 10):
        continue

    jets = getGoodJets(c)
    bTaggedJets = filter(lambda l: l['btagCSV'] > 0.605, jets)
    nJets = len(jets)
    nBTags = len(bTaggedJets)
    nBin = getBin(nJets, nBTags)
    if nBin < 0: continue
Exemplo n.º 14
0
    badElectronCandidates[mode]=[]
  for ev in range(nEvents):
    ntot+=1
    if ev%10000==0:print "At %i/%i"%(ev,nEvents)
    chain.GetEntry(eList.GetEntry(ev))
    mt2Calc.reset()
    weight = reduceStat*getVarValue(chain, "weight")*lumiScale if not s['isData'] else 1
    mt2ll = getVarValue(chain, "dl_mt2ll")
    met = getVarValue(chain, "met_pt")
    metPhi = getVarValue(chain, "met_phi")
    genMet = getVarValue(chain, "met_genPt")
    genMetPhi = getVarValue(chain, "met_genPhi")
    deltaMet = sqrt((met*cos(metPhi)-genMet*cos(genMetPhi))**2+(met*sin(metPhi)-genMet*sin(genMetPhi))**2)
    jets = filter(lambda j:j['pt']>30 and abs(j['eta'])<2.4 and j['id'], getJets(chain))

    allLeptons = getLeptons(chain, collVars=leptonVars+['mcMatchId','mcMatchAny','mcMatchTau','mcPt','ip3d', 'relIso03', 'relIso04', 'jetPtRatiov1', 'jetPtRelv1', 'jetPtRelv2', 'jetPtRatiov2', 'jetBTagCSV', 'jetDR'])
    leptons = filter(lambda l: looseMuID(l) or looseEleID(l), allLeptons)

#LepGood_mcMatchId Match to source from hard scatter (pdgId of heaviest particle in chain, 25 for H, 6 for t, 23/24 for W/Z), zero if non-prompt or fake for Leptons after the preselection 
#LepGood_mcMatchAny  Match to any final state leptons: 0 if unmatched, 1 if light flavour (including prompt), 4 if charm, 5 if bottom for Leptons after the preselection
#LepGood_mcMatchTau True if the leptons comes from a tau for Leptons after the preselection

#    for l in leptons:
#      if (l['mcMatchAny']==0 and (not (l['mcMatchId']==0))) or ( (not l['mcMatchAny']==0) and (l['mcMatchId']==0)):
#        print "Match?",l

#RECO
    looseMu = filter(lambda l: abs(l['pdgId'])==13 and l['miniRelIso']<0.4 and l['pt']>15, allLeptons)
    looseEle= filter(lambda l: abs(l['pdgId'])==11 and l['miniRelIso']<0.4 and l['pt']>15, allLeptons)
    mu      = filter(lambda l: abs(l['pdgId'])==13, leptons)
    ele     = filter(lambda l: abs(l['pdgId'])==11, leptons)
Exemplo n.º 15
0
      sys.stdout.write('\r')
    chain.GetEntry(eList.GetEntry(ev))
    mt2Calc.reset()
    #event weight (L= 4fb^-1)
    weight = reduceStat*getVarValue(chain, "weight")

    if s not in data: weight = weight*(luminosity/4000.)

    #MET
    met = getVarValue(chain, "met_pt")
    metPhi = getVarValue(chain, "met_phi")
    #jetpt
    leadingjetpt = getVarValue(chain, "Jet_pt",0)
    subleadingjetpt = getVarValue(chain, "Jet_pt",1)
    #Leptons 
    allLeptons = getLeptons(chain) 
    muons = filter(looseMuID, allLeptons)    
    electrons = filter(looseEleID, allLeptons)

    #SF and OF channels
    leptons = {\
      'mu':   {'name': 'mumu', 'file': muons},
      'e':   {'name': 'ee', 'file': electrons},
      'emu': {'name': 'emu', 'file': [electrons,muons]},
      }

    for lep in leptons.keys():
      twoleptons = False
      #Same Flavor
      if lep != 'emu':
        if len(leptons[lep]['file'])==2 and leptons[lep]['file'][0]['pdgId']*leptons[lep]['file'][1]['pdgId']<0:
Exemplo n.º 16
0
def cutflow(sig):
  #######################################################
  #        SELECT WHAT YOU WANT TO DO HERE              #
  #######################################################
  reduceStat = 100 #recude the statistics, i.e. 10 is ten times less samples to look at


  #######################################################
  #         Define cutflow you want to make             #
  #######################################################
  mt2llcut = 80.
  metcut = 40.
  lumi = 10000.

  baselineamount = { 'samples':{}, 'SoverB': None,}

  cutflow = {\
    'metsig':{'baseline': 0., 
              'cuts': {\
                3:{'samples':{}, 'SoverB': None}, 
                4:{'samples':{}, 'SoverB': None}, 
                5:{'samples':{}, 'SoverB': None}, 
                6:{'samples':{}, 'SoverB': None},
                7:{'samples':{}, 'SoverB': None},
                8:{'samples':{}, 'SoverB': None},
                9:{'samples':{}, 'SoverB': None},
                10:{'samples':{}, 'SoverB': None},
                10:{'samples':{}, 'SoverB': None},
                },
              'event': None,
              },
    'nbjets':{'baseline': 1., 
              'cuts': {\
                0:{'samples':{}, 'SoverB': None}, 
                1:{'samples':{}, 'SoverB': None}, 
                2:{'samples':{}, 'SoverB': None}, 
                3:{'samples':{}, 'SoverB': None},
                4:{'samples':{}, 'SoverB': None},
                5:{'samples':{}, 'SoverB': None},
                },
              'event': None,
              },
    'njets': {'baseline': 2., 
              'cuts': {\
                1:{'samples':{}, 'SoverB': None}, 
                2:{'samples':{}, 'SoverB': None}, 
                3:{'samples':{}, 'SoverB': None},
                4:{'samples':{}, 'SoverB': None},
                5:{'samples':{}, 'SoverB': None},
                6:{'samples':{}, 'SoverB': None},
                7:{'samples':{}, 'SoverB': None},
                },
              'event': None,
              },
    'ht':    {'baseline': 0., 
              'cuts': {\
                50: {'samples':{}, 'SoverB': None}, 
                100:{'samples':{}, 'SoverB': None}, 
                200:{'samples':{}, 'SoverB': None},
                300:{'samples':{}, 'SoverB': None},
                400:{'samples':{}, 'SoverB': None},
                500:{'samples':{}, 'SoverB': None},
                },
              'event': None,
              },
  }

  #preselection: MET>40, njets>=2, n_bjets>=1, n_lep>=2
  #For now see here for the Sum$ syntax: https://root.cern.ch/root/html/TTree.html#TTree:Draw@2
  preselection = 'met_pt>'+str(metcut)+'&&Sum$(LepGood_pt>20)==2'

  #######################################################
  #                 load all the samples                #
  #######################################################
  backgrounds = [singleTop_50ns,DY_50ns,TTJets_50ns]
  #signals = [SMS_T2tt_2J_mStop425_mLSP325, SMS_T2tt_2J_mStop500_mLSP325, SMS_T2tt_2J_mStop650_mLSP325, SMS_T2tt_2J_mStop850_mLSP100]
  signal = [sig]

  #######################################################
  #            get the TChains for each sample          #
  #######################################################
  for s in backgrounds+signal:
    s['chain'] = getChain(s,histname="")


  #######################################################
  #            Start filling in the histograms          #
  #######################################################
  for s in backgrounds+signal:
    for cuttype in cutflow.keys():
      for cut in cutflow[cuttype]['cuts'].keys():
        cutflow[cuttype]['cuts'][cut]['samples'][s["name"]] = 0

    baselineamount['samples'][s['name']] = 0

    chain = s["chain"]
    #Using Event loop
    #get EList after preselection
    print "Looping over %s" % s["name"]
    eList = getEList(chain, preselection) 
    nEvents = eList.GetN()/reduceStat
    print "Found %i events in %s after preselection %s, looping over %i" % (eList.GetN(),s["name"],preselection,nEvents)

    for ev in range(nEvents):
      increment = 50
      if nEvents>increment and ev%(nEvents/increment)==0: 
        sys.stdout.write('\r' + "=" * (ev / (nEvents/increment)) +  " " * ((nEvents - ev)/ (nEvents/increment)) + "]" +  str(round((ev+1) / (float(nEvents)/100),2)) + "%")
        sys.stdout.flush()
        sys.stdout.write('\r')
      chain.GetEntry(eList.GetEntry(ev))
      mt2Calc.reset()
      #event weight (L= 4fb^-1)
      weight = reduceStat*getVarValue(chain, "weight")

      weight = weight*(lumi/4000.)

      #MET
      met = getVarValue(chain, "met_pt")
      metPhi = getVarValue(chain, "met_phi")
      #jetpt
      leadingjetpt = getVarValue(chain, "Jet_pt",0)
      subleadingjetpt = getVarValue(chain, "Jet_pt",1)
      #Leptons 
      allLeptons = getLeptons(chain) 
      muons = filter(looseMuID, allLeptons)    
      electrons = filter(looseEleID, allLeptons)
      nlep = len(allLeptons)

      #SF and OF channels
      leptons = {\
        'mu':   {'name': 'mumu', 'file': muons},
        'e':   {'name': 'ee', 'file': electrons},
        'emu': {'name': 'emu', 'file': [electrons,muons]},
        }
      for lep in leptons.keys():
        twoleptons = False
        #Same Flavor
        if lep != 'emu':
          if len(leptons[lep]['file'])==2 and leptons[lep]['file'][0]['pdgId']*leptons[lep]['file'][1]['pdgId']<0:

            twoleptons = True
            l0pt, l0eta, l0phi = leptons[lep]['file'][0]['pt'],  leptons[lep]['file'][0]['eta'],  leptons[lep]['file'][0]['phi']
            l1pt, l1eta, l1phi = leptons[lep]['file'][1]['pt'],  leptons[lep]['file'][1]['eta'],  leptons[lep]['file'][1]['phi']
            leadingleptonpt = l0pt
            subleadingleptonpt = l1pt
            mll = sqrt(2.*l0pt*l1pt*(cosh(l0eta-l1eta)-cos(l0phi-l1phi)))
            zveto = True
        #Opposite Flavor
        if lep == 'emu':
          if len(leptons[lep]['file'][0])==1 and len(leptons[lep]['file'][1])==1 and leptons[lep]['file'][0][0]['pdgId']*leptons[lep]['file'][1][0]['pdgId']<0:

            twoleptons = True
            l0pt, l0eta, l0phi = leptons[lep]['file'][0][0]['pt'],  leptons[lep]['file'][0][0]['eta'],  leptons[lep]['file'][0][0]['phi']
            l1pt, l1eta, l1phi = leptons[lep]['file'][1][0]['pt'],  leptons[lep]['file'][1][0]['eta'],  leptons[lep]['file'][1][0]['phi']
            if l1pt > l0pt :
              leadingleptonpt = l1pt
              subleadingleptonpt = l0pt
            else:
              leadingleptonpt = l0pt
              subleadingleptonpt = l1pt
            mll = sqrt(2.*l0pt*l1pt*(cosh(l0eta-l1eta)-cos(l0phi-l1phi)))
            zveto = False
        if (twoleptons and mll>20 and not zveto) or (twoleptons and mll > 20 and zveto and abs(mll-90.2)>15):
          mt2Calc.setMet(met,metPhi)
          mt2Calc.setLeptons(l0pt, l0eta, l0phi, l1pt, l1eta, l1phi)        
          mt2ll = mt2Calc.mt2ll()
          jets = filter(lambda j:j['pt']>30 and abs(j['eta'])<2.4 and j['id'], getJets(chain))
          bjetspt = filter(lambda j:j['btagCSV']>0.89, jets)
          nobjets = filter(lambda j:j['btagCSV']<=0.89, jets)
          nmuons = len(muons)
          nelectrons = len(electrons)
          ht = sum([j['pt'] for j in jets])


          if len(jets)<1: continue
          if mt2ll<mt2llcut: continue 

          cutflow['metsig']['event'] = met/sqrt(ht)
          cutflow['nbjets']['event'] = len(bjetspt)
          cutflow['njets']['event'] = len(jets)
          cutflow['ht']['event'] = ht

          for cuttype in cutflow.keys():
            eventisgood = True
            for cuttype2 in cutflow.keys():
              if cuttype2 != cuttype:
                if cutflow[cuttype2]['event'] < cutflow[cuttype2]['baseline']:
                  eventisgood = False
            if eventisgood:
              for cut in cutflow[cuttype]['cuts']:
                if cutflow[cuttype]['event'] >= cut:
                  cutflow[cuttype]['cuts'][cut]['samples'][s['name']] += weight

          baselineisgood = True
          for cuttype in cutflow.keys():
            if cutflow[cuttype]['event'] < cutflow[cuttype]['baseline']:
              baselineisgood = False
          if baselineisgood:
            baselineamount['samples'][s['name']] += weight

    del eList

  sigtot = baselineamount['samples'][signal[0]['name']]
  bkgtot = sum(baselineamount['samples'].values()) - sigtot

  if bkgtot > 0: baselineamount['SoverB'] = 100 * (sigtot/sqrt(bkgtot))
  else:          baselineamount['SoverB'] = 0.

  for cuttype in cutflow.keys(): 
    for cut in cutflow[cuttype]['cuts']:
      sigtot = cutflow[cuttype]['cuts'][cut]['samples'][signal[0]['name']]
      bkgtot = sum(cutflow[cuttype]["cuts"][cut]['samples'].values()) - sigtot
      if bkgtot > 0: cutflow[cuttype]['cuts'][cut]['SoverB'] = 100 * (sigtot/sqrt(bkgtot))
      else:          cutflow[cuttype]['cuts'][cut]['SoverB'] = 0.

  maketable(baselineamount, cutflow, mt2llcut, metcut,signal,lumi)
Exemplo n.º 17
0
#for i in range(110):
#  lhe[i] = ROOT.TH1F("lhe_"+str(i), "lhe_"+str(i), len(bins),0,len(bins))
#  for j in range(len(bins)):
#    lhe[i].GetXaxis().SetBinLabel(j+1, getBinName(bins[j]))

def getLHEWeights(c):
    res={}
    for i in range(110):#c.GetLeaf("nLHEweight").GetValue()):
        res[int(c.GetLeaf("LHEweight_id").GetValue(i))] = c.GetLeaf("LHEweight_wgt").GetValue(i)
    return res

for ev in range(nEvents)[:maxN]:
    if ev%10000==0:print "At %i/%i"%(ev,nEvents)
    c.GetEntry(eList.GetEntry(ev))
    weight = c.GetLeaf('genWeight').GetValue()*lumiScaleFactor
    leptons = getLeptons(c, leptonVars+['relIso03'])+getOtherLeptons(c, leptonVars+['relIso03'])
    ele = filter(lambda l:looseEleID(l), leptons)
    mu  = filter(lambda l:looseMuID(l), leptons)
    ele = filter(lambda e:min([999]+[deltaR(m, e) for m in mu])>0.1, ele)
    lep = mu+ele
    lep.sort(key=lambda l:-l['pt'])
    if not (len(lep)==3 and abs( closestOSDLMassToMZ(lep) - mZ)< 10): continue

    jets = getGoodJets(c)
    bTaggedJets = filter(lambda l:l['btagCSV']>0.605, jets)
    nJets = len(jets)
    nBTags = len(bTaggedJets)
    nBin = getBin(nJets, nBTags)
    if nBin<0:continue
#  print "#e %i #m %i #j %i  #b %i n-bin %i"%(len(ele), len(mu), nJets, nBTags, nBin)
    central.Fill(nBin, weight)