예제 #1
0
    def process(self, event):
        self.readCollections(event.input)

        ## Read jets, if necessary recalibrate and shift MET
        #        allJets = map(Jet, self.handles['jets'].product())
        # Read in cleanJetsAK8 and access the subjets per AK8 jet
        allJets = getattr(event, self.cfg_ana.jets_in)

        ## Apply jet selection
        event.fatJets = []
        event.fatJetsSubJets = []

        for jet in allJets:
            event.fatJets.append(jet)
            ijet = Jet(jet)
            SubJets = ijet.subjets(self.cfg_ana.subjetCol)
            nSubJets = int(SubJets.size())
            jet.nSubJets = nSubJets
            if self.cfg_ana.jetVerbose:
                print "ijet.subjets('SDTag').size() : ", SubJets.size()
            for sj in SubJets:
                sj.parentJet = jet
                event.fatJetsSubJets.append(sj)
                if self.cfg_ana.jetVerbose:
                    print "ijet.subjets('SDTag').pt() : ", sj.pt()

        ## Associate jets to leptons
        leptons = event.inclusiveLeptons if hasattr(
            event, 'inclusiveLeptons') else event.selectedLeptons
        jlpairs = matchObjectCollection(leptons, allJets, self.jetLepDR**2)

        for jet in allJets:
            jet.leptons = [l for l in jlpairs if jlpairs[l] == jet]

        for lep in leptons:
            jet = jlpairs[lep]
            if jet is None:
                lep.fatjet = lep.jet
            else:
                lep.fatjet = jet
예제 #2
0
    def process(self, event):

        self.readCollections(event.input)
        miniaodjets = self.handles['jets'].product()

        allJets = []
        event.jets = []
        event.bJets = []
        event.cleanJets = []
        event.cleanBJets = []

        leptons = []
        if hasattr(event, 'selectedLeptons'):
            leptons = event.selectedLeptons

        genJets = None
        if self.cfg_comp.isMC:
            genJets = map(GenJet, self.mchandles['genJets'].product())

        for maodjet in miniaodjets:
            jet = Jet(maodjet)
            allJets.append(jet)
            if self.cfg_comp.isMC and hasattr(self.cfg_comp, 'jetScale'):
                scale = random.gauss(self.cfg_comp.jetScale,
                                     self.cfg_comp.jetSmear)
                jet.scaleEnergy(scale)
            if genJets:
                # Use DeltaR = 0.25 matching like JetMET
                pairs = matchObjectCollection([jet], genJets, 0.25 * 0.25)
                if pairs[jet] is None:
                    pass
                else:
                    jet.matchedGenJet = pairs[jet]
            #Add JER correction for MC jets. Requires gen-jet matching.
            if self.cfg_comp.isMC and hasattr(
                    self.cfg_ana, 'jerCorr') and self.cfg_ana.jerCorr:
                self.jerCorrection(jet)
            #Add JES correction for MC jets.
            if self.cfg_comp.isMC and hasattr(self.cfg_ana, 'jesCorr'):
                self.jesCorrection(jet, self.cfg_ana.jesCorr)
            if self.testJet(jet):
                event.jets.append(jet)
            if self.testBJet(jet):
                event.bJets.append(jet)

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

        event.cleanJets, dummy = cleanObjectCollection(event.jets,
                                                       masks=leptons,
                                                       deltaRMin=0.5)
        event.cleanBJets, dummy = cleanObjectCollection(event.bJets,
                                                        masks=leptons,
                                                        deltaRMin=0.5)

        pairs = matchObjectCollection(leptons, allJets, 0.5 * 0.5)
        # associating a jet to each lepton
        for lepton in leptons:
            jet = pairs[lepton]
            if jet is None:
                lepton.jet = lepton
            else:
                lepton.jet = jet

        # associating a leg to each clean jet
        invpairs = matchObjectCollection(event.cleanJets, leptons, 99999.)
        for jet in event.cleanJets:
            leg = invpairs[jet]
            jet.leg = leg

        for jet in event.cleanJets:
            jet.matchGenParton = 999.0

        if self.cfg_comp.isMC and "BB" in self.cfg_comp.name:
            genParticles = self.mchandles['genParticles'].product()
            event.genParticles = map(GenParticle, genParticles)
            for gen in genParticles:
                if abs(gen.pdgId()) == 5 and gen.mother() and abs(
                        gen.mother().pdgId()) == 21:
                    for jet in event.cleanJets:
                        dR = deltaR2(jet.eta(), jet.phi(), gen.eta(),
                                     gen.phi())
                        if dR < jet.matchGenParton:
                            jet.matchGenParton = dR

        event.jets30 = [jet for jet in event.jets if jet.pt() > 30]
        event.cleanJets30 = [jet for jet in event.cleanJets if jet.pt() > 30]
        if len(event.jets30) >= 2:
            self.counters.counter('jets').inc('at least 2 good jets')
        if len(event.cleanJets30) >= 2:
            self.counters.counter('jets').inc('at least 2 clean jets')
        if len(event.cleanBJets) > 0:
            self.counters.counter('jets').inc('at least 1 b jet')
            if len(event.cleanBJets) > 1:
                self.counters.counter('jets').inc('at least 2 b jets')
        return True
예제 #3
0
    def process(self, event):
        self.readCollections(event.input)
        rho = float(self.handles['rho'].product()[0])
        self.rho = rho

        ## Read jets, if necessary recalibrate and shift MET
        if self.cfg_ana.copyJetsByValue:
            import ROOT
            allJets = map(
                lambda j: Jet(ROOT.pat.Jet(j)), self.handles['jets'].product(
                ))  #copy-by-value is safe if JetAnalyzer is ran more than once
        else:
            allJets = map(Jet, self.handles['jets'].product())

        self.deltaMetFromJEC = [0., 0.]
        #        print "before. rho",self.rho,self.cfg_ana.collectionPostFix,'allJets len ',len(allJets),'pt', [j.pt() for j in allJets]
        if self.doJEC:
            #            print "\nCalibrating jets %s for lumi %d, event %d" % (self.cfg_ana.jetCol, event.lumi, event.eventId)
            self.jetReCalibrator.correctAll(allJets,
                                            rho,
                                            delta=self.shiftJEC,
                                            metShift=self.deltaMetFromJEC)
        self.allJetsUsedForMET = allJets
        #        print "after. rho",self.rho,self.cfg_ana.collectionPostFix,'allJets len ',len(allJets),'pt', [j.pt() for j in allJets]

        if self.cfg_comp.isMC:
            self.genJets = [x for x in self.handles['genJet'].product()]
            self.matchJets(event, allJets)
            if getattr(self.cfg_ana, 'smearJets', False):
                self.smearJets(event, allJets)

##Sort Jets by pT
        allJets.sort(key=lambda j: j.pt(), reverse=True)
        ## Apply jet selection
        self.jets = []
        self.jetsFailId = []
        self.jetsAllNoID = []
        self.jetsIdOnly = []
        for jet in allJets:
            if self.testJetNoID(jet):
                self.jetsAllNoID.append(jet)
                if self.testJetID(jet):

                    if (self.cfg_ana.doQG):
                        self.computeQGvars(jet)
                        jet.qgl = self.qglcalc.computeQGLikelihood(jet, rho)

                    self.jets.append(jet)
                    self.jetsIdOnly.append(jet)
                else:
                    self.jetsFailId.append(jet)
            elif self.testJetID(jet):
                self.jetsIdOnly.append(jet)

        ## Clean Jets from leptons
        leptons = []
        if hasattr(event, 'selectedLeptons'):
            leptons = [
                l for l in event.selectedLeptons
                if l.pt() > self.lepPtMin and self.lepSelCut(l)
            ]
        if self.cfg_ana.cleanJetsFromTaus and hasattr(event, 'selectedTaus'):
            leptons = leptons[:] + event.selectedTaus
        if self.cfg_ana.cleanJetsFromIsoTracks and hasattr(
                event, 'selectedIsoCleanTrack'):
            leptons = leptons[:] + event.selectedIsoCleanTrack
        self.cleanJetsAll, cleanLeptons = cleanJetsAndLeptons(
            self.jets, leptons, self.jetLepDR, self.jetLepArbitration)
        self.cleanJets = [
            j for j in self.cleanJetsAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]
        self.cleanJetsFwd = [
            j for j in self.cleanJetsAll
            if abs(j.eta()) >= self.cfg_ana.jetEtaCentral
        ]
        self.discardedJets = [
            j for j in self.jets if j not in self.cleanJetsAll
        ]
        if hasattr(event,
                   'selectedLeptons') and self.cfg_ana.cleanSelectedLeptons:
            event.discardedLeptons = [
                l for l in leptons if l not in cleanLeptons
            ]
            event.selectedLeptons = [
                l for l in event.selectedLeptons
                if l not in event.discardedLeptons
            ]

        ## Clean Jets from photons
        photons = []
        if hasattr(event, 'selectedPhotons'):
            if self.cfg_ana.cleanJetsFromFirstPhoton:
                photons = event.selectedPhotons[:1]
            else:
                photons = [g for g in event.selectedPhotons]

        self.gamma_cleanJetsAll = cleanNearestJetOnly(self.cleanJetsAll,
                                                      photons, self.jetGammaDR)
        self.gamma_cleanJets = [
            j for j in self.gamma_cleanJetsAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]
        self.gamma_cleanJetsFwd = [
            j for j in self.gamma_cleanJetsAll
            if abs(j.eta()) >= self.cfg_ana.jetEtaCentral
        ]
        ###

        ## Associate jets to leptons
        leptons = event.inclusiveLeptons if hasattr(
            event, 'inclusiveLeptons') else event.selectedLeptons
        jlpairs = matchObjectCollection(leptons, allJets, self.jetLepDR**2)

        for jet in allJets:
            jet.leptons = [l for l in jlpairs if jlpairs[l] == jet]

        for lep in leptons:
            jet = jlpairs[lep]
            if jet is None:
                lep.jet = lep
            else:
                lep.jet = jet
        ## Associate jets to taus
        taus = getattr(event, 'selectedTaus', [])
        jtaupairs = matchObjectCollection(taus, allJets, self.jetLepDR**2)

        for jet in allJets:
            jet.taus = [l for l in jtaupairs if jtaupairs[l] == jet]
        for tau in taus:
            tau.jet = jtaupairs[tau]

        #MC stuff
        if self.cfg_comp.isMC:
            self.deltaMetFromJetSmearing = [0, 0]
            for j in self.cleanJetsAll:
                if hasattr(j, 'deltaMetFromJetSmearing'):
                    self.deltaMetFromJetSmearing[
                        0] += j.deltaMetFromJetSmearing[0]
                    self.deltaMetFromJetSmearing[
                        1] += j.deltaMetFromJetSmearing[1]
            self.cleanGenJets = cleanNearestJetOnly(self.genJets, leptons,
                                                    self.jetLepDR)

            if self.cfg_ana.cleanGenJetsFromPhoton:
                self.cleanGenJets = cleanNearestJetOnly(
                    self.cleanGenJets, photons, self.jetLepDR)

            #event.nGenJets25 = 0
            #event.nGenJets25Cen = 0
            #event.nGenJets25Fwd = 0
            #for j in event.cleanGenJets:
            #    event.nGenJets25 += 1
            #    if abs(j.eta()) <= 2.4: event.nGenJets25Cen += 1
            #    else:                   event.nGenJets25Fwd += 1

            self.jetFlavour(event)

        setattr(event, "rho" + self.cfg_ana.collectionPostFix, self.rho)
        setattr(event, "deltaMetFromJEC" + self.cfg_ana.collectionPostFix,
                self.deltaMetFromJEC)
        setattr(event,
                "deltaMetFromJetSmearing" + self.cfg_ana.collectionPostFix,
                self.deltaMetFromJetSmearing)
        setattr(event, "allJetsUsedForMET" + self.cfg_ana.collectionPostFix,
                self.allJetsUsedForMET)
        setattr(event, "genJets" + self.cfg_ana.collectionPostFix,
                self.genJets)
        setattr(event, "cleanGenJets" + self.cfg_ana.collectionPostFix,
                self.cleanGenJets)
        setattr(event, "jets" + self.cfg_ana.collectionPostFix, self.jets)
        setattr(event, "jetsFailId" + self.cfg_ana.collectionPostFix,
                self.jetsFailId)
        setattr(event, "jetsAllNoID" + self.cfg_ana.collectionPostFix,
                self.jetsAllNoID)
        setattr(event, "jetsIdOnly" + self.cfg_ana.collectionPostFix,
                self.jetsIdOnly)
        setattr(event, "cleanJetsAll" + self.cfg_ana.collectionPostFix,
                self.cleanJetsAll)
        setattr(event, "cleanJets" + self.cfg_ana.collectionPostFix,
                self.cleanJets)
        setattr(event, "cleanJetsFwd" + self.cfg_ana.collectionPostFix,
                self.cleanJetsFwd)
        setattr(event, "discardedJets" + self.cfg_ana.collectionPostFix,
                self.discardedJets)
        setattr(event, "gamma_cleanJetsAll" + self.cfg_ana.collectionPostFix,
                self.gamma_cleanJetsAll)
        setattr(event, "gamma_cleanJets" + self.cfg_ana.collectionPostFix,
                self.gamma_cleanJets)
        setattr(event, "gamma_cleanJetsFwd" + self.cfg_ana.collectionPostFix,
                self.gamma_cleanJetsFwd)
        setattr(event, "bqObjects" + self.cfg_ana.collectionPostFix,
                self.bqObjects)
        setattr(event, "cqObjects" + self.cfg_ana.collectionPostFix,
                self.cqObjects)
        setattr(event, "partons" + self.cfg_ana.collectionPostFix,
                self.partons)
        setattr(event, "heaviestQCDFlavour" + self.cfg_ana.collectionPostFix,
                self.heaviestQCDFlavour)

        return True
