Exemplo n.º 1
0
  def addRecoJetCollection(self,
    proc,
    jet,
    inputCollection    = "",
    minPtFastjet       = None,
    genJetsCollection  = "",
    bTagDiscriminators = ["None"],
    JETCorrLevels      = ["L1FastJet", "L2Relative", "L3Absolute", "L2L3Residual"],
    ):
    print("jetCollectionTools::RecoJetAdder::addRecoJetCollection: Adding Reco Jet Collection: {}".format(jet))

    currentTasks = []

    if inputCollection and inputCollection not in self.patJetsInMiniAOD:
      raise RuntimeError("Invalid input collection: %s" % inputCollection)
    
    #=======================================================
    #
    # Figure out which jet collection we're dealing with
    #
    #=======================================================
    recoJetInfo = RecoJetInfo(jet, inputCollection)
    jetLower = recoJetInfo.jetLower
    jetUpper = recoJetInfo.jetUpper
    tagName  = recoJetInfo.jetTagName

    if inputCollection == "slimmedJets":
      assert(jetLower == "ak4pfchs")
    elif inputCollection == "slimmedJetsAK8":
      assert(jetLower == "ak8pfpuppi")
    elif inputCollection == "slimmedJetsPuppi":
      assert(jetLower == "ak4pfpuppi")
    elif inputCollection == "slimmedCaloJets":
      assert(jetLower == "ak4calo")
    
    #=======================================================
    #
    # If the patJet collection in MiniAOD is not specified, 
    # we have to build the patJet collection from scratch.
    #
    #========================================================
    if not inputCollection or recoJetInfo.doCalo:
      print("jetCollectionTools::RecoJetAdder::addRecoJetCollection: inputCollection not specified. Building recojet collection now")

      #=======================================================
      #
      # Prepare the inputs to jet clustering
      #
      #========================================================
      #
      # Specify PF candidates
      #
      pfCand = self.pfLabel
      #
      # Setup PU method for PF candidates
      # 
      if recoJetInfo.jetPUMethod not in [ "", "cs" ]:
        pfCand += recoJetInfo.jetPUMethod

      
      #
      # Setup modules to perform PU mitigation for 
      # PF candidates
      #
      if pfCand not in self.prerequisites:
        #
        # Skip if no PU Method or CS specified
        #
        if recoJetInfo.jetPUMethod in [ "", "cs" ]:
          pass
        #
        # CHS
        #
        elif recoJetInfo.jetPUMethod == "chs":
          from CommonTools.ParticleFlow.pfCHS_cff import pfCHS, packedPrimaryVertexAssociationJME
          self.addProcessAndTask(proc, "packedPrimaryVertexAssociationJME", packedPrimaryVertexAssociationJME.clone())
          self.prerequisites.append("packedPrimaryVertexAssociationJME")
          self.addProcessAndTask(proc, pfCand, pfCHS.clone())
          self.prerequisites.append(pfCand)
        #
        # PUPPI
        #
        elif recoJetInfo.jetPUMethod == "puppi":
          self.addProcessAndTask(proc, pfCand, puppi.clone(
              candName = self.pfLabel,
              vertexName = self.pvLabel,
            )
          )
          self.prerequisites.append(pfCand)
        #
        # Softkiller
        #
        elif recoJetInfo.jetPUMethod == "sk":
          self.addProcessAndTask(proc, pfCand, softKiller.clone(
              PFCandidates = self.pfLabel,
              rParam = recoJetInfo.jetSizeNr,
            )
          )
          self.prerequisites.append(pfCand)
        else:
          raise RuntimeError("Currently unsupported PU method: '%s'" % recoJetInfo.jetPUMethod)
      
      #============================================
      #
      # Create the recojet collection
      #
      #============================================
      if not recoJetInfo.doCalo:
        jetCollection = '{}Collection'.format(jetUpper)

        if jetCollection in self.main:
          raise ValueError("Step '%s' already implemented" % jetCollection)
        #
        # Cluster new jet
        #
        if recoJetInfo.jetPUMethod == "chs":
          self.addProcessAndTask(proc, jetCollection, ak4PFJetsCHS.clone(
              src = pfCand,
            )
          )
        elif recoJetInfo.jetPUMethod == "puppi":
          self.addProcessAndTask(proc, jetCollection, ak4PFJetsPuppi.clone(
              src = self.pfLabel,
              srcWeights = pfCand
            )
          )
        elif recoJetInfo.jetPUMethod == "sk":
          self.addProcessAndTask(proc, pfCand, ak4PFJetsSK.clone(
              src = pfCand,
            )
          )
        elif recoJetInfo.jetPUMethod == "cs":
          self.addProcessAndTask(proc, jetCollection, ak4PFJetsCS.clone(
            src = pfCand,
          )
        )
        else:
          self.addProcessAndTask(proc, jetCollection, ak4PFJets.clone(
            src = pfCand,
          )
        )
        getattr(proc, jetCollection).jetAlgorithm = supportedJetAlgos[recoJetInfo.jetAlgo]
        getattr(proc, jetCollection).rParam = recoJetInfo.jetSizeNr
        #
        # Set minimum pt threshold of reco jets to be saved after fastjet clustering
        #
        if minPtFastjet != None:
          getattr(proc, jetCollection).jetPtMin = minPtFastjet
        currentTasks.append(jetCollection)
      else:
        jetCollection = inputCollection
      

      #=============================================
      #
      # Make patJet collection
      #
      #=============================================
      #
      # Jet correction 
      #
      if recoJetInfo.jetPUMethod == "puppi":
        jetCorrLabel = "Puppi"
      elif recoJetInfo.jetPUMethod in [ "cs", "sk" ]:
        jetCorrLabel = "chs"
      else:
        jetCorrLabel = recoJetInfo.jetPUMethod

      jetCorrections = (
        "{}{}{}{}".format(
          recoJetInfo.jetAlgo.upper(),
          recoJetInfo.jetSize,
          "Calo" if recoJetInfo.doCalo else recoJetInfo.jetReco.upper(),
          jetCorrLabel
        ),
        JETCorrLevels,
        "None",
      )

      postfix = "Recluster" if inputCollection == "" else ""
      addJetCollection(
        proc,
        labelName          = jetUpper,
        postfix            = postfix,
        jetSource          = cms.InputTag(jetCollection),
        algo               = recoJetInfo.jetAlgo,
        rParam             = recoJetInfo.jetSizeNr,
        pvSource           = cms.InputTag(self.pvLabel),
        pfCandidates       = cms.InputTag(self.pfLabel),
        svSource           = cms.InputTag(self.svLabel),
        muSource           = cms.InputTag(self.muLabel),
        elSource           = cms.InputTag(self.elLabel),
        genJetCollection   = cms.InputTag(genJetsCollection),
        genParticles       = cms.InputTag(self.gpLabel),
        jetCorrections     = jetCorrections,
      )

      #
      # Need to set this explicitly for PUPPI jets
      #
      if recoJetInfo.jetPUMethod == "puppi":
        getattr(proc, "patJetFlavourAssociation{}{}".format(jetUpper,postfix)).weights = cms.InputTag(pfCand)

      getJetMCFlavour = not recoJetInfo.doCalo and recoJetInfo.jetPUMethod != "cs"
      if not self.runOnMC: #Remove modules for Gen-level object matching
        delattr(proc, 'patJetGenJetMatch{}{}'.format(jetUpper,postfix))
        delattr(proc, 'patJetPartonMatch{}{}'.format(jetUpper,postfix))
        getJetMCFlavour = False 
      setattr(getattr(proc, "patJets{}{}".format(jetUpper,postfix)), "getJetMCFlavour", cms.bool(getJetMCFlavour))

      selectedPatJets = "selectedPatJets{}{}".format(jetUpper,postfix)
      #=============================================
      #
      # Update the patJet collection. 
      # This is where we setup 
      # -  JEC
      # -  b-tagging discriminators  
      # 
      #=============================================
      updateJetCollection(
        proc,
        labelName          = jetUpper,
        postfix            = "Final",
        jetSource          = cms.InputTag(selectedPatJets),
        jetCorrections     = jetCorrections,
        btagDiscriminators = bTagDiscriminators,
      )

      recoJetInfo.patJetFinalCollection = "selectedUpdatedPatJets{}{}".format(jetUpper,"Final")
    else:
      recoJetInfo.patJetFinalCollection = inputCollection

    self.main.extend(currentTasks)

    return recoJetInfo
