def fillGenLeptons(self, event, particle, isTau=False, sourceId=25):
        """Get the gen level light leptons (prompt and/or from tau decays)"""

        for i in xrange(particle.numberOfDaughters()):
            dau = GenParticle(particle.daughter(i))
            dau.sourceId = sourceId
            dau.isTau = isTau
            id = abs(dau.pdgId())
            moid = 0
            if dau.numberOfMothers() > 0:
                moid = abs(dau.mother().pdgId())
            if id in [11, 13]:
                if isTau: event.gentauleps.append(dau)
                else: event.genleps.append(dau)
            elif id == 15:
                if moid in [22, 23, 24]:
                    event.gentaus.append(dau)
                self.fillGenLeptons(event, dau, True, sourceId)
            elif id in [22, 23, 24]:
                self.fillGenLeptons(event, dau, False, sourceId)
            elif id in [12, 14, 16]:
                event.gennus.append(dau)
Example #2
0
def DecayTracer(particle, e, mu, visible, rank):
    
    '''Check the tau decay'''

    rank += 1

    for i in range( particle.numberOfDaughters() ):
        dau = GenParticle(particle.daughter(i))
#        print "   "*rank, dau.pdgId(), dau.status(), dau.p4().pt()
        if(abs(dau.pdgId()) == 11 and abs(particle.pdgId())==15):
#            print 'electron !', particle.pdgId()
            e.append(dau)
        elif(abs(dau.pdgId()) == 13 and abs(particle.pdgId())==15):
#            print 'muon !', particle.pdgId()
            mu.append(dau)

        if(dau.status()==1):
            if(abs(dau.pdgId()) in [12,14,16]):
                pass
            else:
                visible.append(dau)

        DecayTracer(dau, e, mu, visible, rank)
Example #3
0
    def process(self, iEvent, event):
        self.readCollections(iEvent)

        event.gen = []
        for genp in self.mchandles['gen'].product():
            if abs(genp.pdgId()) != self.cfg_ana.gen_pdgId:
                continue
            event.gen.append(GenParticle(genp))

        event.col1 = map(PhysicsObject, self.handles['col1'].product())
        event.col2 = map(PhysicsObject, self.handles['col2'].product())

        for p in event.col1:
            if hasattr(self.cfg_ana, 'sel1'):
                p.selected = self.cfg_ana.sel1(p)
            else:
                p.selected = True

        for p in event.col2:
            if hasattr(self.cfg_ana, 'sel2'):
                p.selected = self.cfg_ana.sel2(p)
            else:
                p.selected = True

        # first collection is taken as a pivot.
        # will store in the tree all instances in col1, and each time,
        # the closest object in col2

        event.pairs = matchObjectCollection(event.col1, event.col2,
                                            self.cfg_ana.deltaR)

        event.pairsG1 = matchObjectCollection(event.gen, event.col1,
                                              self.cfg_ana.deltaR)

        event.pairsG2 = matchObjectCollection(event.gen, event.col2,
                                              self.cfg_ana.deltaR)
