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)
Exemple #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 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
Exemple #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 )
Exemple #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)
Exemple #6
0
        if s not in data: weight = weight * (luminosity / 1000.)

        #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
        l0pt = getVarValue(chain, "l1_pt")
        l1pt = getVarValue(chain, "l2_pt")
        mll = getVarValue(chain, "dl_mass")

        #Leptons
        allLeptons = getGoodLeptons(chain)
        muons = getGoodMuons(chain)
        electrons = getGoodElectrons(chain)

        isEE = getVarValue(chain, "isEE")
        isMuMu = getVarValue(chain, "isMuMu")
        isEMu = getVarValue(chain, "isEMu")

        #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():
Exemple #7
0
 eList = getEList(chain, preselection)
 nEvents = eList.GetN() / reduceStat
 print "Found %i events in %s after preselection %s, looping over %i" % (
     eList.GetN(), sample["name"], preselection, nEvents)
 for ev in range(nEvents):
     if ev % 10000 == 0: print "At %i/%i" % (ev, nEvents)
     chain.GetEntry(eList.GetEntry(ev))
     mt2Calc.reset()
     weight = reduceStat * getVarValue(chain, "weight") * lumiScale
     met = getVarValue(chain, "met_pt")
     metPhi = getVarValue(chain, "met_phi")
     puppiMet = getVarValue(chain, "puppiMet_pt")
     puppiMetPhi = getVarValue(chain, "puppiMet_phi")
     genMet = getVarValue(chain, "met_genPt")
     genMetPhi = getVarValue(chain, "met_genPhi")
     leptons = getGoodLeptons(
         chain, leptonVars + ['mcMatchId', 'mcMatchAny', 'mcPt'])
     l0GenPt, l0HasMatch, l0pt, l0eta, l0phi = leptons[0]['mcPt'], abs(
         leptons[0]['mcMatchId']
     ) == 6, leptons[0]['pt'], leptons[0]['eta'], leptons[0]['phi']
     l1GenPt, l1HasMatch, l1pt, l1eta, l1phi = leptons[1]['mcPt'], abs(
         leptons[1]['mcMatchId']
     ) == 6, leptons[1]['pt'], leptons[1]['eta'], leptons[1]['phi']
     mll = sqrt(2. * l0pt * l1pt *
                (cosh(l0eta - l1eta) - cos(l0phi - l1phi)))
     jets = filter(
         lambda j: j['pt'] > 30 and abs(j['eta']) < 2.4 and j['id'],
         getJets(chain, jetVars + ['mcPt', 'mcMatchId', 'mcFlavour']))
     #  bjets = filter(lambda j:j['btagCSV']>0.890, jets)
     #  print len(leptons), len(bjets), mll
     mt2Calc.setMet(met, metPhi)
     mt2Calc.setLeptons(l0pt, l0eta, l0phi, l1pt, l1eta, l1phi)
    weight = weight*(luminosity/1000.)

    #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
    l0pt = getVarValue(chain, "l1_pt")
    l1pt = getVarValue(chain, "l2_pt")
    mll = getVarValue(chain,"dl_mass")
          
    #Leptons 
    allLeptons = getGoodLeptons(chain)
    muons = getGoodMuons(chain)
    electrons = getGoodElectrons(chain)

    #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 (len(muons)+len(electrons))==2 and leptons[lep]['file'][0]['pdgId']*leptons[lep]['file'][1]['pdgId']<0:
Exemple #9
0
    print "Looping over %s" % sample["name"]
    eList = getEList(chain, preselection)
    nEvents = eList.GetN()/reduceStat
    print "Found %i events in %s after preselection %s, looping over %i" % (eList.GetN(),sample["name"],preselection,nEvents)
    for ev in range(nEvents):
        if ev%10000==0:print "At %i/%i"%(ev,nEvents)
        chain.GetEntry(eList.GetEntry(ev))
        mt2Calc.reset()
        weight = reduceStat*getVarValue(chain, "weight")*lumiScale
        met = getVarValue(chain, "met_pt")
        metPhi = getVarValue(chain, "met_phi")
        puppiMet = getVarValue(chain, "puppiMet_pt")
        puppiMetPhi = getVarValue(chain, "puppiMet_phi")
        genMet = getVarValue(chain, "met_genPt")
        genMetPhi = getVarValue(chain, "met_genPhi")
        leptons = getGoodLeptons(chain, leptonVars+['mcMatchId', 'mcMatchAny', 'mcPt'])
        l0GenPt, l0HasMatch, l0pt, l0eta, l0phi = leptons[0]['mcPt'],  abs(leptons[0]['mcMatchId'])==6, leptons[0]['pt'],  leptons[0]['eta'],  leptons[0]['phi']
        l1GenPt, l1HasMatch, l1pt, l1eta, l1phi = leptons[1]['mcPt'],  abs(leptons[1]['mcMatchId'])==6, leptons[1]['pt'],  leptons[1]['eta'],  leptons[1]['phi']
        mll = sqrt(2.*l0pt*l1pt*(cosh(l0eta-l1eta)-cos(l0phi-l1phi)))
        jets = filter(lambda j:j['pt']>30 and abs(j['eta'])<2.4 and j['id'], getJets(chain, jetVars+['mcPt', 'mcMatchId', 'mcFlavour']))
    #  bjets = filter(lambda j:j['btagCSV']>0.890, jets)
    #  print len(leptons), len(bjets), mll
        mt2Calc.setMet(met,metPhi)
        mt2Calc.setLeptons(l0pt, l0eta, l0phi, l1pt, l1eta, l1phi)
        mt2ll = mt2Calc.mt2ll()
        plots['mt2ll_reco']['histo'][sample["name"]].Fill(mt2ll, weight)

        mt2Calc.setMet(puppiMet,puppiMetPhi)
        mt2ll = mt2Calc.mt2ll()
        plots['mt2ll_puppi']['histo'][sample["name"]].Fill(mt2ll, weight)
        for var in v['vars']:
          t.SetBranchAddress(var['stage1Name'], ROOT.AddressOf(r, var['stage1Name']))
      for a in aliases:
        t.SetAlias(*(a.split(":")))
      print "File: %s Chunk: %s nEvents: %i (skim: %s) condition: %s lumiScaleFactor: %f"%(chunk['file'],chunk['name'], nEvents, options.skim, skimCond, lumiScaleFactor)
      
      for i in range(nEvents):
        if (i%10000 == 0) and i>0 :
          print i,"/",nEvents  , "name:" , chunk['name']
        s.init()
        r.init()
        t.GetEntry(i)
        genWeight = 1 if sample['isData'] else t.GetLeaf('genWeight').GetValue()
        s.weight = lumiScaleFactor*genWeight
        if options.skim.lower()=='dilep':
          leptons = getGoodLeptons(r)
          s.nGoodMuons      = len(filter( lambda l:abs(l['pdgId'])==13, leptons))
          s.nGoodElectrons  = len(filter( lambda l:abs(l['pdgId'])==11, leptons))
