예제 #1
0
def addFatJet(process):
    from RecoJets.JetProducers.ak5PFJets_cfi import ak5PFJets
    process.ca8PFJetsCHS = ak5PFJets.clone(
        src = 'pfNoPileUp',
        jetPtMin = cms.double(10.0),
        doAreaFastjet = cms.bool(True),
        rParam = cms.double(0.8),
        jetAlgorithm = cms.string("CambridgeAachen"),
    )

    jetSource = 'ca8PFJetsCHS'

    # corrections 
    from PhysicsTools.PatAlgos.recoLayer0.jetCorrFactors_cfi import patJetCorrFactors
    process.patJetCorrFactorsCA8CHS = patJetCorrFactors.clone()
    process.patJetCorrFactorsCA8CHS.src = jetSource
    # will need to add L2L3 corrections in the cfg
    process.patJetCorrFactorsCA8CHS.levels = ['L1FastJet', 'L2Relative', 'L3Absolute']
    process.patJetCorrFactorsCA8CHS.payload = 'AK7PFchs'
    process.patJetCorrFactorsCA8CHS.useRho = True

    # pat jet
    from PhysicsTools.PatAlgos.producersLayer1.jetProducer_cfi import patJets
    process.patJetsCA8CHS = patJets.clone()
    process.patJetsCA8CHS.jetSource = jetSource
    process.patJetsCA8CHS.addJetCharge = False
    process.patJetsCA8CHS.embedCaloTowers = False
    process.patJetsCA8CHS.embedPFCandidates = False
    process.patJetsCA8CHS.addAssociatedTracks = False
    process.patJetsCA8CHS.addBTagInfo = False
    process.patJetsCA8CHS.addDiscriminators = False
    process.patJetsCA8CHS.getJetMCFlavour = False
    process.patJetsCA8CHS.jetCorrFactorsSource = cms.VInputTag(cms.InputTag('patJetCorrFactorsCA8CHS'))
    process.patJetsCA8CHS.genPartonMatch = cms.InputTag('patJetPartonMatchCA8CHS')
    process.patJetsCA8CHS.genJetMatch = cms.InputTag('patJetGenJetMatchCA8CHS')

    from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets
    process.selectedPatJetsCA8CHS = selectedPatJets.clone()
    process.selectedPatJetsCA8CHS.src = 'patJetsCA8CHS'
    process.selectedPatJetsCA8CHS.cut = 'pt()>20'


#process.jetMCSequenceCA8CHS = cms.Sequence(
    #process.patJetPartonMatchCA8CHS +
    #process.genParticlesForJetsNoNu +
    #process.ca8GenJetsNoNu +
    #process.patJetGenJetMatchCA8CHS
    #)

    process.PATJetSequenceCA8CHS = cms.Sequence(
        process.ca8PFJetsCHS +
        #process.jetMCSequenceCA8CHS +
        process.patJetCorrFactorsCA8CHS
        #process.patJetsCA8CHS +
        #process.selectedPatJetsCA8CHS
        )

    process.PATJetPathCA8CHS = cms.Path ( process.PATJetSequenceCA8CHS )
예제 #2
0
#process.es_prefer_jec = cms.ESPrefer('PoolDBESSource','jec')

process.load("PhysicsTools.PatAlgos.producersLayer1.jetUpdater_cff")
process.patJetCorrFactorsReapplyJEC = process.patJetCorrFactorsUpdated.clone(
    src=cms.InputTag("slimmedJets"),
    levels=['L1FastJet', 'L2Relative', 'L3Absolute'],
    payload='AK4PFchs')

process.load("PhysicsTools.PatAlgos.producersLayer1.jetUpdater_cff")
process.patJetsReapplyJEC = process.patJetsUpdated.clone(
    jetSource=cms.InputTag("slimmedJets"),
    jetCorrFactorsSource=cms.VInputTag(
        cms.InputTag("patJetCorrFactorsReapplyJEC")))

from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets
process.goodJets = selectedPatJets.clone(src='patJetsReapplyJEC',
                                         cut='pt>30 & abs(eta)<2.4')

process.load('RecoJets.JetProducers.QGTagger_cfi')
process.QGTagger.srcJets = cms.InputTag('goodJets')
process.QGTagger.jetsLabel = cms.string('QGL_AK4PFchs')

##-------------------- User analyzer  --------------------------------
process.hadtop = cms.EDAnalyzer(
    'TTHFlatTreeProducer',
    jets=cms.InputTag('goodJets'),
    muons=cms.InputTag('slimmedMuons'),
    electrons=cms.InputTag('slimmedElectrons'),
    met=cms.InputTag('slimmedMETs'),
    vertices=cms.InputTag('offlineSlimmedPrimaryVertices'),
    rho=cms.InputTag('fixedGridRhoFastjetAll'),
    nJetsMin=cms.int32(6),
예제 #3
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)
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','combinedSecondaryVertexBJetTags','pfCombinedSecondaryVertexSoftLeptonBJetTags','pfPositiveCombinedSecondaryVertexBJetTags','pfNegativeCombinedSecondaryVertexBJetTags']
#,'pfCombinedSecondaryVertexBJetTags','pfCombinedMVABJetTags','pfCombinedSecondaryVertexSoftLeptonBJetTags','pfPositiveCombinedSecondaryVertexBJetTags','pfNegativeCombinedSecondaryVertexBJetTags']
#,'pfCombinedInclusiveSecondaryVertexBJetTags'

	#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','L2L3Residual']
	#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']

	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)
예제 #5
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])
예제 #6
0
selectedElectrons = selectedPatElectrons.clone(
  src = cms.InputTag( 'patElectrons' )
, cut = '' # electronCut
)

standAloneElectronVetoFilter = cms.EDFilter(
  "PATCandViewCountFilter"
, src       = cms.InputTag( 'selectedElectrons' )
, minNumber = cms.uint32( 0 )
, maxNumber = cms.uint32( 0 )
)

# Step 4

selectedJets = selectedPatJets.clone(
  src = cms.InputTag( 'patJets' )
, cut = '' # jetCut
)

signalVeryTightJets = selectedPatJets.clone(
  src = cms.InputTag( 'selectedJets' )
, cut = '' # veryTightJetCut
)

standAloneSignalVeryTightJetsFilter = cms.EDFilter(
  "PATCandViewCountFilter"
, src       = cms.InputTag( 'signalVeryTightJets' )
, minNumber = cms.uint32( 1 )
, maxNumber = cms.uint32( 99 )
)

signalTightJets = selectedPatJets.clone(
예제 #7
0
    levels=['L1FastJet', 'L2Relative', 'L3Absolute'],
    payload='AK4PFPuppi')

process.patJetsReapplyJEC = process.updatedPatJets.clone(
    jetSource=cms.InputTag("slimmedJets"),
    jetCorrFactorsSource=cms.VInputTag(
        cms.InputTag("patJetCorrFactorsReapplyJEC")))

process.patJetsReapplyJECPuppi = process.updatedPatJets.clone(
    jetSource=cms.InputTag("slimmedJetsPuppi"),
    jetCorrFactorsSource=cms.VInputTag(
        cms.InputTag("patJetCorrFactorsReapplyJECPuppi")))

#--- define the good jets -------------------------------
from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets
process.goodJets = selectedPatJets.clone(src='patJetsReapplyJEC',
                                         cut='pt > 20 && abs(eta) < 5.0')
process.goodJetsPuppi = selectedPatJets.clone(src='patJetsReapplyJECPuppi',
                                              cut='pt > 20 && abs(eta) < 5.0')

#---- Tight JetID -----------------------------------------------------
tight_abs_eta_2p6_chs_puppi = """((neutralHadronEnergyFraction < 0.90 && neutralEmEnergyFraction < 0.90 && numberOfDaughters > 1)
&& (chargedHadronEnergyFraction > 0 && chargedMultiplicity > 0) && abs(eta) <= 2.6)"""

tight_abs_eta_2p6_2p7_chs = """((neutralHadronEnergyFraction < 0.90 && neutralEmEnergyFraction < 0.99 && chargedMultiplicity > 0)  && abs(eta) > 2.6 && abs(eta) <= 2.7)"""

tight_abs_eta_2p7_3p0_chs = """(neutralEmEnergyFraction > 0.01 && neutralEmEnergyFraction < 0.99 && neutralMultiplicity > 2
&& abs(eta) > 2.7 && abs(eta) <= 3.0 )"""

tight_abs_eta_3p0_chs = """(neutralHadronEnergyFraction > 0.2 && neutralEmEnergyFraction < 0.90 && neutralMultiplicity > 10 && abs(eta) > 3.0 )"""

tight_abs_eta_2p6_2p7_puppi = """((neutralHadronEnergyFraction < 0.90 && neutralEmEnergyFraction < 0.99)  && abs(eta) > 2.6 && abs(eta) <= 2.7)"""
def jetToolbox( proc, jetType, jetSequence,PUMethod=''):

	JETCorrPayload='None'
	JETCorrLevels = [ 'None' ]
	#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+'PFchs'
	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,
			rParam = jetSize,
			jetCorrections =  JEC, #( 'AK'+size+'PFchs', cms.vstring( ['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
			pfCandidates = cms.InputTag( 'particleFlow' ),  #'packedPFCandidates'),
			svSource = cms.InputTag('slimmedSecondaryVertices'),
			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')

				))

	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')
				)
			)

	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']

	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)
예제 #9
0
def jetToolbox(
    proc,
    jetType,
    jetSequence,
    outputFile,
    PUMethod="CHS",  #### Options: Puppi, CS, SK, Plain
    miniAOD=True,
    JETCorrPayload="None",
    JETCorrLevels=["None"],
    GetJetMCFlavour=True,
    Cut="",
    subJETCorrPayload="None",
    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,
):

    ###############################################################################
    #######  Verifying some inputs and defining variables
    ###############################################################################
    print "|---- jetToolbox: Initialyzing collection..."
    supportedJetAlgos = {"ak": "AntiKt", "ca": "CambridgeAachen", "kt": "Kt"}
    recommendedJetAlgos = ["ak4", "ak8", "ca4", "ca8", "ca10"]
    payloadList = [
        "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"]
    jetAlgo = ""
    algorithm = ""
    size = ""
    for type, tmpAlgo in supportedJetAlgos.iteritems():
        if type in jetType.lower():
            jetAlgo = type
            algorithm = tmpAlgo
            size = jetType.replace(type, "")

    jetSize = 0.0
    if int(size) in range(0, 20):
        jetSize = int(size) / 10.0
    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 = "packedPFCandidates"

        setattr(
            proc,
            "chs",
            cms.EDFilter("CandPtrSelector", src=cms.InputTag("packedPFCandidates"), cut=cms.string("fromPV")),
        )
        jetSeq += getattr(proc, "chs")

        ## 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 = "particleFlow"
        svLabel = "inclusiveSecondaryVertices"

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

        ## b-tag discriminators
    bTagDiscriminators = [
        "pfTrackCountingHighEffBJetTags",
        "pfTrackCountingHighPurBJetTags",
        "pfJetProbabilityBJetTags",
        "pfJetBProbabilityBJetTags",
        "pfSimpleSecondaryVertexHighEffBJetTags",
        "pfSimpleSecondaryVertexHighPurBJetTags",
        "pfCombinedSecondaryVertexV2BJetTags",
        "pfCombinedSecondaryVertexBJetTags",
        #'pfcombinedInclusiveSecondaryVertexV2BJetTags',
        #'pfCombinedSecondaryVertexSoftLeptonBJetTags',
        #'pfCombinedMVABJetTags'
    ]

    ####  Creating PATjets
    if "Puppi" in PUMethod:

        proc.load("CommonTools.PileupAlgos.Puppi_cff")
        from RecoJets.JetProducers.ak4PFJetsPuppi_cfi import ak4PFJetsPuppi

        setattr(
            proc,
            jetalgo + "PFJetsPuppi",
            ak4PFJetsPuppi.clone(doAreaFastjet=True, rParam=jetSize, jetAlgorithm=algorithm),
        )
        if miniAOD:
            puppi.candName = cms.InputTag("packedPFCandidates")
            puppi.vertexName = cms.InputTag("offlineSlimmedPrimaryVertices")
        jetSeq += getattr(proc, "puppi")
        jetSeq += getattr(proc, jetalgo + "PFJetsPuppi")

    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 = 'chs'
        if miniAOD:
            getattr(proc, jetalgo + "PFJetsCS").src = "packedPFCandidates"
        # 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")

    elif "SK" in PUMethod:

        proc.load("CommonTools.PileupAlgos.softKiller_cfi")
        from RecoJets.JetProducers.ak4PFJetsSK_cfi import ak4PFJetsSK

        setattr(proc, jetalgo + "PFJetsSK", ak4PFJetsSK.clone(rParam=jetSize, jetAlgorithm=algorithm))
        if miniAOD:
            getattr(proc, "softKiller").PFCandidates = cms.InputTag("packedPFCandidates")
        jetSeq += getattr(proc, "softKiller")
        jetSeq += getattr(proc, jetalgo + "PFJetsSK")

    elif "CHS" in PUMethod:
        setattr(
            proc, jetalgo + "PFJetsCHS", ak4PFJetsCHS.clone(doAreaFastjet=True, rParam=jetSize, jetAlgorithm=algorithm)
        )
        if miniAOD:
            getattr(proc, jetalgo + "PFJetsCHS").src = "chs"
        jetSeq += getattr(proc, jetalgo + "PFJetsCHS")

    else:
        PUMethod = ""
        setattr(proc, jetalgo + "PFJets", ak4PFJets.clone(doAreaFastjet=True, rParam=jetSize, jetAlgorithm=algorithm))
        if miniAOD:
            getattr(proc, jetalgo + "PFJets").src = "packedPFCandidates"
        jetSeq += getattr(proc, jetalgo + "PFJets")

    if 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")

    ### Jet Corrections
    if JETCorrPayload not in payloadList:
        if not set(JETCorrLevels).issubset(set(JECLevels)):
            if "CHS" in PUMethod:
                JEC = ("AK" + size + "PFchs", ["L1FastJet", "L2Relative", "L3Absolute"], "None")
            elif "Plain" in PUMethod:
                JEC = ("AK" + size + "PF", ["L1FastJet", "L2Relative", "L3Absolute"], "None")
            else:
                JEC = None
            if "None" in JETCorrPayload:
                print "|---- jetToolBox: No JEC provided, jetToolbox is using the recommended corrections for this PU method: " + str(
                    JEC
                )
            else:
                print '|---- jetToolBox: JEC payload provided ("' + JETCorrPayload + '") is wrong, jetToolbox is using the recommended corrections for this PU method: ' + str(
                    JEC
                )
        else:
            if "CHS" in PUMethod:
                JEC = ("AK" + size + "PFchs", JETCorrLevels, "None")
            elif "Plain" in PUMethod:
                JEC = ("AK" + size + "PF", JETCorrLevels, "None")
            else:
                JEC = None
            if "None" in JETCorrPayload:
                print "|---- jetToolBox: No JEC payload provided, jetToolbox is using the recommended payload. Using JEC: " + str(
                    JEC
                )
            else:
                print '|---- jetToolBox: JEC payload provided ("' + JETCorrPayload + '") is wrong, jetToolbox is using the recommended corrections for this PU method: ' + str(
                    JEC
                )
    else:
        if not set(JETCorrLevels).issubset(set(JECLevels)):
            if ("CHS" in PUMethod) or ("Plain" in PUMethod):
                JEC = (JETCorrPayload, ["L1FastJet", "L2Relative", "L3Absolute"], "None")
            else:
                JEC = None
            print "|---- jetToolBox: JEC levels are not provided or wrong, jetToolbox is using the recommended levels for this PU method: " + str(
                JEC
            )
        else:
            JEC = (JETCorrPayload, JETCorrLevels, "None")
            print "|---- jetToolBox: JEC payload and levels provided by user. Using JEC: " + str(JEC)

    if addPrunedSubjets or addSoftDropSubjets or addCMSTopTagger:
        if subJETCorrPayload not in payloadList:
            if not set(subJETCorrLevels).issubset(set(JECLevels)):
                if "CHS" in PUMethod:
                    subJEC = ("AK4PFchs", ["L1FastJet", "L2Relative", "L3Absolute"], "None")
                elif "Plain" in PUMethod:
                    subJEC = ("AK4PF", ["L1FastJet", "L2Relative", "L3Absolute"], "None")
                else:
                    subJEC = None
                if "None" in subJETCorrPayload:
                    print "|---- jetToolBox: No subJEC provided, jetToolbox is using the recommended corrections for this PU method: " + str(
                        subJEC
                    )
                else:
                    print '|---- jetToolBox: subJEC payload provided ("' + subJETCorrPayload + '") is wrong, jetToolbox is using the recommended corrections for this PU method: ' + str(
                        subJEC
                    )
            else:
                if "CHS" in PUMethod:
                    subJEC = ("AK4PFchs", subJETCorrLevels, "None")
                elif "Plain" in PUMethod:
                    subJEC = ("AK4PF", subJETCorrLevels, "None")
                else:
                    subJEC = None
                if "None" in subJETCorrPayload:
                    print "|---- jetToolBox: No subJEC payload provided, jetToolbox is using the recommended payload. Using subJEC: " + str(
                        subJEC
                    )
                else:
                    print '|---- jetToolBox: subJEC payload provided ("' + subJETCorrPayload + '") is wrong, jetToolbox is using the recommended corrections for this PU method: ' + str(
                        subJEC
                    )
        else:
            if not set(subJETCorrLevels).issubset(set(JECLevels)):
                if ("CHS" in PUMethod) or ("Plain" in PUMethod):
                    subJEC = (subJETCorrPayload, ["L1FastJet", "L2Relative", "L3Absolute"], "None")
                else:
                    subJEC = None
                print "|---- jetToolBox: subJEC levels are not provided or wrong, jetToolbox is using the recommended levels for this PU method: " + str(
                    subJEC
                )
            else:
                subJEC = (subJETCorrPayload, subJETCorrLevels, "None")
                print "|---- jetToolBox: subJEC payload and levels provided by user. Using subJEC: " + str(subJEC)

    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),  #'packedPFCandidates'),
        svSource=cms.InputTag(svLabel),  #'slimmedSecondaryVertices'),
        genJetCollection=cms.InputTag(jetalgo + "GenJetsNoNu"),
        pvSource=cms.InputTag(pvLabel),  #'offlineSlimmedPrimaryVertices'),
        btagDiscriminators=bTagDiscriminators,
        getJetMCFlavour=GetJetMCFlavour,
        outputModules=["outputFile"],
    )

    if JEC is not None:
        getattr(
            proc, "patJetCorrFactors" + jetALGO + "PF" + PUMethod
        ).primaryVertices = pvLabel  #'offlineSlimmedPrimaryVertices'

    if "CS" in PUMethod:
        getattr(proc, "patJets" + jetALGO + "PF" + PUMethod).getJetMCFlavour = False
    else:
        getattr(proc, "patJetPartons").particles = cms.InputTag(genParticlesLabel)  #'prunedGenParticles')
    getattr(proc, "patJetPartonMatch" + jetALGO + "PF" + PUMethod).matched = cms.InputTag(
        genParticlesLabel
    )  #'prunedGenParticles')
    if miniAOD:
        if hasattr(proc, "pfInclusiveSecondaryVertexFinderTagInfos" + jetALGO + "PF" + PUMethod):
            getattr(
                proc, "pfInclusiveSecondaryVertexFinderTagInfos" + jetALGO + "PF" + PUMethod
            ).extSVCollection = cms.InputTag(
                svLabel
            )  #'slimmedSecondaryVertices')
        getattr(proc, "patJets" + jetALGO + "PF" + PUMethod).addAssociatedTracks = cms.bool(
            False
        )  # needs to be disabled since there is no track collection present in MiniAOD
        getattr(proc, "patJets" + jetALGO + "PF" + PUMethod).addJetCharge = cms.bool(
            False
        )  # needs to be disabled since there is no track collection present in MiniAOD

        #### Grommers
    if addSoftDrop or addSoftDropSubjets:

        setattr(
            proc,
            jetalgo + "PFJets" + PUMethod + "SoftDrop",
            ak8PFJetsCHSSoftDrop.clone(
                src=cms.InputTag(jetalgo + "PFJets" + PUMethod + "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:

            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,
                btagDiscriminators=["None"],
                genJetCollection=cms.InputTag(jetalgo + "GenJetsNoNu"),
                getJetMCFlavour=GetJetMCFlavour,
                outputModules=["outputFile"],
            )

            if JEC is not None:
                getattr(proc, "patJetCorrFactors" + jetALGO + "PF" + PUMethod + "SoftDrop").primaryVertices = pvLabel
            getattr(proc, "patJetPartonMatch" + jetALGO + "PF" + PUMethod + "SoftDrop").matched = cms.InputTag(
                genParticlesLabel
            )  #'prunedGenParticles')
            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,
                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"],
            )

            if miniAOD:
                getattr(proc, "patJets" + jetALGO + "PF" + PUMethod + "SoftDropSubjets").addAssociatedTracks = cms.bool(
                    False
                )
                getattr(proc, "patJets" + jetALGO + "PF" + PUMethod + "SoftDropSubjets").addJetCharge = cms.bool(False)
                if hasattr(
                    proc, "pfInclusiveSecondaryVertexFinderTagInfos" + jetALGO + "PF" + PUMethod + "SoftDropSubjets"
                ):
                    getattr(
                        proc, "pfInclusiveSecondaryVertexFinderTagInfos" + jetALGO + "PF" + PUMethod + "SoftDropSubjets"
                    ).extSVCollection = cms.InputTag(svLabel)
            if subJEC is not None:
                getattr(
                    proc, "patJetCorrFactors" + jetALGO + "PF" + PUMethod + "SoftDropSubjets"
                ).primaryVertices = pvLabel
            getattr(proc, "patJetPartonMatch" + jetALGO + "PF" + PUMethod + "SoftDropSubjets").matched = cms.InputTag(
                genParticlesLabel
            )
            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"),
                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:
            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,
                btagDiscriminators=["None"],
                genJetCollection=cms.InputTag(jetalgo + "GenJetsNoNu"),
                getJetMCFlavour=GetJetMCFlavour,
                outputModules=["outputFile"],
            )
            if JEC is not None:
                getattr(proc, "patJetCorrFactors" + jetALGO + "PF" + PUMethod + "Pruned").primaryVertices = pvLabel
            getattr(proc, "patJetPartonMatch" + jetALGO + "PF" + PUMethod + "Pruned").matched = cms.InputTag(
                genParticlesLabel
            )
            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,
                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"],
            )

            getattr(proc, "patJetPartonMatch" + jetALGO + "PF" + PUMethod + "PrunedSubjets").matched = cms.InputTag(
                genParticlesLabel
            )
            if subJEC is not None:
                getattr(
                    proc, "patJetCorrFactors" + jetALGO + "PF" + PUMethod + "PrunedSubjets"
                ).primaryVertices = pvLabel
            if miniAOD:
                if hasattr(
                    proc, "pfInclusiveSecondaryVertexFinderTagInfos" + jetALGO + "PF" + PUMethod + "PrunedSubjets"
                ):
                    getattr(
                        proc, "pfInclusiveSecondaryVertexFinderTagInfos" + jetALGO + "PF" + PUMethod + "PrunedSubjets"
                    ).extSVCollection = cms.InputTag(svLabel)
                getattr(proc, "patJets" + jetALGO + "PF" + PUMethod + "PrunedSubjets").addAssociatedTracks = cms.bool(
                    False
                )
                getattr(proc, "patJets" + jetALGO + "PF" + PUMethod + "PrunedSubjets").addJetCharge = cms.bool(False)
            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"),
                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"),
                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"),
                        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.0),
                    TopMassMax=cms.double(250.0),
                    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=GetJetMCFlavour,
            )
            getattr(proc, "patJetPartonMatchCMSTopTag" + PUMethod).matched = cms.InputTag(genParticlesLabel)
            if hasattr(proc, "pfInclusiveSecondaryVertexFinderTagInfosCMSTopTag" + PUMethod):
                getattr(
                    proc, "pfInclusiveSecondaryVertexFinderTagInfosCMSTopTag" + PUMethod
                ).extSVCollection = cms.InputTag(svLabel)
            getattr(proc, "patJetsCMSTopTag" + PUMethod).addTagInfos = True
            getattr(proc, "patJetsCMSTopTag" + PUMethod).tagInfoSources = cms.VInputTag(cms.InputTag("CATopTagInfos"))
            if JEC is not None:
                getattr(proc, "patJetCorrFactorsCMSTopTag" + PUMethod).primaryVertices = pvLabel
            getattr(proc, "patJetsCMSTopTag" + PUMethod).addAssociatedTracks = cms.bool(False)
            getattr(proc, "patJetsCMSTopTag" + PUMethod).addJetCharge = cms.bool(False)
            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
            )

            getattr(proc, "patJetPartonMatchCMSTopTag" + PUMethod + "Subjets").matched = cms.InputTag(
                genParticlesLabel
            )  #'prunedGenParticles')
            if hasattr(proc, "pfInclusiveSecondaryVertexFinderTagInfosCMSTopTag" + PUMethod + "Subjets"):
                getattr(
                    proc, "pfInclusiveSecondaryVertexFinderTagInfosCMSTopTag" + PUMethod + "Subjets"
                ).extSVCollection = cms.InputTag(svLabel)
            if subJEC is not None:
                getattr(proc, "patJetCorrFactorsCMSTopTag" + PUMethod + "Subjets").primaryVertices = pvLabel
            getattr(proc, "patJetsCMSTopTag" + PUMethod + "Subjets").addAssociatedTracks = cms.bool(False)
            getattr(proc, "patJetsCMSTopTag" + PUMethod + "Subjets").addJetCharge = cms.bool(False)
            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")
                ),
            )
            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.0) and ("CA" in jetALGO):

            setattr(
                proc,
                "hepTopTagPFJets" + PUMethod,
                hepTopTagPFJetsCHS.clone(src=cms.InputTag(jetalgo + "PFJets" + PUMethod + "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:
        """
		#This is the old way before 731
		### 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 )
		"""
        ### This is for 731 or higher
        if "ak4" in jetalgo:
            proc.load("RecoJets.JetProducers.QGTagger_cfi")
            proc.QGTagger.srcJets = cms.InputTag(
                jetalgo + "PFJets" + PUMethod
            )  # Could be reco::PFJetCollection or pat::JetCollection (both AOD and miniAOD)
            proc.QGTagger.jetsLabel = cms.string(
                "QGL_AK4PFchs"
            )  # Other options (might need to add an ESSource for it): see https://twiki.cern.ch/twiki/bin/viewauth/CMS/QGDataBaseVersion
            elemToKeep += ["keep *_QGTagger_*_*"]
            getattr(proc, "patJets" + jetALGO + "PF" + PUMethod).userData.userFloats.src += ["QGTagger:qgLikelihood"]
            jetSeq += getattr(proc, "QGTagger")
        else:
            print "|---- jetToolBox: QGTagger is optimized for ak4 jets."

            ####### 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),
                ),
            )

            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."

    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_*"]

    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),
            ),
        )