예제 #4
0
    def process(self, event):
        


        run = event.input.eventAuxiliary().id().run()
        lumi = event.input.eventAuxiliary().id().luminosityBlock()
        eventId = event.input.eventAuxiliary().id().event()
        
        self.readCollections( event.input )
        
        # Will need who for jet calibration later
        rho =  self.handles["rho"].product()[0]

        ######## 
        # AK8 Jets from MiniAOD + Subjet btags
        ########

        setattr(event, "ak08", map(PhysicsObject, self.handles["ak08"].product()))

        setattr(event, "ak0softdropsubjets", map(PhysicsObject, self.handles["ak08softdropsubjets"].product()))

        # bb-tag Output
        newtags =  self.handles['ak08bbtag'].product()

        # Loop over jets                        
        for ij, jet in enumerate(getattr(event, "ak08")):

            # Fill bb-tag
            for i in xrange(len(newtags)) :
                if jet.physObj == newtags.key(i).get():
                    jet.bbtag = newtags.value(i)


            # bb-tag Inputs
            muonTagInfos = self.handles['ak08muonTagInfos'].product()[ij]
            elecTagInfos = self.handles['ak08elecTagInfos'].product()[ij]
            ipTagInfo    = self.handles['ak08ipTagInfos'].product()[ij]
            svTagInfo    = self.handles['ak08svTagInfos'].product()[ij]

            calcBBTagVariables(jet, 
                               muonTagInfos, 
                               elecTagInfos, 
                               ipTagInfo, 
                               svTagInfo,
                               njettiness_08,
                               maxSVDeltaRToJet = 0.7,)

        # end of loop over jets



        ######## 
        # Ungroomed Fatjets + NSubjettiness + Hbb Tagging
        ########

        for prefix in ["ca15"]:

            if self.skip_ca15 and ("ca15" in prefix):
                continue

            # N-Subjettiness
            tau1 = self.handles[prefix+'tau1'].product()
            tau2 = self.handles[prefix+'tau2'].product()
            tau3 = self.handles[prefix+'tau3'].product()

            # bb-tag Output
            newtags =  self.handles[prefix+'bbtag'].product()
                
            # Four Vector
            setattr(event, prefix+"ungroomed", map(PhysicsObject, self.handles[prefix+'ungroomed'].product()))

            # Loop over jets                        
            for ij, jet in enumerate(getattr(event, prefix+"ungroomed")):

                # Fill N-Subjettiness
                jet.tau1 = tau1.get(ij)
                jet.tau2 = tau2.get(ij)
                jet.tau3 = tau3.get(ij)

                # Fill bb-tag
                for i in xrange(len(newtags)) :
                    if jet.physObj == newtags.key(i).get():
                        jet.bbtag = newtags.value(i)

                # bb-tag Inputs
                muonTagInfos = self.handles['ca15muonTagInfos'].product()[ij]
                elecTagInfos = self.handles['ca15elecTagInfos'].product()[ij]
                ipTagInfo    = self.handles['ca15ipTagInfos'].product()[ij]
                svTagInfo    = self.handles['ca15svTagInfos'].product()[ij]

                calcBBTagVariables(jet, 
                                   muonTagInfos, 
                                   elecTagInfos, 
                                   ipTagInfo, 
                                   svTagInfo,
                                   njettiness_15,
                                   maxSVDeltaRToJet = 1.3)
                                    
            # end of loop over jets

        ######## 
        # Softdrop Fatjets + NSubjettiness
        ########

        for fj_name in ["ca15softdropz2b1"]:

            if self.skip_ca15 and ("ca15" in fj_name):
                continue
                
            # Set the four-vector
            setattr(event, fj_name, map(PhysicsObject, self.handles[fj_name].product()))

            # N-Subjettiness
            tau1 = self.handles[fj_name+'tau1'].product()
            tau2 = self.handles[fj_name+'tau2'].product()
            tau3 = self.handles[fj_name+'tau3'].product()

            # Loop over jets                        
            for ij, jet in enumerate(getattr(event, fj_name)):

                # Fill N-Subjettiness
                jet.tau1 = tau1.get(ij)
                jet.tau2 = tau2.get(ij)
                jet.tau3 = tau3.get(ij)
                                    
            # end of loop over jets



                                                                
        ######## 
        # Groomed Uncalibrated Fatjets
        ########

        for fj_name in ['ak08pruned', 'ca15trimmed', 'ca15softdrop', 'ca15pruned']:           
            if self.skip_ca15 and ("ca15" in fj_name):
                continue
            
            setattr(event, fj_name, map(PhysicsObject, self.handles[fj_name].product()))


        ######## 
        # Groomed Fatjets to calibrate
        ########

        pruned_cal_jets = []

        for groomed_fj in self.handles['ak08pruned'].product():                        

            # We need the closest ungroomed fatjet to get the JEC:            
            # - Make a list of pairs: deltaR(ungroomed fj, groomed fj) for all ungroomed fatjets
            # - Sort by deltaR
            # - And take the minimum
            
            if len(getattr(event, "ak08")):
                closest_ung_fj_and_dr = sorted(
                    [(ung_fj, deltaR2(ung_fj, groomed_fj)) for ung_fj in getattr(event, "ak08")], 
                    key=lambda x:x[1])[0]
            else:
                print "WARNING: No ungroomed fatjets found in event with groomed fatjet. Skipping"
                continue

            # Use the jet cone size for matching
            minimal_dr_groomed_ungroomed = 0.8
            if closest_ung_fj_and_dr[1] > minimal_dr_groomed_ungroomed:
                print "WARNING: No ungroomed fatjet found close to groomed fatjet. Skipping"
                continue

            ungroomed_jet = Jet(closest_ung_fj_and_dr[0])        
            c = self.jetReCalibrator.getCorrection(ungroomed_jet, rho)
                        
            # Need to do a deep-copy. Otherwise the original jet will be modified
            cal_groomed_fj = PhysicsObject(groomed_fj).__copy__() 
            cal_groomed_fj.scaleEnergy(c)
            
            pruned_cal_jets.append(cal_groomed_fj)

        setattr(event, 'ak08prunedcal', pruned_cal_jets)

        ########
        #  AK08 Regression
        #######
        self.regressionsAK08[0].evaluateRegressionAK08(event)
        
 
        ######## 
        # Subjets 
        ########
        
        for fj_name in ['ak08pruned','ca15pruned']:

            if self.skip_ca15 and ("ca15" in fj_name):
                continue

            setattr(event, fj_name + "subjets", map(PhysicsObject, self.handles[fj_name+"subjets"].product()))
            
            newtags =  self.handles[fj_name+'subjetbtag'].product()
            for i in xrange(0,len(newtags)) :
                for j in getattr(event, fj_name+"subjets"):
                    if  j.physObj == newtags.key(i).get():
                        j.btag = newtags.value(i)


        ######## 
        # HEPTopTagger
        ########

        if not self.skip_ca15:
            candJets = self.handles['httCandJets'].product()
            candInfos = self.handles['httCandInfos'].product()

            event.httCandidates = map(PhysicsObject, candJets) 
            sjbtags = self.handles['httSubjetBtags'].product()

            for i in xrange(0, len(candJets)):            

                event.httCandidates[i].fRec = candInfos[i].properties().fRec
                event.httCandidates[i].Ropt = candInfos[i].properties().Ropt
                event.httCandidates[i].RoptCalc = candInfos[i].properties().RoptCalc
                event.httCandidates[i].ptForRoptCalc = candInfos[i].properties().ptForRoptCalc

                # HTT return the subjet-pair closest to the W-mass as W-subjets
                # Could be improved by b-tagging if we run into a problem

                [sj_w1, sj_w2, sj_nonw] = [con.__deref__() for con in candJets[i].getJetConstituents() if not con.isNull()]
            
                event.httCandidates[i].sjW1pt   = sj_w1.pt()
                event.httCandidates[i].sjW1eta  = sj_w1.eta()
                event.httCandidates[i].sjW1phi  = sj_w1.phi()
                event.httCandidates[i].sjW1mass = sj_w1.mass()

                # Get the correct b-tag
                for ib in xrange(0, len(sjbtags)) :
                    if  sj_w1 == sjbtags.key(ib).get():
                        event.httCandidates[i].sjW1btag = sjbtags.value(ib)


                event.httCandidates[i].sjW2pt   = sj_w2.pt()  
                event.httCandidates[i].sjW2eta  = sj_w2.eta() 
                event.httCandidates[i].sjW2phi  = sj_w2.phi() 
                event.httCandidates[i].sjW2mass = sj_w2.mass()


                # Get the correct b-tag
                for ib in xrange(0, len(sjbtags)) :
                    if  sj_w2 == sjbtags.key(ib).get():
                        event.httCandidates[i].sjW2btag = sjbtags.value(ib)

                event.httCandidates[i].sjNonWpt   = sj_nonw.pt()  
                event.httCandidates[i].sjNonWeta  = sj_nonw.eta() 
                event.httCandidates[i].sjNonWphi  = sj_nonw.phi() 
                event.httCandidates[i].sjNonWmass = sj_nonw.mass()

                # Get the correct b-tag
                for ib in xrange(0, len(sjbtags)) :
                    if  sj_nonw == sjbtags.key(ib).get():
                        event.httCandidates[i].sjNonWbtag = sjbtags.value(ib)

        return True
    def evaluateRegressionAK08(self, event):
#self.readCollections( event.input )
        reg_fj = []
        for ung_fj in getattr(event, "ak08"):         

            # We need the closest ungroomed fatjet to get the JEC:                                                                                                                                              # - Make a list of pairs: deltaR(ungroomed fj, groomed fj) for all ungroomed fatjets                                                                                                                # - Sort by deltaR                                                                                                                                                                                  # - And take the minimum            
            if len(getattr(event, "ak08pruned")):
                closest_pr_fj_and_dr = sorted( [(pr_fj, deltaR2(ung_fj, pr_fj)) for pr_fj in getattr(event, "ak08pruned")],  key=lambda x:x[1])[0] 
            else:
                print "WARNING: No pruned fatjets found in event with ungroomed fatjet. Skipping"
                continue

            # Use the jet cone size for matching                                                                                                                                                    
            minimal_dr_groomed_ungroomed = 0.8
            if closest_pr_fj_and_dr[1] > minimal_dr_groomed_ungroomed:
                print "WARNING: No pruned fatjet found close to ungroomed fatjet. Skipping"
                continue
            
            pr_jet = Jet(closest_pr_fj_and_dr[0])
            
            if len(getattr(event, "ak08prunedcal")):
                closest_cal_fj_and_dr = sorted( [(cal_fj, deltaR2(ung_fj, cal_fj)) for cal_fj in getattr(event, "ak08prunedcal")],  key=lambda x:x[1])[0] 
            else:
                print "WARNING: No calib groomed fatjets found in event with ungroomed fatjet. Skipping"
                continue

            if closest_cal_fj_and_dr[1] > minimal_dr_groomed_ungroomed:
                print "WARNING: No calib fatjet found close to ungroomed fatjet. Skipping"
                continue


            cal_jet = Jet(closest_cal_fj_and_dr[0])

            # now check the AK08 jet is not a lepton  
#            if len(getattr(event, "selectedLeptons")):
#                closest_pr_lep_and_dr = sorted( [(lep, deltaR2(cal_jet,lep)) for lep in getattr(event, "vLeptons")],  key=lambda x:x[1])[0]
#            if closest_pr_lep_and_dr[1] < (0.4 * 0.4):
#              print "WARNING: No groomed fatjet is overlapping with a vLepton. Skipping"
#              continue

            # Need to do a deep-copy. Otherwise the original jet will be modified                                                                                                                   
            reg_groomed_fj = PhysicsObject(closest_cal_fj_and_dr[0]).__copy__()
#        for j in event.FatjetAK08pruned:

            self.FatjetAK08ungroomed_pt[0] = ung_fj.pt()
#            print 'ung_fj.pt() ', ung_fj.pt()
            self.FatjetAK08pruned_pt[0] = pr_jet.pt()
#            print 'pr_jet.pt() ',  pr_jet.pt()
            self.FatjetAK08prunedCal_pt[0] = cal_jet.pt()
#            print 'cal_jet.pt() ', cal_jet.pt()
            self.FatjetAK08prunedCal_eta[0] = cal_jet.eta()
            self.FatjetAK08ungroomed_vertexNTracks[0] = ung_fj.vertexNTracks
            self.FatjetAK08ungroomed_SV_mass_0[0] = ung_fj.SV_mass_0
            self.FatjetAK08ungroomed_SV_EnergyRatio_0[0] = ung_fj.SV_EnergyRatio_0
            self.FatjetAK08ungroomed_SV_EnergyRatio_1[0] = ung_fj.SV_EnergyRatio_1
            self.FatjetAK08ungroomed_PFLepton_ptrel[0] = ung_fj.PFLepton_ptrel
            self.FatjetAK08ungroomed_nSL[0] = ung_fj.nSL
#            print 'ung_fj.nSL ', ung_fj.nSL

            reg_groomed_fj.scaleEnergy(self.reader.EvaluateRegression(self.name)[0])


            reg_fj.append(reg_groomed_fj)
#            print 'reg_groomed_fj.pt() ', reg_groomed_fj.pt()
  
        
        setattr(event, 'ak08prunedreg',  reg_fj )
