Exemple #1
0
    def addTau_genMatchType(self, event, tau):
        '''Determine if given tau matched gen level hadronic tau decay or is due to a misidentified jet, electron or muon
             tau.genMatchType = 0 for matched to gen level hadronic tau decay
                              = 1 for matched to gen level jet
                              = 2 for matched to gen level electron
                              = 3 for matched to gen level muon
      '''

        genParticles = list(self.mchandles['genParticles'].product())

        genMatchType = 1  # assume hadronic tau to be due to misidentified jet per default
        if tau.genJet():
            genMatchType = 0
        if genMatchType == 1:
            match = matchObjectCollection3(
                [tau],
                genParticles,
                deltaRMax=0.4,
                filter=lambda x, y: True
                if (y.pt() > 0.5 * x.pt() and abs(y.pdgId()) == 11) else False)
            if match[tau]:
                genMatchType = 2
        if genMatchType == 1:
            match = matchObjectCollection3(
                [tau],
                genParticles,
                deltaRMax=0.4,
                filter=lambda x, y: True
                if (y.pt() > 0.5 * x.pt() and abs(y.pdgId()) == 13) else False)
            if match[tau]:
                genMatchType = 3

        return genMatchType
Exemple #2
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.
Exemple #3
0
 def matchTaus(self, event):
     match = matchObjectCollection3(event.inclusiveTaus,
                                    event.gentaus,
                                    deltaRMax=0.5)
     for lep in event.inclusiveTaus:
         gen = match[lep]
         lep.mcMatchId = 1 if gen else 0
    def process(self, event):
        self.readCollections( event.input )
        triggerBits = self.handles['TriggerBits'].product()
        allTriggerObjects = self.handles['TriggerObjects'].product()
        names = event.input.object().triggerNames(triggerBits)
        for ob in allTriggerObjects: ob.unpackPathNames(names)
        triggerObjects = [ob for ob in allTriggerObjects if False not in [sel(ob) for sel in self.trgObjSelectors]]

        setattr(event,'trgObjects_'+self.label,triggerObjects)

        if self.collToMatch:
            tcoll = getattr(event,self.collToMatch)
            doubleandselector = lambda lep,ob: False if False in [sel(lep,ob) for sel in self.collMatchSelectors] else True
            pairs = matchObjectCollection3(tcoll,triggerObjects,deltaRMax=self.collMatchDRCut,filter=doubleandselector) if self.match1To1 else matchObjectCollection(tcoll,triggerObjects,self.collMatchDRCut,filter=doubleandselector)
            for lep in tcoll: setattr(lep,'matchedTrgObj'+self.label,pairs[lep])

        if self.verbose:
            print 'Verbose debug for triggerMatchAnalyzer %s'%self.label
            for ob in getattr(event,'trgObjects_'+self.label):
                types = ", ".join([str(f) for f in ob.filterIds()])
                filters = ", ".join([str(f) for f in ob.filterLabels()])
                paths = ", ".join([("%s***" if f in set(ob.pathNames(True)) else "%s")%f for f in ob.pathNames()]) # asterisks indicate final paths fired by this object, see pat::TriggerObjectStandAlone class
                print 'Trigger object: pt=%.2f, eta=%.2f, phi=%.2f, collection=%s, type_ids=%s, filters=%s, paths=%s'%(ob.pt(),ob.eta(),ob.phi(),ob.collection(),types,filters,paths)
            if self.collToMatch:
                for lep in tcoll:
                    mstring = 'None'
                    if getattr(lep,'matchedTrgObj'+self.label):
                        mstring = 'trigger obj with pt=%.2f, eta=%.2f, phi=%.2f, collection=%s'%(ob.pt(),ob.eta(),ob.phi(),ob.collection())
                    print 'Lepton pt=%.2f, eta=%.2f, phi=%.2f matched to %s'%(lep.pt(),lep.eta(),lep.phi(),mstring)

        return True
    def process(self, event):
        self.readCollections( event.input )
        triggerBits = self.handles['TriggerBits'].product()
        allTriggerObjects = self.handles['TriggerObjects'].product()
        names = event.input.object().triggerNames(triggerBits)
        for ob in allTriggerObjects: ob.unpackPathNames(names)
        triggerObjects = [ob for ob in allTriggerObjects if False not in [sel(ob) for sel in self.trgObjSelectors]]

        setattr(event,'trgObjects_'+self.label,triggerObjects)

        if self.collToMatch:
            tcoll = getattr(event,self.collToMatch)
            doubleandselector = lambda lep,ob: False if False in [sel(lep,ob) for sel in self.collMatchSelectors] else True
            pairs = matchObjectCollection3(tcoll,triggerObjects,deltaRMax=self.collMatchDRCut,filter=doubleandselector) if self.match1To1 else matchObjectCollection(tcoll,triggerObjects,self.collMatchDRCut,filter=doubleandselector)
            for lep in tcoll: setattr(lep,'matchedTrgObj'+self.label,pairs[lep])

        if self.verbose:
            print 'Verbose debug for triggerMatchAnalyzer %s'%self.label
            for ob in getattr(event,'trgObjects_'+self.label):
                types = ", ".join([str(f) for f in ob.filterIds()])
                filters = ", ".join([str(f) for f in ob.filterLabels()])
                paths = ", ".join([("%s***" if f in set(ob.pathNames(True)) else "%s")%f for f in ob.pathNames()]) # asterisks indicate final paths fired by this object, see pat::TriggerObjectStandAlone class
                print 'Trigger object: pt=%.2f, eta=%.2f, phi=%.2f, collection=%s, type_ids=%s, filters=%s, paths=%s'%(ob.pt(),ob.eta(),ob.phi(),ob.collection(),types,filters,paths)
            if self.collToMatch:
                for lep in tcoll:
                    mstring = 'None'
                    ob = getattr(lep,'matchedTrgObj'+self.label)
                    if ob: mstring = 'trigger obj with pt=%.2f, eta=%.2f, phi=%.2f, collection=%s'%(ob.pt(),ob.eta(),ob.phi(),ob.collection())
                    print 'Lepton pt=%.2f, eta=%.2f, phi=%.2f matched to %s'%(lep.pt(),lep.eta(),lep.phi(),mstring)

        return True
