def makeHadTopDecays(self, event):
     event.lightJets = [ j for j in event.cleanJets if not j.btagWP("CSVv2IVFM") ]
     event.minMWjj   = 999
     event.minMWjjPt = 0
     event.bestMWjj   = 0
     event.bestMWjjPt = 0
     event.bestMTopHad   = 0
     event.bestMTopHadPt = 0
     for i1,j1 in enumerate(event.lightJets):
         for i2 in xrange(i1+1,len(event.lightJets)):
             j2 = event.lightJets[i2]
             jjp4 = j1.p4() + j2.p4()
             mjj  = jjp4.M()
             if mjj > 30 and mjj < event.minMWjj:
                 event.minMWjj = mjj
                 event.minMWjjPt = jjp4.Pt()
             if abs(mjj-80.4) < abs(event.bestMWjj-80.4):
                 event.bestMWjj = mjj
                 event.bestMWjjPt = jjp4.Pt()
                 for bj in event.bjetsLoose:
                     if deltaR(bj.eta(),bj.phi(),j1.eta(),j1.phi()) < 0.1 or deltaR(bj.eta(),bj.phi(),j2.eta(),j2.phi()) < 0.1: continue
                     tp4 = jjp4 + bj.p4()
                     mtop = tp4.M()
                     if abs(mtop-172) < abs(event.bestMTopHad - 172):
                         event.bestMTopHad = mtop
                         event.bestMTopHadPt = tp4.Pt()
    def process(self, event):
        self.readCollections( event.input )
        self.counters.counter('events').inc('all events')

        
        objects = []
        selectedObjects = getattr(event, self.cfg_ana.objects)
        for obj, ptCut in zip(selectedObjects, self.ptCuts):
	    allowTrack = False
	    for i in range (0,len(event.selectedMuons)) :
		if (i == self.cfg_ana.allowedMuon): break
		if(deltaR(event.selectedMuons[i].eta(), event.selectedMuons[i].phi(), obj.eta(), obj.phi()) < 0.02) : allowTrack=True

	    for i in range (0,len(event.selectedElectrons)) :
		if (i == self.cfg_ana.allowedElectron): break
		if(deltaR(event.selectedElectrons[i].eta(), event.selectedElectrons[i].phi(), obj.eta(), obj.phi()) < 0.02) : allowTrack=True

            if not self.idFunc(obj):
                continue
            if obj.pt() > ptCut and not allowTrack: 
                objects.append(obj)


        ret = False 
        if len(objects) >= self.cfg_ana.minObjects:
            ret = True
        else:
            self.counters.counter('events').inc('too few objects')

        if len(objects) > self.cfg_ana.maxObjects:
            self.counters.counter('events').inc('too many objects')
            ret = False

        if ret: self.counters.counter('events').inc('accepted events')
        return ret
Esempio n. 3
0
    def process(self, event):
        self.readCollections( event.input )
        pf = map( PhysicsObject, self.handles['pf'].product() )
        leptons = getattr(event,self.leptonTag)
        self.IsolationComputer.setPackedCandidates(self.handles['pf'].product())


        #first trim the photons that are only near leptons
        direct=[]
        forIso=[]


        for p in pf:
            if p.pdgId() != 22 or not( p.pt() > 2.0 and abs(p.eta()) < 2.4 ):
                continue
            scVetoed = False
            for l in leptons:
                if abs(l.pdgId())==11 and self.electronID(l):
                    #print "Testing photon pt %5.1f eta %+7.4f phi %+7.4f vs ele pt %.1f eta %+7.4f  phi %+7.4f sc  eta %+7.4f  phi %+7.4f" % ( p.pt(), p.eta(), p.phi(), l.pt(), l.eta(), l.phi(), l.superCluster().eta(), l.superCluster().phi() )
                    #print "Testing                                                       deta %+7.4f dphi %+7.4f sc deta %+7.4f dphi %+7.4f" % ( abs(p.eta()-l.eta()), deltaPhi(p.phi(),l.phi()), abs(p.eta()-l.superCluster().eta()), deltaPhi(p.phi(),l.superCluster().phi()))
                    if self.cfg_ana.electronVeto == "superclusterEta":
                        if (abs(p.eta()-l.superCluster().eta())<0.05 and abs(deltaPhi(p.phi(),l.superCluster().phi()))<2) or deltaR(p.eta(),p.phi(),l.superCluster().eta(),l.superCluster().phi())<0.15: 
                            scVetoed = True; break
                    elif self.cfg_ana.electronVeto == "electronEta":
                        if (abs(p.eta()-l.eta())<0.05 and abs(deltaPhi(p.phi(),l.phi()))<2) or deltaR(p.eta(),p.phi(),l.eta(),l.phi())<0.15: 
                            scVetoed = True; break
                    else: 
                        raise RuntimeError, "electronVeto option %r not implemented" % self.cfg_ana.electronVeto
            if scVetoed: continue
            okNoIso = False; okIfIso = False
            for l in leptons:
                DR =deltaR(l.eta(),l.phi(),p.eta(),p.phi())     
                if DR<0.07 and p.pt()>2.0:
                    direct.append(p)
                    okNoIso = True
                    break;
                elif  DR<0.5 and p.pt()>4.0:   
                    okIfIso = True
            if okIfIso and not okNoIso:
                forIso.append(p)
        isolatedPhotons=[]        
        for g in forIso:
            g.absIsoCH = self.IsolationComputer.chargedAbsIso(g.physObj,0.3,0.0001,0.2)
            g.absIsoPU = self.IsolationComputer.puAbsIso(g.physObj,0.3,0.0001,0.2)
            g.absIsoNH = self.IsolationComputer.neutralHadAbsIsoRaw(g.physObj,0.3,0.01,0.5)
            g.absIsoPH = self.IsolationComputer.photonAbsIsoRaw(g.physObj,0.3,0.01,0.5)
            g.relIso   = (g.absIsoCH+g.absIsoPU+g.absIsoNH+g.absIsoPH)/g.pt()
            if g.relIso<1.0:
                isolatedPhotons.append(g)

        event.fsrPhotons = isolatedPhotons+direct
                    
        # save all, for debugging
        event.fsrPhotonsNoIso = forIso + direct
        for fsr in event.fsrPhotonsNoIso:
            closest = min(leptons, key = lambda l : deltaR(fsr.eta(),fsr.phi(),l.eta(),l.phi()))
            fsr.globalClosestLepton = closest

        return True
Esempio n. 4
0
 def matchPhotons(self, event):
     event.genPhotons = [ x for x in event.genParticles if x.status() == 1 and abs(x.pdgId()) == 22 ]
     event.genPhotonsWithMom = [ x for x in event.genPhotons if x.numberOfMothers()>0 ]
     event.genPhotonsWithoutMom = [ x for x in event.genPhotons if x.numberOfMothers()==0 ]
     event.genPhotonsMatched = [ x for x in event.genPhotonsWithMom if abs(x.mother(0).pdgId())<23 or x.mother(0).pdgId()==2212 ]
     match = matchObjectCollection3(event.allphotons, event.genPhotonsMatched, deltaRMax = 0.1)
     matchNoMom = matchObjectCollection3(event.allphotons, event.genPhotonsWithoutMom, deltaRMax = 0.1)
     packedGenParts = [ p for p in self.mchandles['packedGen'].product() if abs(p.eta()) < 3.1 ]
     for gamma in event.allphotons:
       gen = match[gamma]
       gamma.mcGamma = gen
       if gen and gen.pt()>=0.5*gamma.pt() and gen.pt()<=2.*gamma.pt():
         gamma.mcMatchId = 22
         sumPt03 = 0.;
         sumPt04 = 0.;
         for part in packedGenParts:
           if abs(part.pdgId())==12: continue # exclude neutrinos
           if abs(part.pdgId())==14: continue
           if abs(part.pdgId())==16: continue
           if abs(part.pdgId())==18: continue
           deltar = deltaR(gen.eta(), gen.phi(), part.eta(), part.phi())
           if deltar <= 0.3:
             sumPt03 += part.pt()
           if deltar <= 0.4:
             sumPt04 += part.pt()
         sumPt03 -= gen.pt()
         sumPt04 -= gen.pt()
         if sumPt03<0. : sumPt03=0.
         if sumPt04<0. : sumPt04=0.
         gamma.genIso03 = sumPt03
         gamma.genIso04 = sumPt04
       else:
         genNoMom = matchNoMom[gamma]
         if genNoMom:
           gamma.mcMatchId = 7
           sumPt03 = 0.;
           sumPt04 = 0.;
           for part in packedGenParts:
             if abs(part.pdgId())==12: continue # exclude neutrinos
             if abs(part.pdgId())==14: continue
             if abs(part.pdgId())==16: continue
             if abs(part.pdgId())==18: continue
             deltar = deltaR(genNoMom.eta(), genNoMom.phi(), part.eta(), part.phi());
             if deltar <= 0.3:
               sumPt03 += part.pt()
             if deltar <= 0.4:
               sumPt04 += part.pt()
           sumPt03 -= genNoMom.pt()
           sumPt04 -= genNoMom.pt()
           if sumPt03<0. : sumPt03=0.
           if sumPt04<0. : sumPt04=0.
           gamma.genIso03 = sumPt03
           gamma.genIso04 = sumPt04
         else:
           gamma.mcMatchId = 0
           gamma.genIso03 = -1.
           gamma.genIso04 = -1.
Esempio n. 5
0
    def selectFatJet(self, event):
        if not len(event.cleanFatJets) >= 1:
            return False
        if not event.cleanFatJets[0].pt() > self.cfg_ana.fatjet_pt: 
            return False
        
        # Add n-subjettiness
        for i, j in enumerate(event.cleanFatJets):
            j.tau21 = j.userFloat("NjettinessAK8:tau2")/j.userFloat("NjettinessAK8:tau1")
        
        #########
        # FIXME dirty hack: count the number of ak4 b-tagged jet close instead
        # Count number of b-tagged subjets
        nSubJetTags = 0
        for f in event.cleanFatJets:
            subJets = []
            for j in event.cleanJets:
                if deltaR(f.eta(), f.phi(), j.eta(), j.phi())<0.8:
                    subJets.append(j)
            subJets.sort(key = lambda x : x.btag('combinedInclusiveSecondaryVertexV2BJetTags'), reverse = True)
            f.nSubJets = len(subJets)
            if len(subJets) >= 1:
                f.subJet1 = subJets[0]
            if len(subJets) >= 2:
                f.subJet2 = subJets[1]
        #########
        
        # FatJet selections
        if not event.cleanFatJets[0].nSubJets >= 1 or not event.cleanFatJets[0].subJet1.btag('combinedInclusiveSecondaryVertexV2BJetTags') > self.cfg_ana.fatjet_tag1:
            return False
#        if not event.cleanFatJets[0].nSubJets >= 2 or not event.cleanFatJets[0].subJet2.btag('combinedInclusiveSecondaryVertexV2BJetTags') > self.cfg_ana.fatjet_tag2:
#            return False
        if not event.cleanFatJets[0].userFloat("ak8PFJetsCHSPrunedLinks") > self.cfg_ana.fatjet_mass:
            return False
        if not hasattr(event.cleanFatJets[0], "tau21") or not event.cleanFatJets[0].tau21 > self.cfg_ana.fatjet_tau21:
            return False
        
        
        # Higgs candidate
        prunedJet = copy.deepcopy(event.cleanFatJets[0]) # Copy fatJet...
        prunedJet.setMass(prunedJet.userFloat("ak8PFJetsCHSPrunedLinks")) # ... and set the mass to the pruned mass
        theH = prunedJet.p4()
        theH.charge = event.cleanFatJets[0].charge()
        theH.deltaR = deltaR(event.cleanFatJets[0].subJet1.eta(), event.cleanFatJets[0].subJet1.phi(), event.cleanFatJets[0].subJet2.eta(), event.cleanFatJets[0].subJet2.phi()) if hasattr(event.cleanFatJets[0], "subJet2") else -1.
        theH.deltaEta = abs(event.cleanFatJets[0].subJet1.eta() - event.cleanFatJets[0].subJet2.eta()) if hasattr(event.cleanFatJets[0], "subJet2") else -9.
        theH.deltaPhi = deltaPhi(event.cleanFatJets[0].subJet1.phi(), event.cleanFatJets[0].subJet2.phi()) if hasattr(event.cleanFatJets[0], "subJet2") else -9.
        theH.deltaPhi_met = deltaPhi(theH.phi(), event.met.phi())
        theH.deltaPhi_jet1 = deltaPhi(theH.phi(), event.cleanFatJets[0].phi())
        event.H = theH
        
        return True
Esempio n. 6
0
 def fillTauIndices(self,event) :
     for j in event.cleanJetsAll :
         j.tauIdxs = [event.inclusiveTaus.index(x) for x in j.taus if j.taus in event.inclusiveTaus]
     for t in event.inclusiveTaus :
         dRmin = 1.e+3
         t.jetIdx = -1
         for jIdx, j in enumerate(event.cleanJetsAll) :
             dR = None
             if t.isPFTau():
                dR = deltaR(t.p4Jet().eta(),t.p4Jet().phi(),j.eta(),j.phi())
             else:
                dR = deltaR(t.pfEssential().p4CorrJet_.eta(),t.pfEssential().p4CorrJet_.phi(),j.eta(),j.phi())
             if dR < 0.3 and dR < dRmin :
                 t.jetIdx = jIdx
                 dRmin = dR
    def evaluateRegression(self, event, attrName="pt_reg"):