예제 #6
0
파일: JetAnalyzer.py 프로젝트: smdogra/mTop
    def process(self, event):

        self.readCollections(event.input)
        miniaodjets = self.handles['jets'].product()

        allJets = []
        event.jets = []
        event.bJets = []
        event.cleanJets = []
        event.cleanBJets = []

        leptons = []
        if hasattr(event, 'selectedLeptons'):
            leptons = event.selectedLeptons
        if hasattr(self.cfg_ana, 'toClean'):
            leptons = getattr(event, self.cfg_ana.toClean)

        if hasattr(self.cfg_ana, 'leptonCollections'):
            for coll in self.cfg_ana.leptonCollections:
                leptons += self.handles[coll].product()

        genJets = None
        if self.cfg_comp.isMC:
            genJets = map(GenJet, self.mchandles['genJets'].product())

        allJets = [Jet(jet) for jet in miniaodjets]

        if self.recalibrateJets:
            self.jetReCalibrator.correctAll(allJets,
                                            event.rho,
                                            delta=0.,
                                            addCorr=True,
                                            addShifts=True)

        for jet in allJets:
            if genJets:
                # Use DeltaR = 0.25 matching like JetMET
                pairs = matchObjectCollection([jet], genJets, 0.25 * 0.25)
                if pairs[jet] is None:
                    pass
                else:
                    jet.matchedGenJet = pairs[jet]
            # Add JER correction for MC jets. Requires gen-jet matching.
            if self.cfg_comp.isMC and hasattr(
                    self.cfg_ana, 'jerCorr') and self.cfg_ana.jerCorr:
                self.jerCorrection(jet)
            # Add JES correction for MC jets.
            if self.cfg_comp.isMC and hasattr(self.cfg_ana, 'jesCorr'):
                self.jesCorrection(jet, self.cfg_ana.jesCorr)
            if self.testJet(jet):
                event.jets.append(jet)
            if self.testBJet(jet):
                event.bJets.append(jet)

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

        event.cleanJets, dummy = cleanObjectCollection(event.jets,
                                                       masks=leptons,
                                                       deltaRMin=0.5)
        event.cleanBJets, dummy = cleanObjectCollection(event.bJets,
                                                        masks=leptons,
                                                        deltaRMin=0.5)

        # Attach matched jets to selected + other leptons
        if hasattr(event, 'otherLeptons'):
            leptons += event.otherLeptons

        pairs = matchObjectCollection(leptons, allJets, 0.5 * 0.5)
        # associating a jet to each lepton
        for lepton in leptons:
            jet = pairs[lepton]
            if jet is None:
                lepton.jet = lepton
            else:
                lepton.jet = jet

        # associating a leg to each clean jet
        invpairs = matchObjectCollection(event.cleanJets, leptons, 99999.)
        for jet in event.cleanJets:
            leg = invpairs[jet]
            jet.leg = leg

        for jet in event.cleanJets:
            jet.matchGenParton = 999.0

        event.jets30 = [jet for jet in event.jets if jet.pt() > 30]
        event.cleanJets30 = [jet for jet in event.cleanJets if jet.pt() > 30]
        if len(event.jets30) >= 2:
            self.counters.counter('jets').inc('at least 2 good jets')
        if len(event.cleanJets30) >= 2:
            self.counters.counter('jets').inc('at least 2 clean jets')
        if len(event.cleanBJets) > 0:
            self.counters.counter('jets').inc('at least 1 b jet')
            if len(event.cleanBJets) > 1:
                self.counters.counter('jets').inc('at least 2 b jets')

        # save HTs
        event.HT_allJets = sum([jet.pt() for jet in allJets])
        event.HT_jets = sum([jet.pt() for jet in event.jets])
        event.HT_bJets = sum([jet.pt() for jet in event.bJets])
        event.HT_cleanJets = sum([jet.pt() for jet in event.cleanJets])
        event.HT_jets30 = sum([jet.pt() for jet in event.jets30])
        event.HT_cleanJets30 = sum([jet.pt() for jet in event.cleanJets30])

        return True
예제 #7
0
    def process(self, event):
        self.readCollections(event.input)

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

        # all jets
        miniaodjets = [Jet(jet) for jet in self.handles['jets'].product()]

        # attach qscale (pt hat) to the event
        event.qscale = self.mchandles['genInfo'].product().qScale()
        
        # filter events where the pt hat of a PU vertex is higher than that of the hard scattering
        if getattr(self.cfg_ana, 'filterPU', True):
            if len(event.pileUpVertex_ptHat)>0:
                if max(event.pileUpVertex_ptHat) > event.qscale and 'QCD' in self.cfg_comp.name:
                    return False
            self.counters.counter('L1Gen').inc('no PU vertex has pt hat higher than qsquare')

        # 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]
         
        # HOOK RM
        event.pruned_gen_particles = pruned_gen_particles
        event.packed_gen_particles = packed_gen_particles
        event.all_gen_particles    = all_gen_particles
         
        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_dmesons         = [pp for pp in pruned_gen_particles if abs(pp.pdgId()) > 400  and abs(pp.pdgId()) < 500  and pp.isPromptDecayed()]
        event.gen_bbarions        = [pp for pp in pruned_gen_particles if abs(pp.pdgId()) > 5000 and abs(pp.pdgId()) < 6000 and pp.isPromptDecayed()]
        event.gen_cbarions        = [pp for pp in pruned_gen_particles if abs(pp.pdgId()) > 4000 and abs(pp.pdgId()) < 5000 and pp.isPromptDecayed()]
        event.gen_prompt_jpsis    = [pp for pp in pruned_gen_particles if abs(pp.pdgId()) in [443, 100443, 30443, 9000443, 9010443, 9020443] and pp.isPromptDecayed()]
        event.gen_prompt_upsilons = [pp for pp in pruned_gen_particles if abs(pp.pdgId()) in [553, 100553, 200553, 300553] and pp.isPromptDecayed()]
        event.gen_vbosons         = event.genVBosons
        event.gen_topquarks       = event.gentopquarks

#         if len(event.gen_vbosons) and len(event.gen_dmesons):
#             import pdb ; pdb.set_trace()

        # is this double parton scattering, WOW!
        # https://indico.cern.ch/event/629232/contributions/2807337/attachments/1579753/2495883/Epiphany2018-Maciula.pdf
        # https://indico.cern.ch/event/75247/contributions/1246824/attachments/1048811/1495114/jackson.pdf
#         if len(event.gen_bmesons) and len(event.gen_dmesons):
#             import pdb ; pdb.set_trace()
            
        # walk down the lineage of the B mesons and find the final state muons and charged particles
        for ip in event.gen_bmesons + event.gen_dmesons + event.gen_prompt_jpsis + event.gen_prompt_upsilons + event.gen_vbosons + event.gen_topquarks + event.gen_cbarions + event.gen_bbarions:
            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'
            finaldaus    = []
            finalmuons   = []
            finalcharged = []
            for ipp in packed_gen_particles:
                mother = ipp.mother(0)
                if mother and self.isAncestor(ip, mother):
                    finaldaus.append(ipp)
                    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())
            ip.finaldaughters        = sorted(finaldaus   , key = lambda x : x.pt(), reverse = True)
            ip.finalmuondaughters    = sorted(finalmuons  , key = lambda x : x.pt(), reverse = True)
            ip.finalchargeddaughters = sorted(finalcharged, key = lambda x : x.pt(), reverse = True)

        # 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

        # append a reco jet (if it exists) to each L1 muon
        for mu in event.L1_muons:
            jets = sorted([jj for jj in event.jets if deltaR2(jj.eta(), jj.phi(), mu.etaAtVtx(), mu.phiAtVtx()) < 0.16], key = lambda x : deltaR2(x, mu))
            if len(jets):
                mu.jet = jets[0]

        return True
예제 #8
0
    def process(self, event):
        self.readCollections(event.input)
        rho = float(self.handles['rho'].product()[0])
        self.rho = rho

        ## Read jets, if necessary recalibrate and shift MET
        if self.cfg_ana.copyJetsByValue:
            import ROOT
            allJets = map(
                lambda j: Jet(
                    ROOT.pat.Jet(
                        ROOT.edm.Ptr(ROOT.pat.Jet)
                        (ROOT.edm.ProductID(), j, 0))),
                self.handles['jets'].product(
                ))  #copy-by-value is safe if JetAnalyzer is ran more than once
        else:
            allJets = map(Jet, self.handles['jets'].product())

        self.deltaMetFromJEC = [0., 0.]
        self.type1METCorr = [0., 0., 0.]
        #        print "before. rho",self.rho,self.cfg_ana.collectionPostFix,'allJets len ',len(allJets),'pt', [j.pt() for j in allJets]
        if self.doJEC:
            if not self.recalibrateJets:  # check point that things won't change
                jetsBefore = [(j.pt(), j.eta(), j.phi(), j.rawFactor())
                              for j in allJets]
            self.jetReCalibrator.correctAll(allJets,
                                            rho,
                                            delta=self.shiftJEC,
                                            addCorr=True,
                                            addShifts=self.addJECShifts,
                                            metShift=self.deltaMetFromJEC,
                                            type1METCorr=self.type1METCorr)
            if not self.recalibrateJets:
                jetsAfter = [(j.pt(), j.eta(), j.phi(), j.rawFactor())
                             for j in allJets]
                if len(jetsBefore) != len(jetsAfter):
                    print "ERROR: I had to recompute jet corrections, and they rejected some of the jets:\nold = %s\n new = %s\n" % (
                        jetsBefore, jetsAfter)
                else:
                    for (told, tnew) in zip(jetsBefore, jetsAfter):
                        if (deltaR2(told[1], told[2], tnew[1],
                                    tnew[2])) > 0.0001:
                            print "ERROR: I had to recompute jet corrections, and one jet direction moved: old = %s, new = %s\n" % (
                                told, tnew)
                        elif abs(told[0] - tnew[0]) / (
                                told[0] + tnew[0]) > 0.5e-3 or abs(
                                    told[3] - tnew[3]) > 0.5e-3:
                            print "ERROR: I had to recompute jet corrections, and one jet pt or corr changed: old = %s, new = %s\n" % (
                                told, tnew)
        self.allJetsUsedForMET = allJets
        #        print "after. rho",self.rho,self.cfg_ana.collectionPostFix,'allJets len ',len(allJets),'pt', [j.pt() for j in allJets]

        if self.cfg_comp.isMC:
            self.genJets = [x for x in self.handles['genJet'].product()]
            if self.cfg_ana.do_mc_match:
                for igj, gj in enumerate(self.genJets):
                    gj.index = igj
                self.matchJets(event, allJets)
            if getattr(self.cfg_ana, 'smearJets', False):
                self.smearJets(event, allJets)

