def addFlashggPF(process, doQGTagging=True, label='', debug=False):

    from RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJets
    # process.ak4PFJets  = ak4PFJets.clone (src = 'packedPFCandidates', doAreaFastjet = True)
    setattr(process, 'ak4PFJets' + label,
            ak4PFJets.clone(src='packedPFCandidates', doAreaFastjet=True))

    # cluster the jets
    addJetCollection(process,
                     postfix=label,
                     labelName='AK4PF',
                     jetSource=cms.InputTag('ak4PFJets' + label),
                     pvSource=cms.InputTag('offlineSlimmedPrimaryVertices'),
                     pfCandidates=cms.InputTag('packedPFCandidates'),
                     svSource=cms.InputTag('slimmedSecondaryVertices'),
                     elSource=cms.InputTag("slimmedElectrons"),
                     muSource=cms.InputTag("slimmedMuons"),
                     runIVF=True,
                     btagDiscriminators=[
                         flashggBTag,
                         flashggCMVABTag,
                         flashggDeepCSVb,
                         flashggDeepCSVbb,
                         flashggDeepCSVc,
                         flashggDeepCSVudsg,
                     ],
                     jetCorrections=('AK4PFchs',
                                     ['L1FastJet', 'L2Relative',
                                      'L3Absolute'], 'None'),
                     genJetCollection=cms.InputTag('slimmedGenJets'),
                     genParticles=cms.InputTag('prunedGenParticles'),
                     algo='AK',
                     rParam=0.4)

    # adjust PV used for Jet Corrections
    # getattr(process, 'patJetCorrFactors'+_labelName+label)
    getattr(process, 'patJetCorrFactorsAK4PF' +
            label).primaryVertices = "offlineSlimmedPrimaryVertices"
    #process.patJetCorrFactorsAK4PF.primaryVertices = "offlineSlimmedPrimaryVertices"
    print ' --> patJetCorrFactorsAK4PF == ', getattr(
        process, 'patJetCorrFactorsAK4PF' + label)
    print ' --> patJetsAK4PF           == ', getattr(process,
                                                     'patJetsAK4PF' + label)
    flashggJetsPF = cms.EDProducer(
        'FlashggJetProducer',
        DiPhotonTag=cms.InputTag('flashggDiPhotons'),
        VertexTag=cms.InputTag('offlineSlimmedPrimaryVertices'),
        JetTag=cms.InputTag('patJetsAK4PF' + label),
        VertexCandidateMapTag=cms.InputTag("flashggVertexMapForCHS"),
        #                                 PileupJetIdParameters=cms.PSet(pu_jetid),
    )
    setattr(process, 'flashggJetsPF' + label, flashggJetsPF)
    if doQGTagging:
        from RecoJets.JetProducers.QGTagger_cfi import QGTagger
        setattr(
            process, 'QGTaggerPF' + label,
            QGTagger.clone(srcJets='flashggJetsPF' + label,
                           jetsLabel='QGL_AK4PF'))

    return getattr(process, 'flashggJetsPF' + label)