Example #4
0
    def process(self, iEvent, event):

        self.readCollections(iEvent)

        event.genJets = [
            GenJet(ptc.p4()) for ptc in self.mchandles['genJets'].product()
        ]

        event.jets = effAndSmearObjects(event.genJets, CMS, 'jet', Jet)

        event.genElectrons = []
        event.genMuons = []
        event.genParticles = []
        event.genParticles3 = []
        for gp in self.mchandles['genParticles'].product():
            pygp = GenParticle(gp)
            event.genParticles.append(pygp)
            if gp.status() == 3:
                event.genParticles3.append(pygp)
            if abs(gp.pdgId()) == 11:
                event.genElectrons.append(Electron(gp.p4()))
            elif abs(gp.pdgId()) == 13:
                event.genMuons.append(Muon(gp.p4()))

        event.electrons = effAndSmearObjects(event.genElectrons, CMS,
                                             'electron', Electron)
        event.muons = effAndSmearObjects(event.genMuons, CMS, 'muon', Muon)

        #TODO how to decide which ones are considered as leptons in the analysis?
        # iso cut? smear and eff full collection of gen particles?
        # or use gen provenance?
        event.leptons = []

        #TODO deal with taus

        return True
    def makeMCInfo(self, event):
        event.genParticles = map(GenParticle,
                                 self.mchandles['genParticles'].product())

        if False:
            for i, p in enumerate(event.genParticles):
                print " %5d: pdgId %+5d status %3d  pt %6.1f  " % (
                    i, p.pdgId(), p.status(), p.pt()),
                if p.numberOfMothers() > 0:
                    imom, mom = p.motherRef().key(), p.mother()
                    print " | mother %5d pdgId %+5d status %3d  pt %6.1f  " % (
                        imom, mom.pdgId(), mom.status(), mom.pt()),
                else:
                    print " | no mother particle                              ",

                for j in xrange(min(3, p.numberOfDaughters())):
                    idau, dau = p.daughterRef(j).key(), p.daughter(j)
                    print " | dau[%d] %5d pdgId %+5d status %3d  pt %6.1f  " % (
                        j, idau, dau.pdgId(), dau.status(), dau.pt()),
                print ""

        event.genHiggsBoson = None
        event.genVBosons = []
        event.gennus = []
        event.genleps = []
        event.gentauleps = []
        event.gentaus = []
        event.genbquarks = []
        event.genwzquarks = []
        event.gentopquarks = []

        higgsBosons = [
            p for p in event.genParticles if (p.pdgId() == 25)
            and p.numberOfDaughters() > 0 and abs(p.daughter(0).pdgId()) != 25
        ]

        if len(higgsBosons) == 0:
            event.genHiggsDecayMode = 0

            ## Matching that can be done also on non-Higgs events
            ## First, top quarks
            self.fillTopQuarks(event)
            self.countBPartons(event)

            ## Then W,Z,gamma from hard scattering and that don't come from a top and don't rescatter
            def hasAncestor(particle, filter):
                for i in xrange(particle.numberOfMothers()):
                    mom = particle.mother(i)
                    if filter(mom) or hasAncestor(mom, filter):
                        return True
                return False

            def hasDescendent(particle, filter):
                for i in xrange(particle.numberOfDaughters()):
                    dau = particle.daughter(i)
                    if filter(dau) or hasDescendent(dau, filter):
                        return True
                return False

            bosons = [
                gp for gp in event.genParticles
                if gp.status() > 2 and abs(gp.pdgId()) in [22, 23, 24]
            ]

            if self.cfg_ana.verbose:
                print "\n =============="
                for i, p in enumerate(bosons):
                    print " %5d: pdgId %+5d status %3d  pt %6.1f  " % (
                        i, p.pdgId(), p.status(), p.pt()),
                    if p.numberOfMothers() > 0:
                        imom, mom = p.motherRef().key(), p.mother()
                        print " | mother %5d pdgId %+5d status %3d  pt %6.1f  " % (
                            imom, mom.pdgId(), mom.status(), mom.pt()),
                    else:
                        print " | no mother particle                              ",

                    for j in xrange(min(3, p.numberOfDaughters())):
                        idau, dau = p.daughterRef(j).key(), p.daughter(j)
                        print " | dau[%d] %5d pdgId %+5d status %3d  pt %6.1f  " % (
                            j, idau, dau.pdgId(), dau.status(), dau.pt()),
                        print ""

            for b in bosons:
                b.sourceId = -1
                if hasAncestor(b, lambda gp: abs(gp.pdgId()) == 6): continue
                if hasDescendent(
                        b, lambda gp: abs(gp.pdgId()) in [22, 23, 24] and gp.
                        status() > 2):
                    continue
                self.fillGenLeptons(event, b, sourceId=abs(b.pdgId()))
                self.fillWZQuarks(event, b, isWZ=True, sourceId=abs(b.pdgId()))
                #print " ===>  %5d: pdgId %+5d status %3d  pt %6.1f  " % (i, b.pdgId(),b.status(),b.pt()),
                #event.genVBosons.append(b)

        else:
            if len(higgsBosons) > 1:
                print "More than one higgs? \n%s\n" % higgsBosons

            event.genHiggsBoson = GenParticle(higgsBosons[-1])
            event.genHiggsDecayMode = abs(
                event.genHiggsBoson.daughter(0).pdgId())
            self.fillTopQuarks(event)
            self.countBPartons(event)
            self.fillWZQuarks(event, event.genHiggsBoson)
            self.fillGenLeptons(event, event.genHiggsBoson, sourceId=25)
            if self.cfg_ana.verbose:
                print "Higgs boson decay mode: ", event.genHiggsDecayMode
                print "Generator level prompt nus:\n", "\n".join(
                    ["\t%s" % p for p in event.gennus])
                print "Generator level prompt light leptons:\n", "\n".join(
                    ["\t%s" % p for p in event.genleps])
                print "Generator level light leptons from taus:\n", "\n".join(
                    ["\t%s" % p for p in event.gentauleps])
                print "Generator level prompt tau leptons:\n", "\n".join(
                    ["\t%s" % p for p in event.gentaus])
                print "Generator level b quarks from top:\n", "\n".join(
                    ["\t%s" % p for p in event.genbquarks])
                print "Generator level quarks from W, Z decays:\n", "\n".join(
                    ["\t%s" % p for p in event.genwzquarks])
        # make sure prompt leptons have a non-zero sourceId
        for p in event.genParticles:
            if isPromptLepton(p,
                              True,
                              includeTauDecays=True,
                              includeMotherless=False):
                if getattr(p, 'sourceId', 0) == 0:
                    p.sourceId = 99