##Sort Jets by pT
        allJets.sort(key=lambda j: j.pt(), reverse=True)

        ## Apply jet selection
        self.jets = []
        self.jetsFailId = []
        self.jetsAllNoID = []
        self.jetsIdOnly = []
        for jet in allJets:
            if self.testJetNoID(jet):
                self.jetsAllNoID.append(jet)
                # temporary fix since the jetID it's not good for eta>3
                if self.testJetID(jet):
                    if (self.cfg_ana.doQG):
                        jet.qgl_calc = self.qglcalc.computeQGLikelihood
                        jet.qgl_rho = rho

                    self.jets.append(jet)
                    self.jetsIdOnly.append(jet)
                else:
                    self.jetsFailId.append(jet)
            elif self.testJetID(jet):
                self.jetsIdOnly.append(jet)

        ## Clean Jets from leptons
        leptons = []
        if hasattr(event, 'selectedLeptons'):
            leptons = [
                l for l in event.selectedLeptons
                if l.pt() > self.lepPtMin and self.lepSelCut(l)
            ]
        if self.cfg_ana.cleanJetsFromTaus and hasattr(event, 'selectedTaus'):
            leptons = leptons[:] + event.selectedTaus
        if self.cfg_ana.cleanJetsFromIsoTracks and hasattr(
                event, 'selectedIsoCleanTrack'):
            leptons = leptons[:] + event.selectedIsoCleanTrack

        jetsEtaCut = [
            j for j in self.jets if abs(j.eta()) < self.cfg_ana.jetEta
        ]
        self.cleanJetsAll, cleanLeptons = cleanJetsAndLeptons(
            jetsEtaCut, leptons, self.jetLepDR, self.jetLepArbitration)
        #self.cleanJetsAll, cleanLeptons = cleanJetsAndLeptons(self.jets, leptons, self.jetLepDR, self.jetLepArbitration) ##from central
        self.cleanJets = [
            j for j in self.cleanJetsAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]
        self.cleanJetsFwd = [
            j for j in self.cleanJetsAll
            if abs(j.eta()) >= self.cfg_ana.jetEtaCentral
        ]
        self.discardedJets = [
            j for j in self.jets if j not in self.cleanJetsAll
        ]
        if hasattr(event,
                   'selectedLeptons') and self.cfg_ana.cleanSelectedLeptons:
            event.discardedLeptons = [
                l for l in leptons if l not in cleanLeptons
            ]
            event.selectedLeptons = [
                l for l in event.selectedLeptons
                if l not in event.discardedLeptons
            ]

        ## First cleaning, then Jet Id
        noIdJetsEtaCut = [
            j for j in self.jetsAllNoID if abs(j.eta()) < self.cfg_ana.jetEta
        ]
        self.noIdCleanJetsAll, cleanLeptons = cleanJetsAndLeptons(
            noIdJetsEtaCut, leptons, self.jetLepDR, self.jetLepArbitration)
        self.noIdCleanJets = [
            j for j in self.noIdCleanJetsAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]
        self.noIdCleanJetsFwd = [
            j for j in self.noIdCleanJetsAll
            if abs(j.eta()) >= self.cfg_ana.jetEtaCentral
        ]
        self.noIdDiscardedJets = [
            j for j in self.jets if j not in self.noIdCleanJetsAll
        ]

        ## Clean Jets from photons (first cleaning, then Jet Id)
        photons = []
        if hasattr(event, 'selectedPhotons'):
            if self.cfg_ana.cleanJetsFromFirstPhoton:
                photons = event.selectedPhotons[:1]
            else:
                photons = [g for g in event.selectedPhotons]

        self.gamma_cleanJetsAll = cleanNearestJetOnly(self.cleanJetsAll,
                                                      photons, self.jetGammaDR)
        self.gamma_cleanJets = [
            j for j in self.gamma_cleanJetsAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]
        self.gamma_cleanJetsFwd = [
            j for j in self.gamma_cleanJetsAll
            if abs(j.eta()) >= self.cfg_ana.jetEtaCentral
        ]
        self.gamma_noIdCleanJetsAll = cleanNearestJetOnly(
            self.noIdCleanJetsAll, photons, self.jetGammaDR)
        self.gamma_noIdCleanJets = [
            j for j in self.gamma_noIdCleanJetsAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]
        self.gamma_noIdCleanJetsFwd = [
            j for j in self.gamma_noIdCleanJetsAll
            if abs(j.eta()) >= self.cfg_ana.jetEtaCentral
        ]
        ###

        if self.cfg_ana.alwaysCleanPhotons:
            self.cleanJets = self.gamma_cleanJets
            self.cleanJetsAll = self.gamma_cleanJetsAll
            self.cleanJetsFwd = self.gamma_cleanJetsFwd
            #
            self.noIdCleanJets = self.gamma_noIdCleanJets
            self.noIdCleanJetsAll = self.gamma_noIdCleanJetsAll
            self.noIdCleanJetsFwd = self.gamma_noIdCleanJetsFwd

        ## Jet Id, after jet/lepton cleaning
        self.cleanJetsFailIdAll = []
        for jet in self.noIdCleanJetsAll:
            if not self.testJetID(jet):
                self.cleanJetsFailIdAll.append(jet)

        self.cleanJetsFailId = [
            j for j in self.cleanJetsFailIdAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]

        ## Jet Id, after jet/photon cleaning
        self.gamma_cleanJetsFailIdAll = []
        for jet in self.gamma_noIdCleanJetsAll:
            if not self.testJetID(jet):
                self.gamma_cleanJetsFailIdAll.append(jet)

        self.gamma_cleanJetsFailId = [
            j for j in self.gamma_cleanJetsFailIdAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]

        ## Associate jets to leptons
        leptons = event.inclusiveLeptons if hasattr(
            event, 'inclusiveLeptons') else event.selectedLeptons
        jlpairs = matchObjectCollection(leptons, allJets, self.jetLepDR**2)

        for jet in allJets:
            jet.leptons = [l for l in jlpairs if jlpairs[l] == jet]

        for lep in leptons:
            jet = jlpairs[lep]
            if jet is None:
                setattr(lep, "jet" + self.cfg_ana.collectionPostFix, lep)
            else:
                setattr(lep, "jet" + self.cfg_ana.collectionPostFix, jet)
        ## Associate jets to taus
        taus = getattr(event, 'selectedTaus', [])
        jtaupairs = matchObjectCollection(taus, allJets, self.jetLepDR**2)

        for jet in allJets:
            jet.taus = [l for l in jtaupairs if jtaupairs[l] == jet]
        for tau in taus:
            setattr(tau, "jet" + self.cfg_ana.collectionPostFix,
                    jtaupairs[tau])

        #MC stuff
        if self.cfg_comp.isMC:
            self.deltaMetFromJetSmearing = [0, 0]
            for j in self.cleanJetsAll:
                if hasattr(j, 'deltaMetFromJetSmearing'):
                    self.deltaMetFromJetSmearing[
                        0] += j.deltaMetFromJetSmearing[0]
                    self.deltaMetFromJetSmearing[
                        1] += j.deltaMetFromJetSmearing[1]

            self.cleanGenJets = cleanNearestJetOnly(self.genJets, leptons,
                                                    self.jetLepDR)

            if self.cfg_ana.cleanGenJetsFromPhoton:
                self.cleanGenJets = cleanNearestJetOnly(
                    self.cleanGenJets, photons, self.jetLepDR)

            #event.nGenJets25 = 0
            #event.nGenJets25Cen = 0
            #event.nGenJets25Fwd = 0
            #for j in event.cleanGenJets:
            #    event.nGenJets25 += 1
            #    if abs(j.eta()) <= 2.4: event.nGenJets25Cen += 1
            #    else:                   event.nGenJets25Fwd += 1

            if self.cfg_ana.do_mc_match:
                self.jetFlavour(event)

        if hasattr(event, "jets" + self.cfg_ana.collectionPostFix):
            raise RuntimeError, "Event already contains a jet collection with the following postfix: " + self.cfg_ana.collectionPostFix
        setattr(event, "rho" + self.cfg_ana.collectionPostFix, self.rho)
        setattr(event, "deltaMetFromJEC" + self.cfg_ana.collectionPostFix,
                self.deltaMetFromJEC)
        setattr(event, "type1METCorr" + self.cfg_ana.collectionPostFix,
                self.type1METCorr)
        setattr(event, "allJetsUsedForMET" + self.cfg_ana.collectionPostFix,
                self.allJetsUsedForMET)
        setattr(event, "jets" + self.cfg_ana.collectionPostFix, self.jets)
        setattr(event, "jetsFailId" + self.cfg_ana.collectionPostFix,
                self.jetsFailId)
        setattr(event, "jetsAllNoID" + self.cfg_ana.collectionPostFix,
                self.jetsAllNoID)
        setattr(event, "jetsIdOnly" + self.cfg_ana.collectionPostFix,
                self.jetsIdOnly)
        setattr(event, "cleanJetsAll" + self.cfg_ana.collectionPostFix,
                self.cleanJetsAll)
        setattr(event, "cleanJets" + self.cfg_ana.collectionPostFix,
                self.cleanJets)
        setattr(event, "cleanJetsFwd" + self.cfg_ana.collectionPostFix,
                self.cleanJetsFwd)
        setattr(event, "cleanJetsFailIdAll" + self.cfg_ana.collectionPostFix,
                self.cleanJetsFailIdAll)
        setattr(event, "cleanJetsFailId" + self.cfg_ana.collectionPostFix,
                self.cleanJetsFailId)
        setattr(event, "discardedJets" + self.cfg_ana.collectionPostFix,
                self.discardedJets)
        setattr(event, "gamma_cleanJetsAll" + self.cfg_ana.collectionPostFix,
                self.gamma_cleanJetsAll)
        setattr(event, "gamma_cleanJets" + self.cfg_ana.collectionPostFix,
                self.gamma_cleanJets)
        setattr(event, "gamma_cleanJetsFwd" + self.cfg_ana.collectionPostFix,
                self.gamma_cleanJetsFwd)
        setattr(event,
                "gamma_cleanJetsFailIdAll" + self.cfg_ana.collectionPostFix,
                self.gamma_cleanJetsFailIdAll)
        setattr(event,
                "gamma_cleanJetsFailId" + self.cfg_ana.collectionPostFix,
                self.gamma_cleanJetsFailId)

        if self.cfg_comp.isMC:
            setattr(event,
                    "deltaMetFromJetSmearing" + self.cfg_ana.collectionPostFix,
                    self.deltaMetFromJetSmearing)
            setattr(event, "cleanGenJets" + self.cfg_ana.collectionPostFix,
                    self.cleanGenJets)
            setattr(event, "genJets" + self.cfg_ana.collectionPostFix,
                    self.genJets)
            if self.cfg_ana.do_mc_match:
                setattr(event, "bqObjects" + self.cfg_ana.collectionPostFix,
                        self.bqObjects)
                setattr(event, "cqObjects" + self.cfg_ana.collectionPostFix,
                        self.cqObjects)
                setattr(event, "partons" + self.cfg_ana.collectionPostFix,
                        self.partons)
                setattr(event,
                        "heaviestQCDFlavour" + self.cfg_ana.collectionPostFix,
                        self.heaviestQCDFlavour)

        return True
예제 #9
0
    def process(self, event):

        self.readCollections(event.input)
        miniaodjets = self.handles['jets'].product()

        allJets = []
        event.jets = []
        event.bJets = []
        event.cleanJets = []
        event.cleanBJets = []

        leptons = []
        if hasattr(event, 'selectedLeptons'):
            leptons = event.selectedLeptons

        genJets = None
        if self.cfg_comp.isMC:
            genJets = map(GenJet, self.mchandles['genJets'].product())

        for maodjet in miniaodjets:
            jet = Jet(maodjet)
            allJets.append(jet)
            if self.cfg_comp.isMC and hasattr(self.cfg_comp, 'jetScale'):
                scale = random.gauss(self.cfg_comp.jetScale,
                                     self.cfg_comp.jetSmear)
                jet.scaleEnergy(scale)
            if genJets:
                # Use DeltaR = 0.25 matching like JetMET
                pairs = matchObjectCollection([jet], genJets, 0.25 * 0.25)
                if pairs[jet] is None:
                    pass
                else:
                    jet.matchedGenJet = pairs[jet]
            # Add JER correction for MC jets. Requires gen-jet matching.
            if self.cfg_comp.isMC and hasattr(self.cfg_ana, 'jerCorr') and self.cfg_ana.jerCorr:
                self.jerCorrection(jet)
            # Add JES correction for MC jets.
            if self.cfg_comp.isMC and hasattr(self.cfg_ana, 'jesCorr'):
                self.jesCorrection(jet, self.cfg_ana.jesCorr)
            if self.testJet(jet):
                event.jets.append(jet)
            if self.testBJet(jet):
                event.bJets.append(jet)

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

        event.cleanJets, dummy = cleanObjectCollection(event.jets,
                                                       masks=leptons,
                                                       deltaRMin=0.5)
        event.cleanBJets, dummy = cleanObjectCollection(event.bJets,
                                                        masks=leptons,
                                                        deltaRMin=0.5)

        pairs = matchObjectCollection(leptons, allJets, 0.5 * 0.5)
        # associating a jet to each lepton
        for lepton in leptons:
            jet = pairs[lepton]
            if jet is None:
                lepton.jet = lepton
            else:
                lepton.jet = jet

        # associating a leg to each clean jet
        invpairs = matchObjectCollection(event.cleanJets, leptons, 99999.)
        for jet in event.cleanJets:
            leg = invpairs[jet]
            jet.leg = leg

        for jet in event.cleanJets:
            jet.matchGenParton = 999.0

        if self.cfg_comp.isMC and "BB" in self.cfg_comp.name:
            genParticles = self.mchandles['genParticles'].product()
            event.genParticles = map(GenParticle, genParticles)
            for gen in genParticles:
                if abs(gen.pdgId()) == 5 and gen.mother() and abs(gen.mother().pdgId()) == 21:
                    for jet in event.cleanJets:
                        dR = deltaR2(jet.eta(), jet.phi(), gen.eta(), gen.phi())
                        if dR < jet.matchGenParton:
                            jet.matchGenParton = dR

        event.jets30 = [jet for jet in event.jets if jet.pt() > 30]
        event.cleanJets30 = [jet for jet in event.cleanJets if jet.pt() > 30]
        if len(event.jets30) >= 2:
            self.counters.counter('jets').inc('at least 2 good jets')
        if len(event.cleanJets30) >= 2:
            self.counters.counter('jets').inc('at least 2 clean jets')
        if len(event.cleanBJets) > 0:
            self.counters.counter('jets').inc('at least 1 b jet')
            if len(event.cleanBJets) > 1:
                self.counters.counter('jets').inc('at least 2 b jets')
        return True
예제 #10
0
    def evaluateRegressionAK08(self, event):
        #self.readCollections( event.input )
        reg_fj = []
        for ung_fj in getattr(event, "ak08"):

            # We need the closest ungroomed fatjet to get the JEC:                                                                                                                                              # - Make a list of pairs: deltaR(ungroomed fj, groomed fj) for all ungroomed fatjets                                                                                                                # - Sort by deltaR                                                                                                                                                                                  # - And take the minimum
            if len(getattr(event, "ak08pruned")):
                closest_pr_fj_and_dr = sorted(
                    [(pr_fj, deltaR2(ung_fj, pr_fj))
                     for pr_fj in getattr(event, "ak08pruned")],
                    key=lambda x: x[1])[0]
            else:
                print "WARNING: No pruned fatjets found in event with ungroomed fatjet. Skipping"
                continue

            # Use the jet cone size for matching
            minimal_dr_groomed_ungroomed = 0.8
            if closest_pr_fj_and_dr[1] > minimal_dr_groomed_ungroomed:
                print "WARNING: No pruned fatjet found close to ungroomed fatjet. Skipping"
                continue

            pr_jet = Jet(closest_pr_fj_and_dr[0])

            if len(getattr(event, "ak08prunedcal")):
                closest_cal_fj_and_dr = sorted(
                    [(cal_fj, deltaR2(ung_fj, cal_fj))
                     for cal_fj in getattr(event, "ak08prunedcal")],
                    key=lambda x: x[1])[0]
            else:
                print "WARNING: No calib groomed fatjets found in event with ungroomed fatjet. Skipping"
                continue

            if closest_cal_fj_and_dr[1] > minimal_dr_groomed_ungroomed:
                print "WARNING: No calib fatjet found close to ungroomed fatjet. Skipping"
                continue

            cal_jet = Jet(closest_cal_fj_and_dr[0])

            # now check the AK08 jet is not a lepton
            #            if len(getattr(event, "selectedLeptons")):
            #                closest_pr_lep_and_dr = sorted( [(lep, deltaR2(cal_jet,lep)) for lep in getattr(event, "vLeptons")],  key=lambda x:x[1])[0]
            #            if closest_pr_lep_and_dr[1] < (0.4 * 0.4):
            #              print "WARNING: No groomed fatjet is overlapping with a vLepton. Skipping"
            #              continue

            # Need to do a deep-copy. Otherwise the original jet will be modified
            reg_groomed_fj = PhysicsObject(closest_cal_fj_and_dr[0]).__copy__()
            #        for j in event.FatjetAK08pruned:

            self.FatjetAK08ungroomed_pt[0] = ung_fj.pt()
            #            print 'ung_fj.pt() ', ung_fj.pt()
            self.FatjetAK08pruned_pt[0] = pr_jet.pt()
            #            print 'pr_jet.pt() ',  pr_jet.pt()
            self.FatjetAK08prunedCal_pt[0] = cal_jet.pt()
            #            print 'cal_jet.pt() ', cal_jet.pt()
            self.FatjetAK08prunedCal_eta[0] = cal_jet.eta()
            self.FatjetAK08ungroomed_vertexNTracks[0] = ung_fj.vertexNTracks
            self.FatjetAK08ungroomed_SV_mass_0[0] = ung_fj.SV_mass_0
            self.FatjetAK08ungroomed_SV_EnergyRatio_0[
                0] = ung_fj.SV_EnergyRatio_0
            self.FatjetAK08ungroomed_SV_EnergyRatio_1[
                0] = ung_fj.SV_EnergyRatio_1
            self.FatjetAK08ungroomed_PFLepton_ptrel[0] = ung_fj.PFLepton_ptrel
            self.FatjetAK08ungroomed_nSL[0] = ung_fj.nSL
            #            print 'ung_fj.nSL ', ung_fj.nSL

            reg_groomed_fj.scaleEnergy(
                self.reader.EvaluateRegression(self.name)[0])

            reg_fj.append(reg_groomed_fj)