예제 #2
0
def addFlashggPF(process, doQGTagging =  True, label ='', debug = False):
  
  from RecoJets.JetProducers.ak4PFJets_cfi  import ak4PFJets
  # process.ak4PFJets  = ak4PFJets.clone (src = 'packedPFCandidates', doAreaFastjet = True)
  setattr(process, 'ak4PFJets' + label, ak4PFJets.clone (src = 'packedPFCandidates', doAreaFastjet = True))
  
  # cluster the jets
  addJetCollection(
    process,
    postfix            = label,
    labelName          = 'AK4PF' ,
    jetSource          = cms.InputTag('ak4PFJets'+label),
    pvSource           = cms.InputTag('offlineSlimmedPrimaryVertices'),
    pfCandidates       = cms.InputTag('packedPFCandidates'),
    svSource           = cms.InputTag('slimmedSecondaryVertices'),
    elSource       = cms.InputTag("slimmedElectrons"),
    muSource       = cms.InputTag("slimmedMuons"),
    runIVF         = True,
    btagDiscriminators = [ flashggBTag, flashggCMVABTag , flashggDeepCSVb, flashggDeepCSVbb, flashggDeepCSVc, flashggDeepCSVudsg, ],
    jetCorrections     = ('AK4PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),
    genJetCollection   = cms.InputTag('slimmedGenJets'),
    genParticles       = cms.InputTag('prunedGenParticles'),
    algo = 'AK', rParam = 0.4
  )

  # adjust PV used for Jet Corrections
  # getattr(process, 'patJetCorrFactors'+_labelName+label)
  getattr(process, 'patJetCorrFactorsAK4PF' + label).primaryVertices = "offlineSlimmedPrimaryVertices"
  #process.patJetCorrFactorsAK4PF.primaryVertices = "offlineSlimmedPrimaryVertices"
  print ' --> patJetCorrFactorsAK4PF == ',  getattr(process, 'patJetCorrFactorsAK4PF' + label)
  print ' --> patJetsAK4PF           == ',  getattr(process, 'patJetsAK4PF' + label)
  flashggJetsPF = cms.EDProducer('FlashggJetProducer',
                                 DiPhotonTag=cms.InputTag('flashggDiPhotons'),
                                 VertexTag=cms.InputTag('offlineSlimmedPrimaryVertices'),
                                 JetTag=cms.InputTag('patJetsAK4PF' + label ),
                                 VertexCandidateMapTag = cms.InputTag("flashggVertexMapForCHS"),
#                                 PileupJetIdParameters=cms.PSet(pu_jetid),
  )
  setattr(process, 'flashggJetsPF' + label, flashggJetsPF)
  if doQGTagging:
    from RecoJets.JetProducers.QGTagger_cfi import QGTagger
    setattr(process, 'QGTaggerPF' + label, QGTagger.clone( srcJets   = 'flashggJetsPF' + label ,jetsLabel = 'QGL_AK4PF'))
    
  return getattr(process, 'flashggJetsPF' + label)  
예제 #3
0
def addQGLikelihood(process,jetCollection,postfix):

    ## run evaluator
    from RecoJets.JetProducers.QGTagger_cfi import QGTagger

    if not hasattr(process,'QGTagger'+postfix):
        setattr(process,'QGTagger'+postfix, QGTagger.clone(
                srcJets = cms.InputTag(jetCollection),
                jetsLabel = cms.string('QGL_AK4PFchs'),
                srcVertexCollection   = cms.InputTag('offlineSlimmedPrimaryVertices')))

        ## modify jets
        setattr(process,jetCollection+"QG",
                updatedPatJets.clone(jetSource = cms.InputTag(jetCollection),
                                     addJetCorrFactors = cms.bool(False),
                                     jetCorrFactorsSource = cms.VInputTag()))

        
        getattr(process,jetCollection+"QG").userData.userFloats = cms.PSet(
            src = cms.VInputTag('QGTagger'+postfix+':qgLikelihood'))
        

    return jetCollection+"QG";
예제 #4
0
def makeFatJets(process, isData, label, candidates, ptMin=100.):
    """
    @param label: AK8PFchs, CA15PFPuppi, etc.
    """

    matches = re.match('(AK|CA)([0-9]+)PF(.+)', label)
    if not matches:
        raise RuntimeError('Unknown algo label ' + label)

    algo = matches.group(1) + matches.group(2)

    # set up radius and algoName from the input label
    radius = float(matches.group(2)) * 0.1
    if matches.group(1) == 'CA':
        algoName = 'CambridgeAachen'
    elif matches.group(1) == 'AK':
        algoName = 'AntiKt'

    pu = matches.group(3)

    if pu == 'chs':
        jecLabel = 'AK8PFchs'  # regardless of jet algo
    elif pu == 'Puppi':
        jecLabel = 'AK8PFPuppi'  # regardless of jet algo
    else:
        raise RuntimeError('Unknown PU mitigation ' + pu)

    sdZcut, sdBeta = sdParams(radius)

    sequence = cms.Sequence()

    # Callable object that adds the second argument to process and sequence with label attached as suffix
    addattr = AddAttr(process, sequence, label)

    ########################################
    ##           REMAKE JETS              ##
    ########################################

    pfJets = addattr(
        'pfJets',
        ak4PFJets.clone(
            doAreaFastjet=cms.bool(
                False
            ),  # This flag is turned on by default in CMSSW and makes things much slower, do not turn this on
            jetAlgorithm=cms.string(algoName),
            rParam=cms.double(radius),
            src=cms.InputTag(candidates),
            jetPtMin=cms.double(ptMin)))

    pfJetsSoftDrop = addattr(
        'pfJetsSoftDrop',
        ak4PFJets.clone(
            doAreaFastjet=cms.bool(
                False
            ),  # This flag is turned on by default in CMSSW and makes things much slower, do not turn this on
            jetAlgorithm=cms.string(algoName),
            rParam=cms.double(radius),
            src=cms.InputTag(candidates),
            jetPtMin=cms.double(ptMin),
            useSoftDrop=cms.bool(True),
            R0=cms.double(radius),
            zcut=cms.double(sdZcut),
            beta=cms.double(sdBeta),
            writeCompound=cms.bool(True),
            useExplicitGhosts=cms.bool(True),
            jetCollInstanceName=cms.string("SubJets")))
    subjets = cms.InputTag(pfJetsSoftDrop.getModuleLabel(), 'SubJets')

    pfJetsPruned = addattr(
        'pfJetsPruned',
        ak4PFJets.clone(
            doAreaFastjet=cms.bool(
                False
            ),  # This flag is turned on by default in CMSSW and makes things much slower, do not turn this on
            jetAlgorithm=cms.string(algoName),
            rParam=cms.double(radius),
            src=cms.InputTag(candidates),
            jetPtMin=cms.double(ptMin),
            usePruning=cms.bool(True),
            useExplicitGhosts=cms.bool(True),
            writeCompound=cms.bool(True),
            zcut=cms.double(0.1),  # no idea if these parameters are correct
            rcut_factor=cms.double(0.5),
            nFilt=cms.int32(2),
            jetCollInstanceName=cms.string("SubJets")))

    ########################################
    ##           SUBSTRUCTURE             ##
    #######################################

    Njettiness = addattr(
        'Njettiness',
        nJettinessAdder_cfi.Njettiness.clone(src=pfJets,
                                             R0=cms.double(radius),
                                             Njets=cms.vuint32(1, 2, 3, 4)))

    sdKinematics = addattr(
        'sdKinematics',
        cms.EDProducer('RecoJetDeltaRValueMapProducer',
                       src=pfJets,
                       matched=pfJetsSoftDrop,
                       distMax=cms.double(radius),
                       values=cms.vstring('mass'),
                       valueLabels=cms.vstring('Mass')))

    prunedKinematics = addattr(
        'prunedKinematics',
        cms.EDProducer('RecoJetDeltaRValueMapProducer',
                       src=pfJets,
                       matched=pfJetsPruned,
                       distMax=cms.double(radius),
                       values=cms.vstring('mass'),
                       valueLabels=cms.vstring('Mass')))

    ### subjet qg-tagging ###

    subQGTag = addattr(
        'subQGTag',
        QGTagger.clone(srcJets=subjets, jetsLabel=cms.string('QGL_AK4PFchs')))

    ########################################
    ##          MAKE PAT JETS             ##
    ########################################

    ## MAIN JET ##

    jecLevels = ['L1FastJet', 'L2Relative', 'L3Absolute']
    if isData:
        jecLevels.append('L2L3Residual')

    jetCorrFactors = addattr(
        'jetCorrFactors',
        jetUpdater_cff.patJetCorrFactors.clone(src=pfJets,
                                               payload=jecLabel,
                                               levels=jecLevels,
                                               primaryVertices=pvSource))

    if not isData:
        genJetMatch = addattr(
            'genJetMatch',
            patJetGenJetMatch.clone(src=pfJets,
                                    maxDeltaR=radius,
                                    matched='genJetsNoNu' + algo))

    patJets = addattr(
        'patJets',
        _patJets.clone(jetSource=pfJets,
                       addJetCorrFactors=True,
                       addBTagInfo=True,
                       addAssociatedTracks=False,
                       addJetCharge=False,
                       addGenPartonMatch=False,
                       addGenJetMatch=(not isData),
                       getJetMCFlavour=False,
                       addJetFlavourInfo=False))
    patJetsMod = addattr.last
    patJetsMod.jetCorrFactorsSource = [jetCorrFactors]
    patJetsMod.discriminatorSources = []
    if not isData:
        patJetsMod.genJetMatch = genJetMatch

    for tau in ['tau1', 'tau2', 'tau3', 'tau4']:
        patJetsMod.userData.userFloats.src.append(Njettiness.getModuleLabel() +
                                                  ':' + tau)

    patJetsMod.userData.userFloats.src.append(sdKinematics.getModuleLabel() +
                                              ':Mass')
    patJetsMod.userData.userFloats.src.append(
        prunedKinematics.getModuleLabel() + ':Mass')
    patJetsMod.userData.userFloats.labelPostfixesToStrip = cms.vstring(label)

    selectedPatJets = addattr(
        'selectedPatJets',
        jetSelector_cfi.selectedPatJets.clone(src=patJets,
                                              cut='abs(eta) < 2.5'))

    ## SOFT DROP ##

    patJetsSoftDrop = addattr(
        'patJetsSoftDrop',
        _patJets.clone(jetSource=pfJetsSoftDrop,
                       addJetCorrFactors=False,
                       addBTagInfo=False,
                       addAssociatedTracks=False,
                       addJetCharge=False,
                       addGenPartonMatch=False,
                       addGenJetMatch=False,
                       getJetMCFlavour=False,
                       addJetFlavourInfo=False))

    selectedPatJetsSoftDrop = addattr(
        'selectedPatJetsSoftDrop',
        jetSelector_cfi.selectedPatJets.clone(src=patJetsSoftDrop,
                                              cut='abs(eta) < 2.5'))

    ## GEN MATCH ##

    if not isData:
        genSubjetsMatch = addattr(
            'genSubjetMatch',
            patJetGenJetMatch.clone(src=subjets,
                                    maxDeltaR=0.4,
                                    matched='genJetsNoNuSoftDrop' + algo +
                                    ':SubJets'))

    ### SUBJETS ###

    patSubjets = addattr(
        'patSubjets',
        _patJets.clone(jetSource=subjets,
                       addJetCorrFactors=False,
                       addBTagInfo=False,
                       addAssociatedTracks=False,
                       addJetCharge=False,
                       addGenPartonMatch=False,
                       addGenJetMatch=(not isData),
                       getJetMCFlavour=False,
                       addJetFlavourInfo=False))
    patSubjetsMod = addattr.last
    patSubjetsMod.userData.userFloats.src.append(
        cms.InputTag(subQGTag.getModuleLabel(), 'qgLikelihood'))
    patSubjetsMod.userData.userFloats.labelPostfixesToStrip = cms.vstring(
        label)
    if not isData:
        patSubjetsMod.genJetMatch = genSubjetsMatch

    ## MERGE SUBJETS BACK ##
    jetMerger = addattr(
        'jetMerger',
        cms.EDProducer("BoostedJetMerger",
                       jetSrc=selectedPatJetsSoftDrop,
                       subjetSrc=patSubjets))

    ## PACK ##
    addattr(
        'packedPatJets',
        cms.EDProducer("JetSubstructurePacker",
                       jetSrc=selectedPatJets,
                       distMax=cms.double(radius),
                       algoTags=cms.VInputTag(jetMerger),
                       algoLabels=cms.vstring('SoftDrop'),
                       fixDaughters=cms.bool(False)))

    return sequence
def addFlashggPFCHSJets(process, vertexIndex = 0, doQGTagging = True, label ='', debug = False):
  setattr(process, 'selectedMuons' + label, cms.EDFilter("CandPtrSelector", 
                                                         src = cms.InputTag("slimmedMuons"), 
                                                         cut = cms.string('''abs(eta)<2.5 && pt>10. &&
                                                         (pfIsolationR04().sumChargedHadronPt+
                                                         max(0.,pfIsolationR04().sumNeutralHadronEt+
                                                         pfIsolationR04().sumPhotonEt-
                                                         0.50*pfIsolationR04().sumPUPt))/pt < 0.20 && 
                                                         (isPFMuon && (isGlobalMuon || isTrackerMuon) )''')))
  
  setattr(process, 'selectedElectrons' + label, cms.EDFilter("CandPtrSelector", 
                                                             src = cms.InputTag("slimmedElectrons"), 
                                                             cut = cms.string('''abs(eta)<2.5 && pt>20. &&
                                                             gsfTrack.isAvailable() &&
                                                             gsfTrack.hitPattern().numberOfLostHits(\'MISSING_INNER_HITS\') < 2 &&
                                                             (pfIsolationVariables().sumChargedHadronPt+
                                                             max(0.,pfIsolationVariables().sumNeutralHadronEt+
                                                             pfIsolationVariables().sumPhotonEt-
                                                             0.5*pfIsolationVariables().sumPUPt))/pt < 0.15''')))
  
  # Simple producer which just removes the Candidates which
  # don't come from the legacy vertex according to the Flashgg Vertex Map
  setattr(process,'flashggCHSLegacyVertexCandidates' + label,
          cms.EDProducer('FlashggMultiCHSLegacyVertexCandProducer',
                         PFCandidatesTag       = cms.InputTag('packedPFCandidates'),
                         DiPhotonTag           = cms.InputTag('flashggDiPhotons'),
                         VertexCandidateMapTag = cms.InputTag("flashggVertexMapForCHS"),
                         VertexTag             = cms.InputTag('offlineSlimmedPrimaryVertices'),
                         vertexIndex           = cms.untracked.uint32(vertexIndex),
                         debug                 = cms.untracked.bool(debug)
                       )
  )
  
  setattr(process, 'pfCHSLeg' + label, cms.EDFilter("CandPtrSelector", 
                                                    src = cms.InputTag('flashggCHSLegacyVertexCandidates' + label), 
                                                    cut = cms.string('')))
  
  # then remove the previously selected muons
  setattr(process, 'pfNoMuonCHSLeg' + label,  cms.EDProducer("CandPtrProjector", 
                                                             src  = cms.InputTag("pfCHSLeg" + label), 
                                                             veto = cms.InputTag("selectedMuons" + label)))
  # then remove the previously selected electrons
  setattr(process, 'pfNoElectronsCHSLeg' + label,  cms.EDProducer("CandPtrProjector", 
                                                                  src  = cms.InputTag("pfNoMuonCHSLeg" + label), 
                                                                  veto = cms.InputTag("selectedElectrons" + label)))
  
  #Import RECO jet producer for ak4 PF and GEN jet
  from RecoJets.JetProducers.ak4PFJets_cfi  import ak4PFJets
  #from RecoJets.JetProducers.ak4GenJets_cfi import ak4GenJets
  setattr(process, 'ak4PFJetsCHSLeg' + label, ak4PFJets.clone ( src = 'pfNoElectronsCHSLeg' + label, doAreaFastjet = True))
  #process.ak4GenJetsLeg   = ak4GenJets.clone( src = 'packedGenParticles')
  
  # NOTE: this is the 74X recipe for the jet clustering
  addJetCollection(
    process,
    postfix        = label,
    labelName      = 'AK4PFCHSLeg',
    jetSource      = cms.InputTag('ak4PFJetsCHSLeg' + label),
    pvSource       = cms.InputTag('offlineSlimmedPrimaryVertices'),
    pfCandidates   = cms.InputTag('packedPFCandidates'),
    svSource       = cms.InputTag('slimmedSecondaryVertices'),
    btagDiscriminators = [ flashggBTag ],
    jetCorrections = ('AK4PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),
    genJetCollection = cms.InputTag('slimmedGenJets'),
    genParticles     = cms.InputTag('prunedGenParticles'),
    # jet param
    algo = 'AK', rParam = 0.4
  )
  
  #adjust PV used for Jet Corrections
  #process.patJetCorrFactorsAK4PFCHSLeg.primaryVertices = "offlineSlimmedPrimaryVertices"
  getattr(process, 'patJetCorrFactorsAK4PFCHSLeg' + label).primaryVertices = "offlineSlimmedPrimaryVertices"

  # Flashgg Jet producer using the collection created with function above.
  flashggJets = cms.EDProducer('FlashggJetProducer',
                               DiPhotonTag = cms.InputTag('flashggDiPhotons'),
                               VertexTag   = cms.InputTag('offlineSlimmedPrimaryVertices'),
                               JetTag      = cms.InputTag('patJetsAK4PFCHSLeg' + label),
                               VertexCandidateMapTag = cms.InputTag("flashggVertexMapForCHS"),
#                               PileupJetIdParameters = cms.PSet(pu_jetid)
                             )
  setattr( process, 'flashggPFCHSJets'+ label, flashggJets)
  
  if doQGTagging:
    from RecoJets.JetProducers.QGTagger_cfi import QGTagger
    setattr( process, 'QGTaggerPFCHS' + label,  QGTagger.clone( srcJets   = 'flashggPFCHSJets' + label ,jetsLabel = 'ak4PFJetsCHS'))

  flashggSelectedJets = cms.EDFilter("FLASHggJetSelector",
                                     src = cms.InputTag( 'flashggPFCHSJets'+ label ),
                                     cut = cms.string("pt > 15.")
  )
  setattr( process, 'flashggSelectedPFCHSJets'+label, flashggSelectedJets )
예제 #6
0
    src=cms.InputTag('slimmedJets', '', cms.InputTag.skipCurrentProcess()),
    levels=cms.vstring(*jecLevels),
)

from RecoJets.JetProducers.QGTagger_cfi import QGTagger

process.slimmedJets = updatedPatJets.clone(
    jetSource=cms.InputTag('slimmedJets', '',
                           cms.InputTag.skipCurrentProcess()),
    addJetCorrFactors=cms.bool(True),
    jetCorrFactorsSource=cms.VInputTag(
        cms.InputTag("updatedPatJetCorrFactors")),
    addBTagInfo=cms.bool(False),
    addDiscriminators=cms.bool(False))

process.QGTagger = QGTagger.clone(srcJets='slimmedJets',
                                  jetsLabel=cms.string('QGL_AK4PFchs'))

jetRecorrectionSequence = cms.Sequence(process.updatedPatJetCorrFactors +
                                       process.slimmedJets + process.QGTagger)

### MET
from PandaProd.Producer.utils.makeMET_cff import initMET, makeMET

initMetSequence = initMET(process, False)

# extracts the raw pfMET from input MINIAOD and repack new corrections
pfMetSequence = makeMET(process, False, 'packedPFCandidates', 'slimmedJets',
                        'AK4PFchs')
# compute a brand-new pfMET from puppi candidates and pack with corrections
puppiMetSequence = makeMET(process, False, 'puppiForMET', 'selectedJetsPuppi',
                           'AK4PFPuppi', 'Puppi')
def jetToolbox( proc, jetType, jetSequence,PUMethod='', bTagDiscriminators = None):

	JETCorrPayload='None'
	JETCorrLevels = [ 'None' ]
	bTagDiscriminators = [#'trackCountingHighEffBJetTags',
                          #'trackCountingHighPurBJetTags',
                          #'pfTrackCountingHighEffBJetTags',
                          #'pfTrackCountingHighPurBJetTags',
                          #'softPFMuonByIP3dBJetTags',
                          #'softPFElectronByIP3dBJetTags',
                          #'softPFMuonBJetTags',
                          #'softPFElectronBJetTags',
                          #'simpleSecondaryVertexHighEffBJetTags',
                          #'simpleSecondaryVertexHighPurBJetTags',
                          #'pfSimpleSecondaryVertexHighEffBJetTags',
                          #'pfSimpleSecondaryVertexHighPurBJetTags',
                          #'combinedSecondaryVertexV2BJetTags',
                          'deepFlavourJetTags:probb',
                          'deepFlavourJetTags:probc',
                          'deepFlavourJetTags:probudsg',
                          'deepFlavourJetTags:probbb',
                          'deepFlavourJetTags:probcc',
                          'negativeDeepFlavourJetTags:probb',
                          'negativeDeepFlavourJetTags:probc',
                          'negativeDeepFlavourJetTags:probudsg',
                          'negativeDeepFlavourJetTags:probbb',
                          'negativeDeepFlavourJetTags:probcc',
                          'positiveDeepFlavourJetTags:probb',
                          'positiveDeepFlavourJetTags:probc',
                          'positiveDeepFlavourJetTags:probudsg',
                          'positiveDeepFlavourJetTags:probbb',
                          'positiveDeepFlavourJetTags:probcc',
                          'pfCombinedCvsLJetTags',
                          'pfCombinedCvsBJetTags',
                          'pfBoostedDoubleSecondaryVertexAK8BJetTags',
                          'pfCombinedSecondaryVertexV2BJetTags',
                          'pfPositiveCombinedSecondaryVertexV2BJetTags',  #implemented
                          'pfNegativeCombinedSecondaryVertexV2BJetTags',  #implemented
                          'pfCombinedInclusiveSecondaryVertexV2BJetTags', #implemented
                          'pfCombinedMVAV2BJetTags',                      #implemented
                          'pfJetProbabilityBJetTags']                     #implemented

	GetJetMCFlavour = ['True']
        #JECLevels = [ 'L1Offset', 'L1FastJet', 'L1JPTOffset', 'L2Relative', 'L3Absolute', 'L5Falvour', 'L7Parton' ]

	algorithm='AntiKt' # CambridgeAachen' , 'Kt'
	size = jetType[-1:] #[-1:] takes the last char from string 'akX'
	jetSize = float('0.'+jetType[-1:])
	jetALGO = jetType.upper()
	jetalgo = jetType.lower()
	elemToKeep = []

	print 'Running processes with: '+str(jetALGO)+' PF '+PUMethod+' jet algorithm with radius parameter '+str(jetSize)

	JETCorrPayload = 'AK'+size+'PF'+PUMethod.lower()
	JETCorrLevels = ['L1FastJet', 'L2Relative', 'L3Absolute']
	#JETCorrLevels = [] #No JEC corrections
	JEC = ( JETCorrPayload, JETCorrLevels , 'None')

	#################################################################################
	####### Toolbox start
	#################################################################################

	elemToKeep = []
	jetSeq = cms.Sequence()
	genParticlesLabel = ''
	pvLabel = ''
	tvLabel = ''
	toolsUsed = []

	proc.load('RecoJets.Configuration.GenJetParticles_cff')
	setattr( proc, jetalgo+'GenJetsNoNu', ak4GenJets.clone( src = 'genParticlesForJetsNoNu', rParam = jetSize, jetAlgorithm = algorithm ) )
	jetSeq += getattr(proc, jetalgo+'GenJetsNoNu' )

	proc.load('CommonTools.ParticleFlow.pfNoPileUpJME_cff')
	####  Creating PATjets
	if( PUMethod=='CHS') :
	  setattr( proc, jetalgo+'PFJetsCHS', ak4PFJets.clone( rParam = jetSize, jetAlgorithm = algorithm ) )
	  jetSeq += getattr(proc, jetalgo+'PFJetsCHS' )

	  setattr( proc, jetalgo+'PFJetsCHS',
			  ak4PFJetsCHS.clone(
				  doAreaFastjet = True,
				  rParam = jetSize,
				  jetAlgorithm = algorithm ) )
	  jetSeq += getattr(proc, jetalgo+'PFJetsCHS' )

	else :
	  setattr( proc, jetalgo+'PFJets', ak4PFJets.clone( rParam = jetSize, jetAlgorithm = algorithm ) )
	  jetSeq += getattr(proc, jetalgo+'PFJets' )

	  setattr( proc, jetalgo+'PFJets',
			  ak4PFJets.clone(
				  doAreaFastjet = True,
				  rParam = jetSize,
				  jetAlgorithm = algorithm ) )
	  jetSeq += getattr(proc, jetalgo+'PFJets' )
	  PUMethod=''


	addJetCollection(
			proc,
			labelName = jetALGO+'PF'+PUMethod,
			jetSource = cms.InputTag( jetalgo+'PFJets'+PUMethod),
			algo = jetalgo,
			btagDiscriminators = bTagDiscriminators,
			rParam = jetSize,
			jetCorrections =  JEC, #( 'AK'+size+'PFchs', cms.vstring( ['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
			pfCandidates = cms.InputTag( 'particleFlow' ),  #'packedPFCandidates'),
			svSource = cms.InputTag('inclusiveCandidateSecondaryVertices'),
			genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNu'),
			pvSource = cms.InputTag( 'offlinePrimaryVertices' ), #'offlineSlimmedPrimaryVertices'),
			jetTrackAssociation = True,

			)

	#setattr( proc, jetALGO+'PF'+PUMethod+'pileupJetIdCalculator',
#			pileupJetIdCalculator.clone(
#				jets = cms.InputTag(jetalgo+'PFJets'+PUMethod),
#				rho = cms.InputTag("fixedGridRhoFastjetAll"),
#				vertexes = cms.InputTag('offlinePrimaryVertices'),
#				applyJec = cms.bool(True),
#				inputIsCorrected = cms.bool(False)
#				))

#	setattr( proc, jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator',
#			pileupJetIdEvaluator.clone(
#				jetids = cms.InputTag(jetALGO+'PF'+PUMethod+'pileupJetIdCalculator'),
#				jets = cms.InputTag(jetalgo+'PFJets'+PUMethod),
#				rho = cms.InputTag("fixedGridRhoFastjetAll"),
#				vertexes = cms.InputTag('offlinePrimaryVertices'),
#                               applyJec = cms.bool(True),
#                                inputIsCorrected = cms.bool(False)
#
#				)
#			)

	#getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator:fullDiscriminant']
	#getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userInts.src += [jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator:cutbasedId',jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator:fullId']

	QGjetsLabel='chs'

	setattr( proc, 'QGTagger'+jetALGO+'PF'+PUMethod,
		 QGTagger.clone(
			srcJets = cms.InputTag(jetalgo+'PFJets'+PUMethod),    # Could be reco::PFJetCollection or pat::JetCollection (both AOD and miniAOD)
			jetsLabel = cms.string('QGL_AK4PF'+QGjetsLabel)        # Other options (might need to add an ESSource for it): see https://twiki.cern.ch/twiki/bi
			)
		 )
	elemToKeep += [ 'keep *_QGTagger'+jetALGO+'PF'+PUMethod+'_*_*' ]
	getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += ['QGTagger'+jetALGO+'PF'+PUMethod+':qgLikelihood']
	jetSeq += getattr(proc, 'QGTagger'+jetALGO+'PF'+PUMethod )

	toolsUsed.append( 'QGTagger'+jetALGO+'PF'+PUMethod )

	getattr(proc,'patJetPartons').particles = cms.InputTag( 'genParticles' ) #'prunedGenParticles')
	setattr(proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod, selectedPatJets.clone( src = 'patJets'+jetALGO+'PF'+PUMethod ) )
	setattr(proc, jetSequence, jetSeq)
예제 #8
0
파일: nano_cff.py 프로젝트: ilaflott/cmssw
def nanoAOD_customizeData(process):
    process = nanoAOD_customizeCommon(process)
    process.calibratedPatElectrons.isMC = cms.bool(False)
    process.calibratedPatPhotons.isMC = cms.bool(False)
    return process

def nanoAOD_customizeMC(process):
    process = nanoAOD_customizeCommon(process)
    process.calibratedPatElectrons.isMC = cms.bool(True)
    process.calibratedPatPhotons.isMC = cms.bool(True)
    return process

### Era dependent customization
from Configuration.Eras.Modifier_run2_miniAOD_80XLegacy_cff import run2_miniAOD_80XLegacy
from RecoJets.JetProducers.QGTagger_cfi import  QGTagger
qgtagger80x=QGTagger.clone(srcJets="slimmedJets",srcVertexCollection="offlineSlimmedPrimaryVertices")
_80x_sequence = nanoSequence.copy()
#remove stuff 
_80x_sequence.remove(isoTrackTable)
_80x_sequence.remove(isoTrackSequence)
#add qgl
_80x_sequence.insert(1,qgtagger80x)

_80x_sequenceMC = nanoSequenceMC.copy()
_80x_sequenceMC.remove(genSubJetAK8Table)
_80x_sequenceMC.remove(genJetFlavourTable)
_80x_sequenceMC.insert(-1,genJetFlavourAssociation)
_80x_sequenceMC.insert(-1,genJetFlavourTable)
run2_miniAOD_80XLegacy.toReplaceWith( nanoSequence, _80x_sequence)
run2_miniAOD_80XLegacy.toReplaceWith( nanoSequenceMC, _80x_sequenceMC)
예제 #9
0
def addFlashggPFCHSJets(
        process,
        isData,
        vertexIndex=0,
        #doQGTagging = True,
        label='',
        debug=False):
    setattr(
        process, 'selectedMuons' + label,
        cms.EDFilter("CandPtrSelector",
                     src=cms.InputTag("slimmedMuons"),
                     cut=cms.string('''abs(eta)<2.5 && pt>10. &&
                                                         (pfIsolationR04().sumChargedHadronPt+
                                                         max(0.,pfIsolationR04().sumNeutralHadronEt+
                                                         pfIsolationR04().sumPhotonEt-
                                                         0.50*pfIsolationR04().sumPUPt))/pt < 0.20 && 
                                                         (isPFMuon && (isGlobalMuon || isTrackerMuon) )'''
                                    )))

    setattr(
        process, 'selectedElectrons' + label,
        cms.EDFilter("CandPtrSelector",
                     src=cms.InputTag("slimmedElectrons"),
                     cut=cms.string('''abs(eta)<2.5 && pt>20. &&
                                                             gsfTrack.isAvailable() &&
                                                             gsfTrack.hitPattern().numberOfLostHits(\'MISSING_INNER_HITS\') < 2 &&
                                                             (pfIsolationVariables().sumChargedHadronPt+
                                                             max(0.,pfIsolationVariables().sumNeutralHadronEt+
                                                             pfIsolationVariables().sumPhotonEt-
                                                             0.5*pfIsolationVariables().sumPUPt))/pt < 0.15'''
                                    )))

    # Simple producer which just removes the Candidates which
    # don't come from the legacy vertex according to the Flashgg Vertex Map
    setattr(
        process, 'flashggCHSLegacyVertexCandidates' + label,
        cms.EDProducer(
            'FlashggMultiCHSLegacyVertexCandProducer',
            PFCandidatesTag=cms.InputTag('packedPFCandidates'),
            DiPhotonTag=cms.InputTag('flashggDiPhotons'),
            VertexCandidateMapTag=cms.InputTag("flashggVertexMapForCHS"),
            VertexTag=cms.InputTag('offlineSlimmedPrimaryVertices'),
            vertexIndex=cms.uint32(vertexIndex),
            debug=cms.untracked.bool(debug)))

    setattr(
        process, 'pfCHSLeg' + label,
        cms.EDFilter("CandPtrSelector",
                     src=cms.InputTag('flashggCHSLegacyVertexCandidates' +
                                      label),
                     cut=cms.string('')))

    # then remove the previously selected muons
    setattr(
        process, 'pfNoMuonCHSLeg' + label,
        cms.EDProducer("CandPtrProjector",
                       src=cms.InputTag("pfCHSLeg" + label),
                       veto=cms.InputTag("selectedMuons" + label)))
    # then remove the previously selected electrons
    setattr(
        process, 'pfNoElectronsCHSLeg' + label,
        cms.EDProducer("CandPtrProjector",
                       src=cms.InputTag("pfNoMuonCHSLeg" + label),
                       veto=cms.InputTag("selectedElectrons" + label)))

    #Import RECO jet producer for ak4 PF and GEN jet
    from RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJets
    setattr(
        process, 'ak4PFJetsCHSLeg' + label,
        ak4PFJets.clone(src='pfNoElectronsCHSLeg' + label, doAreaFastjet=True))

    if isData:
        JECs = ['L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual']
    else:
        JECs = ['L1FastJet', 'L2Relative', 'L3Absolute']

    # NOTE: this is the 74X recipe for the jet clustering
    addJetCollection(
        process,
        postfix=label,
        labelName='AK4PFCHSLeg',
        jetSource=cms.InputTag('ak4PFJetsCHSLeg' + label),
        pvSource=cms.InputTag('offlineSlimmedPrimaryVertices'),
        pfCandidates=cms.InputTag('packedPFCandidates'),
        svSource=cms.InputTag('slimmedSecondaryVertices'),
        btagDiscriminators=[flashggBTag],
        jetCorrections=('AK4PFchs', JECs, 'None'),
        genJetCollection=cms.InputTag('slimmedGenJets'),
        genParticles=cms.InputTag('prunedGenParticles'),
        # jet param
        algo='AK',
        rParam=0.4,
        btagInfos=['pfImpactParameterTagInfos',
                   'pfSecondaryVertexTagInfos']  #Extra btagging info
    )

    #Recalculate btagging info
    getattr(process, 'patJetsAK4PFCHSLeg' + label).addTagInfos = True

    #adjust PV used for Jet Corrections
    #process.patJetCorrFactorsAK4PFCHSLeg.primaryVertices = "offlineSlimmedPrimaryVertices"
    getattr(process, 'patJetCorrFactorsAK4PFCHSLeg' +
            label).primaryVertices = "offlineSlimmedPrimaryVertices"

    if not hasattr(process, "QGPoolDBESSource"):
        process.QGPoolDBESSource = cms.ESSource(
            "PoolDBESSource",
            CondDBSetup,
            toGet=cms.VPSet(),
            connect=cms.string('sqlite:QGL_' + qgDatabaseVersion + '.db'))
        process.es_prefer_qg = cms.ESPrefer('PoolDBESSource',
                                            'QGPoolDBESSource')

    for type in ['AK4PFchs']:  #,'AK4PFchs_antib']:
        process.QGPoolDBESSource.toGet.extend(
            cms.VPSet(
                cms.PSet(record=cms.string('QGLikelihoodRcd'),
                         tag=cms.string('QGLikelihoodObject_' +
                                        qgDatabaseVersion + '_' + type),
                         label=cms.untracked.string('QGL_' + type))))

    from RecoJets.JetProducers.QGTagger_cfi import QGTagger
    setattr(
        process, 'QGTaggerPFCHS' + label,
        QGTagger.clone(srcJets='patJetsAK4PFCHSLeg' + label,
                       jetsLabel='QGL_AK4PFchs',
                       vertexIndex=cms.uint32(vertexIndex),
                       srcVertexCollection='offlineSlimmedPrimaryVertices'))

    from RecoJets.JetProducers.PileupJetIDParams_cfi import full_80x_chs

    flashggJets = cms.EDProducer(
        'FlashggJetProducer',
        DiPhotonTag=cms.InputTag('flashggDiPhotons'),
        VertexTag=cms.InputTag('offlineSlimmedPrimaryVertices'),
        JetTag=cms.InputTag('patJetsAK4PFCHSLeg' + label),
        VertexCandidateMapTag=cms.InputTag("flashggVertexMapForCHS"),
        qgVariablesInputTag=cms.InputTag('QGTaggerPFCHS' + label,
                                         'qgLikelihood'),
        ComputeSimpleRMS=cms.bool(True),
        ComputeRegVars=cms.bool(True),
        PileupJetIdParameters=full_80x_chs,
        rho=cms.InputTag("fixedGridRhoFastjetAll"),
        JetCollectionIndex=cms.uint32(vertexIndex),
        Debug=cms.untracked.bool(False))
    setattr(process, 'flashggPFCHSJets' + label, flashggJets)

    # randomize Jets
    from flashgg.MicroAOD.flashggRandomizedJetProducer_cfi import flashggRandomizedJets
    flashggRandomizedPFCHSJets = flashggRandomizedJets.clone()
    flashggRandomizedPFCHSJets.src = "flashggPFCHSJets" + label
    setattr(process.RandomNumberGeneratorService,
            'flashggRandomizedPFCHSJets' + label,
            cms.PSet(initialSeed=cms.untracked.uint32(36423784 + int(label))))
    setattr(process, 'flashggRandomizedPFCHSJets' + label,
            flashggRandomizedPFCHSJets)

    flashggSelectedJets = cms.EDFilter(
        "FLASHggJetSelector",
        src=cms.InputTag('flashggRandomizedPFCHSJets' + label),
        cut=cms.string("pt > 15."))
    setattr(process, 'flashggSelectedPFCHSJets' + label, flashggSelectedJets)
예제 #10
0
def addFlashggPFCHSJets(
        process,
        DeepJet,
        isData,
        vertexIndex=0,
        #doQGTagging = True,
        label='',
        debug=False):

    setattr(
        process, 'pfCHSLeg' + label,
        cms.EDFilter("CandPtrSelector",
                     src=cms.InputTag("packedPFCandidates"),
                     cut=cms.string("fromPV(%i)" % vertexIndex)))
    #Import RECO jet producer for ak4 PF and GEN jet
    from RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJets
    setattr(process, 'ak4PFJetsCHSLeg' + label,
            ak4PFJets.clone(src='pfCHSLeg' + label, doAreaFastjet=True))

    if isData:
        JECs = ['L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual']
    else:
        JECs = ['L1FastJet', 'L2Relative', 'L3Absolute']

    # NOTE: this is the 74X recipe for the jet clustering - has been confirmed to give reasonable results in 10X
    addJetCollection(
        process,
        postfix=label,
        labelName='AK4PFCHSLeg',
        jetSource=cms.InputTag('ak4PFJetsCHSLeg' + label),
        pvSource=cms.InputTag('offlineSlimmedPrimaryVertices'),
        pfCandidates=cms.InputTag('packedPFCandidates'),
        svSource=cms.InputTag('slimmedSecondaryVertices'),
        elSource=cms.InputTag("slimmedElectrons"),
        muSource=cms.InputTag("slimmedMuons"),
        runIVF=True,
        btagDiscriminators=[
            flashggBTag, flashggCMVABTag, flashggDeepCSVb, flashggDeepCSVbb,
            flashggDeepCSVc, flashggDeepCSVudsg
        ],
        jetCorrections=('AK4PFchs', JECs, 'None'),
        genJetCollection=cms.InputTag('slimmedGenJets'),
        genParticles=cms.InputTag('prunedGenParticles'),
        # jet param
        algo='AK',
        rParam=0.4
        #btagInfos =  ['pfImpactParameterTagInfos', 'pfSecondaryVertexTagInfos', 'pfInclusiveSecondaryVertexFinderTagInfos', 'softPFMuonsTagInfos', 'softPFElectronsTagInfos'] #Extra Btagging Info
    )

    #Recalculate btagging info
    getattr(process, 'patJetsAK4PFCHSLeg' + label).addTagInfos = True

    #adjust PV used for Jet Corrections
    #process.patJetCorrFactorsAK4PFCHSLeg.primaryVertices = "offlineSlimmedPrimaryVertices"
    getattr(process, 'patJetCorrFactorsAK4PFCHSLeg' +
            label).primaryVertices = "offlineSlimmedPrimaryVertices"

    if DeepJet == "rerun":
        from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
        updateJetCollection(
            process,
            jetSource=cms.InputTag("slimmedJets"),
            pvSource=cms.InputTag('offlineSlimmedPrimaryVertices'),
            svSource=cms.InputTag('slimmedSecondaryVertices'),
            btagDiscriminators=[
                flashggDeepFlavourb,
                flashggDeepFlavourbb,
                flashggDeepFlavourc,
                flashggDeepFlavouruds,
                flashggDeepFlavourlepb,
                flashggDeepFlavourg,
            ],
            jetCorrections=('AK4PFchs', JECs, 'None'),
        )
        miniaodJets = "selectedUpdatedPatJets"
    else:
        miniaodJets = "slimmedJets"

    if not hasattr(process, "QGPoolDBESSource"):
        process.QGPoolDBESSource = cms.ESSource(
            "PoolDBESSource",
            #CondDB,
            toGet=cms.VPSet(),
            connect=cms.string('sqlite:QGL_' + qgDatabaseVersion + '.db'))
        process.es_prefer_qg = cms.ESPrefer('PoolDBESSource',
                                            'QGPoolDBESSource')

    for type in ['AK4PFchs']:  #,'AK4PFchs_antib']:
        process.QGPoolDBESSource.toGet.extend(
            cms.VPSet(
                cms.PSet(record=cms.string('QGLikelihoodRcd'),
                         tag=cms.string('QGLikelihoodObject_v1_AK4'),
                         label=cms.untracked.string('QGL_' + type))))

    from RecoJets.JetProducers.QGTagger_cfi import QGTagger
    setattr(
        process, 'QGTaggerPFCHS' + label,
        QGTagger.clone(srcJets='patJetsAK4PFCHSLeg' + label,
                       jetsLabel='QGL_AK4PFchs',
                       vertexIndex=cms.uint32(vertexIndex),
                       srcVertexCollection='offlineSlimmedPrimaryVertices'))

    from RecoJets.JetProducers.PileupJetIDParams_cfi import full_81x_chs
    pujidparam = full_81x_chs

    flashggJets = cms.EDProducer(
        'FlashggJetProducer',
        DiPhotonTag=cms.InputTag('flashggDiPhotons'),
        VertexTag=cms.InputTag('offlineSlimmedPrimaryVertices'),
        JetTag=cms.InputTag('patJetsAK4PFCHSLeg' + label),
        VertexCandidateMapTag=cms.InputTag("flashggVertexMapForCHS"),
        qgVariablesInputTag=cms.InputTag('QGTaggerPFCHS' + label,
                                         'qgLikelihood'),
        ComputeSimpleRMS=cms.bool(True),
        PileupJetIdParameters=pujidparam,
        rho=cms.InputTag("fixedGridRhoFastjetAll"),
        JetCollectionIndex=cms.uint32(vertexIndex),
        Debug=cms.untracked.bool(debug),
        DoPuJetID=cms.bool(True),
        ComputeRegVars=cms.bool(True),
        MinPtForEneSum=cms.double(0.),
        MaxEtaForEneSum=cms.double(2.5),
        NJetsForEneSum=cms.uint32(0),
        MiniAodJetTag=cms.InputTag(miniaodJets))
    setattr(process, 'flashggPFCHSJets' + label, flashggJets)

    # randomize Jets
    from flashgg.MicroAOD.flashggRandomizedJetProducer_cfi import flashggRandomizedJets
    flashggRandomizedPFCHSJets = flashggRandomizedJets.clone()
    flashggRandomizedPFCHSJets.src = "flashggPFCHSJets" + label
    setattr(process.RandomNumberGeneratorService,
            'flashggRandomizedPFCHSJets' + label,
            cms.PSet(initialSeed=cms.untracked.uint32(36423784 + int(label))))
    setattr(process, 'flashggRandomizedPFCHSJets' + label,
            flashggRandomizedPFCHSJets)

    flashggSelectedJets = cms.EDFilter(
        "FLASHggJetSelector",
        src=cms.InputTag('flashggRandomizedPFCHSJets' + label),
        cut=cms.string("pt > 15."))
    setattr(process, 'flashggSelectedPFCHSJets' + label, flashggSelectedJets)
예제 #11
0
def JetSubstructure(process,
                    isMC,
                    coneSize=0.8,
                    algo="AK",
                    pileupMethod="chs",
                    selection="pt > 175 && abs(eta) < 2.5",
                    addPruning=True,
                    addPrunedSubjets=True,
                    addSoftDrop=True,
                    addSoftDropSubjets=True,
                    addTrimming=False,
                    addTrimmedSubjets=False,
                    addFiltering=False,
                    addFilteredSubjets=False,
                    addNsubjettiness=True,
                    addEnergyCorrelation=True,
                    addQJets=False,
                    addQGLikelihood=True):

    print "############################"
    print "add substructure information"
    print "isMC             = ", isMC
    print "coneSize         = ", coneSize
    print "algo             = ", algo
    print "pileupMethod     = ", pileupMethod
    print "selection        = ", selection
    print "addPruning       = ", addPruning
    print "addPrunedSubjets = ", addPrunedSubjets
    print "addSoftDrop      = ", addSoftDrop
    print "addSoftDropSubjets = ", addSoftDropSubjets
    print "addTrimming        = ", addTrimming
    print "addTrimmedSubjets  = ", addTrimmedSubjets
    print "addFiltering       = ", addFiltering
    print "addFilteredSubjets = ", addFilteredSubjets
    print "addNsubjettiness   = ", addNsubjettiness
    print "addEnergyCorrelation = ", addEnergyCorrelation
    print "addQJets             = ", addQJets
    print "addQGLikelihood      = ", addQGLikelihood
    print "############################"

    ## build jet algo name for jet clustering
    coneSizeStr = str(coneSize).replace("0", "").replace(".", "")
    jetAlgo = algo + coneSizeStr
    if algo == "AK":
        ALGO = "AntiKt"
    elif algo == "CA":
        ALGO = "CambridgeAachen"

    if isMC:
        ## run gen jet clustering from genParticles
        if not hasattr(process, "genParticlesForJetsNoNu"):
            setattr(
                process, 'genParticlesForJetsNoNu',
                cms.EDFilter(
                    "CandPtrSelector",
                    src=cms.InputTag("packedGenParticles"),
                    cut=cms.string(
                        "abs(pdgId) != 12 && abs(pdgId) != 14 && abs(pdgId) != 16 && abs(pdgId) != 1000022 && abs(pdgId) != 1000012 &&"
                        +
                        "abs(pdgId) != 1000014 && abs(pdgId) != 1000016 && abs(pdgId) != 2000012 && abs(pdgId) != 2000014 &&"
                        +
                        "abs(pdgId) != 2000016 && abs(pdgId) != 1000039 && abs(pdgId) != 5100039 && abs(pdgId) != 4000012 &&"
                        +
                        "abs(pdgId) != 4000014 && abs(pdgId) != 4000016 && abs(pdgId) != 9900012 && abs(pdgId) != 9900014 &&"
                        +
                        "abs(pdgId) != 9900016 && abs(pdgId) != 39 && abs(pdgId) != 9100012"
                    )))  ## skip all the possible invisible particles

        if not hasattr(process, "genJets" + jetAlgo):
            setattr(
                process, "genJets" + jetAlgo,
                ak4GenJets.clone(src='genParticlesForJetsNoNu',
                                 rParam=coneSize,
                                 jetAlgorithm=ALGO,
                                 jetPtMin=cms.double(50.))
            )  ## fix a lower reasonable threshold give the jet response

        ## filter only hadronically decaying W/Z and Higgs at generator level
        if not hasattr(process, "genBosons"):
            setattr(
                process, "genBosons",
                cms.EDFilter(
                    "CandPtrSelector",
                    src=cms.InputTag("prunedGenParticles"),
                    cut=cms.string(
                        "(abs(pdgId) == 23 || abs(pdgId) == 24 || abs(pdgId) == 25) &&"
                        +
                        "numberOfDaughters > 1 && abs(daughter(0).pdgId) <= 5 && abs(daughter(1).pdgId) <= 5"
                    )))

    ## b-tag discriminators to be considered
    bTagDiscriminators = [
        #'pfCombinedInclusiveSecondaryVertexV2BJetTags', ## don't run b-tagging on the whole large cone jet
        'pfBoostedDoubleSecondaryVertexAK8BJetTags'  ## new tag for Boosted double b-tagging
    ]

    ## jet energy corrections already loaded in JECLevels
    if pileupMethod != "chs" and pileupMethod != "Puppi" and pileupMethod != "":
        sys.exit(
            "Invalid pileupMethod setup --> only recognized options are 'chs' and 'Puppi'"
        )

    ## JEC
    JECLevel = copy.deepcopy(process.JECLevels.labels)
    payloadName = ""
    payloadNameSubJet = ""
    jetCollection = ""
    pfCand = ""

    ## in case of CHS select particles and re-cluster jets
    if pileupMethod == "chs":
        ## obtain chs candidates
        if not hasattr(process, "chs"):
            setattr(
                process, 'chs',
                cms.EDFilter('CandPtrSelector',
                             src=cms.InputTag("packedPFCandidates"),
                             cut=cms.string('fromPV')))
        ## cluster basic jets given rParameter and algorithm
        if not hasattr(process, jetAlgo + 'PFJets' + pileupMethod.upper()):
            setattr(
                process, jetAlgo + 'PFJets' + pileupMethod.upper(),
                ak4PFJetsCHS.clone(src=cms.InputTag('chs'),
                                   doAreaFastjet=True,
                                   rParam=coneSize,
                                   jetAlgorithm=ALGO))

        payloadName = jetAlgo + 'PF' + pileupMethod
        payloadNameSubjet = 'AK4PF' + pileupMethod
        jetCollection = jetAlgo + 'PFJets' + pileupMethod.upper()
        pfCand = "chs"

    ## for puppi jets
    elif pileupMethod == "Puppi":
        ### re-run optimal puppi weights
        if not hasattr(process, "puppi"):
            from PhysicsTools.PatAlgos.slimming.puppiForMET_cff import makePuppiesFromMiniAOD
            makePuppiesFromMiniAOD(process, False)
            process.puppi.useExistingWeights = cms.bool(False)
            process.puppiNoLep.useExistingWeights = cms.bool(False)

        ## cluster puppi jets given rParameter and algorithm
        if not hasattr(process, jetAlgo + 'PFJets' + pileupMethod):
            setattr(
                process, jetAlgo + 'PFJets' + pileupMethod,
                ak4PFJetsPuppi.clone(src=cms.InputTag('puppi'),
                                     doAreaFastjet=True,
                                     rParam=coneSize,
                                     jetAlgorithm=ALGO))

        payloadName = jetAlgo + 'PF' + pileupMethod
        payloadNameSubjet = 'AK4PF' + pileupMethod
        jetCollection = jetAlgo + 'PFJets' + pileupMethod
        pfCand = "puppi"

    ## standard PF jets
    elif pileupMethod == "":
        ## no pileup mitigation
        if not hasattr(process, jetAlgo + 'PFJets'):
            setattr(
                process, jetAlgo + 'PFJets',
                ak4PFJetsPuppi.clone(src=cms.InputTag('packedPFCandidates'),
                                     doAreaFastjet=True,
                                     rParam=coneSize,
                                     jetAlgorithm=ALGO))
        payloadName = jetAlgo + 'PF'
        payloadNameSubjet = 'AK4PF'
        jetCollection = jetAlgo + 'PFJets'
        pfCand = "packedPFCandidates"

    ## apply selection and produce a restricted set of consituents only for jets passig the selection
    if not hasattr(process, jetCollection + "Reduced"):
        setattr(
            process, jetCollection + "Reduced",
            cms.EDFilter("MiniAODJetConstituentSelector",
                         src=cms.InputTag(jetCollection),
                         cut=cms.string("pt > 100 && abs(eta) < 2.5")))

    ## build pat-jets from this skimmed collection: example
    if not hasattr(process, "patJets" + jetCollection):

        addJetCollection(
            process,
            labelName=jetCollection,
            jetSource=cms.InputTag(jetCollection + "Reduced"),
            algo=algo,
            rParam=coneSize,
            pfCandidates=cms.InputTag(pfCand),
            jetCorrections=(payloadName, JECLevel, 'None'),
            svSource=cms.InputTag('slimmedSecondaryVertices'),
            genJetCollection=cms.InputTag("genJets" + jetAlgo),
            pvSource=cms.InputTag('offlineSlimmedPrimaryVertices'),
            btagDiscriminators=bTagDiscriminators,
            getJetMCFlavour=isMC,
            genParticles=cms.InputTag("prunedGenParticles"),
        )

        ### special jec set for pruned/sof-drop mass correction --> to be taken from the EDAnalyzer
        if hasattr(process, "patJetCorrFactors" + jetCollection):
            if isMC:
                setattr(
                    process, "patJetCorrFactors" + jetCollection + "v2",
                    getattr(
                        process, "patJetCorrFactors" + jetCollection).clone(
                            levels=cms.vstring('L2Relative', 'L3Absolute')))
            else:
                setattr(
                    process, "patJetCorrFactors" + jetCollection + "v2",
                    getattr(process, "patJetCorrFactors" +
                            jetCollection).clone(levels=cms.vstring(
                                'L2Relative', 'L3Absolute', 'L2L3Residual')))

            getattr(process, "patJets" +
                    jetCollection).jetCorrFactorsSource = cms.VInputTag(
                        cms.InputTag("patJetCorrFactors" + jetCollection),
                        cms.InputTag("patJetCorrFactors" + jetCollection +
                                     "v2"))

        if hasattr(process, "selectedPatJets" + jetCollection):
            getattr(process, "selectedPatJets" +
                    jetCollection).cut = cms.string(selection)

    ## match reco-jets with hadronically decaying genBosons (W,Z,H)
    if isMC:
        if not hasattr(process, jetCollection + 'GenBosonMatched'):
            setattr(
                process,
                jetCollection + 'GenBosonMatched',
                cms.EDProducer(
                    "RecoJetCandDeltaRValueMapProducer",
                    ## basic reco::jet ungroomed
                    src=cms.InputTag(jetCollection + "Reduced"),
                    ## mathched groomed pat jet
                    matched=cms.InputTag('genBosons'),
                    distMax=cms.double(coneSize),
                    values=cms.vstring("pt", "eta", "phi", "mass"),
                    valueLabels=cms.vstring("pt", "eta", "phi", "mass")))

            getattr(process,
                    'patJets' + jetCollection).userData.userFloats.src += [
                        jetCollection + 'GenBosonMatched:pt'
                    ]
            getattr(process,
                    'patJets' + jetCollection).userData.userFloats.src += [
                        jetCollection + 'GenBosonMatched:eta'
                    ]
            getattr(process,
                    'patJets' + jetCollection).userData.userFloats.src += [
                        jetCollection + 'GenBosonMatched:phi'
                    ]
            getattr(process,
                    'patJets' + jetCollection).userData.userFloats.src += [
                        jetCollection + 'GenBosonMatched:mass'
                    ]

    ## add QGLikelihood on fat jet
    if addQGLikelihood:
        if not hasattr(process, jetCollection + "QGL"):
            setattr(
                process, jetCollection + "QGL",
                QGTagger.clone(srcJets=cms.InputTag(jetCollection + "Reduced"),
                               jetsLabel=cms.string('QGL_AK4PFchs'),
                               srcVertexCollection=cms.InputTag(
                                   'offlineSlimmedPrimaryVertices')))
            getattr(process,
                    'patJets' + jetCollection).userData.userFloats.src += [
                        jetCollection + 'QGL:qgLikelihood'
                    ]

    ## addNsubjettiness
    if addNsubjettiness:
        if not hasattr(process, 'Njettiness' + jetCollection):
            setattr(
                process, 'Njettiness' + jetCollection,
                Njettiness.clone(src=cms.InputTag(jetCollection + "Reduced"),
                                 cone=cms.double(coneSize)))

            getattr(process,
                    'patJets' + jetCollection).userData.userFloats.src += [
                        'Njettiness' + jetCollection + ':tau1',
                        'Njettiness' + jetCollection + ':tau2',
                        'Njettiness' + jetCollection + ':tau3',
                        'Njettiness' + jetCollection + ':tau4'
                    ]

        ## on gen jets
        if isMC:
            if not hasattr(process, "NjettinessGenJets" + jetAlgo):
                setattr(
                    process, "NjettinessGenJets" + jetAlgo,
                    Njettiness.clone(src=cms.InputTag("genJets" + jetAlgo),
                                     cone=cms.double(coneSize)))

                ## pattify gen jets --> temp
                if not hasattr(process, 'patGenJets' + jetAlgo):
                    setattr(
                        process, 'patGenJets' + jetAlgo,
                        patJets.clone(
                            jetSource=cms.InputTag("genJets" + jetAlgo),
                            addJetCorrFactors=cms.bool(False),
                            addBTagInfo=cms.bool(False),
                            addDiscriminators=cms.bool(False),
                            discriminatorSources=cms.VInputTag('None'),
                            addAssociatedTracks=cms.bool(False),
                            addJetCharge=cms.bool(False),
                            addGenPartonMatch=cms.bool(False),
                            embedGenPartonMatch=cms.bool(False),
                            addGenJetMatch=cms.bool(False),
                            embedGenJetMatch=cms.bool(False),
                            getJetMCFlavour=cms.bool(False),
                            addJetFlavourInfo=cms.bool(False)))

                    getattr(process, 'patGenJets' +
                            jetAlgo).userData.userFloats.src += [
                                "NjettinessGenJets" + jetAlgo + ':tau1'
                            ]
                    getattr(process, 'patGenJets' +
                            jetAlgo).userData.userFloats.src += [
                                "NjettinessGenJets" + jetAlgo + ':tau2'
                            ]
                    getattr(process, 'patGenJets' +
                            jetAlgo).userData.userFloats.src += [
                                "NjettinessGenJets" + jetAlgo + ':tau3'
                            ]
                    getattr(process, 'patGenJets' +
                            jetAlgo).userData.userFloats.src += [
                                "NjettinessGenJets" + jetAlgo + ':tau4'
                            ]

            if not hasattr(process, jetCollection + 'GenNjettinessMatched'):
                setattr(
                    process,
                    jetCollection + 'GenNjettinessMatched',
                    cms.EDProducer(
                        "RecoPATJetDeltaRValueMapProducer",
                        ## basic reco::jet ungroomed
                        src=cms.InputTag(jetCollection + "Reduced"),
                        ## mathched groomed pat jet
                        matched=cms.InputTag('patGenJets' + jetAlgo),
                        distMax=cms.double(coneSize),
                        values=cms.vstring(
                            "userFloat('NjettinessGenJets" + jetAlgo +
                            ":tau1')", "userFloat('NjettinessGenJets" +
                            jetAlgo + ":tau2')",
                            "userFloat('NjettinessGenJets" + jetAlgo +
                            ":tau3')", "userFloat('NjettinessGenJets" +
                            jetAlgo + ":tau4')"),
                        valueLabels=cms.vstring("tau1", "tau2", "tau3",
                                                "tau4")))

                getattr(process,
                        'patJets' + jetCollection).userData.userFloats.src += [
                            jetCollection + 'GenNjettinessMatched:tau1',
                            jetCollection + 'GenNjettinessMatched:tau2',
                            jetCollection + 'GenNjettinessMatched:tau3',
                            jetCollection + 'GenNjettinessMatched:tau4'
                        ]

    ## add ECF
    if addEnergyCorrelation:
        if not hasattr(process, 'ecf' + jetCollection):
            setattr(
                process, 'ecf' + jetCollection,
                ECF.clone(src=cms.InputTag(jetCollection + "Reduced"),
                          Njets=cms.vuint32(1, 2, 3)))

            getattr(process,
                    'patJets' + jetCollection).userData.userFloats.src += [
                        'ecf' + jetCollection + ':ecf1'
                    ]
            getattr(process,
                    'patJets' + jetCollection).userData.userFloats.src += [
                        'ecf' + jetCollection + ':ecf2'
                    ]
            getattr(process,
                    'patJets' + jetCollection).userData.userFloats.src += [
                        'ecf' + jetCollection + ':ecf3'
                    ]

    ## add QJets
    if addQJets:
        if not hasattr(process, "qjets" + jetCollection):
            setattr(
                process, "qjets" + jetCollection,
                QJetsAdder.clone(src=cms.InputTag(jetCollection + "Reduced"),
                                 jeRad=cms.double(coneSize),
                                 jetAlgo=cms.string(algo)))

            setattr(process,
                    'patJets' + jetCollection).userData.userFloats.src += [
                        "qjets" + jetCollection + ":QjetsVolatility"
                    ]

    ### start with substructure: Pruning (run it on both reco and gen jets):
    Tags = []
    Labels = []
    JECLevelTemp = copy.deepcopy(JECLevel)
    if 'L1FastJet' in JECLevelTemp:
        JECLevelTemp.remove(
            'L1FastJet')  ## in any case groomers are removing already pileup

    if addPruning:
        runGroomedMethod(process,
                         isMC=isMC,
                         jetCollection=jetCollection,
                         coneSize=coneSize,
                         algo=algo,
                         payloadName=payloadName,
                         payloadNameSubjet=payloadNameSubjet,
                         JECLevel=JECLevelTemp,
                         pfCand=pfCand,
                         btagDiscriminators=bTagDiscriminators,
                         addSubJets=addPrunedSubjets,
                         addQGLikelihood=addQGLikelihood,
                         isPruning=True,
                         isSoftDrop=False,
                         isTrimming=False,
                         isFiltering=False)

        if addPrunedSubjets:
            Tags += ['patJets' + jetCollection + 'PrunedPacked']
            Labels += ['Pruned']

    if addSoftDrop:
        runGroomedMethod(process,
                         isMC=isMC,
                         jetCollection=jetCollection,
                         coneSize=coneSize,
                         algo=algo,
                         payloadName=payloadName,
                         payloadNameSubjet=payloadNameSubjet,
                         JECLevel=JECLevelTemp,
                         pfCand=pfCand,
                         btagDiscriminators=bTagDiscriminators,
                         addSubJets=addSoftDropSubjets,
                         addQGLikelihood=addQGLikelihood,
                         isPruning=False,
                         isSoftDrop=True,
                         isTrimming=False,
                         isFiltering=False)

        if addSoftDropSubjets:
            Tags += ['patJets' + jetCollection + 'SoftDropPacked']
            Labels += ['SoftDrop']

    if addTrimming:
        runGroomedMethod(process,
                         isMC=isMC,
                         jetCollection=jetCollection,
                         coneSize=coneSize,
                         algo=algo,
                         payloadName=payloadName,
                         payloadNameSubjet=payloadNameSubjet,
                         JECLevel=JECLevelTemp,
                         pfCand=pfCand,
                         btagDiscriminators=bTagDiscriminators,
                         addSubJets=addTrimmedSubjets,
                         addQGLikelihood=addQGLikelihood,
                         isPruning=False,
                         isSoftDrop=False,
                         isTrimming=True,
                         isFiltering=False)

        if addTrimmedSubjets:
            Tags += ['patJets' + jetCollection + 'TrimmedPacked']
            Labels += ['Trimmed']

    if addFiltering:
        runGroomedMethod(process,
                         isMC=isMC,
                         jetCollection=jetCollection,
                         coneSize=coneSize,
                         algo=algo,
                         payloadName=payloadName,
                         payloadNameSubjet=payloadNameSubjet,
                         JECLevel=JECLevelTemp,
                         pfCand=pfCand,
                         btagDiscriminators=bTagDiscriminators,
                         addSubJets=addFilteredSubjets,
                         addQGLikelihood=addQGLikelihood,
                         isPruning=False,
                         isSoftDrop=False,
                         isTrimming=False,
                         isFiltering=True)

        if addFilteredSubjets:
            Tags += ['patJets' + jetCollection + 'FilteredPacked']
            Labels += ['Filtered']

    ## finally fix the pat fat jet collection
    if not hasattr(process, "packedPatJets" + jetCollection):
        setattr(
            process, "packedPatJets" + jetCollection,
            cms.EDProducer("JetSubstructurePacker",
                           jetSrc=cms.InputTag("selectedPatJets" +
                                               jetCollection),
                           distMax=cms.double(coneSize),
                           fixDaughters=cms.bool(False),
                           algoTags=cms.VInputTag(),
                           algoLabels=cms.vstring()))

        getattr(process, "packedPatJets" + jetCollection).algoTags = Tags
        getattr(process, "packedPatJets" + jetCollection).algoLabels = Labels

    return "packedPatJets" + jetCollection
예제 #12
0
def runGroomedMethod(process,
                     isMC,
                     jetCollection,
                     coneSize,
                     algo,
                     payloadName,
                     payloadNameSubjet,
                     JECLevel,
                     pfCand,
                     btagDiscriminators,
                     addSubJets=True,
                     addQGLikelihood=True,
                     isPruning=True,
                     isSoftDrop=True,
                     isTrimming=True,
                     isFiltering=True):

    ### name for cone size and algo
    coneSizeStr = str(coneSize).replace("0", "").replace(".", "")
    jetAlgo = algo + coneSizeStr

    if algo == "AK":
        ALGO = "AntiKt"
    elif algo == "CA":
        ALGO = "CambridgeAachen"

    btagSubjets = ['pfCombinedInclusiveSecondaryVertexV2BJetTags']

    ### form the right postfix
    if not isPruning and not isSoftDrop and not isTrimming and not isFiltering:
        sys.exit("runGroomedMethod: all bools are false --> please check")

    if isPruning and not isSoftDrop and not isTrimming and not isFiltering:
        postfix = "Pruned"
    elif not isPruning and isSoftDrop and not isTrimming and not isFiltering:
        postfix = "SoftDrop"
    elif not isPruning and not isSoftDrop and isTrimming and not isFiltering:
        postfix = "Trimmed"
    elif not isPruning and not isSoftDrop and not isTrimming and isFiltering:
        postfix = "Filtered"
    else:
        sys.exit(
            "wrong setup, only one groomer is allowed each time --> please check"
        )

    ## build default reco groomed jets
    if not hasattr(process, jetCollection + postfix):
        if isPruning:
            setattr(process, jetCollection + postfix,
                    ak8PFJetsCHSPruned.clone())
        elif isSoftDrop:
            setattr(process, jetCollection + postfix,
                    ak8PFJetsCHSSoftDrop.clone())
        elif isTrimming:
            setattr(process, jetCollection + postfix,
                    ak8PFJetsCHSTrimmed.clone())
        elif isFiltering:
            setattr(process, jetCollection + postfix,
                    ak8PFJetsCHSFiltered.clone())

        getattr(process, jetCollection + postfix).src = cms.InputTag(
            jetCollection + "Reduced", 'constituents')
        getattr(process, jetCollection + postfix).rParam = coneSize
        getattr(process, jetCollection + postfix).jetAlgorithm = ALGO
        ## write compounds means that subjets are stored as reco::Jet while the groomed jet is stored as base::Jet
        getattr(process,
                jetCollection + postfix).writeCompound = cms.bool(True)
        getattr(process,
                jetCollection + postfix).doAreaFastjet = cms.bool(True)

    ## gen groomed jets
    if isMC:
        if not hasattr(process, "genJets" + jetAlgo + postfix):
            ## store AK8 gen::Jet
            setattr(
                process, "genJets" + jetAlgo + postfix,
                getattr(process, jetCollection + postfix).clone(
                    src=cms.InputTag('genParticlesForJetsNoNu'),
                    writeCompound=cms.bool(False),
                    useExplicitGhosts=cms.bool(True),
                    jetPtMin=cms.double(50.),
                    jetType=cms.string('GenJet'),
                    jetCollInstanceName=cms.string("")))

    ## pruned pat jets with embeded gen-jet info
    if not hasattr(process, "patJets" + jetCollection + postfix):
        addJetCollection(
            process,
            labelName=jetCollection + postfix,
            jetSource=cms.InputTag(jetCollection + postfix),
            algo=algo,
            pfCandidates=cms.InputTag(pfCand),
            rParam=coneSize,
            jetCorrections=(payloadName, JECLevel, 'None'),
            svSource=cms.InputTag('slimmedSecondaryVertices'),
            genJetCollection=cms.InputTag("genJets" + jetAlgo + postfix),
            pvSource=cms.InputTag('offlineSlimmedPrimaryVertices'),
            btagDiscriminators=
            btagDiscriminators,  ## no b-tag info for pruned jets                                                                                     
            getJetMCFlavour=
            isMC,  ## no flavor info                                                                                                                       
            genParticles=cms.InputTag("prunedGenParticles"))

    ## matched fat jet with groomed one adding info as user float
    if not hasattr(process, jetCollection + postfix + 'Matched'):
        setattr(
            process,
            jetCollection + postfix + 'Matched',
            cms.EDProducer(
                "RecoPATJetDeltaRValueMapProducer",
                ## basic reco::jet ungroomed
                src=cms.InputTag(jetCollection + "Reduced"),
                ## mathched groomed pat jet
                matched=cms.InputTag('patJets' + jetCollection + postfix),
                distMax=cms.double(coneSize),
                values=cms.vstring(
                    "mass", "pt", "eta", "phi",
                    "bDiscriminator('pfCombinedInclusiveSecondaryVertexV2BJetTags')",
                    "bDiscriminator('pfBoostedDoubleSecondaryVertexAK8BJetTags')",
                    "correctedP4(0).mass()", "correctedP4(0).pt()",
                    "correctedP4(0).eta()", "correctedP4(0).phi()"),
                valueLabels=cms.vstring(
                    "mass", "pt", "eta", "phi",
                    "pfCombinedInclusiveSecondaryVertexV2BJetTags",
                    "pfBoostedDoubleSecondaryVertexAK8BJetTags", "rawmass",
                    "rawpt", "raweta", "rawphi")))

        if isMC:
            getattr(process,
                    jetCollection + postfix + 'Matched').valueLabels += [
                        "hadronFlavour", "partonFlavour", "genMass", "genPt",
                        "genEta", "genPhi"
                    ]
            getattr(process, jetCollection + postfix + 'Matched').values += [
                "hadronFlavour", "partonFlavour", "genJet().mass",
                "genJet().pt", "genJet().eta", "genJet().phi"
            ]

        getattr(process,
                'patJets' + jetCollection).userData.userFloats.src += [
                    jetCollection + postfix + 'Matched:mass'
                ]
        getattr(process,
                'patJets' + jetCollection).userData.userFloats.src += [
                    jetCollection + postfix + 'Matched:pt'
                ]
        getattr(process,
                'patJets' + jetCollection).userData.userFloats.src += [
                    jetCollection + postfix +
                    'Matched:pfCombinedInclusiveSecondaryVertexV2BJetTags'
                ]
        getattr(process,
                'patJets' + jetCollection).userData.userFloats.src += [
                    jetCollection + postfix +
                    'Matched:pfBoostedDoubleSecondaryVertexAK8BJetTags'
                ]
        getattr(process,
                'patJets' + jetCollection).userData.userFloats.src += [
                    jetCollection + postfix + 'Matched:eta'
                ]
        getattr(process,
                'patJets' + jetCollection).userData.userFloats.src += [
                    jetCollection + postfix + 'Matched:phi'
                ]
        getattr(process,
                'patJets' + jetCollection).userData.userFloats.src += [
                    jetCollection + postfix + 'Matched:rawmass'
                ]
        getattr(process,
                'patJets' + jetCollection).userData.userFloats.src += [
                    jetCollection + postfix + 'Matched:rawpt'
                ]
        getattr(process,
                'patJets' + jetCollection).userData.userFloats.src += [
                    jetCollection + postfix + 'Matched:raweta'
                ]
        getattr(process,
                'patJets' + jetCollection).userData.userFloats.src += [
                    jetCollection + postfix + 'Matched:rawphi'
                ]

        if isMC:
            getattr(process,
                    'patJets' + jetCollection).userData.userFloats.src += [
                        jetCollection + postfix + 'Matched:hadronFlavour'
                    ]
            getattr(process,
                    'patJets' + jetCollection).userData.userFloats.src += [
                        jetCollection + postfix + 'Matched:partonFlavour'
                    ]
            getattr(process,
                    'patJets' + jetCollection).userData.userFloats.src += [
                        jetCollection + postfix + 'Matched:genMass'
                    ]
            getattr(process,
                    'patJets' + jetCollection).userData.userFloats.src += [
                        jetCollection + postfix + 'Matched:genPt'
                    ]
            getattr(process,
                    'patJets' + jetCollection).userData.userFloats.src += [
                        jetCollection + postfix + 'Matched:genEta'
                    ]
            getattr(process,
                    'patJets' + jetCollection).userData.userFloats.src += [
                        jetCollection + postfix + 'Matched:genPhi'
                    ]

    ## add QGL --> some tricks are needed
    if addQGLikelihood:
        ## redo groomed jet with a special postfix (ForQGL)
        if not hasattr(process, jetCollection + postfix + "ForQGL"):
            setattr(
                process, jetCollection + postfix + "ForQGL",
                getattr(process, jetCollection + postfix).clone(
                    writeCompound=cms.bool(False),
                    jetCollInstanceName=cms.string("")))

        ## run QGL evaluator
        if not hasattr(process, jetCollection + postfix + "QGL"):
            setattr(
                process, jetCollection + postfix + "QGL",
                QGTagger.clone(srcJets=cms.InputTag(jetCollection + postfix +
                                                    "ForQGL"),
                               jetsLabel=cms.string('QGL_AK4PFchs'),
                               srcVertexCollection=cms.InputTag(
                                   'offlineSlimmedPrimaryVertices')))

        ## pattify jets on the fly
        if not hasattr(process, 'patJets' + jetCollection + postfix + "QGL"):
            setattr(
                process, 'patJets' + jetCollection + postfix + "QGL",
                patJets.clone(jetSource=cms.InputTag(jetCollection + postfix +
                                                     "ForQGL"),
                              addJetCorrFactors=cms.bool(False),
                              addBTagInfo=cms.bool(False),
                              addDiscriminators=cms.bool(False),
                              discriminatorSources=cms.VInputTag('None'),
                              addAssociatedTracks=cms.bool(False),
                              addJetCharge=cms.bool(False),
                              addGenPartonMatch=cms.bool(False),
                              embedGenPartonMatch=cms.bool(False),
                              addGenJetMatch=cms.bool(False),
                              embedGenJetMatch=cms.bool(False),
                              getJetMCFlavour=cms.bool(False),
                              addJetFlavourInfo=cms.bool(False)))

            getattr(process, 'patJets' + jetCollection + postfix +
                    "QGL").userData.userFloats.src += [
                        jetCollection + postfix + "QGL:qgLikelihood"
                    ]

        ## match QGL value with the original jet
        if not hasattr(process, jetCollection + postfix + "QGLMatched"):
            setattr(
                process, jetCollection + postfix + 'QGLMatched',
                cms.EDProducer(
                    "RecoPATJetDeltaRValueMapProducer",
                    src=cms.InputTag(jetCollection + "Reduced"),
                    matched=cms.InputTag('patJets' + jetCollection + postfix +
                                         "QGL"),
                    distMax=cms.double(coneSize),
                    values=cms.vstring("userFloat('" + jetCollection +
                                       postfix + "QGL:qgLikelihood')"),
                    valueLabels=cms.vstring("qgLikelihood")))

            getattr(process,
                    'patJets' + jetCollection).userData.userFloats.src += [
                        jetCollection + postfix + 'QGLMatched:qgLikelihood'
                    ]

    ## add subjet information
    if addSubJets:

        ## gen groomed sub-jets --> star with default clustering
        if isMC and not hasattr(process,
                                "genJets" + jetAlgo + postfix + "SubJets"):
            setattr(
                process, "genJets" + jetAlgo + postfix + "SubJets",
                getattr(process, "genJets" + jetAlgo + postfix).clone(
                    writeCompound=cms.bool(True),
                    jetCollInstanceName=cms.string('SubJets')))

        if not hasattr(process,
                       "patJets" + jetCollection + postfix + "SubJets"):

            addJetCollection(
                process,
                labelName=jetCollection + postfix + 'SubJets',
                jetSource=cms.InputTag(jetCollection + postfix, 'SubJets'),
                algo=algo,  # needed for subjet b tagging
                rParam=coneSize,  # needed for subjet b tagging
                pfCandidates=cms.InputTag(pfCand),
                jetCorrections=(payloadNameSubjet, JECLevel, 'None'),
                pvSource=cms.InputTag('offlineSlimmedPrimaryVertices'),
                svSource=cms.InputTag('slimmedSecondaryVertices'),
                getJetMCFlavour=isMC,
                genParticles=cms.InputTag("prunedGenParticles"),
                btagDiscriminators=btagSubjets,
                genJetCollection=cms.InputTag(
                    "genJets" + jetAlgo + postfix + "SubJets", "SubJets"),
                explicitJTA=True,  # needed for subjet b tagging
                svClustering=True,  # needed for subjet b tagging
                fatJets=cms.InputTag(
                    jetCollection +
                    "Reduced"),  # needed for subjet flavor clustering
                groomedFatJets=cms.InputTag(
                    jetCollection +
                    postfix),  # needed for subjet flavor clustering
            )

        ## adding sub-jet QGL
        if addQGLikelihood:
            if not hasattr(process, jetCollection + postfix + "SubJetsQGL"):
                setattr(
                    process, jetCollection + postfix + "SubJetsQGL",
                    QGTagger.clone(srcJets=cms.InputTag(
                        jetCollection + postfix, "SubJets"),
                                   jetsLabel=cms.string('QGL_AK4PFchs'),
                                   srcVertexCollection=cms.InputTag(
                                       'offlineSlimmedPrimaryVertices')))

                getattr(process, 'patJets' + jetCollection + postfix +
                        "SubJets").userData.userFloats.src += [
                            jetCollection + postfix + 'SubJetsQGL:qgLikelihood'
                        ]

        ## Establish references between PATified fat jets and subjets using the BoostedJetMerger
        if not hasattr(process,
                       'patJets' + jetCollection + postfix + 'Packed'):
            setattr(
                process, 'patJets' + jetCollection + postfix + 'Packed',
                cms.EDProducer(
                    "BoostedJetMerger",
                    jetSrc=cms.InputTag('selectedPatJets' + jetCollection +
                                        postfix),
                    subjetSrc=cms.InputTag("selectedPatJets" + jetCollection +
                                           postfix + "SubJets")))
예제 #13
0
def makeJets(process, isData, label, candidates, suffix):
    """
    Light-weight version of pat addJetCollection.
    @labels: e.g. 'AK4PFPuppi'
    """

    sequence = cms.Sequence()

    addattr = AddAttr(process, sequence, suffix)

    jets = addattr('ak4PFJets',
                   ak4PFJets.clone(src=candidates, doAreaFastjet=True))

    jecLevels = ['L1FastJet', 'L2Relative', 'L3Absolute']
    if isData:
        jecLevels.append('L2L3Residual')

    jetCorrFactors = addattr(
        'jetCorrFactors',
        patJetCorrFactors.clone(src=jets,
                                payload=label,
                                levels=jecLevels,
                                primaryVertices=pvSource))

    # btag should always use standard PF collection
    sequence += initBTag(process, '', pfSource, pvSource)

    sequence += setupBTag(process,
                          jetCollection=jets,
                          suffix=suffix,
                          vsuffix='',
                          muons=muons,
                          electrons=electrons,
                          tags=[
                              'pfCombinedInclusiveSecondaryVertexV2BJetTags',
                              'pfCombinedMVAV2BJetTags', 'pfDeepCSVJetTags',
                              'pfDeepCMVAJetTags'
                          ])

    qgTagger = addattr('QGTagger', QGTagger.clone(srcJets=jets))

    if not isData:
        genJetMatch = addattr(
            'genJetMatch',
            patJetGenJetMatch.clone(src=jets, maxDeltaR=0.4, matched=genJets))


    allPatJets = addattr('patJets',
        patJets.clone(
            jetSource = jets,
            addJetCorrFactors = True,
            jetCorrFactorsSource = [jetCorrFactors],
            addBTagInfo = True,
            discriminatorSources = [
                cms.InputTag('pfCombinedInclusiveSecondaryVertexV2BJetTags' + suffix),
                cms.InputTag('pfCombinedMVAV2BJetTags' + suffix),
                ] + \
                sum([[cms.InputTag('pfDeepCSVJetTags' + suffix, 'prob' + prob),
                      cms.InputTag('pfDeepCMVAJetTags' + suffix, 'prob' + prob)]
                       #                     for prob in ['udsg', 'b', 'c', 'bb', 'cc']],
                     for prob in ['udsg', 'b', 'c', 'bb']],
                    []),
            addAssociatedTracks = False,
            addJetCharge = False,
            addGenPartonMatch = False,
            addGenJetMatch = (not isData),
            getJetMCFlavour = False,
            addJetFlavourInfo = False
        )
    )

    addattr.last.userData.userFloats.src = [
        qgTagger.getModuleLabel() + ':qgLikelihood'
    ]
    addattr.last.userData.userFloats.labelPostfixesToStrip = cms.vstring(
        suffix)

    if not isData:
        addattr.last.genJetMatch = genJetMatch

    selectedJets = addattr(
        'selectedJets', selectedPatJets.clone(src=allPatJets, cut='pt > 15'))

    addattr('slimmedJets',
            slimmedJets.clone(src=selectedJets, rekeyDaughters='0'))

    return sequence
예제 #14
0
def jetToolbox(proc,
               jetType,
               jetSequence,
               PUMethod='',
               bTagDiscriminators=None):
    JETCorrPayload = 'None'
    JETCorrLevels = ['None']
    # See PhysicsTools/PatAlgos/python/recoLayer0/bTagging_cff.py for further options
    bTagDiscriminators = [
        'pfDeepCSVJetTags:probb',
        'pfDeepCSVJetTags:probc',
        'pfDeepCSVJetTags:probudsg',
        'pfDeepCSVJetTags:probbb',
        #'pfDeepFlavourJetTags:probb',
        #'pfDeepFlavourJetTags:probc',
        #'pfDeepFlavourJetTags:probg',
        #'pfDeepFlavourJetTags:probuds',
        #'pfDeepFlavourJetTags:probbb',
        #'pfTrackCountingHighEffBJetTags',
        'pfJetProbabilityBJetTags',
        #'pfSimpleSecondaryVertexHighEffBJetTags',
        'pfCombinedCvsLJetTags',
        'pfCombinedCvsBJetTags',
        'pfBoostedDoubleSecondaryVertexAK8BJetTags',
        #'pfCombinedSecondaryVertexV2BJetTags',
        'pfCombinedInclusiveSecondaryVertexV2BJetTags',
        'pfCombinedMVAV2BJetTags',
        'pfJetProbabilityBJetTags'
    ]

    GetJetMCFlavour = ['True']

    algorithm = 'AntiKt'  # CambridgeAachen' , 'Kt'
    size = jetType[-1:]  #[-1:] takes the last char from string 'akX'
    jetSize = float('0.' + jetType[-1:])
    jetALGO = jetType.upper()
    jetalgo = jetType.lower()
    elemToKeep = []

    print 'Running processes with: ' + str(
        jetALGO
    ) + ' PF ' + PUMethod + ' jet algorithm with radius parameter ' + str(
        jetSize)

    JETCorrPayload = 'AK' + size + 'PF' + PUMethod.lower()
    JETCorrLevels = ['L1FastJet', 'L2Relative', 'L3Absolute']
    JEC = (JETCorrPayload, JETCorrLevels, 'None')

    #################################################################################
    ####### Toolbox start
    #################################################################################

    elemToKeep = []
    jetSeq = cms.Sequence()
    genParticlesLabel = ''
    pvLabel = ''
    tvLabel = ''
    toolsUsed = []

    proc.load('RecoJets.Configuration.GenJetParticles_cff')
    setattr(
        proc, jetalgo + 'GenJetsNoNu',
        ak4GenJets.clone(src='genParticlesForJetsNoNu',
                         rParam=jetSize,
                         jetAlgorithm=algorithm))
    jetSeq += getattr(proc, jetalgo + 'GenJetsNoNu')

    proc.load('CommonTools.ParticleFlow.pfNoPileUpJME_cff')
    if (PUMethod == 'CHS'):
        setattr(proc, jetalgo + 'PFJetsCHS',
                ak4PFJets.clone(rParam=jetSize, jetAlgorithm=algorithm))
        jetSeq += getattr(proc, jetalgo + 'PFJetsCHS')

        setattr(
            proc, jetalgo + 'PFJetsCHS',
            ak4PFJetsCHS.clone(doAreaFastjet=True,
                               rParam=jetSize,
                               jetAlgorithm=algorithm))
        jetSeq += getattr(proc, jetalgo + 'PFJetsCHS')
    else:
        setattr(proc, jetalgo + 'PFJets',
                ak4PFJets.clone(rParam=jetSize, jetAlgorithm=algorithm))
        jetSeq += getattr(proc, jetalgo + 'PFJets')

        setattr(
            proc, jetalgo + 'PFJets',
            ak4PFJets.clone(doAreaFastjet=True,
                            rParam=jetSize,
                            jetAlgorithm=algorithm))
        jetSeq += getattr(proc, jetalgo + 'PFJets')
        PUMethod = ''

    ####  Creating PATjets
    addJetCollection(
        proc,
        labelName=jetALGO + 'PF' + PUMethod,
        jetSource=cms.InputTag(jetalgo + 'PFJets' + PUMethod),
        algo=jetalgo,
        btagDiscriminators=bTagDiscriminators,
        rParam=jetSize,
        jetCorrections=JEC,
        pfCandidates=cms.InputTag('particleFlow'),
        svSource=cms.InputTag('inclusiveCandidateSecondaryVertices'),
        genJetCollection=cms.InputTag(jetalgo + 'GenJetsNoNu'),
        pvSource=cms.InputTag(
            'offlinePrimaryVertices'),  #'offlineSlimmedPrimaryVertices'),
        jetTrackAssociation=True)

    # srcJets Could be reco::PFJetCollection or pat::JetCollection (both AOD and miniAOD)
    # Other options for jetsLabel (might need to add an ESSource for it): see https://twiki.cern.ch/twiki/bin/viewauth/CMS/QGDataBaseVersion
    setattr(
        proc, 'QGTagger' + jetALGO + 'PF' + PUMethod,
        QGTagger.clone(srcJets=cms.InputTag(jetalgo + 'PFJets' + PUMethod),
                       jetsLabel=cms.string('QGL_AK4PFchs')))
    elemToKeep += ['keep *_QGTagger' + jetALGO + 'PF' + PUMethod + '_*_*']
    getattr(proc,
            'patJets' + jetALGO + 'PF' + PUMethod).userData.userFloats.src += [
                'QGTagger' + jetALGO + 'PF' + PUMethod + ':qgLikelihood'
            ]
    jetSeq += getattr(proc, 'QGTagger' + jetALGO + 'PF' + PUMethod)
    toolsUsed.append('QGTagger' + jetALGO + 'PF' + PUMethod)

    getattr(proc, 'patJetPartons').particles = cms.InputTag(
        'genParticles')  #'prunedGenParticles')
    setattr(proc, 'selectedPatJets' + jetALGO + 'PF' + PUMethod,
            selectedPatJets.clone(src='patJets' + jetALGO + 'PF' + PUMethod))
    setattr(proc, jetSequence, jetSeq)
예제 #15
0
def jetToolbox(proc, jetType, jetSequence):
    # See PhysicsTools/PatAlgos/python/recoLayer0/bTagging_cff.py for further options
    bTagDiscriminators = [
        'pfDeepCSVJetTags:probb',
        'pfDeepCSVJetTags:probc',
        'pfDeepCSVJetTags:probudsg',
        'pfDeepCSVJetTags:probbb',
        #'pfDeepFlavourJetTags:probb',
        #'pfDeepFlavourJetTags:probc',
        #'pfDeepFlavourJetTags:probg',
        #'pfDeepFlavourJetTags:probuds',
        #'pfDeepFlavourJetTags:probbb',
        #'pfTrackCountingHighEffBJetTags',
        'pfJetProbabilityBJetTags',
        #'pfSimpleSecondaryVertexHighEffBJetTags',
        'pfCombinedCvsLJetTags',
        'pfCombinedCvsBJetTags',
        'pfBoostedDoubleSecondaryVertexAK8BJetTags',
        #'pfCombinedSecondaryVertexV2BJetTags',
        'pfCombinedInclusiveSecondaryVertexV2BJetTags',
        'pfCombinedMVAV2BJetTags',
        'pfJetProbabilityBJetTags'
    ]

    print '|---- jetToolbox: Initialyzing collection...'
    algorithm = 'AntiKt'  # CambridgeAachen' , 'Kt'
    size = jetType[-1:]  #[-1:] takes the last char from string 'akX'
    jetSize = float('0.' + jetType[-1:])
    jetALGO = jetType.upper()
    jetalgo = jetType.lower()
    PUMethod = 'CHS'
    jetNAME = jetALGO + 'PF' + PUMethod
    jetname = jetalgo + 'PFJets' + PUMethod
    gjetname = jetalgo + 'GenJetsNoNu'
    print 'Running processes with: ' + jetNAME + ' jet algorithm with radius parameter ' + str(
        jetSize)

    JEC = ('AK' + size + 'PF' + PUMethod.lower(),
           ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None')
    print '|---- jetToolBox: Applying these corrections: ' + str(JEC)

    #################################################################################
    ####### Toolbox start
    #################################################################################

    jetSeq = cms.Sequence()

    # Creating GenJets
    proc.load('RecoJets.Configuration.GenJetParticles_cff')
    setattr(
        proc, gjetname,
        ak4GenJets.clone(src='genParticlesForJetsNoNu',
                         rParam=jetSize,
                         jetAlgorithm=algorithm))
    jetSeq += getattr(proc, gjetname)

    # Creating AK4PFJetsCHS
    proc.load('CommonTools.ParticleFlow.pfNoPileUpJME_cff')
    setattr(
        proc, jetname,
        ak4PFJetsCHS.clone(src=cms.InputTag('pfNoPileUpJME'),
                           doAreaFastjet=True,
                           rParam=jetSize,
                           jetAlgorithm=algorithm))
    jetSeq += getattr(proc, jetname)

    ####  Creating PATjets
    addJetCollection(
        proc,
        labelName=jetNAME,
        jetSource=cms.InputTag(jetname),
        algo=jetalgo,
        rParam=jetSize,
        btagDiscriminators=bTagDiscriminators,
        jetCorrections=JEC,
        pfCandidates=cms.InputTag('particleFlow'),  #redundant (default)
        svSource=cms.InputTag(
            'inclusiveCandidateSecondaryVertices'),  # redundant (default)
        pvSource=cms.InputTag(
            'offlinePrimaryVertices'),  # redundant (default) 
        getJetMCFlavour=True,  # redundant (default)
        genJetCollection=cms.InputTag(gjetname),
        jetTrackAssociation=True)
    getattr(proc, 'patJets' + jetNAME).addTagInfos = cms.bool(True)
    getattr(proc, 'patJets' + jetNAME).addAssociatedTracks = cms.bool(True)

    setattr(
        proc, 'QGTagger' + jetNAME,
        QGTagger.clone(srcJets=cms.InputTag(jetname),
                       jetsLabel=cms.string('QGL_AK4PFchs')))
    getattr(proc, 'patJets' + jetNAME).userData.userFloats.src += [
        'QGTagger' + jetNAME + ':qgLikelihood'
    ]
    jetSeq += getattr(proc, 'QGTagger' + jetNAME)

    getattr(proc, 'patJetPartons').particles = cms.InputTag('genParticles')
    # This is already done in addJetCollection, but I worry that the changes done to patJets do not get updated to     selectedPatJets
    setattr(proc, 'selectedPatJets' + jetNAME,
            selectedPatJets.clone(src='patJets' + jetNAME))
    # return
    setattr(proc, jetSequence, jetSeq)
예제 #16
0
def jetToolbox( proc, jetType, jetSequence, outputFile, 
		newPFCollection=False, nameNewPFCollection = '',	
		PUMethod='CHS',                    #### Options: Puppi, CS, SK, Plain
		miniAOD=True,
		runOnMC=True,
		JETCorrPayload='', JETCorrLevels = [ 'None' ], GetJetMCFlavour=True,
		Cut = '', 
		bTagDiscriminators = None, 
		subJETCorrPayload='', subJETCorrLevels = [ 'None' ], GetSubjetMCFlavour=False,
		CutSubjet = '', 
		addPruning=False, zCut=0.1, rCut=0.5, addPrunedSubjets=False,
		addSoftDrop=False, betaCut=0.0,  zCutSD=0.1, addSoftDropSubjets=False,
		addTrimming=False, rFiltTrim=0.2, ptFrac=0.03,
		addFiltering=False, rfilt=0.3, nfilt=3,
		addCMSTopTagger=False,
		addMassDrop=False,
		addHEPTopTagger=False,
		addNsub=False, maxTau=4,
		addPUJetID=False,
		addQJets=False,
		addQGTagger=False, QGjetsLabel='chs',
		addEnergyCorrFunc=False, ecfBeta = 1.0, maxECF=3,
		):

	runOnData = not runOnMC
	if runOnData:
		GetJetMCFlavour = False
		GetSubjetMCFlavour = False
	
	###############################################################################
	#######  Verifying some inputs and defining variables
	###############################################################################
	print '|---- jetToolbox: Initialyzing collection...'
	if newPFCollection: print '|---- jetToolBox: Using '+ nameNewPFCollection +' as PFCandidates collection'
	supportedJetAlgos = { 'ak': 'AntiKt', 'ca' : 'CambridgeAachen', 'kt' : 'Kt' }
	recommendedJetAlgos = [ 'ak4', 'ak8', 'ca4', 'ca8', 'ca10' ]
	payloadList = [ 'None',
			'AK1PFchs', 'AK2PFchs', 'AK3PFchs', 'AK4PFchs', 'AK5PFchs', 'AK6PFchs', 'AK7PFchs', 'AK8PFchs', 'AK9PFchs', 'AK10PFchs',
			'AK1PFPUPPI', 'AK2PFPUPPI', 'AK3PFPUPPI', 'AK4PFPUPPI', 'AK5PFPUPPI', 'AK6PFPUPPI', 'AK7PFPUPPI', 'AK8PFPUPPI', 'AK9PFPUPPI', 'AK10PFPUPPI',  
			'AK1PFSK', 'AK2PFSK', 'AK3PFSK', 'AK4PFSK', 'AK5PFSK', 'AK6PFSK', 'AK7PFSK', 'AK8PFSK', 'AK9PFSK', 'AK10PFSK',  
			'AK1PF', 'AK2PF', 'AK3PF', 'AK4PF', 'AK5PF', 'AK6PF', 'AK7PF', 'AK8PF', 'AK9PF', 'AK10PF' ]
	JECLevels = [ 'L1Offset', 'L1FastJet', 'L1JPTOffset', 'L2Relative', 'L3Absolute', 'L5Falvour', 'L7Parton' ]
	if runOnData:
		JECLevels += ['L2L3Residual']
	jetAlgo = ''
	algorithm = ''
	size = ''
	for type, tmpAlgo in supportedJetAlgos.iteritems(): 
		if type in jetType.lower():
			jetAlgo = type
			algorithm = tmpAlgo
			size = jetType.replace( type, '' )

	jetSize = 0.
	if int(size) in range(0, 20): jetSize = int(size)/10.
	else: print '|---- jetToolBox: jetSize has not a valid value. Insert a number between 1 and 20 after algorithm, like: AK8'
	### Trick for uppercase/lowercase algo name
	jetALGO = jetAlgo.upper()+size
	jetalgo = jetAlgo.lower()+size
	if jetalgo not in recommendedJetAlgos: print '|---- jetToolBox: CMS recommends the following jet algoritms: '+' '.join(recommendedJetAlgos)+'. You are using', jetalgo,'.'


	#################################################################################
	####### Toolbox start 
	#################################################################################

	elemToKeep = []
	jetSeq = cms.Sequence()
	genParticlesLabel = ''
	pvLabel = ''
	tvLabel = ''
	toolsUsed = []

	#### For MiniAOD
	if miniAOD:

		print '|---- jetToolBox: JETTOOLBOX RUNNING ON MiniAOD FOR '+jetALGO+' JETS USING '+PUMethod

		genParticlesLabel = 'prunedGenParticles'
		pvLabel = 'offlineSlimmedPrimaryVertices'
		svLabel = 'slimmedSecondaryVertices'
		tvLabel = 'unpackedTracksAndVertices'
		pfCand = nameNewPFCollection if newPFCollection else 'packedPFCandidates'

		if runOnMC:
			## Filter out neutrinos from packed GenParticles
			setattr( proc, 'packedGenParticlesForJetsNoNu', 
					cms.EDFilter("CandPtrSelector", 
						src = cms.InputTag("packedGenParticles"), 
						cut = cms.string("abs(pdgId) != 12 && abs(pdgId) != 14 && abs(pdgId) != 16")
						))
			jetSeq += getattr(proc, 'packedGenParticlesForJetsNoNu' )

			setattr( proc, jetalgo+'GenJetsNoNu', 
					ak4GenJets.clone( src = 'packedGenParticlesForJetsNoNu', 
						rParam = jetSize, 
						jetAlgorithm = algorithm ) ) 
			jetSeq += getattr(proc, jetalgo+'GenJetsNoNu' )

		#for Inclusive Vertex Finder
		proc.load('PhysicsTools.PatAlgos.slimming.unpackedTracksAndVertices_cfi')

	#### For AOD
	else:
		print '|---- jetToolBox: JETTOOLBOX RUNNING ON AOD FOR '+jetALGO+' JETS USING '+PUMethod

		genParticlesLabel = 'genParticles'
		pvLabel = 'offlinePrimaryVertices'
		tvLabel = 'generalTracks'
		pfCand =  nameNewPFCollection if newPFCollection else 'particleFlow'
		svLabel = 'inclusiveCandidateSecondaryVertices'

		if runOnMC:
			proc.load('RecoJets.Configuration.GenJetParticles_cff')
			setattr( proc, jetalgo+'GenJetsNoNu', ak4GenJets.clone( src = 'genParticlesForJetsNoNu', rParam = jetSize, jetAlgorithm = algorithm ) ) 
			jetSeq += getattr(proc, jetalgo+'GenJetsNoNu' )
		
		

	## b-tag discriminators
	if bTagDiscriminators is None:
		bTagDiscriminators = [
				'pfTrackCountingHighEffBJetTags',
				'pfTrackCountingHighPurBJetTags',
				'pfJetProbabilityBJetTags',
				'pfJetBProbabilityBJetTags',
				'pfSimpleSecondaryVertexHighEffBJetTags',
				'pfSimpleSecondaryVertexHighPurBJetTags',
				'pfCombinedSecondaryVertexV2BJetTags',
				'pfCombinedInclusiveSecondaryVertexV2BJetTags'
	    	]

	### Jet Corrections
	if not set(JETCorrLevels).issubset(set(JECLevels)): 
		if ( 'CHS' in PUMethod ) or  ( 'Plain' in PUMethod ): JETCorrLevels = ['L1FastJet','L2Relative', 'L3Absolute']
		else: JETCorrLevels = [ 'L2Relative', 'L3Absolute']
		if runOnData: JETCorrLevels.append('L2L3Residual')
	if not set(subJETCorrLevels).issubset(set(JECLevels)): 
		if ( 'CHS' in PUMethod ) or  ( 'Plain' in PUMethod ): subJETCorrLevels = ['L1FastJet','L2Relative', 'L3Absolute']
		else: subJETCorrLevels = [ 'L2Relative', 'L3Absolute']
		if runOnData: subJETCorrLevels.append('L2L3Residual')

	####  Creating PATjets
	tmpPfCandName = pfCand.lower()
	if 'Puppi' in PUMethod:
		if ('puppi' in tmpPfCandName): 
			srcForPFJets = pfCand
			print '|---- jetToolBox: Not running puppi algorithm because keyword puppi was specified in nameNewPFCollection, but applying puppi corrections.' 
		else: 
			proc.load('CommonTools.PileupAlgos.Puppi_cff')
			puppi.candName = cms.InputTag( pfCand ) 
			if miniAOD: puppi.vertexName = cms.InputTag('offlineSlimmedPrimaryVertices')
			jetSeq += getattr(proc, 'puppi' )
			srcForPFJets = 'puppi'
		from RecoJets.JetProducers.ak4PFJetsPuppi_cfi import ak4PFJetsPuppi
		setattr( proc, jetalgo+'PFJetsPuppi', 
				ak4PFJetsPuppi.clone( src = cms.InputTag( srcForPFJets ),
					doAreaFastjet = True, 
					rParam = jetSize, 
					jetAlgorithm = algorithm ) )  
		jetSeq += getattr(proc, jetalgo+'PFJetsPuppi' )
		if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PFPuppi'
		if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PFPuppi'

	elif 'CS' in PUMethod:

		from RecoJets.JetProducers.ak4PFJetsCS_cfi import ak4PFJetsCS
		setattr( proc, jetalgo+'PFJetsCS', 
				ak4PFJetsCS.clone( doAreaFastjet = True, 
					csRParam = cms.double(jetSize),
					jetAlgorithm = algorithm ) ) 
		if miniAOD: getattr( proc, jetalgo+'PFJetsCS').src = pfCand
		#setattr( proc, jetalgo+'PFJetsCSConstituents', ak8PFJetsCSConstituents.clone( src = cms.InputTag(jetalgo+'PFJetsCS') ) )
		jetSeq += getattr(proc, jetalgo+'PFJetsCS' )

		#setattr( proc, jetalgo+'PFJetsCSConstituents', ak8PFJetsCSConstituents.clone( src = cms.InputTag(jetalgo+'PFJetsCS') ) )
		jetSeq += getattr(proc, jetalgo+'PFJetsCS' )
		if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PFCS'
		if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PFCS'

	elif 'SK' in PUMethod:

		if ('sk' in tmpPfCandName): 
			srcForPFJets = pfCand
			print '|---- jetToolBox: Not running softkiller algorithm because keyword SK was specified in nameNewPFCollection, but applying SK corrections.' 
		else:
			proc.load('CommonTools.PileupAlgos.softKiller_cfi')
			getattr( proc, 'softKiller' ).PFCandidates = cms.InputTag( pfCand ) 
			jetSeq += getattr(proc, 'softKiller' )
			srcForPFJets = 'softKiller'
		from RecoJets.JetProducers.ak4PFJetsSK_cfi import ak4PFJetsSK
		setattr( proc, jetalgo+'PFJetsSK', 
				ak4PFJetsSK.clone(  src = cms.InputTag( srcForPFJets ),
					rParam = jetSize, 
					jetAlgorithm = algorithm ) ) 
		jetSeq += getattr(proc, jetalgo+'PFJetsSK' )
		if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PFSK'
		if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PFSK'
	
	elif 'CHS' in PUMethod: 
		
		if miniAOD:
			if ('chs' in tmpPfCandName): 
				srcForPFJets = pfCand
				print '|---- jetToolBox: Not running CHS algorithm because keyword CHS was specified in nameNewPFCollection, but applying CHS corrections.' 
			else: 
				setattr( proc, 'chs', cms.EDFilter('CandPtrSelector', src = cms.InputTag( pfCand ), cut = cms.string('fromPV')) )
				jetSeq += getattr(proc, 'chs')
				srcForPFJets = 'chs'
		else:
			if ( pfCand == 'particleFlow' ):
				from RecoParticleFlow.PFProducer.particleFlowTmpPtrs_cfi import particleFlowTmpPtrs
				setattr( proc, 'newParticleFlowTmpPtrs', particleFlowTmpPtrs.clone( src = pfCand ) )
				jetSeq += getattr(proc, 'newParticleFlowTmpPtrs')
				from CommonTools.ParticleFlow.pfNoPileUpJME_cff import pfPileUpJME, pfNoPileUpJME
				proc.load('CommonTools.ParticleFlow.goodOfflinePrimaryVertices_cfi')
				setattr( proc, 'newPfPileUpJME', pfPileUpJME.clone( PFCandidates= 'newParticleFlowTmpPtrs' ) )
				jetSeq += getattr(proc, 'newPfPileUpJME')
				setattr( proc, 'newPfNoPileUpJME', pfNoPileUpJME.clone( topCollection='newPfPileUpJME', bottomCollection= 'newParticleFlowTmpPtrs' ) )
				jetSeq += getattr(proc, 'newPfNoPileUpJME')
				srcForPFJets = 'newPfNoPileUpJME'
			else: 
				proc.load('CommonTools.ParticleFlow.pfNoPileUpJME_cff')
				srcForPFJets = 'pfNoPileUpJME'
			

		setattr( proc, jetalgo+'PFJetsCHS', 
				ak4PFJetsCHS.clone( src = cms.InputTag( srcForPFJets ), 
					doAreaFastjet = True, 
					rParam = jetSize, 
					jetAlgorithm = algorithm ) ) 
		jetSeq += getattr(proc, jetalgo+'PFJetsCHS' )
		if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PFchs'
		if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PFchs'

	else: 
		PUMethod = ''
		setattr( proc, jetalgo+'PFJets', 
				ak4PFJets.clone( 
					doAreaFastjet = True, 
					rParam = jetSize, 
					jetAlgorithm = algorithm ) ) 
		if miniAOD: getattr( proc, jetalgo+'PFJets').src = pfCand
		jetSeq += getattr(proc, jetalgo+'PFJets' )
		if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PF'
		if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PF'

	if 'None' in JETCorrPayload: JEC = None
	else: JEC = ( JETCorrPayload.replace('CS','chs').replace('SK','chs') , JETCorrLevels, 'None' )   ### temporary
	#else: JEC = ( JETCorrPayload., JETCorrLevels, 'None' ) 
	print '|---- jetToolBox: Applying this corrections: '+str(JEC)

	if addPrunedSubjets or addSoftDropSubjets or addCMSTopTagger:
		if 'None' in subJETCorrPayload: subJEC = None
		else: subJEC = ( subJETCorrPayload.replace('CS','chs').replace('SK','chs') , subJETCorrLevels, 'None' )   ### temporary


	if ( 'CHS' in PUMethod ) and miniAOD: setattr( proc, jetalgo+'PFJets'+PUMethod+'Constituents', cms.EDFilter("MiniAODJetConstituentSelector", src = cms.InputTag( jetalgo+'PFJets'+PUMethod ), cut = cms.string( Cut ) ))
	else: setattr( proc, jetalgo+'PFJets'+PUMethod+'Constituents', cms.EDFilter("PFJetConstituentSelector", src = cms.InputTag( jetalgo+'PFJets'+PUMethod ), cut = cms.string( Cut ) ))
	jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'Constituents' )

	addJetCollection(
			proc,
			labelName = jetALGO+'PF'+PUMethod,
			jetSource = cms.InputTag( jetalgo+'PFJets'+PUMethod),
			algo = jetalgo,
			rParam = jetSize,
			jetCorrections = JEC if JEC is not None else None, 
			pfCandidates = cms.InputTag( pfCand ),  
			svSource = cms.InputTag( svLabel ),  
			genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNu'),
			pvSource = cms.InputTag( pvLabel ), 
			btagDiscriminators = bTagDiscriminators,
			getJetMCFlavour = GetJetMCFlavour,
			genParticles = cms.InputTag(genParticlesLabel),
			outputModules = ['outputFile']
			) 


	if 'CS' in PUMethod: getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod ).getJetMCFlavour = False  # CS jets cannot be re-clustered from their constituents
	
	#### Groomers
	if addSoftDrop or addSoftDropSubjets: 

		setattr( proc, jetalgo+'PFJets'+PUMethod+'SoftDrop', 
			ak8PFJetsCHSSoftDrop.clone( 
				src = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Constituents', 'constituents' ),
				rParam = jetSize, 
				jetAlgorithm = algorithm, 
				useExplicitGhosts=True,
				R0= cms.double(jetSize),
				#zcut=zCutSD, 
				beta=betaCut,
				writeCompound = cms.bool(True),
				jetCollInstanceName=cms.string('SubJets') ) )
		setattr( proc, jetalgo+'PFJets'+PUMethod+'SoftDropMass', 
			ak8PFJetsCHSSoftDropMass.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
				matched = cms.InputTag( jetalgo+'PFJets'+PUMethod+'SoftDrop'), 
				distMax = cms.double( jetSize ) ) )

		elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'SoftDropMass_*_*'] 
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'SoftDrop' )
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'SoftDropMass' )
		getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'SoftDropMass']
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'SoftDropMass' )

		if addSoftDropSubjets:

			if runOnMC:
				setattr( proc, jetalgo+'GenJetsNoNuSoftDrop',
						ak4GenJets.clone(
							SubJetParameters,
							useSoftDrop = cms.bool(True),
							rParam = jetSize, 
							jetAlgorithm = algorithm, 
							useExplicitGhosts=cms.bool(True),
							#zcut=cms.double(zCutSD), 
							R0= cms.double(jetSize),
							beta=cms.double(betaCut),
							writeCompound = cms.bool(True),
							jetCollInstanceName=cms.string('SubJets')
							))
				if miniAOD: getattr( proc, jetalgo+'GenJetsNoNuSoftDrop' ).src = 'packedGenParticlesForJetsNoNu'
				jetSeq += getattr(proc, jetalgo+'GenJetsNoNuSoftDrop' )

			addJetCollection(
					proc,
					labelName = jetALGO+'PF'+PUMethod+'SoftDrop',
					jetSource = cms.InputTag( jetalgo+'PFJets'+PUMethod+'SoftDrop'),
					algo = jetalgo,
					rParam = jetSize,
					jetCorrections = JEC if JEC is not None else None, 
					pvSource = cms.InputTag( pvLabel ),
					btagDiscriminators = ['None'],
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNu'),
					getJetMCFlavour = False, # jet flavor should always be disabled for groomed jets
					genParticles = cms.InputTag(genParticlesLabel),
					outputModules = ['outputFile']
					) 

			setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDrop', selectedPatJets.clone( src = 'patJets'+jetALGO+'PF'+PUMethod+'SoftDrop', cut = Cut ) )

			addJetCollection(
					proc,
					labelName = jetALGO+'PF'+PUMethod+'SoftDropSubjets',
					jetSource = cms.InputTag( jetalgo+'PFJets'+PUMethod+'SoftDrop', 'SubJets'),
					algo = jetalgo,  # needed for subjet b tagging
					rParam = jetSize,  # needed for subjet b tagging
					jetCorrections = subJEC if subJEC is not None else None, 
					pfCandidates = cms.InputTag( pfCand ), 
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ),  
					btagDiscriminators = bTagDiscriminators,
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNuSoftDrop','SubJets'),
					getJetMCFlavour = GetSubjetMCFlavour,
					genParticles = cms.InputTag(genParticlesLabel),
					explicitJTA = True,  # needed for subjet b tagging
					svClustering = True, # needed for subjet b tagging
					fatJets=cms.InputTag(jetalgo+'PFJets'+PUMethod),             # needed for subjet flavor clustering
					groomedFatJets=cms.InputTag(jetalgo+'PFJets'+PUMethod+'SoftDrop'), # needed for subjet flavor clustering
					outputModules = ['outputFile']
					) 

			setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropSubjets', selectedPatJets.clone( src = 'patJets'+jetALGO+'PF'+PUMethod+'SoftDropSubjets', cut = Cut ))

			## Establish references between PATified fat jets and subjets using the BoostedJetMerger
			setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropPacked', 
					cms.EDProducer("BoostedJetMerger",
						jetSrc=cms.InputTag('selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDrop'),
						subjetSrc=cms.InputTag('selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropSubjets')
						))
			jetSeq += getattr(proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropPacked' )
			elemToKeep += [ 'keep *_selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropPacked_*_*' ]
			toolsUsed.append( 'selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropPacked' )
			toolsUsed.append( 'selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropSubjets' )

	if addPruning or addPrunedSubjets: 

		setattr( proc, jetalgo+'PFJets'+PUMethod+'Pruned', 
			ak8PFJetsCHSPruned.clone( 
				src = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Constituents', 'constituents' ),
				rParam = jetSize, 
				jetAlgorithm = algorithm, 
				zcut=zCut, 
				rcut_factor=rCut,
				writeCompound = cms.bool(True),
				doAreaFastjet = cms.bool(True),
				jetCollInstanceName=cms.string('SubJets') ) )
		setattr( proc, jetalgo+'PFJets'+PUMethod+'PrunedMass', 
			ak8PFJetsCHSPrunedMass.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
				matched = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Pruned'), 
				distMax = cms.double( jetSize ) ) )

		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'Pruned' )
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'PrunedMass' )
		getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'PrunedMass']
		elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'PrunedMass_*_*'] 
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'PrunedMass' )

		if addPrunedSubjets:
			if runOnMC:
				setattr( proc, jetalgo+'GenJetsNoNuPruned',
						ak4GenJets.clone(
							SubJetParameters,
							rParam = jetSize,
							usePruning = cms.bool(True),
							writeCompound = cms.bool(True),
							jetCollInstanceName=cms.string('SubJets')
							))
				if miniAOD: getattr( proc, jetalgo+'GenJetsNoNuPruned' ).src = 'packedGenParticlesForJetsNoNu'
				jetSeq += getattr(proc, jetalgo+'GenJetsNoNuPruned' )

			addJetCollection(
					proc,
					labelName = jetALGO+'PF'+PUMethod+'Pruned',
					jetSource = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Pruned'),
					algo = jetalgo,
					rParam = jetSize,
					jetCorrections = JEC if JEC is not None else None, 
					pvSource = cms.InputTag( pvLabel ),
					btagDiscriminators = ['None'],
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNu'),
					getJetMCFlavour = False, # jet flavor should always be disabled for groomed jets
					genParticles = cms.InputTag(genParticlesLabel),
					outputModules = ['outputFile']
					) 

			setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'Pruned', selectedPatJets.clone( src = 'patJets'+jetALGO+'PF'+PUMethod+'Pruned', cut = Cut ) )

			addJetCollection(
					proc,
					labelName = jetALGO+'PF'+PUMethod+'PrunedSubjets',
					jetSource = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Pruned', 'SubJets'),
					algo = jetalgo,  # needed for subjet b tagging
					rParam = jetSize,  # needed for subjet b tagging
					jetCorrections = subJEC if subJEC is not None else None, 
					pfCandidates = cms.InputTag( pfCand ),  
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ), 
					getJetMCFlavour = GetSubjetMCFlavour,
					genParticles = cms.InputTag(genParticlesLabel),
					btagDiscriminators = bTagDiscriminators,
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNuPruned','SubJets'),
					explicitJTA = True,  # needed for subjet b tagging
					svClustering = True, # needed for subjet b tagging
					fatJets=cms.InputTag(jetalgo+'PFJets'+PUMethod),             # needed for subjet flavor clustering
					groomedFatJets=cms.InputTag(jetalgo+'PFJets'+PUMethod+'Pruned'), # needed for subjet flavor clustering
					outputModules = ['outputFile']
					) 

			setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedSubjets', selectedPatJets.clone( src = 'patJets'+jetALGO+'PF'+PUMethod+'PrunedSubjets', cut = Cut ) )

			## Establish references between PATified fat jets and subjets using the BoostedJetMerger
			setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedPacked', 
					cms.EDProducer("BoostedJetMerger",
						jetSrc=cms.InputTag('selectedPatJets'+jetALGO+'PF'+PUMethod+'Pruned'),
						subjetSrc=cms.InputTag('selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedSubjets')
						))
			jetSeq += getattr(proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedPacked' )
			elemToKeep += [ 'keep *_selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedPacked_*_*' ]
			toolsUsed.append( 'selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedPacked' )
			toolsUsed.append( 'selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedSubjets' )


	if addTrimming:

		setattr( proc, jetalgo+'PFJets'+PUMethod+'Trimmed', 
				ak8PFJetsCHSTrimmed.clone( 
					rParam = jetSize, 
					src = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Constituents', 'constituents'),
					jetAlgorithm = algorithm,
					rFilt= rFiltTrim,
					trimPtFracMin= ptFrac) ) 
		setattr( proc, jetalgo+'PFJets'+PUMethod+'TrimmedMass', 
				ak8PFJetsCHSTrimmedMass.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
					matched = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Trimmed'), 
					distMax = cms.double( jetSize ) ) )

		elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'TrimmedMass_*_*'] 
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'Trimmed' )
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'TrimmedMass' )
		getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'TrimmedMass']
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'TrimmedMass' )

	if addFiltering:

		setattr( proc, jetalgo+'PFJets'+PUMethod+'Filtered', 
				ak8PFJetsCHSFiltered.clone( 
					src = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Constituents', 'constituents' ),
					rParam = jetSize, 
					jetAlgorithm = algorithm,
					rFilt= rfilt,
					nFilt= nfilt ) ) 
		setattr( proc, jetalgo+'PFJets'+PUMethod+'FilteredMass', 
				ak8PFJetsCHSFilteredMass.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
					matched = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Filtered'), 
					distMax = cms.double( jetSize ) ) )
		elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'FilteredMass_*_*'] 
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'Filtered' )
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'FilteredMass' )
		getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'FilteredMass']
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'FilteredMass' )

	if addCMSTopTagger :

		if 'CA' in jetALGO : 

			setattr( proc, 'cmsTopTagPFJets'+PUMethod,  
					cms.EDProducer("CATopJetProducer",
						PFJetParameters.clone( 
							src = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Constituents', 'constituents' ),
							doAreaFastjet = cms.bool(True),
							doRhoFastjet = cms.bool(False),
							jetPtMin = cms.double(100.0)
							),
						AnomalousCellParameters,
						CATopJetParameters.clone( jetCollInstanceName = cms.string("SubJets"),
							verbose = cms.bool(False),
							algorithm = cms.int32(1), # 0 = KT, 1 = CA, 2 = anti-KT
							tagAlgo = cms.int32(0), #0=legacy top
							useAdjacency = cms.int32(2), # modified adjacency
							centralEtaCut = cms.double(2.5), # eta for defining "central" jets
							sumEtBins = cms.vdouble(0,1600,2600), # sumEt bins over which cuts vary. vector={bin 0 lower bound, bin 1 lower bound, ...}
							rBins = cms.vdouble(0.8,0.8,0.8), # Jet distance paramter R. R values depend on sumEt bins.
							ptFracBins = cms.vdouble(0.05,0.05,0.05), # minimum fraction of central jet pt for subjets (deltap)
							deltarBins = cms.vdouble(0.19,0.19,0.19), # Applicable only if useAdjacency=1. deltar adjacency values for each sumEtBin
							nCellBins = cms.vdouble(1.9,1.9,1.9),
							),
						jetAlgorithm = cms.string("CambridgeAachen"),
						rParam = cms.double(jetSize),
						writeCompound = cms.bool(True)
						)
					)
			
			setattr( proc, "CATopTagInfos", 
					cms.EDProducer("CATopJetTagger",
						src = cms.InputTag('cmsTopTagPFJets'+PUMethod),
						TopMass = cms.double(171),
						TopMassMin = cms.double(0.),
						TopMassMax = cms.double(250.),
						WMass = cms.double(80.4),
						WMassMin = cms.double(0.0),
						WMassMax = cms.double(200.0),
						MinMassMin = cms.double(0.0),
						MinMassMax = cms.double(200.0),
						verbose = cms.bool(False)
						)
					)
			addJetCollection(
					proc,
					labelName = 'CMSTopTag'+PUMethod,
					jetSource = cms.InputTag('cmsTopTagPFJets'+PUMethod),
					jetCorrections = JEC if JEC is not None else None, 
					pfCandidates = cms.InputTag( pfCand ),  
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ), 
					btagDiscriminators = bTagDiscriminators,
					genJetCollection = cms.InputTag(jetalgo+'GenJetsNoNu'),
					getJetMCFlavour = False, # jet flavor should always be disabled for groomed jets
					genParticles = cms.InputTag(genParticlesLabel)
					)
			getattr(proc,'patJetsCMSTopTag'+PUMethod).addTagInfos = True
			getattr(proc,'patJetsCMSTopTag'+PUMethod).tagInfoSources = cms.VInputTag( cms.InputTag('CATopTagInfos'))
			setattr( proc, 'selectedPatJetsCMSTopTag'+PUMethod, selectedPatJets.clone( src = 'patJetsCMSTopTag'+PUMethod, cut = Cut ) )

			addJetCollection(
					proc,
					labelName = 'CMSTopTag'+PUMethod+'Subjets',
					jetSource = cms.InputTag('cmsTopTagPFJets'+PUMethod, 'SubJets'),
					algo = jetalgo,  # needed for subjet b tagging
					rParam = jetSize,  # needed for subjet b tagging
					jetCorrections = subJEC if subJEC is not None else None, 
					pfCandidates = cms.InputTag( pfCand ),  
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ), 
					btagDiscriminators = bTagDiscriminators,
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNu'),
					getJetMCFlavour = GetSubjetMCFlavour,
					explicitJTA = True,  # needed for subjet b tagging
					svClustering = True, # needed for subjet b tagging
					fatJets=cms.InputTag(jetalgo+'PFJets'+PUMethod),             # needed for subjet flavor clustering
					groomedFatJets=cms.InputTag('patJetsCMSTopTag'+PUMethod), # needed for subjet flavor clustering
					genParticles = cms.InputTag(genParticlesLabel)
					)

			setattr( proc, 'selectedPatJetsCMSTopTag'+PUMethod+'Subjets', selectedPatJets.clone( src = 'patJetsCMSTopTag'+PUMethod+'Subjets', cut = Cut ) )

			setattr( proc, 'patJetsCMSTopTag'+PUMethod+'Packed', 
					cms.EDProducer("BoostedJetMerger",
						jetSrc=cms.InputTag('patJetsCMSTopTag'+PUMethod ),
						subjetSrc=cms.InputTag('patJetsCMSTopTag'+PUMethod+'Subjets')
						))
			jetSeq += getattr(proc, 'patJetsCMSTopTag'+PUMethod+'Packed' )
			elemToKeep += [ 'keep *_patJetsCMSTopTag'+PUMethod+'Packed_*_*' ]
			toolsUsed.append( 'patJetsCMSTopTag'+PUMethod+'Packed' )

		else: print '|---- jetToolBox: CMS recommends CambridgeAachen for CMS Top Tagger, you are using '+algorithm+'. JetToolbox will not run CMS Top Tagger.'

	if addMassDrop :

		if 'CA' in jetALGO : 
			setattr( proc, jetalgo+'PFJets'+PUMethod+'MassDropFiltered', 
					ca15PFJetsCHSMassDropFiltered.clone( 
						rParam = jetSize,
						src = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Constituents', 'constituents' ),
						) )
			setattr( proc, jetalgo+'PFJets'+PUMethod+'MassDropFilteredMass', ak8PFJetsCHSPrunedMass.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
				matched = cms.InputTag(jetalgo+'PFJets'+PUMethod+'MassDropFiltered'), distMax = cms.double( jetSize ) ) )
			elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'MassDropFilteredMass_*_*' ]
			getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'MassDropFilteredMass' ]
			jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'MassDropFiltered' )
			jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'MassDropFilteredMass' )
		else: print '|---- jetToolBox: CMS recommends CambridgeAachen for Mass Drop, you are using '+algorithm+'. JetToolbox will not run Mass Drop.'
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'MassDropFilteredMass' )

	if addHEPTopTagger: 
		if ( jetSize >= 1. ) and ( 'CA' in jetALGO ): 

			setattr( proc, 'hepTopTagPFJets'+PUMethod, hepTopTagPFJetsCHS.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Constituents', 'constituents' ) ) )
			setattr( proc, 'hepTopTagPFJets'+PUMethod+'Mass'+jetALGO, ak8PFJetsCHSPrunedMass.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
				matched = cms.InputTag("hepTopTagPFJets"+PUMethod), distMax = cms.double( jetSize ) ) )
			elemToKeep += [ 'keep *_hepTopTagPFJets'+PUMethod+'Mass'+jetALGO+'_*_*' ]
			getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ 'hepTopTagPFJets'+PUMethod+'Mass'+jetALGO ]
			jetSeq += getattr(proc, 'hepTopTagPFJets'+PUMethod )
			jetSeq += getattr(proc, 'hepTopTagPFJets'+PUMethod+'Mass'+jetALGO )
			toolsUsed.append( 'hepTopTagPFJets'+PUMethod+'Mass'+jetALGO )
		else: print '|---- jetToolBox: CMS recommends CambridgeAachen for HEPTopTagger, you are using '+algorithm+', and a jet cone size bigger than 1. JetToolbox will not run HEP TopTagger.'

	####### Nsubjettiness
	if addNsub:
		from RecoJets.JetProducers.nJettinessAdder_cfi import Njettiness

		rangeTau = range(1,maxTau+1)
		setattr( proc, 'Njettiness'+jetALGO+PUMethod, 
				Njettiness.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
					Njets=cms.vuint32(rangeTau),         # compute 1-, 2-, 3-, 4- subjettiness
					# variables for measure definition : 
					measureDefinition = cms.uint32( 0 ), # CMS default is normalized measure
					beta = cms.double(1.0),              # CMS default is 1
					R0 = cms.double( jetSize ),              # CMS default is jet cone size
					Rcutoff = cms.double( -999.0),       # not used by default
					# variables for axes definition :
					axesDefinition = cms.uint32( 6 ),    # CMS default is 1-pass KT axes
					nPass = cms.int32(-999),             # not used by default
					akAxesR0 = cms.double(-999.0) ) )        # not used by default

		elemToKeep += [ 'keep *_Njettiness'+jetALGO+PUMethod+'_*_*' ]
		for tau in rangeTau: getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += ['Njettiness'+jetALGO+PUMethod+':tau'+str(tau) ] 
		jetSeq += getattr(proc, 'Njettiness'+jetALGO+PUMethod )
		toolsUsed.append( 'Njettiness'+jetALGO+PUMethod )

	###### QJetsAdder
	'''
	if addQJets:
		### there must be a better way to do this random number introduction
		setattr( proc, 'RandomNumberGeneratorService', cms.Service("RandomNumberGeneratorService", 
							QJetsAdderCA8 = cms.PSet(initialSeed = cms.untracked.uint32(7)),
							QJetsAdderAK8 = cms.PSet(initialSeed = cms.untracked.uint32(31)),
							QJetsAdderCA15 = cms.PSet(initialSeed = cms.untracked.uint32(76)), ) )

		from RecoJets.JetProducers.qjetsadder_cfi import QJetsAdder
		setattr( proc, 'QJetsAdder'+jetALGO, 
				QJetsAdder.clone( src = cms.InputTag(jetalgo+'PFJets'+PUMethod), 
					jetRad = cms.double( jetSize ), 
					jetAlgo = cms.string( jetALGO[0:2] )))
		elemToKeep += [ 'keep *_QJetsAdder'+jetALGO+'_*_*' ]
		getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += ['QJetsAdder'+jetALGO+':QjetsVolatility']  
		jetSeq += getattr(proc, 'QJetsAdder'+jetALGO )
		toolsUsed.append( 'QJetsAdder'+jetALGO )
	'''

	###### QGTagger
	if addQGTagger:
		if ( 'ak4' in jetalgo ) and ( PUMethod not in ['Puppi','CS','SK'] ) :
			from RecoJets.JetProducers.QGTagger_cfi import QGTagger
			proc.load('RecoJets.JetProducers.QGTagger_cfi') 	## In 74X you need to run some stuff before.
			setattr( proc, 'QGTagger'+jetALGO+'PF'+PUMethod, 
					QGTagger.clone(
						srcJets = cms.InputTag(jetalgo+'PFJets'+PUMethod),    # Could be reco::PFJetCollection or pat::JetCollection (both AOD and miniAOD)
						jetsLabel = cms.string('QGL_AK4PF'+QGjetsLabel)        # Other options (might need to add an ESSource for it): see https://twiki.cern.ch/twiki/bin/viewauth/CMS/QGDataBaseVersion
						)
					)
			elemToKeep += [ 'keep *_QGTagger'+jetALGO+'PF'+PUMethod+'_*_*' ]
			getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += ['QGTagger'+jetALGO+'PF'+PUMethod+':qgLikelihood']  
			jetSeq += getattr(proc, 'QGTagger'+jetALGO+'PF'+PUMethod )

                        toolsUsed.append( 'QGTagger'+jetALGO+'PF'+PUMethod )
		else:
			print '|---- jetToolBox: QGTagger is optimized for ak4 jets with CHS. NOT running QGTagger'

			
	####### Pileup JetID
        if addPUJetID:
                if ( 'ak4' in jetalgo ) and ( 'CHS' in PUMethod ):
                        from RecoJets.JetProducers.pileupjetidproducer_cfi import pileupJetIdCalculator,pileupJetIdEvaluator

			setattr( proc, jetALGO+'PF'+PUMethod+'pileupJetIdCalculator',
					pileupJetIdCalculator.clone(
						jets = cms.InputTag(jetalgo+'PFJets'+PUMethod),
						rho = cms.InputTag("fixedGridRhoFastjetAll"),
						vertexes = cms.InputTag(pvLabel),
						applyJec = cms.bool(True),
						inputIsCorrected = cms.bool(False)
						))

			setattr( proc, jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator',
					pileupJetIdEvaluator.clone(
						jetids = cms.InputTag(jetALGO+'PF'+PUMethod+'pileupJetIdCalculator'),
						jets = cms.InputTag(jetalgo+'PFJets'+PUMethod),
						rho = cms.InputTag("fixedGridRhoFastjetAll"),
						vertexes = cms.InputTag(pvLabel)
						)
					)

                        getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator:fullDiscriminant']
                        getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userInts.src += [jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator:cutbasedId',jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator:fullId']
                        elemToKeep += ['keep *_'+jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator_*_*']
                        toolsUsed.append( jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator' )
		else:
                        print '|---- jetToolBox: PUJetID is optimized for ak4 PFjets with CHS. NOT running PUJetID.'

	###### Energy Correlation Functions
	if addEnergyCorrFunc:
		from RecoJets.JetProducers.ECF_cfi import ECF 
		rangeECF = range(1,maxECF+1)
		setattr( proc, jetalgo+'PFJets'+PUMethod+'ECF', ECF.clone(
				src = cms.InputTag(jetalgo+'PFJets'+PUMethod),
				Njets = cms.vuint32( rangeECF ),
				beta = cms.double( ecfBeta ) 
				))

		elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'ECF_*_*'] 
		for ecf in rangeECF: getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'ECF:ecf'+str(ecf) ]
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'ECF' )
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'ECF' )
	
	if hasattr(proc, 'patJetPartons'): proc.patJetPartons.particles = genParticlesLabel


	setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod, selectedPatJets.clone( src = 'patJets'+jetALGO+'PF'+PUMethod, cut = Cut ) )
	elemToKeep += [ 'keep *_selectedPatJets'+jetALGO+'PF'+PUMethod+'_*_*' ]
	elemToKeep += [ 'drop *_selectedPatJets'+jetALGO+'PF'+PUMethod+'_calo*_*' ]
	elemToKeep += [ 'drop *_selectedPatJets'+jetALGO+'PF'+PUMethod+'_tagInfos_*' ]


	if len(toolsUsed) > 0 : print '|---- jetToolBox: Running '+', '.join(toolsUsed)+'.'
	print '|---- jetToolBox: Creating selectedPatJets'+jetALGO+'PF'+PUMethod+' collection.'

	### "return"
	setattr(proc, jetSequence, jetSeq)
	if hasattr(proc, outputFile): getattr(proc, outputFile).outputCommands += elemToKeep
	else: setattr( proc, outputFile, 
			cms.OutputModule('PoolOutputModule', 
				fileName = cms.untracked.string('jettoolbox.root'), 
				outputCommands = cms.untracked.vstring( elemToKeep ) ) )

	if runOnData:
		from PhysicsTools.PatAlgos.tools.coreTools import removeMCMatching
		removeMCMatching(proc, names=['Jets'], outputModules=[outputFile])