#self.readCollections( event.input )
	self.rho[0] = event.rho
	for j in event.jetsForHiggs :
		self.Jet_pt[0] = j.pt()
		self.Jet_eta[0] = j.eta()
		self.Jet_rawPt[0] = j.pt()*j.rawFactor()
		self.Jet_mt[0] = j.mt()
		self.Jet_leadTrackPt[0] = j.leadTrackPt()
		if len(j.leptons) > 0       :
			self.Jet_leptonPtRel[0] = ptRel(j.leptons[0].p4(),j.p4())
			self.Jet_leptonPt[0] =  j.leptons[0].pt()
			self.Jet_leptonDeltaR[0] = deltaR(j.leptons[0].p4().eta(),j.leptons[0].p4().phi(),j.p4().eta(),j.p4().phi())
		else:
			self.Jet_leptonPtRel[0] = -99
			self.Jet_leptonPt[0] =  -99
			self.Jet_leptonDeltaR[0] =-99
		self.Jet_chEmEF[0] = j.chargedEmEnergyFraction()
		self.Jet_chHEF[0] = j.chargedHadronEnergyFraction()
		self.Jet_neHEF[0] = j.neutralHadronEnergyFraction()
		self.Jet_neEmEF[0] = j.neutralEmEnergyFraction()
		self.Jet_chMult[0] = j.chargedMultiplicity()
		self.Jet_vtxPt[0] = sqrt(j.userFloat("vtxPx")**2 + j.userFloat("vtxPy")**2)
		self.Jet_vtxMass[0] = j.userFloat("vtxMass")
		self.Jet_vtx3dL[0] = j.userFloat("vtx3dL")
		self.Jet_vtxNtrk[0] = j.userFloat("vtxNtrk")
		self.Jet_vtx3deL[0] = j.userFloat("vtx3deL")
		setattr(j,attrName,self.reader.EvaluateRegression(self.name)[0])
Esempio n. 8
0
def matchToGenHadron(particle, event, minDR=0.05, minDpt=0.1):
        match = ( None, minDR, 2 )
        myeta, myphi = particle.eta(), particle.phi()
        # now, we don't loop over all the packed gen candidates, but rather do fast bisection to find the rightmost with eta > particle.eta() - 0.05
        etacut = myeta - match[1]
        ileft, iright = 0, len(event.packedGenForHadMatch)
        while iright - ileft > 1:
            imid = (iright + ileft)/2
            if event.packedGenForHadMatch[imid][0] > etacut:
                iright = imid
            else:
                ileft = imid
        # now scan from imid to the end (but stop much earlier)
        etacut = myeta +  match[1]
        for i in xrange(ileft,len(event.packedGenForHadMatch)):
            (eta,phi,pg) = event.packedGenForHadMatch[i]
            if eta > etacut: break
            dr  = deltaR(myeta,myphi,eta,phi)
            if dr > match[1]: continue
            if pg.charge() != particle.charge(): continue
            dpt = abs(particle.pt() - pg.pt())/(particle.pt()+pg.pt())
            if pg.pt() > 10: dpt /= 2; # scale down 
            if dpt < minDpt:
                match = ( pg, dr, dpt )
        return match 
    def process(self, event):
        self.readCollections( event.input )

        muons  = [ mu for mu in event.selectedLeptons if abs(mu.pdgId())==13 and self.cfg_ana.selectedMuCut(mu) ]
        muons += [ mu for mu in event.otherLeptons    if abs(mu.pdgId())==13 and self.cfg_ana.otherMuCut(mu)    ]
        
        selectedElectrons = [ ]
        selectedLeptons = [ mu for mu in event.selectedLeptons if abs(mu.pdgId())==13  ]
        for ele in event.selectedLeptons:
            if abs(ele.pdgId()) != 11: continue
            good = True
            for mu in muons:
                dr = deltaR(mu.eta(), mu.phi(), ele.eta(), ele.phi())
                if self.cfg_ana.mustClean(ele,mu,dr):
                    good = False
                    break
            if good:
                selectedLeptons.append(ele) 
            else: # move to the discarded ones
                event.otherLeptons.append(ele) 

        # re-sort
        selectedLeptons.sort(key = lambda l : l.pt(), reverse = True)
        selectedElectrons.sort(key = lambda l : l.pt(), reverse = True)
        event.otherLeptons.sort(key = lambda l : l.pt(), reverse = True)
        event.selectedLeptons = selectedLeptons
        event.selectedElectrons = selectedElectrons

        return True
Esempio n. 10
0
    def checkMatch( self, eta, phi, particles, deltar ):

      for part in particles:
        if deltaR(eta, phi, part.eta(), part.phi()) < deltar:
          return True

      return False
Esempio n. 11
0
 def selectFatJet(self, event):
     if not len(event.cleanJetsAK8) >= 1:
         return False
     if not event.cleanJetsAK8[0].pt() > self.cfg_ana.fatjet_pt: 
         return False
     
     # FatJet selections
     if not event.cleanJetsAK8[0].nSubJetTags >= 2:
         return False
     if not event.cleanJetsAK8[0].userFloat(self.cfg_ana.fatjet_mass_algo) > self.cfg_ana.fatjet_mass:
         return False
     if not hasattr(event.cleanJetsAK8[0], "tau21") or not event.cleanJetsAK8[0].tau21 > self.cfg_ana.fatjet_tau21:
         return False
     
     # Add subjets to the event
     event.SubJets = event.cleanJetsAK8[0].subjets('SoftDrop')
     
     # Higgs candidate
     theV = event.cleanJetsAK8[0].p4()
     theV.charge = event.cleanJetsAK8[0].charge()
     theV.deltaR = deltaR(event.SubJets[0].eta(), event.SubJets[0].phi(), event.SubJets[1].eta(), event.SubJets[1].phi())
     theV.deltaEta = abs(event.SubJets[0].eta() - event.SubJets[1].eta())
     theV.deltaPhi = deltaPhi(event.SubJets[0].phi(), event.SubJets[1].phi())
     theV.deltaPhi_met = deltaPhi(theV.phi(), event.met.phi())
     theV.deltaPhi_jet1 = deltaPhi(theV.phi(), event.cleanJetsAK8[0].phi())
     event.V = theV
     
     return True
Esempio n. 12
0
    def process(self, event):

        for l in event.genParticles:
            if abs(l.pdgId()) in [11, 13] and l.status() == 2:
                hasFSR = False
                for d in range(0, l.numberOfDaughters()):
                    daughter = l.daughter(d)
                    if daughter.pdgId() == 22:
                        hasFSR = True
                if hasFSR:
                    self.vars["mZ"][0] = l.mother(0).mother(0).mass()
                    self.vars["mStar"][0] = (l.daughter(0).p4() + l.daughter(1).p4()).M()
                    self.vars["P"][0] = l.daughter(0).p()
                    self.vars["E"][0] = l.daughter(1).energy()
                    self.vars["ET"][0] = l.daughter(1).pt()
                    self.vars["cosTheta"][0] = l.daughter(0).p4().Vect().Dot(l.daughter(1).p4().Vect()) / (
                        l.daughter(0).p() * l.daughter(1).energy()
                    )
                    self.vars["DR"][0] = deltaR(
                        l.daughter(0).eta(), l.daughter(0).phi(), l.daughter(1).eta(), l.daughter(1).phi()
                    )

                    finalStateLeptons = self.fetchFinalStateLeptons(l.mother(0).mother(0))
                    if len(finalStateLeptons) < 2:
                        continue
                    print "Final state leptons", len(finalStateLeptons)
                    self.vars["mll"][0] = (finalStateLeptons[0].p4() + finalStateLeptons[1].p4()).M()
                    self.vars["mllgamma"][0] = (
                        finalStateLeptons[0].p4() + finalStateLeptons[1].p4() + l.daughter(1).p4()
                    ).M()
                    self.tree.Fill()
        return False
Esempio n. 13
0
 def selectZ(self, event):
     event.isZtoEE = False
     event.isZtoMM = False
     
     if hasattr(event, "muon1") and hasattr(event, "muon2"):
         event.isZtoMM = True
         event.Leptons.append(event.muon1)
         event.Leptons.append(event.muon2)
     elif hasattr(event, "electron1") and hasattr(event, "electron2"):
         event.isZtoEE = True
         event.Leptons.append(event.electron1)
         event.Leptons.append(event.electron2)
     else:
         return False
         
     theZ = event.Leptons[0].p4() + event.Leptons[1].p4()
     if theZ.mass() < self.cfg_ana.mass_low or theZ.mass() > self.cfg_ana.mass_high:
         return False
     theZ.charge = event.Leptons[0].charge() + event.Leptons[1].charge()
     theZ.deltaR = deltaR(event.Leptons[0].eta(), event.Leptons[0].phi(), event.Leptons[1].eta(), event.Leptons[1].phi())
     theZ.deltaEta = abs(event.Leptons[0].eta() - event.Leptons[1].eta())
     theZ.deltaPhi = deltaPhi(event.Leptons[0].phi(), event.Leptons[1].phi())
     theZ.deltaPhi_met = deltaPhi(theZ.phi(), event.met.phi())
     theZ.deltaPhi_jet1 = deltaPhi(theZ.phi(), event.Jets[0].phi())
     event.Z = theZ
     
     return True
    def makeZGenVars(self, event):

        if len(event.genleps) > 1:
            event.genl1l2_m = (event.genleps[0].p4() + event.genleps[1].p4()).M() 
            event.genl1l2_pt = (event.genleps[0].p4() + event.genleps[1].p4()).pt() 
            event.genl1l2_eta = (event.genleps[0].p4() + event.genleps[1].p4()).eta() 
            event.genl1l2_phi = (event.genleps[0].p4() + event.genleps[1].p4()).phi() 
            event.genl1l2_DR = deltaR(event.genleps[0].eta(), event.genleps[0].phi(), event.genleps[1].eta(), event.genleps[1].phi())  
    def makeZVars(self, event):

        if len(event.selectedLeptons) > 1:
            event.l1l2_m = (event.selectedLeptons[0].p4() + event.selectedLeptons[1].p4()).M() 
            event.l1l2_pt = (event.selectedLeptons[0].p4() + event.selectedLeptons[1].p4()).pt() 
            event.l1l2_eta = (event.selectedLeptons[0].p4() + event.selectedLeptons[1].p4()).eta() 
            event.l1l2_phi = (event.selectedLeptons[0].p4() + event.selectedLeptons[1].p4()).phi() 
            event.l1l2_DR = deltaR(event.selectedLeptons[0].eta(), event.selectedLeptons[0].phi(), event.selectedLeptons[1].eta(), event.selectedLeptons[1].phi())  
 def partonCount(self, event):
     if not self.cfg_comp.isMC:
         return True
     partons = [
         p
         for p in event.generatorSummary
         if abs(p.pdgId()) in [1, 2, 3, 4, 5, 21, 22] and p.pt() > self.cfg_ana.mcPartonPtCut
     ]
     leptons = [l for l in event.genleps + event.gentauleps if l.pt() > self.cfg_ana.mcLeptonPtCut]
     taus = [t for t in event.gentaus if t.pt() > self.cfg_ana.mcTauPtCut]
     for i, j in enumerate(event.jets):
         j.mcNumPartons = sum([(deltaR(p, j) < 0.4) for p in partons])
         j.mcNumLeptons = sum([(deltaR(p, j) < 0.4) for p in leptons])
         j.mcNumTaus = sum([(deltaR(p, j) < 0.4) for p in taus])
         p4any = None
         for p in partons + leptons + taus:
             if deltaR(p, j) < 0.4:
                 p4any = p.p4() + p4any if p4any != None else p.p4()
         j.mcAnyPartonMass = p4any.M() if p4any != None else 0.0
Esempio n. 17
0
 def countBPartons(self,event):
     event.allBPartons = [ q for q in event.genParticles if abs(q.pdgId()) == 5 and abs(q.status()) == 2 and abs(q.pt()) > 15 ]
     event.allBPartons.sort(key = lambda q : q.pt(), reverse = True)
     event.bPartons = []
     for q in event.allBPartons:
         duplicate = False
         for q2 in event.bPartons:
             if deltaR(q.eta(),q.phi(),q2.eta(),q2.phi()) < 0.5:
                 duplicate = True
                 continue
         if not duplicate: event.bPartons.append(q)
Esempio n. 18
0
    def __call__(self,object):
        hasOverlap=False
        if abs(object.pdgId()) ==self.sourcePdgId:
            for p in self.collection:
                if abs(p.pdgId()) ==self.targetPdgId:
                    if self.targetID(p)==True:
                        if deltaR(object.eta(),object.phi(),p.eta(),p.phi())<self.dr:
                            hasOverlap=True

        if hasOverlap:
            return False                 
        else:
            return True
Esempio n. 19
0
 def selectW(self, event):
     if not hasattr(event, "muon1"):
         return False
     theW = event.selectedMuons[0].p4() + event.met.p4()
     theW.deltaPhi_met = deltaPhi(event.selectedMuons[0].phi(), event.met.phi())
     theW.mT = math.sqrt( 2.*event.selectedMuons[0].et()*event.met.pt()*(1.-math.cos(theW.deltaPhi_met)) )        
     if theW.mT < self.cfg_ana.mt_low or theW.mT > self.cfg_ana.mt_high:
         return False
     theW.charge = event.selectedMuons[0].charge()
     theW.deltaEta = abs(event.selectedMuons[0].eta())
     theW.deltaPhi = deltaPhi(event.selectedMuons[0].phi(), event.met.phi())
     theW.deltaR = deltaR(event.selectedMuons[0].eta(), event.selectedMuons[0].phi(), 0, event.met.phi())
     event.W = theW
     return True