예제 #10
0
## configure process options
process.options = cms.untracked.PSet(
    wantSummary = cms.untracked.bool(True)
)

#-------------------------------------------------
# tagAndProbeAnalysis analysis
#-------------------------------------------------

## muon selector
from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets

## produce collection of well defined jets
process.selectedJets = selectedPatJets.clone(src = 'selectedPatJets',
                                                cut = 'pt>30 & abs(eta)<3 & emEnergyFraction<0.95'
                                                )

## muon selector
from PhysicsTools.PatAlgos.selectionLayer1.muonSelector_cfi import selectedPatMuons

## as probe requirement choose standalonMuon 
process.probeMuons = selectedPatMuons.clone(src = 'selectedPatMuons',
                                               cut = 'standAloneMuon.isNull=0'
                                               )

## as test requirement choose combinedMuon 
process.testMuons = selectedPatMuons.clone(src = 'probeMuons',
                                              cut = 'combinedMuon.isNull=0'
                                              )
예제 #11
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)
예제 #12
0
def makeFatJets(process,
                src,
                algoLabel,
                jetRadius,
                colLabel,
                jetPtMin=150.,
                btagLabel=''):

    rLabel = algoLabel + '%d' % (int(jetRadius * 10))  # 'ak8'

    if algoLabel.lower() == 'ca':
        jetAlgo = 'CambridgeAachen'
    elif algoLabel.lower() == 'ak':
        jetAlgo = 'AntiKt'
    else:
        raise RuntimeError('Unknown jet algo ' + algoLabel)

    if jetRadius < 1.:
        sdZcut = 0.1
        sdBeta = 0.0
    else:
        sdZcut = 0.15
        sdBeta = 1.0

    ## Used for btagging & jet clustering (pvSource)
    ## CMS uses the particleFlow collection to compute the btag info regardless of the jet source collection.
    pfSource = 'particleFlow'
    pvSource = 'offlinePrimaryVertices'

    ########################################
    ##           CLUSTER JETS             ##
    ########################################

    jets = ak4PFJets.clone(jetAlgorithm=cms.string(jetAlgo),
                           rParam=cms.double(jetRadius),
                           src=cms.InputTag(src),
                           srcPVs=cms.InputTag(pvSource),
                           doAreaFastjet=cms.bool(True),
                           jetPtMin=cms.double(jetPtMin))

    jetsName = rLabel + colLabel  # 'ak8PFJetsCHS'
    setattr(process, jetsName, jets)

    softDropJets = jets.clone(useSoftDrop=cms.bool(True),
                              R0=cms.double(jetRadius),
                              zcut=cms.double(sdZcut),
                              beta=cms.double(sdBeta),
                              writeCompound=cms.bool(True),
                              useExplicitGhosts=cms.bool(True),
                              jetCollInstanceName=cms.string("SubJets"))

    softDropJetsName = jetsName + 'SoftDrop'
    setattr(process, softDropJetsName, softDropJets)

    softDropSubjetsName = softDropJetsName + 'Subjets'

    clustering = cms.Sequence(jets + softDropJets)

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

    njettiness = Njettiness.clone(src=cms.InputTag(jetsName),
                                  R0=cms.double(jetRadius),
                                  Njets=cms.vuint32(1, 2, 3, 4))

    njettinessName = 'njettiness' + jetsName
    setattr(process, njettinessName, njettiness)

    sdKinematics = cms.EDProducer(
        'RecoJetDeltaRValueMapProducer',
        src=cms.InputTag(jetsName),
        matched=cms.InputTag(softDropJetsName),
        distMax=cms.double(1.5),
        values=cms.vstring('mass'),
        valueLabels=cms.vstring('Mass'),
    )

    sdKinematicsName = 'sdKinematics' + jetsName
    setattr(process, sdKinematicsName, sdKinematics)

    substructure = cms.Sequence(njettiness + sdKinematics)

    if btagLabel != '':
        #######################################
        ##         FATJET BTAGGING           ##
        #######################################

        initBTag(process, btagLabel, pfSource, pvSource)

        btags = [
            'pfJetProbabilityBJetTags', 'pfJetBProbabilityBJetTags',
            'pfCombinedSecondaryVertexV2BJetTags',
            'pfCombinedInclusiveSecondaryVertexV2BJetTags',
            'pfCombinedMVAV2BJetTags'
        ]

        btagInfos = []
        btagging = setupBTag(process,
                             jetsName,
                             jetsName,
                             btagLabel,
                             tags=btags,
                             addedTagInfos=btagInfos)

        doubleBtags = ['pfBoostedDoubleSecondaryVertexBJetTags']

        doubleBtagging = setupDoubleBTag(process,
                                         jetsName,
                                         jetsName,
                                         btagLabel,
                                         rLabel.lower(),
                                         addedTagInfos=btagInfos)

        #######################################
        ##         SUBJET BTAGGING           ##
        #######################################

        # Product: std::vector<reco::CandIPTagInfo>
        # IPTagInfo object contains a reference to jet
        subjetIpTagInfos = btag.pfImpactParameterTagInfos.clone(
            jets=cms.InputTag(softDropJetsName, 'SubJets'),
            primaryVertex=cms.InputTag(pvSource),
            candidates=cms.InputTag(pfSource),
            #      explicitJTA = cms.bool(True)
        )

        subjetIpTagInfosName = 'pfImpactParameterTagInfos' + softDropSubjetsName
        setattr(process, subjetIpTagInfosName, subjetIpTagInfos)

        # Product: std::vector<TemplatedSecondaryVertexTagInfo<reco::CandIPTagInfo, reco::VertexCompositePtrCandidate>>
        subjetInclSVFinderTagInfos = btag.pfInclusiveSecondaryVertexFinderTagInfos.clone(
            trackIPTagInfos=cms.InputTag(subjetIpTagInfosName),
            extSVCollection=cms.InputTag(
                'inclusiveCandidateSecondaryVertices' + btagLabel),
            #      useSVClustering = cms.bool(True),
            #      jetAlgorithm = cms.string(jetAlgo),
            #      rParam = cms.double(jetRadius),
            #      fatJets = cms.InputTag(jetsName),
            #      groomedFatJets = cms.InputTag(softDropJetsName)
        )

        subjetInclSVFinderTagInfosName = 'pfInclusiveSecondaryVertexFinderTagInfos' + softDropSubjetsName
        setattr(process, subjetInclSVFinderTagInfosName,
                subjetInclSVFinderTagInfos)

        # Product: JetTagCollection (aka reco::JetFloatAssociation::Container aka edm::AssociationVector<reco::JetRefBaseProd, std::vector<float>>)
        # Uses the internal reference to the jet in the TagInfos object to create an AssociationVector
        subjetBjetTags = btag.pfCombinedInclusiveSecondaryVertexV2BJetTags.clone(
            tagInfos=cms.VInputTag(
                cms.InputTag(subjetIpTagInfosName),
                cms.InputTag(subjetInclSVFinderTagInfosName)))

        subjetBjetTagsName = 'pfCombinedInclusiveSecondaryVertexV2BJetTags' + softDropSubjetsName
        setattr(process, subjetBjetTagsName, subjetBjetTags)

        subjetBTagging = cms.Sequence(subjetIpTagInfos +
                                      subjetInclSVFinderTagInfos +
                                      subjetBjetTags)

    else:
        btagging = cms.Sequence()
        doubleBtagging = cms.Sequence()
        subjetBTagging = cms.Sequence()

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

    patJets = _patJets.clone(jetSource=cms.InputTag(jetsName),
                             getJetMCFlavour=cms.bool(False),
                             addGenJetMatch=cms.bool(False),
                             addGenPartonMatch=cms.bool(False),
                             addJetFlavourInfo=cms.bool(False),
                             addAssociatedTracks=cms.bool(False),
                             addJetCharge=cms.bool(False),
                             addJetCorrFactors=cms.bool(False),
                             addBTagInfo=cms.bool(True),
                             addTagInfos=cms.bool(True),
                             addDiscriminators=cms.bool(True),
                             tagInfoSources=cms.VInputTag(
                                 [cms.InputTag(name) for name in btagInfos]),
                             discriminatorSources=cms.VInputTag([
                                 cms.InputTag(name + jetsName)
                                 for name in btags + doubleBtags
                             ]))
    patJets.userData.userFloats.src = [
        cms.InputTag(njettinessName + ':tau1'),
        cms.InputTag(njettinessName + ':tau2'),
        cms.InputTag(njettinessName + ':tau3'),
        cms.InputTag(njettinessName + ':tau4'),
        cms.InputTag(sdKinematicsName + ':Mass')
    ]

    patJetsName = 'pat' + jetsName
    setattr(process, patJetsName, patJets)

    selectedJets = selectedPatJets.clone(src=cms.InputTag(patJetsName))

    selectedJetsName = 'selectedPat' + jetsName
    setattr(process, selectedJetsName, selectedJets)

    patSoftDropJets = _patJets.clone(jetSource=cms.InputTag(softDropJetsName),
                                     getJetMCFlavour=cms.bool(False),
                                     addGenJetMatch=cms.bool(False),
                                     addGenPartonMatch=cms.bool(False),
                                     addJetFlavourInfo=cms.bool(False),
                                     addTagInfos=cms.bool(False),
                                     addBTagInfo=cms.bool(False),
                                     addDiscriminators=cms.bool(False),
                                     addAssociatedTracks=cms.bool(False),
                                     addJetCharge=cms.bool(False),
                                     addJetCorrFactors=cms.bool(False))

    patSoftDropJetsName = 'pat' + softDropJetsName
    setattr(process, patSoftDropJetsName, patSoftDropJets)

    selectedSoftDropJets = selectedPatJets.clone(
        src=cms.InputTag(patSoftDropJetsName))

    selectedSoftDropJetsName = 'selectedPat' + softDropJetsName
    setattr(process, selectedSoftDropJetsName, selectedSoftDropJets)

    patSoftDropSubjets = _patJets.clone(
        jetSource=cms.InputTag(softDropJetsName, 'SubJets'),
        getJetMCFlavour=cms.bool(False),
        addGenJetMatch=cms.bool(False),
        addGenPartonMatch=cms.bool(False),
        addJetFlavourInfo=cms.bool(False),
        addAssociatedTracks=cms.bool(False),
        addJetCharge=cms.bool(False),
        addJetCorrFactors=cms.bool(False),
        addBTagInfo=cms.bool(True),
        addDiscriminators=cms.bool(True),
        addTagInfos=cms.bool(False),
        discriminatorSources=cms.VInputTag(cms.InputTag(subjetBjetTagsName)))

    patSoftDropSubjetsName = 'pat' + softDropJetsName + 'Subjets'
    setattr(process, patSoftDropSubjetsName, patSoftDropSubjets)

    selectedSoftDropSubjets = selectedPatJets.clone(
        src=cms.InputTag(patSoftDropSubjetsName))

    selectedSoftDropSubjetsName = 'selectedPat' + softDropSubjetsName
    setattr(process, selectedSoftDropSubjetsName, selectedSoftDropSubjets)

    pat = cms.Sequence(patJets + selectedJets + patSoftDropJets +
                       selectedSoftDropJets + patSoftDropSubjets +
                       selectedSoftDropSubjets)

    ###############################################
    ##     Pack subjets back into fat jets       ##
    ###############################################

    packedSoftDropJets = cms.EDProducer(
        'BoostedJetMerger',
        jetSrc=cms.InputTag(selectedSoftDropJetsName),
        subjetSrc=cms.InputTag(selectedSoftDropSubjetsName))

    packedSoftDropJetsName = 'packed' + softDropJetsName
    setattr(process, packedSoftDropJetsName, packedSoftDropJets)

    packedPatJets = cms.EDProducer('JetSubstructurePacker',
                                   jetSrc=cms.InputTag(selectedJetsName),
                                   distMax=cms.double(jetRadius),
                                   algoTags=cms.VInputTag(
                                       cms.InputTag(packedSoftDropJetsName)),
                                   algoLabels=cms.vstring('SoftDrop'),
                                   fixDaughters=cms.bool(False))

    packedPatJetsName = 'packed' + jetsName
    setattr(process, packedPatJetsName, packedPatJets)

    packing = cms.Sequence(packedSoftDropJets + packedPatJets)

    ##############################
    ##     Return a sequence    ##
    ##############################

    sequence = cms.Sequence(clustering + substructure + btagging +
                            doubleBtagging + subjetBTagging + pat + packing)

    return sequence
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)
예제 #14
0
def makeFatJets(process, src, algoLabel, jetRadius, colLabel, jetPtMin = 150., btagLabel = ''):

  rLabel = algoLabel + '%d' % (int(jetRadius * 10)) # 'ak8'

  if algoLabel.lower() == 'ca':
    jetAlgo = 'CambridgeAachen'
  elif algoLabel.lower() == 'ak':
    jetAlgo = 'AntiKt'
  else:
    raise RuntimeError('Unknown jet algo ' + algoLabel)

  if jetRadius < 1.:
    sdZcut = 0.1
    sdBeta = 0.0
  else:
    sdZcut = 0.15
    sdBeta = 1.0

  ## Used for btagging & jet clustering (pvSource)
  ## CMS uses the particleFlow collection to compute the btag info regardless of the jet source collection.
  pfSource = 'particleFlow'
  pvSource = 'offlinePrimaryVertices'

  ########################################
  ##           CLUSTER JETS             ##
  ########################################

  jets = ak4PFJets.clone(
    jetAlgorithm = cms.string(jetAlgo),
    rParam = cms.double(jetRadius),
    src = cms.InputTag(src),
    srcPVs = cms.InputTag(pvSource),
    doAreaFastjet = cms.bool(True),
    jetPtMin = cms.double(jetPtMin)
  )

  jetsName = rLabel + colLabel # 'ak8PFJetsCHS'
  setattr(process, jetsName, jets)

  softDropJets = jets.clone(
    useSoftDrop = cms.bool(True),
    R0 = cms.double(jetRadius),
    zcut = cms.double(sdZcut),
    beta = cms.double(sdBeta),
    writeCompound = cms.bool(True),
    useExplicitGhosts = cms.bool(True),
    jetCollInstanceName = cms.string("SubJets")
  )

  softDropJetsName = jetsName + 'SoftDrop'
  setattr(process, softDropJetsName, softDropJets)

  softDropSubjetsName = softDropJetsName + 'Subjets'

  clustering = cms.Sequence(
    jets +
    softDropJets
  )
  
  ########################################
  ##           SUBSTRUCTURE             ##
  ########################################

  njettiness = Njettiness.clone(
    src = cms.InputTag(jetsName),
    R0 = cms.double(jetRadius),
    Njets = cms.vuint32(1,2,3,4)
  )

  njettinessName = 'njettiness' + jetsName
  setattr(process, njettinessName, njettiness)

  sdKinematics = cms.EDProducer('RecoJetDeltaRValueMapProducer',
    src = cms.InputTag(jetsName),
    matched = cms.InputTag(softDropJetsName),
    distMax = cms.double(1.5),
    values = cms.vstring('mass'),
    valueLabels = cms.vstring('Mass'),
  )

  sdKinematicsName = 'sdKinematics' + jetsName
  setattr(process, sdKinematicsName, sdKinematics)

  substructure = cms.Sequence(
    njettiness +
    sdKinematics
  )

  if btagLabel != '':
    #######################################
    ##         FATJET BTAGGING           ##
    #######################################

    initBTag(process, btagLabel, pfSource, pvSource)
  
    btags = [
      'pfJetProbabilityBJetTags',
      'pfJetBProbabilityBJetTags',
      'pfCombinedSecondaryVertexV2BJetTags',
      'pfCombinedInclusiveSecondaryVertexV2BJetTags',
      'pfCombinedMVAV2BJetTags'
    ]
  
    btagInfos = []
    btagging = setupBTag(process, jetsName, jetsName, btagLabel, tags = btags, addedTagInfos = btagInfos)

    doubleBtags = [
      'pfBoostedDoubleSecondaryVertexBJetTags'
    ]
    
    doubleBtagging = setupDoubleBTag(process, jetsName, jetsName, btagLabel, rLabel.lower(), addedTagInfos = btagInfos)

    #######################################
    ##         SUBJET BTAGGING           ##
    #######################################
  
    # Product: std::vector<reco::CandIPTagInfo>
    # IPTagInfo object contains a reference to jet
    subjetIpTagInfos = btag.pfImpactParameterTagInfos.clone(
      jets = cms.InputTag(softDropJetsName, 'SubJets'),
      primaryVertex = cms.InputTag(pvSource),
      candidates = cms.InputTag(pfSource),
#      explicitJTA = cms.bool(True)
    )
  
    subjetIpTagInfosName = 'pfImpactParameterTagInfos' + softDropSubjetsName
    setattr(process, subjetIpTagInfosName, subjetIpTagInfos)
  
    # Product: std::vector<TemplatedSecondaryVertexTagInfo<reco::CandIPTagInfo, reco::VertexCompositePtrCandidate>>
    subjetInclSVFinderTagInfos = btag.pfInclusiveSecondaryVertexFinderTagInfos.clone(
      trackIPTagInfos = cms.InputTag(subjetIpTagInfosName),
      extSVCollection = cms.InputTag('inclusiveCandidateSecondaryVertices' + btagLabel),
#      useSVClustering = cms.bool(True),
#      jetAlgorithm = cms.string(jetAlgo),
#      rParam = cms.double(jetRadius),
#      fatJets = cms.InputTag(jetsName),
#      groomedFatJets = cms.InputTag(softDropJetsName)
    )
  
    subjetInclSVFinderTagInfosName = 'pfInclusiveSecondaryVertexFinderTagInfos' + softDropSubjetsName
    setattr(process, subjetInclSVFinderTagInfosName, subjetInclSVFinderTagInfos)
  
    # Product: JetTagCollection (aka reco::JetFloatAssociation::Container aka edm::AssociationVector<reco::JetRefBaseProd, std::vector<float>>)
    # Uses the internal reference to the jet in the TagInfos object to create an AssociationVector
    subjetBjetTags = btag.pfCombinedInclusiveSecondaryVertexV2BJetTags.clone(
      tagInfos = cms.VInputTag( 
        cms.InputTag(subjetIpTagInfosName), 
        cms.InputTag(subjetInclSVFinderTagInfosName)
      )
    )
  
    subjetBjetTagsName = 'pfCombinedInclusiveSecondaryVertexV2BJetTags' + softDropSubjetsName
    setattr(process, subjetBjetTagsName, subjetBjetTags)
  
    subjetBTagging = cms.Sequence(
      subjetIpTagInfos +
      subjetInclSVFinderTagInfos +
      subjetBjetTags
    )

  else:
    btagging = cms.Sequence()
    doubleBtagging = cms.Sequence()
    subjetBTagging = cms.Sequence()

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

  patJets = _patJets.clone(
    jetSource = cms.InputTag(jetsName),
    getJetMCFlavour = cms.bool(False),
    addGenJetMatch = cms.bool(False),
    addGenPartonMatch = cms.bool(False),
    addJetFlavourInfo = cms.bool(False),
    addAssociatedTracks = cms.bool(False),
    addJetCharge = cms.bool(False),
    addJetCorrFactors = cms.bool(False),
    addBTagInfo = cms.bool(True),
    addTagInfos = cms.bool(True),
    addDiscriminators = cms.bool(True),
    tagInfoSources = cms.VInputTag([cms.InputTag(name) for name in btagInfos]),
    discriminatorSources = cms.VInputTag([cms.InputTag(name + jetsName) for name in btags + doubleBtags])
  )
  patJets.userData.userFloats.src = [
    cms.InputTag(njettinessName + ':tau1'),
    cms.InputTag(njettinessName + ':tau2'),
    cms.InputTag(njettinessName + ':tau3'),
    cms.InputTag(njettinessName + ':tau4'),
    cms.InputTag(sdKinematicsName + ':Mass')
  ]

  patJetsName = 'pat' + jetsName
  setattr(process, patJetsName, patJets)

  selectedJets = selectedPatJets.clone(
    src = cms.InputTag(patJetsName)
  )

  selectedJetsName = 'selectedPat' + jetsName
  setattr(process, selectedJetsName, selectedJets)

  patSoftDropJets = _patJets.clone(
    jetSource = cms.InputTag(softDropJetsName),
    getJetMCFlavour = cms.bool(False),
    addGenJetMatch = cms.bool(False),
    addGenPartonMatch = cms.bool(False),
    addJetFlavourInfo = cms.bool(False),
    addTagInfos = cms.bool(False),
    addBTagInfo = cms.bool(False),
    addDiscriminators = cms.bool(False),
    addAssociatedTracks = cms.bool(False),
    addJetCharge = cms.bool(False),
    addJetCorrFactors = cms.bool(False)
  )

  patSoftDropJetsName = 'pat' + softDropJetsName
  setattr(process, patSoftDropJetsName, patSoftDropJets)

  selectedSoftDropJets = selectedPatJets.clone(
    src = cms.InputTag(patSoftDropJetsName)
  )

  selectedSoftDropJetsName = 'selectedPat' + softDropJetsName
  setattr(process, selectedSoftDropJetsName, selectedSoftDropJets)

  patSoftDropSubjets = _patJets.clone(
    jetSource = cms.InputTag(softDropJetsName, 'SubJets'),
    getJetMCFlavour = cms.bool(False),
    addGenJetMatch = cms.bool(False),
    addGenPartonMatch = cms.bool(False),
    addJetFlavourInfo = cms.bool(False),
    addAssociatedTracks = cms.bool(False),
    addJetCharge = cms.bool(False),
    addJetCorrFactors = cms.bool(False),
    addBTagInfo = cms.bool(True),
    addDiscriminators = cms.bool(True),
    addTagInfos = cms.bool(False),
    discriminatorSources = cms.VInputTag(
      cms.InputTag(subjetBjetTagsName)
    )
  )

  patSoftDropSubjetsName = 'pat' + softDropJetsName + 'Subjets'
  setattr(process, patSoftDropSubjetsName, patSoftDropSubjets)

  selectedSoftDropSubjets = selectedPatJets.clone(
    src = cms.InputTag(patSoftDropSubjetsName)
  )

  selectedSoftDropSubjetsName = 'selectedPat' + softDropSubjetsName
  setattr(process, selectedSoftDropSubjetsName, selectedSoftDropSubjets)

  pat = cms.Sequence(
    patJets +
    selectedJets +
    patSoftDropJets +
    selectedSoftDropJets +
    patSoftDropSubjets +
    selectedSoftDropSubjets
  )

  ###############################################
  ##     Pack subjets back into fat jets       ##
  ###############################################

  packedSoftDropJets = cms.EDProducer('BoostedJetMerger',
    jetSrc = cms.InputTag(selectedSoftDropJetsName),
    subjetSrc = cms.InputTag(selectedSoftDropSubjetsName)
  )

  packedSoftDropJetsName = 'packed' + softDropJetsName
  setattr(process, packedSoftDropJetsName, packedSoftDropJets)

  packedPatJets = cms.EDProducer('JetSubstructurePacker',
    jetSrc = cms.InputTag(selectedJetsName),
    distMax = cms.double(jetRadius),
    algoTags = cms.VInputTag(cms.InputTag(packedSoftDropJetsName)),
    algoLabels = cms.vstring('SoftDrop'),
    fixDaughters = cms.bool(False)
  )

  packedPatJetsName = 'packed' + jetsName
  setattr(process, packedPatJetsName, packedPatJets)

  packing = cms.Sequence(
    packedSoftDropJets +
    packedPatJets
  )

  ##############################
  ##     Return a sequence    ##
  ##############################

  sequence = cms.Sequence(
    clustering + 
    substructure +
    btagging +
    doubleBtagging +
    subjetBTagging +
    pat +
    packing
  )

  return sequence