#          print "Leptons", leptons 
          if len(leptons)>=2:# and leptons[0]['pdgId']*leptons[1]['pdgId']<0 and abs(leptons[0]['pdgId'])==abs(leptons[1]['pdgId']): #OSSF choice
            mt2Calc.reset()
            s.l1_pt  = leptons[0]['pt'] 
            s.l1_eta = leptons[0]['eta']
            s.l1_phi = leptons[0]['phi']
            s.l1_mass   = leptons[0]['mass']
            s.l1_pdgId  = leptons[0]['pdgId']
            s.l1_index  = leptons[0]['index']
            s.l2_pt  = leptons[1]['pt'] 
            s.l2_eta = leptons[1]['eta']
            s.l2_phi = leptons[1]['phi']
            s.l2_mass   = leptons[1]['mass']
def filler(s):
    # shortcut
    r = reader.data
    if isMC: gPart = getGenPartsAll(r)

    # weight
    if options.T2tt:
        s.weight=signalWeight[(r.GenSusyMScan1, r.GenSusyMScan2)]['weight']
        s.mStop = r.GenSusyMScan1
        s.mNeu  = r.GenSusyMScan2
        s.reweightXSecUp    = signalWeight[(r.GenSusyMScan1, r.GenSusyMScan2)]['xSecFacUp']
        s.reweightXSecDown  = signalWeight[(r.GenSusyMScan1, r.GenSusyMScan2)]['xSecFacDown']
    elif isMC:
        s.weight = lumiScaleFactor*r.genWeight if lumiScaleFactor is not None else 1
    elif isData:
        s.weight = 1
    else:
        raise NotImplementedError( "isMC %r isData %r T2tt? %r TTDM?" % (isMC, isData, options.T2tt, options.TTDM) )

    # lumi lists and vetos
    if isData:
        s.vetoPassed  = vetoList.passesVeto(r.run, r.lumi, r.evt)
        s.jsonPassed  = lumiList.contains(r.run, r.lumi)
        # store decision to use after filler has been executed
        s.jsonPassed_ = s.jsonPassed

    if isMC:
        s.reweightPU     = puRW(r.nTrueInt)
        s.reweightPUDown = puRWDown(r.nTrueInt)
        s.reweightPUUp   = puRWUp(r.nTrueInt)

    # top pt reweighting
    if isMC: s.reweightTopPt = topPtReweightingFunc(getTopPtsForReweighting(r))/topScaleF if doTopPtReweighting else 1.

    # jet/met related quantities, also load the leptons already
    allJets      = getGoodJets(r, ptCut=0, jetVars = jetVarNames )
    jets         = filter(lambda j:jetId(j, ptCut=30, absEtaCut=2.4), allJets)
    bJets        = filter(lambda j:isBJet(j), jets)
    nonBJets     = filter(lambda j:not isBJet(j), jets)
    if isVeryLoose:
        # all leptons up to relIso 1
        miniRelIso = 999.
        ptCut = 20 if not isVeryLoosePt10 else 10 
        leptons_pt10 = getGoodAndOtherLeptons(r, ptCut=10, miniRelIso = miniRelIso , dz = 0.1, dxy = 1.)
        leptons      = filter(lambda l:l['pt']>ptCut, leptons_pt10)
    elif isLoose:
        # reliso 0.4
        miniRelIso = 0.4
        leptons_pt10 = getGoodLeptons(r, ptCut=10, miniRelIso = miniRelIso)
        leptons      = filter(lambda l:l['pt']>20, leptons_pt10)
    else:
        miniRelIso = 0.2
        leptons_pt10 = getGoodLeptons(r, ptCut=10, miniRelIso = miniRelIso)
        # relIso 0.2
        leptons      = filter(lambda l:l['pt']>20, leptons_pt10)

    s.met_pt  = r.met_pt
    s.met_phi = r.met_phi

    # Filling jets
    s.nJetGood   = len(jets)
    for iJet, jet in enumerate(jets):
        for b in jetVarNames:
            getattr(s, "JetGood_"+b)[iJet] = jet[b]
    if isSingleLep:
        # Compute M3 and the three indiced of the jets entering m3
        s.m3, s.m3_ind1, s.m3_ind2, s.m3_ind3 = m3( jets )

    s.ht         = sum([j['pt'] for j in jets])
    s.metSig     = s.met_pt/sqrt(s.ht) if s.ht>0 else float('nan')
    s.nBTag      = len(bJets)

    jets_sys      = {}
    bjets_sys     = {}
    nonBjets_sys  = {}

    metVariants = [''] # default

    # Keep photons and estimate met including (leading pt) photon
    if options.keepPhotons:
       photons = getGoodPhotons(r, ptCut=20, idLevel="loose", isData=isData)
       s.nPhotonGood = len(photons)
       if s.nPhotonGood > 0:
         metVariants += ['_photonEstimated']  # do all met calculations also for the photonEstimated variant
         s.photon_pt         = photons[0]['pt']
         s.photon_eta        = photons[0]['eta']
         s.photon_phi        = photons[0]['phi']
         s.photon_idCutBased = photons[0]['idCutBased']
         if isMC:
           genPhoton       = getGenPhoton(gPart)
           s.photon_genPt  = genPhoton['pt']  if genPhoton is not None else float('nan')
           s.photon_genEta = genPhoton['eta'] if genPhoton is not None else float('nan')

         s.met_pt_photonEstimated, s.met_phi_photonEstimated = getMetPhotonEstimated(r.met_pt, r.met_phi, photons[0])
         s.metSig_photonEstimated = s.met_pt_photonEstimated/sqrt(s.ht) if s.ht>0 else float('nan')

         s.photonJetdR = min(deltaR(photons[0], j) for j in jets) if len(jets) > 0 else 999
         s.photonLepdR = min(deltaR(photons[0], l) for l in leptons_pt10) if len(leptons_pt10) > 0 else 999

    if options.checkTTGJetsOverlap and isMC:
       s.TTGJetsEventType = getTTGJetsEventType(r)

    if addSystematicVariations:
        for j in allJets:
            j['pt_JECUp']   =j['pt']/j['corr']*j['corr_JECUp']
            j['pt_JECDown'] =j['pt']/j['corr']*j['corr_JECDown']
            # JERUp, JERDown, JER
            addJERScaling(j)
        for var in ['JECUp', 'JECDown', 'JERUp', 'JERDown']:
            jets_sys[var]       = filter(lambda j:jetId(j, ptCut=30, absEtaCut=2.4, ptVar='pt_'+var), allJets)
            bjets_sys[var]      = filter(isBJet, jets_sys[var])
            nonBjets_sys[var]   = filter(lambda j: not isBJet(j), jets_sys[var])

            setattr(s, "nJetGood_"+var, len(jets_sys[var]))
            setattr(s, "ht_"+var,       sum([j['pt_'+var] for j in jets_sys[var]]))
            setattr(s, "nBTag_"+var,    len(bjets_sys[var]))

        for var in ['JECUp', 'JECDown', 'JERUp', 'JERDown', 'UnclusteredEnUp', 'UnclusteredEnDown']:
            for i in metVariants:
                # use cmg MET correction values ecept for JER where it is zero. There, propagate jet variations.
                if 'JER' in var:
                  (met_corr_pt, met_corr_phi) = getMetJetCorrected(getattr(s, "met_pt" + i), getattr(s,"met_phi" + i), jets_sys[var], var)
                else:
                  (met_corr_pt, met_corr_phi) = getMetCorrected(r, var, photons[0] if i.count("photonEstimated") else None)

                setattr(s, "met_pt" +i+"_"+var, met_corr_pt)
                setattr(s, "met_phi"+i+"_"+var, met_corr_phi)
                ht = getattr(s, "ht_"+var) if 'Unclustered' not in var else s.ht 
                setattr(s, "metSig" +i+"_"+var, getattr(s, "met_pt"+i+"_"+var)/sqrt( ht ) if ht>0 else float('nan') )

    if isSingleLep or isDiLep:
        s.nGoodMuons      = len(filter( lambda l:abs(l['pdgId'])==13, leptons))
        s.nGoodElectrons  = len(filter( lambda l:abs(l['pdgId'])==11, leptons))

        if len(leptons)>=1:
            s.l1_pt     = leptons[0]['pt']
            s.l1_eta    = leptons[0]['eta']
            s.l1_phi    = leptons[0]['phi']
            s.l1_pdgId  = leptons[0]['pdgId']
            s.l1_index  = leptons[0]['index']
            s.l1_jetPtRelv2  = leptons[0]['jetPtRelv2']
            s.l1_jetPtRatiov2  = leptons[0]['jetPtRatiov2']
            s.l1_jetPtRelv2    = leptons[0]['jetPtRelv2']
            s.l1_miniRelIso = leptons[0]['miniRelIso']
            s.l1_dxy = leptons[0]['dxy']
            s.l1_dz = leptons[0]['dz']

        # For TTZ studies: find Z boson candidate, and use third lepton to calculate mt
        (s.mlmZ_mass, zl1, zl2) = closestOSDLMassToMZ(leptons_pt10)