Esempio n. 20
0
    def makeTaus(self, event):
        event.selectedTaus = []
        event.looseTaus = []
        event.inclusiveTaus = []

        #get all
        alltaus = map( Tau, self.handles['taus'].product() )

        foundTau = False
        for tau in alltaus:
            tau.associatedVertex = event.goodVertices[0]
            tau.lepVeto = False
            if self.cfg_ana.vetoLeptons:
                for lep in event.selectedLeptons:
                    if deltaR(lep.eta(), lep.phi(), tau.eta(), tau.phi()) < self.cfg_ana.leptonVetoDR:
                        tau.lepVeto = True
                if tau.lepVeto: continue
            if self.cfg_ana.vetoLeptonsPOG:
                if not tau.tauID("againstMuonTight"):
                        tau.lepVeto = True
                if not tau.tauID("againstElectronLoose"):
                        tau.lepVeto = True
                if tau.lepVeto: continue
            if tau.pt() < self.cfg_ana.ptMin: continue
            if abs(tau.eta()) > self.cfg_ana.etaMax: continue
###            tau.dxy and tau.dz are zero
###            if abs(tau.dxy()) > self.cfg_ana.dxyMax or abs(tau.dz()) > self.cfg_ana.dzMax: continue
            foundTau = True
            def id3(tau,X):
                """Create an integer equal to 1-2-3 for (loose,medium,tight)"""
                return tau.tauID(X%"Loose") + tau.tauID(X%"Medium") + tau.tauID(X%"Tight")
            #tau.idMVA2   = id3(tau, "by%sIsolationMVA2")
            tau.idCI3hit = id3(tau, "by%sCombinedIsolationDeltaBetaCorr3Hits")
            #print "Tau pt %5.1f: idMVA2 %d, idCI3hit %d, %s, %s" % (tau.pt(), tau.idMVA2, tau.idCI3hit, tau.tauID(self.cfg_ana.tauID), tau.tauID(self.cfg_ana.tauLooseID))
            if tau.tauID(self.cfg_ana.tauID):
                event.selectedTaus.append(tau)
                event.inclusiveTaus.append(tau)
            elif tau.tauID(self.cfg_ana.tauLooseID):
                event.looseTaus.append(tau)
                event.inclusiveTaus.append(tau)

        event.selectedTaus.sort(key = lambda l : l.pt(), reverse = True)
        event.looseTaus.sort(key = lambda l : l.pt(), reverse = True)
        self.counters.counter('events').inc('all events')
        if foundTau: self.counters.counter('events').inc('has >=1 tau at preselection')
        if len(event.selectedTaus): self.counters.counter('events').inc('has >=1 selected taus')
        if len(event.looseTaus): self.counters.counter('events').inc('has >=1 loose taus')
        if len(event.inclusiveTaus): self.counters.counter('events').inc('has >=1 inclusive taus')
Esempio n. 21
0
def makeNearestLeptons(leptons,track, event):

    minDeltaR = 99999
    
    nearestLepton = []
    ibest=-1
    for i,lepton in enumerate(leptons):
        minDeltaRtemp=deltaR(lepton.eta(),lepton.phi(),track.eta(),track.phi())
        if minDeltaRtemp < minDeltaR:
            minDeltaR = minDeltaRtemp
            ibest=i

    if len(leptons) > 0 and ibest!=-1:
        nearestLepton.append(leptons[ibest])

    return nearestLepton
    def makeDeltaRPhoJet(self, event):

        event.minDeltaRPhoJet = []

        for i,photon in enumerate(event.selectedPhotons):

            if i == self.maxPhotons: break

            minDeltaR = 999

            for jet in event.cleanJets:
                minDeltaR=min(deltaR(photon.eta(),photon.phi(),jet.eta(),jet.phi()), minDeltaR)

            # Fill event with the min deltaR for each photon
            event.minDeltaRPhoJet.append(minDeltaR)

        return
Esempio n. 23
0
    def twoLeptonIsolation(self,twoLepton):
        ##First ! attach the FSR photons of this candidate to the leptons!
        
        leptons = twoLepton.daughterLeptons()
        photons = twoLepton.daughterPhotons()

        for l in leptons:
            l.fsrPhotons=[]
            for g in photons:
                if deltaR(g.eta(),g.phi(),l.eta(),l.phi())<0.4:
                    l.fsrPhotons.append(g)
            if abs(l.pdgId())==11:
                if not self.electronIsolation(l):
                    return False
            if abs(l.pdgId())==13:
                if not self.muonIsolation(l):
                    return False
        return True        
Esempio n. 24
0
 def absIsoWithFSR(self, R=0.4, puCorr="rhoArea", dBetaFactor=0.5):
     '''
     Calculate Isolation, subtract FSR, apply specific PU corrections" 
     '''
     photonIso = self.photonIsoR(R)
     if hasattr(self,'fsrPhotons'):
         for gamma in self.fsrPhotons:
             dr = deltaR(gamma.eta(), gamma.phi(), self.physObj.eta(), self.physObj.phi())
             if (self.isEB() or dr > 0.08) and dr < R:
                 photonIso = max(photonIso-gamma.pt(),0.0)                
     if puCorr == "deltaBeta":
         offset = dBetaFactor * self.puChargedHadronIsoR(R)
     elif puCorr == "rhoArea":
         offset = self.rho*getattr(self,"EffectiveArea"+(str(R).replace(".","")))
     elif puCorr in ["none","None",None]:
         offset = 0
     else:
          raise RuntimeError, "Unsupported PU correction scheme %s" % puCorr
     return self.chargedHadronIsoR(R)+max(0.,photonIso+self.neutralHadronIsoR(R)-offset)            
Esempio n. 25
0
    def computeRandomCone( self, event, eta, phi, deltarmax, charged, jets, photons ):

      if self.checkMatch( eta, phi, jets, 2.*deltarmax ): 
        return -1.
    
      if self.checkMatch( eta, phi, photons, 2.*deltarmax ): 
        return -1.
    
      if self.checkMatch( eta, phi, event.selectedLeptons, deltarmax ): 
        return -1.

      iso = 0.

      for part in charged:
        if deltaR(eta, phi, part.eta(), part.phi()) > deltarmax : continue
        #if deltaR(eta, phi, part.eta(), part.phi()) < 0.02: continue
        iso += part.pt()

      return iso
    def process(self, event):
        self.readCollections(event.input)

        puppi = self.handles['puppi'].product()

        for tau in self.getter(event):
            puppi_iso_cands = []
            puppi_iso_cands_04 = []
            puppi_iso_cands_03 = []
            isoPtSumOld = 0.
            tau_eta = tau.eta()
            tau_phi = tau.phi()
            # Normal loop crashes for some reason...
            for i_iso in range(len(tau.isolationCands())):
                    isoPtSumOld += tau.isolationCands()[i_iso].pt()
                    eta = tau.isolationCands()[i_iso].eta()
                    phi = tau.isolationCands()[i_iso].phi()
                    n_p = 0
                    for c_p in puppi:
                        if abs(eta - c_p.eta()) < 0.00001 and \
                           abs(deltaPhi(phi, c_p.phi())) < 0.00001:
                            pdgId = c_p.pdgId()
                            if abs(pdgId) not in [22, 211]:
                                print 'Found puppi particle with pdgID', pdgId, 'ignoring...'
                                continue
                                
                            puppi_iso_cands.append(c_p)
                            n_p += 1
                            dr = deltaR(c_p.eta(), c_p.phi(), tau_eta, tau_phi)
                            if dr < 0.4:
                                puppi_iso_cands_04.append(c_p)
                            if dr < 0.3:
                                puppi_iso_cands_03.append(c_p)
                    if n_p > 1:
                        print 'WARNING, found more than 2 matching puppi particles'

            tau.puppi_iso_pt = sum(c_p.pt() for c_p in puppi_iso_cands)
            tau.puppi_iso04_pt = sum(c_p.pt() for c_p in puppi_iso_cands_04)
            tau.puppi_iso03_pt = sum(c_p.pt() for c_p in puppi_iso_cands_03)
            # Add puppi isolation

        return True
Esempio n. 27
0
    def evaluateRegression(self, event, attrName="pt_reg", analysis=""):
#self.readCollections( event.input )
# uniform with https://github.com/degrutto/HbbRegression 
	#self.rho[0] = event.rho
        self.nPVs[0] = len(event.goodVertices) 
	for j in event.jetsForHiggs :
            pt_corr = 1.0
            if ("JEC" in analysis and hasattr(j, analysis)):
                pt_corr = getattr(j, analysis)/getattr(j, "corr") if hasattr(j, "corr") and getattr(j, "corr") !=0 else 1.0
                #print "JEC"+analysis, pt_corr
            elif ("JER" in analysis and hasattr(j, analysis)):
                pt_corr = getattr(j, analysis)/getattr(j, "corrJER") if hasattr(j, "corrJER") and getattr(j, "corrJER")!=0 else 1.0
                #print "JER"+analysis, pt_corr
            if pt_corr<=0.:
                pt_corr = 1.0
            self.Jet_pt[0] = j.pt()*pt_corr
            #self.Jet_corr[0] = j.rawFactor()/(pt_corr if "JER" not in analysis else 1.0)
           # self.Jet_corr[0] =  (1/ j.rawFactor() ) / j.corrJER * ( pt_corr if "JER" not in analysis else 1.0 )
            self.Jet_corr[0] =  getattr(j, "corr") if hasattr(j, "corr") * (pt_corr if "JER" not in analysis else 1.0 ) else 0.0
            self.Jet_mt[0] = j.mt()*pt_corr
            self.Jet_eta[0] = j.eta()
            self.Jet_leadTrackPt[0] = j.leadTrackPt()
            if len(j.leptons) > 0       :
                self.Jet_leptonPtRel[0] = ptRel(j.leptons[0].p4(),j.p4()*pt_corr)
                self.Jet_leptonPt[0] =  j.leptons[0].pt()
                self.Jet_leptonDeltaR[0] = deltaR(j.leptons[0].p4().eta(),j.leptons[0].p4().phi(),j.p4().eta(),j.p4().phi())
            else:
                self.Jet_leptonPtRel[0] = 0
                self.Jet_leptonPt[0] =  0
                self.Jet_leptonDeltaR[0] =0
            #self.Jet_chEmEF[0] = min(1,0, j.chargedEmEnergyFraction())
            #self.Jet_chHEF[0] = min(1.-, j.chargedHadronEnergyFraction())
            #self.Jet_neHEF[0] = min(1.0,j.neutralHadronEnergyFraction())
            self.Jet_totHEF[0] = min(1.0, j.chargedHadronEnergyFraction() + j.neutralHadronEnergyFraction())    
            self.Jet_neEmEF[0] = min(1.0,j.neutralEmEnergyFraction())
            #self.Jet_chMult[0] = j.chargedMultiplicity()
            self.Jet_vtxPt[0] = sqrt(j.userFloat("vtxPx")**2 + j.userFloat("vtxPy")**2)
            self.Jet_vtxMass[0] = j.userFloat("vtxMass")
            self.Jet_vtx3dL[0] = max(0., j.userFloat("vtx3DVal"))
            self.Jet_vtxNtrk[0] = j.userFloat("vtxNtracks")
            self.Jet_vtx3deL[0] = self.Jet_vtx3dL[0]/j.userFloat("vtx3DSig") if j.userFloat("vtx3DSig") > 0 else 0
            setattr(j,attrName+analysis,self.reader.EvaluateRegression(self.name)[0] * self.Jet_pt[0])
Esempio n. 28
0
 def doHiggsAddJetsdR08(self,event) :
     if ( len(event.jetsForHiggs) >= 2):
        event.hJetsaddJetsdR08 = [x for x in event.hJetsCSV]
        event.dRaddJetsdR08 = []
        event.aJetsaddJetsdR08 = [x for x in event.aJetsCSV]
        event.hjidxaddJetsdR08 = [x for x in event.hjidxCSV]         
        event.ajidxaddJetsdR08 = [x for x in event.ajidxCSV]         
      #multiple jets interpretations, for central jets closest to dR<0.8 from higgs jets
        jetsForHiggsAddJetsdR08 = [x for x in event.cleanJetsAll if (x.pt()>15 and abs(x.eta())<3.0 and x.puJetId() > 0 and x.jetID('POG_PFID_Loose') ) ]
        if (len(jetsForHiggsAddJetsdR08) > 2): 
           addJetsForHiggs = [x for x in jetsForHiggsAddJetsdR08 if ( x not in event.hJetsCSV  and  min(deltaR( x.eta(), x.phi(), event.hJetsCSV[0].eta(), event.hJetsCSV[0].phi()),deltaR( x.eta(), x.phi(), event.hJetsCSV[1].eta(), event.hJetsCSV[1].phi()))<0.8 ) ]
           for x in addJetsForHiggs:
              event.hJetsaddJetsdR08.append(x)
              event.dRaddJetsdR08.append( min(deltaR( x.eta(), x.phi(), event.hJetsCSV[0].eta(), event.hJetsCSV[0].phi()),deltaR( x.eta(), x.phi(), event.hJetsCSV[1].eta(), event.hJetsCSV[1].phi() )) )
           event.hjidxaddJetsdR08=[event.cleanJetsAll.index(x) for x in event.hJetsaddJetsdR08 ]   
           event.aJetsaddJetsdR08 = [x for x in event.cleanJets if x not in event.hJetsaddJetsdR08]
           event.aJetsaddJetsdR08+=event.cleanJetsFwd
           event.ajidxaddJetsdR08=[event.cleanJetsAll.index(x) for x in event.aJetsaddJetsdR08 ]
     
        event.HaddJetsdR08 = sum(map(lambda x:x.p4(), event.hJetsaddJetsdR08), ROOT.reco.Particle.LorentzVector(0.,0.,0.,0.)) 