def jetToolbox(proc,
               jetType,
               jetSequence,
               PUMethod='',
               bTagDiscriminators=None):

    JETCorrPayload = 'None'
    JETCorrLevels = ['None']
    bTagDiscriminators = [  #'trackCountingHighEffBJetTags',
        #'trackCountingHighPurBJetTags',
        #'pfTrackCountingHighEffBJetTags',
        #'pfTrackCountingHighPurBJetTags',
        #'softPFMuonByIP3dBJetTags',
        #'softPFElectronByIP3dBJetTags',
        #'softPFMuonBJetTags',
        #'softPFElectronBJetTags',
        #'simpleSecondaryVertexHighEffBJetTags',
        #'simpleSecondaryVertexHighPurBJetTags',
        #'pfSimpleSecondaryVertexHighEffBJetTags',
        #'pfSimpleSecondaryVertexHighPurBJetTags',
        #'combinedSecondaryVertexV2BJetTags',
        #'deepFlavourJetTags:probb',
        #'deepFlavourJetTags:probc',
        #'deepFlavourJetTags:probudsg',
        #'deepFlavourJetTags:probbb',
        #'deepFlavourJetTags:probcc',
        #'negativeDeepFlavourJetTags:probb',
        #'negativeDeepFlavourJetTags:probc',
        #'negativeDeepFlavourJetTags:probudsg',
        #'negativeDeepFlavourJetTags:probbb',
        #'negativeDeepFlavourJetTags:probcc',
        #'positiveDeepFlavourJetTags:probb',
        #'positiveDeepFlavourJetTags:probc',
        #'positiveDeepFlavourJetTags:probudsg',
        #'positiveDeepFlavourJetTags:probbb',
        #'positiveDeepFlavourJetTags:probcc',
        #'pfCombinedCvsLJetTags',
        #'pfCombinedCvsBJetTags',
        'pfBoostedDoubleSecondaryVertexAK8BJetTags',
        'pfCombinedSecondaryVertexV2BJetTags',
        'pfPositiveCombinedSecondaryVertexV2BJetTags',  #implemented
        'pfNegativeCombinedSecondaryVertexV2BJetTags',  #implemented
        'pfCombinedInclusiveSecondaryVertexV2BJetTags',  #implemented
        'pfCombinedMVAV2BJetTags',  #implemented
        'pfJetProbabilityBJetTags'
    ]  #implemented

    GetJetMCFlavour = ['True']
    #JECLevels = [ 'L1Offset', 'L1FastJet', 'L1JPTOffset', 'L2Relative', 'L3Absolute', 'L5Falvour', 'L7Parton' ]

    algorithm = 'AntiKt'  # CambridgeAachen' , 'Kt'
    size = jetType[-1:]  #[-1:] takes the last char from string 'akX'
    jetSize = float('0.' + jetType[-1:])
    jetALGO = jetType.upper()
    jetalgo = jetType.lower()
    elemToKeep = []

    print 'Running processes with: ' + str(
        jetALGO
    ) + ' PF ' + PUMethod + ' jet algorithm with radius parameter ' + str(
        jetSize)

    JETCorrPayload = 'AK' + size + 'PF' + PUMethod.lower()
    JETCorrLevels = ['L1FastJet', 'L2Relative', 'L3Absolute']
    #JETCorrLevels = [] #No JEC corrections
    JEC = (JETCorrPayload, JETCorrLevels, 'None')

    #################################################################################
    ####### Toolbox start
    #################################################################################

    elemToKeep = []
    jetSeq = cms.Sequence()
    genParticlesLabel = ''
    pvLabel = ''
    tvLabel = ''
    toolsUsed = []

    proc.load('RecoJets.Configuration.GenJetParticles_cff')
    setattr(
        proc, jetalgo + 'GenJetsNoNu',
        ak4GenJets.clone(src='genParticlesForJetsNoNu',
                         rParam=jetSize,
                         jetAlgorithm=algorithm))
    jetSeq += getattr(proc, jetalgo + 'GenJetsNoNu')

    proc.load('CommonTools.ParticleFlow.pfNoPileUpJME_cff')
    ####  Creating PATjets
    if (PUMethod == 'CHS'):
        setattr(proc, jetalgo + 'PFJetsCHS',
                ak4PFJets.clone(rParam=jetSize, jetAlgorithm=algorithm))
        jetSeq += getattr(proc, jetalgo + 'PFJetsCHS')

        setattr(
            proc, jetalgo + 'PFJetsCHS',
            ak4PFJetsCHS.clone(doAreaFastjet=True,
                               rParam=jetSize,
                               jetAlgorithm=algorithm))
        jetSeq += getattr(proc, jetalgo + 'PFJetsCHS')

    else:
        setattr(proc, jetalgo + 'PFJets',
                ak4PFJets.clone(rParam=jetSize, jetAlgorithm=algorithm))
        jetSeq += getattr(proc, jetalgo + 'PFJets')

        setattr(
            proc, jetalgo + 'PFJets',
            ak4PFJets.clone(doAreaFastjet=True,
                            rParam=jetSize,
                            jetAlgorithm=algorithm))
        jetSeq += getattr(proc, jetalgo + 'PFJets')
        PUMethod = ''

    addJetCollection(
        proc,
        labelName=jetALGO + 'PF' + PUMethod,
        jetSource=cms.InputTag(jetalgo + 'PFJets' + PUMethod),
        algo=jetalgo,
        btagDiscriminators=bTagDiscriminators,
        rParam=jetSize,
        jetCorrections=
        JEC,  #( 'AK'+size+'PFchs', cms.vstring( ['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
        pfCandidates=cms.InputTag('particleFlow'),  #'packedPFCandidates'),
        svSource=cms.InputTag('inclusiveCandidateSecondaryVertices'),
        genJetCollection=cms.InputTag(jetalgo + 'GenJetsNoNu'),
        pvSource=cms.InputTag(
            'offlinePrimaryVertices'),  #'offlineSlimmedPrimaryVertices'),
        jetTrackAssociation=True,
    )

    #setattr( proc, jetALGO+'PF'+PUMethod+'pileupJetIdCalculator',
    #			pileupJetIdCalculator.clone(
    #				jets = cms.InputTag(jetalgo+'PFJets'+PUMethod),
    #				rho = cms.InputTag("fixedGridRhoFastjetAll"),
    #				vertexes = cms.InputTag('offlinePrimaryVertices'),
    #				applyJec = cms.bool(True),
    #				inputIsCorrected = cms.bool(False)
    #				))

    #	setattr( proc, jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator',
    #			pileupJetIdEvaluator.clone(
    #				jetids = cms.InputTag(jetALGO+'PF'+PUMethod+'pileupJetIdCalculator'),
    #				jets = cms.InputTag(jetalgo+'PFJets'+PUMethod),
    #				rho = cms.InputTag("fixedGridRhoFastjetAll"),
    #				vertexes = cms.InputTag('offlinePrimaryVertices'),
    #                               applyJec = cms.bool(True),
    #                                inputIsCorrected = cms.bool(False)
    #
    #				)
    #			)

    #getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator:fullDiscriminant']
    #getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userInts.src += [jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator:cutbasedId',jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator:fullId']

    QGjetsLabel = 'chs'

    setattr(
        proc,
        'QGTagger' + jetALGO + 'PF' + PUMethod,
        QGTagger.clone(
            srcJets=cms.InputTag(
                jetalgo + 'PFJets' + PUMethod
            ),  # Could be reco::PFJetCollection or pat::JetCollection (both AOD and miniAOD)
            jetsLabel=cms.string(
                'QGL_AK4PF' + QGjetsLabel
            )  # Other options (might need to add an ESSource for it): see https://twiki.cern.ch/twiki/bi
        ))
    elemToKeep += ['keep *_QGTagger' + jetALGO + 'PF' + PUMethod + '_*_*']
    getattr(proc,
            'patJets' + jetALGO + 'PF' + PUMethod).userData.userFloats.src += [
                'QGTagger' + jetALGO + 'PF' + PUMethod + ':qgLikelihood'
            ]
    jetSeq += getattr(proc, 'QGTagger' + jetALGO + 'PF' + PUMethod)

    toolsUsed.append('QGTagger' + jetALGO + 'PF' + PUMethod)

    getattr(proc, 'patJetPartons').particles = cms.InputTag(
        'genParticles')  #'prunedGenParticles')
    setattr(proc, 'selectedPatJets' + jetALGO + 'PF' + PUMethod,
            selectedPatJets.clone(src='patJets' + jetALGO + 'PF' + PUMethod))
    setattr(proc, jetSequence, jetSeq)