#        if len(leptons_pt10) >= 3:
#            thirdLepton = leptons_pt10[[x for x in range(len(leptons_pt10)) if x != zl1 and x != zl2][0]]
#            for i in metVariants:
#              setattr(s, "mt"+i, sqrt(2*thirdLepton['pt']*getattr(s, "met_pt"+i)*(1-cos(thirdLepton['phi']-getattr(s, "met_phi"+i)))))

        if options.fastSim:
            s.reweightLeptonFastSimSF     = reduce(mul, [leptonFastSimSF.get3DSF(pdgId=l['pdgId'], pt=l['pt'], eta=l['eta'] , nvtx = r.nVert) for l in leptons], 1)
            s.reweightLeptonFastSimSFUp   = reduce(mul, [leptonFastSimSF.get3DSF(pdgId=l['pdgId'], pt=l['pt'], eta=l['eta'] , nvtx = r.nVert, sigma = +1) for l in leptons], 1)
            s.reweightLeptonFastSimSFDown = reduce(mul, [leptonFastSimSF.get3DSF(pdgId=l['pdgId'], pt=l['pt'], eta=l['eta'] , nvtx = r.nVert, sigma = -1) for l in leptons], 1)

    if isDiLep:
        if len(leptons)>=2:# and leptons[0]['pdgId']*leptons[1]['pdgId']<0 and abs(leptons[0]['pdgId'])==abs(leptons[1]['pdgId']): #OSSF choice
            mt2Calc.reset()
            s.l2_pt     = leptons[1]['pt']
            s.l2_eta    = leptons[1]['eta']
            s.l2_phi    = leptons[1]['phi']
            s.l2_pdgId  = leptons[1]['pdgId']
            s.l2_index  = leptons[1]['index']
            s.l2_jetPtRatiov2  = leptons[1]['jetPtRatiov2']
            s.l2_jetPtRelv2    = leptons[1]['jetPtRelv2']
            s.l2_miniRelIso = leptons[1]['miniRelIso']
            s.l2_dxy = leptons[1]['dxy']
            s.l2_dz = leptons[1]['dz']

            l_pdgs = [abs(leptons[0]['pdgId']), abs(leptons[1]['pdgId'])]
            l_pdgs.sort()
            s.isMuMu = l_pdgs==[13,13]
            s.isEE   = l_pdgs==[11,11]
            s.isEMu  = l_pdgs==[11,13]
            s.isOS   = s.l1_pdgId*s.l2_pdgId<0

            l1 = ROOT.TLorentzVector()
            l1.SetPtEtaPhiM(leptons[0]['pt'], leptons[0]['eta'], leptons[0]['phi'], 0 )
            l2 = ROOT.TLorentzVector()
            l2.SetPtEtaPhiM(leptons[1]['pt'], leptons[1]['eta'], leptons[1]['phi'], 0 )
            dl = l1+l2
            s.dl_pt   = dl.Pt()
            s.dl_eta  = dl.Eta()
            s.dl_phi  = dl.Phi()
            s.dl_mass = dl.M()
            mt2Calc.setLeptons(s.l1_pt, s.l1_eta, s.l1_phi, s.l2_pt, s.l2_eta, s.l2_phi)

            # To check MC truth when looking at the TTZToLLNuNu sample
            if isMC:
              zBoson          = getGenZ(gPart)
              s.zBoson_genPt  = zBoson['pt']  if zBoson is not None else float('nan')
              s.zBoson_genEta = zBoson['eta'] if zBoson is not None else float('nan')

            if options.keepPhotons and s.nPhotonGood > 0:
              gamma = ROOT.TLorentzVector()
              gamma.SetPtEtaPhiM(photons[0]['pt'], photons[0]['eta'], photons[0]['phi'], photons[0]['mass'] )
              dlg = dl + gamma
              s.dlg_mass = dlg.M()

            for i in metVariants:
                mt2Calc.setMet(getattr(s, 'met_pt'+i), getattr(s, 'met_phi', i))
                setattr(s, "dl_mt2ll"+i, mt2Calc.mt2ll())

                if len(jets)>=2:
                    bj0, bj1 = (bJets+nonBJets)[:2]
                    mt2Calc.setBJets(bj0['pt'], bj0['eta'], bj0['phi'], bj1['pt'], bj1['eta'], bj1['phi'])
                    setattr(s, "dl_mt2bb"+i,   mt2Calc.mt2bb())
                    setattr(s, "dl_mt2blbl"+i, mt2Calc.mt2blbl())

                if addSystematicVariations:
                    for var in ['JECUp', 'JECDown', 'JERUp', 'JERDown', 'UnclusteredEnUp', 'UnclusteredEnDown']:
                        mt2Calc.setMet( getattr(s, "met_pt"+i+"_"+var), getattr(s, "met_phi"+i+"_"+var) )
                        setattr(s, "dl_mt2ll"+i+"_"+var,  mt2Calc.mt2ll())
                        bj0_, bj1_ = bj0, bj1
                        if not 'Unclustered' in var:
                            if len(jets_sys[var])>=2:
                                bj0_, bj1_ = (bjets_sys[var]+nonBjets_sys[var])[:2]
                            else: 
                                bj0_, bj1_ = None, None
                        if bj0_ and bj1_:
                            mt2Calc.setBJets(bj0_['pt'], bj0_['eta'], bj0_['phi'], bj1_['pt'], bj1_['eta'], bj1_['phi'])
                            setattr(s, 'dl_mt2bb'  +i+'_'+var, mt2Calc.mt2bb())
                            setattr(s, 'dl_mt2blbl'+i+'_'+var, mt2Calc.mt2blbl())

    if addSystematicVariations:
        # B tagging weights method 1a
        for j in jets:
            btagEff.addBTagEffToJet(j)
        for var in btagEff.btagWeightNames:
            if var!='MC':
                setattr(s, 'reweightBTag_'+var, btagEff.getBTagSF_1a( var, bJets, nonBJets ) )

    # gen information on extra leptons
    if isMC and not options.skipGenLepMatching:
        genSearch.init( gPart )
        # Start with status 1 gen leptons in acceptance
        gLep = filter( lambda p:abs(p['pdgId']) in [11, 13] and p['status']==1 and p['pt']>20 and abs(p['eta'])<2.5, gPart )
        for l in gLep:
            ancestry = [ gPart[x]['pdgId'] for x in genSearch.ancestry( l ) ]
            l["n_D"]   =  sum([ancestry.count(p) for p in D_mesons])
            l["n_B"]   =  sum([ancestry.count(p) for p in B_mesons])
            l["n_W"]   =  sum([ancestry.count(p) for p in [24, -24]])
            l["n_t"]   =  sum([ancestry.count(p) for p in [6, -6]])
            l["n_tau"] =  sum([ancestry.count(p) for p in [15, -15]])
            matched_lep = bestDRMatchInCollection(l, leptons_pt10)
            if matched_lep:
                l["lepGoodMatchIndex"] = matched_lep['index']
                if isSingleLep:
                    l["matchesPromptGoodLepton"] = l["lepGoodMatchIndex"] in [s.l1_index]
                elif isDiLep:
                    l["matchesPromptGoodLepton"] = l["lepGoodMatchIndex"] in [s.l1_index, s.l2_index]
                else:
                    l["matchesPromptGoodLepton"] = 0
            else:
                l["lepGoodMatchIndex"] = -1
                l["matchesPromptGoodLepton"] = 0