Esempio n. 29
0
    def softActivity(self,event,j1,j2,excludedJets,dR0=0.4) :
	if not hasattr(event,"pfCands") :
	        event.pfCands = list(self.handles['pfCands'].product())

        inputs=ROOT.std.vector(ROOT.heppy.ReclusterJets.LorentzVector)() 
        used=[]
        for j in excludedJets :
	    for i in xrange(0,j.numberOfSourceCandidatePtrs()) :
		    if j.sourceCandidatePtr(i).isAvailable() :
	                used.append(j.sourceCandidatePtr(i))
	#get the pointed objects
 	used =  [x.get() for x in used]
	remainingPF = [x for x in event.pfCands if x.charge() != 0 and abs(x.eta()) < 2.5 and  x.pt() > 0.3 and x.fromPV() >= 2 and abs(x.dz()) < 0.2 and x not in used] 
        dRbb = deltaR(j1.eta(),j1.phi(),j2.eta(),j2.phi())
	map(lambda x:inputs.push_back(x.p4()), remainingPF)
	softActivity=ROOT.heppy.FastSoftActivity(inputs,-1,0.4,j1.p4(),j2.p4(),dRbb+2*dR0)
        jets=softActivity.getGrouping(1)
        softActivityJets =  [ ROOT.reco.Particle.LorentzVector(p4) for p4 in jets ]
        softActivityJets.sort(key=lambda x:x.pt(), reverse=True)
	return softActivityJets
Esempio n. 30
0
 def absIsoWithFSR(self, R=0.4, puCorr="deltaBeta", dBetaFactor=0.5):
     '''
     Calculate Isolation, subtract FSR, apply specific PU corrections" 
     '''
     photonIso = self.photonIsoR(R)
     if hasattr(self, 'fsrPhotons'):
         for gamma in self.fsrPhotons:
             dr = deltaR(gamma.eta(), gamma.phi(), self.physObj.eta(),
                         self.physObj.phi())
             if dr > 0.01 and dr < R:
                 photonIso = max(photonIso - gamma.pt(), 0.0)
     if puCorr == "deltaBeta":
         offset = dBetaFactor * self.puChargedHadronIsoR(R)
     elif puCorr == "rhoArea":
         offset = self.rho * getattr(
             self, "EffectiveArea" + (str(R).replace(".", "")))
     elif puCorr in ["none", "None", None]:
         offset = 0
     else:
         raise RuntimeError("Unsupported PU correction scheme %s" % puCorr)
     return self.chargedHadronIsoR(R) + max(
         0., photonIso + self.neutralHadronIsoR(R) - offset)
Esempio n. 31
0
def pt_weighted_dx(tau, mode=0, var=0, decaymode=-1):
    sum_pt = 0.
    sum_dx_pt = 0.
    signalrad = max(0.05, min(0.1, 3. / max(1., tau.pt())))
    cands = getGammas(tau, mode < 2)
    for cand in cands:
        if cand.pt() < 0.5:
            continue
        dr = deltaR(cand, tau)
        deta = abs(cand.eta() - tau.eta())
        dphi = abs(deltaPhi(cand.phi(), tau.phi()))
        pt = cand.pt()
        flag = isInside(pt, deta, dphi)
        if decaymode != 10:
            if mode == 2 or (mode == 0
                             and dr < signalrad) or (mode == 1
                                                     and dr > signalrad):
                sum_pt += pt
                if var == 0:
                    sum_dx_pt += pt * dr
                elif var == 1:
                    sum_dx_pt += pt * deta
                elif var == 2:
                    sum_dx_pt += pt * dphi
        else:
            if (mode == 2
                    and flag == False) or (mode == 1
                                           and flag == True) or mode == 0:
                sum_pt += pt
                if var == 0:
                    sum_dx_pt += pt * dr
                elif var == 1:
                    sum_dx_pt += pt * deta
                elif var == 2:
                    sum_dx_pt += pt * dphi
    if sum_pt > 0.:
        return sum_dx_pt / sum_pt
    return 0.
Esempio n. 32
0
    def attachPuppiIso(self, muon, puppi, name='puppi'):
        puppi_iso_cands = []
        puppi_iso_cands_04 = []
        puppi_iso_cands_03 = []
        muon_eta = muon.eta()
        muon_phi = muon.phi()

        for c_p in puppi:
            pdgId = c_p.pdgId()

            if abs(pdgId) not in [22, 130, 211]:
                continue

            eta = c_p.eta()
            phi = c_p.phi()
            # Neutral hadrons or photons
            inner_cone = 0.01
            if abs(pdgId) in [211]:
                inner_cone = 0.0001
            elif c_p.pt() < 0.5:
                continue

            if abs(muon_eta - eta) < 0.5:
                dr = deltaR(eta, phi, muon_eta, muon_phi)
                if inner_cone < dr:
                    if dr < 0.5:
                        puppi_iso_cands.append(c_p)
                    if dr < 0.4:
                        puppi_iso_cands_04.append(c_p)
                    if dr < 0.3:
                        puppi_iso_cands_03.append(c_p)

        setattr(muon, name + '_iso_pt',
                sum(c_p.pt() for c_p in puppi_iso_cands))
        setattr(muon, name + '_iso04_pt',
                sum(c_p.pt() for c_p in puppi_iso_cands_04))
        setattr(muon, name + '_iso03_pt',
                sum(c_p.pt() for c_p in puppi_iso_cands_03))
Esempio n. 33
0
    def nIsrMatch(self, event):

        event.nisrMatch = 0
        jets = [j for j in event.cleanJets if j.pt() > self.jetPt]
        for jet in jets:
            matched = False
            for mc in event.genParticles:  #WithMotherId:
                if matched: break
                if (mc.status() != 23 or abs(mc.pdgId()) > 5): continue
                momid = abs(mc.mother().pdgId())
                if not (momid == 6 or momid == 23 or momid == 24 or momid == 25
                        or momid > 1e6):
                    continue  # MT
                #check against daughter in case of hard initial splitting
                for idau in range(mc.numberOfDaughters()):
                    dR = deltaR(jet.eta(), jet.phi(),
                                mc.daughter(idau).p4().eta(),
                                mc.daughter(idau).p4().phi())
                    if dR < 0.3:
                        matched = True
                        break
            if not matched:
                event.nisrMatch += 1
Esempio n. 34
0
def chargedHadronIso(event, dRCone, PU=False):
    if PU == True:
        charged_pfs = [
            ipf for ipf in event.pfs if (ipf.charge() != 0 and ipf.pt() > 0.5)
        ]
        charged_pfs = [ipf for ipf in charged_pfs if ipf.fromPV() <= 1]
    if PU == False:
        charged_pfs = [
            ipf for ipf in event.pfs
            if (ipf.charge() != 0 and abs(ipf.pdgId()) != 11
                and abs(ipf.pdgId()) != 13 and ipf.pt() > 0.5)
        ]
        charged_pfs = [
            ipf for ipf in charged_pfs
            if (ipf.fromPV() > 1 and abs(ipf.pdgId()) == 211)
        ]
    charged_pfs = [
        ipf for ipf in charged_pfs
        if deltaR(ipf, event.the_3lep_cand.hnVisP4()) < dRCone
    ]
    ch_iso = sum([ipf.pt() for ipf in charged_pfs])
    #    for i in charged_pfs: print 'charged hadron, pile up:\t', dRCone, PU, i.dz(), i.dxy(), i.pt(), i.pdgId()
    return ch_iso
Esempio n. 35
0
    def makeLeptonPairs(self, event, electrons, muons):
        ''' Create all the possible di-lepton pairs 
        out of the different collections'''
        if self.cfg_ana.L1L2LeptonType == 'ee':
            leptons = electrons
        if self.cfg_ana.L1L2LeptonType == 'mm':
            leptons = muons
        if self.cfg_ana.L1L2LeptonType == 'em':
            leptons = electrons + muons

        dileptons = combinations(leptons, 2)
        dileptons = [(lep1, lep2) for lep1, lep2 in dileptons
                     if deltaR(lep1, lep2) > 0.01]

        if self.cfg_ana.L1L2LeptonType == 'em':
            dileptons = [(lep1, lep2) for lep1, lep2 in dileptons
                         if abs(lep1.pdgId()) + abs(lep2.pdgId()) == 24]
            for pair in dileptons:
                pair = sorted(pair,
                              key=lambda lep: (abs(lep.pdgId()), -lep.pt()),
                              reverse=False)

        return dileptons
Esempio n. 36
0
    def selectResolvedJet(self, event):
        if not len(event.cleanJets) >= 2:
            return False
        if not event.cleanJets[0].pt() > self.cfg_ana.jet1_pt: 
            return False
#        if not event.cleanJets[0].btag('combinedInclusiveSecondaryVertexV2BJetTags') > self.cfg_ana.jet1_tag: 
#            return False
        if not event.cleanJets[1].pt() > self.cfg_ana.jet2_pt: 
            return False
#        if not event.cleanJets[1].btag('combinedInclusiveSecondaryVertexV2BJetTags') > self.cfg_ana.jet2_tag: 
#            return False
        
        # Higgs candidate
        theH = event.cleanJets[0].p4() + event.cleanJets[1].p4()
        theH.charge = event.cleanJets[0].charge() + event.cleanJets[1].charge()
        theH.deltaR = deltaR(event.cleanJets[0].eta(), event.cleanJets[0].phi(), event.cleanJets[1].eta(), event.cleanJets[1].phi())
        theH.deltaEta = abs(event.cleanJets[0].eta() - event.cleanJets[1].eta())
        theH.deltaPhi = deltaPhi(event.cleanJets[0].phi(), event.cleanJets[1].phi())
        theH.deltaPhi_met = deltaPhi(theH.phi(), event.met.phi())
        theH.deltaPhi_jet1 = deltaPhi(theH.phi(), event.cleanJets[0].phi())
        event.H = theH
        
        return True
Esempio n. 37
0
    def selectResolvedJet(self, event):
        if not len(event.cleanJets) >= 2:
            return False
        if not event.cleanJets[0].pt() > self.cfg_ana.jet1_pt: 
            return False
#        if not event.cleanJets[0].btag('combinedInclusiveSecondaryVertexV2BJetTags') > self.cfg_ana.jet1_tag: 
#            return False
        if not event.cleanJets[1].pt() > self.cfg_ana.jet2_pt: 
            return False
#        if not event.cleanJets[1].btag('combinedInclusiveSecondaryVertexV2BJetTags') > self.cfg_ana.jet2_tag: 
#            return False
        
        # Higgs candidate
        theH = event.cleanJets[0].p4() + event.cleanJets[1].p4()
        theH.charge = event.cleanJets[0].charge() + event.cleanJets[1].charge()
        theH.deltaR = deltaR(event.cleanJets[0].eta(), event.cleanJets[0].phi(), event.cleanJets[1].eta(), event.cleanJets[1].phi())
        theH.deltaEta = abs(event.cleanJets[0].eta() - event.cleanJets[1].eta())
        theH.deltaPhi = deltaPhi(event.cleanJets[0].phi(), event.cleanJets[1].phi())
        theH.deltaPhi_met = deltaPhi(theH.phi(), event.met.phi())
        theH.deltaPhi_jet1 = deltaPhi(theH.phi(), event.cleanJets[0].phi())
        event.H = theH
        
        return True
    def process(self, event):
        self.readCollections(event.input)

        muons = [
            mu for mu in event.selectedLeptons
            if abs(mu.pdgId()) == 13 and self.cfg_ana.selectedMuCut(mu)
        ]
        muons += [
            mu for mu in event.otherLeptons
            if abs(mu.pdgId()) == 13 and self.cfg_ana.otherMuCut(mu)
        ]

        selectedElectrons = []
        selectedLeptons = [
            mu for mu in event.selectedLeptons if abs(mu.pdgId()) == 13
        ]
        for ele in event.selectedLeptons:
            if abs(ele.pdgId()) != 11: continue
            good = True
            for mu in muons:
                dr = deltaR(mu.eta(), mu.phi(), ele.eta(), ele.phi())
                if self.cfg_ana.mustClean(ele, mu, dr):
                    good = False
                    break
            if good:
                selectedLeptons.append(ele)
            else:  # move to the discarded ones
                event.otherLeptons.append(ele)

        # re-sort
        selectedLeptons.sort(key=lambda l: l.pt(), reverse=True)
        selectedElectrons.sort(key=lambda l: l.pt(), reverse=True)
        event.otherLeptons.sort(key=lambda l: l.pt(), reverse=True)
        event.selectedLeptons = selectedLeptons
        event.selectedElectrons = selectedElectrons

        return True