예제 #15
0
import FWCore.ParameterSet.Config as cms

#______________________ Event-Selection _____________________________

from HLTrigger.HLTfilters.hltHighLevel_cfi import hltHighLevel
hltFilter = hltHighLevel.clone(
    andOr = True, ## choose logical OR between Triggerbits
    HLTPaths = ['HLT_ZeroBias'],
    throw = False # tolerate triggers stated above, but not available
    )

#______________________ Object-Selection ____________________________

from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets
from PhysicsTools.PatAlgos.selectionLayer1.electronSelector_cfi import selectedPatElectrons
from PhysicsTools.PatAlgos.selectionLayer1.muonSelector_cfi import selectedPatMuons
from PhysicsTools.PatAlgos.selectionLayer1.tauSelector_cfi import selectedPatTaus

patJetSelector = selectedPatJets.clone( filter = cms.bool(False), src = "", cut = "")
patElectronSelector = selectedPatElectrons.clone( filter = cms.bool(False), src = "", cut = "")
patMuonSelector = selectedPatMuons.clone( filter = cms.bool(False), src = "", cut = "")
patTauSelector = selectedPatTaus.clone( filter = cms.bool(False), src = "", cut = "")

candStringSelector = cms.EDFilter("CandViewSelector",
    filter = cms.bool(False),
    src = cms.InputTag(""),
    cut = cms.string("")
)


예제 #16
0
파일: step3.py 프로젝트: latinos/WWAnalysis
def addFatJet(process):
    from RecoJets.JetProducers.ak5PFJets_cfi import ak5PFJets
    process.ca8PFJetsCHS = ak5PFJets.clone(
        src='pfNoPileUp',
        jetPtMin=cms.double(10.0),
        doAreaFastjet=cms.bool(True),
        rParam=cms.double(0.8),
        jetAlgorithm=cms.string("CambridgeAachen"),
    )

    jetSource = 'ca8PFJetsCHS'

    # corrections
    from PhysicsTools.PatAlgos.recoLayer0.jetCorrFactors_cfi import patJetCorrFactors
    process.patJetCorrFactorsCA8CHS = patJetCorrFactors.clone()
    process.patJetCorrFactorsCA8CHS.src = jetSource
    # will need to add L2L3 corrections in the cfg
    process.patJetCorrFactorsCA8CHS.levels = [
        'L1FastJet', 'L2Relative', 'L3Absolute'
    ]
    process.patJetCorrFactorsCA8CHS.payload = 'AK7PFchs'
    process.patJetCorrFactorsCA8CHS.useRho = True

    # pat jet
    from PhysicsTools.PatAlgos.producersLayer1.jetProducer_cfi import patJets
    process.patJetsCA8CHS = patJets.clone()
    process.patJetsCA8CHS.jetSource = jetSource
    process.patJetsCA8CHS.addJetCharge = False
    process.patJetsCA8CHS.embedCaloTowers = False
    process.patJetsCA8CHS.embedPFCandidates = False
    process.patJetsCA8CHS.addAssociatedTracks = False
    process.patJetsCA8CHS.addBTagInfo = False
    process.patJetsCA8CHS.addDiscriminators = False
    process.patJetsCA8CHS.getJetMCFlavour = False
    process.patJetsCA8CHS.jetCorrFactorsSource = cms.VInputTag(
        cms.InputTag('patJetCorrFactorsCA8CHS'))
    process.patJetsCA8CHS.genPartonMatch = cms.InputTag(
        'patJetPartonMatchCA8CHS')
    process.patJetsCA8CHS.genJetMatch = cms.InputTag('patJetGenJetMatchCA8CHS')

    from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets
    process.selectedPatJetsCA8CHS = selectedPatJets.clone()
    process.selectedPatJetsCA8CHS.src = 'patJetsCA8CHS'
    process.selectedPatJetsCA8CHS.cut = 'pt()>20'

    #process.jetMCSequenceCA8CHS = cms.Sequence(
    #process.patJetPartonMatchCA8CHS +
    #process.genParticlesForJetsNoNu +
    #process.ca8GenJetsNoNu +
    #process.patJetGenJetMatchCA8CHS
    #)

    process.PATJetSequenceCA8CHS = cms.Sequence(
        process.ca8PFJetsCHS +
        #process.jetMCSequenceCA8CHS +
        process.patJetCorrFactorsCA8CHS
        #process.patJetsCA8CHS +
        #process.selectedPatJetsCA8CHS
    )

    process.PATJetPathCA8CHS = cms.Path(process.PATJetSequenceCA8CHS)