#            if      l["n_t"]>0 and l["n_W"]>0 and l["n_B"]==0 and l["n_D"]==0 and l["n_tau"]==0:
#                print "t->W->l"
#            elif    l["n_t"]>0 and l["n_W"]==0 and l["n_B"]>0 and l["n_D"]==0 and l["n_tau"]==0:
#                print "t->b->B->l"
#            elif    l["n_t"]>0 and l["n_W"]==0 and l["n_B"]>0 and l["n_D"]>0 and l["n_tau"]==0:
#                print "t->b->B->D->l"
#            elif    l["n_t"]>0 and l["n_W"]>0 and l["n_B"]==0 and l["n_D"]==0 and l["n_tau"]>0 :
#                print "t->W->tau->l"
#            elif    l["n_t"]>0 and l["n_W"]>0 and l["n_B"]==0 and l["n_D"]>0 and l["n_tau"]==0:
#                print "t->W->c->D->l"
#            elif    l["n_t"]==0 and l["n_W"]==0 and l["n_B"]>0 and l["n_D"]>=0 and l["n_tau"]==0:
#                print l['pdgId'], l['pt'], l['phi'], l['eta'], ",".join(pdgToName( gPart[x]['pdgId']) for x in genSearch.ancestry(l) )
#                for p in genSearch.ancestry(l):
#                    print p, gPart[p]
#            else:
#                pass
                # print l['pdgId'], l['pt'], l['phi'], l['eta'], ",".join(pdgToName(gPart[x]['pdgId']) for x in genSearch.ancestry(l))
        s.nGenLep   = len(gLep)
        for iLep, lep in enumerate(gLep):
            for b in genLepVarNames:
                getattr(s, "GenLep_"+b)[iLep] = lep[b]