Exemple #6
0
 def matchIsoTrack(self, event):
     matchTau = matchObjectCollection3(event.selectedIsoTrack,
                                       event.gentaus + event.gentauleps +
                                       event.genleps,
                                       deltaRMax=0.5)
     for lep in event.selectedIsoTrack:
         gen = matchTau[lep]
         lep.mcMatchId = 1 if gen else 0
    def matchLeptons(self, ret, leps, genleps, genlepsfromtau, event):

        # if precalculated, propagate the value and return
        if hasattr(event._tree, "LepGood_mcMatchPdgId"):
            if not hasattr(self, "printed_mcMatch_warning"):
                print "Found LepGood_mcMatchPdgId in the event, will use that."
                self.printed_mcMatch_warning = True
            for il, lep in enumerate(leps):
                ret["LepGood_mcMatchPdgId"][il] = lep.mcMatchPdgId
            return

        if not hasattr(self, "printed_mcMatch_warning"):
            print "Will calculate LepGood_mcMatchPdgId in leptonJetReCleaner, the result will be similar to the precalculated one but not identical."
            self.printed_mcMatch_warning = True

        def plausible(rec, gen):
            if abs(rec.pdgId()) == 11 and abs(gen.pdgId()) != 11:
                return False
            if abs(rec.pdgId()) == 13 and abs(gen.pdgId()) != 13:
                return False
            dr = deltaR(rec.eta(), rec.phi(), gen.eta(), gen.phi())
            if dr < 0.3:
                return True
            if rec.pt() < 10 and abs(rec.pdgId()) == 13 and gen.pdgId() != rec.pdgId():
                return False
            if dr < 0.7:
                return True
            if min(rec.pt(), gen.pt()) / max(rec.pt(), gen.pt()) < 0.3:
                return False
            return True

        allgenleps = genleps + genlepsfromtau
        myleps = [MyVarProxy(lep) for lep in leps]
        mygenleps = [MyVarProxy(glep) for glep in allgenleps]
        match = matchObjectCollection3(myleps, mygenleps, deltaRMax=1.2, filter=plausible)

        for il, mylep in enumerate(myleps):
            mygen = match[mylep]
            if mygen:
                if mygen.sourceId != mylep.mcMatchId:
                    raise RuntimeError, "Error in lepton re-matching: sourceId/mcMatchId %d %d" % (
                        mygen.sourceId,
                        mylep.mcMatchId,
                    )
                ret["LepGood_mcMatchPdgId"][il] = mygen.pdgId()
            else:
                if mylep.mcMatchId != 0:
                    if mylep.mcMatchId == 100:
                        print "Warning (evt. %d): reco lepton which has mcMatchId==100, mcMatchAny==%d had been matched to a prompt lepton that was not included in the genLepton collections. It was not re-matched: assuming correct charge reconstruction in this case!" % (
                            event.evt,
                            mylep.mcMatchAny,
                        )
                        ret["LepGood_mcMatchPdgId"][il] = mylep.pdgId()
                    else:
                        raise RuntimeError, "Error in lepton re-matching: lep.mcMatchId is %d for not matched" % (
                            mylep.mcMatchId
                        )
    def __call__(self, event):

        nleps = getattr(event, "nLepGood")
        nFO = getattr(event, "nLepFO" + self.label)
        chosen = getattr(event, "iLepFO" + self.label)
        leps = [
            MatchRecoToPartonsTTH_MyObjectProxy(event, "LepGood", i)
            for i in xrange(nleps)
        ]
        lepsFO = [leps[chosen[i]] for i in xrange(nFO)]
        reco = [
            MatchRecoToPartonsTTH_MyObjectProxy(event, "JetSel" + self.label,
                                                i)
            for i in xrange(getattr(event, "nJetSel" + self.label))
        ]
        gen = [
            MatchRecoToPartonsTTH_MyObjectProxy(event, "GenPart", i)
            for i in xrange(getattr(event, 'nGenPart'))
        ]
        ngenfinal = getattr(event, "nallFinalParton")
        igenfinal = getattr(event, "iallFinalParton")
        genfinal = [gen[igenfinal[i]] for i in xrange(ngenfinal)]

        pairs = matchObjectCollection3(lepsFO + reco, genfinal)

        mLeps = [-1] * len(leps)
        mReco = [-1] * len(reco)
        mPartLeps = [-1] * len(gen)
        mPart = [-1] * len(gen)
        for ij, j in enumerate(leps):
            if j not in lepsFO: continue
            mp = pairs[j]
            if mp:
                gind = gen.index(mp)
                mLeps[ij] = gind
                mPartLeps[gind] = ij
        for ij, j in enumerate(reco):
            mp = pairs[j]
            if mp:
                gind = gen.index(mp)
                mReco[ij] = gind
                mPart[gind] = ij
        ret = {}
        ret["nLepGood"] = len(leps)
        ret["nJetSel" + self.label] = len(reco)
        ret["nGenPart"] = len(gen)
        ret["LepGood_matchedGenPart"] = mLeps
        ret["JetSel" + self.label + "_matchedGenPart"] = mReco
        ret['GenPart_matchedLepGood'] = mPartLeps
        ret['GenPart_matchedJetSel'] = mPart
        return ret
   def addTau_genMatchType(self, event, tau):      
      '''Determine if given tau matched gen level hadronic tau decay or is due to a misidentified jet, electron or muon
             tau.genMatchType = 0 for matched to gen level hadronic tau decay
                              = 1 for matched to gen level jet
                              = 2 for matched to gen level electron
                              = 3 for matched to gen level muon
      '''

      genParticles = list(self.mchandles['genParticles'].product() )

      genMatchType = 1 # assume hadronic tau to be due to misidentified jet per default
      if tau.genJet():
         genMatchType = 0
      if genMatchType == 1:
         match = matchObjectCollection3([ tau ], genParticles, deltaRMax = 0.4, filter = lambda x,y : True if (y.pt() > 0.5*x.pt() and abs(y.pdgId()) == 11) else False)
         if match[tau]:
            genMatchType = 2
      if genMatchType == 1:
         match = matchObjectCollection3([ tau ], genParticles, deltaRMax = 0.4, filter = lambda x,y : True if (y.pt() > 0.5*x.pt() and abs(y.pdgId()) == 13) else False)
         if match[tau]:
            genMatchType = 3

      return genMatchType
    def matchLeptons(self, ret, leps, genleps, genlepsfromtau, event):

        # if precalculated, propagate the value and return
        if hasattr(event._tree,"LepGood_mcMatchPdgId"):
            if not hasattr(self,"printed_mcMatch_warning"):
                print 'Found LepGood_mcMatchPdgId in the event, will use that.'
                self.printed_mcMatch_warning = True
            for il,lep in enumerate(leps):
                ret["LepGood_mcMatchPdgId"][il] = lep.mcMatchPdgId
            return

        if not hasattr(self,"printed_mcMatch_warning"):
            print 'Will calculate LepGood_mcMatchPdgId in leptonJetReCleaner, the result will be similar to the precalculated one but not identical.'
            self.printed_mcMatch_warning = True

        def plausible(rec,gen):
            if abs(rec.pdgId()) == 11 and abs(gen.pdgId()) != 11:   return False
            if abs(rec.pdgId()) == 13 and abs(gen.pdgId()) != 13:   return False
            dr = deltaR(rec.eta(),rec.phi(),gen.eta(),gen.phi())
            if dr < 0.3: return True
            if rec.pt() < 10 and abs(rec.pdgId()) == 13 and gen.pdgId() != rec.pdgId(): return False
            if dr < 0.7: return True
            if min(rec.pt(),gen.pt())/max(rec.pt(),gen.pt()) < 0.3: return False
            return True

        allgenleps = genleps+genlepsfromtau
        myleps = [MyVarProxy(lep) for lep in leps]
        mygenleps = [MyVarProxy(glep) for glep in allgenleps]
        match = matchObjectCollection3(myleps,mygenleps, 
                                       deltaRMax = 1.2, filter = plausible)

        for il,mylep in enumerate(myleps):
            mygen = match[mylep]
            if mygen:
                if (mygen.sourceId != mylep.mcMatchId): raise RuntimeError, "Error in lepton re-matching: sourceId/mcMatchId %d %d"%(mygen.sourceId,mylep.mcMatchId)
                ret["LepGood_mcMatchPdgId"][il] = mygen.pdgId()
            else:
                if mylep.mcMatchId != 0:
                    if mylep.mcMatchId == 100:
                        print 'Warning (evt. %d): reco lepton which has mcMatchId==100, mcMatchAny==%d had been matched to a prompt lepton that was not included in the genLepton collections. It was not re-matched: assuming correct charge reconstruction in this case!'%(event.evt,mylep.mcMatchAny)
                        ret["LepGood_mcMatchPdgId"][il] = mylep.pdgId()
                    else: raise RuntimeError, "Error in lepton re-matching: lep.mcMatchId is %d for not matched"%(mylep.mcMatchId)