예제 #17
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
예제 #18
0
def jetToolbox( proc, jetType, jetSequence, outputFile, 
		PUMethod='CHS',                    #### Options: Puppi, CS, SK, Plain
		JETCorrPayload='None', JETCorrLevels = [ 'None' ],
		subJETCorrPayload='None', subJETCorrLevels = [ 'None' ],
		miniAOD=True,
		Cut = '', 
		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, 
		addQJets=False 
		):
	
	###############################################################################
	#######  Verifying some inputs and defining variables
	###############################################################################
	print '|---- jetToolbox: Initialyzing...'
	supportedJetAlgos = { 'ak': 'AntiKt', 'ca' : 'CambridgeAachen', 'kt' : 'Kt' }
	recommendedJetAlgos = [ 'ak4', 'ak8', 'ca4', 'ca8', 'ca10' ]
	payloadList = [ 'AK1PFchs', 'AK2PFchs', 'AK3PFchs', 'AK4PFchs', 'AK5PFchs', 'AK6PFchs', 'AK7PFchs', 'AK8PFchs', 'AK9PFchs', 'AK10PFchs' ]
	JECLevels = [ 'L1Offset', 'L1FastJet', 'L1JPTOffset', 'L2Relative', 'L3Absolute', 'L5Falvour', 'L7Parton' ]
	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,'.'

	if JETCorrPayload not in payloadList:
		if( int(size) > 10 ): 
			size = '10' 
			print '|---- jetToolbox: For jets bigger than 1.0, the jet corrections are AK10PFchs.'
		if not 'None' in JETCorrPayload: print '|---- jetToolBox: Payload given for Jet corrections ('+JETCorrPayload+') is not correct. Using a default AK'+size+'PFchs instead.'
		JETCorrPayload = 'AK'+size+'PFchs'
	else: print '|---- jetToolBox: Using '+JETCorrPayload+' payload for jet corrections.'

	if not set(JETCorrLevels).issubset(set(JECLevels)) :
		if not 'None' in JETCorrLevels: print '|---- jetToolbox: JEC levels given ( '+' '.join(JETCorrLevels)+' ) are incorrect. Using the default levels: L1FastJet, L2Relative, L3Absolute.'
		JETCorrLevels = ['L1FastJet', 'L2Relative', 'L3Absolute']
	
	print '|---- jetToolBox: Applying these jet corrections: ( '+JETCorrPayload+', '+' '.join(JETCorrLevels)+' )'
	JEC = ( JETCorrPayload, JETCorrLevels , 'None')

	if addPrunedSubjets or addSoftDropSubjets or addCMSTopTagger:
		if subJETCorrPayload not in payloadList: 
			if not 'None' in subJETCorrPayload: print '|---- jetToolBox: Payload given for subjet corrections ('+JETCorrPayload+') is not correct. Using default AK4PFchs instead.'
			subJETCorrPayload = 'AK4PFchs'
		if not set(subJETCorrLevels).issubset(set(JECLevels)) or not subJETCorrLevels:
			if not 'None' in subJETCorrLevels: print '|---- jetToolbox: Subjet JEC levels given ( '+' '.join(subJETCorrLevels)+' ) are incorrect. Using the default levels: L1FastJet, L2Relative, L3Absolute.'
			subJETCorrLevels = ['L1FastJet', 'L2Relative', 'L3Absolute']
		print '|---- jetToolBox: Applying these subjet corrections: ( '+subJETCorrPayload+', '+' '.join(subJETCorrLevels)+' )'
		subJEC = ( subJETCorrPayload, subJETCorrLevels , 'None')


	#################################################################################
	####### 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 = 'packedPFCandidates'

		setattr( proc, 'chs', cms.EDFilter('CandPtrSelector', src = cms.InputTag('packedPFCandidates'), cut = cms.string('fromPV')) )
		jetSeq += getattr(proc, 'chs')


		## 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' )
		#fixedGridRhoFastjetAll.pfCandidatesTag = 'packedPFCandidates'

		#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 = 'particleFlow'
		svLabel = 'inclusiveSecondaryVertices'

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

	## b-tag discriminators
	bTagDiscriminators = [
			'pfTrackCountingHighEffBJetTags',
			'pfTrackCountingHighPurBJetTags',
			'pfJetProbabilityBJetTags',
			'pfJetBProbabilityBJetTags',
			'pfSimpleSecondaryVertexHighEffBJetTags',
			'pfSimpleSecondaryVertexHighPurBJetTags',
			'pfCombinedSecondaryVertexBJetTags',
			'pfCombinedInclusiveSecondaryVertexV2BJetTags'
	    ]

	####  Creating PATjets
	if 'Puppi' in PUMethod:

		proc.load('CommonTools.PileupAlgos.Puppi_cff')
		from RecoJets.JetProducers.ak4PFJetsPuppi_cfi import ak4PFJetsPuppi
		setattr( proc, jetalgo+'PFJetsPuppi', 
				ak4PFJetsPuppi.clone( doAreaFastjet = True, 
					rParam = jetSize, 
					jetAlgorithm = algorithm ) )  
		if miniAOD:
			puppi.candName = cms.InputTag('packedPFCandidates')
			puppi.vertexName = cms.InputTag('offlineSlimmedPrimaryVertices')
		jetSeq += getattr(proc, 'puppi' )
		jetSeq += getattr(proc, jetalgo+'PFJetsPuppi' )

	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 = 'chs'
		jetSeq += getattr(proc, jetalgo+'PFJetsCS' )

		#setattr( proc, jetalgo+'PFJetsCSConstituents', ak8PFJetsCSConstituents.clone( src = cms.InputTag(jetalgo+'PFJetsCS') ) )
		jetSeq += getattr(proc, jetalgo+'PFJetsCS' )

	elif 'SK' in PUMethod:

		proc.load('CommonTools.PileupAlgos.softKiller_cfi')
		from RecoJets.JetProducers.ak4PFJetsSK_cfi import ak4PFJetsSK
		setattr( proc, jetalgo+'PFJetsSK', 
				ak4PFJetsSK.clone( rParam = jetSize, 
					jetAlgorithm = algorithm ) ) 
		if miniAOD: getattr( proc, 'softKiller' ).PFCandidates = cms.InputTag('packedPFCandidates')
		jetSeq += getattr(proc, 'softKiller' )
		jetSeq += getattr(proc, jetalgo+'PFJetsSK' )
	
	elif 'CHS' in PUMethod: 
		setattr( proc, jetalgo+'PFJetsCHS', 
				ak4PFJetsCHS.clone( 
					doAreaFastjet = True, 
					rParam = jetSize, 
					jetAlgorithm = algorithm ) ) 
		if miniAOD: getattr( proc, jetalgo+'PFJetsCHS').src = 'chs'
		jetSeq += getattr(proc, jetalgo+'PFJetsCHS' )
	else: 
		PUMethod = ''
		setattr( proc, jetalgo+'PFJets', 
				ak4PFJets.clone( 
					doAreaFastjet = True, 
					rParam = jetSize, 
					jetAlgorithm = algorithm ) ) 
		if miniAOD: getattr( proc, jetalgo+'PFJets').src = 'packedPFCandidates'
		jetSeq += getattr(proc, jetalgo+'PFJets' )

	#if miniAOD: setattr( proc, jetalgo+'PFJets'+PUMethod+'Constituents', cms.EDFilter("MiniAODJetConstituentSelector", src = cms.InputTag( jetalgo+'PFJets'+PUMethod ), cut = cms.string( 'pt > 100.0 ' ) ))
	#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, #( 'AK'+size+'PFchs', cms.vstring( ['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
			pfCandidates = cms.InputTag( pfCand ),  #'packedPFCandidates'),
			svSource = cms.InputTag( svLabel ),   #'slimmedSecondaryVertices'),
			genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNu'),
			pvSource = cms.InputTag( pvLabel ), #'offlineSlimmedPrimaryVertices'),
			btagDiscriminators = bTagDiscriminators,
			outputModules = ['outputFile']
			) 

	getattr( proc, 'patJetCorrFactors'+jetALGO+'PF'+PUMethod ).primaryVertices = pvLabel  #'offlineSlimmedPrimaryVertices' 
	getattr( proc, 'jetTracksAssociatorAtVertex'+jetALGO+'PF'+PUMethod ).tracks = tvLabel  # 'unpackedTracksAndVertices'

	if 'CS' in PUMethod: getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod ).getJetMCFlavour = False  
	else: getattr(proc,'patJetPartons').particles = cms.InputTag( genParticlesLabel ) #'prunedGenParticles')
	getattr(proc,'patJetPartonMatch'+jetALGO+'PF'+PUMethod).matched = cms.InputTag( genParticlesLabel ) #'prunedGenParticles')
	if miniAOD:
		if hasattr(proc,'pfInclusiveSecondaryVertexFinderTagInfos'+jetALGO+'PF'+PUMethod):
			    getattr(proc,'pfInclusiveSecondaryVertexFinderTagInfos'+jetALGO+'PF'+PUMethod).extSVCollection = cms.InputTag( svLabel ) #'slimmedSecondaryVertices')
		getattr(proc,'patJets'+jetALGO+'PF'+PUMethod).addAssociatedTracks = cms.bool(False) # needs to be disabled since there is no track collection present in MiniAOD
		getattr(proc,'patJets'+jetALGO+'PF'+PUMethod).addJetCharge = cms.bool(False)        # needs to be disabled since there is no track collection present in MiniAOD
	

	if addSoftDrop or addSoftDropSubjets: 

		setattr( proc, jetalgo+'PFJets'+PUMethod+'SoftDrop', 
			ak8PFJetsCHSSoftDrop.clone( 
				rParam = jetSize, 
				jetAlgorithm = algorithm, 
				useExplicitGhosts=True,
				zcut=zCutSD, 
				beta=betaCut,
				writeCompound = cms.bool(True),
				jetCollInstanceName=cms.string('SubJets') ) )
		if miniAOD: getattr( proc, jetalgo+'PFJets'+PUMethod+'SoftDrop').src = 'chs'
		setattr( proc, jetalgo+'PFJets'+PUMethod+'SoftDropLinks', 
			ak8PFJetsCHSSoftDropLinks.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
				matched = cms.InputTag( jetalgo+'PFJets'+PUMethod+'SoftDrop'), 
				distMax = cms.double( jetSize ) ) )

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

		if addSoftDropSubjets:

			setattr( proc, jetalgo+'GenJetsNoNuSoftDrop',
					ak4GenJets.clone(
						SubJetParameters,
						useSoftDrop = cms.bool(True),
						rParam = jetSize, 
						jetAlgorithm = algorithm, 
						useExplicitGhosts=cms.bool(True),
						#zcut=cms.double(zCutSD), 
						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,
					btagDiscriminators = ['None'],
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNu'),
					getJetMCFlavour = False,
					outputModules = ['outputFile']
					) 
			getattr( proc, 'patJetCorrFactors'+jetALGO+'PF'+PUMethod+'SoftDrop' ).primaryVertices = pvLabel  #'offlineSlimmedPrimaryVertices' 
			getattr(proc,'patJetPartonMatch'+jetALGO+'PF'+PUMethod+'SoftDrop').matched = cms.InputTag( genParticlesLabel ) #'prunedGenParticles')
			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, 
					pfCandidates = cms.InputTag( pfCand ), 
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ),  
					btagDiscriminators = bTagDiscriminators,
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNuSoftDrop','SubJets'),
					getJetMCFlavour = False,
					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']
					) 

			if miniAOD:
				getattr( proc,'patJets'+jetALGO+'PF'+PUMethod+'SoftDropSubjets').addAssociatedTracks = cms.bool(False) 
				getattr( proc,'patJets'+jetALGO+'PF'+PUMethod+'SoftDropSubjets').addJetCharge = cms.bool(False) 
				if hasattr(proc,'pfInclusiveSecondaryVertexFinderTagInfos'+jetALGO+'PF'+PUMethod+'SoftDropSubjets'):
					    getattr(proc,'pfInclusiveSecondaryVertexFinderTagInfos'+jetALGO+'PF'+PUMethod+'SoftDropSubjets').extSVCollection = cms.InputTag( svLabel ) 
			getattr(proc,'patJetCorrFactors'+jetALGO+'PF'+PUMethod+'SoftDropSubjets' ).primaryVertices = pvLabel 
			getattr(proc,'patJetPartonMatch'+jetALGO+'PF'+PUMethod+'SoftDropSubjets').matched = cms.InputTag( genParticlesLabel ) 
			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( 
				rParam = jetSize, 
				jetAlgorithm = algorithm, 
				zcut=zCut, 
				rcut_factor=rCut,
				writeCompound = cms.bool(True),
				doAreaFastjet = cms.bool(True),
				jetCollInstanceName=cms.string('SubJets') ) )
		if miniAOD: getattr( proc, jetalgo+'PFJets'+PUMethod+'Pruned').src = 'chs'
		setattr( proc, jetalgo+'PFJets'+PUMethod+'PrunedLinks', 
			ak8PFJetsCHSPrunedLinks.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+'PrunedLinks' )
		getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'PrunedLinks']
		elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'PrunedLinks_*_*'] 
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'PrunedLinks' )

		if addPrunedSubjets:
			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,
					btagDiscriminators = ['None'],
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNu'),
					getJetMCFlavour = False,
					outputModules = ['outputFile']
					) 
			getattr( proc, 'patJetCorrFactors'+jetALGO+'PF'+PUMethod+'Pruned' ).primaryVertices = pvLabel  
			getattr(proc,'patJetPartonMatch'+jetALGO+'PF'+PUMethod+'Pruned').matched = cms.InputTag( genParticlesLabel ) 
			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,
					pfCandidates = cms.InputTag( pfCand ),  
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ), 
					btagDiscriminators = bTagDiscriminators,
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNuPruned','SubJets'),
					getJetMCFlavour = False,
					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']
					) 

			getattr(proc,'patJetPartonMatch'+jetALGO+'PF'+PUMethod+'PrunedSubjets').matched = cms.InputTag( genParticlesLabel ) 
			getattr(proc,'patJetCorrFactors'+jetALGO+'PF'+PUMethod+'PrunedSubjets' ).primaryVertices = pvLabel  
			if miniAOD:
				if hasattr(proc,'pfInclusiveSecondaryVertexFinderTagInfos'+jetALGO+'PF'+PUMethod+'PrunedSubjets'):
					getattr(proc,'pfInclusiveSecondaryVertexFinderTagInfos'+jetALGO+'PF'+PUMethod+'PrunedSubjets').extSVCollection = cms.InputTag( svLabel ) 
				getattr( proc,'patJets'+jetALGO+'PF'+PUMethod+'PrunedSubjets').addAssociatedTracks = cms.bool(False)
				getattr( proc,'patJets'+jetALGO+'PF'+PUMethod+'PrunedSubjets').addJetCharge = cms.bool(False) 
			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( #src = 'chs',
					rParam = jetSize, 
					jetAlgorithm = algorithm,
					rFilt= rFiltTrim,
					trimPtFracMin= ptFrac) ) 
		if miniAOD: getattr( proc, jetalgo+'PFJets'+PUMethod+'Trimmed').src = 'chs'
		setattr( proc, jetalgo+'PFJets'+PUMethod+'TrimmedLinks', 
				ak8PFJetsCHSTrimmedLinks.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
					matched = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Trimmed'), 
					distMax = cms.double( jetSize ) ) )

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

	if addFiltering:

		setattr( proc, jetalgo+'PFJets'+PUMethod+'Filtered', 
				ak8PFJetsCHSFiltered.clone( #src = 'chs', 
					rParam = jetSize, 
					jetAlgorithm = algorithm,
					rFilt= rfilt,
					nFilt= nfilt ) ) 
		if miniAOD: getattr( proc, jetalgo+'PFJets'+PUMethod+'Filtered').src = 'chs'
		setattr( proc, jetalgo+'PFJets'+PUMethod+'FilteredLinks', 
				ak8PFJetsCHSFilteredLinks.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
					matched = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Filtered'), 
					distMax = cms.double( jetSize ) ) )
		elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'FilteredLinks_*_*'] 
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'Filtered' )
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'FilteredLinks' )
		getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'FilteredLinks']
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'FilteredLinks' )

	if addCMSTopTagger :

		if 'CA' in jetALGO : 

			setattr( proc, 'cmsTopTagPFJets'+PUMethod,  
					cms.EDProducer("CATopJetProducer",
						PFJetParameters.clone( #src = cms.InputTag("chs"), #ak8PFJetsCHSConstituents", "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)
						)
					)
			if miniAOD: getattr( proc, 'cmsTopTagPFJets'+PUMethod ).src = 'chs'
			
			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,
					pfCandidates = cms.InputTag( pfCand ),  
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ), 
					btagDiscriminators = bTagDiscriminators,
					genJetCollection = cms.InputTag(jetalgo+'GenJetsNoNu'),
					getJetMCFlavour = False
					)
			getattr(proc,'patJetPartonMatchCMSTopTag'+PUMethod).matched = cms.InputTag( genParticlesLabel ) 
			if hasattr(proc,'pfInclusiveSecondaryVertexFinderTagInfosCMSTopTag'+PUMethod):
				getattr(proc,'pfInclusiveSecondaryVertexFinderTagInfosCMSTopTag'+PUMethod).extSVCollection = cms.InputTag( svLabel ) 
			getattr(proc,'patJetsCMSTopTag'+PUMethod).addTagInfos = True
			getattr(proc,'patJetsCMSTopTag'+PUMethod).tagInfoSources = cms.VInputTag( cms.InputTag('CATopTagInfos'))
			getattr(proc,'patJetCorrFactorsCMSTopTag'+PUMethod ).primaryVertices = pvLabel  
			getattr(proc,'patJetsCMSTopTag'+PUMethod).addAssociatedTracks = cms.bool(False)
			getattr(proc,'patJetsCMSTopTag'+PUMethod).addJetCharge = cms.bool(False)      
			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,
					pfCandidates = cms.InputTag( pfCand ),  
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ), 
					btagDiscriminators = bTagDiscriminators,
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNu'),
					#getJetMCFlavour = False,
					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
					)

			getattr(proc,'patJetPartonMatchCMSTopTag'+PUMethod+'Subjets').matched = cms.InputTag( genParticlesLabel ) #'prunedGenParticles')
			if hasattr(proc,'pfInclusiveSecondaryVertexFinderTagInfosCMSTopTag'+PUMethod+'Subjets'):
				getattr(proc,'pfInclusiveSecondaryVertexFinderTagInfosCMSTopTag'+PUMethod+'Subjets').extSVCollection = cms.InputTag(svLabel) 
			getattr(proc,'patJetCorrFactorsCMSTopTag'+PUMethod+'Subjets' ).primaryVertices = pvLabel  
			getattr(proc,'patJetsCMSTopTag'+PUMethod+'Subjets').addAssociatedTracks = cms.bool(False)
			getattr(proc,'patJetsCMSTopTag'+PUMethod+'Subjets').addJetCharge = cms.bool(False)      
			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 '|----- 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 ) )
			if miniAOD: getattr( proc, jetalgo+'PFJets'+PUMethod+'MassDropFiltered').src = 'chs'
			setattr( proc, jetalgo+'PFJets'+PUMethod+'MassDropFilteredLinks', ak8PFJetsCHSPrunedLinks.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
				matched = cms.InputTag(jetalgo+'PFJets'+PUMethod+'MassDropFiltered'), distMax = cms.double( jetSize ) ) )
			elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'MassDropFilteredLinks_*_*' ]
			getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'MassDropFilteredLinks' ]
			jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'MassDropFiltered' )
			jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'MassDropFilteredLinks' )
		else: print '|----- CMS recommends CambridgeAachen for Mass Drop, you are using '+algorithm+'. JetToolbox will not run Mass Drop.'
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'MassDropFilteredLinks' )

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

			if miniAOD: setattr( proc, 'hepTopTagPFJets'+PUMethod, hepTopTagPFJetsCHS.clone( src = 'chs' ) )
			else: 
				setattr( proc, jetalgo+'PFJets'+PUMethod+'Constituents', ak8PFJetsCHSConstituents.clone( src = jetalgo+'PFJets'+PUMethod ) )
				setattr( proc, 'hepTopTagPFJets'+PUMethod, hepTopTagPFJetsCHS.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Constituents', 'constituents' ) ) )
			setattr( proc, 'hepTopTagPFJets'+PUMethod+'Links'+jetALGO, ak8PFJetsCHSPrunedLinks.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
				matched = cms.InputTag("hepTopTagPFJets"+PUMethod), distMax = cms.double( jetSize ) ) )
			elemToKeep += [ 'keep *_hepTopTagPFJets'+PUMethod+'Links'+jetALGO+'_*_*' ]
			getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ 'hepTopTagPFJets'+PUMethod+'Links'+jetALGO ]
			jetSeq += getattr(proc, 'hepTopTagPFJets'+PUMethod )
			jetSeq += getattr(proc, 'hepTopTagPFJets'+PUMethod+'Links'+jetALGO )
			toolsUsed.append( 'hepTopTagPFJets'+PUMethod+'Links'+jetALGO )
		else: print '|----- 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:
		#This is the old way before 731
		### 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 )
		'''
		### This is for 731 or higher
		if 'ak4' in jetalgo:
			proc.load('RecoJets.JetProducers.QGTagger_cfi')
			proc.QGTagger.srcJets = cms.InputTag(jetalgo+'PFJets'+PUMethod)    # Could be reco::PFJetCollection or pat::JetCollection (both AOD and miniAOD)
			proc.QGTagger.jetsLabel = cms.string('QGL_AK4PFchs')        # Other options (might need to add an ESSource for it): see https://twiki.cern.ch/twiki/bin/viewauth/CMS/QGDataBaseVersion
			elemToKeep += [ 'keep *_QGTagger_*_*' ]
			getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += ['QJetsAdder'+jetALGO+':qgLikelihood']  
			jetSeq += getattr(proc, 'QGTagger' )
		else:
			'QGTagger is optimized for ak4 jets.'
		'''

	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_*' ]

	print '|---- jetToolBox: Running '+', '.join(toolsUsed)+'.'

	### "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 ) ) )