Example #6
0
    def makeMCInfo(self, event):
        event.genParticles = map(GenParticle,
                                 self.mchandles['genParticles'].product())

        event.genHiggsBoson = None
        event.genleps = []
        event.gentauleps = []
        event.genbquarks = []
        event.genwzquarks = []
        event.gentopquarks = []

        higgsBosons = [
            p for p in event.genParticles
            if (p.status() == 3 and p.pdgId() == 25)
        ]

        if len(higgsBosons) == 0:
            event.genHiggsDecayMode = 0

            ## Matching that can be done also on non-Higgs events
            ## First, top quarks
            self.fillTopQuarks(event)
            self.countBPartons(event)

            ## Then W,Z,gamma from hard scattering and that don't come from a top and don't rescatter
            def hasAncestor(particle, filter):
                for i in xrange(particle.numberOfMothers()):
                    mom = particle.mother(i)
                    if filter(mom) or hasAncestor(mom, filter):
                        return True
                return False

            def hasDescendent(particle, filter):
                for i in xrange(particle.numberOfDaughters()):
                    dau = particle.daughter(i)
                    if filter(dau) or hasDescendent(dau, filter):
                        return True
                return False

            bosons = [
                gp for gp in event.genParticles
                if gp.status() == 3 and abs(gp.pdgId()) in [22, 23, 24]
            ]
            for b in bosons:
                if hasAncestor(b, lambda gp: abs(gp.pdgId()) == 6): continue
                if hasDescendent(
                        b, lambda gp: abs(gp.pdgId()) in [22, 23, 24] and gp.
                        status() == 3):
                    continue
                self.fillGenLeptons(event, b, sourceId=abs(b.pdgId()))
                self.fillWZQuarks(event, b, isWZ=True, sourceId=abs(b.pdgId()))
        else:
            if len(higgsBosons) > 1:
                print "More than one higgs? \n%s\n" % higgsBosons

            event.genHiggsBoson = GenParticle(higgsBosons[-1])
            event.genHiggsDecayMode = abs(
                event.genHiggsBoson.daughter(0).pdgId())
            self.fillTopQuarks(event)
            self.countBPartons(event)
            self.fillWZQuarks(event, event.genHiggsBoson)
            self.fillGenLeptons(event, event.genHiggsBoson, sourceId=25)
            if self.cfg_ana.verbose:
                print "Higgs boson decay mode: ", event.genHiggsDecayMode
                print "Generator level prompt light leptons:\n", "\n".join(
                    ["\t%s" % p for p in event.genleps])
                print "Generator level light leptons from taus:\n", "\n".join(
                    ["\t%s" % p for p in event.gentauleps])
                print "Generator level b quarks from top:\n", "\n".join(
                    ["\t%s" % p for p in event.genbquarks])
                print "Generator level quarks from W, Z decays:\n", "\n".join(
                    ["\t%s" % p for p in event.genwzquarks])