Exemple #11
0
 def matchIsoTrack(self, event):
     matchTau = matchObjectCollection3(event.selectedIsoTrack, event.gentaus + event.gentauleps + event.genleps, deltaRMax = 0.5)
     for lep in event.selectedIsoTrack:
         gen = matchTau[lep]
         lep.mcMatchId = 1 if gen else 0
Exemple #12
0
 def matchTaus(self, event):
     match = matchObjectCollection3(event.inclusiveTaus, event.gentaus, deltaRMax = 0.5)
     for lep in event.inclusiveTaus:
         gen = match[lep]
         lep.mcMatchId = 1 if gen else 0
         lep.genp = gen
Exemple #13
0
    def process(self, event):
        self.readCollections(event.input)
        self.counters.counter('events').inc('all events')

        muons = []
        electrons = []
        for i, l in enumerate(event.selectedLeptons):
            l.index = i
            if abs(l.pdgId()) == 13: muons.append(l)
            if abs(l.pdgId()) == 11: electrons.append(l)

        for i, l in enumerate(event.selectedTaus):
            l.index = i

        for i, l in enumerate(event.cleanJets):
            l.index = i

        getDeDxRef = self.handles['dedx'].product().get
        if self.cfg_ana.doDeDx == "94XMiniAODv1-Hack":
            fixed = self.handles['dedx'].product().fixOffsets(-1)
            getDeDxRef = fixed.get

        event.isoTracks = []

        pixelChargeToEnergyCoefficient = 3.61e-6
        stripChargeToEnergyCoefficient = 3.61e-6 * 265

        for t in event.preselIsoTracks:
            # add more variables
            t.leadAwayJet = leading(cleaned(t, event.cleanJets, 0.4))
            t.awayJetInfo = jetStats(cleaned(t, event.cleanJets, 0.4))
            t.leadAwayMu = leading(cleaned(t, muons, 0.4))
            t.leadAwayEle = leading(cleaned(t, electrons, 0.4))
            t.leadAwayTau = leading(cleaned(t, event.selectedTaus, 0.4))
            t.closestMu = closest(t, nearby(t, muons, 0.4))
            t.closestEle = closest(t, nearby(t, electrons, 0.4))
            t.closestTau = closest(t, nearby(t, event.selectedTaus, 0.4))

            dedxArray = []
            subDetIdArray = []
            sizeXarray = []
            sizeYarray = []

            # geometry for pixels
            layerPixelArray = []
            ladderPixelArray = []
            modulePixelArray = []
            sidePixelArray = []
            diskPixelArray = []
            bladePixelArray = []
            panelPixelArray = []

            for i in xrange(100):
                dedxArray.append(0)
                subDetIdArray.append(0)
                sizeXarray.append(0)
                sizeYarray.append(0)

                # geometry for pixels
                layerPixelArray.append(0)
                ladderPixelArray.append(0)
                modulePixelArray.append(0)
                sidePixelArray.append(0)
                diskPixelArray.append(0)
                bladePixelArray.append(0)
                panelPixelArray.append(0)

            # get dedx
            if self.cfg_ana.doDeDx:
                ref = getDeDxRef(t.index)
                if ref.isNull():
                    print "ERROR: no dE/dx for track of pt %.2f, eta %.2f" % (
                        t.pt(), t.eta())
                    continue
                dedx = ref.get()
                nhits = dedx.size()

                # this below is just dummy to give you a template
                mysum = 0

                for ih in xrange(nhits):
                    pixelCluster = dedx.pixelCluster(ih)
                    stripCluster = dedx.stripCluster(ih)
                    if pixelCluster:
                        dedxArray[ih] = pixelCluster.charge(
                        ) / dedx.pathlength(ih)
                        # convert number of electrons to MeV
                        dedxArray[ih] *= pixelChargeToEnergyCoefficient

                        sizeXarray[ih] = pixelCluster.sizeX()
                        sizeYarray[ih] = pixelCluster.sizeY()

                        mysum += pixelCluster.charge()

                        #
                        #  https://github.com/cms-sw/cmssw/blob/master/DataFormats/TrackReco/interface/DeDxHitInfo.h
                        #
                        #  dEdX object DeDxHitInfoCollection
                        #
                        #
                        #  https://github.com/cms-sw/cmssw/blob/master/DataFormats/SiPixelDetId/interface/PXBDetId.h
                        #  https://github.com/cms-sw/cmssw/blob/master/DataFormats/SiPixelDetId/interface/PXFDetId.h
                        #
                        if dedx.detId(ih).subdetId() == 1:
                            # barrel
                            layerPixelArray[ih] = ROOT.PXBDetId(
                                dedx.detId(ih).rawId()).layer()
                            ladderPixelArray[ih] = ROOT.PXBDetId(
                                dedx.detId(ih).rawId()).ladder()
                            modulePixelArray[ih] = ROOT.PXBDetId(
                                dedx.detId(ih).rawId()).module()
                            sidePixelArray[ih] = -99
                            diskPixelArray[ih] = -99
                            bladePixelArray[ih] = -99
                            panelPixelArray[ih] = -99

                            #print " Barrel[", dedx.detId(ih).subdetId(), "]:: ", ROOT.PXBDetId( dedx.detId(ih).rawId() ).layer(), "   ",  ROOT.PXBDetId( dedx.detId(ih).rawId() ).ladder(), "   ",  ROOT.PXBDetId( dedx.detId(ih).rawId() ).module()
                        else:
                            # endcap
                            layerPixelArray[ih] = -99
                            ladderPixelArray[ih] = -99
                            modulePixelArray[ih] = ROOT.PXFDetId(
                                dedx.detId(ih).rawId()).module()
                            sidePixelArray[ih] = ROOT.PXFDetId(
                                dedx.detId(ih).rawId()).side()
                            diskPixelArray[ih] = ROOT.PXFDetId(
                                dedx.detId(ih).rawId()).disk()
                            bladePixelArray[ih] = ROOT.PXFDetId(
                                dedx.detId(ih).rawId()).blade()
                            panelPixelArray[ih] = ROOT.PXFDetId(
                                dedx.detId(ih).rawId()).panel()

                            #print " Endcap[", dedx.detId(ih).subdetId(), "]:: ", ROOT.PXFDetId( dedx.detId(ih).rawId() ).side(), "   ",  ROOT.PXFDetId( dedx.detId(ih).rawId() ).disk(), "   ",  ROOT.PXFDetId( dedx.detId(ih).rawId() ).blade(), "   ",  ROOT.PXFDetId( dedx.detId(ih).rawId() ).panel(), "   ",  ROOT.PXFDetId( dedx.detId(ih).rawId() ).module()

                    if stripCluster:
                        dedxArray[ih] = stripCluster.charge(
                        ) / dedx.pathlength(ih)
                        # convert number of electrons to MeV
                        dedxArray[ih] *= stripChargeToEnergyCoefficient
                    subDetIdArray[ih] = dedx.detId(ih).subdetId()

                t.myDeDx = mysum
            else:
                t.myDeDx = 0

            t.dedxByLayer = dedxArray
            t.subDetIdByLayer = subDetIdArray
            t.sizeXbyLayer = sizeXarray
            t.sizeYbyLayer = sizeYarray

            t.layerPixelByLayer = layerPixelArray
            t.ladderPixelByLayer = ladderPixelArray
            t.modulePixelByLayer = modulePixelArray
            t.sidePixelByLayer = sidePixelArray
            t.diskPixelByLayer = diskPixelArray
            t.bladePixelByLayer = bladePixelArray
            t.panelPixelByLayer = panelPixelArray

            # add a flag for bad ECAL channels in the way of the track
            t.channelsGoodECAL = 1
            for ie in t.crossedEcalStatus():
                if ie != 0: t.channelsGoodECAL = 0

            # add a flag for bad HCAL channels in the way of the track
            t.channelsGoodHCAL = 1
            for ih in t.crossedHcalStatus():
                if (ih & (1 << 5)) != 0: t.channelsGoodHCAL = 0

            # add to the list
            event.isoTracks.append(t)

        if len(event.isoTracks) == 0:
            return False
        self.counters.counter('events').inc('selected iso track')

        if self.cfg_comp.isMC:  # do MC matching
            event.genCharginos = [
                g for g in event.generatorSummary
                if abs(g.pdgId()) in (1000024, 1000037)
            ]
            for i, g in enumerate(event.genCharginos):
                g.index = i
                g.decayPoint = g.vertex()
                if g.numberOfDaughters() > 1:
                    for i in xrange(g.numberOfDaughters()):
                        dau = g.daughter(i)
                        if dau:
                            g.decayPoint = dau.vertex()
                            break
                #print "GEN pdgId %+8d pt %7.1f eta %+6.2f phi %+6.2f status %3d daughters %d decay R %5.1f, z %+5.1f" % (g.pdgId(), g.pt(), g.eta(), g.phi(), g.status(), g.numberOfDaughters(), g.decayPoint.R(), g.decayPoint.Z())
            match = matchObjectCollection3(event.isoTracks,
                                           event.genCharginos,
                                           deltaRMax=0.1)
            for t in event.isoTracks:
                t.mcMatch = match[t]
                #print "REC charge %+7d pt %7.1f eta %+6.2f phi %+6.2f" % (t.charge(), t.pt(), t.eta(), t.phi())
            #    for t in event.isoTracks:
            #        if deltaR(g,t) < 0.3:
            #            print " -> charge %+7d pt %7.1f eta %+6.2f phi %+6.2f   dr %.4f" % (t.charge(), t.pt(), t.eta(), t.phi(), deltaR(g,t))
            #print "\n"

            ## Now we add a generic match to charginos + prompt leptons + prompt taus + prompt photons
            anyMatchable = event.genCharginos[:]
            anyMatchable += [
                x for x in event.genParticles
                if abs(x.pdgId()) in (11, 13) and (x.isPromptFinalState(
                ) or x.isDirectPromptTauDecayProductFinalState())
            ]
            anyMatchable += [
                x for x in event.genParticles
                if abs(x.pdgId()) == 15 and x.isPromptDecayed() and x.pt() > 10
            ]
            anyMatchable += [
                x for x in event.genParticles
                if x.pdgId() == 22 and x.isPromptFinalState() and x.pt() > 20
            ]
            matchAny = matchObjectCollection3(event.isoTracks,
                                              anyMatchable,
                                              deltaRMax=0.2)
            for t in event.isoTracks:
                t.mcMatchAny = matchAny[t]

        # do any more event selection
        self.counters.counter('events').inc('accepted events')
        return True
    def process(self, event):
        self.readCollections(event.input)
        self.counters.counter('events').inc('all events')

        muons = []
        electrons = []
        for i, l in enumerate(event.selectedLeptons):
            l.index = i
            if abs(l.pdgId()) == 13: muons.append(l)
            if abs(l.pdgId()) == 11: electrons.append(l)

        for i, l in enumerate(event.selectedTaus):
            l.index = i

        for i, l in enumerate(event.cleanJets):
            l.index = i

        getDeDxRef = self.handles['dedx'].product().get
        if self.cfg_ana.doDeDx == "94XMiniAODv1-Hack":
            fixed = self.handles['dedx'].product().fixOffsets(-1)
            getDeDxRef = fixed.get

        event.isoTracks = []

        getVertexRef = self.handles['vertex'].product()

        vertex = None

        for v in getVertexRef:
            if (v.isFake() == 0 and v.ndof() > 4 and abs(v.z()) <= 24
                    and v.position().rho() < 2):
                vertex = v
                break

        if (vertex is None):
            print(
                "ERROR: no primary vertex passing all cuts was found for the event!"
            )
            event.vx = 999
            event.vy = 999
            event.vz = 999
        else:
            event.vx = vertex.x()
            event.vy = vertex.y()
            event.vz = vertex.z()

        pixelChargeToEnergyCoefficient = 3.61e-6
        stripChargeToEnergyCoefficient = 3.61e-6 * 265

        for t in event.preselIsoTracks:
            # add more variables
            t.leadAwayJet = leading(cleaned(t, event.cleanJets, 0.4))
            t.awayJetInfo = jetStats(cleaned(t, event.cleanJets, 0.4))
            t.leadAwayMu = leading(cleaned(t, muons, 0.4))
            t.leadAwayEle = leading(cleaned(t, electrons, 0.4))
            t.leadAwayTau = leading(cleaned(t, event.selectedTaus, 0.4))
            t.closestMu = closest(t, nearby(t, muons, 0.4))
            t.closestEle = closest(t, nearby(t, electrons, 0.4))
            t.closestTau = closest(t, nearby(t, event.selectedTaus, 0.4))

            t.dedxByHit = [0 for i in xrange(14)]
            t.deByHit = [0 for i in xrange(14)]
            t.dxByHit = [0 for i in xrange(14)]
            t.dedxUnSmearedByHit = [
                0 for i in xrange(14)
            ]  # unsmeared dedx. For MC the dedx is smeared according to data/mc discrepancy, but the unsmeared is kept for future use
            t.subDetIdByHit = [0 for i in xrange(14)]
            t.pixByHit = [0 for i in xrange(14)
                          ]  # 0 = strips, 1 = bpix, 2 = fpix
            t.layerOrSideByHit = [0 for i in xrange(14)]
            t.ladderOrBladeByHit = [0 for i in xrange(14)]
            t.diskByHit = [0 for i in xrange(14)]
            t.sideByHit = [0 for i in xrange(14)]
            t.moduleByHit = [0 for i in xrange(14)]
            t.sizeXbyHit = [0 for i in xrange(14)]
            t.sizeYbyHit = [0 for i in xrange(14)]

            # get dedx
            if self.cfg_ana.doDeDx:
                ref = getDeDxRef(t.index)
                if ref.isNull():
                    print "ERROR: no dE/dx for track of pt %.2f, eta %.2f" % (
                        t.pt(), t.eta())
                    continue
                dedx = ref.get()
                nhits = dedx.size()

                # this below is just dummy to give you a template
                mysum = 0

                for ih in xrange(min(nhits, len(t.dedxByHit))):
                    detid = dedx.detId(ih)
                    pixelCluster = dedx.pixelCluster(ih)
                    stripCluster = dedx.stripCluster(ih)
                    if pixelCluster:
                        t.dedxByHit[ih] = pixelCluster.charge(
                        ) / dedx.pathlength(ih)
                        # convert number of electrons to MeV
                        t.dedxByHit[ih] *= pixelChargeToEnergyCoefficient

                        t.deByHit[ih] = (pixelCluster.charge() *
                                         pixelChargeToEnergyCoefficient)
                        t.dxByHit[ih] = dedx.pathlength(ih)

                        t.sizeXbyHit[ih] = pixelCluster.sizeX()
                        t.sizeYbyHit[ih] = pixelCluster.sizeY()

                        # barrel
                        if detid.subdetId() == 1:
                            t.layerOrSideByHit[ih] = self.topology.layer(detid)
                            t.ladderOrBladeByHit[ih] = self.topology.pxbLadder(
                                detid)
                            t.pixByHit[ih] = 1

                        # endcap
                        if detid.subdetId() == 2:
                            t.layerOrSideByHit[ih] = self.topology.pxfDisk(
                                detid)
                            #t.layerOrSideByHit[ih] = 2*self.topology.side(detid)-3 # side is 2 for eta > 0, 1 for eta < 0 -> map to +1, -1
                            t.ladderOrBladeByHit[ih] = self.topology.pxfBlade(
                                detid)
                            t.diskByHit[ih] = self.topology.pxfDisk(detid)
                            t.sideByHit[ih] = 2 * self.topology.side(
                                detid
                            ) - 3  # side is 2 for eta > 0, 1 for eta < 0 -> map to +1, -1
                            t.pixByHit[ih] = 2
                        t.moduleByHit[ih] = self.topology.module(detid)

                        mysum += pixelCluster.charge()

                        #
                        #  https://github.com/cms-sw/cmssw/blob/master/DataFormats/TrackReco/interface/DeDxHitInfo.h
                        #
                        #  dEdX object DeDxHitInfoCollection
                        #
                        #
                        #  https://github.com/cms-sw/cmssw/blob/master/DataFormats/SiPixelDetId/interface/PXBDetId.h
                        #  https://github.com/cms-sw/cmssw/blob/master/DataFormats/SiPixelDetId/interface/PXFDetId.h
                        #

                    # strips
                    if stripCluster:
                        t.dedxByHit[ih] = stripCluster.charge(
                        ) / dedx.pathlength(ih)
                        # convert number of electrons to MeV
                        t.dedxByHit[ih] *= stripChargeToEnergyCoefficient
                        #t.sizeXbyHit[ih] = stripCluster.sizeX() --> 'SiStripCluster' object has no attribute 'sizeX'
                        t.layerOrSideByHit[ih] = self.topology.layer(detid)

                        t.deByHit[ih] = (stripCluster.charge() *
                                         stripChargeToEnergyCoefficient)
                        t.dxByHit[ih] = dedx.pathlength(ih)

                    t.subDetIdByHit[ih] = detid.subdetId()

                    # save unsmeared and smear (for MC) and the un-scaled (for Data)
                    t.dedxUnSmearedByHit[ih] = t.dedxByHit[ih]

                    if self.cfg_comp.isMC:  # if MC
                        if pixelCluster:  # if pixel
                            t.dedxByHit[ih] = smearDedx(
                                t.dedxByHit[ih], t.pixByHit[ih],
                                t.layerOrSideByHit[ih],
                                t.ladderOrBladeByHit[ih], abs(t.eta()))

                    #print " run = ", event.run
                    if not self.cfg_comp.isMC:  # if data
                        if self.cfg_ana.doCalibrateScaleDeDx:  # if scale activated
                            if pixelCluster:  # if pixel
                                t.dedxByHit[ih] = scaleDedx(
                                    t.dedxByHit[ih], t.pixByHit[ih],
                                    t.layerOrSideByHit[ih],
                                    t.ladderOrBladeByHit[ih], abs(t.eta()),
                                    event.run)

                t.myDeDx = mysum
            else:
                t.myDeDx = 0

            # add a flag for bad ECAL channels in the way of the track
            t.channelsGoodECAL = 1
            for ie in t.crossedEcalStatus():
                if ie != 0: t.channelsGoodECAL = 0

            # add a flag for bad HCAL channels in the way of the track
            t.channelsGoodHCAL = 1
            for ih in t.crossedHcalStatus():
                if (ih & (1 << 5)) != 0: t.channelsGoodHCAL = 0

            # add to the list
            event.isoTracks.append(t)

        if len(event.isoTracks) == 0:
            return False
        self.counters.counter('events').inc('selected iso track')

        if self.cfg_comp.isMC:  # do MC matching
            event.genCharginos = [
                g for g in event.generatorSummary
                if abs(g.pdgId()) in (1000024, 1000037)
            ]
            for i, g in enumerate(event.genCharginos):
                g.index = i
                g.decayPoint = g.vertex()
                if g.numberOfDaughters() > 1:
                    for i in xrange(g.numberOfDaughters()):
                        dau = g.daughter(i)
                        if dau:
                            g.decayPoint = dau.vertex()
                            break
                #print "GEN pdgId %+8d pt %7.1f eta %+6.2f phi %+6.2f status %3d daughters %d decay R %5.1f, z %+5.1f" % (g.pdgId(), g.pt(), g.eta(), g.phi(), g.status(), g.numberOfDaughters(), g.decayPoint.R(), g.decayPoint.Z())
            match = matchObjectCollection3(event.isoTracks,
                                           event.genCharginos,
                                           deltaRMax=0.1)
            for t in event.isoTracks:
                t.mcMatch = match[t]
                #print "REC charge %+7d pt %7.1f eta %+6.2f phi %+6.2f" % (t.charge(), t.pt(), t.eta(), t.phi())
            #    for t in event.isoTracks:
            #        if deltaR(g,t) < 0.3:
            #            print " -> charge %+7d pt %7.1f eta %+6.2f phi %+6.2f   dr %.4f" % (t.charge(), t.pt(), t.eta(), t.phi(), deltaR(g,t))
            #print "\n"

            ## Now we add a generic match to charginos + prompt leptons + prompt taus + prompt photons
            anyMatchable = event.genCharginos[:]
            anyMatchable += [
                x for x in event.genParticles
                if abs(x.pdgId()) in (11, 13) and (x.isPromptFinalState(
                ) or x.isDirectPromptTauDecayProductFinalState())
            ]
            anyMatchable += [
                x for x in event.genParticles
                if abs(x.pdgId()) == 15 and x.isPromptDecayed() and x.pt() > 10
            ]
            anyMatchable += [
                x for x in event.genParticles
                if x.pdgId() == 22 and x.isPromptFinalState() and x.pt() > 20
            ]
            matchAny = matchObjectCollection3(event.isoTracks,
                                              anyMatchable,
                                              deltaRMax=0.2)
            for t in event.isoTracks:
                t.mcMatchAny = matchAny[t]

        # do any more event selection
        self.counters.counter('events').inc('accepted events')
        return True
    def process(self, event):
        self.readCollections( event.input )
        self.counters.counter('events').inc('all events')

        muons = []
        electrons = []
        for i,l in enumerate(event.selectedLeptons):
            l.index = i
            if abs(l.pdgId()) == 13: muons.append(l)
            if abs(l.pdgId()) == 11: electrons.append(l)

        for i,l in enumerate(event.selectedTaus):
            l.index = i

        for i,l in enumerate(event.cleanJets):
            l.index = i

        getDeDxRef = self.handles['dedx'].product().get
        if self.cfg_ana.doDeDx == "94XMiniAODv1-Hack":
            fixed = self.handles['dedx'].product().fixOffsets(-1)
            getDeDxRef = fixed.get
        
        event.isoTracks = []
        for t in event.preselIsoTracks:
            # add more variables
            t.leadAwayJet = leading(cleaned(t,  event.cleanJets, 0.4))
            t.awayJetInfo = jetStats(cleaned(t, event.cleanJets, 0.4))
            t.leadAwayMu  = leading(cleaned(t, muons, 0.4))
            t.leadAwayEle = leading(cleaned(t, electrons, 0.4))
            t.leadAwayTau = leading(cleaned(t, event.selectedTaus, 0.4))
            t.closestMu   = closest(t, nearby(t, muons, 0.4))
            t.closestEle  = closest(t, nearby(t, electrons, 0.4))
            t.closestTau  = closest(t, nearby(t, event.selectedTaus, 0.4))
            # get dedx
            if self.cfg_ana.doDeDx:
                ref = getDeDxRef(t.index)
                if ref.isNull():
                    print "ERROR: no dE/dx for track of pt %.2f, eta %.2f" % (t.pt(),t.eta())
                    continue
                dedx = ref.get(); 
                nhits = dedx.size()
                # this below is just dummy to give you a template
                mysum = 0
                for ih in xrange(dedx.size()):
                    pxclust = dedx.pixelCluster(ih)
                    if not pxclust: continue
                    mysum += pxclust.charge()
                t.myDeDx = mysum
            else:
                t.myDeDx = 0
            # add to the list
            event.isoTracks.append(t)

        if len(event.isoTracks) == 0: 
            return False
        self.counters.counter('events').inc('selected iso track')

        if self.cfg_comp.isMC: # do MC matching
            event.genCharginos = [ g for g in event.generatorSummary if abs(g.pdgId()) in (1000024,1000037)]
            for i,g in enumerate(event.genCharginos):
                g.index = i
                g.decayPoint = g.vertex()
                if g.numberOfDaughters() > 1:
                    for i in xrange(g.numberOfDaughters()):
                        dau = g.daughter(i)
                        if dau: 
                            g.decayPoint = dau.vertex()
                            break
                #print "GEN pdgId %+8d pt %7.1f eta %+6.2f phi %+6.2f status %3d daughters %d decay R %5.1f, z %+5.1f" % (g.pdgId(), g.pt(), g.eta(), g.phi(), g.status(), g.numberOfDaughters(), g.decayPoint.R(), g.decayPoint.Z())
            match = matchObjectCollection3(event.isoTracks, event.genCharginos, deltaRMax = 0.1)
            for t in event.isoTracks:
                t.mcMatch = match[t]
                #print "REC charge %+7d pt %7.1f eta %+6.2f phi %+6.2f" % (t.charge(), t.pt(), t.eta(), t.phi())
            #    for t in event.isoTracks:
            #        if deltaR(g,t) < 0.3:
            #            print " -> charge %+7d pt %7.1f eta %+6.2f phi %+6.2f   dr %.4f" % (t.charge(), t.pt(), t.eta(), t.phi(), deltaR(g,t))
            #print "\n"

        # do any more event selection
        self.counters.counter('events').inc('accepted events')
        return True