예제 #19
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)

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

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

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

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

    sequence += setupBTag(
        process,
        jetCollection = ak4PFJets,
        suffix = suffix,
        vsuffix = '',
        muons = muons,
        electrons = electrons,
        tags = ['pfCombinedInclusiveSecondaryVertexV2BJetTags']
    )

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

    allPatJets = addattr('patJets',
        patJets.clone(
            jetSource = ak4PFJets,
            addJetCorrFactors = True,
            jetCorrFactorsSource = [jetCorrFactors],
            addBTagInfo = True,
            discriminatorSources = [cms.InputTag('pfCombinedInclusiveSecondaryVertexV2BJetTags' + suffix)],
            addAssociatedTracks = False,
            addJetCharge = False,
            addGenPartonMatch = False,
            addGenJetMatch = (not isData),
            getJetMCFlavour = False,
            addJetFlavourInfo = False
        )
    )

    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
예제 #20
0
import FWCore.ParameterSet.Config as cms

process = cms.Process("Jets")

process.source = cms.Source("PoolSource",
  fileNames = cms.untracked.vstring(
    'file:patTuple.root'
  )
)

process.MessageLogger = cms.Service("MessageLogger")

## prepare jet collections
from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets
process.goodCaloJets = selectedPatJets.clone(src='cleanPatJets', cut='pt>30 & abs(eta)<3')

## monitor jet collections
from PhysicsTools.PatExamples.PatJetAnalyzer_cfi import analyzePatJets
## modules for jet response
process.rawJets     = analyzePatJets.clone(corrLevel='Uncorrected')
process.relJets     = analyzePatJets.clone(corrLevel='L2Relative')
process.absJets     = analyzePatJets.clone(corrLevel='L3Absolute')
## modules to compare calo and pflow jets
process.caloJets    = analyzePatJets.clone(src='goodCaloJets')
process.pflowJets   = analyzePatJets.clone(src='goodCaloJets')
## modules for shift in JES
process.shiftedJets = analyzePatJets.clone(src='goodCaloJets')


process.TFileService = cms.Service("TFileService",
  fileName = cms.string('analyzePatJets.root')
process.maxEvents = cms.untracked.PSet(
    input = cms.untracked.int32(100)
)

## configure process options
process.options = cms.untracked.PSet(
    wantSummary = cms.untracked.bool(True)
)

#-------------------------------------------------
# top analysis
#-------------------------------------------------

# produce jet collection to be used for further analysis
from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets
process.leadingJets = selectedPatJets.clone()
process.leadingJets.src = "selectedPatJets"
process.leadingJets.cut = "pt > 20 & abs(eta) < 2.4 & 0.05 < emEnergyFraction & emEnergyFraction < 0.95"

## remove events with overlapping jets
process.load("TopAnalysis.TopFilter.filters.JetOverlapEventFilter_cfi")
process.filterJetOverlapEvent.src = "leadingJets"
process.filterJetOverlapEvent.deltaR = 1.0

## produce generated top event
process.load("TopQuarkAnalysis.TopEventProducers.sequences.ttGenEvent_cff")

## produce reconstructed top events
process.load("TopQuarkAnalysis.TopEventProducers.sequences.ttSemiLepEvtBuilder_cff")
process.ttSemiLepJetPartonMatch.verbosity = 1
process.ttSemiLepEvent.verbosity = 1
예제 #22
0
process.patJetCorrFactorsReapplyJECAK8 = process.updatedPatJetCorrFactors.clone(
    src=cms.InputTag("slimmedJetsAK8"),
    levels=["L1FastJet", "L2Relative", "L3Absolute", "L2L3Residual"],
    payload="AK8PFchs",
)

process.load("PhysicsTools.PatAlgos.producersLayer1.jetUpdater_cff")
process.patJetsReapplyJECAK8 = process.updatedPatJets.clone(
    jetSource=cms.InputTag("slimmedJetsAK8"),
    jetCorrFactorsSource=cms.VInputTag(cms.InputTag("patJetCorrFactorsReapplyJECAK8")),
)

from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets

process.goodJets = selectedPatJets.clone(src="patJetsReapplyJEC", cut="pt>30 & abs(eta)<2.4")

############# QGL #################
process.load("RecoJets.JetProducers.QGTagger_cfi")
process.QGTagger.srcJets = cms.InputTag("goodJets")
process.QGTagger.jetsLabel = cms.string("QGL_AK4PFchs")

##-------------------- User analyzer  --------------------------------
process.boosted = cms.EDAnalyzer(
    "BoostedTTbarFlatTreeProducer",
    jets=cms.InputTag("patJetsReapplyJECAK8"),
    muons=cms.InputTag("slimmedMuons"),
    electrons=cms.InputTag("slimmedElectrons"),
    met=cms.InputTag("slimmedMETs"),
    vertices=cms.InputTag("offlineSlimmedPrimaryVertices"),
    rho=cms.InputTag("fixedGridRhoFastjetAll"),
예제 #23
0
# process.GlobalTag.globaltag = 'PHYS14_25_V1'
##-------------------- Define the source  ----------------------------
process.maxEvents = cms.untracked.PSet(input=cms.untracked.int32(-1))
process.source = cms.Source(
    "PoolSource",
    fileNames=cms.untracked.vstring(
        "/store/mc/RunIISpring15DR74/TT_TuneCUETP8M1_13TeV-powheg-pythia8/MINIAODSIM/Asympt50ns_MCRUN2_74_V9A-v4/10000/00D2A247-2910-E511-9F3D-0CC47A4DEDD2.root"
    ),
)
#############   Format MessageLogger #################
process.load("FWCore.MessageService.MessageLogger_cfi")
process.MessageLogger.cerr.FwkReport.reportEvery = 1000

from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets

process.goodJets = selectedPatJets.clone(src="slimmedJets", cut="pt>30 & abs(eta)<2.4")

process.load("RecoJets.JetProducers.QGTagger_cfi")
process.QGTagger.srcJets = cms.InputTag("slimmedJets")
process.QGTagger.jetsLabel = cms.string("QGL_AK4PFchs")

##-------------------- User analyzer  --------------------------------
process.hadtop = cms.EDAnalyzer(
    "TTbarFlatTreeProducer",
    jets=cms.InputTag("slimmedJets"),
    muons=cms.InputTag("slimmedMuons"),
    electrons=cms.InputTag("slimmedElectrons"),
    met=cms.InputTag("slimmedMETs"),
    vertices=cms.InputTag("offlineSlimmedPrimaryVertices"),
    rho=cms.InputTag("fixedGridRhoFastjetAll"),
    nJetsMin=cms.int32(6),
예제 #24
0
)

#--- clean jets from leptons -----------------------------------
process. cleanedJets = cms.EDProducer('JetCleanedProducer',
  jets        = cms.InputTag('patJetsReapplyJEC'),
  rho         = cms.InputTag('fixedGridRhoFastjetAll'),
  muons       = cms.InputTag('slimmedMuons'),
  electrons   = cms.InputTag('slimmedElectrons'),
  vertices    = cms.InputTag('offlineSlimmedPrimaryVertices'),
  minMuPt     = cms.double(10),
  minElPt     = cms.double(10)
)

#--- finally define the good jets -------------------------------
from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets
process.goodJets = selectedPatJets.clone(src='cleanedJets',cut='pt>30 & abs(eta)<2.4')

process.load('RecoJets.JetProducers.QGTagger_cfi')
process.QGTagger.srcJets   = cms.InputTag('goodJets')
process.QGTagger.jetsLabel = cms.string('QGL_AK4PFchs')

##-------------------- User analyzers  --------------------------------
process.load('TopQuarkAnalysis.TopKinFitter.TtFullHadKinFitProducer_cfi')

process.kinFitTtFullHadEvent.jets                = 'goodJets'
process.kinFitTtFullHadEvent.jetCorrectionLevel  = 'L3Absolute'
process.kinFitTtFullHadEvent.bTagAlgo            = 'pfCombinedInclusiveSecondaryVertexV2BJetTags'
process.kinFitTtFullHadEvent.minBTagValueBJet    = 0.8484
process.kinFitTtFullHadEvent.maxBTagValueNonBJet = 0.8484
process.kinFitTtFullHadEvent.bTags               = 2
process.kinFitTtFullHadEvent.maxNJets            = 8
예제 #25
0
)
process.shiftedJetsDown = process.shiftedJetsUp.clone(shiftJES = -1.0)

process.shiftedJetsAK8Up = cms.EDProducer('JetShiftProducer',
  jets        = cms.InputTag('patJetsReapplyJECAK8'),
  rho         = cms.InputTag('fixedGridRhoFastjetAll'),
  payload     = cms.untracked.string('AK8PFchs'),
  shiftJES    = cms.untracked.double(1.0),
  doShift     = cms.untracked.bool(True)
)

process.shiftedJetsAK8Down = process.shiftedJetsAK8Up.clone(shiftJES = -1.0)

#--- finally define the good jets -------------------------------
from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets
process.goodJets            = selectedPatJets.clone(src='patJetsReapplyJEC',cut='pt>30 & abs(eta)<2.4')
process.goodSmearedJets     = selectedPatJets.clone(src='smearedJets',cut='pt>30 & abs(eta)<2.4')
process.goodSmearedJetsUp   = selectedPatJets.clone(src='smearedJetsUp',cut='pt>30 & abs(eta)<2.4')
process.goodSmearedJetsDown = selectedPatJets.clone(src='smearedJetsDown',cut='pt>30 & abs(eta)<2.4')
process.goodShiftedJets     = selectedPatJets.clone(src='shiftedJets',cut='pt>30 & abs(eta)<2.4')
process.goodShiftedJetsUp   = selectedPatJets.clone(src='shiftedJetsUp',cut='pt>30 & abs(eta)<2.4')
process.goodShiftedJetsDown = selectedPatJets.clone(src='shiftedJetsDown',cut='pt>30 & abs(eta)<2.4')

process.load('RecoJets.JetProducers.QGTagger_cfi')
process.QGTagger.srcJets   = cms.InputTag('goodJets')
process.QGTagger.jetsLabel = cms.string('QGL_AK4PFchs')

process.QGTaggerSmeared     = process.QGTagger.clone(srcJets = 'goodSmearedJets')
process.QGTaggerSmearedUp   = process.QGTagger.clone(srcJets = 'goodSmearedJetsUp')
process.QGTaggerSmearedDown = process.QGTagger.clone(srcJets = 'goodSmearedJetsDown')
process.QGTaggerShiftedUp   = process.QGTagger.clone(srcJets = 'goodShiftedJetsUp')
예제 #26
0
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',
        'combinedSecondaryVertexBJetTags',
        'pfCombinedSecondaryVertexSoftLeptonBJetTags',
        'pfPositiveCombinedSecondaryVertexBJetTags',
        'pfNegativeCombinedSecondaryVertexBJetTags'
    ]
    #,'pfCombinedSecondaryVertexBJetTags','pfCombinedMVABJetTags','pfCombinedSecondaryVertexSoftLeptonBJetTags','pfPositiveCombinedSecondaryVertexBJetTags','pfNegativeCombinedSecondaryVertexBJetTags']
    #,'pfCombinedInclusiveSecondaryVertexBJetTags'

    #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', 'L2L3Residual']
    #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']

    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)