Exemple #12
0
 
        for var in ['JECUp', 'JECDown', 'JER', 'JERUp', 'JERDown']:
          jets_[var]       = filter(lambda j:jetId(j, ptCut=30, absEtaCut=2.4, ptVar='pt_'+var), allJets)
          bJets_[var]      = filter(isBJet, jets_[var])
          nonBJets_[var]      = filter(lambda j: not isBJet(j), jets_[var])
          met_corr_px = r.met_pt*cos(r.met_phi) + sum([(j['pt']-j['pt_'+var])*cos(j['phi']) for j in jets_[var] ])
          met_corr_py = r.met_pt*sin(r.met_phi) + sum([(j['pt']-j['pt_'+var])*sin(j['phi']) for j in jets_[var] ])
          
          setattr(s, "met_pt_"+var, sqrt(met_corr_px**2 + met_corr_py**2))
          setattr(s, "met_phi_"+var, atan2(met_corr_py, met_corr_px)) 
          setattr(s, "nGoodJets_"+var, len(jets_[var])) 
          setattr(s, "ht_"+var, sum([j['pt_'+var] for j in jets_[var]])) 
          setattr(s, "nBTags_"+var, len(bJets_[var])) 

      if options.skim.lower().startswith('dilep'):
        leptons_pt10 = getGoodLeptons(r, ptCut=10)
        leptons      = filter(lambda l:l['pt']>20, leptons_pt10) 
        if options.fastSim:
          s.reweightLeptonFastSimSF     = reduce(mul, [leptonFastSimSF.get3DSF(pdgId=l['pdgId'], pt=l['pt'], eta=l['eta'] , nvtx = r.nVert) for l in leptons], 1)
          s.reweightLeptonFastSimSFUp   = reduce(mul, [leptonFastSimSF.get3DSF(pdgId=l['pdgId'], pt=l['pt'], eta=l['eta'] , nvtx = r.nVert, sigma = +1) for l in leptons], 1)
          s.reweightLeptonFastSimSFDown = reduce(mul, [leptonFastSimSF.get3DSF(pdgId=l['pdgId'], pt=l['pt'], eta=l['eta'] , nvtx = r.nVert, sigma = -1) for l in leptons], 1)
#          if s.reweightLeptonFastSimSF==0:
#            print [leptonFastSimSF.get3DSF(pdgId=l['pdgId'], pt=l['pt'], eta=l['eta'] , nvtx = r.nVert) for l in leptons], leptons

        s.nGoodMuons      = len(filter( lambda l:abs(l['pdgId'])==13, leptons))
        s.nGoodElectrons  = len(filter( lambda l:abs(l['pdgId'])==11, leptons))
#          print "Leptons", leptons 
        if len(leptons)>=2:# and leptons[0]['pdgId']*leptons[1]['pdgId']<0 and abs(leptons[0]['pdgId'])==abs(leptons[1]['pdgId']): #OSSF choice
          mt2Calc.reset()
          s.l1_pt  = leptons[0]['pt'] 
          s.l1_eta = leptons[0]['eta']
Exemple #13
0
            sys.stdout.flush()
            sys.stdout.write('\r')
        chain.GetEntry(eList.GetEntry(ev))

        #No double counting in data samples
        if getVarValue(chain, "evt") in ListOfDataEvents:
            continue
        else:
            ListOfDataEvents.append(getVarValue(chain, "evt"))

        weight = reduceStat*getVarValue(chain, "weight")*(luminosity/1000.) if not s['isData'] else 1

        #leptons
        electrons = getGoodElectrons(chain)
        muons = getGoodMuons(chain)
        leptons = getGoodLeptons(chain,10)

        #mt2ll for 2l
        mt2ll = getVarValue(chain,"dl_mt2ll")

        #met
        met = getVarValue(chain,'met_pt')

        #jets
        jets =  getGoodJets(chain)
        bjets = filter(lambda j:j['btagCSV']>btagcoeff, jets)
        nobjets = filter(lambda j:j['btagCSV']<=btagcoeff, jets)


        zleptons = []
        ttleptons = []