Esempio n. 39
0
 def doJets(self, event):
     event.cleanJetsAll = []
     event.cleanJetsFwd = []
     event.cleanJets = []
     if self.mchandles['jetsNoNu'].isValid():
         jets = [j for j in self.mchandles['jetsNoNu'].product()]
     else:
         jets = []
         for j in self.mchandles['jets'].product():
             #print "(pass 0) gen jet pt %7.1f eta %+5.2f phi %+5.2f invEnF %.3f " %  (j.pt(), j.eta(), j.phi(), j.invisibleEnergy()/j.energy())
             if j.invisibleEnergy() > 0:
                 p4noNu = j.p4()
                 for idau in xrange(j.numberOfDaughters()):
                     dau = j.daughter(idau)
                     if abs(dau.pdgId()) in [12, 14, 16]:
                         p4noNu -= dau.p4()
                 j.setP4(p4noNu)
                 #print "          w/o nu pt %7.1f eta %+5.2f phi %+5.2f " %  (j.pt(), j.eta(), j.phi())
             jets.append(j)
     jets.sort(key=lambda l: -l.pt())
     for j in jets:
         good = True
         if j.pt() < 25: continue
         #print "(pass 1) gen jet pt %7.1f eta %+5.2f phi %+5.2f" %  (j.pt(), j.eta(), j.phi())
         for l in event.selectedLeptons:
             if l.pt() > 10 and deltaR(l.eta(), l.phi(), j.eta(),
                                       j.phi()) < 0.4:
                 #print "          ov lep pt %7.1f eta %+5.2f phi %+5.2f dr %.3f" %  (l.pt(), l.eta(), l.phi(), deltaR(l.eta(),l.phi(),j.eta(),j.phi()))
                 good = False
                 break
         if not good: continue
         jo = JetFromGen(j)
         event.cleanJetsAll.append(jo)
         if abs(j.eta()) < 2.4:
             event.cleanJets.append(jo)
         else:
             event.cleanJetsFwd.append(jo)
    def leptonAccept(self, leptons, event):
        '''Di-lepton veto: returns false if >= 1 OS same flavour lepton pair,
        e.g. >= 1 OS mu pair in the mu tau channel'''
        looseLeptons = [
            muon for muon in leptons
            if self.testLegKine(muon, ptcut=15, etacut=2.4)
            and muon.isLooseMuon() and self.testVertex(muon)
            and self.testLeg1Iso(muon, 0.3)
        ]
        nLeptons = len(looseLeptons)

        if event.leg1 not in looseLeptons:
            looseLeptons.append(event.leg1)  #TODO why ?

        # by comparison with TauEleAnalyser.py
        if nLeptons < 2:
            return True
        ##

        # if there is an opposite-charge muon pair in the event with muons separated by dR>0.15 and both passing the loose selection
        if any(l.charge() > 0 for l in looseLeptons) and \
           any(l.charge() < 0 for l in looseLeptons):
            looseLeptons_positives = [
                l for l in looseLeptons if l.charge() > 0
            ]
            looseLeptons_negatives = [
                l for l in looseLeptons if l.charge() < 0
            ]
            for l_pos in looseLeptons_positives:
                for l_neg in looseLeptons_negatives:
                    dR = deltaR(l_pos.eta(), l_pos.phi(), l_neg.eta(),
                                l_neg.phi())
                    if dR > 0.15:
                        return False

        return True
Esempio n. 41
0
    def process(self, event):
        self.readCollections(event.input)
        self.counters.counter('RecoGenTreeAnalyzer').inc('all events')

        # produce collections and map our objects to convenient Heppy objects
        event.muons = map(Muon, self.handles['muons'].product())
        event.electrons = map(Electron, self.handles['electrons'].product())
        event.photons = map(Photon, self.handles['photons'].product())
        event.taus = map(Tau, self.handles['taus'].product())
        event.jets = map(Jet, self.handles['jets'].product())
        event.dsmuons = self.buildDisplacedMuons(
            self.handles['dsmuons'].product())
        event.dgmuons = self.buildDisplacedMuons(
            self.handles['dgmuons'].product())

        # vertex stuff
        event.pvs = self.handles['pvs'].product()
        event.svs = self.handles['svs'].product()
        event.beamspot = self.handles['beamspot'].product()

        # met
        event.met = self.handles['met'].product().at(0)

        # assign to the leptons the primary vertex, will be needed to compute a few quantities
        # FIXME! understand exactly to which extent it is reasonable to assign the PV to *all* leptons
        #        regardless whether they're displaced or not
        if len(event.pvs):
            myvtx = event.pvs[0]
        else:
            myvtx = event.beamspot

        self.assignVtx(event.muons, myvtx)
        self.assignVtx(event.electrons, myvtx)
        self.assignVtx(event.photons, myvtx)
        self.assignVtx(event.taus, myvtx)

        # all matchable objects
        # matchable = event.electrons + event.photons + event.muons + event.taus + event.dsmuons + event.dgmuons
        matchable = event.electrons + event.photons + event.muons + event.taus + event.dsmuons

        # match gen to reco
        for ip in [event.the_hnl.l0(), event.the_hnl.l1(), event.the_hnl.l2()]:
            ip.bestmatch = None
            ip.bestmatchtype = None
            ip.matches = inConeCollection(ip, matchable,
                                          getattr(self.cfg_ana, 'drmax', 0.2),
                                          0.)

            # matches the corresponding "slimmed electron" to the gen particle
            if len(event.electrons):
                dr2 = np.inf
                match, dr2 = bestMatch(ip, event.electrons)
                if dr2 < 0.04:
                    ip.bestelectron = match

            # matches the corresponding "slimmed photon" to the gen particle
            if len(event.photons):
                dr2 = np.inf
                match, dr2 = bestMatch(ip, event.photons)
                if dr2 < 0.04:
                    ip.bestphoton = match

            # matches the corresponding "slimmed muon" to the gen particle
            if len(event.muons):
                dr2 = np.inf
                match, dr2 = bestMatch(ip, event.muons)
                if dr2 < 0.04:
                    ip.bestmuon = match

            # matches the corresponding "slimmed tau" to the gen particle
            if len(event.taus):
                dr2 = np.inf
                match, dr2 = bestMatch(ip, event.taus)
                if dr2 < 0.04:
                    ip.besttau = match

            # matches the corresponding "displaced stand alone muon" to the gen particle
            if len(event.dsmuons):
                dr2 = np.inf
                match, dr2 = bestMatch(ip, event.dsmuons)
                if dr2 < 0.04:
                    ip.bestdsmuon = match

            # matches the corresponding "displaced global muon" to the gen particle
            if len(event.dgmuons):
                dr2 = np.inf
                match, dr2 = bestMatch(ip, event.dgmuons)
                if dr2 < 0.04:
                    ip.bestdgmuon = match

            # to find the best match, give precedence to any matched
            # particle in the matching cone with the correct PDG ID
            # then to the one which is closest
            ip.matches.sort(key=lambda x:
                            (x.pdgId() == ip.pdgId(), -deltaR(x, ip)),
                            reverse=True)
            if len(ip.matches) and abs(ip.pdgId()) == abs(
                    ip.matches[0].pdgId()):
                ip.bestmatch = ip.matches[0]
                # remove already matched particles, avoid multiple matches to the same candidate while recording the type of reconstruction
                matchable.remove(ip.bestmatch)

                # record which is which
                if ip.bestmatch in event.electrons: ip.bestmatchtype = 11
                if ip.bestmatch in event.photons: ip.bestmatchtype = 22
                if ip.bestmatch in event.muons: ip.bestmatchtype = 13
                if ip.bestmatch in event.taus: ip.bestmatchtype = 15
                if ip.bestmatch in event.dsmuons: ip.bestmatchtype = 26
                if ip.bestmatch in event.dgmuons: ip.bestmatchtype = 39

            else:
                ip.bestmatchtype = -1

        # clear it before doing it again
        event.recoSv = None

        # if hasattr(event.the_hnl.l2().bestmatch, 'pt'):
        # set_trace()
        # if (abs(event.the_hnl.l1().pt()-13.851562)<0.001):
        # set_trace()

        ######### DEBUG VTX MADE OUT OF DSA MUONS
        #         if len(event.dsmuons) > 2:
        #             # clear the vector
        #             self.tofit.clear()
        #             # create a RecoChargedCandidate for each reconstructed lepton and flush it into the vector
        #             for il in [event.dsmuons[0], event.dsmuons[1]]:
        #                 # if the reco particle is a displaced thing, it does not have the p4() method, so let's build it
        #                 myp4 = ROOT.Math.LorentzVector('<ROOT::Math::PxPyPzE4D<double> >')(il.px(), il.py(), il.pz(), math.sqrt(il.mass()**2 + il.px()**2 + il.py()**2 + il.pz()**2))
        #                 ic = ROOT.reco.RecoChargedCandidate() # instantiate a dummy RecoChargedCandidate
        #                 ic.setCharge(il.charge())             # assign the correct charge
        #                 ic.setP4(myp4)                        # assign the correct p4
        #                 ic.setTrack(il.track())               # set the correct TrackRef
        #                 if ic.track().isNonnull():            # check that the track is valid, there are photons around too!
        #                     self.tofit.push_back(ic)
        #             # further sanity check: two *distinct* tracks
        #             if self.tofit.size()==2 and self.tofit[0].track() != self.tofit[1].track():
        #                 # fit it!
        #                 svtree = self.vtxfit.Fit(self.tofit) # actual vertex fitting
        #                 # check that the vertex is good
        #                 if not svtree.get().isEmpty() and svtree.get().isValid():
        #                     svtree.movePointerToTheTop()
        #                     sv = svtree.currentDecayVertex().get()
        #                     event.recoSv = makeRecoVertex(sv, kinVtxTrkSize=2) # need to do some gymastics
        #                     print 'good double dsa vertex! vx=%.2f, vy=%.2f, vz=%.2f' %(event.recoSv.x(), event.recoSv.y(), event.recoSv.z())
        #                     import pdb ; pdb.set_trace()

        # let's refit the secondary vertex, IF both leptons match to some reco particle
        if not(event.the_hnl.l1().bestmatch is None or \
               event.the_hnl.l2().bestmatch is None):
            # clear the vector
            self.tofit.clear()
            # create a RecoChargedCandidate for each reconstructed lepton and flush it into the vector
            for il in [
                    event.the_hnl.l1().bestmatch,
                    event.the_hnl.l2().bestmatch
            ]:
                # if the reco particle is a displaced thing, it does not have the p4() method, so let's build it
                myp4 = ROOT.Math.LorentzVector(
                    '<ROOT::Math::PxPyPzE4D<double> >')(
                        il.px(), il.py(), il.pz(),
                        math.sqrt(il.mass()**2 + il.px()**2 + il.py()**2 +
                                  il.pz()**2))
                ic = ROOT.reco.RecoChargedCandidate(
                )  # instantiate a dummy RecoChargedCandidate
                ic.setCharge(il.charge())  # assign the correct charge
                ic.setP4(myp4)  # assign the correct p4
                ic.setTrack(il.track())  # set the correct TrackRef
                if ic.track().isNonnull(
                ):  # check that the track is valid, there are photons around too!
                    self.tofit.push_back(ic)

            # further sanity check: two *distinct* tracks
            if self.tofit.size(
            ) == 2 and self.tofit[0].track() != self.tofit[1].track():
                # fit it!
                svtree = self.vtxfit.Fit(self.tofit)  # actual vertex fitting
                # check that the vertex is good
                if not svtree.get().isEmpty() and svtree.get().isValid():
                    svtree.movePointerToTheTop()
                    sv = svtree.currentDecayVertex().get()
                    event.recoSv = makeRecoVertex(
                        sv, kinVtxTrkSize=2)  # need to do some gymastics

            if event.recoSv:
                # primary vertex
                pv = event.goodVertices[0]

                event.recoSv.disp3DFromBS = ROOT.VertexDistance3D().distance(
                    event.recoSv, pv)
                event.recoSv.disp3DFromBS_sig = event.recoSv.disp3DFromBS.significance(
                )

                # create an 'ideal' vertex out of the BS
                point = ROOT.reco.Vertex.Point(
                    event.beamspot.position().x(),
                    event.beamspot.position().y(),
                    event.beamspot.position().z(),
                )
                error = event.beamspot.covariance3D()
                chi2 = 0.
                ndof = 0.
                bsvtx = ROOT.reco.Vertex(point, error, chi2, ndof,
                                         2)  # size? say 3? does it matter?

                event.recoSv.disp2DFromBS = ROOT.VertexDistanceXY().distance(
                    event.recoSv, bsvtx)
                event.recoSv.disp2DFromBS_sig = event.recoSv.disp2DFromBS.significance(
                )
                event.recoSv.prob = ROOT.TMath.Prob(event.recoSv.chi2(),
                                                    int(event.recoSv.ndof()))

                dilep_p4 = event.the_hnl.l1().bestmatch.p4(
                ) + event.the_hnl.l2().bestmatch.p4()

                perp = ROOT.math.XYZVector(dilep_p4.px(), dilep_p4.py(), 0.)

                dxybs = ROOT.GlobalPoint(
                    -1 * ((event.beamspot.x0() - event.recoSv.x()) +
                          (event.recoSv.z() - event.beamspot.z0()) *
                          event.beamspot.dxdz()),
                    -1 * ((event.beamspot.y0() - event.recoSv.y()) +
                          (event.recoSv.z() - event.beamspot.z0()) *
                          event.beamspot.dydz()), 0)

                vperp = ROOT.math.XYZVector(dxybs.x(), dxybs.y(), 0.)

                cos = vperp.Dot(perp) / (vperp.R() * perp.R())

                event.recoSv.disp2DFromBS_cos = cos

#             if (abs(event.the_hnl.l1().pdgId()) == 11 or abs(event.the_hnl.l2().pdgId()) == 11):
#                 if (abs(event.the_hnl.l1().bestmatch.pdgId()) == 11 or abs(event.the_hnl.l2().bestmatch.pdgId()) == 11):
#                     if event.recoSv:
#                         print 'lept1      \t', event.the_hnl.l1()
#                         print 'lept2      \t', event.the_hnl.l2()
#                         print 'lept1 match\t', event.the_hnl.l1().bestmatch
#                         print 'lept2 match\t', event.the_hnl.l2().bestmatch
#                         import pdb ; pdb.set_trace()

        return True
Esempio n. 42
0
 def dR12(self):
     return deltaR(self.l1().p4(), self.l2().p4())
Esempio n. 43
0
 def dR02(self):
     return deltaR(self.l0().p4(), self.l2().p4())