예제 #27
0
    def toolCode(self, process):
        """
        Tool code implementation
        """
        ## initialize parameters
        labelName='patJets'+self._parameters['labelName'].value
        postfix=self._parameters['postfix'].value
        jetSource=self._parameters['jetSource'].value
        algo=self._parameters['algo'].value
        jetCorrections=self._parameters['jetCorrections'].value
        btagDiscriminators=list(self._parameters['btagDiscriminators'].value)
        btagInfos=list(self._parameters['btagInfos'].value)
        jetTrackAssociation=self._parameters['jetTrackAssociation'].value
        outputModules=list(self._parameters['outputModules'].value)

        ## a list of all producer modules, which are already known to process
        knownModules = process.producerNames().split()
        ## determine whether btagging information is required or not
        if btagDiscriminators.count('None')>0:
            btagDiscriminators.remove('None')
        if btagInfos.count('None')>0:
            btagInfos.remove('None')
        bTagging=(len(btagDiscriminators)>0 or len(btagInfos)>0)
        ## construct postfix label for auxiliary modules; this postfix
        ## label will start with a capitalized first letter following
        ## the CMS nameing conventions and for improved readablility
        _labelName=labelName[:1].upper()+labelName[1:]
	#_labelName=labelName
        ## determine jet algorithm from jetSource; supported algo types
        ## are ak, kt, sc, ic. This loop expects that the algo type is
        ## followed by a single integer corresponding to the opening
        ## angle parameter dR times 10 (examples ak5, kt4, kt6, ...)
        _algo=algo
	#jetSource=cms.InputTag("ak5PFJets")
        for x in ["ak", "kt", "sc", "ic"]:
            if jetSource.getModuleLabel().lower().find(x)>-1:
                _algo=jetSource.getModuleLabel()[jetSource.getModuleLabel().lower().find(x):jetSource.getModuleLabel().lower().find(x)+3]
	#print _algo
        ## add new patJets to process (keep instance for later further modifications)
        from PhysicsTools.PatAlgos.producersLayer1.jetProducer_cfi import patJets
        if labelName in knownModules :
            _newPatJets=getattr(process, labelName+postfix)
            _newPatJets.jetSource=jetSource
        else :
            #setattr(process, labelName, patJets.clone(jetSource=jetSource))
            setattr(process, labelName+postfix, patJets.clone(jetSource=jetSource))
            _newPatJets=getattr(process, labelName+postfix)
            knownModules.append(labelName+postfix)
        ## add new selectedPatJets to process
        from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets
        if 'selected'+_labelName+postfix in knownModules :
            _newSelectedPatJets=getattr(process, 'selected'+_labelName+postfix)
            _newSelectedPatJets.src=labelName+postfix
        else :
            setattr(process, 'selected'+_labelName+postfix, selectedPatJets.clone(src=labelName+postfix))
            knownModules.append('selected'+_labelName+postfix)

        ## set postfix label to '' if there is no labelName given. In this case all
        ## modules should keep there names w/o postfixes. This will cover the case
        ## of switchJectCollection
        if self._parameters['labelName'].value == '' :
            _labelName = ''

	## add new patJetPartonMatch to process
        from PhysicsTools.PatAlgos.mcMatchLayer0.jetMatch_cfi import patJetPartonMatch
        if 'patJetPartonMatch'+_labelName+postfix in knownModules :
            _newPatJetPartonMatch=getattr(process, 'patJetPartonMatch'+_labelName+postfix)
            _newPatJetPartonMatch.src=jetSource
        else :
            setattr(process, 'patJetPartonMatch'+_labelName+postfix, patJetPartonMatch.clone(src=jetSource))
            knownModules.append('patJetPartonMatch'+_labelName+postfix)
        ## add new patJetGenJetMatch to process
        from PhysicsTools.PatAlgos.mcMatchLayer0.jetMatch_cfi import patJetGenJetMatch
        if 'patJetGenJetMatch'+_labelName+postfix in knownModules :
            _newPatJetGenJetMatch=getattr(process, 'patJetGenJetMatch'+_labelName+postfix)
            _newPatJetGenJetMatch.src=jetSource
            _newPatJetGenJetMatch.matched=_algo.lower()+'GenJets'+postfix
        else :
            setattr(process, 'patJetGenJetMatch'+_labelName+postfix, patJetGenJetMatch.clone(src=jetSource, matched=_algo+'GenJets'))
            knownModules.append('patJetGenJetMatch'+_labelName+postfix)
        ## add new patJetPartonAssociation to process
        from PhysicsTools.PatAlgos.mcMatchLayer0.jetFlavourId_cff import patJetPartonAssociation
        if 'patJetPartonAssociation'+_labelName+postfix in knownModules :
            _newPatJetPartonAssociation=getattr(process, 'patJetPartonAssociation'+_labelName+postfix, patJetPartonAssociation.clone(jets=jetSource))
            _newPatJetPartonAssociation.jets=jetSource
        else :
            setattr(process, 'patJetPartonAssociation'+_labelName+postfix, patJetPartonAssociation.clone(jets=jetSource))
            knownModules.append('patJetPartonAssociation'+_labelName+postfix)
        ## add new patJetPartonAssociation to process
        from PhysicsTools.PatAlgos.mcMatchLayer0.jetFlavourId_cff import patJetFlavourAssociation
        if 'patJetFlavourAssociation'+_labelName+postfix in knownModules :
            _newPatJetFlavourAssociation=getattr(process, 'patJetFlavourAssociation'+_labelName+postfix, patJetFlavourAssociation.clone(srcByReference='patJetPartonAssociation'+_labelName+postfix))
            _newPatJetFlavourAssociation.srcByReference='patJetPartonAssociation'+_labelName+postfix
        else:
            setattr(process, 'patJetFlavourAssociation'+_labelName+postfix, patJetFlavourAssociation.clone(srcByReference='patJetPartonAssociation'+_labelName+postfix))
            knownModules.append('patJetFlavourAssociation'+_labelName+postfix)
        ## modify new patJets collection accordingly
        _newPatJets.genJetMatch.setModuleLabel('patJetGenJetMatch'+_labelName+postfix)
        _newPatJets.genPartonMatch.setModuleLabel('patJetPartonMatch'+_labelName+postfix)
        _newPatJets.JetPartonMapSource.setModuleLabel('patJetFlavourAssociation'+_labelName+postfix)

        ## add jetTrackAssociation for btagging (or jetTracksAssociation only) if required by user
        if (jetTrackAssociation or bTagging):
            ## add new jetTracksAssociationAtVertex to process
            from RecoJets.JetAssociationProducers.ak5JTA_cff import ak5JetTracksAssociatorAtVertex
            if 'jetTracksAssociationAtVertex'+_labelName+postfix in knownModules :
                _newJetTracksAssociationAtVertex=getattr(process, 'jetTracksAssociatorAtVertex'+_labelName+postfix)
                _newJetTracksAssociationAtVertex.jets=jetSource
            else:
                setattr(process, 'jetTracksAssociatorAtVertex'+_labelName+postfix, ak5JetTracksAssociatorAtVertex.clone(jets=jetSource))
                knownModules.append('jetTracksAssociationAtVertex'+_labelName+postfix)
            ## add new patJetCharge to process
            from PhysicsTools.PatAlgos.recoLayer0.jetTracksCharge_cff import patJetCharge
            if 'patJetCharge'+_labelName+postfix in knownModules :
                _newPatJetCharge=getattr(process, 'patJetCharge'+_labelName+postfix)
                _newPatJetCharge.src='jetTracksAssociatorAtVertex'+_labelName+postfix
            else:
                setattr(process, 'patJetCharge'+_labelName+postfix, patJetCharge.clone(src = 'jetTracksAssociatorAtVertex'+_labelName+postfix))
                knownModules.append('patJetCharge'+_labelName+postfix)
            ## modify new patJets collection accordingly
            _newPatJets.addAssociatedTracks=True
            _newPatJets.trackAssociationSource=cms.InputTag('jetTracksAssociatorAtVertex'+_labelName+postfix)
            _newPatJets.addJetCharge=True
            _newPatJets.jetChargeSource=cms.InputTag('patJetCharge'+_labelName+postfix)
        else:
            ## modify new patJets collection accordingly
            _newPatJets.addAssociatedTracks=False
            _newPatJets.trackAssociationSource=''
            _newPatJets.addJetCharge=False
            _newPatJets.jetChargeSource=''
        ## run btagging if required by user
        if (bTagging):
            ## expand tagInfos to what is explicitely required by user + implicit
            ## requirements that come in from one or the other discriminator
            requiredTagInfos = list(btagInfos)
            for btagDiscr in btagDiscriminators :
                for requiredTagInfo in supportedBtagDiscr[btagDiscr] :
                    tagInfoCovered = False
                    for tagInfo in requiredTagInfos :
                        if requiredTagInfo == tagInfo :
                            tagInfoCovered = True
                            break
                    if not tagInfoCovered :
                        requiredTagInfos.append(requiredTagInfo)
            ## load sequences and setups needed fro btagging
	    ## This loads all available btagger, but the ones we need are added to the process by hand lader. Only needed to get the ESProducer. Needs improvement
            #loadWithPostFix(process,"RecoBTag.Configuration.RecoBTag_cff",postfix)
            process.load("RecoBTag.Configuration.RecoBTag_cff")
	    #addESProducers(process,'RecoBTag.Configuration.RecoBTag_cff')
            import RecoBTag.Configuration.RecoBTag_cff as btag

            ## prepare setups for simple secondary vertex infos
            setattr(process, "simpleSecondaryVertex2Trk", simpleSecondaryVertex2Trk)
            ## prepare setups for transient tracks
            setattr(process, "TransientTrackBuilderESProducer", TransientTrackBuilderESProducer)
            ## setup all required btagInfos : we give a dedicated treatment for all five different
            ## types of tagINfos here. A common treatment is possible but might require a more
            ## general approach anyway in coordination with the btaggin POG.
            for btagInfo in requiredTagInfos :
                if 'impactParameterTagInfos' in btagInfo :
                    setattr(process, btagInfo+_labelName+postfix, btag.impactParameterTagInfos.clone(jetTracks = cms.InputTag('jetTracksAssociatorAtVertex'+_labelName+postfix)))
                if 'secondaryVertexTagInfos' in btagInfo :
                    setattr(process, btagInfo+_labelName+postfix, btag.secondaryVertexTagInfos.clone(trackIPTagInfos = cms.InputTag('impactParameterTagInfos'+_labelName+postfix)))
                if 'secondaryVertexNegativeTagInfos' in btagInfo :
                    setattr(process, btagInfo+_labelName+postfix, btag.secondaryVertexNegativeTagInfos.clone(trackIPTagInfos = cms.InputTag('impactParameterTagInfos'+_labelName+postfix)))
                if 'softElectronTagInfos' in btagInfo :
                    setattr(process, btagInfo+_labelName+postfix, btag.softElectronTagInfos.clone(jets = cms.InputTag(_newJetCollection)))
                if 'softMuonTagInfos' in btagInfo :
                    setattr(process, btagInfo+_labelName+postfix, btag.softMuonTagInfos.clone(jets = cms.InputTag(_newJetCollection)))
            ## setup all required btagDiscriminators
            for btagDiscr in btagDiscriminators :
                setattr(process, btagDiscr+_labelName+postfix, getattr(btag, btagDiscr).clone(tagInfos = cms.VInputTag( *[ cms.InputTag(x+_labelName+postfix) for x in supportedBtagDiscr[btagDiscr] ] )))
            ## replace corresponding tags for pat jet production
            _newPatJets.tagInfoSources = cms.VInputTag( *[ cms.InputTag(x+_labelName+postfix) for x in btagInfos ] )
            _newPatJets.discriminatorSources = cms.VInputTag( *[ cms.InputTag(x+_labelName+postfix) for x in btagDiscriminators ] )
        else:
            _newPatJets.addBTagInfo = False
            ## adjust output module; these collections will be empty anyhow, but we do it to stay clean
            for outputModule in outputModules:
                    if hasattr(process,outputModule):
                        getattr(process,outputModule).outputCommands.append("drop *_"+'selected'+_labelName+postfix+"_tagInfos_*")

        ## add jet correction factors if required by user
        if (jetCorrections != None):
            ## check for the correct format
            if type(jetCorrections) != type(('PAYLOAD-LABEL',['CORRECTION-LEVEL-A','CORRECTION-LEVEL-B'], 'MET-LABEL')):
                raise ValueError, "In addJetCollection: 'jetCorrections' must be 'None' (as a python value w/o quotation marks), or of type ('PAYLOAD-LABEL', ['CORRECTION-LEVEL-A', \
                'CORRECTION-LEVEL-B', ...], 'MET-LABEL'). Note that 'MET-LABEL' can be set to 'None' (as a string in quotation marks) in case you do not want to apply MET(Type1) \
                corrections."
            ## determine type of jet constituents from jetSource; supported
            ## jet constituent types are calo, pf, jpt, for pf also particleflow
            ## is aloowed as part of the jetSource label, which might be used
            ## in CommonTools.ParticleFlow
            _type="NONE"
            if jetCorrections[0].count('PF')>0:
                _type='PF'
            elif jetCorrections[0].count('Calo')>0:
                _type='Calo'
            elif jetCorrections[0].count('JPT')>0:
                _type='JPT'
            else:
                raise TypeError, "In addJetCollection: Jet energy corrections are only supported for PF, JPT and Calo jets."
            from PhysicsTools.PatAlgos.recoLayer0.jetCorrFactors_cfi import patJetCorrFactors
            if 'patJetCorrFactors'+_labelName+postfix in knownModules :
                _newPatJetCorrFactors=getattr(process, 'patJetCorrFactors'+_labelName+postfix)
                _newPatJetCorrFactors.src=jetSource
            else :

                setattr(process, 'patJetCorrFactors'+_labelName+postfix, patJetCorrFactors.clone(src=jetSource))
                _newPatJetCorrFactors=getattr(process, "patJetCorrFactors"+_labelName+postfix)
            _newPatJetCorrFactors.payload=jetCorrections[0]
            _newPatJetCorrFactors.levels=jetCorrections[1]
            ## check whether L1Offset or L1FastJet is part of levels
            error=False
            for x in jetCorrections[1]:
                if x == 'L1Offset' :
                    if not error :
                        _newPatJetCorrFactors.useNPV=True
                        _newPatJetCorrFactors.primaryVertices='offlinePrimaryVertices'
                        ## we set this to True now as a L1 correction type should appear only once
                        ## otherwise levels is miss configured
                        error=True
                    else:
                        raise ValueError, "In addJetCollection: Correction levels for jet energy corrections are miss configured. An L1 correction type should appear not more than \
                        once. Check the list of correction levels you requested to be applied: ", jetCorrections[1]
                if x == 'L1FastJet' :
                    if not error :
                        if _type == "JPT" :
                            raise TypeError, "In addJetCollection: L1FastJet corrections are only supported for PF and Calo jets."
                        ## configure module
                        _newPatJetCorrFactors.useRho=True
                        _newPatJetCorrFactors.rho=cms.InputTag('kt6'+_type+'Jets', 'rho')
                        ## we set this to True now as a L1 correction type should appear only once
                        ## otherwise levels is miss configured
                        error=True
                    else:
                        raise ValueError, "In addJetCollection: Correction levels for jet energy corrections are miss configured. An L1 correction type should appear not more than \
                        once. Check the list of correction levels you requested to be applied: ", jetCorrections[1]
            _newPatJets.jetCorrFactorsSource=cms.VInputTag(cms.InputTag('patJetCorrFactors'+_labelName+postfix))
            ## configure MET(Type1) corrections
            if jetCorrections[2].lower() != 'none' and jetCorrections[2] != '':
                if not jetCorrections[2].lower() == 'type-1' and not jetCorrections[2].lower() == 'type-2':
                    raise valueError, "In addJetCollection: Wrong choice of MET corrections for new jet collection. Possible choices are None (or empty string), Type-1, Type-2 (i.e.\
                    Type-1 and Type-2 corrections applied). This choice is not case sensitive. Your choice was: ", jetCorrections[2]
                if _type == "JPT":
                    raise ValueError, "In addJecCollection: MET(type1) corrections are not supported for JPTJets. Please set the MET-LABEL to \"None\" (as string in quatiation \
                    marks) and use raw tcMET together with JPTJets."
                ## set up jet correctors for MET corrections
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFL1Fastjet
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFL1Offset
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFL2Relative
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFL3Absolute
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFResidual

                setattr(process, jetCorrections[0]+'L1FastJet', ak5PFL1Fastjet.clone(algorithm=jetCorrections[0], srcRho=cms.InputTag('kt6'+_type+'Jets','rho')))
                setattr(process, jetCorrections[0]+'L1Offset', ak5PFL1Offset.clone(algorithm=jetCorrections[0]))
                setattr(process, jetCorrections[0]+'L2Relative', ak5PFL2Relative.clone(algorithm=jetCorrections[0]))
                setattr(process, jetCorrections[0]+'L3Absolute', ak5PFL3Absolute.clone(algorithm=jetCorrections[0]))
                setattr(process, jetCorrections[0]+'L2L3Residual', ak5PFResidual.clone(algorithm=jetCorrections[0]))
                setattr(process, jetCorrections[0]+'CombinedCorrector', cms.ESProducer( 'JetCorrectionESChain', correctors = cms.vstring()))
                for x in jetCorrections[1]:
                    if x != 'L1FastJet' and x != 'L1Offset' and x != 'L2Relative' and x != 'L3Absolute' and x != 'L2L3Residual':
                        raise ValueError, 'In addJetCollection: Unsupported JEC for MET(Type1). Currently supported jet correction levels are L1FastJet, L1Offset, L2Relative, \
                        L3Asolute, L2L3Residual. Requested was:', x
                    else:
                        getattr(process, jetCorrections[0]+'CombinedCorrector').correctors.append(jetCorrections[0]+x)

                ## set up MET(Type1) correction modules
                if _type == 'Calo':
                    from JetMETCorrections.Type1MET.caloMETCorrections_cff import caloJetMETcorr
                    from JetMETCorrections.Type1MET.caloMETCorrections_cff import caloType1CorrectedMet
                    from JetMETCorrections.Type1MET.caloMETCorrections_cff import caloType1p2CorrectedMet
                    setattr(process,jetCorrections[0]+'JetMETcorr'+postfix, caloJetMETcorr.clone(src=jetSource,srcMET = "corMetGlobalMuons",jetCorrections = cms.string(jetCorrections[0]+'CombinedCorrector'+postfix)))
                    setattr(process,jetCorrections[0]+'Type1CorMet'+postfix, caloType1CorrectedMet.clone(src = "corMetGlobalMuons"+postfix,srcType1Corrections = cms.VInputTag(cms.InputTag(jetCorrections[0]+'JetMETcorr'+postfix, 'type1'))))
                    setattr(process,jetCorrections[0]+'Type1p2CorMet'+postfix,caloType1p2CorrectedMet.clone(src = "corMetGlobalMuons"+postfix,srcType1Corrections = cms.VInputTag(cms.InputTag(jetCorrections[0]+'JetMETcorr'+postfix, 'type1')),srcUnclEnergySums = cms.VInputTag(cms.InputTag(jetCorrections[0]+'JetMETcorr'+postfix, 'type2'),cms.InputTag(jetCorrections[0]+'JetMETcorr'+postfix, 'offset'),cms.InputTag('muonCaloMETcorr'+postfix))))

                elif _type == 'PF':
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfCandsNotInJet
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfJetMETcorr
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfCandMETcorr
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfType1CorrectedMet
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfType1p2CorrectedMet
                    setattr(process,jetCorrections[0]+'CandsNotInJet'+postfix,pfCandsNotInJet.clone(topCollection = jetSource))
                    setattr(process,jetCorrections[0]+'CandMETcorr'+postfix, pfCandMETcorr.clone(src = cms.InputTag(jetCorrections[0]+'CandsNotInJet'+postfix)))
                    setattr(process,jetCorrections[0]+'JetMETcorr'+postfix, pfJetMETcorr.clone(src = jetSource))
                    setattr(process,jetCorrections[0]+'Type1CorMet'+postfix, pfType1CorrectedMet.clone(srcType1Corrections = cms.VInputTag(cms.InputTag(jetCorrections[0]+'JetMETcorr'+postfix, 'type1'))))
                    setattr(process,jetCorrections[0]+'Type1p2CorMet'+postfix, pfType1p2CorrectedMet.clone(srcType1Corrections = cms.VInputTag(cms.InputTag(jetCorrections[0]+'JetMETcorr'+postfix, 'type1')),srcUnclEnergySums = cms.VInputTag(cms.InputTag(jetCorrections[0]+'JetMETcorr'+postfix, 'type2'),cms.InputTag(jetCorrections[0]+'JetMETcorr'+postfix, 'offset'),cms.InputTag(jetCorrections[0]+'CandMETcorr'+postfix))))

                ## common configuration for Calo and PF
                if ('L1FastJet' in jetCorrections[1] or 'L1Fastjet' in jetCorrections[1]):
                    getattr(process,jetCorrections[0]+'JetMETcorr'+postfix).offsetCorrLabel = cms.string(jetCorrections[0]+'L1FastJet')
                elif ('L1Offset' in jetCorrections[1]):
                    getattr(process,jetCorrections[0]+'JetMETcorr'+postfix).offsetCorrLabel = cms.string(jetCorrections[0]+'L1Offset')
                else:
                    getattr(process,jetCorrections[0]+'JetMETcorr'+postfix).offsetCorrLabel = cms.string('')

                from PhysicsTools.PatAlgos.producersLayer1.metProducer_cfi import patMETs
                if jetCorrections[2].lower() == 'type-1':
                    setattr(process, 'patMETs'+_labelName+postfix, patMETs.clone(metSource = cms.InputTag(jetCorrections[0]+'Type1CorMet'+postfix), addMuonCorrections = False))
                elif jetCorrections[2].lower() == 'type-1':
                    setattr(process, 'patMETs'+_labelName+postfix, patMETs.clone(metSource = cms.InputTag(jetCorrections[0]+'Type1p2CorMet'+postfix), addMuonCorrections = False))
        else:
            ## switch jetCorrFactors off
            _newPatJets.addJetCorrFactors=False
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)
예제 #29
0
def makeMET(process, isData, pfCandidates, jetSource, jetFlavor, postfix=''):
    """
    @jetFlavor: e.g. 'ak4PFchs'

    Additional information (such as gen and calo mets) are added only if postfix is empty.
    """

    sequence = cms.Sequence()
    # postfix is automatically added to the module names
    addattr = AddAttr(process, sequence, postfix)

    if postfix == '':
        # default MET - extract from input slimmedMETs
        pfMet = addattr(
            'pfMet',
            cms.EDProducer("RecoMETExtractor",
                           metSource=cms.InputTag(
                               "slimmedMETs",
                               processName=cms.InputTag.skipCurrentProcess()),
                           correctionLevel=cms.string('raw')))
    else:
        pfMet = addattr(
            'pfMet',
            PFMET_cfi.pfMet.clone(
                src=pfCandidates,
                calculateSignificance=False  # done in PAT
            ))

    cleanedJets = addattr(
        'cleanedJetsForMET',
        cms.EDProducer(
            "PATJetCleanerForType1MET",
            src=cms.InputTag(jetSource),
            jetCorrEtaMax=cms.double(9.9),
            jetCorrLabel=cms.InputTag("L3Absolute"),
            jetCorrLabelRes=cms.InputTag("L2L3Residual"),
            offsetCorrLabel=cms.InputTag("L1FastJet"),
            skipEM=cms.bool(True),
            skipEMfractionThreshold=cms.double(0.9),
            skipMuonSelection=cms.string('isGlobalMuon | isStandAloneMuon'),
            skipMuons=cms.bool(True),
            type1JetPtThreshold=cms.double(15.0)))

    selectedJets = addattr(
        'selectedJetsForMET',
        selectedPatJets.clone(src=cleanedJets,
                              cut='pt > 15 && abs(eta) < 9.9'))

    crossCleanedJets = addattr('crossCleanedJetsForMET',
                               cleanPatJets.clone(src=selectedJets))
    ccJetsMod = addattr.last
    ccJetsMod.checkOverlaps.muons.src = muons
    ccJetsMod.checkOverlaps.electrons.src = electrons
    del ccJetsMod.checkOverlaps.photons
    del ccJetsMod.checkOverlaps.taus
    # not used at all and electrons are already cleaned
    del ccJetsMod.checkOverlaps.tkIsoElectrons

    patPFMet = addattr(
        'patPFMet',
        patMET_cff.patPFMet.clone(
            metSource=pfMet,
            genMETSource='genMetTrue',
            srcPFCands=pfCandidates,
            computeMETSignificance=True,
            parameters=(METSignificanceParams_Data
                        if isData else METSignificanceParams),
            srcJets=crossCleanedJets,
            srcLeptons=[electrons, muons, photons],
            addGenMET=(not isData and postfix == '')))

    patPFMetT1Corr = addattr(
        'patPFMetT1Corr',
        patMET_cff.patPFMetT1T2Corr.clone(src=crossCleanedJets))

    patPFMetT1 = addattr(
        'patPFMetT1',
        patMET_cff.patPFMetT1.clone(src=patPFMet,
                                    srcCorrections=[
                                        cms.InputTag(
                                            patPFMetT1Corr.getModuleLabel(),
                                            'type1')
                                    ]))

    pfCandsNoEle = addattr(
        'pfCandsNoEle',
        cms.EDProducer("CandPtrProjector",
                       src=cms.InputTag(pfCandidates),
                       veto=electrons))

    pfCandsNoEleMu = addattr(
        'pfCandsNoEleMu',
        cms.EDProducer("CandPtrProjector", src=pfCandsNoEle, veto=muons))

    pfCandsNoEleMuTau = addattr(
        'pfCandsNoEleMuTau',
        cms.EDProducer("CandPtrProjector", src=pfCandsNoEleMu, veto=taus))

    pfCandsNoEleMuTauGamma = addattr(
        'pfCandsNoEleMuTauGamma',
        cms.EDProducer("CandPtrProjector", src=pfCandsNoEleMuTau,
                       veto=photons))

    pfCandsForUnclusteredUnc = addattr(
        'pfCandsForUnclusteredUnc',
        cms.EDProducer("CandPtrProjector",
                       src=pfCandsNoEleMuTauGamma,
                       veto=crossCleanedJets))

    for vsign, vname in [(1, 'Up'), (-1, 'Down')]:
        shiftConf = [('MuonEn', muons.value(),
                      '((x<100)?(0.002+0*y):(0.05+0*y))'),
                     ('ElectronEn', electrons.value(),
                      '((abs(y)<1.479)?(0.006+0*x):(0.015+0*x))'),
                     ('PhotonEn', photons.value(),
                      '((abs(y)<1.479)?(0.01+0*x):(0.025+0*x))'),
                     ('TauEn', taus.value(), '0.03+0*x*y'),
                     ('UnclusteredEn', pfCandsForUnclusteredUnc.value(), ''),
                     ('JetEn', crossCleanedJets.value(), '')]

        for part, coll, formula in shiftConf:
            if part == 'UnclusteredEn':
                shifted = addattr(
                    'shifted' + part + vname,
                    cms.EDProducer(
                        "ShiftedParticleProducer",
                        src=pfCandsForUnclusteredUnc,
                        binning=cms.VPSet(
                            # charged PF hadrons - tracker resolution
                            cms.PSet(
                                binSelection=cms.string('charge!=0'),
                                binUncertainty=cms.string(
                                    'sqrt(pow(0.00009*x,2)+pow(0.0085/sqrt(sin(2*atan(exp(-y)))),2))'
                                )),
                            # neutral PF hadrons - HCAL resolution
                            cms.PSet(
                                binSelection=cms.string('pdgId==130'),
                                energyDependency=cms.bool(True),
                                binUncertainty=cms.string(
                                    '((abs(y)<1.3)?(min(0.25,sqrt(0.64/x+0.0025))):(min(0.30,sqrt(1.0/x+0.0016))))'
                                )),
                            # photon - ECAL resolution
                            cms.PSet(binSelection=cms.string('pdgId==22'),
                                     energyDependency=cms.bool(True),
                                     binUncertainty=cms.string(
                                         'sqrt(0.0009/x+0.000001)+0*y')),
                            # HF particules - HF resolution
                            cms.PSet(binSelection=cms.string(
                                'pdgId==1 || pdgId==2'),
                                     energyDependency=cms.bool(True),
                                     binUncertainty=cms.string(
                                         'sqrt(1./x+0.0025)+0*y')),
                        ),
                        shiftBy=cms.double(float(vsign))))

            elif part == 'JetEn':
                shifted = addattr(
                    'shifted' + part + vname,
                    cms.EDProducer(
                        'SUEPShiftedPATJetProducer',
                        src=crossCleanedJets,
                        jetCorrPayloadName=cms.string(jetFlavor),
                        jetCorrUncertaintyTag=cms.string('Uncertainty'),
                        addResidualJES=cms.bool(isData),
                        jetCorrLabelUpToL3=cms.InputTag(
                            'L3Absolute'),  # use embedded correction factors
                        jetCorrLabelUpToL3Res=cms.InputTag('L2L3Residual'),
                        shiftBy=cms.double(float(vsign))))

            else:
                shifted = addattr(
                    'shifted' + part + vname,
                    cms.EDProducer("ShiftedParticleProducer",
                                   src=cms.InputTag(coll),
                                   uncertainty=cms.string(formula),
                                   shiftBy=cms.double(float(vsign))))

            metCorrShifted = addattr(
                'metCorrShifted' + part + vname,
                cms.EDProducer("ShiftedParticleMETcorrInputProducer",
                               srcOriginal=cms.InputTag(coll),
                               srcShifted=shifted))
            addattr(
                'patPFMetT1' + part + vname,
                patMET_cff.patPFMetT1.clone(src=patPFMetT1,
                                            srcCorrections=[metCorrShifted]))

    # Dummy JetResUp and JetResDown modules because PATJetSlimmer requires them
    # Jet smearing should be propagated to MET simply by using ptSmear(|Up|Down) branches at the ntuples level
    addattr('patPFMetT1JetResUp',
            getattr(process, 'patPFMetT1JetEnUp' + postfix).clone())
    addattr('patPFMetT1JetResDown',
            getattr(process, 'patPFMetT1JetEnDown' + postfix).clone())

    addattr(
        'slimmedMETs',
        slimmedMETs.clone(src=patPFMetT1,
                          rawVariation=patPFMet,
                          t1Uncertainties="patPFMetT1%s" + postfix,
                          runningOnMiniAOD=True))

    slimmed = addattr.last

    if postfix == '':  # default MET
        slimmed.caloMET = 'patCaloMet'
    else:
        del slimmed.caloMET

    del slimmed.t01Variation
    del slimmed.t1SmearedVarsAndUncs
    del slimmed.tXYUncForT1
    del slimmed.tXYUncForRaw
    del slimmed.tXYUncForT01
    del slimmed.tXYUncForT1Smear
    del slimmed.tXYUncForT01Smear

    return sequence