def filler(s):
    # shortcut
    r = reader.data
    if isMC: gPart = getGenPartsAll(r)

    # weight
    if options.T2tt:
        s.weight = signalWeight[(r.GenSusyMScan1, r.GenSusyMScan2)]['weight']
        s.mStop = r.GenSusyMScan1
        s.mNeu = r.GenSusyMScan2
        s.reweightXSecUp = signalWeight[(r.GenSusyMScan1,
                                         r.GenSusyMScan2)]['xSecFacUp']
        s.reweightXSecDown = signalWeight[(r.GenSusyMScan1,
                                           r.GenSusyMScan2)]['xSecFacDown']
    elif isMC:
        s.weight = lumiScaleFactor * r.genWeight if lumiScaleFactor is not None else 1
    elif isData:
        s.weight = 1
    else:
        raise NotImplementedError("isMC %r isData %r T2tt? %r TTDM?" %
                                  (isMC, isData, options.T2tt, options.TTDM))

    # lumi lists and vetos
    if isData:
        s.vetoPassed = vetoList.passesVeto(r.run, r.lumi, r.evt)
        s.jsonPassed = lumiList.contains(r.run, r.lumi)
        # store decision to use after filler has been executed
        s.jsonPassed_ = s.jsonPassed

    if isMC:
        s.reweightPU = puRW(r.nTrueInt)
        s.reweightPUDown = puRWDown(r.nTrueInt)
        s.reweightPUUp = puRWUp(r.nTrueInt)

    # top pt reweighting
    if isMC:
        s.reweightTopPt = topPtReweightingFunc(getTopPtsForReweighting(
            r)) / topScaleF if doTopPtReweighting else 1.

    # jet/met related quantities, also load the leptons already
    allJets = getGoodJets(r, ptCut=0, jetVars=jetVarNames)
    jets = filter(lambda j: jetId(j, ptCut=30, absEtaCut=2.4), allJets)
    bJets = filter(lambda j: isBJet(j), jets)
    nonBJets = filter(lambda j: not isBJet(j), jets)
    if isVeryLoose:
        # all leptons up to relIso 1
        miniRelIso = 999.
        ptCut = 20 if not isVeryLoosePt10 else 10
        leptons_pt10 = getGoodAndOtherLeptons(r,
                                              ptCut=10,
                                              miniRelIso=miniRelIso,
                                              dz=0.1,
                                              dxy=1.)
        leptons = filter(lambda l: l['pt'] > ptCut, leptons_pt10)
    elif isLoose:
        # reliso 0.4
        miniRelIso = 0.4
        leptons_pt10 = getGoodLeptons(r, ptCut=10, miniRelIso=miniRelIso)
        leptons = filter(lambda l: l['pt'] > 20, leptons_pt10)
    else:
        miniRelIso = 0.2
        leptons_pt10 = getGoodLeptons(r, ptCut=10, miniRelIso=miniRelIso)
        # relIso 0.2
        leptons = filter(lambda l: l['pt'] > 20, leptons_pt10)

    s.met_pt = r.met_pt
    s.met_phi = r.met_phi

    # Filling jets
    s.nJetGood = len(jets)
    for iJet, jet in enumerate(jets):
        for b in jetVarNames:
            getattr(s, "JetGood_" + b)[iJet] = jet[b]
    if isSingleLep:
        # Compute M3 and the three indiced of the jets entering m3
        s.m3, s.m3_ind1, s.m3_ind2, s.m3_ind3 = m3(jets)

    s.ht = sum([j['pt'] for j in jets])
    s.metSig = s.met_pt / sqrt(s.ht) if s.ht > 0 else float('nan')
    s.nBTag = len(bJets)

    jets_sys = {}
    bjets_sys = {}
    nonBjets_sys = {}

    metVariants = ['']  # default

    # Keep photons and estimate met including (leading pt) photon
    if options.keepPhotons:
        photons = getGoodPhotons(r, ptCut=20, idLevel="loose", isData=isData)
        s.nPhotonGood = len(photons)
        if s.nPhotonGood > 0:
            metVariants += [
                '_photonEstimated'
            ]  # do all met calculations also for the photonEstimated variant
            s.photon_pt = photons[0]['pt']
            s.photon_eta = photons[0]['eta']
            s.photon_phi = photons[0]['phi']
            s.photon_idCutBased = photons[0]['idCutBased']
            if isMC:
                genPhoton = getGenPhoton(gPart)
                s.photon_genPt = genPhoton[
                    'pt'] if genPhoton is not None else float('nan')
                s.photon_genEta = genPhoton[
                    'eta'] if genPhoton is not None else float('nan')

            s.met_pt_photonEstimated, s.met_phi_photonEstimated = getMetPhotonEstimated(
                r.met_pt, r.met_phi, photons[0])
            s.metSig_photonEstimated = s.met_pt_photonEstimated / sqrt(
                s.ht) if s.ht > 0 else float('nan')

            s.photonJetdR = min(deltaR(photons[0], j)
                                for j in jets) if len(jets) > 0 else 999
            s.photonLepdR = min(
                deltaR(photons[0], l)
                for l in leptons_pt10) if len(leptons_pt10) > 0 else 999

    if options.checkTTGJetsOverlap and isMC:
        s.TTGJetsEventType = getTTGJetsEventType(r)

    if addSystematicVariations:
        for j in allJets:
            j['pt_JECUp'] = j['pt'] / j['corr'] * j['corr_JECUp']
            j['pt_JECDown'] = j['pt'] / j['corr'] * j['corr_JECDown']
            # JERUp, JERDown, JER
            addJERScaling(j)
        for var in ['JECUp', 'JECDown', 'JERUp', 'JERDown']:
            jets_sys[var] = filter(
                lambda j: jetId(j, ptCut=30, absEtaCut=2.4, ptVar='pt_' + var),
                allJets)
            bjets_sys[var] = filter(isBJet, jets_sys[var])
            nonBjets_sys[var] = filter(lambda j: not isBJet(j), jets_sys[var])

            setattr(s, "nJetGood_" + var, len(jets_sys[var]))
            setattr(s, "ht_" + var,
                    sum([j['pt_' + var] for j in jets_sys[var]]))
            setattr(s, "nBTag_" + var, len(bjets_sys[var]))

        for var in [
                'JECUp', 'JECDown', 'JERUp', 'JERDown', 'UnclusteredEnUp',
                'UnclusteredEnDown'
        ]:
            for i in metVariants:
                # use cmg MET correction values ecept for JER where it is zero. There, propagate jet variations.
                if 'JER' in var:
                    (met_corr_pt, met_corr_phi) = getMetJetCorrected(
                        getattr(s, "met_pt" + i), getattr(s, "met_phi" + i),
                        jets_sys[var], var)
                else:
                    (met_corr_pt, met_corr_phi) = getMetCorrected(
                        r, var,
                        photons[0] if i.count("photonEstimated") else None)

                setattr(s, "met_pt" + i + "_" + var, met_corr_pt)
                setattr(s, "met_phi" + i + "_" + var, met_corr_phi)
                ht = getattr(s, "ht_" +
                             var) if 'Unclustered' not in var else s.ht
                setattr(
                    s, "metSig" + i + "_" + var,
                    getattr(s, "met_pt" + i + "_" + var) /
                    sqrt(ht) if ht > 0 else float('nan'))

    if isSingleLep or isDiLep:
        s.nGoodMuons = len(filter(lambda l: abs(l['pdgId']) == 13, leptons))
        s.nGoodElectrons = len(filter(lambda l: abs(l['pdgId']) == 11,
                                      leptons))

        if len(leptons) >= 1:
            s.l1_pt = leptons[0]['pt']
            s.l1_eta = leptons[0]['eta']
            s.l1_phi = leptons[0]['phi']
            s.l1_pdgId = leptons[0]['pdgId']
            s.l1_index = leptons[0]['index']
            s.l1_jetPtRelv2 = leptons[0]['jetPtRelv2']
            s.l1_jetPtRatiov2 = leptons[0]['jetPtRatiov2']
            s.l1_jetPtRelv2 = leptons[0]['jetPtRelv2']
            s.l1_miniRelIso = leptons[0]['miniRelIso']
            s.l1_dxy = leptons[0]['dxy']
            s.l1_dz = leptons[0]['dz']

        # For TTZ studies: find Z boson candidate, and use third lepton to calculate mt
        (s.mlmZ_mass, zl1, zl2) = closestOSDLMassToMZ(leptons_pt10)
        #        if len(leptons_pt10) >= 3:
        #            thirdLepton = leptons_pt10[[x for x in range(len(leptons_pt10)) if x != zl1 and x != zl2][0]]
        #            for i in metVariants:
        #              setattr(s, "mt"+i, sqrt(2*thirdLepton['pt']*getattr(s, "met_pt"+i)*(1-cos(thirdLepton['phi']-getattr(s, "met_phi"+i)))))

        if options.fastSim:
            s.reweightLeptonFastSimSF = reduce(mul, [
                leptonFastSimSF.get3DSF(
                    pdgId=l['pdgId'], pt=l['pt'], eta=l['eta'], nvtx=r.nVert)
                for l in leptons
            ], 1)
            s.reweightLeptonFastSimSFUp = reduce(mul, [
                leptonFastSimSF.get3DSF(pdgId=l['pdgId'],
                                        pt=l['pt'],
                                        eta=l['eta'],
                                        nvtx=r.nVert,
                                        sigma=+1) for l in leptons
            ], 1)
            s.reweightLeptonFastSimSFDown = reduce(mul, [
                leptonFastSimSF.get3DSF(pdgId=l['pdgId'],
                                        pt=l['pt'],
                                        eta=l['eta'],
                                        nvtx=r.nVert,
                                        sigma=-1) for l in leptons
            ], 1)

    if isDiLep:
        if len(
                leptons
        ) >= 2:  # and leptons[0]['pdgId']*leptons[1]['pdgId']<0 and abs(leptons[0]['pdgId'])==abs(leptons[1]['pdgId']): #OSSF choice
            mt2Calc.reset()
            s.l2_pt = leptons[1]['pt']
            s.l2_eta = leptons[1]['eta']
            s.l2_phi = leptons[1]['phi']
            s.l2_pdgId = leptons[1]['pdgId']
            s.l2_index = leptons[1]['index']
            s.l2_jetPtRatiov2 = leptons[1]['jetPtRatiov2']
            s.l2_jetPtRelv2 = leptons[1]['jetPtRelv2']
            s.l2_miniRelIso = leptons[1]['miniRelIso']
            s.l2_dxy = leptons[1]['dxy']
            s.l2_dz = leptons[1]['dz']

            l_pdgs = [abs(leptons[0]['pdgId']), abs(leptons[1]['pdgId'])]
            l_pdgs.sort()
            s.isMuMu = l_pdgs == [13, 13]
            s.isEE = l_pdgs == [11, 11]
            s.isEMu = l_pdgs == [11, 13]
            s.isOS = s.l1_pdgId * s.l2_pdgId < 0

            l1 = ROOT.TLorentzVector()
            l1.SetPtEtaPhiM(leptons[0]['pt'], leptons[0]['eta'],
                            leptons[0]['phi'], 0)
            l2 = ROOT.TLorentzVector()
            l2.SetPtEtaPhiM(leptons[1]['pt'], leptons[1]['eta'],
                            leptons[1]['phi'], 0)
            dl = l1 + l2
            s.dl_pt = dl.Pt()
            s.dl_eta = dl.Eta()
            s.dl_phi = dl.Phi()
            s.dl_mass = dl.M()
            mt2Calc.setLeptons(s.l1_pt, s.l1_eta, s.l1_phi, s.l2_pt, s.l2_eta,
                               s.l2_phi)

            # To check MC truth when looking at the TTZToLLNuNu sample
            if isMC:
                zBoson = getGenZ(gPart)
                s.zBoson_genPt = zBoson['pt'] if zBoson is not None else float(
                    'nan')
                s.zBoson_genEta = zBoson[
                    'eta'] if zBoson is not None else float('nan')

            if options.keepPhotons and s.nPhotonGood > 0:
                gamma = ROOT.TLorentzVector()
                gamma.SetPtEtaPhiM(photons[0]['pt'], photons[0]['eta'],
                                   photons[0]['phi'], photons[0]['mass'])
                dlg = dl + gamma
                s.dlg_mass = dlg.M()

            for i in metVariants:
                mt2Calc.setMet(getattr(s, 'met_pt' + i),
                               getattr(s, 'met_phi', i))
                setattr(s, "dl_mt2ll" + i, mt2Calc.mt2ll())

                if len(jets) >= 2:
                    bj0, bj1 = (bJets + nonBJets)[:2]
                    mt2Calc.setBJets(bj0['pt'], bj0['eta'], bj0['phi'],
                                     bj1['pt'], bj1['eta'], bj1['phi'])
                    setattr(s, "dl_mt2bb" + i, mt2Calc.mt2bb())
                    setattr(s, "dl_mt2blbl" + i, mt2Calc.mt2blbl())

                if addSystematicVariations:
                    for var in [
                            'JECUp', 'JECDown', 'JERUp', 'JERDown',
                            'UnclusteredEnUp', 'UnclusteredEnDown'
                    ]:
                        mt2Calc.setMet(getattr(s, "met_pt" + i + "_" + var),
                                       getattr(s, "met_phi" + i + "_" + var))
                        setattr(s, "dl_mt2ll" + i + "_" + var, mt2Calc.mt2ll())
                        bj0_, bj1_ = bj0, bj1
                        if not 'Unclustered' in var:
                            if len(jets_sys[var]) >= 2:
                                bj0_, bj1_ = (bjets_sys[var] +
                                              nonBjets_sys[var])[:2]
                            else:
                                bj0_, bj1_ = None, None
                        if bj0_ and bj1_:
                            mt2Calc.setBJets(bj0_['pt'], bj0_['eta'],
                                             bj0_['phi'], bj1_['pt'],
                                             bj1_['eta'], bj1_['phi'])
                            setattr(s, 'dl_mt2bb' + i + '_' + var,
                                    mt2Calc.mt2bb())
                            setattr(s, 'dl_mt2blbl' + i + '_' + var,
                                    mt2Calc.mt2blbl())

    if addSystematicVariations:
        # B tagging weights method 1a
        for j in jets:
            btagEff.addBTagEffToJet(j)
        for var in btagEff.btagWeightNames:
            if var != 'MC':
                setattr(s, 'reweightBTag_' + var,
                        btagEff.getBTagSF_1a(var, bJets, nonBJets))

    # gen information on extra leptons
    if isMC and not options.skipGenLepMatching:
        genSearch.init(gPart)
        # Start with status 1 gen leptons in acceptance
        gLep = filter(
            lambda p: abs(p['pdgId']) in [11, 13] and p['status'] == 1 and p[
                'pt'] > 20 and abs(p['eta']) < 2.5, gPart)
        for l in gLep:
            ancestry = [gPart[x]['pdgId'] for x in genSearch.ancestry(l)]
            l["n_D"] = sum([ancestry.count(p) for p in D_mesons])
            l["n_B"] = sum([ancestry.count(p) for p in B_mesons])
            l["n_W"] = sum([ancestry.count(p) for p in [24, -24]])
            l["n_t"] = sum([ancestry.count(p) for p in [6, -6]])
            l["n_tau"] = sum([ancestry.count(p) for p in [15, -15]])
            matched_lep = bestDRMatchInCollection(l, leptons_pt10)
            if matched_lep:
                l["lepGoodMatchIndex"] = matched_lep['index']
                if isSingleLep:
                    l["matchesPromptGoodLepton"] = l["lepGoodMatchIndex"] in [
                        s.l1_index
                    ]
                elif isDiLep:
                    l["matchesPromptGoodLepton"] = l["lepGoodMatchIndex"] in [
                        s.l1_index, s.l2_index
                    ]
                else:
                    l["matchesPromptGoodLepton"] = 0
            else:
                l["lepGoodMatchIndex"] = -1
                l["matchesPromptGoodLepton"] = 0