#            print 'reg_groomed_fj.pt() ', reg_groomed_fj.pt()

        setattr(event, 'ak08prunedreg', reg_fj)
예제 #11
0
    def process(self, event):
        '''
        '''

        self.readCollections(event.input)

        taus     = [Tau(tau) for tau in self.handles['taus'].product()]
        jets     = [Jet(jet) for jet in self.handles['jets'].product()]
        pfmet    = self.handles['pfMET'   ].product()[0]
        puppimet = self.handles['puppiMET'].product()[0]
        
        pairs = matchObjectCollection(taus, jets, 0.5 * 0.5)
        
#         import pdb ; pdb.set_trace()
        
        # associating a jet to each lepton
        for tau in taus:
            jet = pairs[tau]
            if jet is None:
                pass
            else:
                tau.jet = jet

        event.calibratedTaus = []
        
        for tau in taus:

            tau.associatedVertex = event.goodVertices[0]

            tau_p4_scale = 1.
            
            if tau.decayMode() in (0, 1, 10) and hasattr(tau, 'jet'):

                self.tauIsoBreakdown(tau)

                self.variables['tau_pt'                     ][0] = tau.pt()               
                self.variables['tau_eta'                    ][0] = tau.eta()              
                self.variables['tau_mass'                   ][0] = tau.mass()             
                self.variables['tau_decayMode'              ][0] = tau.decayMode()        

                self.variables['tau_charged_iso'            ][0] = tau.chargedPtSumIso    
                self.variables['tau_gamma_iso'              ][0] = tau.gammaPtSumIso      
                self.variables['tau_charged_sig'            ][0] = tau.chargedPtSumSignal 
                self.variables['tau_gamma_sig'              ][0] = tau.gammaPtSumSignal   

                self.variables['tau_jet_pt'                 ][0] = tau.jet.pt()           
                self.variables['tau_jet_mass'               ][0] = tau.jet.mass()         
                self.variables['tau_jet_nConstituents'      ][0] = tau.jet.nConstituents()
                self.variables['tau_jet_rawFactor'          ][0] = tau.jet.rawFactor()
                self.variables['tau_jet_chargedHadronEnergy'][0] = tau.jet.chargedHadronEnergy()      
                self.variables['tau_jet_neutralHadronEnergy'][0] = tau.jet.neutralHadronEnergy()      
                self.variables['tau_jet_neutralEmEnergy'    ][0] = tau.jet.neutralEmEnergy()    
                self.variables['tau_jet_chargedEmEnergy'    ][0] = tau.jet.chargedEmEnergy()          

                calibrated_tau_pt = self.reader.EvaluateRegression('BDTG')[0]
                tau_p4_scale = calibrated_tau_pt / tau.pt()

                pfmetP4    = pfmet   .p4()
                puppimetP4 = puppimet.p4()

                # remove pre-calibrated tau from met computation
                pfmetP4    += tau.p4()
                puppimetP4 += tau.p4()
                
                self.scaleP4(tau, tau_p4_scale)
                tau.ptScale = tau_p4_scale

                # include calibrated tau into the met computation
                pfmetP4    -= tau.p4()
                puppimetP4 -= tau.p4()
            
                pfmet   .setP4(pfmetP4   )
                puppimet.setP4(puppimetP4)
            
            event.calibratedTaus.append(tau)
        
        event.calibratedPfMet    = pfmet
        event.calibratedPuppiMet = puppimet

        return True
예제 #12
0
    def process(self, event):

        self.counters.counter('jets').inc('all events')
        self.readCollections(event.input)
        miniaodjets = self.handles['jets'].product()

        allJets = []

        to_clean_against = []
        if hasattr(self.cfg_ana, 'toClean'):
            for collection in self.cfg_ana.toClean:
                to_clean_against += getattr(event, collection)

        genJets = None
        if self.cfg_comp.isMC:
            genJets = map(GenJet, self.mchandles['genJets'].product())

        allJets = [Jet(jet) for jet in miniaodjets]

        if self.recalibrateJets:
            self.jetReCalibrator.correctAll(allJets,
                                            event.rho,
                                            delta=0.,
                                            addCorr=True,
                                            addShifts=True)

        for jet in allJets:
            if genJets:
                # Use DeltaR = 0.25 matching like JetMET
                pairs = matchObjectCollection([jet], genJets, 0.25 * 0.25)
                if pairs[jet] is None:
                    pass
                else:
                    jet.matchedGenJet = pairs[jet]
            # Add JER correction for MC jets. Requires gen-jet matching.
            if self.cfg_comp.isMC and hasattr(
                    self.cfg_ana, 'jerCorr') and self.cfg_ana.jerCorr:
                self.jerCorrection(jet)
            # Add JES correction for MC jets.
            if self.cfg_comp.isMC and hasattr(self.cfg_ana, 'jesCorr'):
                self.jesCorrection(jet, self.cfg_ana.jesCorr)
            jet.btagMVA = jet.btag(
                'pfCombinedInclusiveSecondaryVertexV2BJetTags'
            )  #TODO switch to deepCSV
            jet.btagged = self.btagSF.isBTagged(
                pt=jet.pt(),
                eta=jet.eta(),
                csv=jet.btag("pfCombinedInclusiveSecondaryVertexV2BJetTags"),
                jetflavor=abs(jet.hadronFlavour()),
                is_data=not self.cfg_comp.isMC,
                csv_cut=
                0.800  #CSVM from https://twiki.cern.ch/twiki/bin/viewauth/CMS/BtagRecommendation80X
            )
            ## if self.testJet(jet):
            ## 	event.jets.append(jet)
            ## if self.testBJet(jet):
            ## 	event.bJets.append(jet)

        allJets = [
            jet for jet in allJets if bool(jet.jetID("POG_PFID_Loose"))
            if jet.pt() > 20. if abs(jet.eta()) < 2.4
        ]
        if len(allJets) < 2: return False
        self.counters.counter('jets').inc('at least 2 good jets')

        event.jets, dummy = cleanObjectCollection(allJets,
                                                  masks=to_clean_against,
                                                  deltaRMin=0.5)
        if len(event.jets) < 2: return False
        self.counters.counter('jets').inc('at least 2 clean jets')

        event.bJets = [jet for jet in event.jets if jet.btagged]
        if len(event.bJets) != 2: return False
        self.counters.counter('jets').inc('exactly 2 b jets')

        # save HTs
        event.HT_jets = sum([jet.pt() for jet in event.jets])
        event.HT_bJets = sum([jet.pt() for jet in event.bJets])

        return True
예제 #13
0
    def process(self, event):
        # needed when doing handle.product(), goes back to
        # PhysicsTools.Heppy.analyzers.core.Analyzer
        self.readCollections(event.input)

        if not eval(self.skimFunction):
            return False

        ptSelGentauleps = []
        ptSelGenleps = []
        ptSelGenSummary = []

        if self.cfg_comp.isMC:
            event.genJets = self.mchandles['genJets'].product()

            ptcut = 8.
            ptSelGentauleps = [
                lep for lep in event.gentauleps if lep.pt() > ptcut
            ]
            ptSelGenleps = [lep for lep in event.genleps if lep.pt() > ptcut]
            ptSelGenSummary = [
                p for p in event.generatorSummary if p.pt() > ptcut
                and abs(p.pdgId()) not in [6, 23, 24, 25, 35, 36, 37]
            ]

        for i_dil, dil in enumerate(event.selDiLeptons):

            muon = dil.leg1()
            jet = dil.leg2()
            found = False
            for corr_jet in event.jets:
                if deltaR2(jet.eta(), jet.phi(), corr_jet.eta(),
                           corr_jet.phi()) < 0.01:
                    pt = max(
                        corr_jet.pt(),
                        corr_jet.pt() * corr_jet.corrJECUp / corr_jet.corr,
                        corr_jet.pt() * corr_jet.corrJECDown / corr_jet.corr)
                    if pt < 20.:
                        continue
                    found = True

            if not found:
                continue

            tau = jet.tau if hasattr(jet, 'tau') else None
            if self.cfg_comp.isMC:
                if tau:
                    DYJetsFakeAnalyzer.genMatch(event, tau, ptSelGentauleps,
                                                ptSelGenleps, ptSelGenSummary)
                    DYJetsFakeAnalyzer.attachGenStatusFlag(tau)
                DYJetsFakeAnalyzer.genMatch(event, muon, ptSelGentauleps,
                                            ptSelGenleps, ptSelGenSummary)
                DYJetsFakeAnalyzer.attachGenStatusFlag(muon)

            self.tree.reset()
            self.fillEvent(self.tree, event)
            self.fillDiLepton(self.tree, event.diLepton, fill_svfit=False)
            self.fillExtraMetInfo(self.tree, event)
            self.fillGenInfo(self.tree, event)

            self.fillJetMETVars(event)
            self.fillMuon(self.tree, 'muon', muon)
            jet = Jet(jet)
            jet.btagMVA = jet.btag(
                'pfCombinedInclusiveSecondaryVertexV2BJetTags')
            jet.btagFlag = jet.btagMVA > 0.8
            self.fillJet(self.tree, 'oriJet', jet)
            self.fill(self.tree, 'jet_nth', i_dil)

            for corr_jet in event.jets:
                if deltaR2(jet.eta(), jet.phi(), corr_jet.eta(),
                           corr_jet.phi()) < 0.01:
                    self.fillJet(self.tree, 'jet', corr_jet)
                    self.fill(self.tree, 'jet_nooverlap',
                              True if corr_jet in event.cleanJets else False)
                    self.fill(self.tree, 'jet_corrJECUp',
                              corr_jet.corrJECUp / corr_jet.corr)
                    self.fill(self.tree, 'jet_corrJECDown',
                              corr_jet.corrJECDown / corr_jet.corr)
                    self.fill(self.tree, 'jet_corr', corr_jet.corr)

            if tau:
                self.fillTau(self.tree, 'tau', tau)

                if hasattr(tau, 'genp') and tau.genp:
                    self.fillGenParticle(self.tree, 'tau_gen', tau.genp)
                    if tau.genJet():
                        self.fillGenParticle(self.tree, 'tau_gen_vis',
                                             tau.genJet())
                        self.fill(self.tree, 'tau_gen_decayMode',
                                  tauDecayModes.genDecayModeInt(tau.genJet()))

            self.fillTree(event)
예제 #14
0
    def process(self, event):

        self.readCollections(event.input)
        cmgJets = self.handles['jets'].product()

        allJets = []
        event.jets = []
        event.bJets = []
        event.cleanJets = []
        event.cleanBJets = []

        leg1 = event.diLepton.leg1()
        leg2 = event.diLepton.leg2()

        genJets = None
        if self.cfg_comp.isMC:
            genJets = map(GenJet, self.mchandles['genJets'].product())

        for cmgJet in cmgJets:
            jet = Jet(cmgJet)
            allJets.append(jet)
            if self.cfg_comp.isMC and hasattr(self.cfg_comp, 'jetScale'):
                scale = random.gauss(self.cfg_comp.jetScale,
                                     self.cfg_comp.jetSmear)
                jet.scaleEnergy(scale)

            if self.testJet(jet):
                event.jets.append(jet)
            if self.testBJet(jet):
                event.bJets.append(jet)
            if genJets:
                # Use DeltaR = 0.25 matching like JetMET
                pairs = matchObjectCollection([jet], genJets, 0.25 * 0.25)
                if pairs[jet] is None:
                    pass
                else:
                    jet.matchedGenJet = pairs[jet]

            #Add JER correction for MC jets. Requires gen-jet matching
            if self.cfg_comp.isMC and hasattr(
                    self.cfg_ana, 'jerCorr') and self.cfg_ana.jerCorr:
                self.jerCorrection(jet)

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

        event.cleanJets, dummy = cleanObjectCollection(event.jets,
                                                       masks=[leg1, leg2],
                                                       deltaRMin=0.5)

        event.cleanBJets, dummy = cleanObjectCollection(event.bJets,
                                                        masks=[leg1, leg2],
                                                        deltaRMin=0.5)

        pairs = matchObjectCollection([leg1, leg2], allJets, 0.5 * 0.5)

        # associating a jet to each leg
        leg1.jet = pairs[leg1]
        leg2.jet = pairs[leg2]
        if leg1.jet is None:  #COLIN: I don't understand the code below...
            leg1.jet = leg1
        if leg2.jet is None:
            leg2.jet = leg2

        # associating a leg to each clean jet
        invpairs = matchObjectCollection(event.cleanJets, [leg1, leg2], 99999.)
        for jet in event.cleanJets:
            leg = invpairs[jet]
            jet.leg = leg

        for jet in event.cleanJets:
            jet.matchGenParton = 999.0

        if self.cfg_comp.isMC and "BB" in self.cfg_comp.name:
            genParticles = self.mchandles['genParticles'].product()
            event.genParticles = map(GenParticle, genParticles)
            for gen in genParticles:
                if abs(gen.pdgId()) == 5 and gen.mother() and abs(
                        gen.mother().pdgId()) == 21:
                    for jet in event.cleanJets:
                        dR = deltaR2(jet.eta(), jet.phi(), gen.eta(),
                                     gen.phi())
                        if dR < jet.matchGenParton:
                            jet.matchGenParton = dR

        event.jets30 = [jet for jet in event.jets if jet.pt() > 30]
        event.cleanJets30 = [jet for jet in event.cleanJets if jet.pt() > 30]

        if len(event.jets30) >= 2:
            self.counters.counter('VBF').inc('at least 2 good jets')

        if len(event.cleanJets30) >= 2:
            self.counters.counter('VBF').inc('at least 2 clean jets')

        if len(event.cleanJets) < 2:
            return True

        event.vbf = VBF(event.cleanJets, event.diLepton, None,
                        self.cfg_ana.cjvPtCut)
        if event.vbf.mjj > self.cfg_ana.Mjj:
            self.counters.counter('VBF').inc(
                'M_jj > {cut:3.1f}'.format(cut=self.cfg_ana.Mjj))
        else:
            return True
        if abs(event.vbf.deta) > self.cfg_ana.deltaEta:
            self.counters.counter('VBF').inc(
                'delta Eta > {cut:3.1f}'.format(cut=self.cfg_ana.deltaEta))
        else:
            return True
        if len(event.vbf.centralJets) == 0:
            self.counters.counter('VBF').inc('no central jets')
        else:
            return True

        return True