Example #7
0
    def buildLeptonList(self, event):

        self.eleele = False
        self.mumu = False
        self.tautau = False
        self.electrons = []
        self.muons = []
        self.taus = []

        for ptc in self.mchandles['genParticles'].product():
            isElectron = abs(ptc.pdgId()) == 11
            isMuon = abs(ptc.pdgId()) == 13
            isTau = abs(ptc.pdgId()) == 15
            if isElectron:
                if ptc.numberOfMothers() and ptc.mother(0).pdgId() != 23:
                    continue
                self.electrons.append(GenParticle(ptc))
            if isMuon:
                if ptc.numberOfMothers() and ptc.mother(0).pdgId() != 23:
                    continue
                self.muons.append(GenParticle(ptc))
            if isTau:
                if ptc.numberOfMothers() and ptc.mother(0).pdgId() != 23:
                    continue
                self.taus.append(GenParticle(ptc))

        if len(self.electrons) == 2:
            self.eleele = True
        if len(self.muons) == 2:
            self.mumu = True
        if len(self.taus) == 2:
            self.tautau = True

        event.eleele = self.eleele
        event.mumu = self.mumu
        event.tautau = self.tautau

        self.jets = []
        for ptj in self.handles['jets'].product():
            self.jets.append(Jet(ptj))

        self.leptons = []
        for pte in self.handles['electrons'].product():
            self.leptons.append(Lepton(pte))
        for ptm in self.handles['muons'].product():
            self.leptons.append(Lepton(ptm))

        self.photons = []
        for ptg in self.handles['photons'].product():
            if ptg.energy() > 1.0: self.photons.append(Photon(ptg))

        # Find FSR
        tmpLept = set(self.leptons)
        for lept in self.leptons:
            leptonIso = self.leptonIso(lept)
            if leptonIso > 0.05:
                tmpLept.remove(lept)
                continue

            #if (self.eleele or self.mumu or self.tautau ) :
            #    print self.eleele, self.mumu, self.tautau,lept, leptonIso
            for i, ph in enumerate(self.photons):
                dr = deltaR(lept.eta(), lept.phi(), ph.eta(), ph.phi())
                if abs(lept.pdgId()) == 13 and dr < 0.4:
                    #print 'found ISR ',ph,lept
                    leph = lept.p4()
                    p4ph = ph.p4()
                    p4 = ph.p4() + lept.p4()
                    lept.setP4(p4)
                    #print 'added ISR ',ph,lept
        self.leptons = []

        for lept in tmpLept:
            self.leptons.append(lept)

        for lept in self.leptons:
            drmin = 999.

            ijet = -1
            for i, jet in enumerate(self.jets):
                dr = deltaR(lept.eta(), lept.phi(), jet.eta(), jet.phi())
                if dr < drmin:
                    drmin = dr
                    ijet = i
            if ijet >= 0:
                if drmin < 0.1:
                    self.jets[ijet].setP4(lept.p4())
                    self.jets[ijet].setPdgId(lept.pdgId())
Example #8
0
    def process(self, iEvent, event):
        self.readCollections( iEvent )

        self.count.inc('all events')


        # import pdb; pdb.set_trace()
        higgs = None
        event.status3 = []
        for genp in self.mchandles['genParticles'].product():
            if genp.status()==3:
                event.status3.append( GenParticle(genp) )
                if genp.pdgId() == 25:
                    higgs = genp
                    break
                
        # return False

        if higgs is None:
            return False

        if not self.isHtoZZ( higgs ):
            allDaus = []
            allDaus = self.allDaughters( higgs, allDaus, 0 )
            print 'Event', event.iEv
            print 'Higgs', higgs