예제 #18
0
def addFlashggPFCHSJets(process,
                        isData,
                        vertexIndex=0,
                        useZeroVertex=False,
                        label='',
                        debug=False):

    #if useZeroVertex:
    setattr(
        process, 'pfCHSLeg' + label,
        cms.EDFilter("CandPtrSelector",
                     src=cms.InputTag("packedPFCandidates"),
                     cut=cms.string("fromPV(%i)" % vertexIndex)))
    #else:
    #    setattr(process, 'selectedMuons' + label, cms.EDFilter("CandPtrSelector",
    #                                                           src = cms.InputTag("slimmedMuons"),
    #                                                           cut = cms.string('''abs(eta)<2.5 && pt>10. &&
    #                                                         (pfIsolationR04().sumChargedHadronPt+
    #                                                         max(0.,pfIsolationR04().sumNeutralHadronEt+
    #                                                         pfIsolationR04().sumPhotonEt-
    #                                                         0.50*pfIsolationR04().sumPUPt))/pt < 0.20 &&
    #                                                         (isPFMuon && (isGlobalMuon || isTrackerMuon) )''')))

    #    setattr(process, 'selectedElectrons' + label, cms.EDFilter("CandPtrSelector",
    #                                                               src = cms.InputTag("slimmedElectrons"),
    #                                                               cut = cms.string('''abs(eta)<2.5 && pt>20. &&
    #                                                             gsfTrack.isAvailable() &&
    #                                                             gsfTrack.hitPattern().numberOfLostHits(\'MISSING_INNER_HITS\') < 2 &&
    #                                                             (pfIsolationVariables().sumChargedHadronPt+
    #                                                             max(0.,pfIsolationVariables().sumNeutralHadronEt+
    #                                                             pfIsolationVariables().sumPhotonEt-
    #                                                             0.5*pfIsolationVariables().sumPUPt))/pt < 0.15''')))

    #    # Simple producer which just removes the Candidates which
    #    # don't come from the legacy vertex according to the Flashgg Vertex Map
    #    setattr(process,'flashggCHSLegacyVertexCandidates' + label,
    #            cms.EDProducer('FlashggMultiCHSLegacyVertexCandProducer',
    #                           PFCandidatesTag       = cms.InputTag('packedPFCandidates'),
    #                           DiPhotonTag           = cms.InputTag('flashggDiPhotons'),
    #                           VertexCandidateMapTag = cms.InputTag("flashggVertexMapForCHS"),
    #                           VertexTag             = cms.InputTag('offlineSlimmedPrimaryVertices'),
    #                           vertexIndex           = cms.uint32(vertexIndex),
    #                           debug                 = cms.untracked.bool(debug)
    #                           )
    #            )

    #    setattr(process, 'pfCHSLeg' + label, cms.EDFilter("CandPtrSelector",
    #                                                      src = cms.InputTag('flashggCHSLegacyVertexCandidates' + label),
    #                                                      cut = cms.string('')))

    #    #   then remove the previously selected muons
    #    setattr(process, 'pfNoMuonCHSLeg' + label,  cms.EDProducer("CandPtrProjector",
    #                                                               src  = cms.InputTag("pfCHSLeg" + label),
    #                                                               veto = cms.InputTag("selectedMuons" + label)))
    #    # then remove the previously selected electrons
    #    setattr(process, 'pfNoElectronsCHSLeg' + label,  cms.EDProducer("CandPtrProjector",
    #                                                                  src  = cms.InputTag("pfNoMuonCHSLeg" + label),
    #                                                                  veto = cms.InputTag("selectedElectrons" + label)))

    #Import RECO jet producer for ak4 PF and GEN jet
    from RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJets
    #if useZeroVertex:
    setattr(process, 'ak4PFJetsCHSLeg' + label,
            ak4PFJets.clone(src='pfCHSLeg' + label, doAreaFastjet=True))
    #else:
    #    setattr(process, 'ak4PFJetsCHSLeg' + label, ak4PFJets.clone ( src = 'pfNoElectronsCHSLeg' + label, doAreaFastjet = True))

    if isData:
        JECs = ['L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual']
    else:
        JECs = ['L1FastJet', 'L2Relative', 'L3Absolute']

    # NOTE: this is the 74X recipe for the jet clustering
    addJetCollection(
        process,
        postfix=label,
        labelName='AK4PFCHSLeg',
        jetSource=cms.InputTag('ak4PFJetsCHSLeg' + label),
        pvSource=cms.InputTag('offlineSlimmedPrimaryVertices'),
        pfCandidates=cms.InputTag('packedPFCandidates'),
        svSource=cms.InputTag('slimmedSecondaryVertices'),
        elSource=cms.InputTag("slimmedElectrons"),
        muSource=cms.InputTag("slimmedMuons"),
        runIVF=True,
        btagDiscriminators=[
            flashggBTag, flashggCMVABTag, flashggDeepCSVb, flashggDeepCSVbb,
            flashggDeepCSVc, flashggDeepCSVudsg
        ],
        jetCorrections=('AK4PFchs', JECs, 'None'),
        genJetCollection=cms.InputTag('slimmedGenJets'),
        genParticles=cms.InputTag('prunedGenParticles'),
        # jet param
        algo='AK',
        rParam=0.4)

    #Recalculate btagging info
    getattr(process, 'patJetsAK4PFCHSLeg' + label).addTagInfos = True

    #adjust PV used for Jet Corrections
    getattr(process, 'patJetCorrFactorsAK4PFCHSLeg' +
            label).primaryVertices = "offlineSlimmedPrimaryVertices"

    # Add MiniAOD jet with Deep flavour for matching with flashgg jets based on 0th vertex
    from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
    updateJetCollection(
        process,
        jetSource=cms.InputTag("slimmedJets"),
        pvSource=cms.InputTag('offlineSlimmedPrimaryVertices'),
        svSource=cms.InputTag('slimmedSecondaryVertices'),
        btagDiscriminators=[
            flashggDeepFlavourb,
            flashggDeepFlavourbb,
            flashggDeepFlavourc,
            flashggDeepFlavouruds,
            flashggDeepFlavourlepb,
            flashggDeepFlavourg,
        ],
        jetCorrections=('AK4PFchs', JECs, 'None'),
    )
    miniaodJets = "selectedUpdatedPatJets"

    # Add new gq tagger database
    process.QGPoolDBESSource = cms.ESSource(
        "PoolDBESSource",
        CondDBSetup,
        toGet=cms.VPSet(),
        connect=cms.string(
            'sqlite_fip:flashggPlugins/flashggAnalysisNtuplizer/data/QGL_' +
            qgDatabaseVersion + '.db'))
    process.es_prefer_qg = cms.ESPrefer('PoolDBESSource', 'QGPoolDBESSource')

    process.QGPoolDBESSource.toGet.extend(
        cms.VPSet(
            cms.PSet(record=cms.string('QGLikelihoodRcd'),
                     tag=cms.string('QGLikelihoodObject_v1_AK4'),
                     label=cms.untracked.string('QGL_AK4PFchs'))))

    from RecoJets.JetProducers.QGTagger_cfi import QGTagger
    setattr(
        process, 'QGTaggerPFCHS' + label,
        QGTagger.clone(srcJets='patJetsAK4PFCHSLeg' + label,
                       jetsLabel='QGL_AK4PFchs',
                       vertexIndex=cms.uint32(vertexIndex),
                       srcVertexCollection='offlineSlimmedPrimaryVertices'))

    from RecoJets.JetProducers.PileupJetIDParams_cfi import full_81x_chs
    flashggJets = cms.EDProducer(
        'FlashggJetProducer',
        DiPhotonTag=cms.InputTag('flashggDiPhotons'),
        VertexTag=cms.InputTag('offlineSlimmedPrimaryVertices'),
        JetTag=cms.InputTag('patJetsAK4PFCHSLeg' + label),
        VertexCandidateMapTag=cms.InputTag("flashggVertexMapForCHS"),
        qgVariablesInputTag=cms.InputTag('QGTaggerPFCHS' + label,
                                         'qgLikelihood'),
        ComputeSimpleRMS=cms.bool(True),
        PileupJetIdParameters=full_81x_chs,
        rho=cms.InputTag("fixedGridRhoFastjetAll"),
        JetCollectionIndex=cms.uint32(vertexIndex),
        Debug=cms.untracked.bool(debug),
        DoPuJetID=cms.bool(True),
        ComputeRegVars=cms.bool(True),
        MinPtForEneSum=cms.double(0.),
        MaxEtaForEneSum=cms.double(2.5),
        NJetsForEneSum=cms.uint32(0),
        MiniAodJetTag=cms.InputTag(miniaodJets))
    setattr(process, 'flashggPFCHSJets' + label, flashggJets)

    # randomize Jets
    from flashgg.MicroAOD.flashggRandomizedJetProducer_cfi import flashggRandomizedJets
    flashggRandomizedPFCHSJets = flashggRandomizedJets.clone()
    flashggRandomizedPFCHSJets.src = "flashggPFCHSJets" + label
    setattr(process.RandomNumberGeneratorService,
            'flashggRandomizedPFCHSJets' + label,
            cms.PSet(initialSeed=cms.untracked.uint32(36423784 + int(label))))
    setattr(process, 'flashggRandomizedPFCHSJets' + label,
            flashggRandomizedPFCHSJets)

    flashggSelectedJets = cms.EDFilter(
        "FLASHggJetSelector",
        src=cms.InputTag('flashggRandomizedPFCHSJets' + label),
        cut=cms.string("pt > 15."))
    setattr(process, 'flashggSelectedPFCHSJets' + label, flashggSelectedJets)