예제 #15
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
예제 #16
0
    def process(self, event):
        self.readCollections(event.input)

        # all jets
        miniaodjets = [Jet(jet) for jet in self.handles['jets'].product()]

        # ugt decision
        event.ugt = self.handles['ugt'].product().at(0, 0)

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

        if getattr(self.cfg_ana, 'onlyBX0', True):
            L1_muons = []
            for jj in range(L1muons_allbx.size(0)):
                L1_muons.append(L1muons_allbx.at(0, jj))

            event.L1_muons = L1_muons

        else:
            event.L1_muons = [mu for mu in L1muons_allbx]
            if len(event.L1_muons):
                import pdb
                pdb.set_trace()

        # append a reco jet (if it exists) to each L1 muon
        for mu in event.L1_muons:
            jets = sorted([
                jj for jj in miniaodjets if deltaR2(
                    jj.eta(), jj.phi(), mu.etaAtVtx(), mu.phiAtVtx()) < 0.16
            ],
                          key=lambda x: deltaR2(x, mu))
            if len(jets):
                mu.jet = jets[0]

        event.L1_muons_eta_0p5_q8 = sorted([
            mu for mu in event.L1_muons
            if abs(mu.eta()) < 0.5 and mu.hwQual() >= 8
        ],
                                           key=lambda mu: mu.pt(),
                                           reverse=True)
        event.L1_muons_eta_0p5_q12 = sorted([
            mu for mu in event.L1_muons
            if abs(mu.eta()) < 0.5 and mu.hwQual() >= 12
        ],
                                            key=lambda mu: mu.pt(),
                                            reverse=True)
        event.L1_muons_eta_0p8_q8 = sorted([
            mu for mu in event.L1_muons
            if abs(mu.eta()) < 0.8 and mu.hwQual() >= 8
        ],
                                           key=lambda mu: mu.pt(),
                                           reverse=True)
        event.L1_muons_eta_0p8_q12 = sorted([
            mu for mu in event.L1_muons
            if abs(mu.eta()) < 0.8 and mu.hwQual() >= 12
        ],
                                            key=lambda mu: mu.pt(),
                                            reverse=True)
        event.L1_muons_eta_1p0_q8 = sorted([
            mu for mu in event.L1_muons
            if abs(mu.eta()) < 1.0 and mu.hwQual() >= 8
        ],
                                           key=lambda mu: mu.pt(),
                                           reverse=True)
        event.L1_muons_eta_1p0_q12 = sorted([
            mu for mu in event.L1_muons
            if abs(mu.eta()) < 1.0 and mu.hwQual() >= 12
        ],
                                            key=lambda mu: mu.pt(),
                                            reverse=True)
        event.L1_muons_eta_1p5_q8 = sorted([
            mu for mu in event.L1_muons
            if abs(mu.eta()) < 1.5 and mu.hwQual() >= 8
        ],
                                           key=lambda mu: mu.pt(),
                                           reverse=True)
        event.L1_muons_eta_1p5_q12 = sorted([
            mu for mu in event.L1_muons
            if abs(mu.eta()) < 1.5 and mu.hwQual() >= 12
        ],
                                            key=lambda mu: mu.pt(),
                                            reverse=True)
        event.L1_muons_eta_2p1_q8 = sorted([
            mu for mu in event.L1_muons
            if abs(mu.eta()) < 2.1043125 and mu.hwQual() >= 8
        ],
                                           key=lambda mu: mu.pt(),
                                           reverse=True)
        event.L1_muons_eta_2p1_q12 = sorted([
            mu for mu in event.L1_muons
            if abs(mu.eta()) < 2.1043125 and mu.hwQual() >= 12
        ],
                                            key=lambda mu: mu.pt(),
                                            reverse=True)
        event.L1_muons_eta_2p5_q8 = sorted([
            mu for mu in event.L1_muons
            if abs(mu.eta()) < 2.5 and mu.hwQual() >= 8
        ],
                                           key=lambda mu: mu.pt(),
                                           reverse=True)
        event.L1_muons_eta_2p5_q12 = sorted([
            mu for mu in event.L1_muons
            if abs(mu.eta()) < 2.5 and mu.hwQual() >= 12
        ],
                                            key=lambda mu: mu.pt(),
                                            reverse=True)
        event.L1_muons_eta_inf_q8 = sorted(
            [mu for mu in event.L1_muons if mu.hwQual() >= 8],
            key=lambda mu: mu.pt(),
            reverse=True)
        event.L1_muons_eta_inf_q12 = sorted(
            [mu for mu in event.L1_muons if mu.hwQual() >= 12],
            key=lambda mu: mu.pt(),
            reverse=True)

        #         # 29  L1_SingleMu22er2p1
        #         if ugt.getAlgoDecisionFinal(29) and len([mu for mu in event.L1_muons_eta_2p1_q12 if mu.pt()>=22.])==0:
        #             import pdb ; pdb.set_trace()

        #         if any([mm.eta() == 2.1 for mm in event.L1_muons]):
        #             print 'cazz...'
        #             import pdb ; pdb.set_trace()

        #         if len(event.L1_muons_eta_2p5_q12)>1:
        #             for mm in event.L1_muons_eta_2p5_q12: print mm.pt(), mm.eta(), mm.phi(), mm.hwQual()
        #             import pdb ; pdb.set_trace()

        #         if event.run==305081:

        event.fakeL1mu = True
        event.deltapt = -9999.
        event.isiso = -99.
        event.lowptjet = False

        if len(event.L1_muons_eta_2p1_q12
               ) > 0 and event.L1_muons_eta_2p1_q12[0].pt() >= 22.:

            print 'Jets, unfiltered'
            for jet in miniaodjets:
                print jet, '\tpfJetId', jet.jetID(
                    "POG_PFID_Loose"), '\tpuJetId', jet.puJetId(
                    ), '\tbtag', jet.btag(
                        'pfCombinedInclusiveSecondaryVertexV2BJetTags')
                if deltaR2(jet.eta(), jet.phi(),
                           event.L1_muons_eta_2p1_q12[0].etaAtVtx(),
                           event.L1_muons_eta_2p1_q12[0].phiAtVtx()) < 0.25:
                    if jet.pt() < 20.:
                        event.lowptjet = True

            print 'L1 muons'
            for mu in event.L1_muons_eta_2p1_q12:
                print 'pt %.2f\teta %.2f\tphi %.2f\tetaAtVtx %.2f\tphiAtVtx %.2f' % (
                    mu.pt(), mu.eta(), mu.phi(), mu.etaAtVtx(), mu.phiAtVtx())

            print 'offline muons'
            for mm in [Muon(ii) for ii in self.handles['muons'].product()]:
                print mm

                if deltaR2(mm.eta(), mm.phi(),
                           event.L1_muons_eta_2p1_q12[0].etaAtVtx(),
                           event.L1_muons_eta_2p1_q12[0].phiAtVtx()) < 0.25:
                    event.fakeL1mu = False
                    event.isiso = int(mm.relIso() < 1.)
                    event.deltapt = event.L1_muons_eta_2p1_q12[0].pt() - mm.pt(
                    )

            # jj = miniaodjets[1]
            # deltaR(jj.eta(), jj.phi(), mu.etaAtVtx(), mu.phiAtVtx())

#             import pdb ; pdb.set_trace()

        return True
예제 #17
0
    def process(self, event):
        self.readCollections(event.input)
        rho = float(self.handles['rho'].product()[0])
        self.rho = rho

        ## Read jets, if necessary recalibrate and shift MET
        if self.cfg_ana.copyJetsByValue:
            import ROOT
            #from ROOT.heppy import JetUtils
            allJets = map(
                lambda j: Jet(ROOT.heppy.JetUtils.copyJet(j)),
                self.handles['jets'].product(
                ))  #copy-by-value is safe if JetAnalyzer is ran more than once
        else:
            allJets = map(Jet, self.handles['jets'].product())

        #set dummy MC flavour for all jets in case we want to ntuplize discarded jets later
        for jet in allJets:
            jet.mcFlavour = 0

        self.deltaMetFromJEC = [0., 0.]
        self.type1METCorr = [0., 0., 0.]
        #        print "before. rho",self.rho,self.cfg_ana.collectionPostFix,'allJets len ',len(allJets),'pt', [j.pt() for j in allJets]
        if self.doJEC:
            if not self.recalibrateJets:  # check point that things won't change
                jetsBefore = [(j.pt(), j.eta(), j.phi(), j.rawFactor())
                              for j in allJets]
            self.jetReCalibrator.correctAll(allJets,
                                            rho,
                                            delta=self.shiftJEC,
                                            addCorr=True,
                                            addShifts=self.addJECShifts,
                                            metShift=self.deltaMetFromJEC,
                                            type1METCorr=self.type1METCorr)
            if not self.recalibrateJets:
                jetsAfter = [(j.pt(), j.eta(), j.phi(), j.rawFactor())
                             for j in allJets]
                if len(jetsBefore) != len(jetsAfter):
                    print "ERROR: I had to recompute jet corrections, and they rejected some of the jets:\nold = %s\n new = %s\n" % (
                        jetsBefore, jetsAfter)
                else:
                    for (told, tnew) in zip(jetsBefore, jetsAfter):
                        if (deltaR2(told[1], told[2], tnew[1],
                                    tnew[2])) > 0.0001:
                            print "ERROR: I had to recompute jet corrections, and one jet direction moved: old = %s, new = %s\n" % (
                                told, tnew)
                        elif abs(told[0] - tnew[0]) / (
                                told[0] + tnew[0]) > 0.5e-3 or abs(
                                    told[3] - tnew[3]) > 0.5e-3:
                            print "ERROR: I had to recompute jet corrections, and one jet pt or corr changed: old = %s, new = %s\n" % (
                                told, tnew)
        self.allJetsUsedForMET = allJets
        #        print "after. rho",self.rho,self.cfg_ana.collectionPostFix,'allJets len ',len(allJets),'pt', [j.pt() for j in allJets]

        if self.cfg_comp.isMC:
            self.genJets = [x for x in self.handles['genJet'].product()]
            if self.cfg_ana.do_mc_match:
                for igj, gj in enumerate(self.genJets):
                    gj.index = igj
#                self.matchJets(event, allJets)
                self.matchJets(
                    event, [j for j in allJets if j.pt() > self.cfg_ana.jetPt
                            ])  # To match only jets above chosen threshold
            if getattr(self.cfg_ana, 'smearJets', False):
                self.smearJets(event, allJets)

##Sort Jets by pT
        allJets.sort(key=lambda j: j.pt(), reverse=True)

        leptons = []
        if hasattr(event, 'selectedLeptons'):
            leptons = [
                l for l in event.selectedLeptons
                if l.pt() > self.lepPtMin and self.lepSelCut(l)
            ]
        if self.cfg_ana.cleanJetsFromTaus and hasattr(event, 'selectedTaus'):
            leptons = leptons[:] + event.selectedTaus
        if self.cfg_ana.cleanJetsFromIsoTracks and hasattr(
                event, 'selectedIsoCleanTrack'):
            leptons = leptons[:] + event.selectedIsoCleanTrack