#            for dau in allDaus:
#                print dau.rank*'\t', GenParticle( dau )
            self.count.inc('weird')
            return False
            # import pdb; pdb.set_trace()

        leptons = []
        leptons = self.findStatus1Leptons( higgs, leptons )

        event.leptons = map( GenParticle, leptons )

        nEles = 0
        nMus = 0
        for lepton in event.leptons:
            pdgId = abs(lepton.pdgId())
            if pdgId==11:
                nEles+=1
            elif pdgId==13:
                nMus += 1
            else:
                raise ValueError('a lepton should be e or mu: {pdgId}'.format(pdgId=pdgId))

        if not ( nMus==4 or \
                 nEles==4 or \
                 (nMus==2 and nEles==2) or \
                 self.isHtoZZtoTaus(higgs)) :
            import pdb; pdb.set_trace()
            
        if self.cfg_ana.channel=='mu-mu' and nMus == 4:
            self.count.inc('mu-mu')
            return True
        elif self.cfg_ana.channel=='ele-ele' and nEles == 4:
            self.count.inc('ele-ele')
            return True
        elif self.cfg_ana.channel=='mu-ele' and nMus == 2 and nEles == 2:
            self.count.inc('mu-ele')
            return True
        else:
            return False
Example #9
0
    def process(self, iEvent, event):
        self.readCollections( iEvent )

        eventNumber = iEvent.eventAuxiliary().id().event()
        #print 'Event ',eventNumber
        # creating a "sub-event" for this analyzer
        myEvent = Event(event.iEv)
        setattr(event, self.name, myEvent)
        event = myEvent
        
        self.buildLeptonList ( event )

        self.buildMiss( event )

        event.allJets = self.jets
        event.njet_ini = len(self.jets)
        #print 'Njet ini ', len(self.jets)
       
        event.jetPairs = self.findPairs( event.allJets )

        #for ptc in self.mchandles['genParticles'].product():
        #    print GenParticle(ptc)
        #for jet in self.jets :
        #    print jet, jet.nConstituents(), jet.component(1).number(), jet.component(1).fraction(), jet.mass(),jet.btag(7),jet.btag(0)

        ###COUNTERS HERE 

        self.counters.counter('FourJetEMiss').inc('All events')
        if self.nunuVV : self.counters.counter('nunuVV').inc('All events')
        event.step = 0

        if self.leptonic:
            self.counters.counter('FourJetEMiss').inc('Leptonic 0')
            if self.nunuVV : self.counters.counter('nunuVV').inc('Leptonic 0')

        #Cut on pTMiss>0
        if self.eMiss.Pt() < self.cfg_ana.ptmiss :
            return 0
        else:
            event.step +=1
        self.counters.counter('FourJetEMiss').inc('ptMiss > 10.')
        if self.nunuVV : self.counters.counter('nunuVV').inc('ptMiss > 10.')
            
        #cut on mVis<180
        if self.eVis.M() > self.cfg_ana.mvis[1] or self.eVis.M() < self.cfg_ana.mvis[0]:
            return 0
        else:
            event.step +=1
        self.counters.counter('FourJetEMiss').inc('10 < mVis < 180.')
        if self.nunuVV : self.counters.counter('nunuVV').inc('10 < mVis < 180.')
        if self.leptonic:
            self.counters.counter('FourJetEMiss').inc('Leptonic 1')
            if self.nunuVV : self.counters.counter('nunuVV').inc('Leptonic 1')

            
        #cut on ctmiss
        if self.eMiss.P() == 0. or abs(self.eMiss.Pz()/self.eMiss.P()) > self.cfg_ana.ctmiss  :
            return 0
        else:
            event.step +=1
        self.counters.counter('FourJetEMiss').inc('ctMiss > 1.00')
        if self.nunuVV : self.counters.counter('nunuVV').inc('ctMiss > 1.00')
            
        #cut on mMiss>0
        if self.eMiss.M() < self.cfg_ana.mmiss :
            return 0
        else:
            event.step +=1

        self.counters.counter('FourJetEMiss').inc('mMiss > 0.')
        if self.nunuVV : self.counters.counter('nunuVV').inc('mMiss > 0.')


        #Calculate alpha for rescaling
        delta = self.eVis.E()*self.eVis.E() * 91.2 * 91.2 + self.eVis.p()*self.eVis.p()*(240.*240.-91.2*91.2)
        if self.eVis.M()> 0 :
            event.alpha = (self.eVis.E()*240. - sqrt(delta)) / (self.eVis.M()*self.eVis.M())
        else:
            print 'Event ', eventNumber, self.eVis.M()
         

        lj = False
        for jet in self.jets :
            if jet.energy() > 10. and jet.component(1).number() < 3 : lj = True
            if jet.pdgId() != 0 : lj = True

        # build two lists: one with 4 jets and onw with only 2 jets 
        self.buildJetList( event )        

        event.njet = len(self.jets)
        #print 'Njet after ', len(self.jets)

        #remove the 4jet cuts, require at least 2
        #if len(self.jet2) <2 : 
        if len(self.jets) != 4 : 
            return 0
        else:
            event.step +=1

        acol = self.jet2[0].px() * self.jet2[1].px() + \
               self.jet2[0].py() * self.jet2[1].py() + \
               self.jet2[0].pz() * self.jet2[1].pz()
        acol /= self.jet2[0].p() * self.jet2[1].p()
        if acol >= 1.0 : acol = 1. - 1E-12
        if acol <= -1.0 : acol = -1. + 1E-12
        acol = acos(acol)*180./pi

        acop = self.jet2[0].px() * self.jet2[1].px() + \
               self.jet2[0].py() * self.jet2[1].py() 
        acop /= self.jet2[0].pt() * self.jet2[1].pt()
        if acop >= 1.0 : acop = 1. - 1E-12
        if acop <= -1.0 : acop = -1. + 1E-12
        acop = acos(acop)*180./pi

        vect1 = TVector3(self.jet2[0].px(), self.jet2[0].py(), self.jet2[0].pz())
        vect2 = TVector3(self.jet2[1].px(), self.jet2[1].py(), self.jet2[1].pz())
        cross = vect1.Unit().Cross(vect2.Unit())
        cross = abs(cross.z())
        cross = asin(cross) * 180./pi

        sumtet = 0.
        if len(self.jet3) == 3 :
            jp = self.findPairs( self.jet3 )
            for j in jp :
                angle = j.leg1.px() * j.leg2.px() + \
                        j.leg1.py() * j.leg2.py() + \
                        j.leg1.pz() * j.leg2.pz() 
                angle /= j.leg1.p() * j.leg2.p()
                angle = acos(angle)*180./pi
                sumtet += angle

        event.acol = acol
        event.acop = acop
        event.sumtet = sumtet
        event.cross = cross

        if self.cfg_ana.hinvis: 
            event.chi2mZ = self.fitmZ()
            event.chi2partiel = self.chi2partiel
            eVisFit = EVis(self.jets)
            eMissFit = EMiss(self.jets)
            event.mVisFit = eVisFit.M()
            event.mMissFit = eMissFit.M()
        else:
            event.chi2mZ = 0.
            event.mVisFit = event.alpha*event.mVis
            event.mMissFit = 91.2


        self.counters.counter('FourJetEMiss').inc('Two Jets')
        if self.nunuVV : self.counters.counter('nunuVV').inc('Two Jets')
        event.step += 1

        if self.leptonic:
            self.counters.counter('FourJetEMiss').inc('Leptonic 2')
            if self.nunuVV : self.counters.counter('nunuVV').inc('Leptonic 2')

        #Check how many 4 jets events would be there (no cut)
        if len(self.jets) == 4 : self.counters.counter('FourJetEMiss').inc('Four Good Jets')
        if len(self.jets) == 4 and self.nunuVV : self.counters.counter('nunuVV').inc('Four Good Jets')

        #add the cuts in the macro
        if abs(self.eMiss.M()-95.) > 1000.  or event.acop > 1800. or event.ptMiss < 0. or lj :
            return 0
        else :
            self.counters.counter('FourJetEMiss').inc('Other Cuts')
            if self.nunuVV : self.counters.counter('nunuVV').inc('Other Cuts')
        event.step+1

        #print out the genparticle info
        for ptc in self.mchandles['genParticles'].product():
           print GenParticle(ptc)
        for jet in self.jets :
            print jet, jet.nConstituents(), jet.component(1).number(), jet.component(1).fraction(), jet.mass(),jet.btag(7),jet.btag(0)


        return True