예제 #19
0
run2_nanoAOD_92X.toModify(
    genJetFlavourTable,
    jetFlavourInfos=cms.InputTag("genJetFlavourAssociation"),
)

#before cross linking
jetSequence = cms.Sequence(tightJetId + tightJetIdLepVeto + bJetVars +
                           slimmedJetsWithUserData + jetCorrFactorsNano +
                           updatedJets + tightJetIdAK8 + tightJetIdLepVetoAK8 +
                           slimmedJetsAK8WithUserData + jetCorrFactorsAK8 +
                           updatedJetsAK8 + chsForSATkJets + softActivityJets +
                           softActivityJets2 + softActivityJets5 +
                           softActivityJets10 + finalJets + finalJetsAK8)

from RecoJets.JetProducers.QGTagger_cfi import QGTagger
qgtagger80x = QGTagger.clone(
    srcJets="slimmedJets", srcVertexCollection="offlineSlimmedPrimaryVertices")

_jetSequence_80X = jetSequence.copy()
_jetSequence_80X.replace(tightJetIdLepVeto, looseJetId)
_jetSequence_80X.replace(tightJetIdLepVetoAK8, looseJetIdAK8)
_jetSequence_80X.insert(1, qgtagger80x)
run2_miniAOD_80XLegacy.toReplaceWith(jetSequence, _jetSequence_80X)