## Apply jet selection
        self.jets = []
        self.jetsFailId = []
        self.jetsAllNoID = []
        self.jetsIdOnly = []
        for jet in allJets:
            #Check if lepton and jet have overlapping PF candidates
            leps_with_overlaps = []
            if getattr(self.cfg_ana, 'checkLeptonPFOverlap', True):
                for i in range(jet.numberOfSourceCandidatePtrs()):
                    p1 = jet.sourceCandidatePtr(i)  #Ptr<Candidate> p1
                    for lep in leptons:
                        for j in range(lep.numberOfSourceCandidatePtrs()):
                            p2 = lep.sourceCandidatePtr(j)
                            has_overlaps = p1.key() == p2.key() and p1.refCore(
                            ).id().productIndex() == p2.refCore().id(
                            ).productIndex() and p1.refCore().id(
                            ).processIndex() == p2.refCore().id().processIndex(
                            )
                            if has_overlaps:
                                leps_with_overlaps += [lep]
            if len(leps_with_overlaps) > 0:
                for lep in leps_with_overlaps:
                    lep.jetOverlap = jet
            if self.testJetNoID(jet):
                self.jetsAllNoID.append(jet)
                if (self.cfg_ana.doQG):
                    jet.qgl_calc = self.qglcalc.computeQGLikelihood
                    jet.qgl_rho = rho
                if self.testJetID(jet):
                    self.jets.append(jet)
                    self.jetsIdOnly.append(jet)
                else:
                    self.jetsFailId.append(jet)
            elif self.testJetID(jet):
                self.jetsIdOnly.append(jet)

        jetsEtaCut = [
            j for j in self.jets if abs(j.eta()) < self.cfg_ana.jetEta
        ]
        self.cleanJetsAll, cleanLeptons = cleanJetsAndLeptons(
            jetsEtaCut, leptons, self.jetLepDR, self.jetLepArbitration)

        self.cleanJets = [
            j for j in self.cleanJetsAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]
        self.cleanJetsFwd = [
            j for j in self.cleanJetsAll
            if abs(j.eta()) >= self.cfg_ana.jetEtaCentral
        ]
        self.discardedJets = [
            j for j in self.jets if j not in self.cleanJetsAll
        ]
        if hasattr(event,
                   'selectedLeptons') and self.cfg_ana.cleanSelectedLeptons:
            event.discardedLeptons = [
                l for l in leptons if l not in cleanLeptons
            ]
            event.selectedLeptons = [
                l for l in event.selectedLeptons
                if l not in event.discardedLeptons
            ]
        for lep in leptons:
            if hasattr(lep, "jetOverlap"):
                if lep.jetOverlap in self.cleanJetsAll:
                    #print "overlap reco", lep.p4().pt(), lep.p4().eta(), lep.p4().phi(), lep.jetOverlap.p4().pt(), lep.jetOverlap.p4().eta(), lep.jetOverlap.p4().phi()
                    lep.jetOverlapIdx = self.cleanJetsAll.index(lep.jetOverlap)
                elif lep.jetOverlap in self.discardedJets:
                    #print "overlap discarded", lep.p4().pt(), lep.p4().eta(), lep.p4().phi(), lep.jetOverlap.p4().pt(), lep.jetOverlap.p4().eta(), lep.jetOverlap.p4().phi()
                    lep.jetOverlapIdx = 1000 + self.discardedJets.index(
                        lep.jetOverlap)

        ## First cleaning, then Jet Id
        self.noIdCleanJetsAll, cleanLeptons = cleanJetsAndLeptons(
            self.jetsAllNoID, leptons, self.jetLepDR, self.jetLepArbitration)
        self.noIdCleanJets = [
            j for j in self.noIdCleanJetsAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]
        self.noIdCleanJetsFwd = [
            j for j in self.noIdCleanJetsAll
            if abs(j.eta()) >= self.cfg_ana.jetEtaCentral
        ]
        self.noIdDiscardedJets = [
            j for j in self.jetsAllNoID if j not in self.noIdCleanJetsAll
        ]

        ## Clean Jets from photons (first cleaning, then Jet Id)
        photons = []
        if hasattr(event, 'selectedPhotons'):
            if self.cfg_ana.cleanJetsFromFirstPhoton:
                photons = event.selectedPhotons[:1]
            else:
                photons = [g for g in event.selectedPhotons]

        self.gamma_cleanJetaAll = []
        self.gamma_noIdCleanJetsAll = []

        if self.cleanFromLepAndGammaSimultaneously:
            self.gamma_cleanJetsAll = cleanNearestJetOnly(
                jetsEtaCut, photons + leptons, self.jetGammaLepDR)
            self.gamma_noIdCleanJetsAll = cleanNearestJetOnly(
                self.jetsAllNoID, photons + leptons, self.jetGammaLepDR)
        else:
            self.gamma_cleanJetsAll = cleanNearestJetOnly(
                self.cleanJetsAll, photons, self.jetGammaDR)
            self.gamma_noIdCleanJetsAll = cleanNearestJetOnly(
                self.noIdCleanJetsAll, photons, self.jetGammaDR)

        self.gamma_cleanJets = [
            j for j in self.gamma_cleanJetsAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]
        self.gamma_cleanJetsFwd = [
            j for j in self.gamma_cleanJetsAll
            if abs(j.eta()) >= self.cfg_ana.jetEtaCentral
        ]

        self.gamma_noIdCleanJets = [
            j for j in self.gamma_noIdCleanJetsAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]
        self.gamma_noIdCleanJetsFwd = [
            j for j in self.gamma_noIdCleanJetsAll
            if abs(j.eta()) >= self.cfg_ana.jetEtaCentral
        ]
        ###

        if self.cfg_ana.alwaysCleanPhotons:
            self.cleanJets = self.gamma_cleanJets
            self.cleanJetsAll = self.gamma_cleanJetsAll
            self.cleanJetsFwd = self.gamma_cleanJetsFwd
            #
            self.noIdCleanJets = self.gamma_noIdCleanJets
            self.noIdCleanJetsAll = self.gamma_noIdCleanJetsAll
            self.noIdCleanJetsFwd = self.gamma_noIdCleanJetsFwd

        ## Jet Id, after jet/lepton cleaning
        self.cleanJetsFailIdAll = []
        for jet in self.noIdCleanJetsAll:
            if not self.testJetID(jet):
                self.cleanJetsFailIdAll.append(jet)

        self.cleanJetsFailId = [
            j for j in self.cleanJetsFailIdAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]

        ## Jet Id, after jet/photon cleaning
        self.gamma_cleanJetsFailIdAll = []
        for jet in self.gamma_noIdCleanJetsAll:
            if not self.testJetID(jet):
                self.gamma_cleanJetsFailIdAll.append(jet)

        self.gamma_cleanJetsFailId = [
            j for j in self.gamma_cleanJetsFailIdAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]

        ## Associate jets to leptons
        incleptons = event.inclusiveLeptons if hasattr(
            event, 'inclusiveLeptons') else event.selectedLeptons
        jlpairs = matchObjectCollection(incleptons, allJets, self.jetLepDR**2)

        for jet in allJets:
            jet.leptons = [l for l in jlpairs if jlpairs[l] == jet]
        for lep in incleptons:
            jet = jlpairs[lep]
            if jet is None:
                setattr(lep, "jet" + self.cfg_ana.collectionPostFix, lep)
            else:
                setattr(lep, "jet" + self.cfg_ana.collectionPostFix, jet)
        ## Associate jets to taus
        taus = getattr(event, 'selectedTaus', [])
        jtaupairs = matchObjectCollection(taus, allJets, self.jetLepDR**2)

        for jet in allJets:
            jet.taus = [l for l in jtaupairs if jtaupairs[l] == jet]
        for tau in taus:
            setattr(tau, "jet" + self.cfg_ana.collectionPostFix,
                    jtaupairs[tau])

        #MC stuff
        if self.cfg_comp.isMC:
            self.deltaMetFromJetSmearing = [0, 0]
            for j in self.cleanJetsAll:
                if hasattr(j, 'deltaMetFromJetSmearing'):
                    self.deltaMetFromJetSmearing[
                        0] += j.deltaMetFromJetSmearing[0]
                    self.deltaMetFromJetSmearing[
                        1] += j.deltaMetFromJetSmearing[1]

            self.cleanGenJets = cleanNearestJetOnly(self.genJets, leptons,
                                                    self.jetLepDR)

            if self.cfg_ana.cleanGenJetsFromPhoton:
                self.cleanGenJets = cleanNearestJetOnly(
                    self.cleanGenJets, photons, self.jetLepDR)

            if getattr(self.cfg_ana, 'attachNeutrinos', True) and hasattr(
                    self.cfg_ana, "genNuSelection"):
                jetNus = [
                    x for x in event.genParticles
                    if abs(x.pdgId()) in [12, 14, 16]
                    and self.cfg_ana.genNuSelection(x)
                ]
                pairs = matchObjectCollection(jetNus, self.genJets, 0.4**2)

                for (nu, genJet) in pairs.iteritems():
                    if genJet is not None:
                        if not hasattr(genJet, "nu"):
                            genJet.nu = nu.p4()
                        else:
                            genJet.nu += nu.p4()

            if self.cfg_ana.do_mc_match:
                self.jetFlavour(event)

        if hasattr(event, "jets" + self.cfg_ana.collectionPostFix):
            raise RuntimeError(
                "Event already contains a jet collection with the following postfix: "
                + self.cfg_ana.collectionPostFix)
        setattr(event, "rho" + self.cfg_ana.collectionPostFix, self.rho)
        setattr(event, "deltaMetFromJEC" + self.cfg_ana.collectionPostFix,
                self.deltaMetFromJEC)
        setattr(event, "type1METCorr" + self.cfg_ana.collectionPostFix,
                self.type1METCorr)
        setattr(event, "allJetsUsedForMET" + self.cfg_ana.collectionPostFix,
                self.allJetsUsedForMET)
        setattr(event, "jets" + self.cfg_ana.collectionPostFix, self.jets)
        setattr(event, "jetsFailId" + self.cfg_ana.collectionPostFix,
                self.jetsFailId)
        setattr(event, "jetsAllNoID" + self.cfg_ana.collectionPostFix,
                self.jetsAllNoID)
        setattr(event, "jetsIdOnly" + self.cfg_ana.collectionPostFix,
                self.jetsIdOnly)
        setattr(event, "cleanJetsAll" + self.cfg_ana.collectionPostFix,
                self.cleanJetsAll)
        setattr(event, "cleanJets" + self.cfg_ana.collectionPostFix,
                self.cleanJets)
        setattr(event, "cleanJetsFwd" + self.cfg_ana.collectionPostFix,
                self.cleanJetsFwd)
        setattr(event, "cleanJetsFailIdAll" + self.cfg_ana.collectionPostFix,
                self.cleanJetsFailIdAll)
        setattr(event, "cleanJetsFailId" + self.cfg_ana.collectionPostFix,
                self.cleanJetsFailId)
        setattr(event, "discardedJets" + self.cfg_ana.collectionPostFix,
                self.discardedJets)
        setattr(event, "gamma_cleanJetsAll" + self.cfg_ana.collectionPostFix,
                self.gamma_cleanJetsAll)
        setattr(event, "gamma_cleanJets" + self.cfg_ana.collectionPostFix,
                self.gamma_cleanJets)
        setattr(event, "gamma_cleanJetsFwd" + self.cfg_ana.collectionPostFix,
                self.gamma_cleanJetsFwd)
        setattr(event,
                "gamma_cleanJetsFailIdAll" + self.cfg_ana.collectionPostFix,
                self.gamma_cleanJetsFailIdAll)
        setattr(event,
                "gamma_cleanJetsFailId" + self.cfg_ana.collectionPostFix,
                self.gamma_cleanJetsFailId)

        if self.cfg_comp.isMC:
            setattr(event,
                    "deltaMetFromJetSmearing" + self.cfg_ana.collectionPostFix,
                    self.deltaMetFromJetSmearing)
            setattr(event, "cleanGenJets" + self.cfg_ana.collectionPostFix,
                    self.cleanGenJets)
            setattr(event, "genJets" + self.cfg_ana.collectionPostFix,
                    self.genJets)
            if self.cfg_ana.do_mc_match:
                setattr(event, "bqObjects" + self.cfg_ana.collectionPostFix,
                        self.bqObjects)
                setattr(event, "cqObjects" + self.cfg_ana.collectionPostFix,
                        self.cqObjects)
                setattr(event, "partons" + self.cfg_ana.collectionPostFix,
                        self.partons)
                setattr(event,
                        "heaviestQCDFlavour" + self.cfg_ana.collectionPostFix,
                        self.heaviestQCDFlavour)

        return True
예제 #18
0
    def process(self, event):
        self.readCollections(event.input)
        rho = float(self.handles['rho'].product()[0])
        rho_jer = float(self.handles['rho_jer'].product()[0])
        self.rho = rho

        ## Read jets, if necessary recalibrate and shift MET
        #self.jets_raw = map(Jet, self.handles['jets_raw'].product())
        if self.cfg_ana.copyJetsByValue:
            import ROOT
            allJets = map(
                lambda j: Jet(
                    ROOT.pat.Jet(
                        ROOT.edm.Ptr(ROOT.pat.Jet)
                        (ROOT.edm.ProductID(), j, 0))),
                self.handles['jets'].product(
                ))  #copy-by-value is safe if JetAnalyzer is ran more than once
        else:
            allJets = map(Jet, self.handles['jets'].product())
        self.jets_raw = copy.deepcopy(allJets)
        #set dummy MC flavour for all jets in case we want to ntuplize discarded jets later
        for jet in allJets:
            jet.mcFlavour = 0

        self.deltaMetFromJEC = [0., 0.]
        self.type1METCorr = [0., 0., 0.]
        self.type1METCorrUp = [0., 0., 0.]
        self.type1METCorrDown = [0., 0., 0.]
        self.sumRawJetsforT1 = [0., 0., 0.]

        #        print "before. rho",self.rho,self.cfg_ana.collectionPostFix,'allJets len ',len(allJets),'pt', [j.pt() for j in allJets]

        if self.doJEC:
            if not self.recalibrateJets:  # check point that things won't change
                jetsBefore = [(j.pt(), j.eta(), j.phi(), j.rawFactor())
                              for j in allJets]
            #print '[Debug] I am event = ', event.input.eventAuxiliary().id().event()

            self.jetReCalibrator.correctAll(
                allJets,
                rho,
                delta=self.shiftJEC,
                addCorr=True,
                addShifts=self.addJECShifts,
                metShift=self.deltaMetFromJEC,
                type1METCorr=self.type1METCorr,
                type1METCorrUp=self.type1METCorrUp,
                type1METCorrDown=self.type1METCorrDown,
                sumRawJetsforT1=self.sumRawJetsforT1)

            if not self.recalibrateJets:
                jetsAfter = [(j.pt(), j.eta(), j.phi(), j.rawFactor())
                             for j in allJets]
                if len(jetsBefore) != len(jetsAfter):
                    print "ERROR: I had to recompute jet corrections, and they rejected some of the jets:\nold = %s\n new = %s\n" % (
                        jetsBefore, jetsAfter)
                else:
                    for (told, tnew) in zip(jetsBefore, jetsAfter):
                        if (deltaR2(told[1], told[2], tnew[1],
                                    tnew[2])) > 0.0001:
                            print "ERROR: I had to recompute jet corrections, and one jet direction moved: old = %s, new = %s\n" % (
                                told, tnew)
                        elif abs(told[0] - tnew[0]) / (
                                told[0] + tnew[0]) > 0.5e-3 or abs(
                                    told[3] - tnew[3]) > 0.5e-3:
                            print "ERROR: I had to recompute jet corrections, and one jet pt or corr changed: old = %s, new = %s\n" % (
                                told, tnew)
        self.allJetsUsedForMET = allJets
        self.sumJetsInT1 = {
            "rawP4forT1":
            self.sumRawJetsforT1,
            "type1METCorr":
            self.type1METCorr,
            "corrP4forT1":
            [x + y for x, y in zip(self.sumRawJetsforT1, self.type1METCorr)]
        }

        #        print "after. rho",self.rho,self.cfg_ana.collectionPostFix,'allJets len ',len(allJets),'pt', [j.pt() for j in allJets]

        if self.cfg_comp.isMC:
            self.genJets = [x for x in self.handles['genJet'].product()]

        # ==> following matching example from PhysicsTools/Heppy/python/analyzers/examples/JetAnalyzer.py
        if self.cfg_comp.isMC:
            for jet in allJets:
                if self.smearJets:
                    jet.resolution = self.jetResolution.getResolution(
                        jet, rho_jer)
                    jet.jerfactor = self.jetResolution.getScaleFactor(jet)
                else:
                    jet.resolution = 1.0
                    jet.jerfactor = 1.0

                if self.genJets:
                    # Use DeltaR = 0.2 matching jet and genJet from
                    # https://github.com/blinkseb/JMEReferenceSample/blob/master/test/createReferenceSample.py
                    pairs = XZZmatchObjectCollection([jet], self.genJets,
                                                     0.2 * 0.2, 3)
                    if pairs[jet] is None:
                        pass
                    else:
                        jet.matchedGenJet = pairs[jet]
                else:
                    pass
                if self.debug:
                    print '[Debug] I am event = ', event.input.eventAuxiliary(
                    ).id().event()
                if self.smearJets:
                    self.jerCorrection(jet, rho_jer)