Exemple #16
0
        for d in j.daus():
            if d.pt() < 1: continue
            ptsum += d.pt()
            print "        dau pt %7.2f  eta %+5.2f  phi %+5.2f  dr %.2f   id % +5d  ch %+1d  ptsum %7.2f" % (d.pt(), d.eta(), d.phi(), d.dr, d.pdgId(), d.charge(), ptsum) 
        print "   total pt from charged particles, pt > 1: %7.2f" % sum(d.pt() for d in j.daus() if d.charge() != 0 and d.pt() > 1)
        print "   total pt from photons          , pt > 1: %7.2f" % sum(d.pt() for d in j.daus() if d.charge() == 0 and d.pdgId() == 22 and d.pt() > 1)
        print "   total pt from neutrals (n, K0L), pt > 1: %7.2f" % sum(d.pt() for d in j.daus() if d.charge() == 0 and d.pdgId() in (130,2112,-2112) and d.pt() > 1)
        print "   total pt from short neut.(K0S) , pt > 1: %7.2f" % sum(d.pt() for d in j.daus() if d.charge() == 0 and d.pdgId() in (310,) and d.pt() > 1)
        print "   total pt from other neutrals   , pt > 1: %7.2f" % sum(d.pt() for d in j.daus() if d.charge() == 0 and d.pdgId() not in (22,130,2112,-2112,310) and d.pt() > 1)
        print ""
        
        c_tomatch = [g for g in j.daus() if g.charge() != 0 and g.pt() > 1]
        n_tomatch = [g for g in j.daus() if g.charge() == 0 and g.pt() > 1]
        a_tomatch = c_tomatch + n_tomatch

        tk2tk = matchObjectCollection3(events_new[key]["tracks"], events_ref[key]["tracks"], 0.07, lambda d,g: d.charge() == g.charge() and abs(d.pt()-g.pt())/(d.pt()+g.pt()) < 0.2)
        pf2pf = matchObjectCollection3(events_new[key]["pf"], events_ref[key]["pf"], 0.07, lambda d,g: abs(d.pt()-g.pt())/(d.pt()+g.pt()) < 0.6)
        pfb2pfb = matchObjectCollection3(events_new[key]["pfblock"], events_ref[key]["pfblock"], 0.07, lambda d,g: abs(d.pt()-g.pt())/(d.pt()+g.pt()) < 0.6)
        gsf2gsf = matchObjectCollection3(events_new[key]["gsfE"], events_ref[key]["gsfE"], 0.07, lambda d,g: abs(d.pt()-g.pt())/(d.pt()+g.pt()) < 0.6)
        #calt2calt = matchObjectCollection3(events_new[key]["caloT"], events_ref[key]["caloT"], 0.1)
        pf2tk_ref = matchObjectCollection3(events_ref[key]["pf"], events_ref[key]["tracks"], 0.07, lambda d,g: d.charge() == g.charge() and abs(d.pt()-g.pt())/(d.pt()+g.pt()) < 0.6)
        pf2tk_new = matchObjectCollection3(events_new[key]["pf"], events_new[key]["tracks"], 0.07, lambda d,g: d.charge() == g.charge() and abs(d.pt()-g.pt())/(d.pt()+g.pt()) < 0.6)
        pfb2tk_ref = matchObjectCollection(events_ref[key]["pfblock"], events_ref[key]["tracks"], 0.07, lambda d,g: d.charge() == g.charge() and abs(d.pt()-g.pt())/(d.pt()+g.pt()) < 0.6)
        pf2pfb_ref = matchObjectCollection(events_ref[key]["pf"], events_ref[key]["pfblock"], 0.07, lambda d,g: d.charge() == g.charge() and abs(d.pt()-g.pt())/(d.pt()+g.pt()) < 0.6)
        pfb2tk_new = matchObjectCollection(events_new[key]["pfblock"], events_new[key]["tracks"], 0.07, lambda d,g: d.charge() == g.charge() and abs(d.pt()-g.pt())/(d.pt()+g.pt()) < 0.6)
        pf2pfb_new = matchObjectCollection(events_new[key]["pf"], events_new[key]["pfblock"], 0.07, lambda d,g: d.charge() == g.charge() and abs(d.pt()-g.pt())/(d.pt()+g.pt()) < 0.6)
        mu2mu = matchObjectCollection3(events_new[key]["mu"], events_ref[key]["mu"], 0.07, lambda d,g: d.charge() == g.charge() and abs(d.pt()-g.pt())/(d.pt()+g.pt()) < 0.2)
        mu2tk_ref = matchObjectCollection3(events_ref[key]["mu"], events_ref[key]["tracks"], 0.07, lambda d,g: d.charge() == g.charge() and abs(d.pt()-g.pt())/(d.pt()+g.pt()) < 0.2)
        mu2tk_new = matchObjectCollection3(events_new[key]["mu"], events_new[key]["tracks"], 0.07, lambda d,g: d.charge() == g.charge() and abs(d.pt()-g.pt())/(d.pt()+g.pt()) < 0.2)
        layers = [
                ('tk_ref', events_ref[key]["tracks"], []),
Exemple #17
0
    tree.var(X,int)
jetvars = events_ref[common[0]][0].keys() 
for Y in jetvars:
    tree.var("r_"+Y)
    tree.var(""  +Y)
tree.var("deltaR")


goodevents = set()
print "%-14s     |  %8s   %8s   %8s   %7s  |  %7s  %7s    %7s  %7s    %7s  %7s    %7s  %7s    %7s  %7s" % ( 
        "event", "new pt", "ref pt", "gen pt", "gen eta",  "c had","ref", "n had","ref", "c em","ref", "n em","ref", "mu","ref")
for key in common:
    (run,lumi,event) = key
    jets_ref = events_ref[key]
    jets_new = events_new[key]
    matching = matchObjectCollection3(jets_ref, jets_new, 0.3, filter = lambda r,n : abs(r.val("gen")-n.val("gen"))<0.01)
    tree.fill("run", run)
    tree.fill("lumi", lumi)
    tree.fill("event", event)
    for jr in jets_ref:
        jm = matching[jr]
        if not jm: continue
        for v in jetvars:
            tree.fill("r_"+v,jr.val(v))
            tree.fill(v,jm.val(v))
        tree.fill("deltaR", deltaR(jr,jm))
        tree.tree.Fill()
        goodevents.add(key)
        newpt, refpt, genpt, gen_eta = jm.val("pt"), jr.val("pt"), jr.val("gen"), jr.val("gen_eta")
        toPrint = options.allprint
        if abs(newpt/refpt-1) > 0.2 and abs(refpt/genpt-1)<0.2 and abs(newpt/genpt-1)>2*abs(refpt/genpt-1): toPrint = True