#after cross linkining
jetTables = cms.Sequence(bjetMVA + bjetNN + jetTable + fatJetTable +
                         subJetTable + saJetTable + saTable)

#MC only producers and tables
jetMC = cms.Sequence(jetMCTable + genJetTable + patJetPartons +
                     genJetFlavourTable + genJetAK8Table +
                     genJetAK8FlavourAssociation + genJetAK8FlavourTable +
예제 #20
0
def jetToolbox( proc, jetType, jetSequence, outputFile,
		updateCollection='', updateCollectionSubjets='',
		newPFCollection=False, nameNewPFCollection = '',	
		PUMethod='CHS', 
		miniAOD=True,
		runOnMC=True,
		JETCorrPayload='', JETCorrLevels = [ 'None' ], GetJetMCFlavour=True,
		Cut = '', 
		postFix='',
		# blank means default list of discriminators, None means none
		bTagDiscriminators = '',
		bTagInfos = None, 
		subjetBTagDiscriminators = '',
		subjetBTagInfos = None, 
		subJETCorrPayload='', subJETCorrLevels = [ 'None' ], GetSubjetMCFlavour=True,
		CutSubjet = '', 
		addPruning=False, zCut=0.1, rCut=0.5, addPrunedSubjets=False,
		addSoftDrop=False, betaCut=0.0,  zCutSD=0.1, addSoftDropSubjets=False,
		addTrimming=False, rFiltTrim=0.2, ptFrac=0.03,
		addFiltering=False, rfilt=0.3, nfilt=3,
		addCMSTopTagger=False,
		addMassDrop=False,
		addHEPTopTagger=False,
		addNsub=False, maxTau=4,
		addNsubSubjets=False, subjetMaxTau=4,
		addPUJetID=False,
		addQGTagger=False, QGjetsLabel='chs',
		addEnergyCorrFunc=False, 
		addEnergyCorrFuncSubjets=False,
		# set this to false to disable creation of jettoolbox.root
		# then you need to associate the jetTask to a Path or EndPath manually in your config
		associateTask=True,
		# 0 = no printouts, 1 = warnings only, 2 = warnings & info, 3 = warnings, info, debug
		verbosity=2,
		):

	runOnData = not runOnMC
	if runOnData:
		GetJetMCFlavour = False
		GetSubjetMCFlavour = False
	
	###############################################################################
	#######  Verifying some inputs and defining variables
	###############################################################################
	if verbosity>=1: print('|---- jetToolbox: Initializing collection... (with postfix '+postFix+')')
	if newPFCollection and verbosity>=2: print('|---- jetToolBox: Using '+ nameNewPFCollection +' as PFCandidates collection')
	supportedJetAlgos = { 'ak': 'AntiKt', 'ca' : 'CambridgeAachen', 'kt' : 'Kt' }
	recommendedJetAlgos = [ 'ak4', 'ak8', 'ca4', 'ca8', 'ca10', 'ca15' ]
	payloadList = [ 'None',
			'AK1PFchs', 'AK2PFchs', 'AK3PFchs', 'AK4PFchs', 'AK5PFchs', 'AK6PFchs', 'AK7PFchs', 'AK8PFchs', 'AK9PFchs', 'AK10PFchs',
			'AK1PFPuppi', 'AK2PFPuppi', 'AK3PFPuppi', 'AK4PFPuppi', 'AK5PFPuppi', 'AK6PFPuppi', 'AK7PFPuppi', 'AK8PFPuppi', 'AK9PFPuppi', 'AK10PFPuppi',  
			'AK1PFSK', 'AK2PFSK', 'AK3PFSK', 'AK4PFSK', 'AK5PFSK', 'AK6PFSK', 'AK7PFSK', 'AK8PFSK', 'AK9PFSK', 'AK10PFSK',  
			'AK1PF', 'AK2PF', 'AK3PF', 'AK4PF', 'AK5PF', 'AK6PF', 'AK7PF', 'AK8PF', 'AK9PF', 'AK10PF' ]
	JECLevels = [ 'L1Offset', 'L1FastJet', 'L1JPTOffset', 'L2Relative', 'L3Absolute', 'L5Falvour', 'L7Parton' ]
	if runOnData:
		JECLevels += ['L2L3Residual']
	jetAlgo = ''
	algorithm = ''
	size = ''
	for TYPE, tmpAlgo in supportedJetAlgos.iteritems(): 
		if TYPE in jetType.lower():
			jetAlgo = TYPE
			algorithm = tmpAlgo
			size = jetType.replace( TYPE, '' )

	jetSize = 0.
	if int(size) in range(0, 20): jetSize = int(size)/10.
	else: raise ValueError('|---- jetToolBox: jetSize has not a valid value. Insert a number between 1 and 20 after algorithm, like: AK8')
	### Trick for uppercase/lowercase algo name
	jetALGO = jetAlgo.upper()+size
	jetalgo = jetAlgo.lower()+size
	if jetalgo not in recommendedJetAlgos and verbosity>=1: print('|---- jetToolBox: CMS recommends the following jet algorithms: '+' '.join(recommendedJetAlgos)+'. You are using '+jetalgo+' .')


	#################################################################################
	####### Toolbox start 
	#################################################################################

	elemToKeep = []
	jetSeq = cms.Sequence()
	genParticlesLabel = ''
	pvLabel = ''
	tvLabel = ''
	toolsUsed = []
	mod = OrderedDict()

	### List of Jet Corrections
	if not set(JETCorrLevels).issubset(set(JECLevels)): 
		if ( 'CHS' in PUMethod ) or  ( 'Plain' in PUMethod ): JETCorrLevels = ['L1FastJet','L2Relative', 'L3Absolute']
		else: JETCorrLevels = [ 'L2Relative', 'L3Absolute']
		if runOnData: JETCorrLevels.append('L2L3Residual')
	if not set(subJETCorrLevels).issubset(set(JECLevels)): 
		if ( 'CHS' in PUMethod ) or  ( 'Plain' in PUMethod ): subJETCorrLevels = ['L1FastJet','L2Relative', 'L3Absolute']
		else: subJETCorrLevels = [ 'L2Relative', 'L3Absolute']
		if runOnData: subJETCorrLevels.append('L2L3Residual')


	## b-tag discriminators
	defaultBTagDiscriminators = [
			'pfTrackCountingHighEffBJetTags',
			'pfTrackCountingHighPurBJetTags',
			'pfJetProbabilityBJetTags',
			'pfJetBProbabilityBJetTags',
			'pfSimpleSecondaryVertexHighEffBJetTags',
			'pfSimpleSecondaryVertexHighPurBJetTags',
			'pfCombinedSecondaryVertexV2BJetTags',
			'pfCombinedInclusiveSecondaryVertexV2BJetTags',
			'pfCombinedMVAV2BJetTags'
	]
	if bTagDiscriminators is '': bTagDiscriminators = defaultBTagDiscriminators
	if subjetBTagDiscriminators is '': subjetBTagDiscriminators = defaultBTagDiscriminators

	if updateCollection and 'Puppi' in updateCollection: PUMethod='Puppi'
	mod["PATJetsLabel"] = jetALGO+'PF'+PUMethod
	mod["PATJetsLabelPost"] = mod["PATJetsLabel"]+postFix
	# some substructure quantities don't include the 'PF' in the name
	mod["SubstructureLabel"] = jetALGO+PUMethod+postFix
	if not updateCollection: 

		mod["GenJetsNoNu"] = jetalgo+'GenJetsNoNu'
		#### For MiniAOD
		if miniAOD:

			if verbosity>=2: print('|---- jetToolBox: JETTOOLBOX RUNNING ON MiniAOD FOR '+jetALGO+' JETS USING '+PUMethod)

			genParticlesLabel = 'prunedGenParticles'
			pvLabel = 'offlineSlimmedPrimaryVertices'
			svLabel = 'slimmedSecondaryVertices'
			tvLabel = 'unpackedTracksAndVertices'
			muLabel = 'slimmedMuons'
			elLabel = 'slimmedElectrons'
			pfCand = nameNewPFCollection if newPFCollection else 'packedPFCandidates'

			if runOnMC:
				## Filter out neutrinos from packed GenParticles
				mod["GenParticlesNoNu"] = 'packedGenParticlesForJetsNoNu'
				_addProcessAndTask(proc, mod["GenParticlesNoNu"],
						cms.EDFilter("CandPtrSelector", 
							src = cms.InputTag("packedGenParticles"), 
							cut = cms.string("abs(pdgId) != 12 && abs(pdgId) != 14 && abs(pdgId) != 16")
							))
				jetSeq += getattr(proc, mod["GenParticlesNoNu"])

				_addProcessAndTask(proc, mod["GenJetsNoNu"],
						ak4GenJets.clone( src = mod["GenParticlesNoNu"],
							rParam = jetSize, 
							jetAlgorithm = algorithm ) ) 
				jetSeq += getattr(proc, mod["GenJetsNoNu"])

			#for Inclusive Vertex Finder
			proc.load('PhysicsTools.PatAlgos.slimming.unpackedTracksAndVertices_cfi')

		#### For AOD
		else:
			if verbosity>=2: print('|---- jetToolBox: JETTOOLBOX RUNNING ON AOD FOR '+jetALGO+' JETS USING '+PUMethod)

			genParticlesLabel = 'genParticles'
			pvLabel = 'offlinePrimaryVertices'
			tvLabel = 'generalTracks'
			muLabel = 'muons'
			elLabel = 'gedGsfElectrons'
			pfCand =  nameNewPFCollection if newPFCollection else 'particleFlow'
			svLabel = 'inclusiveCandidateSecondaryVertices'

			if runOnMC:
				proc.load('RecoJets.Configuration.GenJetParticles_cff')
				_addProcessAndTask(proc, mod["GenJetsNoNu"], ak4GenJets.clone(src='genParticlesForJetsNoNu', rParam=jetSize, jetAlgorithm=algorithm))
				jetSeq += getattr(proc, mod["GenJetsNoNu"])
			

		####  Creating PATjets
		tmpPfCandName = pfCand.lower()
		mod["PFJets"] = ""
		if 'Puppi' in PUMethod:
			if ('puppi' in tmpPfCandName): 
				srcForPFJets = pfCand
				if verbosity>=1: print('|---- jetToolBox: Not running puppi algorithm because keyword puppi was specified in nameNewPFCollection, but applying puppi corrections.')
			else: 
				proc.load('CommonTools.PileupAlgos.Puppi_cff')
				puppi.candName = cms.InputTag( pfCand ) 
				if miniAOD:
				  puppi.vertexName = cms.InputTag('offlineSlimmedPrimaryVertices')
				  puppi.clonePackedCands = cms.bool(True)
				  puppi.useExistingWeights = cms.bool(True)
				_addProcessAndTask(proc, 'puppi', getattr(proc, 'puppi'))
				jetSeq += getattr(proc, 'puppi' )
				srcForPFJets = 'puppi'

			from RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJetsPuppi
			mod["PFJets"] = jetalgo+'PFJetsPuppi'+postFix
			_addProcessAndTask(proc, mod["PFJets"],
					ak4PFJetsPuppi.clone( src = cms.InputTag( srcForPFJets ),
						doAreaFastjet = True, 
						rParam = jetSize, 
						jetAlgorithm = algorithm ) )  
			jetSeq += getattr(proc, mod["PFJets"])

			if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PFPuppi'
			if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PFPuppi'

		elif 'SK' in PUMethod:

			if ('sk' in tmpPfCandName): 
				srcForPFJets = pfCand
				if verbosity>=1: print('|---- jetToolBox: Not running softkiller algorithm because keyword SK was specified in nameNewPFCollection, but applying SK corrections.')
			else:
				proc.load('CommonTools.PileupAlgos.softKiller_cfi')
				getattr( proc, 'softKiller' ).PFCandidates = cms.InputTag( pfCand )
				_addProcessAndTask(proc, 'softKiller', getattr(proc, 'softKiller'))
				jetSeq += getattr(proc, 'softKiller' )
				srcForPFJets = 'softKiller'

			from RecoJets.JetProducers.ak4PFJetsSK_cfi import ak4PFJetsSK
			mod["PFJets"] = jetalgo+'PFJetsSK'+postFix
			_addProcessAndTask(proc, mod["PFJets"],
					ak4PFJetsSK.clone(  src = cms.InputTag( srcForPFJets ),
						rParam = jetSize, 
						jetAlgorithm = algorithm ) ) 
			jetSeq += getattr(proc, mod["PFJets"])

			if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PFSK'
			if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PFSK'
		
		elif 'CS' in PUMethod: 

			from RecoJets.JetProducers.ak4PFJetsCHSCS_cfi import ak4PFJetsCHSCS
			mod["PFJets"] = jetalgo+'PFJetsCS'+postFix
			_addProcessAndTask(proc, mod["PFJets"],
					ak4PFJetsCHSCS.clone( doAreaFastjet = True, 
						src = cms.InputTag( pfCand ), #srcForPFJets ),
						csRParam = cms.double(jetSize),
						jetAlgorithm = algorithm ) ) 
			if miniAOD: getattr( proc, mod["PFJets"]).src = pfCand
			jetSeq += getattr(proc, mod["PFJets"])

			if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PFCS'
			if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PFCS'

		elif 'CHS' in PUMethod: 
			
			if miniAOD:
				if ('chs' in tmpPfCandName): 
					srcForPFJets = pfCand
					if verbosity>=1: print('|---- jetToolBox: Not running CHS algorithm because keyword CHS was specified in nameNewPFCollection, but applying CHS corrections.')
				else: 
					_addProcessAndTask(proc, 'chs', cms.EDFilter('CandPtrSelector', src=cms.InputTag(pfCand), cut=cms.string('fromPV')))
					jetSeq += getattr(proc, 'chs')
					srcForPFJets = 'chs'
			else:
				if ( pfCand == 'particleFlow' ):
					from RecoParticleFlow.PFProducer.particleFlowTmpPtrs_cfi import particleFlowTmpPtrs
					_addProcessAndTask(proc, 'newParticleFlowTmpPtrs', particleFlowTmpPtrs.clone(src=pfCand))
					jetSeq += getattr(proc, 'newParticleFlowTmpPtrs')
					from CommonTools.ParticleFlow.pfNoPileUpJME_cff import pfPileUpJME, pfNoPileUpJME
					proc.load('CommonTools.ParticleFlow.goodOfflinePrimaryVertices_cfi')
					_addProcessAndTask(proc, 'newPfPileUpJME', pfPileUpJME.clone(PFCandidates='newParticleFlowTmpPtrs'))
					jetSeq += getattr(proc, 'newPfPileUpJME')
					_addProcessAndTask(proc, 'newPfNoPileUpJME', pfNoPileUpJME.clone(topCollection='newPfPileUpJME', bottomCollection='newParticleFlowTmpPtrs'))
					jetSeq += getattr(proc, 'newPfNoPileUpJME')
					srcForPFJets = 'newPfNoPileUpJME'
				else: 
					proc.load('CommonTools.ParticleFlow.pfNoPileUpJME_cff')
					srcForPFJets = 'pfNoPileUpJME'
				
			mod["PFJets"] = jetalgo+'PFJetsCHS'+postFix
			_addProcessAndTask(proc, mod["PFJets"],
					ak4PFJetsCHS.clone( src = cms.InputTag( srcForPFJets ), 
						doAreaFastjet = True, 
						rParam = jetSize, 
						jetAlgorithm = algorithm ) ) 
			jetSeq += getattr(proc, mod["PFJets"])

			if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PFchs'
			if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PFchs'

		else: 
			PUMethod = ''
			mod["PFJets"] = jetalgo+'PFJets'+postFix
			_addProcessAndTask(proc, mod["PFJets"],
					ak4PFJets.clone( 
						doAreaFastjet = True, 
						rParam = jetSize, 
						jetAlgorithm = algorithm ) ) 
			if miniAOD: getattr( proc, mod["PFJets"]).src = pfCand
			jetSeq += getattr(proc, mod["PFJets"])
			if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PF'
			if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PF'


		if 'None' in JETCorrPayload: JEC = None
		else: JEC = ( JETCorrPayload.replace('CS','chs').replace('SK','chs') , JETCorrLevels, 'None' )   ### temporary
		#else: JEC = ( JETCorrPayload., JETCorrLevels, 'None' ) 
		if verbosity>=2: print('|---- jetToolBox: Applying these corrections: '+str(JEC))

		if addPrunedSubjets or addSoftDropSubjets or addCMSTopTagger:
			if 'None' in subJETCorrPayload: subJEC = None
			else: subJEC = ( subJETCorrPayload.replace('CS','chs').replace('SK','chs') , subJETCorrLevels, 'None' )   ### temporary


		mod["PFJetsConstituents"] = mod["PFJets"]+'Constituents'
		mod["PFJetsConstituentsColon"] = mod["PFJets"]+'Constituents:constituents'
		mod["PFJetsConstituentsColonOrUpdate"] = mod["PFJetsConstituentsColon"] if not updateCollection else updateCollection
		if (PUMethod in [ 'CHS', 'CS', 'Puppi' ]) and miniAOD: _addProcessAndTask(proc, mod["PFJetsConstituents"], cms.EDProducer("MiniAODJetConstituentSelector", src=cms.InputTag(mod["PFJets"]), cut=cms.string(Cut)))
		else: _addProcessAndTask(proc, mod["PFJetsConstituents"], cms.EDProducer("PFJetConstituentSelector", src=cms.InputTag(mod["PFJets"]), cut=cms.string(Cut)))
		jetSeq += getattr(proc, mod["PFJetsConstituents"])

		addJetCollection(
				proc,
				labelName = mod["PATJetsLabel"],
				jetSource = cms.InputTag(mod["PFJets"]),
				postfix = postFix, 
				algo = jetalgo,
				rParam = jetSize,
				jetCorrections = JEC if JEC is not None else None, 
				pfCandidates = cms.InputTag( pfCand ),  
				svSource = cms.InputTag( svLabel ),  
				genJetCollection = cms.InputTag(mod["GenJetsNoNu"]),
				pvSource = cms.InputTag( pvLabel ), 
				muSource = cms.InputTag( muLabel ),
				elSource = cms.InputTag( elLabel ),
				btagDiscriminators = bTagDiscriminators,
				btagInfos = bTagInfos,
				getJetMCFlavour = GetJetMCFlavour,
				genParticles = cms.InputTag(genParticlesLabel),
				outputModules = ['outputFile']
				)
		patJets = 'patJets'
		patSubJets = ''
		selPatJets = 'selectedPatJets'
		mod["PATJets"] = patJets+mod["PATJetsLabelPost"]
		mod["selPATJets"] = selPatJets+mod["PATJetsLabelPost"]
		getattr(proc, mod["PATJets"]).addTagInfos = cms.bool(True)

		if 'CS' in PUMethod: getattr( proc, mod["PATJets"] ).getJetMCFlavour = False  # CS jets cannot be re-clustered from their constituents
	else:
		if verbosity>=2: print('|---- jetToolBox: JETTOOLBOX IS UPDATING '+updateCollection+' collection')
		genParticlesLabel = 'prunedGenParticles'
		pvLabel = 'offlineSlimmedPrimaryVertices'
		svLabel = 'slimmedSecondaryVertices'
		tvLabel = 'unpackedTracksAndVertices'
		muLabel = 'slimmedMuons'
		elLabel = 'slimmedElectrons'

		if not JETCorrPayload: 
			raise ValueError('|---- jetToolBox: updateCollection option requires to add JETCorrPayload.')

		JEC = ( JETCorrPayload, JETCorrLevels, 'None' )   ### temporary
		if verbosity>=2: print('|---- jetToolBox: Applying these corrections: '+str(JEC))
		updateJetCollection(
				proc,
				postfix = postFix,
				jetSource = cms.InputTag( updateCollection ),
				labelName = mod["PATJetsLabel"],
				jetCorrections = JEC, 
				btagDiscriminators = bTagDiscriminators,
				)
		mod["PATJetsCorrFactors"] = 'patJetCorrFactors'+mod["PATJetsLabelPost"]
		getattr( proc, mod["PATJetsCorrFactors"] ).payload = JETCorrPayload
		getattr( proc, mod["PATJetsCorrFactors"] ).levels = JETCorrLevels
		patJets = 'updatedPatJets'
		patSubJets = ''
		selPatJets = 'selectedPatJets'
		mod["PATJets"] = patJets+mod["PATJetsLabelPost"]
		mod["selPATJets"] = selPatJets+mod["PATJetsLabelPost"]

		if updateCollectionSubjets:
			if verbosity>=2: print('|---- jetToolBox: JETTOOLBOX IS UPDATING '+updateCollectionSubjets+' collection for subjets/groomers.')
			if 'SoftDrop' in updateCollectionSubjets: updateSubjetLabel = 'SoftDrop'
			else: updateSubjetLabel = 'Pruned'
			mod["PATSubjetsLabel"] = jetALGO+'PF'+PUMethod+postFix+updateSubjetLabel+'Packed'
			updateJetCollection(
					proc,
					jetSource = cms.InputTag( updateCollectionSubjets ),
					labelName = mod["PATSubjetsLabel"],
					jetCorrections = JEC, 
					explicitJTA = True,
					fatJets = cms.InputTag( updateCollection ),
					rParam = jetSize, 
					algo = jetALGO,
					btagDiscriminators = subjetBTagDiscriminators,
					)
			mod["PATSubjetsCorrFactors"] = 'patJetCorrFactors'+mod["PATSubjetsLabel"]
			getattr( proc, mod["PATSubjetsCorrFactors"] ).payload = subJETCorrPayload
			getattr( proc, mod["PATSubjetsCorrFactors"] ).levels = subJETCorrLevels
			patSubJets = 'updatedPatJets'+mod["PATSubjetsLabel"]

		if addPrunedSubjets or addSoftDropSubjets or addCMSTopTagger or addMassDrop or addHEPTopTagger or addPruning or addSoftDrop: 
			if verbosity>=1: print('|---- jetToolBox: You are trying to add a groomer variable into a clustered jet collection. THIS IS NOT RECOMMENDED, it is recommended to recluster jets instead using a plain jetToolbox configuration. Please use this feature at your own risk.')

	mod["PFJetsOrUpdate"] = mod["PFJets"] if not updateCollection else updateCollection

	if bTagDiscriminators and verbosity>=2: print('|---- jetToolBox: Adding these btag discriminators: '+str(bTagDiscriminators)+' in the jet collection.')
	if ( (addPrunedSubjets or addSoftDropSubjets) or (updateCollection and updateCollectionSubjets) ) and subjetBTagDiscriminators and verbosity>=2:
		print('|---- jetToolBox: Adding these btag discriminators: '+str(subjetBTagDiscriminators)+' in the subjet collection.')

	#### Groomers
	if addSoftDrop or addSoftDropSubjets: 

		mod["PFJetsSoftDrop"] = mod["PFJets"]+'SoftDrop'
		mod["SoftDropMass"] = mod["PFJets"]+'SoftDropMass'
		_addProcessAndTask(proc, mod["PFJetsSoftDrop"],
			ak8PFJetsCHSSoftDrop.clone( 
				src = cms.InputTag( mod["PFJetsConstituentsColonOrUpdate"] ),
				rParam = jetSize, 
				jetAlgorithm = algorithm, 
				useExplicitGhosts=True,
				R0= cms.double(jetSize),
				zcut=zCutSD, 
				beta=betaCut,
				doAreaFastjet = cms.bool(True),
				writeCompound = cms.bool(True),
				jetCollInstanceName=cms.string('SubJets') ) )
		_addProcessAndTask(proc, mod["SoftDropMass"],
			ak8PFJetsCHSSoftDropMass.clone( src = cms.InputTag( mod["PFJetsOrUpdate"] ), 
				matched = cms.InputTag( mod["PFJetsSoftDrop"] ),
				distMax = cms.double( jetSize ) ) )

		elemToKeep += [ 'keep *_'+mod["SoftDropMass"]+'_*_*'] 
		jetSeq += getattr(proc, mod["PFJetsSoftDrop"] )
		jetSeq += getattr(proc, mod["SoftDropMass"] )
		getattr( proc, mod["PATJets"]).userData.userFloats.src += [ mod["SoftDropMass"] ]
		toolsUsed.append( mod["SoftDropMass"] )

		if addSoftDropSubjets:

			mod["GenJetsNoNuSoftDrop"] = mod["GenJetsNoNu"]+'SoftDrop'
			if runOnMC:
				_addProcessAndTask(proc, mod["GenJetsNoNuSoftDrop"],
						ak4GenJets.clone(
							SubJetParameters,
							useSoftDrop = cms.bool(True),
							rParam = jetSize, 
							jetAlgorithm = algorithm, 
							useExplicitGhosts=cms.bool(True),
							#zcut=cms.double(zCutSD), 
							R0= cms.double(jetSize),
							beta=cms.double(betaCut),
							writeCompound = cms.bool(True),
							jetCollInstanceName=cms.string('SubJets')
							))
				if miniAOD: getattr( proc, mod["GenJetsNoNuSoftDrop"] ).src = mod["GenParticlesNoNu"]
				jetSeq += getattr(proc, mod["GenJetsNoNuSoftDrop"] )

			mod["PATJetsSoftDropLabel"] = mod["PATJetsLabelPost"]+'SoftDrop'
			addJetCollection(
					proc,
					labelName = mod["PATJetsSoftDropLabel"],
					jetSource = cms.InputTag( mod["PFJetsSoftDrop"]),
					algo = jetalgo,
					rParam = jetSize,
					jetCorrections = JEC if JEC is not None else None, 
					pvSource = cms.InputTag( pvLabel ),
					btagDiscriminators = ['None'],
					genJetCollection = cms.InputTag( mod["GenJetsNoNu"]),
					getJetMCFlavour = False, # jet flavor should always be disabled for groomed jets
					genParticles = cms.InputTag(genParticlesLabel),
					outputModules = ['outputFile']
					)
			mod["PATJetsSoftDrop"] = patJets+mod["PATJetsSoftDropLabel"]
			mod["selPATJetsSoftDrop"] = selPatJets+mod["PATJetsSoftDropLabel"]

			_addProcessAndTask(proc, mod["selPATJetsSoftDrop"], selectedPatJets.clone(src=mod["PATJetsSoftDrop"], cut=Cut))

			mod["PATSubjetsSoftDropLabel"] = mod["PATJetsSoftDropLabel"]+'Subjets'
			addJetCollection(
					proc,
					labelName = mod["PATSubjetsSoftDropLabel"],
					jetSource = cms.InputTag( mod["PFJetsSoftDrop"], 'SubJets'),
					algo = jetalgo,  # needed for subjet b tagging
					rParam = jetSize,  # needed for subjet b tagging
					jetCorrections = subJEC if subJEC is not None else None, 
					pfCandidates = cms.InputTag( pfCand ), 
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ),  
					muSource = cms.InputTag( muLabel ),
					elSource = cms.InputTag( elLabel ),
					btagDiscriminators = subjetBTagDiscriminators,
					btagInfos = bTagInfos,
					genJetCollection = cms.InputTag( mod["GenJetsNoNuSoftDrop"],'SubJets'),
					getJetMCFlavour = GetSubjetMCFlavour,
					genParticles = cms.InputTag(genParticlesLabel),
					explicitJTA = True,  # needed for subjet b tagging
					svClustering = True, # needed for subjet b tagging
					fatJets=cms.InputTag(mod["PFJets"]),             # needed for subjet flavor clustering
					groomedFatJets=cms.InputTag(mod["PFJetsSoftDrop"]), # needed for subjet flavor clustering
					outputModules = ['outputFile']
					) 
			mod["PATSubjetsSoftDrop"] = patJets+mod["PATSubjetsSoftDropLabel"]
			mod["selPATSubjetsSoftDrop"] = selPatJets+mod["PATSubjetsSoftDropLabel"]

			_addProcessAndTask(proc, mod["selPATSubjetsSoftDrop"], selectedPatJets.clone(src=mod["PATSubjetsSoftDrop"], cut=CutSubjet))

			# Establish references between PATified fat jets and subjets using the BoostedJetMerger
			mod["selPATJetsSoftDropPacked"] = mod["selPATJetsSoftDrop"]+'Packed'
			_addProcessAndTask(proc, mod["selPATJetsSoftDropPacked"],
					cms.EDProducer("BoostedJetMerger",
						jetSrc=cms.InputTag(mod["selPATJetsSoftDrop"]),
						subjetSrc=cms.InputTag(mod["selPATSubjetsSoftDrop"])
						))
			jetSeq += getattr(proc, mod["selPATJetsSoftDropPacked"] )
			elemToKeep += [ 'keep *_'+mod["selPATJetsSoftDropPacked"]+'_SubJets_*' ]
			toolsUsed.append( mod["selPATJetsSoftDropPacked"]+':SubJets' )

			## Pack fat jets with subjets
			mod["packedPATJetsSoftDrop"] = 'packedPatJets'+mod["PATJetsSoftDropLabel"]
			_addProcessAndTask(proc, mod["packedPATJetsSoftDrop"],
				 cms.EDProducer("JetSubstructurePacker",
						jetSrc=cms.InputTag(mod["selPATJets"]),
						distMax = cms.double( jetSize ),
						fixDaughters = cms.bool(False),
						algoTags = cms.VInputTag(
						cms.InputTag(mod["selPATJetsSoftDropPacked"])
						), 
						algoLabels =cms.vstring('SoftDrop')
						)
				 )
			jetSeq += getattr(proc, mod["packedPATJetsSoftDrop"])
			elemToKeep += [ 'keep *_'+mod["packedPATJetsSoftDrop"]+'_*_*' ]
			if verbosity>=2: print('|---- jetToolBox: Creating '+mod["packedPATJetsSoftDrop"]+' collection with SoftDrop subjets.')



	if addPruning or addPrunedSubjets: 

		mod["PFJetsPruned"] = mod["PFJets"]+'Pruned'
		mod["PrunedMass"] =  mod["PFJets"]+'PrunedMass'
		_addProcessAndTask(proc, mod["PFJetsPruned"],
			ak8PFJetsCHSPruned.clone( 
				src = cms.InputTag( mod["PFJetsConstituentsColonOrUpdate"] ),
				rParam = jetSize, 
				jetAlgorithm = algorithm, 
				zcut=zCut, 
				rcut_factor=rCut,
				writeCompound = cms.bool(True),
				doAreaFastjet = cms.bool(True),
				jetCollInstanceName=cms.string('SubJets') ) )
		_addProcessAndTask(proc, mod["PrunedMass"],
			ak8PFJetsCHSPrunedMass.clone( 
				src = cms.InputTag( mod["PFJetsOrUpdate"] ), 
				matched = cms.InputTag( mod["PFJetsPruned"]), 
				distMax = cms.double( jetSize ) ) )

		jetSeq += getattr(proc, mod["PFJetsPruned"])
		jetSeq += getattr(proc, mod["PrunedMass"])
		getattr( proc, mod["PATJets"]).userData.userFloats.src += [ mod["PrunedMass"] ]
		elemToKeep += [ 'keep *_'+mod["PrunedMass"]+'_*_*'] 
		toolsUsed.append( mod["PrunedMass"] )

		if addPrunedSubjets:
			if runOnMC:
				mod["GenJetsNoNuPruned"] = mod["GenJetsNoNu"]+'Pruned'
				_addProcessAndTask(proc, mod["GenJetsNoNuPruned"],
						ak4GenJets.clone(
							SubJetParameters,
							rParam = jetSize,
							usePruning = cms.bool(True),
							writeCompound = cms.bool(True),
							jetCollInstanceName=cms.string('SubJets')
							))
				if miniAOD: getattr( proc, mod["GenJetsNoNuPruned"] ).src = mod["GenParticlesNoNu"]
				jetSeq += getattr(proc, mod["GenJetsNoNuPruned"])

			mod["PATJetsPrunedLabel"] = mod["PATJetsLabelPost"]+'Pruned'
			addJetCollection(
					proc,
					labelName = mod["PATJetsPrunedLabel"],
					jetSource = cms.InputTag( mod["PFJetsPruned"]),
					algo = jetalgo,
					rParam = jetSize,
					jetCorrections = JEC if JEC is not None else None, 
					pvSource = cms.InputTag( pvLabel ),
					btagDiscriminators = ['None'],
					genJetCollection = cms.InputTag( mod["GenJetsNoNu"]),
					getJetMCFlavour = False, # jet flavor should always be disabled for groomed jets
					genParticles = cms.InputTag(genParticlesLabel),
					outputModules = ['outputFile']
					)
			mod["PATJetsPruned"] = patJets+mod["PATJetsPrunedLabel"]
			mod["selPATJetsPruned"] = selPatJets+mod["PATJetsPrunedLabel"]

			_addProcessAndTask(proc, mod["selPATJetsPruned"], selectedPatJets.clone(src=mod["PATJetsPruned"], cut=Cut))

			mod["PATSubjetsPrunedLabel"] = mod["PATJetsPrunedLabel"]+'Subjets'
			addJetCollection(
					proc,
					labelName = mod["PATSubjetsPrunedLabel"],
					jetSource = cms.InputTag( mod["PFJetsPruned"], 'SubJets'),
					algo = jetalgo,  # needed for subjet b tagging
					rParam = jetSize,  # needed for subjet b tagging
					jetCorrections = subJEC if subJEC is not None else None, 
					pfCandidates = cms.InputTag( pfCand ),  
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ), 
					muSource = cms.InputTag( muLabel ),
					elSource = cms.InputTag( elLabel ),
					getJetMCFlavour = GetSubjetMCFlavour,
					genParticles = cms.InputTag(genParticlesLabel),
					btagDiscriminators = subjetBTagDiscriminators,
					btagInfos = bTagInfos,
					genJetCollection = cms.InputTag( mod["GenJetsNoNuPruned"],'SubJets'),
					explicitJTA = True,  # needed for subjet b tagging
					svClustering = True, # needed for subjet b tagging
					fatJets=cms.InputTag(mod["PFJets"]),             # needed for subjet flavor clustering
					groomedFatJets=cms.InputTag(mod["PFJetsPruned"]), # needed for subjet flavor clustering
					outputModules = ['outputFile']
					) 
			mod["PATSubjetsPruned"] = patJets+mod["PATSubjetsPrunedLabel"]
			mod["selPATSubjetsPruned"] = selPatJets+mod["PATSubjetsPrunedLabel"]

			_addProcessAndTask(proc, mod["selPATSubjetsPruned"], selectedPatJets.clone(src=mod["PATSubjetsPruned"], cut=CutSubjet))

			## Establish references between PATified fat jets and subjets using the BoostedJetMerger
			mod["selPATJetsPrunedPacked"] = mod["selPATJetsPruned"]+'Packed'
			_addProcessAndTask(proc, mod["selPATJetsPrunedPacked"],
					cms.EDProducer("BoostedJetMerger",
						jetSrc=cms.InputTag(mod["selPATJetsPruned"]),
						subjetSrc=cms.InputTag(mod["selPATSubjetsPruned"]),
						))
			jetSeq += getattr(proc, mod["selPATJetsPrunedPacked"])
			elemToKeep += [ 'keep *_'+mod["selPATJetsPrunedPacked"]+'_SubJets_*' ]
			toolsUsed.append( mod["selPATJetsPrunedPacked"]+':SubJets' )

			## Pack fat jets with subjets
			mod["packedPATJetsPruned"] = 'packedPatJets'+mod["PATSubjetsPrunedLabel"]
			_addProcessAndTask(proc, mod["packedPATJetsPruned"],
				 cms.EDProducer("JetSubstructurePacker",
						jetSrc=cms.InputTag(mod["selPATJets"]),
						distMax = cms.double( jetSize ),
						fixDaughters = cms.bool(False),
						algoTags = cms.VInputTag(
						cms.InputTag(mod["selPATJetsPrunedPacked"])
						), 
						algoLabels =cms.vstring('Pruned')
						)
				 )
			jetSeq += getattr(proc, mod["packedPATJetsPruned"])
			elemToKeep += [ 'keep *_'+mod["packedPATJetsPruned"]+'_*_*' ]
			if verbosity>=2: print('|---- jetToolBox: Creating '+mod["packedPATJetsPruned"]+' collection with Pruned subjets.')


	if addTrimming:

		mod["PFJetsTrimmed"] = mod["PFJets"]+'Trimmed'
		mod["TrimmedMass"] = mod["PFJets"]+'TrimmedMass'
		_addProcessAndTask(proc, mod["PFJetsTrimmed"],
				ak8PFJetsCHSTrimmed.clone( 
					rParam = jetSize, 
					src = cms.InputTag( mod["PFJetsConstituentsColonOrUpdate"] ),
					jetAlgorithm = algorithm,
					rFilt= rFiltTrim,
					trimPtFracMin= ptFrac) ) 
		_addProcessAndTask(proc, mod["TrimmedMass"],
				ak8PFJetsCHSTrimmedMass.clone( 
					src = cms.InputTag( mod["PFJetsOrUpdate"] ), 
					matched = cms.InputTag( mod["PFJetsTrimmed"]), 
					distMax = cms.double( jetSize ) ) )

		elemToKeep += [ 'keep *_'+mod["TrimmedMass"]+'_*_*'] 
		jetSeq += getattr(proc, mod["PFJetsTrimmed"])
		jetSeq += getattr(proc, mod["TrimmedMass"])
		getattr( proc, mod["PATJets"]).userData.userFloats.src += [mod["TrimmedMass"]]
		toolsUsed.append( mod["TrimmedMass"] )

	if addFiltering:

		mod["PFJetsFiltered"] = mod["PFJets"]+'Filtered'
		mod["FilteredMass"] = mod["PFJets"]+'FilteredMass'
		_addProcessAndTask(proc, mod["PFJetsFiltered"],
				ak8PFJetsCHSFiltered.clone( 
					src = cms.InputTag( mod["PFJetsConstituentsColonOrUpdate"] ),
					rParam = jetSize, 
					jetAlgorithm = algorithm,
					rFilt= rfilt,
					nFilt= nfilt ) ) 
		_addProcessAndTask(proc, mod["FilteredMass"],
				ak8PFJetsCHSFilteredMass.clone( 
					src = cms.InputTag( mod["PFJetsOrUpdate"] ), 
					matched = cms.InputTag( mod["PFJetsFiltered"]), 
					distMax = cms.double( jetSize ) ) )
		elemToKeep += [ 'keep *_'+mod["FilteredMass"]+'_*_*'] 
		jetSeq += getattr(proc, mod["PFJetsFiltered"])
		jetSeq += getattr(proc, mod["FilteredMass"])
		getattr( proc, patJets+jetALGO+'PF'+PUMethod+postFix).userData.userFloats.src += [mod["FilteredMass"]]
		toolsUsed.append( mod["FilteredMass"] )

	if addCMSTopTagger :

		if 'CA' in jetALGO : 

			mod["PFJetsCMSTopTag"] = mod["PFJets"].replace(jetalgo,"cmsTopTag")
			_addProcessAndTask(proc, mod["PFJetsCMSTopTag"],
					cms.EDProducer("CATopJetProducer",
						PFJetParameters.clone( 
							src = cms.InputTag( mod["PFJetsConstituentsColonOrUpdate"] ),
							doAreaFastjet = cms.bool(True),
							doRhoFastjet = cms.bool(False),
							jetPtMin = cms.double(100.0)
							),
						AnomalousCellParameters,
						CATopJetParameters.clone( jetCollInstanceName = cms.string("SubJets"),
							verbose = cms.bool(False),
							algorithm = cms.int32(1), # 0 = KT, 1 = CA, 2 = anti-KT
							tagAlgo = cms.int32(0), #0=legacy top
							useAdjacency = cms.int32(2), # modified adjacency
							centralEtaCut = cms.double(2.5), # eta for defining "central" jets
							sumEtBins = cms.vdouble(0,1600,2600), # sumEt bins over which cuts vary. vector={bin 0 lower bound, bin 1 lower bound, ...}
							rBins = cms.vdouble(0.8,0.8,0.8), # Jet distance paramter R. R values depend on sumEt bins.
							ptFracBins = cms.vdouble(0.05,0.05,0.05), # minimum fraction of central jet pt for subjets (deltap)
							deltarBins = cms.vdouble(0.19,0.19,0.19), # Applicable only if useAdjacency=1. deltar adjacency values for each sumEtBin
							nCellBins = cms.vdouble(1.9,1.9,1.9),
							),
						jetAlgorithm = cms.string("CambridgeAachen"),
						rParam = cms.double(jetSize),
						writeCompound = cms.bool(True)
						)
					)
			
			mod["CATopTagInfos"] = "CATopTagInfos"+postFix
			_addProcessAndTask(proc, mod["CATopTagInfos"],
					cms.EDProducer("CATopJetTagger",
						src = cms.InputTag(mod["PFJetsCMSTopTag"]),
						TopMass = cms.double(171),
						TopMassMin = cms.double(0.),
						TopMassMax = cms.double(250.),
						WMass = cms.double(80.4),
						WMassMin = cms.double(0.0),
						WMassMax = cms.double(200.0),
						MinMassMin = cms.double(0.0),
						MinMassMax = cms.double(200.0),
						verbose = cms.bool(False)
						)
					)
			mod["PATJetsCMSTopTagLabel"] = 'CMSTopTag'+PUMethod+postFix
			addJetCollection(
					proc,
					labelName = mod["PATJetsCMSTopTagLabel"],
					jetSource = cms.InputTag(mod["PFJetsCMSTopTag"]),
					jetCorrections = JEC if JEC is not None else None, 
					pfCandidates = cms.InputTag( pfCand ),  
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ), 
					muSource = cms.InputTag( muLabel ),
					elSource = cms.InputTag( elLabel ),
					btagDiscriminators = bTagDiscriminators,
					btagInfos = bTagInfos,
					genJetCollection = cms.InputTag(mod["GenJetsNoNu"]),
					getJetMCFlavour = False, # jet flavor should always be disabled for groomed jets
					genParticles = cms.InputTag(genParticlesLabel)
					)
			mod["PATJetsCMSTopTag"] = patJets+mod["PATJetsCMSTopTagLabel"]
			mod["selPATJetsCMSTopTag"] = selPatJets+mod["PATJetsCMSTopTagLabel"]
			getattr(proc,mod["PATJetsCMSTopTag"]).addTagInfos = True
			getattr(proc,mod["PATJetsCMSTopTag"]).tagInfoSources = cms.VInputTag( cms.InputTag(mod["CATopTagInfos"]))
			_addProcessAndTask(proc, mod["selPATJetsCMSTopTag"], selectedPatJets.clone(src=mod["PATJetsCMSTopTag"], cut=Cut))

			mod["PATSubjetsCMSTopTagLabel"] = mod["PATJetsCMSTopTagLabel"]+'Subjets'
			addJetCollection(
					proc,
					labelName = mod["PATSubjetsCMSTopTagLabel"],
					jetSource = cms.InputTag(mod["PFJetsCMSTopTag"], 'SubJets'),
					algo = jetalgo,  # needed for subjet b tagging
					rParam = jetSize,  # needed for subjet b tagging
					jetCorrections = subJEC if subJEC is not None else None, 
					pfCandidates = cms.InputTag( pfCand ),  
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ), 
					muSource = cms.InputTag( muLabel ),
					elSource = cms.InputTag( elLabel ),
					btagDiscriminators = bTagDiscriminators,
					btagInfos = bTagInfos,
					genJetCollection = cms.InputTag( mod["GenJetsNoNu"]),
					getJetMCFlavour = GetSubjetMCFlavour,
					explicitJTA = True,  # needed for subjet b tagging
					svClustering = True, # needed for subjet b tagging
					fatJets=cms.InputTag(mod["PFJets"]),             # needed for subjet flavor clustering
					groomedFatJets=cms.InputTag(mod["PATJetsCMSTopTag"]), # needed for subjet flavor clustering
					genParticles = cms.InputTag(genParticlesLabel)
					)
			mod["PATSubjetsCMSTopTag"] = patJets+mod["PATSubjetsCMSTopTagLabel"]
			mod["selPATSubjetsCMSTopTag"] = selPatJets+mod["PATSubjetsCMSTopTagLabel"]

			_addProcessAndTask(proc, mod["selPATSubjetsCMSTopTag"], selectedPatJets.clone(src=mod["PATSubjetsCMSTopTag"], cut=Cut))

			mod["PATJetsCMSTopTagPacked"] = mod["PATJetsCMSTopTag"]+'Packed'
			_addProcessAndTask(proc, mod["PATJetsCMSTopTagPacked"],
					cms.EDProducer("BoostedJetMerger",
						jetSrc=cms.InputTag(mod["PATJetsCMSTopTag"]),
						subjetSrc=cms.InputTag(mod["PATSubjetsCMSTopTag"])
						))
			jetSeq += getattr(proc, mod["PATJetsCMSTopTagPacked"])
			elemToKeep += [ 'keep *_'+mod["PATJetsCMSTopTagPacked"]+'_*_*' ]
			toolsUsed.append( mod["PATJetsCMSTopTagPacked"] )

		else:
			raise ValueError('|---- jetToolBox: CMS recommends CambridgeAachen for CMS Top Tagger, you are using '+algorithm+'. JetToolbox will not run CMS Top Tagger.')

	if addMassDrop :

		if 'CA' in jetALGO :
			mod["PFJetsMassDrop"] = mod["PFJets"]+'MassDropFiltered'
			mod["MassDropFilteredMass"] = mod["PFJetsMassDrop"]+'Mass'
			_addProcessAndTask(proc, mod["PFJetsMassDrop"],
					ca15PFJetsCHSMassDropFiltered.clone( 
						rParam = jetSize,
						src = cms.InputTag( mod["PFJetsConstituentsColonOrUpdate"] ),
						) )
			_addProcessAndTask(proc, mod["MassDropFilteredMass"], ak8PFJetsCHSPrunedMass.clone(src=cms.InputTag(mod["PFJets"]),
				matched = cms.InputTag(mod["PFJetsMassDrop"]), distMax = cms.double( jetSize ) ) )
			elemToKeep += [ 'keep *_'+mod["MassDropFilteredMass"]+'_*_*' ]
			getattr( proc, mod["PATJets"]).userData.userFloats.src += [ mod["MassDropFilteredMass"] ]
			jetSeq += getattr(proc, mod["PFJetsMassDrop"])
			jetSeq += getattr(proc, mod["MassDropFilteredMass"])
			toolsUsed.append( mod["MassDropFilteredMass"] )
		else:
			raise ValueError('|---- jetToolBox: CMS recommends CambridgeAachen for Mass Drop, you are using '+algorithm+'. JetToolbox will not run Mass Drop.')

	if addHEPTopTagger: 
		if ( jetSize >= 1. ) and ( 'CA' in jetALGO ): 

			mod["PFJetsHEPTopTag"] = mod["PFJets"].replace(jetalgo,"hepTopTag")
			mod["PFJetsHEPTopTagMass"] = mod["PFJetsHEPTopTag"]+'Mass'+jetALGO
			_addProcessAndTask(proc, mod["PFJetsHEPTopTag"], hepTopTagPFJetsCHS.clone(src=cms.InputTag(mod["PFJetsConstituentsColonOrUpdate"])))
			_addProcessAndTask(proc, mod["PFJetsHEPTopTagMass"], ak8PFJetsCHSPrunedMass.clone(src=cms.InputTag(mod["PFJets"]),
				matched = cms.InputTag(mod["PFJetsHEPTopTag"]), distMax = cms.double( jetSize ) ) )
			elemToKeep += [ 'keep *_'+mod["PFJetsHEPTopTagMass"]+'_*_*' ]
			getattr( proc, mod["PATJets"]).userData.userFloats.src += [ mod["PFJetsHEPTopTagMass"] ]
			jetSeq += getattr(proc, mod["PFJetsHEPTopTag"])
			jetSeq += getattr(proc, mod["PFJetsHEPTopTagMass"])
			toolsUsed.append( mod["PFJetsHEPTopTagMass"] )
		else:
			raise ValueError('|---- jetToolBox: CMS recommends CambridgeAachen w/ jet cone size > 1.0 for HEPTopTagger, you are using '+algorithm+'. JetToolbox will not run HEP TopTagger.')

	####### Nsubjettiness
	if addNsub:
		from RecoJets.JetProducers.nJettinessAdder_cfi import Njettiness

		rangeTau = range(1,maxTau+1)
		mod["Njettiness"] = 'Njettiness'+mod["SubstructureLabel"]
		_addProcessAndTask(proc, mod["Njettiness"],
				Njettiness.clone( src = cms.InputTag( mod["PFJetsOrUpdate"] ),
					Njets=cms.vuint32(rangeTau),         # compute 1-, 2-, 3-, 4- subjettiness
					# variables for measure definition : 
					measureDefinition = cms.uint32( 0 ), # CMS default is normalized measure
					beta = cms.double(1.0),              # CMS default is 1
					R0 = cms.double( jetSize ),              # CMS default is jet cone size
					Rcutoff = cms.double( 999.0),       # not used by default
					# variables for axes definition :
					axesDefinition = cms.uint32( 6 ),    # CMS default is 1-pass KT axes
					nPass = cms.int32(999),             # not used by default
					akAxesR0 = cms.double(-999.0) ) )        # not used by default

		elemToKeep += [ 'keep *_'+mod["Njettiness"]+'_*_*' ]
		for tau in rangeTau: getattr( proc, mod["PATJets"]).userData.userFloats.src += [mod["Njettiness"]+':tau'+str(tau) ] 
		jetSeq += getattr(proc, mod["Njettiness"])
		toolsUsed.append( mod["Njettiness"] )

	####### Nsubjettiness
	if addNsubSubjets:

		from RecoJets.JetProducers.nJettinessAdder_cfi import Njettiness

		mod["NsubGroomer"] = ''
		mod["NsubSubjets"] = ''
		mod["NsubPATSubjets"] = ''
		if addSoftDropSubjets or updateCollectionSubjets:
			mod["NsubGroomer"] = mod["PFJetsSoftDrop"]
			mod["NsubSubjets"] = mod["PATSubjetsSoftDropLabel"]
			mod["NsubPATSubjets"] = mod["PATSubjetsSoftDrop"]
			if updateCollectionSubjets:
				if verbosity>=2: print('|---- jetToolBox: Using updateCollection option. ASSUMING MINIAOD collection '+ updateCollectionSubjets +' for Nsubjettiness of subjets.')
		elif addPrunedSubjets:
			mod["NsubGroomer"] = mod["PFJetsPruned"]
			mod["NsubSubjets"] = mod["PATSubjetsPrunedLabel"]
			mod["NsubPATSubjets"] = mod["PATSubjetsPruned"]
		else: 
			raise ValueError('|---- jetToolBox: Nsubjettiness of subjets needs a Subjet collection. Or create one using addSoftDropSubjets option, or updateCollection.')

		mod["Nsubjettiness"] = 'Nsubjettiness'+mod["NsubSubjets"]
		rangeTau = range(1,subjetMaxTau+1)
		_addProcessAndTask(proc, mod["Nsubjettiness"],
				Njettiness.clone( src = cms.InputTag( ( mod["NsubGroomer"] if not updateCollectionSubjets else updateCollectionSubjets ), 'SubJets' ), 
					Njets=cms.vuint32(rangeTau),         # compute 1-, 2-, 3-, 4- subjettiness
					# variables for measure definition : 
					measureDefinition = cms.uint32( 0 ), # CMS default is normalized measure
					beta = cms.double(1.0),              # CMS default is 1
					R0 = cms.double( jetSize ),              # CMS default is jet cone size
					Rcutoff = cms.double( 999.0),       # not used by default
					# variables for axes definition :
					axesDefinition = cms.uint32( 6 ),    # CMS default is 1-pass KT axes
					nPass = cms.int32(999),             # not used by default
					akAxesR0 = cms.double(-999.0) ) )        # not used by default

		elemToKeep += [ 'keep *_'+mod["Nsubjettiness"]+'_*_*' ]
		for tau in rangeTau: getattr( proc, ( mod["NsubPATSubjets"] if not updateCollectionSubjets else patSubJets ) ).userData.userFloats.src += [mod["Nsubjettiness"]+':tau'+str(tau) ] 
		jetSeq += getattr(proc, mod["Nsubjettiness"])
		toolsUsed.append( mod["Nsubjettiness"] )

	###### QGTagger
	if addQGTagger:
		if ( 'ak4' in jetalgo ) and ( PUMethod not in ['Puppi','CS','SK'] ) :
			from RecoJets.JetProducers.QGTagger_cfi import QGTagger
			proc.load('RecoJets.JetProducers.QGTagger_cfi') 	## In 74X you need to run some stuff before.
			mod["QGTagger"] = 'QGTagger'+mod["PATJetsLabelPost"]
			_addProcessAndTask(proc, mod["QGTagger"],
					QGTagger.clone(
						srcJets = cms.InputTag( mod["PFJetsOrUpdate"] ),    # Could be reco::PFJetCollection or pat::JetCollection (both AOD and miniAOD)
						jetsLabel = cms.string('QGL_AK4PF'+QGjetsLabel)        # Other options (might need to add an ESSource for it): see https://twiki.cern.ch/twiki/bin/viewauth/CMS/QGDataBaseVersion
						)
					)
			elemToKeep += [ 'keep *_'+mod["QGTagger"]+'_*_*' ]
			getattr( proc, mod["PATJets"]).userData.userFloats.src += [mod["QGTagger"]+':qgLikelihood']
			jetSeq += getattr(proc, mod["QGTagger"])

			toolsUsed.append( mod["QGTagger"] )
		else:
			raise ValueError('|---- jetToolBox: QGTagger is optimized for ak4 jets with CHS. NOT running QGTagger')

			
	####### Pileup JetID
	if addPUJetID:
		if ( 'ak4' in jetalgo ) and ( PUMethod not in ['CS','SK'] ):
			if PUMethod=="Puppi" and verbosity>=1: print('|---- jetToolBox: PUJetID is not yet optimized for ak4 PFjets with PUPPI. USE ONLY FOR TESTING.')
			from RecoJets.JetProducers.pileupjetidproducer_cfi import pileupJetIdCalculator,pileupJetIdEvaluator

			mod["PUJetIDCalc"] = mod["PATJetsLabelPost"]+'pileupJetIdCalculator'
			_addProcessAndTask(proc, mod["PUJetIDCalc"],
					pileupJetIdCalculator.clone(
						jets = cms.InputTag( mod["PFJetsOrUpdate"] ),
						rho = cms.InputTag("fixedGridRhoFastjetAll"),
						vertexes = cms.InputTag(pvLabel),
						applyJec = cms.bool(True),
						inputIsCorrected = cms.bool(False)
						))

			mod["PUJetIDEval"] = mod["PATJetsLabelPost"]+'pileupJetIdEvaluator'
			_addProcessAndTask(proc, mod["PUJetIDEval"],
					pileupJetIdEvaluator.clone(
						jetids = cms.InputTag(mod["PUJetIDCalc"]),
						jets = cms.InputTag( mod["PFJetsOrUpdate"] ),
						rho = cms.InputTag("fixedGridRhoFastjetAll"),
						vertexes = cms.InputTag(pvLabel)
						)
					)

			getattr( proc, mod["PATJets"]).userData.userFloats.src += [mod["PUJetIDEval"]+':fullDiscriminant']
			getattr( proc, mod["PATJets"]).userData.userInts.src += [mod["PUJetIDEval"]+':cutbasedId',mod["PUJetIDEval"]+':fullId']
			elemToKeep += ['keep *_'+mod["PUJetIDEval"]+'_*_*']
			toolsUsed.append( mod["PUJetIDEval"] )
		else:
			raise ValueError('|---- jetToolBox: PUJetID is optimized for ak4 PFjets with CHS. NOT running PUJetID.')

	###### Energy Correlation Functions
	if addEnergyCorrFunc:
		if PUMethod!="Puppi" or (addSoftDrop==False and addSoftDropSubjets==False):
			raise ValueError("|---- jetToolBox: addEnergyCorrFunc only supported for Puppi w/ addSoftDrop or addSoftDropSubjets")
		from RecoJets.JetProducers.ECF_cff import ecfNbeta1, ecfNbeta2
		mod["ECFnb1"] = 'nb1'+mod["SubstructureLabel"]+'SoftDrop'