Esempio n. 44
0
    def makeIsoTrack(self, event):



        event.selectedIsoTrack = []
        event.selectedIsoCleanTrack = []
        #event.preIsoTrack = []

        pfcands = self.handles['cmgCand'].product()

        charged = [ p for p in pfcands if ( p.charge() != 0 and abs(p.dz())<=self.cfg_ana.dzMax ) ]

        alltrack = map( IsoTrack, charged )


        for track in alltrack:

            foundNonIsoTrack = False

## ===> require Track Candidate above some pt and charged
            if ( (abs(track.pdgId())!=11) and (abs(track.pdgId())!=13) and (track.pt() < self.cfg_ana.ptMin) ): continue
            if ( track.pt() < self.cfg_ana.ptMinEMU ): continue


## ===> require is not the leading lepton and opposite to the leading lepton 
            if( (self.cfg_ana.doSecondVeto) and len(event.selectedLeptons)>0) : 
               if( deltaR(event.selectedLeptons[0].eta(), event.selectedLeptons[0].phi(), track.eta(), track.phi()) <0.01) : continue
               if ( (abs(track.pdgId())!=11) and (abs(track.pdgId())!=13) and (track.charge()*event.selectedLeptons[0].charge()) ): continue

## ===> Redundant:: require the Track Candidate with a  minimum dz
            track.associatedVertex = event.goodVertices[0]

## ===> compute the isolation and find the most isolated track

            othertracks = [ p for p in charged if( deltaR(p.eta(), p.phi(), track.eta(), track.phi()) < self.cfg_ana.isoDR and p.pt()>self.cfg_ana.ptPartMin ) ]
            #othertracks = alltrack

            isoSum=0
            for part in othertracks:
                #### ===> skip pfcands with a pt min (this should be 0)
                #if part.pt()<self.cfg_ana.ptPartMin : continue
                #### ===> skip pfcands outside the cone (this should be 0.3)
                #if deltaR(part.eta(), part.phi(), track.eta(), track.phi()) > self.cfg_ana.isoDR : continue
                isoSum += part.pt()
                ### break the loop to save time
                if(isoSum > (self.cfg_ana.maxAbsIso + track.pt())):
                    foundNonIsoTrack = True
                    break

            if foundNonIsoTrack: continue

               ## reset
               #isoSum=0
               #for part in othertracks :
               #### ===> skip pfcands with a pt min (this should be 0)
               #    if part.pt()<self.cfg_ana.ptPartMin : continue
               #### ===> skip pfcands outside the cone (this should be 0.3)
               #    if deltaR(part.eta(), part.phi(), track.eta(), track.phi()) > self.cfg_ana.isoDR : continue
               #    isoSum += part.pt()

            #    ###            isoSum = isoSum/track.pt()  ## <--- this is for relIso

            ### ===> the sum should not contain the track candidate

            track.absIso = isoSum - track.pt()

            #### store a preIso track
            #event.preIsoTrack.append(track)
            
#            if (isoSum < minIsoSum ) :
            if(track.absIso < min(0.2*track.pt(), self.cfg_ana.maxAbsIso)): 
                event.selectedIsoTrack.append(track)

                if self.cfg_ana.doPrune:
                    myMet = self.handles['met'].product()[0]
                    mtwIsoTrack = mtw(track, myMet)
                    if mtwIsoTrack < 100:
                        if abs(track.pdgId()) == 11 or abs(track.pdgId()) == 13:
                            if track.pt()>5 and track.absIso/track.pt()<0.2:

                                myLeptons = [ l for l in event.selectedLeptons if l.pt() > 10 ] 
                                nearestSelectedLeptons = makeNearestLeptons(myLeptons,track, event)
                                if len(nearestSelectedLeptons) > 0:
                                    for lep in nearestSelectedLeptons:
                                        if deltaR(lep.eta(), lep.phi(), track.eta(), track.phi()) > 0.1:
                                            event.selectedIsoCleanTrack.append(track)
                                else: 
                                    event.selectedIsoCleanTrack.append(track)

        event.selectedIsoTrack.sort(key = lambda l : l.pt(), reverse = True)
        event.selectedIsoCleanTrack.sort(key = lambda l : l.pt(), reverse = True)

        self.counters.counter('events').inc('all events')
        #if(len(event.preIsoTrack)): self.counters.counter('events').inc('has >=1 selected Track') 
        if(len(event.selectedIsoTrack)): self.counters.counter('events').inc('has >=1 selected Iso Track')
Esempio n. 45
0
    def process(self, event):
        '''
        '''
        self.readCollections(event.input)
        self.tree.reset()

        if not eval(self.skimFunction):
            return False

        self.fillEvent(self.tree, event)
        self.fillTriplet(self.tree, 'cand', event.tau3mu)

        self.fillTriplet(self.tree, 'cand', event.tau3mu)
        self.fillMuon(self.tree, 'mu1', event.tau3mu.mu1())
        self.fillMuon(self.tree, 'mu2', event.tau3mu.mu2())
        self.fillMuon(self.tree, 'mu3', event.tau3mu.mu3())
        self.fillParticle(self.tree, 'met', event.tau3mu.met())

        self.fillTriplet(self.tree, 'cand_refit', event.tau3muRefit)
        self.fillMuon(self.tree, 'mu1_refit', event.tau3muRefit.mu1())
        self.fillMuon(self.tree, 'mu2_refit', event.tau3muRefit.mu2())
        self.fillMuon(self.tree, 'mu3_refit', event.tau3muRefit.mu3())

        if hasattr(event.tau3muRefit, 'refittedVertex'
                   ) and event.tau3muRefit.refittedVertex is not None:
            self.fillVertex(self.tree, 'tau_sv',
                            event.tau3muRefit.refittedVertex)

        # generator information
        if hasattr(event, 'genw') and event.genw is not None:
            self.fillGenParticle(self.tree, 'w', event.genw)

        if hasattr(event.tau3muRefit.mu1(),
                   'genp') and event.tau3muRefit.mu1().genp is not None:
            self.fillGenParticle(self.tree, 'mu1_refit_gen',
                                 event.tau3muRefit.mu1().genp)
        if hasattr(event.tau3muRefit.mu2(),
                   'genp') and event.tau3muRefit.mu2().genp is not None:
            self.fillGenParticle(self.tree, 'mu2_refit_gen',
                                 event.tau3muRefit.mu2().genp)
        if hasattr(event.tau3muRefit.mu3(),
                   'genp') and event.tau3muRefit.mu3().genp is not None:
            self.fillGenParticle(self.tree, 'mu3_refit_gen',
                                 event.tau3muRefit.mu3().genp)

        if hasattr(event, 'genmet') and event.genmet is not None:
            self.fillParticle(self.tree, 'genmet', event.genmet)

        if hasattr(event, 'gentau') and event.gentau is not None:
            self.fillParticle(self.tree, 'gentau', event.gentau)

        # trigger information
        if hasattr(event.tau3muRefit.mu1(), 'L1'):
            self.fillL1object(self.tree, 'mu1_L1', event.tau3muRefit.mu1().L1)
        if hasattr(event.tau3muRefit.mu2(), 'L1'):
            self.fillL1object(self.tree, 'mu2_L1', event.tau3muRefit.mu2().L1)
        if hasattr(event.tau3muRefit.mu3(), 'L1'):
            self.fillL1object(self.tree, 'mu3_L1', event.tau3muRefit.mu3().L1)


        if hasattr(event.tau3muRefit.mu1(), 'L1') and \
           hasattr(event.tau3muRefit.mu2(), 'L1'):

            l1mu1 = ROOT.TLorentzVector()
            l1mu1.SetPtEtaPhiM(
                event.tau3muRefit.mu1().L1.pt(),
                event.tau3muRefit.mu1().L1.eta(),
                event.tau3muRefit.mu1().L1.phi(),
                0.1056583745,
            )

            l1mu2 = ROOT.TLorentzVector()
            l1mu2.SetPtEtaPhiM(
                event.tau3muRefit.mu2().L1.pt(),
                event.tau3muRefit.mu2().L1.eta(),
                event.tau3muRefit.mu2().L1.phi(),
                0.1056583745,
            )

            l1mass12 = (l1mu1 + l1mu2).M()
            l1dR12 = deltaR(l1mu1.Eta(), l1mu1.Phi(), l1mu2.Eta(), l1mu2.Phi())
            l1pt12 = (l1mu1 + l1mu2).Pt()
            self.fill(self.tree, 'L1_mass12', l1mass12)
            self.fill(self.tree, 'L1_dR12', l1dR12)
            self.fill(self.tree, 'L1_pt12', l1pt12)

        if hasattr(event.tau3muRefit.mu1(), 'L1') and \
           hasattr(event.tau3muRefit.mu3(), 'L1'):

            l1mu1 = ROOT.TLorentzVector()
            l1mu1.SetPtEtaPhiM(
                event.tau3muRefit.mu1().L1.pt(),
                event.tau3muRefit.mu1().L1.eta(),
                event.tau3muRefit.mu1().L1.phi(),
                0.1056583745,
            )

            l1mu3 = ROOT.TLorentzVector()
            l1mu3.SetPtEtaPhiM(
                event.tau3muRefit.mu3().L1.pt(),
                event.tau3muRefit.mu3().L1.eta(),
                event.tau3muRefit.mu3().L1.phi(),
                0.1056583745,
            )

            l1mass13 = (l1mu1 + l1mu3).M()
            l1dR13 = deltaR(l1mu1.Eta(), l1mu1.Phi(), l1mu3.Eta(), l1mu3.Phi())
            l1pt13 = (l1mu1 + l1mu3).Pt()
            self.fill(self.tree, 'L1_mass13', l1mass13)
            self.fill(self.tree, 'L1_dR13', l1dR13)
            self.fill(self.tree, 'L1_pt13', l1pt13)

        if hasattr(event.tau3muRefit.mu2(), 'L1') and \
           hasattr(event.tau3muRefit.mu3(), 'L1'):

            l1mu2 = ROOT.TLorentzVector()
            l1mu2.SetPtEtaPhiM(
                event.tau3muRefit.mu2().L1.pt(),
                event.tau3muRefit.mu2().L1.eta(),
                event.tau3muRefit.mu2().L1.phi(),
                0.1056583745,
            )

            l1mu3 = ROOT.TLorentzVector()
            l1mu3.SetPtEtaPhiM(
                event.tau3muRefit.mu3().L1.pt(),
                event.tau3muRefit.mu3().L1.eta(),
                event.tau3muRefit.mu3().L1.phi(),
                0.1056583745,
            )

            l1mass23 = (l1mu2 + l1mu3).M()
            l1dR23 = deltaR(l1mu2.Eta(), l1mu2.Phi(), l1mu3.Eta(), l1mu3.Phi())
            l1pt23 = (l1mu2 + l1mu3).Pt()
            self.fill(self.tree, 'L1_mass23', l1mass23)
            self.fill(self.tree, 'L1_dR23', l1dR23)
            self.fill(self.tree, 'L1_pt23', l1pt23)

        # BDT output
        if hasattr(event, 'bdt_proba'):
            self.fill(self.tree, 'bdt_proba', event.bdt_proba)
        if hasattr(event, 'bdt_decision'):
            self.fill(self.tree, 'bdt_decision', event.bdt_decision)

        self.fillTree(event)