예제 #30
0
    def toolCode(self, process):
        """
        Tool code implementation
        """
        ## initialize parameters
        labelName = "patJets" + self._parameters["labelName"].value
        postfix = self._parameters["postfix"].value
        jetSource = self._parameters["jetSource"].value
        algo = self._parameters["algo"].value
        jetCorrections = self._parameters["jetCorrections"].value
        btagDiscriminators = list(self._parameters["btagDiscriminators"].value)
        btagInfos = list(self._parameters["btagInfos"].value)
        jetTrackAssociation = self._parameters["jetTrackAssociation"].value
        outputModules = list(self._parameters["outputModules"].value)

        ## a list of all producer modules, which are already known to process
        knownModules = process.producerNames().split()
        ## determine whether btagging information is required or not
        if btagDiscriminators.count("None") > 0:
            btagDiscriminators.remove("None")
        if btagInfos.count("None") > 0:
            btagInfos.remove("None")
        bTagging = len(btagDiscriminators) > 0 or len(btagInfos) > 0
        ## construct postfix label for auxiliary modules; this postfix
        ## label will start with a capitalized first letter following
        ## the CMS nameing conventions and for improved readablility
        _labelName = labelName[:1].upper() + labelName[1:]
        # _labelName=labelName
        ## determine jet algorithm from jetSource; supported algo types
        ## are ak, kt, sc, ic. This loop expects that the algo type is
        ## followed by a single integer corresponding to the opening
        ## angle parameter dR times 10 (examples ak5, kt4, kt6, ...)
        _algo = algo
        # jetSource=cms.InputTag("ak5PFJets")
        for x in ["ak", "kt", "sc", "ic"]:
            if jetSource.getModuleLabel().lower().find(x) > -1:
                _algo = jetSource.getModuleLabel()[
                    jetSource.getModuleLabel().lower().find(x) : jetSource.getModuleLabel().lower().find(x) + 3
                ]
        # print _algo
        ## add new patJets to process (keep instance for later further modifications)
        from PhysicsTools.PatAlgos.producersLayer1.jetProducer_cfi import patJets

        if labelName in knownModules:
            _newPatJets = getattr(process, labelName + postfix)
            _newPatJets.jetSource = jetSource
        else:
            # setattr(process, labelName, patJets.clone(jetSource=jetSource))
            setattr(process, labelName + postfix, patJets.clone(jetSource=jetSource))
            _newPatJets = getattr(process, labelName + postfix)
            knownModules.append(labelName + postfix)
        ## add new selectedPatJets to process
        from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets

        if "selected" + _labelName + postfix in knownModules:
            _newSelectedPatJets = getattr(process, "selected" + _labelName + postfix)
            _newSelectedPatJets.src = labelName + postfix
        else:
            setattr(process, "selected" + _labelName + postfix, selectedPatJets.clone(src=labelName + postfix))
            knownModules.append("selected" + _labelName + postfix)

        ## set postfix label to '' if there is no labelName given. In this case all
        ## modules should keep there names w/o postfixes. This will cover the case
        ## of switchJectCollection
        if self._parameters["labelName"].value == "":
            _labelName = ""

        ## add new patJetPartonMatch to process
        from PhysicsTools.PatAlgos.mcMatchLayer0.jetMatch_cfi import patJetPartonMatch

        if "patJetPartonMatch" + _labelName + postfix in knownModules:
            _newPatJetPartonMatch = getattr(process, "patJetPartonMatch" + _labelName + postfix)
            _newPatJetPartonMatch.src = jetSource
        else:
            setattr(process, "patJetPartonMatch" + _labelName + postfix, patJetPartonMatch.clone(src=jetSource))
            knownModules.append("patJetPartonMatch" + _labelName + postfix)
        ## add new patJetGenJetMatch to process
        from PhysicsTools.PatAlgos.mcMatchLayer0.jetMatch_cfi import patJetGenJetMatch

        if "patJetGenJetMatch" + _labelName + postfix in knownModules:
            _newPatJetGenJetMatch = getattr(process, "patJetGenJetMatch" + _labelName + postfix)
            _newPatJetGenJetMatch.src = jetSource
            _newPatJetGenJetMatch.matched = _algo.lower() + "GenJets" + postfix
        else:
            setattr(
                process,
                "patJetGenJetMatch" + _labelName + postfix,
                patJetGenJetMatch.clone(src=jetSource, matched=_algo + "GenJets"),
            )
            knownModules.append("patJetGenJetMatch" + _labelName + postfix)
        ## add new patJetPartonAssociation to process
        from PhysicsTools.PatAlgos.mcMatchLayer0.jetFlavourId_cff import patJetPartonAssociation

        if "patJetPartonAssociation" + _labelName + postfix in knownModules:
            _newPatJetPartonAssociation = getattr(
                process, "patJetPartonAssociation" + _labelName + postfix, patJetPartonAssociation.clone(jets=jetSource)
            )
            _newPatJetPartonAssociation.jets = jetSource
        else:
            setattr(
                process, "patJetPartonAssociation" + _labelName + postfix, patJetPartonAssociation.clone(jets=jetSource)
            )
            knownModules.append("patJetPartonAssociation" + _labelName + postfix)
        ## add new patJetPartonAssociation to process
        from PhysicsTools.PatAlgos.mcMatchLayer0.jetFlavourId_cff import patJetFlavourAssociation

        if "patJetFlavourAssociation" + _labelName + postfix in knownModules:
            _newPatJetFlavourAssociation = getattr(
                process,
                "patJetFlavourAssociation" + _labelName + postfix,
                patJetFlavourAssociation.clone(srcByReference="patJetPartonAssociation" + _labelName + postfix),
            )
            _newPatJetFlavourAssociation.srcByReference = "patJetPartonAssociation" + _labelName + postfix
        else:
            setattr(
                process,
                "patJetFlavourAssociation" + _labelName + postfix,
                patJetFlavourAssociation.clone(srcByReference="patJetPartonAssociation" + _labelName + postfix),
            )
            knownModules.append("patJetFlavourAssociation" + _labelName + postfix)
        ## modify new patJets collection accordingly
        _newPatJets.genJetMatch.setModuleLabel("patJetGenJetMatch" + _labelName + postfix)
        _newPatJets.genPartonMatch.setModuleLabel("patJetPartonMatch" + _labelName + postfix)
        _newPatJets.JetPartonMapSource.setModuleLabel("patJetFlavourAssociation" + _labelName + postfix)

        ## add jetTrackAssociation for btagging (or jetTracksAssociation only) if required by user
        if jetTrackAssociation or bTagging:
            ## add new jetTracksAssociationAtVertex to process
            from RecoJets.JetAssociationProducers.ak5JTA_cff import ak5JetTracksAssociatorAtVertex

            if "jetTracksAssociationAtVertex" + _labelName + postfix in knownModules:
                _newJetTracksAssociationAtVertex = getattr(
                    process, "jetTracksAssociatorAtVertex" + _labelName + postfix
                )
                _newJetTracksAssociationAtVertex.jets = jetSource
            else:
                setattr(
                    process,
                    "jetTracksAssociatorAtVertex" + _labelName + postfix,
                    ak5JetTracksAssociatorAtVertex.clone(jets=jetSource),
                )
                knownModules.append("jetTracksAssociationAtVertex" + _labelName + postfix)
            ## add new patJetCharge to process
            from PhysicsTools.PatAlgos.recoLayer0.jetTracksCharge_cff import patJetCharge

            if "patJetCharge" + _labelName + postfix in knownModules:
                _newPatJetCharge = getattr(process, "patJetCharge" + _labelName + postfix)
                _newPatJetCharge.src = "jetTracksAssociatorAtVertex" + _labelName + postfix
            else:
                setattr(
                    process,
                    "patJetCharge" + _labelName + postfix,
                    patJetCharge.clone(src="jetTracksAssociatorAtVertex" + _labelName + postfix),
                )
                knownModules.append("patJetCharge" + _labelName + postfix)
            ## modify new patJets collection accordingly
            _newPatJets.addAssociatedTracks = True
            _newPatJets.trackAssociationSource = cms.InputTag("jetTracksAssociatorAtVertex" + _labelName + postfix)
            _newPatJets.addJetCharge = True
            _newPatJets.jetChargeSource = cms.InputTag("patJetCharge" + _labelName + postfix)
        else:
            ## modify new patJets collection accordingly
            _newPatJets.addAssociatedTracks = False
            _newPatJets.trackAssociationSource = ""
            _newPatJets.addJetCharge = False
            _newPatJets.jetChargeSource = ""
        ## run btagging if required by user
        if bTagging:
            ## expand tagInfos to what is explicitely required by user + implicit
            ## requirements that come in from one or the other discriminator
            requiredTagInfos = list(btagInfos)
            for btagDiscr in btagDiscriminators:
                for requiredTagInfo in supportedBtagDiscr[btagDiscr]:
                    tagInfoCovered = False
                    for tagInfo in requiredTagInfos:
                        if requiredTagInfo == tagInfo:
                            tagInfoCovered = True
                            break
                    if not tagInfoCovered:
                        requiredTagInfos.append(requiredTagInfo)
            ## load sequences and setups needed fro btagging
            ## This loads all available btagger, but the ones we need are added to the process by hand lader. Only needed to get the ESProducer. Needs improvement
            # loadWithPostFix(process,"RecoBTag.Configuration.RecoBTag_cff",postfix)
            process.load("RecoBTag.Configuration.RecoBTag_cff")
            # addESProducers(process,'RecoBTag.Configuration.RecoBTag_cff')
            import RecoBTag.Configuration.RecoBTag_cff as btag

            ## prepare setups for simple secondary vertex infos
            setattr(process, "simpleSecondaryVertex2Trk", simpleSecondaryVertex2Trk)
            ## prepare setups for transient tracks
            setattr(process, "TransientTrackBuilderESProducer", TransientTrackBuilderESProducer)
            ## setup all required btagInfos : we give a dedicated treatment for all five different
            ## types of tagINfos here. A common treatment is possible but might require a more
            ## general approach anyway in coordination with the btaggin POG.
            for btagInfo in requiredTagInfos:
                if "impactParameterTagInfos" in btagInfo:
                    setattr(
                        process,
                        btagInfo + _labelName + postfix,
                        btag.impactParameterTagInfos.clone(
                            jetTracks=cms.InputTag("jetTracksAssociatorAtVertex" + _labelName + postfix)
                        ),
                    )
                if "secondaryVertexTagInfos" in btagInfo:
                    setattr(
                        process,
                        btagInfo + _labelName + postfix,
                        btag.secondaryVertexTagInfos.clone(
                            trackIPTagInfos=cms.InputTag("impactParameterTagInfos" + _labelName + postfix)
                        ),
                    )
                if "secondaryVertexNegativeTagInfos" in btagInfo:
                    setattr(
                        process,
                        btagInfo + _labelName + postfix,
                        btag.secondaryVertexNegativeTagInfos.clone(
                            trackIPTagInfos=cms.InputTag("impactParameterTagInfos" + _labelName + postfix)
                        ),
                    )
                if "softElectronTagInfos" in btagInfo:
                    setattr(
                        process,
                        btagInfo + _labelName + postfix,
                        btag.softElectronTagInfos.clone(jets=cms.InputTag(_newJetCollection)),
                    )
                if "softMuonTagInfos" in btagInfo:
                    setattr(
                        process,
                        btagInfo + _labelName + postfix,
                        btag.softMuonTagInfos.clone(jets=cms.InputTag(_newJetCollection)),
                    )
            ## setup all required btagDiscriminators
            for btagDiscr in btagDiscriminators:
                setattr(
                    process,
                    btagDiscr + _labelName + postfix,
                    getattr(btag, btagDiscr).clone(
                        tagInfos=cms.VInputTag(
                            *[cms.InputTag(x + _labelName + postfix) for x in supportedBtagDiscr[btagDiscr]]
                        )
                    ),
                )
            ## replace corresponding tags for pat jet production
            _newPatJets.tagInfoSources = cms.VInputTag(*[cms.InputTag(x + _labelName + postfix) for x in btagInfos])
            _newPatJets.discriminatorSources = cms.VInputTag(
                *[cms.InputTag(x + _labelName + postfix) for x in btagDiscriminators]
            )
        else:
            _newPatJets.addBTagInfo = False
            ## adjust output module; these collections will be empty anyhow, but we do it to stay clean
            for outputModule in outputModules:
                if hasattr(process, outputModule):
                    getattr(process, outputModule).outputCommands.append(
                        "drop *_" + "selected" + _labelName + postfix + "_tagInfos_*"
                    )

        ## add jet correction factors if required by user
        if jetCorrections != None:
            ## check for the correct format
            if type(jetCorrections) != type(
                ("PAYLOAD-LABEL", ["CORRECTION-LEVEL-A", "CORRECTION-LEVEL-B"], "MET-LABEL")
            ):
                raise ValueError, "In addJetCollection: 'jetCorrections' must be 'None' (as a python value w/o quotation marks), or of type ('PAYLOAD-LABEL', ['CORRECTION-LEVEL-A', \
                'CORRECTION-LEVEL-B', ...], 'MET-LABEL'). Note that 'MET-LABEL' can be set to 'None' (as a string in quotation marks) in case you do not want to apply MET(Type1) \
                corrections."
            ## determine type of jet constituents from jetSource; supported
            ## jet constituent types are calo, pf, jpt, for pf also particleflow
            ## is aloowed as part of the jetSource label, which might be used
            ## in CommonTools.ParticleFlow
            _type = "NONE"
            if jetCorrections[0].count("PF") > 0:
                _type = "PF"
            elif jetCorrections[0].count("Calo") > 0:
                _type = "Calo"
            elif jetCorrections[0].count("JPT") > 0:
                _type = "JPT"
            else:
                raise TypeError, "In addJetCollection: Jet energy corrections are only supported for PF, JPT and Calo jets."
            from PhysicsTools.PatAlgos.recoLayer0.jetCorrFactors_cfi import patJetCorrFactors

            if "patJetCorrFactors" + _labelName + postfix in knownModules:
                _newPatJetCorrFactors = getattr(process, "patJetCorrFactors" + _labelName + postfix)
                _newPatJetCorrFactors.src = jetSource
            else:

                setattr(process, "patJetCorrFactors" + _labelName + postfix, patJetCorrFactors.clone(src=jetSource))
                _newPatJetCorrFactors = getattr(process, "patJetCorrFactors" + _labelName + postfix)
            _newPatJetCorrFactors.payload = jetCorrections[0]
            _newPatJetCorrFactors.levels = jetCorrections[1]
            ## check whether L1Offset or L1FastJet is part of levels
            error = False
            for x in jetCorrections[1]:
                if x == "L1Offset":
                    if not error:
                        _newPatJetCorrFactors.useNPV = True
                        _newPatJetCorrFactors.primaryVertices = "offlinePrimaryVertices"
                        ## we set this to True now as a L1 correction type should appear only once
                        ## otherwise levels is miss configured
                        error = True
                    else:
                        raise ValueError, "In addJetCollection: Correction levels for jet energy corrections are miss configured. An L1 correction type should appear not more than \
                        once. Check the list of correction levels you requested to be applied: ", jetCorrections[
                            1
                        ]
                if x == "L1FastJet":
                    if not error:
                        if _type == "JPT":
                            raise TypeError, "In addJetCollection: L1FastJet corrections are only supported for PF and Calo jets."
                        ## configure module
                        _newPatJetCorrFactors.useRho = True
                        _newPatJetCorrFactors.rho = cms.InputTag("kt6" + _type + "Jets", "rho")
                        ## we set this to True now as a L1 correction type should appear only once
                        ## otherwise levels is miss configured
                        error = True
                    else:
                        raise ValueError, "In addJetCollection: Correction levels for jet energy corrections are miss configured. An L1 correction type should appear not more than \
                        once. Check the list of correction levels you requested to be applied: ", jetCorrections[
                            1
                        ]
            _newPatJets.jetCorrFactorsSource = cms.VInputTag(cms.InputTag("patJetCorrFactors" + _labelName + postfix))
            ## configure MET(Type1) corrections
            if jetCorrections[2].lower() != "none" and jetCorrections[2] != "":
                if not jetCorrections[2].lower() == "type-1" and not jetCorrections[2].lower() == "type-2":
                    raise valueError, "In addJetCollection: Wrong choice of MET corrections for new jet collection. Possible choices are None (or empty string), Type-1, Type-2 (i.e.\
                    Type-1 and Type-2 corrections applied). This choice is not case sensitive. Your choice was: ", jetCorrections[
                        2
                    ]
                if _type == "JPT":
                    raise ValueError, 'In addJecCollection: MET(type1) corrections are not supported for JPTJets. Please set the MET-LABEL to "None" (as string in quatiation \
                    marks) and use raw tcMET together with JPTJets.'
                ## set up jet correctors for MET corrections
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFL1Fastjet
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFL1Offset
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFL2Relative
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFL3Absolute
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFResidual

                setattr(
                    process,
                    jetCorrections[0] + "L1FastJet",
                    ak5PFL1Fastjet.clone(
                        algorithm=jetCorrections[0], srcRho=cms.InputTag("kt6" + _type + "Jets", "rho")
                    ),
                )
                setattr(process, jetCorrections[0] + "L1Offset", ak5PFL1Offset.clone(algorithm=jetCorrections[0]))
                setattr(process, jetCorrections[0] + "L2Relative", ak5PFL2Relative.clone(algorithm=jetCorrections[0]))
                setattr(process, jetCorrections[0] + "L3Absolute", ak5PFL3Absolute.clone(algorithm=jetCorrections[0]))
                setattr(process, jetCorrections[0] + "L2L3Residual", ak5PFResidual.clone(algorithm=jetCorrections[0]))
                setattr(
                    process,
                    jetCorrections[0] + "CombinedCorrector",
                    cms.ESProducer("JetCorrectionESChain", correctors=cms.vstring()),
                )
                for x in jetCorrections[1]:
                    if (
                        x != "L1FastJet"
                        and x != "L1Offset"
                        and x != "L2Relative"
                        and x != "L3Absolute"
                        and x != "L2L3Residual"
                    ):
                        raise ValueError, "In addJetCollection: Unsupported JEC for MET(Type1). Currently supported jet correction levels are L1FastJet, L1Offset, L2Relative, \
                        L3Asolute, L2L3Residual. Requested was:", x
                    else:
                        getattr(process, jetCorrections[0] + "CombinedCorrector").correctors.append(
                            jetCorrections[0] + x
                        )

                ## set up MET(Type1) correction modules
                if _type == "Calo":
                    from JetMETCorrections.Type1MET.caloMETCorrections_cff import caloJetMETcorr
                    from JetMETCorrections.Type1MET.caloMETCorrections_cff import caloType1CorrectedMet
                    from JetMETCorrections.Type1MET.caloMETCorrections_cff import caloType1p2CorrectedMet

                    setattr(
                        process,
                        jetCorrections[0] + "JetMETcorr" + postfix,
                        caloJetMETcorr.clone(
                            src=jetSource,
                            srcMET="corMetGlobalMuons",
                            jetCorrections=cms.string(jetCorrections[0] + "CombinedCorrector" + postfix),
                        ),
                    )
                    setattr(
                        process,
                        jetCorrections[0] + "Type1CorMet" + postfix,
                        caloType1CorrectedMet.clone(
                            src="corMetGlobalMuons" + postfix,
                            srcType1Corrections=cms.VInputTag(
                                cms.InputTag(jetCorrections[0] + "JetMETcorr" + postfix, "type1")
                            ),
                        ),
                    )
                    setattr(
                        process,
                        jetCorrections[0] + "Type1p2CorMet" + postfix,
                        caloType1p2CorrectedMet.clone(
                            src="corMetGlobalMuons" + postfix,
                            srcType1Corrections=cms.VInputTag(
                                cms.InputTag(jetCorrections[0] + "JetMETcorr" + postfix, "type1")
                            ),
                            srcUnclEnergySums=cms.VInputTag(
                                cms.InputTag(jetCorrections[0] + "JetMETcorr" + postfix, "type2"),
                                cms.InputTag(jetCorrections[0] + "JetMETcorr" + postfix, "offset"),
                                cms.InputTag("muonCaloMETcorr" + postfix),
                            ),
                        ),
                    )

                elif _type == "PF":
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfCandsNotInJet
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfJetMETcorr
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfCandMETcorr
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfType1CorrectedMet
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfType1p2CorrectedMet

                    setattr(
                        process,
                        jetCorrections[0] + "CandsNotInJet" + postfix,
                        pfCandsNotInJet.clone(topCollection=jetSource),
                    )
                    setattr(
                        process,
                        jetCorrections[0] + "CandMETcorr" + postfix,
                        pfCandMETcorr.clone(src=cms.InputTag(jetCorrections[0] + "CandsNotInJet" + postfix)),
                    )
                    setattr(process, jetCorrections[0] + "JetMETcorr" + postfix, pfJetMETcorr.clone(src=jetSource))
                    setattr(
                        process,
                        jetCorrections[0] + "Type1CorMet" + postfix,
                        pfType1CorrectedMet.clone(
                            srcType1Corrections=cms.VInputTag(
                                cms.InputTag(jetCorrections[0] + "JetMETcorr" + postfix, "type1")
                            )
                        ),
                    )
                    setattr(
                        process,
                        jetCorrections[0] + "Type1p2CorMet" + postfix,
                        pfType1p2CorrectedMet.clone(
                            srcType1Corrections=cms.VInputTag(
                                cms.InputTag(jetCorrections[0] + "JetMETcorr" + postfix, "type1")
                            ),
                            srcUnclEnergySums=cms.VInputTag(
                                cms.InputTag(jetCorrections[0] + "JetMETcorr" + postfix, "type2"),
                                cms.InputTag(jetCorrections[0] + "JetMETcorr" + postfix, "offset"),
                                cms.InputTag(jetCorrections[0] + "CandMETcorr" + postfix),
                            ),
                        ),
                    )

                ## common configuration for Calo and PF
                if "L1FastJet" in jetCorrections[1] or "L1Fastjet" in jetCorrections[1]:
                    getattr(process, jetCorrections[0] + "JetMETcorr" + postfix).offsetCorrLabel = cms.string(
                        jetCorrections[0] + "L1FastJet"
                    )
                elif "L1Offset" in jetCorrections[1]:
                    getattr(process, jetCorrections[0] + "JetMETcorr" + postfix).offsetCorrLabel = cms.string(
                        jetCorrections[0] + "L1Offset"
                    )
                else:
                    getattr(process, jetCorrections[0] + "JetMETcorr" + postfix).offsetCorrLabel = cms.string("")

                from PhysicsTools.PatAlgos.producersLayer1.metProducer_cfi import patMETs

                if jetCorrections[2].lower() == "type-1":
                    setattr(
                        process,
                        "patMETs" + _labelName + postfix,
                        patMETs.clone(
                            metSource=cms.InputTag(jetCorrections[0] + "Type1CorMet" + postfix),
                            addMuonCorrections=False,
                        ),
                    )
                elif jetCorrections[2].lower() == "type-1":
                    setattr(
                        process,
                        "patMETs" + _labelName + postfix,
                        patMETs.clone(
                            metSource=cms.InputTag(jetCorrections[0] + "Type1p2CorMet" + postfix),
                            addMuonCorrections=False,
                        ),
                    )
        else:
            ## switch jetCorrFactors off
            _newPatJets.addJetCorrFactors = False