# 		mod["ECFnb2"] = 'nb2'+mod["SubstructureLabel"]+'SoftDrop'
		_addProcessAndTask(proc, mod["ECFnb1"], ecfNbeta1.clone(src=cms.InputTag(mod["PFJetsSoftDrop"]), cuts=cms.vstring('', '', 'pt > 250')))
# 		_addProcessAndTask(proc, mod["ECFnb2"], ecfNbeta2.clone(src=cms.InputTag(mod["PFJetsSoftDrop"]), cuts=cms.vstring('', '', 'pt > 250')))
		elemToKeep += [ 'keep *_' + mod["ECFnb1"] + '_*_*',
					# 'keep *_'+mod["ECFnb2"]+'_*_*'
					]
		jetSeq += getattr(proc, mod["ECFnb1"])
# 		jetSeq += getattr(proc, mod["ECFnb2"])
# 		toolsUsed.extend([mod["ECFnb1"], mod["ECFnb2"]])
		toolsUsed.extend([mod["ECFnb1"]])

		# set up user floats
		getattr(proc, mod["PATJetsSoftDrop"]).userData.userFloats.src += [
			mod["ECFnb1"]+':ecfN2',
			mod["ECFnb1"]+':ecfN3',
# 			mod["ECFnb2"]+':ecfN2',
# 			mod["ECFnb2"]+':ecfN3',
		]
		# rekey the groomed ECF value maps to the ungroomed reco jets, which will then be picked
		# up by PAT in the user floats. 
		mod["PFJetsSoftDropValueMap"] = mod["PFJetsSoftDrop"]+'ValueMap'
		_addProcessAndTask(proc, mod["PFJetsSoftDropValueMap"],
			cms.EDProducer("RecoJetToPatJetDeltaRValueMapProducer",
				src = cms.InputTag(mod["PFJets"]),
				matched = cms.InputTag(mod["PATJetsSoftDrop"]),
				distMax = cms.double(jetSize),
				values = cms.vstring([
					'userFloat("'+mod["ECFnb1"]+':ecfN2'+'")',
					'userFloat("'+mod["ECFnb1"]+':ecfN3'+'")',
# 					'userFloat("'+mod["ECFnb2"]+':ecfN2'+'")',
# 					'userFloat("'+mod["ECFnb2"]+':ecfN3'+'")',
				]),
				valueLabels = cms.vstring( [
					mod["ECFnb1"]+'N2',
					mod["ECFnb1"]+'N3',
# 					mod["ECFnb2"]+'N2',
# 					mod["ECFnb2"]+'N3',
				]),
			)
		)
		getattr(proc, mod["PATJets"]).userData.userFloats.src += [
			mod["PFJetsSoftDropValueMap"]+':'+mod["ECFnb1"]+'N2',
			mod["PFJetsSoftDropValueMap"]+':'+mod["ECFnb1"]+'N3',
# 			mod["PFJetsSoftDropValueMap"]+':'+mod["ECFnb2"]+'N2',
# 			mod["PFJetsSoftDropValueMap"]+':'+mod["ECFnb2"]+'N3',
		]

	if addEnergyCorrFuncSubjets:
		if PUMethod!="Puppi" or addSoftDropSubjets==False:
			raise ValueError("|---- jetToolBox: addEnergyCorrFuncSubjets only supported for Puppi w/ addSoftDropSubjets")
		from RecoJets.JetProducers.ECF_cff import ecfNbeta1, ecfNbeta2
		mod["ECFnb1Subjets"] = 'nb1'+mod["SubstructureLabel"]+'SoftDropSubjets'
		mod["ECFnb2Subjets"] = 'nb2'+mod["SubstructureLabel"]+'SoftDropSubjets'
		_addProcessAndTask(proc, mod["ECFnb1Subjets"], ecfNbeta1.clone(src=cms.InputTag(mod["PFJetsSoftDrop"], 'SubJets')))
		_addProcessAndTask(proc, mod["ECFnb2Subjets"], ecfNbeta2.clone(src=cms.InputTag(mod["PFJetsSoftDrop"], 'SubJets')))
		elemToKeep += [ 'keep *_'+mod["ECFnb1Subjets"]+'_*_*', 'keep *_'+mod["ECFnb2Subjets"]+'_*_*']
		jetSeq += getattr(proc, mod["ECFnb1Subjets"])
		jetSeq += getattr(proc, mod["ECFnb2Subjets"])
		toolsUsed.extend([mod["ECFnb1Subjets"],mod["ECFnb2Subjets"]])

		# set up user floats
		getattr(proc, mod["PATSubjetsSoftDrop"]).userData.userFloats.src += [
			mod["ECFnb1Subjets"]+':ecfN2',
			mod["ECFnb1Subjets"]+':ecfN3',
			mod["ECFnb2Subjets"]+':ecfN2',
			mod["ECFnb2Subjets"]+':ecfN3',
		]

	if hasattr(proc, 'patJetPartons'): proc.patJetPartons.particles = genParticlesLabel

	_addProcessAndTask(proc, mod["selPATJets"], selectedPatJets.clone(src=mod["PATJets"], cut=Cut))
	elemToKeep += [ 'keep *_'+mod["selPATJets"]+'_*_*' ]
	elemToKeep += [ 'drop *_'+mod["selPATJets"]+'_calo*_*' ]
	elemToKeep += [ 'drop *_'+mod["selPATJets"]+'_tagInfos_*' ]

	if updateCollectionSubjets:
		mod["PATSubjets"] = patJets+mod["PATSubjetsLabel"]
		mod["selPATSubjets"] = selPatJets+mod["PATSubjetsLabel"]
		_addProcessAndTask(proc, mod["selPATSubjets"], selectedPatJets.clone(src=mod["PATSubjets"], cut=Cut))
		elemToKeep += [ 'keep *_'+mod["selPATSubjets"]+'__*' ]


	if len(toolsUsed) > 0 and verbosity>=2: print('|---- jetToolBox: Running '+', '.join(toolsUsed)+'.')
	if verbosity>=2: print('|---- jetToolBox: Creating '+mod["selPATJets"]+' collection.')
	if updateCollectionSubjets and verbosity>=2: print('|---- jetToolBox: Creating '+mod["selPATSubjets"]+' collection.')

	### "return"
	setattr(proc, jetSequence, jetSeq)
	if outputFile!='':
		if hasattr(proc, outputFile): getattr(proc, outputFile).outputCommands += elemToKeep
		else: setattr( proc, outputFile, 
				cms.OutputModule('PoolOutputModule', 
					fileName = cms.untracked.string('jettoolbox.root'), 
					outputCommands = cms.untracked.vstring( elemToKeep ) ) )

	if associateTask:
		from PhysicsTools.PatAlgos.tools.helpers import getPatAlgosToolsTask
		task = getPatAlgosToolsTask(proc)
		if hasattr(proc, 'endpath'):
			getattr(proc, 'endpath').associate(task)
		else:
			setattr(proc, 'endpath', cms.EndPath(task))
		if outputFile != '': 
			getattr(proc, 'endpath').insert(-1, getattr(proc, outputFile))

	#### removing mc matching for data
	if runOnData:
		from PhysicsTools.PatAlgos.tools.coreTools import removeMCMatching
		removeMCMatching(proc, names=['Jets'], outputModules=[outputFile])

	if verbosity>=3:
		print('|---- jetToolBox: List of modules created (and other internal names):')
		for m in mod:
			print('      '+m+' = '+mod[m])