Esempio n. 46
0
     if abs(lepton.pdgId()) == 11 else lepton.muonBestTrackType(),
     int,
     help="Muon best track type"),
 NTupleVariable("ptErrTk",
                lambda lepton: (lepton.gsfTrack().ptError())
                if abs(lepton.pdgId()) == 11 else
                (lepton.muonBestTrack().ptError()),
                help="pt error, for the gsf track or muon best track"),
 NTupleVariable(
     "matchedTrgObjMuPt",
     lambda x: x.matchedTrgObjwmassMu.pt()
     if x.matchedTrgObjwmassMu else -999.,
     help="Matched trigger object (cone dR<0.3) pT to IsoMu24"),
 NTupleVariable(
     "matchedTrgObjMuDR",
     lambda x: deltaR(x, x.matchedTrgObjwmassMu)
     if x.matchedTrgObjwmassMu else -999.,
     help="Matched trigger object (cone dR<0.3) dR to IsoMu24"),
 NTupleVariable(
     "matchedTrgObjTkMuPt",
     lambda x: x.matchedTrgObjwmassTkMu.pt()
     if x.matchedTrgObjwmassTkMu else -999.,
     help="Matched trigger object (cone dR<0.3) pT to IsoTkMu24"),
 NTupleVariable(
     "matchedTrgObjTkMuDR",
     lambda x: deltaR(x, x.matchedTrgObjwmassTkMu)
     if x.matchedTrgObjwmassTkMu else -999.,
     help="Matched trigger object (cone dR<0.3) dR to IsoTkMu24"),
 NTupleVariable("matchedTrgObjMu50Pt",
                lambda x: x.matchedTrgObjwmassMu50.pt()
                if x.matchedTrgObjwmassMu50 else -999.,
Esempio n. 47
0
 def dRHn0(self):
     return deltaR(self.hnP4(), self.l0()) if self.met() else None
 def build_dilepton(self, l1, l2):
     dr = deltaR(l1.eta(), l1.phi(), l2.eta(), l2.phi())
     if dr < self.cfg_ana.dr_min:
         return None
     else:
         return DiLepton(l1, l2)
Esempio n. 49
0
            tofill['mu3_y'] = extra_mu.y()
            tofill['mu3_phi'] = extra_mu.phi()
            tofill['mu3_q'] = extra_mu.charge()

            three_mu_p4 = extra_mu.p4() + jpsi_muons[0].p4(
            ) + jpsi_muons[1].p4()
            b_scaled_p4 = three_mu_p4 * (6.275 / three_mu_p4.mass())

            tofill['mmm_pt'] = three_mu_p4.pt()
            tofill['mmm_eta'] = three_mu_p4.eta()
            tofill['mmm_y'] = three_mu_p4.y()
            tofill['mmm_phi'] = three_mu_p4.phi()
            tofill['mmm_m'] = three_mu_p4.mass()
            tofill['mmm_q'] = extra_mu.charge()

            tofill['dr_jpsi_m'] = deltaR(extra_mu, jpsi)

            tofill['n_extra_mu'] = len(final_state_muons_non_jpsi)

            # how the hell does one boost LorentzVectors back and forth?!
            # using TLorentzVectors of course... shit.
            three_mu_p4_tlv = ROOT.TLorentzVector()
            three_mu_p4_tlv.SetPtEtaPhiE(three_mu_p4.pt(), three_mu_p4.eta(),
                                         three_mu_p4.phi(),
                                         three_mu_p4.energy())
            b_scaled_p4_tlv = ROOT.TLorentzVector()
            b_scaled_p4_tlv.SetPtEtaPhiE(b_scaled_p4.pt(), b_scaled_p4.eta(),
                                         b_scaled_p4.phi(),
                                         b_scaled_p4.energy())
            jpsi_p4_tlv = ROOT.TLorentzVector()
            jpsi_p4_tlv.SetPtEtaPhiE(jpsi.p4().pt(),
 def drllValues(self, event, pairSelection, maxLeps):
     return self.llValues(event, lambda l1,l2: deltaR(l1.eta(), l1.phi(), l2.eta(), l2.phi()), pairSelection, maxLeps)
Esempio n. 51
0
    def process(self, event):
        self.readCollections(event.input)

        self.counters.counter('BKstLLGenAnalyzer').inc('all events')

        # attach qscale (pt hat) to the event
        event.qscale = self.mchandles['genInfo'].product().qScale()

        # get the tracks
        allpf = map(PhysicsObject, self.handles['pfcands'].product())
        losttracks = map(PhysicsObject, self.handles['losttracks'].product())

        # merge the track collections
        event.alltracks = sorted([
            tt for tt in allpf + losttracks
            if tt.charge() != 0 and abs(tt.pdgId()) not in (11, 13)
        ],
                                 key=lambda x: x.pt(),
                                 reverse=True)

        #         import pdb ; pdb.set_trace()

        # get the offline electrons and muons
        event.electrons = map(Electron, self.handles['electrons'].product())
        event.muons = map(Muon, self.handles['muons'].product())

        # find the gen B mesons from the hard scattering
        pruned_gen_particles = self.mchandles['prunedGenParticles'].product()
        packed_gen_particles = self.mchandles['packedGenParticles'].product()
        all_gen_particles = [ip for ip in pruned_gen_particles
                             ] + [ip for ip in packed_gen_particles]

        # match gen mu to offline mu
        genmus = [
            ii for ii in all_gen_particles
            if abs(ii.pdgId()) == 13 and ii.status() == 1
        ]
        for imu in genmus:
            bm, dr = bestMatch(imu, event.muons)
            if dr < 0.3:
                imu.reco = bm
        if len(genmus) > 0:
            event.thetagmu = sorted(genmus, key=lambda x: x.pt(),
                                    reverse=True)[0]

        # match gen ele to offline ele
        geneles = [
            ii for ii in all_gen_particles
            if abs(ii.pdgId()) == 11 and ii.status() == 1
        ]
        for iele in geneles:
            bm, dr = bestMatch(iele, event.electrons)
            if dr < 0.3:
                iele.reco = bm

        event.gen_bmesons = [
            pp for pp in pruned_gen_particles if abs(pp.pdgId()) > 500
            and abs(pp.pdgId()) < 600 and pp.isPromptDecayed()
        ]

        event.gen_b0mesons = [
            pp for pp in pruned_gen_particles if abs(pp.pdgId()) == 511
        ]

        # walk down the lineage of the B mesons and find the final state muons and charged particles
        for ip in event.gen_b0mesons + event.gen_bmesons:
            if getattr(self.cfg_ana, 'verbose', False):
                print 'PdgId : %s   pt : %s  eta : %s   phi : %s' % (
                    ip.pdgId(), ip.pt(), ip.eta(), ip.phi())
                print '     daughters'
            finaldaughters = []
            finalcharged = []
            finalmuons = []
            for ipp in packed_gen_particles:
                mother = ipp.mother(0)
                if mother and self.isAncestor(ip, mother):
                    if abs(ipp.pdgId()) == 13:
                        finalmuons.append(ipp)
                    if abs(ipp.charge()) == 1:
                        finalcharged.append(ipp)
                    if getattr(self.cfg_ana, 'verbose', False):
                        print '     PdgId : %s   pt : %s  eta : %s   phi : %s' % (
                            ipp.pdgId(), ipp.pt(), ipp.eta(), ipp.phi())
                    finaldaughters.append(ipp)
                    if getattr(self.cfg_ana, 'verbose', False):
                        print '     PdgId : %s   pt : %s  eta : %s   phi : %s' % (
                            ipp.pdgId(), ipp.pt(), ipp.eta(), ipp.phi())
            ip.finalmuondaughters = sorted(finalmuons,
                                           key=lambda x: x.pt(),
                                           reverse=True)
            ip.finalchargeddaughters = sorted(finalcharged,
                                              key=lambda x: x.pt(),
                                              reverse=True)
            ip.finaldaughters = sorted(finaldaughters,
                                       key=lambda x: x.pt(),
                                       reverse=True)

        for ib0 in event.gen_b0mesons:
            if abs(self.cfg_ana.flavour) == 11:
                togenmatchleptons = event.electrons
            elif abs(self.cfg_ana.flavour) == 13:
                togenmatchleptons = event.muons
            else:
                print 'you can only pick either pdgId 11 or 13'
                raise
            isit, lp, lm, pi, k = self.isKstLL(ib0, togenmatchleptons,
                                               event.alltracks,
                                               abs(self.cfg_ana.flavour))
            if isit:
                event.kstll = ib0
                event.kstll.lp = lp
                event.kstll.lm = lm
                event.kstll.pi = pi
                event.kstll.k = k
                event.kstll.dr = min(
                    [deltaR(event.kstll, jj) for jj in [lp, lm, pi, k]])
                break  # yeah, only one at a time, mate!

#         if hasattr(event.kstll.lp, 'reco') and hasattr(event.kstll.lm, 'reco'):
#             if event.kstll.lp.reco.pt() ==  event.kstll.lm.reco.pt():
#                 import pdb ; pdb.set_trace()

        if not hasattr(event, 'kstll'):
            return False
        self.counters.counter('BKstLLGenAnalyzer').inc(
            'has a good gen B0->K*LL')

        toclean = None

        if event.kstll.isPromptDecayed():
            toclean = event.kstll

        else:
            for ip in event.gen_bmesons:
                if self.isAncestor(ip, event.kstll):
                    toclean = ip
                    break

#         if toclean is None:
#             print 'nothing to clean lumi %d, ev %d' %(event.lumi, event.eventId)
#             return False
#             import pdb ; pdb.set_trace()
#
#         self.counters.counter('BKstLLGenAnalyzer').inc('no f**k ups')

#         elif abs(event.kstll.mother(0).pdgId())>500 and abs(event.kstll.mother(0).pdgId())<600:
#             if toclean = event.kstll.mother(0)
#         elif abs(event.kstll.mother(0).mother(0).pdgId())>500 and abs(event.kstll.mother(0).mother(0).pdgId())<600:
#         else:
#             print 'nothing to clean lumi %d, ev %d' %(event.lumi, event.eventId)
#             import pdb ; pdb.set_trace()

        if toclean is not None:
            event.clean_gen_bmesons = [
                ib for ib in event.gen_bmesons if ib != toclean
            ]
        else:
            event.clean_gen_bmesons = event.gen_bmesons

#         import pdb ; pdb.set_trace()

# now find the L1 muons from BX = 0
        L1muons_allbx = self.handles['L1muons'].product()

        L1_muons = []

        for jj in range(L1muons_allbx.size(0)):
            L1_muons.append(L1muons_allbx.at(0, jj))

        event.L1_muons = L1_muons

        event.selectedLeptons = [
        ]  # don't really care about isolated leptons, right?

        return True
Esempio n. 52
0
    def process(self, event):
        self.readCollections(event.input)

        event.run = event.input.eventAuxiliary().id().run()
        event.lumi = event.input.eventAuxiliary().id().luminosityBlock()
        event.eventId = event.input.eventAuxiliary().id().event()

        triggerBits = self.handles['triggerResultsHLT'].product()
        names = event.input.object().triggerNames(triggerBits)

        preScales = self.handles['triggerPrescales'].product()

        self.counters.counter('Trigger').inc('All events')

        trigger_passed = False

        trigger_infos = []
        triggers_fired = []

        for trigger_name in self.triggerList + self.extraTrig:
            index = names.triggerIndex(trigger_name)
            if index == len(triggerBits):
                continue
            prescale = preScales.getPrescaleForIndex(index)
            fired = triggerBits.accept(index)

            trigger_infos.append(
                TriggerInfo(trigger_name, index, fired, prescale))

            #print trigger_name, fired, prescale
            #if fired:
            #    import pdb ; pdb.set_trace()
            if fired and (prescale == 1 or self.cfg_ana.usePrescaled):
                if trigger_name in self.triggerList:
                    trigger_passed = True
                    self.counters.counter('Trigger').inc(trigger_name)
                triggers_fired.append(trigger_name)
            elif fired:
                print 'WARNING: Trigger not passing because of prescale', trigger_name
                self.counters.counter('Trigger').inc(trigger_name +
                                                     'prescaled')

        if self.cfg_ana.requireTrigger:
            if not trigger_passed:
                return False

#         if event.eventId == 104644585: import pdb ; pdb.set_trace()
        if self.cfg_ana.addTriggerObjects:
            triggerObjects = self.handles['triggerObjects'].product()
            #             if event.eventId == 104644585: import pdb ; pdb.set_trace()
            for to in triggerObjects:
                to.unpackPathNames(names)
                for info in trigger_infos:
                    #                     if event.eventId == 104644585: import pdb ; pdb.set_trace()
                    if to.hasPathName(info.name):
                        if to in info.objects:
                            continue
                        # print 'TO name', [n for n in to.filterLabels()], to.hasPathName(info.name, False)
                        if self.triggerObjects or self.extraTriggerObjects:
                            if not any(n in to.filterLabels()
                                       for n in self.triggerObjects +
                                       self.extraTriggerObjects):
                                continue
                            info.object_names.append([
                                obj_n for obj_n in self.triggerObjects
                                if obj_n in to.filterLabels()
                            ])
                        else:
                            info.object_names.append('')
                        info.objects.append(to)
                        info.objIds.add(abs(to.pdgId()))

        # RIC: remove duplicated trigger objects
        #      (is this something that may happen in first place?)
        for info in trigger_infos:
            #             if event.eventId == 104644585:
            #                 for oo in info.objects: print oo.pt(), oo.eta(), oo.phi()
            objs = info.objects
            for to1, to2 in combinations(info.objects, 2):
                to1Filter = set(sorted(list(to1.filterLabels())))
                to2Filter = set(sorted(list(to2.filterLabels())))
                if to1Filter != to2Filter:
                    continue
                dR = deltaR(to1.eta(), to1.phi(), to2.eta(), to2.phi())
                if dR < 0.01 and to2 in objs:
                    objs.remove(to2)
            info.objects = objs


#             if event.eventId == 104644585:
#                 for oo in info.objects: print oo.pt(), oo.eta(), oo.phi()

        event.trigger_infos = trigger_infos

        if self.cfg_ana.verbose:
            print 'run %d, lumi %d,event %d' % (
                event.run, event.lumi,
                event.eventId), 'Triggers_fired: ', triggers_fired
        if hasattr(self.cfg_ana, 'saveFlag'):
            if self.cfg_ana.saveFlag:
                setattr(event, 'tag', False)
                setattr(event, 'probe', False)
                for trig in self.triggerList:
                    if trig in triggers_fired:
                        setattr(event, 'tag', True)
                        break
                for trig in self.extraTrig:
                    if trig in triggers_fired:
                        setattr(event, 'probe', True)
                        break

        self.counters.counter('Trigger').inc('HLT')
        return True
Esempio n. 53
0
    def makeTaus(self, event):
        event.inclusiveTaus = []
        event.selectedTaus = []
        event.otherTaus = []

        #get all
        alltaus = map( Tau, self.handles['taus'].product() )

        #make inclusive taus
        goodVertices = getattr(event, self.vertexChoice)
        for tau in alltaus:
            tau.associatedVertex = goodVertices[0] if len(goodVertices)>0 else event.vertices[0]
            tau.lepVeto = False
            tau.idDecayMode = tau.tauID("decayModeFinding")
            tau.idDecayModeNewDMs = tau.tauID("decayModeFindingNewDMs")

            if hasattr(self.cfg_ana, 'inclusive_decayModeID') and self.cfg_ana.inclusive_decayModeID and not tau.tauID(self.cfg_ana.inclusive_decayModeID):
                continue

            tau.inclusive_lepVeto = False
            if self.cfg_ana.inclusive_vetoLeptons:
                for lep in event.selectedLeptons:
                    if deltaR(lep.eta(), lep.phi(), tau.eta(), tau.phi()) < self.cfg_ana.inclusive_leptonVetoDR:
                        tau.inclusive_lepVeto = True
                if tau.inclusive_lepVeto: continue
            if self.cfg_ana.inclusive_vetoLeptonsPOG:
                if not tau.tauID(self.cfg_ana.inclusive_tauAntiMuonID):
                        tau.inclusive_lepVeto = True
                if not tau.tauID(self.cfg_ana.inclusive_tauAntiElectronID):
                        tau.inclusive_lepVeto = True
                if tau.inclusive_lepVeto: continue

            if tau.pt() < self.cfg_ana.inclusive_ptMin: continue
            if abs(tau.eta()) > self.cfg_ana.inclusive_etaMax: continue
            if abs(tau.dxy()) > self.cfg_ana.inclusive_dxyMax or abs(tau.dz()) > self.cfg_ana.inclusive_dzMax: continue

            def id3(tau,X):
                """Create an integer equal to 1-2-3 for (loose,medium,tight)"""
                return tau.tauID(X%"Loose") + tau.tauID(X%"Medium") + tau.tauID(X%"Tight")
            def id5(tau,X):
                """Create an integer equal to 1-2-3-4-5 for (very loose, 
                    loose, medium, tight, very tight)"""
                return id3(tau, X) + tau.tauID(X%"VLoose") + tau.tauID(X%"VTight")
            def id6(tau,X):
                """Create an integer equal to 1-2-3-4-5-6 for (very loose, 
                    loose, medium, tight, very tight, very very tight)"""
                return id5(tau, X) + tau.tauID(X%"VVTight")

            tau.idMVA = id6(tau, "by%sIsolationMVArun2v1DBoldDMwLT")
            tau.idMVAdR03 = id6(tau, "by%sIsolationMVArun2v1DBdR03oldDMwLT")
            tau.idMVANewDM = id6(tau, "by%sIsolationMVArun2v1DBnewDMwLT")
            tau.idCI3hit = id3(tau, "by%sCombinedIsolationDeltaBetaCorr3Hits")
            tau.idAntiMu = tau.tauID("againstMuonLoose3") + tau.tauID("againstMuonTight3")
            tau.idAntiE = id5(tau, "againstElectron%sMVA6")
            #print "Tau pt %5.1f: idMVA2 %d, idCI3hit %d, %s, %s" % (tau.pt(), tau.idMVA2, tau.idCI3hit, tau.tauID(self.cfg_ana.tauID), tau.tauID(self.cfg_ana.tauLooseID))
           
            if self._mvaId2017: tau.mvaId2017 = self._mvaId2017(tau.physObj)
            if tau.tauID(self.cfg_ana.inclusive_tauID):
                event.inclusiveTaus.append(tau)
            
        for tau in event.inclusiveTaus:

            tau.loose_lepVeto = False
            if self.cfg_ana.loose_vetoLeptons:
                for lep in event.selectedLeptons:
                    if deltaR(lep.eta(), lep.phi(), tau.eta(), tau.phi()) < self.cfg_ana.loose_leptonVetoDR:
                        tau.loose_lepVeto = True
            if self.cfg_ana.loose_vetoLeptonsPOG:
                if not tau.tauID(self.cfg_ana.loose_tauAntiMuonID):
                        tau.loose_lepVeto = True
                if not tau.tauID(self.cfg_ana.loose_tauAntiElectronID):
                        tau.loose_lepVeto = True

            if tau.tauID(self.cfg_ana.loose_decayModeID) and \
                      tau.pt() > self.cfg_ana.loose_ptMin and abs(tau.eta()) < self.cfg_ana.loose_etaMax and \
                      abs(tau.dxy()) < self.cfg_ana.loose_dxyMax and abs(tau.dz()) < self.cfg_ana.loose_dzMax and \
                      tau.tauID(self.cfg_ana.loose_tauID) and not tau.loose_lepVeto:
                event.selectedTaus.append(tau)
            else:
                event.otherTaus.append(tau)

        event.inclusiveTaus.sort(key = lambda l : l.pt(), reverse = True)        
        event.selectedTaus.sort(key = lambda l : l.pt(), reverse = True)
        event.otherTaus.sort(key = lambda l : l.pt(), reverse = True)
        self.counters.counter('events').inc('all events')
        if len(event.inclusiveTaus): self.counters.counter('events').inc('has >=1 tau at preselection')
        if len(event.selectedTaus): self.counters.counter('events').inc('has >=1 selected taus')
        if len(event.otherTaus): self.counters.counter('events').inc('has >=1 other taus')
Esempio n. 54
0
 def matchPhotons(self, event):
     event.genPhotons = [ x for x in event.genParticles if x.status() == 1 and abs(x.pdgId()) == 22 ]
     event.genPhotonsWithMom = [ x for x in event.genPhotons if x.numberOfMothers()>0 ]
     event.genPhotonsWithoutMom = [ x for x in event.genPhotons if x.numberOfMothers()==0 ]
     event.genPhotonsMatched = [ x for x in event.genPhotonsWithMom if abs(x.mother(0).pdgId())<23 or x.mother(0).pdgId()==2212 ]
     match = matchObjectCollection3(event.allphotons, event.genPhotonsMatched, deltaRMax = 0.1)
     matchNoMom = matchObjectCollection3(event.allphotons, event.genPhotonsWithoutMom, deltaRMax = 0.1)
     packedGenParts = [ p for p in self.mchandles['packedGen'].product() if abs(p.eta()) < 3.1 ]
     partons = [ p for p in self.mchandles['prunedGen'].product() if (p.status()==23 or p.status()==22) and abs(p.pdgId())<22 ]
     for gamma in event.allphotons:
       gen = match[gamma]
       gamma.mcGamma = gen
       if gen and gen.pt()>=0.5*gamma.pt() and gen.pt()<=2.*gamma.pt():
         gamma.mcMatchId = 22
         sumPt03 = 0.;
         sumPt04 = 0.;
         for part in packedGenParts:
           if abs(part.pdgId())==12: continue # exclude neutrinos
           if abs(part.pdgId())==14: continue
           if abs(part.pdgId())==16: continue
           if abs(part.pdgId())==18: continue
           deltar = deltaR(gen.eta(), gen.phi(), part.eta(), part.phi())
           if deltar <= 0.3:
             sumPt03 += part.pt()
           if deltar <= 0.4:
             sumPt04 += part.pt()
         sumPt03 -= gen.pt()
         sumPt04 -= gen.pt()
         if sumPt03<0. : sumPt03=0.
         if sumPt04<0. : sumPt04=0.
         gamma.genIso03 = sumPt03
         gamma.genIso04 = sumPt04
         # match to parton
         deltaRmin = 999.
         for p in partons:
           deltar = deltaR(gen.eta(), gen.phi(), p.eta(), p.phi())
           if deltar < deltaRmin:
             deltaRmin = deltar
         gamma.drMinParton = deltaRmin
       else:
         genNoMom = matchNoMom[gamma]
         if genNoMom:
           gamma.mcMatchId = 7
           sumPt03 = 0.;
           sumPt04 = 0.;
           for part in packedGenParts:
             if abs(part.pdgId())==12: continue # exclude neutrinos
             if abs(part.pdgId())==14: continue
             if abs(part.pdgId())==16: continue
             if abs(part.pdgId())==18: continue
             deltar = deltaR(genNoMom.eta(), genNoMom.phi(), part.eta(), part.phi())
             if deltar <= 0.3:
               sumPt03 += part.pt()
             if deltar <= 0.4:
               sumPt04 += part.pt()
           sumPt03 -= genNoMom.pt()
           sumPt04 -= genNoMom.pt()
           if sumPt03<0. : sumPt03=0.
           if sumPt04<0. : sumPt04=0.
           gamma.genIso03 = sumPt03
           gamma.genIso04 = sumPt04
           # match to parton
           deltaRmin = 999.
           for p in partons:
             deltar = deltaR(genNoMom.eta(), genNoMom.phi(), p.eta(), p.phi())
             if deltar < deltaRmin:
               deltaRmin = deltar
           gamma.drMinParton = deltaRmin
         else:
           gamma.mcMatchId = 0
           gamma.genIso03 = -1.
           gamma.genIso04 = -1.
           gamma.drMinParton = -1.
Esempio n. 55
0
    def process(self, event):

        self.readCollections(event.input)

        try:
            event.hltL2TauPixelIsoTagProducerLegacy = self.handles[
                'hltL2TauPixelIsoTagProducerLegacy'].product()
            event.hltL2TauPixelIsoTagProducer = self.handles[
                'hltL2TauPixelIsoTagProducer'].product()
            event.hltL2TauJetsIso = self.handles['hltL2TauJetsIso'].product()
            event.hltL2TauIsoFilter = self.handles[
                'hltL2TauIsoFilter'].product()
            event.hltL2TausForPixelIsolation = self.handles[
                'hltL2TausForPixelIsolation'].product()
        except:
            pass

        if self.cfg_ana.verbose:

            if hasattr(event, 'hltL2TauPixelIsoTagProducer'      ) or \
               hasattr(event, 'hltL2TauPixelIsoTagProducerLegacy') or \
               hasattr(event, 'hltL2TauJetsIso'                  ) or \
               hasattr(event, 'hltL2TauIsoFilter'                ) or \
               hasattr(event, 'hltL2TausForPixelIsolation'       ):

                print '\n\n===================== event', event.eventId

                for jet in event.hltL2TausForPixelIsolation:
                    print '\t====>\thltL2TausForPixelIsolation      pt, eta, phi     ', jet.pt(
                    ), jet.eta(), jet.phi()

                for j in range(event.hltL2TauPixelIsoTagProducer.size()):
                    jet = event.hltL2TauPixelIsoTagProducer.keyProduct(
                    ).product().at(j)
                    iso = event.hltL2TauPixelIsoTagProducer.value(j)
                    print '\t====>\thltL2TauPixelIsoTagProducer     pt, eta, phi, iso', jet.pt(
                    ), jet.eta(), jet.phi(), iso

                for jet in event.hltL2TauIsoFilter.jetRefs():
                    print '\t====>\thltL2TauIsoFilter               pt, eta, phi     ', jet.pt(
                    ), jet.eta(), jet.phi()

        self.dRmax = 0.5
        if hasattr(self.cfg_ana, 'dR'):
            self.dRmax = self.cfg_ana.dR

        event.L2jets = []

        # stop here if there are no L2 jets
        if not hasattr(event, 'hltL2TauPixelIsoTagProducer'):
            return True

        nL2jets = event.hltL2TauPixelIsoTagProducer.size()

        for l2jIndex in range(nL2jets):
            jet = event.hltL2TauPixelIsoTagProducer.keyProduct().product().at(
                l2jIndex)
            iso = event.hltL2TauPixelIsoTagProducer.value(l2jIndex)
            isolegacy = event.hltL2TauPixelIsoTagProducerLegacy.value(l2jIndex)

            l2jet = Jet(jet)
            l2jet.L2iso = iso
            l2jet.L2isolegacy = isolegacy

            event.L2jets.append(l2jet)

        for ti in event.trigger_infos:
            for to, jet in product(ti.objects, event.L2jets):

                dR = deltaR(jet.eta(), jet.phi(), to.eta(), to.phi())

                if hasattr(to, 'L2dR'):
                    dRmax = to.L2dR
                else:
                    dRmax = self.dRmax

                if dR < dRmax:
                    to.L2 = jet
                    to.L2iso = jet.L2iso
                    to.L2isolegacy = jet.L2isolegacy
                    to.L2dR = dR

        # stop here if there's no diLepton. Useful for rate studies
        if not hasattr(event, 'diLepton'):
            return True

        legs = {
            event.diLepton.leg1(): self.dRmax,
            event.diLepton.leg2(): self.dRmax
        }

        event.diLepton.leg1().L2 = None
        event.diLepton.leg1().L2iso = None
        event.diLepton.leg1().L2isolegacy = None

        event.diLepton.leg2().L2 = None
        event.diLepton.leg2().L2iso = None
        event.diLepton.leg2().L2isolegacy = None

        for leg, l2jIndex in product(legs.keys(), range(nL2jets)):
            dR = deltaR(jet.eta(), jet.phi(), leg.eta(), leg.phi())
            if dR < legs[leg]:
                leg.L2 = jet
                leg.L2iso = jet.L2iso
                leg.L2isolegacy = jet.L2isolegacy
                leg.L2dR = dR
                legs[leg] = dR

        if self.cfg_ana.verbose:

            if event.diLepton.leg1().L2:
                print 'leg1 L2 jet pt, eta, phi, iso, dR', event.diLepton.leg1(
                ).L2.pt(), event.diLepton.leg1().L2.eta(), event.diLepton.leg1(
                ).L2.phi(), event.diLepton.leg1().L2iso, event.diLepton.leg1(
                ).L2dR
            if event.diLepton.leg2().L2:
                print 'leg2 L2 jet pt, eta, phi, iso, dR', event.diLepton.leg2(
                ).L2.pt(), event.diLepton.leg2().L2.eta(), event.diLepton.leg2(
                ).L2.phi(), event.diLepton.leg2().L2iso, event.diLepton.leg2(
                ).L2dR

        return True
 def ghostSuppression(self, fourLepton):
     leptons = fourLepton.daughterLeptons()
     for l1, l2 in itertools.combinations(leptons, 2):
         if deltaR(l1.eta(), l1.phi(), l2.eta(), l2.phi()) < 0.02:
             return False
     return True
Esempio n. 57
0
 def dR01(self):
     return deltaR(self.l0().p4(), self.l1().p4())
Esempio n. 58
0
 def dR2MET(self):
     return deltaR(self.l2().p4(), self.met().p4()) if self.met() else None
Esempio n. 59
0
 def dRvisHn0(self):
     return deltaR(self.hnVisP4(), self.l0())
Esempio n. 60
0
 def dRvisHnMET(self):
     return deltaR(self.hnVisP4(), self.met()) if self.met() else None