##Sort Jets by pT
        allJets.sort(key=lambda j: j.pt(), reverse=True)

        leptons = []
        if hasattr(event, 'selectedLeptons'):
            leptons = [
                l for l in event.selectedLeptons
                if l.pt() > self.lepPtMin and self.lepSelCut(l)
            ]
        if self.cfg_ana.cleanJetsFromTaus and hasattr(event, 'selectedTaus'):
            leptons = leptons[:] + event.selectedTaus
        if self.cfg_ana.cleanJetsFromIsoTracks and hasattr(
                event, 'selectedIsoCleanTrack'):
            leptons = leptons[:] + event.selectedIsoCleanTrack

        self.counters.counter('jets').inc('All Events')
        ## Apply jet selection
        self.jets = []
        self.jetsFailId = []
        self.jetsAllNoID = []
        self.jetsIdOnly = []
        for jet in allJets:
            #Check if lepton and jet have overlapping PF candidates
            leps_with_overlaps = []
            if getattr(self.cfg_ana, 'checkLeptonPFOverlap', True):
                for i in range(jet.numberOfSourceCandidatePtrs()):
                    p1 = jet.sourceCandidatePtr(i)  #Ptr<Candidate> p1
                    for lep in leptons:
                        for j in range(lep.numberOfSourceCandidatePtrs()):
                            p2 = lep.sourceCandidatePtr(j)
                            has_overlaps = p1.key() == p2.key() and p1.refCore(
                            ).id().productIndex() == p2.refCore().id(
                            ).productIndex() and p1.refCore().id(
                            ).processIndex() == p2.refCore().id().processIndex(
                            )
                            if has_overlaps:
                                leps_with_overlaps += [lep]
            if len(leps_with_overlaps) > 0:
                for lep in leps_with_overlaps:
                    lep.jetOverlap = jet
            if self.testJetNoID(jet):
                self.jetsAllNoID.append(jet)
                if (self.cfg_ana.doQG):
                    jet.qgl_calc = self.qglcalc.computeQGLikelihood
                    jet.qgl_rho = rho
                if self.testJetID(jet):
                    self.jets.append(jet)
                    self.jetsIdOnly.append(jet)
                else:
                    self.jetsFailId.append(jet)
            elif self.testJetID(jet):
                self.jetsIdOnly.append(jet)

        jetsEtaCut = [
            j for j in self.jets if abs(j.eta()) < self.cfg_ana.jetEta
        ]
        self.cleanJetsAll, cleanLeptons = cleanJetsAndLeptons(
            jetsEtaCut, leptons, self.jetLepDR, self.jetLepArbitration)

        self.cleanJets = [
            j for j in self.cleanJetsAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]
        self.cleanJetsFwd = [
            j for j in self.cleanJetsAll
            if abs(j.eta()) >= self.cfg_ana.jetEtaCentral
        ]
        self.discardedJets = [
            j for j in self.jets if j not in self.cleanJetsAll
        ]
        if hasattr(event,
                   'selectedLeptons') and self.cfg_ana.cleanSelectedLeptons:
            event.discardedLeptons = [
                l for l in leptons if l not in cleanLeptons
            ]
            event.selectedLeptons = [
                l for l in event.selectedLeptons
                if l not in event.discardedLeptons
            ]
        for lep in leptons:
            if hasattr(lep, "jetOverlap"):
                if lep.jetOverlap in self.cleanJetsAll:
                    #print "overlap reco", lep.p4().pt(), lep.p4().eta(), lep.p4().phi(), lep.jetOverlap.p4().pt(), lep.jetOverlap.p4().eta(), lep.jetOverlap.p4().phi()
                    lep.jetOverlapIdx = self.cleanJetsAll.index(lep.jetOverlap)
                elif lep.jetOverlap in self.discardedJets:
                    #print "overlap discarded", lep.p4().pt(), lep.p4().eta(), lep.p4().phi(), lep.jetOverlap.p4().pt(), lep.jetOverlap.p4().eta(), lep.jetOverlap.p4().phi()
                    lep.jetOverlapIdx = 1000 + self.discardedJets.index(
                        lep.jetOverlap)

        ## First cleaning, then Jet Id
        self.noIdCleanJetsAll, cleanLeptons = cleanJetsAndLeptons(
            self.jetsAllNoID, leptons, self.jetLepDR, self.jetLepArbitration)
        self.noIdCleanJets = [
            j for j in self.noIdCleanJetsAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]
        self.noIdCleanJetsFwd = [
            j for j in self.noIdCleanJetsAll
            if abs(j.eta()) >= self.cfg_ana.jetEtaCentral
        ]
        self.noIdDiscardedJets = [
            j for j in self.jetsAllNoID if j not in self.noIdCleanJetsAll
        ]

        ## Clean Jets from photons (first cleaning, then Jet Id)
        photons = []
        if hasattr(event, 'selectedPhotons'):
            if self.cfg_ana.cleanJetsFromFirstPhoton:
                photons = event.selectedPhotons[:1]
            else:
                photons = [g for g in event.selectedPhotons]

        self.gamma_cleanJetsAll = cleanNearestJetOnly(self.cleanJetsAll,
                                                      photons, self.jetGammaDR)
        self.gamma_cleanJets = [
            j for j in self.gamma_cleanJetsAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]
        self.gamma_cleanJetsFwd = [
            j for j in self.gamma_cleanJetsAll
            if abs(j.eta()) >= self.cfg_ana.jetEtaCentral
        ]
        self.gamma_noIdCleanJetsAll = cleanNearestJetOnly(
            self.noIdCleanJetsAll, photons, self.jetGammaDR)
        self.gamma_noIdCleanJets = [
            j for j in self.gamma_noIdCleanJetsAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]
        self.gamma_noIdCleanJetsFwd = [
            j for j in self.gamma_noIdCleanJetsAll
            if abs(j.eta()) >= self.cfg_ana.jetEtaCentral
        ]
        ###

        if self.cfg_ana.alwaysCleanPhotons:
            self.cleanJets = self.gamma_cleanJets
            self.cleanJetsAll = self.gamma_cleanJetsAll
            self.cleanJetsFwd = self.gamma_cleanJetsFwd
            #
            self.noIdCleanJets = self.gamma_noIdCleanJets
            self.noIdCleanJetsAll = self.gamma_noIdCleanJetsAll
            self.noIdCleanJetsFwd = self.gamma_noIdCleanJetsFwd

        ## Jet Id, after jet/lepton cleaning
        self.cleanJetsFailIdAll = []
        for jet in self.noIdCleanJetsAll:
            if not self.testJetID(jet):
                self.cleanJetsFailIdAll.append(jet)

        self.cleanJetsFailId = [
            j for j in self.cleanJetsFailIdAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]

        ## Jet Id, after jet/photon cleaning
        self.gamma_cleanJetsFailIdAll = []
        for jet in self.gamma_noIdCleanJetsAll:
            if not self.testJetID(jet):
                self.gamma_cleanJetsFailIdAll.append(jet)

        self.gamma_cleanJetsFailId = [
            j for j in self.gamma_cleanJetsFailIdAll
            if abs(j.eta()) < self.cfg_ana.jetEtaCentral
        ]

        ## Associate jets to leptons
        incleptons = event.inclusiveLeptons if hasattr(
            event, 'inclusiveLeptons') else event.selectedLeptons
        jlpairs = matchObjectCollection(incleptons, allJets, self.jetLepDR**2)

        for jet in allJets:
            jet.leptons = [l for l in jlpairs if jlpairs[l] == jet]
        for lep in incleptons:
            jet = jlpairs[lep]
            if jet is None:
                setattr(lep, "jet" + self.cfg_ana.collectionPostFix, lep)
            else:
                setattr(lep, "jet" + self.cfg_ana.collectionPostFix, jet)
        ## Associate jets to taus
        taus = getattr(event, 'selectedTaus', [])
        jtaupairs = matchObjectCollection(taus, allJets, self.jetLepDR**2)

        for jet in allJets:
            jet.taus = [l for l in jtaupairs if jtaupairs[l] == jet]
        for tau in taus:
            setattr(tau, "jet" + self.cfg_ana.collectionPostFix,
                    jtaupairs[tau])

        #MC stuff
        if self.cfg_comp.isMC:
            self.deltaMetFromJetSmearing = [0, 0]
            for j in self.cleanJetsAll:
                if hasattr(j, 'deltaMetFromJetSmearing'):
                    self.deltaMetFromJetSmearing[
                        0] += j.deltaMetFromJetSmearing[0]
                    self.deltaMetFromJetSmearing[
                        1] += j.deltaMetFromJetSmearing[1]

            self.cleanGenJets = cleanNearestJetOnly(self.genJets, leptons,
                                                    self.jetLepDR)

            if self.cfg_ana.cleanGenJetsFromPhoton:
                self.cleanGenJets = cleanNearestJetOnly(
                    self.cleanGenJets, photons, self.jetLepDR)

            if getattr(self.cfg_ana, 'attachNeutrinos', True) and hasattr(
                    self.cfg_ana, "genNuSelection"):
                jetNus = [
                    x for x in event.genParticles
                    if abs(x.pdgId()) in [12, 14, 16]
                    and self.cfg_ana.genNuSelection(x)
                ]
                pairs = matchObjectCollection(jetNus, self.genJets, 0.4**2)

                for (nu, genJet) in pairs.iteritems():
                    if genJet is not None:
                        if not hasattr(genJet, "nu"):
                            genJet.nu = nu.p4()
                        else:
                            genJet.nu += nu.p4()

            if self.cfg_ana.do_mc_match:
                self.jetFlavour(event)

        if hasattr(event, "jets" + self.cfg_ana.collectionPostFix):
            raise RuntimeError, "Event already contains a jet collection with the following postfix: " + self.cfg_ana.collectionPostFix
        setattr(event, "rho" + self.cfg_ana.collectionPostFix, self.rho)
        setattr(event, "deltaMetFromJEC" + self.cfg_ana.collectionPostFix,
                self.deltaMetFromJEC)
        setattr(event, "type1METCorr" + self.cfg_ana.collectionPostFix,
                self.type1METCorr)
        setattr(event, "type1METCorrUp" + self.cfg_ana.collectionPostFix,
                self.type1METCorrUp)
        setattr(event, "type1METCorrDown" + self.cfg_ana.collectionPostFix,
                self.type1METCorrDown)
        setattr(event, "sumJetsInT1" + self.cfg_ana.collectionPostFix,
                self.sumJetsInT1)
        setattr(event, "allJetsUsedForMET" + self.cfg_ana.collectionPostFix,
                self.allJetsUsedForMET)
        setattr(event, "jets_raw" + self.cfg_ana.collectionPostFix,
                self.jets_raw)
        setattr(event, "jets" + self.cfg_ana.collectionPostFix, self.jets)
        setattr(event, "jetsFailId" + self.cfg_ana.collectionPostFix,
                self.jetsFailId)
        setattr(event, "jetsAllNoID" + self.cfg_ana.collectionPostFix,
                self.jetsAllNoID)
        setattr(event, "jetsIdOnly" + self.cfg_ana.collectionPostFix,
                self.jetsIdOnly)
        setattr(event, "cleanJetsAll" + self.cfg_ana.collectionPostFix,
                self.cleanJetsAll)
        setattr(event, "cleanJets" + self.cfg_ana.collectionPostFix,
                self.cleanJets)
        setattr(event, "cleanJetsFwd" + self.cfg_ana.collectionPostFix,
                self.cleanJetsFwd)
        setattr(event, "cleanJetsFailIdAll" + self.cfg_ana.collectionPostFix,
                self.cleanJetsFailIdAll)
        setattr(event, "cleanJetsFailId" + self.cfg_ana.collectionPostFix,
                self.cleanJetsFailId)
        setattr(event, "discardedJets" + self.cfg_ana.collectionPostFix,
                self.discardedJets)
        setattr(event, "gamma_cleanJetsAll" + self.cfg_ana.collectionPostFix,
                self.gamma_cleanJetsAll)
        setattr(event, "gamma_cleanJets" + self.cfg_ana.collectionPostFix,
                self.gamma_cleanJets)
        setattr(event, "gamma_cleanJetsFwd" + self.cfg_ana.collectionPostFix,
                self.gamma_cleanJetsFwd)
        setattr(event,
                "gamma_cleanJetsFailIdAll" + self.cfg_ana.collectionPostFix,
                self.gamma_cleanJetsFailIdAll)
        setattr(event,
                "gamma_cleanJetsFailId" + self.cfg_ana.collectionPostFix,
                self.gamma_cleanJetsFailId)

        if self.cfg_comp.isMC:
            setattr(event,
                    "deltaMetFromJetSmearing" + self.cfg_ana.collectionPostFix,
                    self.deltaMetFromJetSmearing)
            setattr(event, "cleanGenJets" + self.cfg_ana.collectionPostFix,
                    self.cleanGenJets)
            setattr(event, "genJets" + self.cfg_ana.collectionPostFix,
                    self.genJets)
            if self.cfg_ana.do_mc_match:
                setattr(event, "bqObjects" + self.cfg_ana.collectionPostFix,
                        self.bqObjects)
                setattr(event, "cqObjects" + self.cfg_ana.collectionPostFix,
                        self.cqObjects)
                setattr(event, "partons" + self.cfg_ana.collectionPostFix,
                        self.partons)
                setattr(event,
                        "heaviestQCDFlavour" + self.cfg_ana.collectionPostFix,
                        self.heaviestQCDFlavour)

        return True