#            if      l["n_t"]>0 and l["n_W"]>0 and l["n_B"]==0 and l["n_D"]==0 and l["n_tau"]==0:
#                print "t->W->l"
#            elif    l["n_t"]>0 and l["n_W"]==0 and l["n_B"]>0 and l["n_D"]==0 and l["n_tau"]==0:
#                print "t->b->B->l"
#            elif    l["n_t"]>0 and l["n_W"]==0 and l["n_B"]>0 and l["n_D"]>0 and l["n_tau"]==0:
#                print "t->b->B->D->l"
#            elif    l["n_t"]>0 and l["n_W"]>0 and l["n_B"]==0 and l["n_D"]==0 and l["n_tau"]>0 :
#                print "t->W->tau->l"
#            elif    l["n_t"]>0 and l["n_W"]>0 and l["n_B"]==0 and l["n_D"]>0 and l["n_tau"]==0:
#                print "t->W->c->D->l"
#            elif    l["n_t"]==0 and l["n_W"]==0 and l["n_B"]>0 and l["n_D"]>=0 and l["n_tau"]==0:
#                print l['pdgId'], l['pt'], l['phi'], l['eta'], ",".join(pdgToName( gPart[x]['pdgId']) for x in genSearch.ancestry(l) )
#                for p in genSearch.ancestry(l):
#                    print p, gPart[p]
#            else:
#                pass
# print l['pdgId'], l['pt'], l['phi'], l['eta'], ",".join(pdgToName(gPart[x]['pdgId']) for x in genSearch.ancestry(l))
        s.nGenLep = len(gLep)
        for iLep, lep in enumerate(gLep):
            for b in genLepVarNames:
                getattr(s, "GenLep_" + b)[iLep] = lep[b]