Exemplo n.º 2
0
    def addRecoJetCollection(
        self,
        proc,
        jet,
        inputCollection="",
        genJetsCollection="",
        minPt=5.,
        bTagDiscriminators=None,
        JETCorrLevels=None,
    ):
        print(
            "jetCollectionTools::RecoJetAdder::addRecoJetCollection: Adding Reco Jet Collection: {}"
            .format(jet))

        currentTasks = []

        if inputCollection and inputCollection not in [
                "slimmedJets",
                "slimmedJetsAK8",
                "slimmedJetsPuppi",
                "slimmedCaloJets",
        ]:
            raise RuntimeError("Invalid input collection: %s" %
                               inputCollection)

        if bTagDiscriminators is None:
            bTagDiscriminators = self.bTagDiscriminators

        if JETCorrLevels is None:
            JETCorrLevels = self.JETCorrLevels

        #
        # Decide which jet collection we're dealing with
        #
        recoJetInfo = RecoJetInfo(jet, inputCollection)
        jetLower = recoJetInfo.jetLower
        jetUpper = recoJetInfo.jetUpper
        tagName = recoJetInfo.jetTagName

        if inputCollection == "slimmedJets":
            assert (jetLower == "ak4pfchs")
        elif inputCollection == "slimmedJetsAK8":
            assert (jetLower == "ak8pfpuppi")
        elif inputCollection == "slimmedJetsPuppi":
            assert (jetLower == "ak4pfpuppi")
        elif inputCollection == "slimmedCaloJets":
            assert (jetLower == "ak4calo")

        #=======================================================
        #
        # If jet collection in MiniAOD is not
        # specified, build the jet collection.
        #
        #========================================================
        if not inputCollection or recoJetInfo.doCalo:
            print(
                "jetCollectionTools::RecoJetAdder::addRecoJetCollection: inputCollection not specified. Building recojet collection now"
            )

            #=======================================================
            #
            # Prepare the inputs to jet clustering
            #
            #========================================================
            #
            # Set up PF candidates
            #
            pfCand = self.pfLabel
            #
            # Setup PU method for PF candidates
            #
            if recoJetInfo.jetPUMethod not in ["", "cs"]:
                pfCand += recoJetInfo.jetPUMethod
            #
            #
            #
            if pfCand not in self.prerequisites:
                #
                # Skip if no PU Method or CS specified
                #
                if recoJetInfo.jetPUMethod in ["", "cs"]:
                    pass
                #
                # CHS
                #
                elif recoJetInfo.jetPUMethod == "chs":
                    setattr(
                        proc, pfCand,
                        cms.EDFilter(
                            "CandPtrSelector",
                            src=cms.InputTag(self.pfLabel),
                            cut=cms.string("fromPV"),
                        ))
                    self.prerequisites.append(pfCand)
                #
                # PUPPI
                #
                elif recoJetInfo.jetPUMethod == "puppi":
                    setattr(
                        proc, pfCand,
                        puppi.clone(
                            candName=self.pfLabel,
                            vertexName=self.pvLabel,
                        ))
                    self.prerequisites.append(pfCand)
                #
                # Softkiller
                #
                elif recoJetInfo.jetPUMethod == "sk":
                    setattr(
                        proc, pfCand,
                        softKiller.clone(
                            PFCandidates=self.pfLabel,
                            rParam=recoJetInfo.jetSizeNr,
                        ))
                    self.prerequisites.append(pfCand)
                else:
                    raise RuntimeError(
                        "Currently unsupported PU method: '%s'" %
                        recoJetInfo.jetPUMethod)

            #============================================
            #
            # Create the recojet collection
            #
            #============================================
            if not recoJetInfo.doCalo:
                jetCollection = '{}Collection'.format(tagName)

                if jetCollection in self.main:
                    raise ValueError("Step '%s' already implemented" %
                                     jetCollection)

                setattr(
                    proc, jetCollection,
                    ak4PFJetsCS.clone(
                        src=pfCand,
                        doAreaFastjet=True,
                        jetPtMin=minPt,
                        jetAlgorithm=supportedJetAlgos[recoJetInfo.jetAlgo],
                        rParam=recoJetInfo.jetSizeNr,
                        useConstituentSubtraction=recoJetInfo.doCS,
                        csRParam=0.4 if recoJetInfo.doCS else -1.,
                        csRho_EtaMax=PFJetParameters.Rho_EtaMax
                        if recoJetInfo.doCS else -1.,
                        useExplicitGhosts=recoJetInfo.doCS
                        or recoJetInfo.jetPUMethod == "sk",
                    ))
                currentTasks.append(jetCollection)
            else:
                jetCollection = inputCollection

            #
            # PATify
            #
            if recoJetInfo.jetPUMethod == "puppi":
                jetCorrLabel = "Puppi"
            elif recoJetInfo.jetPUMethod in ["cs", "sk"]:
                jetCorrLabel = "chs"
            else:
                jetCorrLabel = recoJetInfo.jetPUMethod

            #
            # Jet correction
            #
            jetCorrections = (
                "{}{}{}{}".format(
                    recoJetInfo.jetAlgo.upper(), recoJetInfo.jetSize, "Calo"
                    if recoJetInfo.doCalo else recoJetInfo.jetReco.upper(),
                    jetCorrLabel),
                JETCorrLevels,
                "None",
            )

            addJetCollection(
                proc,
                labelName=tagName,
                jetSource=cms.InputTag(jetCollection),
                algo=recoJetInfo.jetAlgo,
                rParam=recoJetInfo.jetSizeNr,
                pvSource=cms.InputTag(self.pvLabel),
                pfCandidates=cms.InputTag(self.pfLabel),
                svSource=cms.InputTag(self.svLabel),
                muSource=cms.InputTag(self.muLabel),
                elSource=cms.InputTag(self.elLabel),
                btagDiscriminators=bTagDiscriminators
                if not recoJetInfo.doCalo else ["None"],
                jetCorrections=jetCorrections,
                genJetCollection=cms.InputTag(genJetsCollection),
                genParticles=cms.InputTag(self.gpLabel),
            )

            getJetMCFlavour = not recoJetInfo.doCalo and recoJetInfo.jetPUMethod != "cs"

            setattr(getattr(proc, "patJets{}".format(tagName)),
                    "getJetMCFlavour", cms.bool(getJetMCFlavour))
            setattr(getattr(proc, "patJetCorrFactors{}".format(tagName)),
                    "payload", cms.string(recoJetInfo.jetCorrPayload))
            selJet = "selectedPatJets{}".format(tagName)
        else:
            selJet = inputCollection

        if not recoJetInfo.skipUserData:
            #
            #
            #
            jercVar = "jercVars{}".format(tagName)
            if jercVar in self.main:
                raise ValueError("Step '%s' already implemented" % jercVar)
            setattr(proc, jercVar, proc.jercVars.clone(srcJet=selJet))
            currentTasks.append(jercVar)
            #
            #
            #
            looseJetId = "looseJetId{}".format(tagName)
            if looseJetId in self.main:
                raise ValueError("Step '%s' already implemented" % looseJetId)
            setattr(proc, looseJetId, proc.looseJetId.clone(src=selJet))
            #
            #
            #
            tightJetId = "tightJetId{}".format(tagName)
            if tightJetId in self.main:
                raise ValueError("Step '%s' already implemented" % tightJetId)
            setattr(proc, tightJetId, proc.tightJetId.clone(src=selJet))
            currentTasks.append(tightJetId)
            #
            #
            #
            tightJetIdLepVeto = "tightJetIdLepVeto{}".format(tagName)
            if tightJetIdLepVeto in self.main:
                raise ValueError("Step '%s' already implemented" %
                                 tightJetIdLepVeto)
            setattr(proc, tightJetIdLepVeto,
                    proc.tightJetIdLepVeto.clone(src=selJet))
            currentTasks.append(tightJetIdLepVeto)
            #
            #
            #
            selectedPatJetsWithUserData = "{}WithUserData".format(selJet)
            if selectedPatJetsWithUserData in self.main:
                raise ValueError("Step '%s' already implemented" %
                                 selectedPatJetsWithUserData)
            setattr(
                proc, selectedPatJetsWithUserData,
                cms.EDProducer(
                    "PATJetUserDataEmbedder",
                    src=cms.InputTag(selJet),
                    userFloats=cms.PSet(
                        jercCHPUF=cms.InputTag(
                            "{}:chargedHadronPUEnergyFraction".format(
                                jercVar)),
                        jercCHF=cms.InputTag(
                            "{}:chargedHadronCHSEnergyFraction".format(
                                jercVar)),
                    ),
                    userInts=cms.PSet(
                        tightId=cms.InputTag(tightJetId),
                        tightIdLepVeto=cms.InputTag(tightJetIdLepVeto),
                    ),
                ))
            for modifier in run2_miniAOD_80XLegacy, run2_nanoAOD_94X2016:
                selectedPatJetsWithUserDataObj = getattr(
                    proc, selectedPatJetsWithUserData)
                modifier.toModify(
                    selectedPatJetsWithUserDataObj.userInts,
                    looseId=looseJetId,
                    tightIdLepVeto=None,
                )
            currentTasks.append(selectedPatJetsWithUserData)
        else:
            selectedPatJetsWithUserData = "selectedPatJets{}".format(tagName)

        #
        # Not sure why we can't re-use patJetCorrFactors* created by addJetCollection()
        # (even cloning doesn't work) Let's just create our own
        #
        jetCorrFactors = "jetCorrFactors{}".format(tagName)
        if jetCorrFactors in self.main:
            raise ValueError("Step '%s' already implemented" % jetCorrFactors)

        setattr(
            proc, jetCorrFactors,
            patJetCorrFactors.clone(
                src=selectedPatJetsWithUserData,
                levels=JETCorrLevels,
                primaryVertices=self.pvLabel,
                payload=recoJetInfo.jetCorrPayload,
                rho="fixedGridRhoFastjetAll{}".format(
                    "Calo" if recoJetInfo.doCalo else ""),
            ))
        currentTasks.append(jetCorrFactors)

        updatedJets = "updatedJets{}".format(tagName)
        if updatedJets in self.main:
            raise ValueError("Step '%s' already implemented" % updatedJets)

        setattr(
            proc, updatedJets,
            updatedPatJets.clone(
                addBTagInfo=False,
                jetSource=selectedPatJetsWithUserData,
                jetCorrFactorsSource=[jetCorrFactors],
            ))

        currentTasks.append(updatedJets)
        self.main.extend(currentTasks)

        return recoJetInfo