예제 #31
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])
예제 #32
0
)

process.patJetCorrFactorsReapplyJECAK8 = process.patJetCorrFactorsUpdated.clone(
  src = cms.InputTag("slimmedJetsAK8"),
  levels = ['L1FastJet','L2Relative','L3Absolute'],
  payload = 'AK4PFchs' 
) 

process.load("PhysicsTools.PatAlgos.producersLayer1.jetUpdater_cff")
process.patJetsReapplyJECAK8 = process.patJetsUpdated.clone(
  jetSource = cms.InputTag("slimmedJetsAK8"),
  jetCorrFactorsSource = cms.VInputTag(cms.InputTag("patJetCorrFactorsReapplyJECAK8"))
)

from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets
process.goodJets = selectedPatJets.clone(src='patJetsReapplyJEC',cut='pt>30 & abs(eta)<2.4')

process.load('RecoJets.JetProducers.QGTagger_cfi')
process.QGTagger.srcJets   = cms.InputTag('goodJets')
process.QGTagger.jetsLabel = cms.string('QGL_AK4PFchs')

##-------------------- User analyzer  --------------------------------
process.hadtopBoost = cms.EDAnalyzer('BoostedTTbarFlatTreeProducer',
  jets             = cms.InputTag('patJetsReapplyJECAK8'),
  muons            = cms.InputTag('slimmedMuons'),
  electrons        = cms.InputTag('slimmedElectrons'),
  met              = cms.InputTag('slimmedMETs'),
  vertices         = cms.InputTag('offlineSlimmedPrimaryVertices'),
  rho              = cms.InputTag('fixedGridRhoFastjetAll'),
  massMin          = cms.double(50),
  ptMin            = cms.double(30),
예제 #33
0
    doShift=cms.untracked.bool(True))
process.shiftedJetsDown = process.shiftedJetsUp.clone(shiftJES=-1.0)

process.shiftedJetsAK8Up = cms.EDProducer(
    'JetShiftProducer',
    jets=cms.InputTag('patJetsReapplyJECAK8'),
    rho=cms.InputTag('fixedGridRhoFastjetAll'),
    payload=cms.untracked.string('AK8PFchs'),
    shiftJES=cms.untracked.double(1.0),
    doShift=cms.untracked.bool(True))

process.shiftedJetsAK8Down = process.shiftedJetsAK8Up.clone(shiftJES=-1.0)

#--- finally define the good jets -------------------------------
from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets
process.goodJets = selectedPatJets.clone(src='patJetsReapplyJEC',
                                         cut='pt>30 & abs(eta)<2.4')
process.goodSmearedJets = selectedPatJets.clone(src='smearedJets',
                                                cut='pt>30 & abs(eta)<2.4')
process.goodSmearedJetsUp = selectedPatJets.clone(src='smearedJetsUp',
                                                  cut='pt>30 & abs(eta)<2.4')
process.goodSmearedJetsDown = selectedPatJets.clone(src='smearedJetsDown',
                                                    cut='pt>30 & abs(eta)<2.4')
process.goodShiftedJets = selectedPatJets.clone(src='shiftedJets',
                                                cut='pt>30 & abs(eta)<2.4')
process.goodShiftedJetsUp = selectedPatJets.clone(src='shiftedJetsUp',
                                                  cut='pt>30 & abs(eta)<2.4')
process.goodShiftedJetsDown = selectedPatJets.clone(src='shiftedJetsDown',
                                                    cut='pt>30 & abs(eta)<2.4')

process.load('RecoJets.JetProducers.QGTagger_cfi')
process.QGTagger.srcJets = cms.InputTag('goodJets')
예제 #34
0
process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')
process.GlobalTag.globaltag = '80X_dataRun2_2016SeptRepro_v7'
##-------------------- Define the source  ----------------------------
process.maxEvents = cms.untracked.PSet(input = cms.untracked.int32(2000))
process.source = cms.Source("PoolSource",
  fileNames = cms.untracked.vstring(
        #"file:10B2302E-DA08-E611-884E-001E67DDD348.root")
        #"file:004A0552-3929-E611-BD44-0025905A48F0.root"),
        "file:00619786-8D7D-E711-9AB1-D4AE52A685A7.root"),
)
#############   Format MessageLogger #################
process.load('FWCore.MessageService.MessageLogger_cfi')
process.MessageLogger.cerr.FwkReport.reportEvery = 1000

from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets
process.goodJets = selectedPatJets.clone(src='slimmedJets',cut='pt>30 & abs(eta)<2.4')

process.load('RecoJets.JetProducers.QGTagger_cfi')
process.QGTagger.srcJets   = cms.InputTag('slimmedJets')
process.QGTagger.jetsLabel = cms.string('QGL_AK4PFchs')

from RecoJets.Configuration.RecoGenJets_cff import ak4GenJets, ak8GenJets

genParticleCollection = 'prunedGenParticles'

from RecoJets.JetProducers.ak4GenJets_cfi import ak4GenJets
from RecoJets.JetProducers.GenJetParameters_cfi import *

process.ak8GenJetsCustom = ak4GenJets.clone(
    src = genParticleCollection,
    rParam = cms.double(0.8),
예제 #35
0
#______________________ Event-Selection _____________________________

from HLTrigger.HLTfilters.hltHighLevel_cfi import hltHighLevel
hltFilter = hltHighLevel.clone(
    andOr=True,  ## choose logical OR between Triggerbits
    HLTPaths=['HLT_ZeroBias'],
    throw=False  # tolerate triggers stated above, but not available
)

#______________________ Object-Selection ____________________________

from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets
from PhysicsTools.PatAlgos.selectionLayer1.electronSelector_cfi import selectedPatElectrons
from PhysicsTools.PatAlgos.selectionLayer1.muonSelector_cfi import selectedPatMuons
from PhysicsTools.PatAlgos.selectionLayer1.tauSelector_cfi import selectedPatTaus

patJetSelector = selectedPatJets.clone(filter=cms.bool(False), src="", cut="")
patElectronSelector = selectedPatElectrons.clone(filter=cms.bool(False),
                                                 src="",
                                                 cut="")
patMuonSelector = selectedPatMuons.clone(filter=cms.bool(False),
                                         src="",
                                         cut="")
patTauSelector = selectedPatTaus.clone(filter=cms.bool(False), src="", cut="")

candStringSelector = cms.EDFilter("CandViewSelector",
                                  filter=cms.bool(False),
                                  src=cms.InputTag(""),
                                  cut=cms.string(""))