예제 #21
0
def addFlashggPFCHSJets(process, 
                        isData,
                        vertexIndex = 0, 
                        #doQGTagging = True, 
                        label ='', 
                        debug = False):
  setattr(process, 'selectedMuons' + label, cms.EDFilter("CandPtrSelector", 
                                                         src = cms.InputTag("slimmedMuons"), 
                                                         cut = cms.string('''abs(eta)<2.5 && pt>10. &&
                                                         (pfIsolationR04().sumChargedHadronPt+
                                                         max(0.,pfIsolationR04().sumNeutralHadronEt+
                                                         pfIsolationR04().sumPhotonEt-
                                                         0.50*pfIsolationR04().sumPUPt))/pt < 0.20 && 
                                                         (isPFMuon && (isGlobalMuon || isTrackerMuon) )''')))
  
  setattr(process, 'selectedElectrons' + label, cms.EDFilter("CandPtrSelector", 
                                                             src = cms.InputTag("slimmedElectrons"), 
                                                             cut = cms.string('''abs(eta)<2.5 && pt>20. &&
                                                             gsfTrack.isAvailable() &&
                                                             gsfTrack.hitPattern().numberOfLostHits(\'MISSING_INNER_HITS\') < 2 &&
                                                             (pfIsolationVariables().sumChargedHadronPt+
                                                             max(0.,pfIsolationVariables().sumNeutralHadronEt+
                                                             pfIsolationVariables().sumPhotonEt-
                                                             0.5*pfIsolationVariables().sumPUPt))/pt < 0.15''')))
  
  # Simple producer which just removes the Candidates which
  # don't come from the legacy vertex according to the Flashgg Vertex Map
  setattr(process,'flashggCHSLegacyVertexCandidates' + label,
          cms.EDProducer('FlashggMultiCHSLegacyVertexCandProducer',
                         PFCandidatesTag       = cms.InputTag('packedPFCandidates'),
                         DiPhotonTag           = cms.InputTag('flashggDiPhotons'),
                         VertexCandidateMapTag = cms.InputTag("flashggVertexMapForCHS"),
                         VertexTag             = cms.InputTag('offlineSlimmedPrimaryVertices'),
                         vertexIndex           = cms.uint32(vertexIndex),
                         debug                 = cms.untracked.bool(debug)
                       )
  )
  
  setattr(process, 'pfCHSLeg' + label, cms.EDFilter("CandPtrSelector", 
                                                    src = cms.InputTag('flashggCHSLegacyVertexCandidates' + label), 
                                                    cut = cms.string('')))
  
  # then remove the previously selected muons
  setattr(process, 'pfNoMuonCHSLeg' + label,  cms.EDProducer("CandPtrProjector", 
                                                             src  = cms.InputTag("pfCHSLeg" + label), 
                                                             veto = cms.InputTag("selectedMuons" + label)))
  # then remove the previously selected electrons
  setattr(process, 'pfNoElectronsCHSLeg' + label,  cms.EDProducer("CandPtrProjector", 
                                                                  src  = cms.InputTag("pfNoMuonCHSLeg" + label), 
                                                                  veto = cms.InputTag("selectedElectrons" + label)))
  
  #Import RECO jet producer for ak4 PF and GEN jet
  from RecoJets.JetProducers.ak4PFJets_cfi  import ak4PFJets
  setattr(process, 'ak4PFJetsCHSLeg' + label, ak4PFJets.clone ( src = 'pfNoElectronsCHSLeg' + label, doAreaFastjet = True))

  if isData:
    JECs = ['L1FastJet', 'L2Relative', 'L3Absolute','L2L3Residual']
  else:
    JECs = ['L1FastJet', 'L2Relative', 'L3Absolute']
    
  # NOTE: this is the 74X recipe for the jet clustering
  addJetCollection(
    process,
    postfix        = label,
    labelName      = 'AK4PFCHSLeg',
    jetSource      = cms.InputTag('ak4PFJetsCHSLeg' + label),
    pvSource       = cms.InputTag('offlineSlimmedPrimaryVertices'),
    pfCandidates   = cms.InputTag('packedPFCandidates'),
    svSource       = cms.InputTag('slimmedSecondaryVertices'),
    btagDiscriminators = [ flashggBTag ],
    jetCorrections = ('AK4PFchs', JECs, 'None'),
    genJetCollection = cms.InputTag('slimmedGenJets'),
    genParticles     = cms.InputTag('prunedGenParticles'),
    # jet param
    algo = 'AK', rParam = 0.4
  )
  
  #adjust PV used for Jet Corrections
  #process.patJetCorrFactorsAK4PFCHSLeg.primaryVertices = "offlineSlimmedPrimaryVertices"
  getattr(process, 'patJetCorrFactorsAK4PFCHSLeg' + label).primaryVertices = "offlineSlimmedPrimaryVertices"
  
  if not hasattr(process,"QGPoolDBESSource"):
    process.QGPoolDBESSource = cms.ESSource("PoolDBESSource",
                                            CondDBSetup,
                                            toGet = cms.VPSet(),
                                            connect = cms.string('sqlite:QGL_'+qgDatabaseVersion+'.db') 
                                            )
    process.es_prefer_qg = cms.ESPrefer('PoolDBESSource','QGPoolDBESSource')
  
  for type in ['AK4PFchs']:#,'AK4PFchs_antib']:
    process.QGPoolDBESSource.toGet.extend(cms.VPSet(cms.PSet(
          record = cms.string('QGLikelihoodRcd'),
          tag    = cms.string('QGLikelihoodObject_'+qgDatabaseVersion+'_'+type),
          label  = cms.untracked.string('QGL_'+type)
          )))
  
  from RecoJets.JetProducers.QGTagger_cfi import QGTagger
  setattr( process, 'QGTaggerPFCHS' + label,  
           QGTagger.clone( srcJets   = 'patJetsAK4PFCHSLeg' + label ,jetsLabel = 'QGL_AK4PFchs', vertexIndex = cms.uint32(vertexIndex),
                           srcVertexCollection = 'offlineSlimmedPrimaryVertices'))

  from RecoJets.JetProducers.PileupJetIDParams_cfi import full_80x_chs
  
  flashggJets = cms.EDProducer('FlashggJetProducer',
                               DiPhotonTag = cms.InputTag('flashggDiPhotons'),
                               VertexTag   = cms.InputTag('offlineSlimmedPrimaryVertices'),
                               JetTag      = cms.InputTag('patJetsAK4PFCHSLeg' + label),
                               VertexCandidateMapTag = cms.InputTag("flashggVertexMapForCHS"),
                               qgVariablesInputTag   = cms.InputTag('QGTaggerPFCHS'+label, 'qgLikelihood'),
                               ComputeSimpleRMS = cms.bool(True),
                               PileupJetIdParameters = full_80x_chs,
                               rho     = cms.InputTag("fixedGridRhoFastjetAll"),
                               JetCollectionIndex = cms.uint32(vertexIndex),
                               Debug = cms.untracked.bool(False)
                               )
  setattr( process, 'flashggPFCHSJets'+ label, flashggJets)

  # randomize Jets
  from flashgg.MicroAOD.flashggRandomizedJetProducer_cfi import flashggRandomizedJets
  flashggRandomizedPFCHSJets = flashggRandomizedJets.clone()
  flashggRandomizedPFCHSJets.src = "flashggPFCHSJets" + label
  setattr(process.RandomNumberGeneratorService, 'flashggRandomizedPFCHSJets' + label, cms.PSet(initialSeed = cms.untracked.uint32(36423784 + int(label))))
  setattr( process, 'flashggRandomizedPFCHSJets' + label, flashggRandomizedPFCHSJets )

  flashggSelectedJets = cms.EDFilter("FLASHggJetSelector",
                                     src = cms.InputTag( 'flashggRandomizedPFCHSJets' + label ),
                                     cut = cms.string("pt > 15.")
  )
  setattr( process, 'flashggSelectedPFCHSJets'+label, flashggSelectedJets )
예제 #22
0
def addFlashggPFCHSJets(process,
                        vertexIndex=0,
                        doQGTagging=True,
                        label='',
                        debug=False):
    setattr(
        process, 'selectedMuons' + label,
        cms.EDFilter("CandPtrSelector",
                     src=cms.InputTag("slimmedMuons"),
                     cut=cms.string('''abs(eta)<2.5 && pt>10. &&
                                                         (pfIsolationR04().sumChargedHadronPt+
                                                         max(0.,pfIsolationR04().sumNeutralHadronEt+
                                                         pfIsolationR04().sumPhotonEt-
                                                         0.50*pfIsolationR04().sumPUPt))/pt < 0.20 && 
                                                         (isPFMuon && (isGlobalMuon || isTrackerMuon) )'''
                                    )))

    setattr(
        process, 'selectedElectrons' + label,
        cms.EDFilter("CandPtrSelector",
                     src=cms.InputTag("slimmedElectrons"),
                     cut=cms.string('''abs(eta)<2.5 && pt>20. &&
                                                             gsfTrack.isAvailable() &&
                                                             gsfTrack.hitPattern().numberOfLostHits(\'MISSING_INNER_HITS\') < 2 &&
                                                             (pfIsolationVariables().sumChargedHadronPt+
                                                             max(0.,pfIsolationVariables().sumNeutralHadronEt+
                                                             pfIsolationVariables().sumPhotonEt-
                                                             0.5*pfIsolationVariables().sumPUPt))/pt < 0.15'''
                                    )))

    # Simple producer which just removes the Candidates which
    # don't come from the legacy vertex according to the Flashgg Vertex Map
    setattr(
        process, 'flashggCHSLegacyVertexCandidates' + label,
        cms.EDProducer(
            'FlashggMultiCHSLegacyVertexCandProducer',
            PFCandidatesTag=cms.InputTag('packedPFCandidates'),
            DiPhotonTag=cms.InputTag('flashggDiPhotons'),
            VertexCandidateMapTag=cms.InputTag("flashggVertexMapForCHS"),
            VertexTag=cms.InputTag('offlineSlimmedPrimaryVertices'),
            vertexIndex=cms.untracked.uint32(vertexIndex),
            debug=cms.untracked.bool(debug)))

    setattr(
        process, 'pfCHSLeg' + label,
        cms.EDFilter("CandPtrSelector",
                     src=cms.InputTag('flashggCHSLegacyVertexCandidates' +
                                      label),
                     cut=cms.string('')))

    # then remove the previously selected muons
    setattr(
        process, 'pfNoMuonCHSLeg' + label,
        cms.EDProducer("CandPtrProjector",
                       src=cms.InputTag("pfCHSLeg" + label),
                       veto=cms.InputTag("selectedMuons" + label)))
    # then remove the previously selected electrons
    setattr(
        process, 'pfNoElectronsCHSLeg' + label,
        cms.EDProducer("CandPtrProjector",
                       src=cms.InputTag("pfNoMuonCHSLeg" + label),
                       veto=cms.InputTag("selectedElectrons" + label)))

    #Import RECO jet producer for ak4 PF and GEN jet
    from RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJets
    #from RecoJets.JetProducers.ak4GenJets_cfi import ak4GenJets
    setattr(
        process, 'ak4PFJetsCHSLeg' + label,
        ak4PFJets.clone(src='pfNoElectronsCHSLeg' + label, doAreaFastjet=True))
    #process.ak4GenJetsLeg   = ak4GenJets.clone( src = 'packedGenParticles')

    # NOTE: this is the 74X recipe for the jet clustering
    addJetCollection(
        process,
        postfix=label,
        labelName='AK4PFCHSLeg',
        jetSource=cms.InputTag('ak4PFJetsCHSLeg' + label),
        pvSource=cms.InputTag('offlineSlimmedPrimaryVertices'),
        pfCandidates=cms.InputTag('packedPFCandidates'),
        svSource=cms.InputTag('slimmedSecondaryVertices'),
        btagDiscriminators=[flashggBTag],
        jetCorrections=('AK4PFchs', ['L1FastJet', 'L2Relative',
                                     'L3Absolute'], 'None'),
        genJetCollection=cms.InputTag('slimmedGenJets'),
        genParticles=cms.InputTag('prunedGenParticles'),
        # jet param
        algo='AK',
        rParam=0.4)

    #adjust PV used for Jet Corrections
    #process.patJetCorrFactorsAK4PFCHSLeg.primaryVertices = "offlineSlimmedPrimaryVertices"
    getattr(process, 'patJetCorrFactorsAK4PFCHSLeg' +
            label).primaryVertices = "offlineSlimmedPrimaryVertices"

    # Flashgg Jet producer using the collection created with function above.
    flashggJets = cms.EDProducer(
        'FlashggJetProducer',
        DiPhotonTag=cms.InputTag('flashggDiPhotons'),
        VertexTag=cms.InputTag('offlineSlimmedPrimaryVertices'),
        JetTag=cms.InputTag('patJetsAK4PFCHSLeg' + label),
        VertexCandidateMapTag=cms.InputTag("flashggVertexMapForCHS"),
        #                               PileupJetIdParameters = cms.PSet(pu_jetid)
    )
    setattr(process, 'flashggPFCHSJets' + label, flashggJets)

    if doQGTagging:
        from RecoJets.JetProducers.QGTagger_cfi import QGTagger
        setattr(
            process, 'QGTaggerPFCHS' + label,
            QGTagger.clone(srcJets='flashggPFCHSJets' + label,
                           jetsLabel='ak4PFJetsCHS'))

    flashggSelectedJets = cms.EDFilter("FLASHggJetSelector",
                                       src=cms.InputTag('flashggPFCHSJets' +
                                                        label),
                                       cut=cms.string("pt > 15."))
    setattr(process, 'flashggSelectedPFCHSJets' + label, flashggSelectedJets)