Exemple #15
0
            sys.stdout.write('\r')
        chain.GetEntry(eList.GetEntry(ev))

        #No double counting in data samples
        if getVarValue(chain, "evt") in ListOfDataEvents:
            continue
        else:
            ListOfDataEvents.append(getVarValue(chain, "evt"))

        weight = reduceStat * getVarValue(
            chain, "weight") * (luminosity / 1000.) if not s['isData'] else 1

        #leptons
        electrons = getGoodElectrons(chain)
        muons = getGoodMuons(chain)
        leptons = getGoodLeptons(chain, 10)

        #mt2ll for 2l
        mt2ll = getVarValue(chain, "dl_mt2ll")

        #met
        met = getVarValue(chain, 'met_pt')

        #jets
        jets = getGoodJets(chain)
        bjets = filter(lambda j: j['btagCSV'] > btagcoeff, jets)
        nobjets = filter(lambda j: j['btagCSV'] <= btagcoeff, jets)

        zleptons = []
        ttleptons = []
Exemple #16
0
                         for j in jets_[var]])
                    met_corr_py = r.met_pt * sin(r.met_phi) + sum(
                        [(j['pt'] - j['pt_' + var]) * sin(j['phi'])
                         for j in jets_[var]])

                    setattr(s, "met_pt_" + var,
                            sqrt(met_corr_px**2 + met_corr_py**2))
                    setattr(s, "met_phi_" + var, atan2(met_corr_py,
                                                       met_corr_px))
                    setattr(s, "nGoodJets_" + var, len(jets_[var]))
                    setattr(s, "ht_" + var,
                            sum([j['pt_' + var] for j in jets_[var]]))
                    setattr(s, "nBTags_" + var, len(bJets_[var]))

            if options.skim.lower().startswith('dilep'):
                leptons_pt10 = getGoodLeptons(r, ptCut=10)
                leptons = filter(lambda l: l['pt'] > 20, leptons_pt10)
                if options.fastSim:
                    s.reweightLeptonFastSimSF = reduce(mul, [
                        leptonFastSimSF.get3DSF(pdgId=l['pdgId'],
                                                pt=l['pt'],
                                                eta=l['eta'],
                                                nvtx=r.nVert) for l in leptons
                    ], 1)
                    s.reweightLeptonFastSimSFUp = reduce(
                        mul, [
                            leptonFastSimSF.get3DSF(pdgId=l['pdgId'],
                                                    pt=l['pt'],
                                                    eta=l['eta'],
                                                    nvtx=r.nVert,
                                                    sigma=+1) for l in leptons
            genWeight = 1 if sample.isData else t.GetLeaf(
                'genWeight').GetValue()
            s.weight = lumiScaleFactor * genWeight if not sample.isData else 1
            if sample.isData:
                if not sample.lumiList.contains(r.run, r.lumi):
                    #        print "Did not find run %i lumi %i in json file %s"%(r.run, r.lumi, sample.json)
                    s.weight = 0
                else:
                    if r.run not in outputLumiList.keys():
                        outputLumiList[r.run] = [r.lumi]
                    else:
                        if r.lumi not in outputLumiList[r.run]:
                            outputLumiList[r.run].append(r.lumi)
#        print "Found run %i lumi %i in json file %s"%(r.run, r.lumi, sample.json)
            if options.skim.lower().startswith('dilep'):
                leptons = getGoodLeptons(r)
                s.nGoodMuons = len(
                    filter(lambda l: abs(l['pdgId']) == 13, leptons))
                s.nGoodElectrons = len(
                    filter(lambda l: abs(l['pdgId']) == 11, leptons))
                #          print "Leptons", leptons
                if len(
                        leptons
                ) >= 2:  # and leptons[0]['pdgId']*leptons[1]['pdgId']<0 and abs(leptons[0]['pdgId'])==abs(leptons[1]['pdgId']): #OSSF choice
                    mt2Calc.reset()
                    s.l1_pt = leptons[0]['pt']
                    s.l1_eta = leptons[0]['eta']
                    s.l1_phi = leptons[0]['phi']
                    s.l1_mass = leptons[0]['mass']
                    s.l1_pdgId = leptons[0]['pdgId']
                    s.l1_index = leptons[0]['index']