Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2025-02-05 03:15:11

0001 from PhysicsTools.PatAlgos.tools.ConfigToolBase import *
0002 from FWCore.ParameterSet.Mixins import PrintOptions,_ParameterTypeBase,_SimpleParameterTypeBase, _Parameterizable, _ConfigureComponent, _TypedParameterizable, _Labelable,  _Unlabelable,  _ValidatingListBase
0003 from FWCore.ParameterSet.SequenceTypes import _ModuleSequenceType, _Sequenceable
0004 from FWCore.ParameterSet.SequenceTypes import *
0005 from PhysicsTools.PatAlgos.tools.helpers import *
0006 from PhysicsTools.PatAlgos.recoLayer0.bTagging_cff import *
0007 import sys
0008 from FWCore.ParameterSet.MassReplace import MassSearchReplaceAnyInputTagVisitor
0009 from RecoBTag.ONNXRuntime.pfParticleNetFromMiniAODAK4_cff import pfParticleNetFromMiniAODAK4PuppiCentralTagInfos,pfParticleNetFromMiniAODAK4PuppiCentralJetTags,pfParticleNetFromMiniAODAK4PuppiCentralDiscriminatorsJetTags,pfNegativeParticleNetFromMiniAODAK4PuppiCentralJetTags
0010 from RecoBTag.ONNXRuntime.pfParticleNetFromMiniAODAK4_cff import pfParticleNetFromMiniAODAK4PuppiForwardTagInfos,pfParticleNetFromMiniAODAK4PuppiForwardJetTags,pfParticleNetFromMiniAODAK4PuppiForwardDiscriminatorsJetTags
0011 from RecoBTag.ONNXRuntime.pfParticleNetFromMiniAODAK4_cff import pfParticleNetFromMiniAODAK4CHSCentralTagInfos,pfParticleNetFromMiniAODAK4CHSCentralJetTags,pfParticleNetFromMiniAODAK4CHSCentralDiscriminatorsJetTags,pfNegativeParticleNetFromMiniAODAK4CHSCentralJetTags
0012 from RecoBTag.ONNXRuntime.pfParticleNetFromMiniAODAK4_cff import pfParticleNetFromMiniAODAK4CHSForwardTagInfos,pfParticleNetFromMiniAODAK4CHSForwardJetTags,pfParticleNetFromMiniAODAK4CHSForwardDiscriminatorsJetTags
0013 from RecoBTag.ONNXRuntime.pfParticleNetFromMiniAODAK8_cff import pfParticleNetFromMiniAODAK8TagInfos,pfParticleNetFromMiniAODAK8JetTags,pfParticleNetFromMiniAODAK8DiscriminatorsJetTags
0014 
0015 ## dictionary with supported jet clustering algorithms
0016 supportedJetAlgos = {
0017    'ak' : 'AntiKt'
0018  , 'ca' : 'CambridgeAachen'
0019  , 'kt' : 'Kt'
0020 }
0021 
0022 def checkJetCorrectionsFormat(jetCorrections):
0023     ## check for the correct format
0024     if not isinstance(jetCorrections, type(('PAYLOAD-LABEL',['CORRECTION-LEVEL-A','CORRECTION-LEVEL-B'], 'MET-LABEL'))):
0025         raise ValueError("In addJetCollection: 'jetCorrections' must be 'None' (as a python value w/o quotation marks), or of type ('PAYLOAD-LABEL', ['CORRECTION-LEVEL-A', \
0026         '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) \
0027         corrections.")
0028 
0029 
0030 def setupJetCorrections(process, knownModules, jetCorrections, jetSource, pvSource, patJets, labelName, postfix):
0031 
0032     task = getPatAlgosToolsTask(process)
0033 
0034     ## determine type of jet constituents from jetSource; supported
0035     ## jet constituent types are calo, pf, jpt, for pf also particleflow
0036     ## is aloowed as part of the jetSource label, which might be used
0037     ## in CommonTools.ParticleFlow
0038     _type="NONE"
0039     if jetCorrections[0].count('PF')>0:
0040         _type='PF'
0041     elif jetCorrections[0].count('Calo')>0:
0042         _type='Calo'
0043     elif jetCorrections[0].count('JPT')>0:
0044         _type='JPT'
0045     else:
0046         raise TypeError("In addJetCollection: Jet energy corrections are only supported for PF, JPT and Calo jets.")
0047     from PhysicsTools.PatAlgos.recoLayer0.jetCorrFactors_cfi import patJetCorrFactors
0048     if 'patJetCorrFactors'+labelName+postfix in knownModules :
0049         _newPatJetCorrFactors=getattr(process, 'patJetCorrFactors'+labelName+postfix)
0050         _newPatJetCorrFactors.src=jetSource
0051         _newPatJetCorrFactors.primaryVertices=pvSource
0052     else:
0053         addToProcessAndTask('patJetCorrFactors'+labelName+postfix,
0054                             patJetCorrFactors.clone(src=jetSource, primaryVertices=pvSource),
0055                             process, task)
0056         _newPatJetCorrFactors=getattr(process, "patJetCorrFactors"+labelName+postfix)
0057     _newPatJetCorrFactors.payload=jetCorrections[0]
0058     _newPatJetCorrFactors.levels=jetCorrections[1]
0059     ## check whether L1Offset or L1FastJet is part of levels
0060     error=False
0061     for x in jetCorrections[1]:
0062         if x == 'L1Offset' :
0063             if not error :
0064                 _newPatJetCorrFactors.useNPV=True
0065                 _newPatJetCorrFactors.primaryVertices='offlinePrimaryVertices'
0066                 _newPatJetCorrFactors.useRho=False
0067                 ## we set this to True now as a L1 correction type should appear only once
0068                 ## otherwise levels is miss configured
0069                 error=True
0070             else:
0071                 raise ValueError("In addJetCollection: Correction levels for jet energy corrections are miss configured. An L1 correction type should appear not more than \
0072                 once. Check the list of correction levels you requested to be applied: "+ jetCorrections[1])
0073         if x == 'L1FastJet' :
0074             if not error :
0075                 if _type == "JPT" :
0076                     raise TypeError("In addJetCollection: L1FastJet corrections are only supported for PF and Calo jets.")
0077                 ## configure module
0078                 _newPatJetCorrFactors.useRho=True
0079                 if "PF" in _type :
0080                     _newPatJetCorrFactors.rho=cms.InputTag('fixedGridRhoFastjetAll')
0081                 else :
0082                     _newPatJetCorrFactors.rho=cms.InputTag('fixedGridRhoFastjetAllCalo')
0083                 ## we set this to True now as a L1 correction type should appear only once
0084                 ## otherwise levels is miss configured
0085                 error=True
0086             else:
0087                 raise ValueError("In addJetCollection: Correction levels for jet energy corrections are miss configured. An L1 correction type should appear not more than \
0088                 once. Check the list of correction levels you requested to be applied: "+ jetCorrections[1])
0089     patJets.jetCorrFactorsSource=cms.VInputTag(cms.InputTag('patJetCorrFactors'+labelName+postfix))
0090     ## configure MET(Type1) corrections
0091     if jetCorrections[2].lower() != 'none' and jetCorrections[2] != '':
0092         if not jetCorrections[2].lower() == 'type-1' and not jetCorrections[2].lower() == 'type-2':
0093             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.\
0094             Type-1 and Type-2 corrections applied). This choice is not case sensitive. Your choice was: "+ jetCorrections[2])
0095         if _type == "JPT":
0096             raise ValueError("In addJecCollection: MET(type1) corrections are not supported for JPTJets. Please set the MET-LABEL to \"None\" (as string in quatiation \
0097             marks) and use raw tcMET together with JPTJets.")
0098         ## set up jet correctors for MET corrections
0099         process.load( "JetMETCorrections.Configuration.JetCorrectorsAllAlgos_cff") # FIXME: This adds a lot of garbage
0100         # I second the FIXME comment on the last line. When I counted it, this brought in 344 EDProducers
0101         # to be available to run unscheduled. All jet correctors, probably some small fraction of which
0102         # are actually used.
0103         task.add(process.jetCorrectorsAllAlgosTask)
0104         _payloadType = jetCorrections[0].split(_type)[0].lower()+_type
0105         if "PF" in _type :
0106             addToProcessAndTask(jetCorrections[0]+'L1FastJet',
0107                                 getattr(process, _payloadType+'L1FastjetCorrector').clone(srcRho=cms.InputTag('fixedGridRhoFastjetAll')),
0108                                 process, task)
0109         else :
0110             addToProcessAndTask(jetCorrections[0]+'L1FastJet',
0111                                 getattr(process, _payloadType+'L1FastjetCorrector').clone(srcRho=cms.InputTag('fixedGridRhoFastjetAllCalo')),
0112                                 process, task)
0113         addToProcessAndTask(jetCorrections[0]+'L1Offset', getattr(process, _payloadType+'L1OffsetCorrector').clone(), process, task)
0114         addToProcessAndTask(jetCorrections[0]+'L2Relative', getattr(process, _payloadType+'L2RelativeCorrector').clone(), process, task)
0115         addToProcessAndTask(jetCorrections[0]+'L3Absolute', getattr(process, _payloadType+'L3AbsoluteCorrector').clone(), process, task)
0116         addToProcessAndTask(jetCorrections[0]+'L2L3Residual', getattr(process, _payloadType+'ResidualCorrector').clone(), process, task)
0117         addToProcessAndTask(jetCorrections[0]+'CombinedCorrector',
0118                             cms.EDProducer( 'ChainedJetCorrectorProducer', correctors = cms.VInputTag()),
0119                             process, task)
0120         for x in jetCorrections[1]:
0121             if x != 'L1FastJet' and x != 'L1Offset' and x != 'L2Relative' and x != 'L3Absolute' and x != 'L2L3Residual':
0122                 raise ValueError('In addJetCollection: Unsupported JEC for MET(Type1). Currently supported jet correction levels are L1FastJet, L1Offset, L2Relative, L3Asolute, L2L3Residual. Requested was: %s'%(x))
0123             else:
0124                 _corrector = _payloadType
0125                 if x == 'L1FastJet':
0126                   _corrector += 'L1Fastjet'
0127                 elif x  == 'L2L3Residual':
0128                   _corrector += 'Residual'
0129                 else:
0130                   _corrector += x
0131                 _corrector += 'Corrector'
0132                 getattr(process, jetCorrections[0]+'CombinedCorrector').correctors.append(cms.InputTag(_corrector))
0133 
0134         ## set up MET(Type1) correction modules
0135         _labelCorrName = labelName
0136         if labelName != '':
0137             _labelCorrName = 'For' + labelName
0138         if _type == 'Calo':
0139             from JetMETCorrections.Type1MET.correctionTermsCaloMet_cff import corrCaloMetType1
0140             from JetMETCorrections.Type1MET.correctionTermsCaloMet_cff import corrCaloMetType2
0141             from JetMETCorrections.Type1MET.correctedMet_cff import caloMetT1
0142             from JetMETCorrections.Type1MET.correctedMet_cff import caloMetT1T2
0143             addToProcessAndTask(
0144                 jetCorrections[0]+_labelCorrName+'JetMETcorr'+postfix,
0145                 corrCaloMetType1.clone(src=jetSource,srcMET = "caloMetM",jetCorrLabel = cms.InputTag(jetCorrections[0]+'CombinedCorrector')),
0146                 process, task)
0147             addToProcessAndTask(
0148                 jetCorrections[0]+_labelCorrName+'JetMETcorr2'+postfix,
0149                 corrCaloMetType2.clone(srcUnclEnergySums = cms.VInputTag(
0150                     cms.InputTag(jetCorrections[0]+_labelCorrName+'JetMETcorr'+postfix, 'type2'),
0151                     cms.InputTag(jetCorrections[0]+_labelCorrName+'JetMETcorr'+postfix, 'offset'),
0152                     cms.InputTag('muCaloMetCorr'))),
0153                 process, task)
0154             addToProcessAndTask(
0155                 jetCorrections[0]+_labelCorrName+'Type1CorMet'+postfix,
0156                 caloMetT1.clone(src = "caloMetM", srcCorrections = cms.VInputTag(
0157                     cms.InputTag(jetCorrections[0]+_labelCorrName+'JetMETcorr'+postfix, 'type1'))),
0158                 process, task)
0159             addToProcessAndTask(jetCorrections[0]+_labelCorrName+'Type1p2CorMet'+postfix,
0160                                 caloMetT1T2.clone(src = "caloMetM", srcCorrections = cms.VInputTag(
0161                                     cms.InputTag(jetCorrections[0]+_labelCorrName+'JetMETcorr'+postfix, 'type1'),
0162                                     cms.InputTag(jetCorrections[0]+_labelCorrName+'JetMETcorr2'+postfix))),
0163                                 process, task)
0164         elif _type == 'PF':
0165             from JetMETCorrections.Type1MET.correctionTermsPfMetType1Type2_cff import pfJetsPtrForMetCorr
0166             from JetMETCorrections.Type1MET.correctionTermsPfMetType1Type2_cff import pfCandsNotInJetsPtrForMetCorr
0167             from JetMETCorrections.Type1MET.correctionTermsPfMetType1Type2_cff import pfCandsNotInJetsForMetCorr
0168             from JetMETCorrections.Type1MET.correctionTermsPfMetType1Type2_cff import pfCandMETcorr
0169             from JetMETCorrections.Type1MET.correctionTermsPfMetType1Type2_cff import corrPfMetType1
0170             from JetMETCorrections.Type1MET.correctionTermsPfMetType1Type2_cff import corrPfMetType2
0171             from JetMETCorrections.Type1MET.correctedMet_cff import pfMetT1
0172             from JetMETCorrections.Type1MET.correctedMet_cff import pfMetT1T2
0173             addToProcessAndTask(jetCorrections[0]+_labelCorrName+'pfJetsPtrForMetCorr'+postfix,
0174                                 pfJetsPtrForMetCorr.clone(src = jetSource), process, task)
0175             addToProcessAndTask(
0176                 jetCorrections[0]+_labelCorrName+'pfCandsNotInJetsPtrForMetCorr'+postfix,
0177                 pfCandsNotInJetsPtrForMetCorr.clone(topCollection = jetCorrections[0]+_labelCorrName+'pfJetsPtrForMetCorr'+postfix),
0178                 process, task)
0179             addToProcessAndTask(
0180                 jetCorrections[0]+_labelCorrName+'pfCandsNotInJetsForMetCorr'+postfix,
0181                 pfCandsNotInJetsForMetCorr.clone(src = jetCorrections[0]+_labelCorrName+'pfCandsNotInJetsPtrForMetCorr'+postfix),
0182                 process, task)
0183             addToProcessAndTask(
0184                 jetCorrections[0]+_labelCorrName+'CandMETcorr'+postfix,
0185                 pfCandMETcorr.clone(src = cms.InputTag(jetCorrections[0]+_labelCorrName+'pfCandsNotInJetsForMetCorr'+postfix)),
0186                 process, task)
0187             addToProcessAndTask(
0188                 jetCorrections[0]+_labelCorrName+'JetMETcorr'+postfix,
0189                 corrPfMetType1.clone(src = jetSource, jetCorrLabel = cms.InputTag(jetCorrections[0]+'CombinedCorrector')),
0190                 process, task) # FIXME: Originally w/o jet corrections?
0191             addToProcessAndTask(jetCorrections[0]+_labelCorrName+'corrPfMetType2'+postfix,
0192                                 corrPfMetType2.clone(srcUnclEnergySums = cms.VInputTag(
0193                                     cms.InputTag(jetCorrections[0]+_labelCorrName+'JetMETcorr'+postfix, 'type2'),
0194                                     cms.InputTag(jetCorrections[0]+_labelCorrName+'JetMETcorr'+postfix, 'offset'),
0195                                     cms.InputTag(jetCorrections[0]+_labelCorrName+'CandMETcorr'+postfix))),
0196                                 process, task)
0197             addToProcessAndTask(jetCorrections[0]+_labelCorrName+'Type1CorMet'+postfix,
0198                                 pfMetT1.clone(srcCorrections = cms.VInputTag(
0199                                     cms.InputTag(jetCorrections[0]+_labelCorrName+'JetMETcorr'+postfix, 'type1'))),
0200                                 process, task)
0201             addToProcessAndTask(jetCorrections[0]+_labelCorrName+'Type1p2CorMet'+postfix,
0202                                 pfMetT1T2.clone(srcCorrections = cms.VInputTag(
0203                                     cms.InputTag(jetCorrections[0]+_labelCorrName+'JetMETcorr'+postfix, 'type1'),
0204                                     jetCorrections[0]+_labelCorrName+'corrPfMetType2'+postfix)),
0205                                 process, task)
0206             if 'Puppi' in jetSource.value() and pfCandidates.value() == 'particleFlow':
0207                 getattr(process,jetCorrections[0]+_labelCorrName+'CandMETcorr'+postfix).srcWeights = "puppiNoLep"
0208 
0209         ## common configuration for Calo and PF
0210         if ('L1FastJet' in jetCorrections[1] or 'L1Fastjet' in jetCorrections[1]):
0211             getattr(process,jetCorrections[0]+_labelCorrName+'JetMETcorr'+postfix).offsetCorrLabel = cms.InputTag(jetCorrections[0]+'L1FastJet')
0212         #FIXME: What is wrong here?
0213         #elif ('L1Offset' in jetCorrections[1]):
0214             #getattr(process,jetCorrections[0]+_labelCorrName+'JetMETcorr'+postfix).offsetCorrLabel = cms.InputTag(jetCorrections[0]+'L1Offset')
0215         else:
0216             getattr(process,jetCorrections[0]+_labelCorrName+'JetMETcorr'+postfix).offsetCorrLabel = cms.InputTag('')
0217 
0218         from PhysicsTools.PatAlgos.producersLayer1.metProducer_cfi import patMETs
0219         if jetCorrections[2].lower() == 'type-1':
0220             addToProcessAndTask('patMETs'+labelName+postfix,
0221                                 patMETs.clone(metSource = cms.InputTag(jetCorrections[0]+_labelCorrName+'Type1CorMet'+postfix),
0222                                               addMuonCorrections = False),
0223                                 process, task)
0224         elif jetCorrections[2].lower() == 'type-2':
0225             addToProcessAndTask('patMETs'+labelName+postfix,
0226                                 patMETs.clone(metSource = cms.InputTag(jetCorrections[0]+_labelCorrName+'Type1p2CorMet'+postfix),
0227                                               addMuonCorrections = False),
0228                                 process, task)
0229 
0230 
0231 def setupSVClustering(btagInfo, svClustering, algo, rParam, fatJets=cms.InputTag(''), groomedFatJets=cms.InputTag('')):
0232     btagInfo.useSVClustering = cms.bool(svClustering)
0233     btagInfo.jetAlgorithm = cms.string(algo)
0234     btagInfo.rParam = cms.double(rParam)
0235     ## if the jet is actually a subjet
0236     if fatJets != cms.InputTag(''):
0237         btagInfo.fatJets = fatJets
0238         if groomedFatJets != cms.InputTag(''):
0239             btagInfo.groomedFatJets = groomedFatJets
0240 
0241 def setupPuppiForPackedPF(process, useExistingWeights=True, postfix=''):
0242     """
0243     Setup puppi weights
0244     Two instances of PuppiProducer:
0245     - packedpuppi (for jet reclustering)
0246     - packedpuppiNoLep (for MET reclustering)
0247     """
0248     from CommonTools.PileupAlgos.Puppi_cff import puppi
0249     task = getPatAlgosToolsTask(process)
0250 
0251     puppiLabel = 'packedpuppi'+postfix
0252 
0253     ## Instantiate PuppiProducer with "puppiLabel"
0254     ## if it does not exist.
0255     if not hasattr(process, puppiLabel):
0256         addToProcessAndTask(puppiLabel, puppi.clone(
0257             useExistingWeights = useExistingWeights,
0258             candName = 'packedPFCandidates',
0259             vertexName = 'offlineSlimmedPrimaryVertices'), process, task)
0260 
0261     puppiNoLepLabel = puppiLabel+'NoLep'
0262 
0263     if hasattr(process, puppiLabel) and not hasattr(process, puppiNoLepLabel):
0264         addToProcessAndTask(puppiNoLepLabel, getattr(process, puppiLabel).clone(
0265             puppiNoLep = True), process, task)
0266 
0267     return puppiLabel, puppiNoLepLabel
0268 
0269 def setupBTagging(process, jetSource, pfCandidates, explicitJTA, pvSource, svSource, elSource, muSource, runIVF, tightBTagNTkHits, loadStdRecoBTag, svClustering, fatJets, groomedFatJets,
0270                   algo, rParam, btagDiscriminators, btagInfos, patJets, labelName, btagPrefix, postfix):
0271 
0272     task = getPatAlgosToolsTask(process)
0273 
0274     ## expand the btagDiscriminators to remove the meta taggers and substitute the equivalent sources
0275     discriminators = set(btagDiscriminators)
0276     present_metaSet = discriminators.intersection(set(supportedMetaDiscr.keys()))
0277     discriminators -= present_metaSet
0278     for meta_tagger in present_metaSet:
0279         for src in supportedMetaDiscr[meta_tagger]:
0280             discriminators.add(src)
0281     present_meta = sorted(present_metaSet)
0282     btagDiscriminators = sorted(discriminators)
0283 
0284     ## expand tagInfos to what is explicitly required by user + implicit
0285     ## requirements that come in from one or the other discriminator
0286     requiredTagInfos = list(btagInfos)
0287     for btagDiscr in btagDiscriminators :
0288         for tagInfoList in supportedBtagDiscr[btagDiscr] :
0289             for requiredTagInfo in tagInfoList :
0290                 tagInfoCovered = False
0291                 for tagInfo in requiredTagInfos :
0292                     if requiredTagInfo == tagInfo :
0293                         tagInfoCovered = True
0294                         break
0295                 if not tagInfoCovered :
0296                     requiredTagInfos.append(requiredTagInfo)
0297     ## load sequences and setups needed for btagging
0298     if hasattr( process, 'candidateJetProbabilityComputer' ) == False :
0299         if loadStdRecoBTag: # also loading modules already run in the standard reconstruction
0300             process.load("RecoBTag.ImpactParameter.impactParameter_cff")
0301             task.add(process.impactParameterTask)
0302             process.load("RecoBTag.SecondaryVertex.secondaryVertex_cff")
0303             task.add(process.secondaryVertexTask)
0304             process.load("RecoBTag.SoftLepton.softLepton_cff")
0305             task.add(process.softLeptonTask)
0306             process.load("RecoBTag.Combined.combinedMVA_cff")
0307             task.add(process.combinedMVATask)
0308             process.load("RecoBTag.CTagging.cTagging_cff")
0309             task.add(process.cTaggingTask)
0310         else: # to prevent loading of modules already run in the standard reconstruction
0311             process.load("RecoBTag.ImpactParameter.impactParameter_EventSetup_cff")
0312             process.load("RecoBTag.SecondaryVertex.secondaryVertex_EventSetup_cff")
0313             process.load("RecoBTag.SoftLepton.softLepton_EventSetup_cff")
0314             process.load("RecoBTag.Combined.combinedMVA_EventSetup_cff")
0315             process.load("RecoBTag.CTagging.cTagging_EventSetup_cff")
0316     import RecoBTag.Configuration.RecoBTag_cff as btag
0317     import RecoJets.JetProducers.caTopTaggers_cff as toptag
0318 
0319     if tightBTagNTkHits:
0320         if not runIVF:
0321             sys.stderr.write("-------------------------------------------------------------------\n")
0322             sys.stderr.write(" Warning: For a complete switch to the legacy tight b-tag track\n")
0323             sys.stderr.write("          selection, please also enable the \'runIVF\' switch.\n")
0324             sys.stderr.write("-------------------------------------------------------------------\n")
0325         if btagPrefix == '':
0326             sys.stderr.write("-------------------------------------------------------------------\n")
0327             sys.stderr.write(" Warning: With the tight b-tag track selection enabled, it is\n")
0328             sys.stderr.write("          advisable to set \'btagPrefix\' to a non-empty string to\n")
0329             sys.stderr.write("          avoid unintentional modifications to the default\n")
0330             sys.stderr.write("          b tagging setup that might be loaded in the same job.\n")
0331             sys.stderr.write("-------------------------------------------------------------------\n")
0332 
0333     ## define c tagging CvsL SV source (for now tied to the default SV source
0334     ## in the first part of the module label, product instance label and process name)
0335     svSourceCvsL = copy.deepcopy(svSource)
0336     svSourceCvsL.setModuleLabel(svSource.getModuleLabel()+'CvsL')
0337 
0338     ## check if and under what conditions to re-run IVF
0339     runIVFforCTagOnly = False
0340     ivfcTagInfos = ['pfInclusiveSecondaryVertexFinderCvsLTagInfos', 'pfInclusiveSecondaryVertexFinderNegativeCvsLTagInfos']
0341     ## if MiniAOD and running c tagging
0342     if pvSource.getModuleLabel() == 'offlineSlimmedPrimaryVertices' and any(i in requiredTagInfos for i in ivfcTagInfos) and not runIVF:
0343         runIVFforCTagOnly = True
0344         runIVF = True
0345         sys.stderr.write("-------------------------------------------------------------------\n")
0346         sys.stderr.write(" Info: To run c tagging on MiniAOD, c-tag-specific IVF secondary\n")
0347         sys.stderr.write("       vertices will be remade.\n")
0348         sys.stderr.write("-------------------------------------------------------------------\n")
0349     ## adjust svSources
0350     if runIVF and btagPrefix != '':
0351         if runIVFforCTagOnly:
0352             svSourceCvsL.setModuleLabel(btagPrefix+svSourceCvsL.getModuleLabel())
0353         else:
0354             svSource.setModuleLabel(btagPrefix+svSource.getModuleLabel())
0355             svSourceCvsL.setModuleLabel(btagPrefix+svSourceCvsL.getModuleLabel())
0356 
0357     ## setup all required btagInfos : we give a dedicated treatment for different
0358     ## types of tagInfos here. A common treatment is possible but might require a more
0359     ## general approach anyway in coordination with the btagging POG.
0360 
0361     runNegativeVertexing = False
0362     runNegativeCvsLVertexing = False
0363     for btagInfo in requiredTagInfos:
0364         if btagInfo in (
0365             'pfInclusiveSecondaryVertexFinderNegativeTagInfos',
0366             'pfNegativeDeepFlavourTagInfos',
0367             'pfNegativeParticleNetAK4TagInfos',
0368             ):
0369             runNegativeVertexing = True
0370         if btagInfo == 'pfInclusiveSecondaryVertexFinderNegativeCvsLTagInfos':
0371             runNegativeCvsLVertexing = True
0372             
0373     if runNegativeVertexing or runNegativeCvsLVertexing:
0374         import RecoVertex.AdaptiveVertexFinder.inclusiveNegativeVertexing_cff as NegVertex
0375 
0376     if runNegativeVertexing:                
0377         addToProcessAndTask(btagPrefix+'inclusiveCandidateNegativeVertexFinder'+labelName+postfix,
0378                             NegVertex.inclusiveCandidateNegativeVertexFinder.clone(primaryVertices = pvSource,tracks=pfCandidates),
0379                             process, task)
0380         addToProcessAndTask(btagPrefix+'candidateNegativeVertexMerger'+labelName+postfix,
0381                             NegVertex.candidateNegativeVertexMerger.clone(secondaryVertices = cms.InputTag(btagPrefix+'inclusiveCandidateNegativeVertexFinder'+labelName+postfix)),
0382                             process, task)
0383         addToProcessAndTask(btagPrefix+'candidateNegativeVertexArbitrator'+labelName+postfix,
0384                             NegVertex.candidateNegativeVertexArbitrator.clone( secondaryVertices = cms.InputTag(btagPrefix+'candidateNegativeVertexMerger'+labelName+postfix)
0385                                                                                ,primaryVertices = pvSource
0386                                                                                ,tracks=pfCandidates),
0387                             process, task)
0388         addToProcessAndTask(btagPrefix+'inclusiveCandidateNegativeSecondaryVertices'+labelName+postfix,
0389                             NegVertex.inclusiveCandidateNegativeSecondaryVertices.clone(secondaryVertices = cms.InputTag(btagPrefix+'candidateNegativeVertexArbitrator'+labelName+postfix)),
0390                             process, task)
0391 
0392     if runNegativeCvsLVertexing:
0393         addToProcessAndTask(btagPrefix+'inclusiveCandidateNegativeVertexFinderCvsL'+labelName+postfix,
0394                             NegVertex.inclusiveCandidateNegativeVertexFinderCvsL.clone(primaryVertices = pvSource,tracks=pfCandidates),
0395                             process, task)
0396         addToProcessAndTask(btagPrefix+'candidateNegativeVertexMergerCvsL'+labelName+postfix,
0397                             NegVertex.candidateNegativeVertexMergerCvsL.clone(secondaryVertices = cms.InputTag(btagPrefix+'inclusiveCandidateNegativeVertexFinderCvsL'+labelName+postfix)),
0398                             process, task)
0399         addToProcessAndTask(btagPrefix+'candidateNegativeVertexArbitratorCvsL'+labelName+postfix,
0400                             NegVertex.candidateNegativeVertexArbitratorCvsL.clone( secondaryVertices = cms.InputTag(btagPrefix+'candidateNegativeVertexMergerCvsL'+labelName+postfix)
0401                                                                                ,primaryVertices = pvSource
0402                                                                                ,tracks=pfCandidates),
0403                             process, task)
0404         addToProcessAndTask(btagPrefix+'inclusiveCandidateNegativeSecondaryVerticesCvsL'+labelName+postfix,
0405                             NegVertex.inclusiveCandidateNegativeSecondaryVerticesCvsL.clone(secondaryVertices = cms.InputTag(btagPrefix+'candidateNegativeVertexArbitratorCvsL'+labelName+postfix)),
0406                             process, task)
0407 
0408 
0409     # Setup the PUPPI ValueMap that will consumed by the TagInfo producers.
0410     puppi_value_map = "puppi"
0411     if pfCandidates.value() == 'packedPFCandidates':
0412         puppi_value_map = setupPuppiForPackedPF(process)[0]
0413 
0414     acceptedTagInfos = list()
0415     for btagInfo in requiredTagInfos:
0416         if hasattr(btag,btagInfo):
0417             if btagInfo == 'pfImpactParameterTagInfos':
0418                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0419                                     btag.pfImpactParameterTagInfos.clone(jets = jetSource,primaryVertex=pvSource,candidates=pfCandidates),
0420                                     process, task)
0421                 if explicitJTA:
0422                     _btagInfo = getattr(process, btagPrefix+btagInfo+labelName+postfix)
0423                     _btagInfo.explicitJTA = cms.bool(explicitJTA)
0424                 if tightBTagNTkHits:
0425                     _btagInfo = getattr(process, btagPrefix+btagInfo+labelName+postfix)
0426                     _btagInfo.minimumNumberOfPixelHits = cms.int32(2)
0427                     _btagInfo.minimumNumberOfHits = cms.int32(8)
0428             if btagInfo == 'pfImpactParameterAK8TagInfos':
0429                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0430                                     btag.pfImpactParameterAK8TagInfos.clone(jets = jetSource,primaryVertex=pvSource,candidates=pfCandidates),
0431                                     process, task)
0432                 if explicitJTA:
0433                     _btagInfo = getattr(process, btagPrefix+btagInfo+labelName+postfix)
0434                     _btagInfo.explicitJTA = cms.bool(explicitJTA)
0435                 if tightBTagNTkHits:
0436                     _btagInfo = getattr(process, btagPrefix+btagInfo+labelName+postfix)
0437                     _btagInfo.minimumNumberOfPixelHits = cms.int32(2)
0438                     _btagInfo.minimumNumberOfHits = cms.int32(8)
0439             if btagInfo == 'pfImpactParameterCA15TagInfos':
0440                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0441                                     btag.pfImpactParameterCA15TagInfos.clone(jets = jetSource,primaryVertex=pvSource,candidates=pfCandidates),
0442                                     process, task)
0443                 if explicitJTA:
0444                     _btagInfo = getattr(process, btagPrefix+btagInfo+labelName+postfix)
0445                     _btagInfo.explicitJTA = cms.bool(explicitJTA)
0446                 if tightBTagNTkHits:
0447                     _btagInfo = getattr(process, btagPrefix+btagInfo+labelName+postfix)
0448                     _btagInfo.minimumNumberOfPixelHits = cms.int32(2)
0449                     _btagInfo.minimumNumberOfHits = cms.int32(8)
0450             if btagInfo == 'pfSecondaryVertexTagInfos':
0451                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0452                                     btag.pfSecondaryVertexTagInfos.clone(
0453                                         trackIPTagInfos = cms.InputTag(btagPrefix+'pfImpactParameterTagInfos'+labelName+postfix)),
0454                                     process, task)
0455                 if tightBTagNTkHits:
0456                     _btagInfo = getattr(process, btagPrefix+btagInfo+labelName+postfix)
0457                     _btagInfo.trackSelection.pixelHitsMin = cms.uint32(2)
0458                     _btagInfo.trackSelection.totalHitsMin = cms.uint32(8)
0459             if btagInfo == 'pfDeepCSVTagInfos':
0460                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0461                                     btag.pfDeepCSVTagInfos.clone(
0462                                         svTagInfos = cms.InputTag(btagPrefix+'pfInclusiveSecondaryVertexFinderTagInfos'+labelName+postfix)),
0463                                     process, task)
0464             if btagInfo == 'pfDeepCSVNegativeTagInfos':
0465                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0466                                     btag.pfDeepCSVNegativeTagInfos.clone(
0467                                         svTagInfos = cms.InputTag(btagPrefix+'pfInclusiveSecondaryVertexFinderNegativeTagInfos'+labelName+postfix)),
0468                                     process, task)
0469             if btagInfo == 'pfDeepCSVPositiveTagInfos':
0470                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0471                                     btag.pfDeepCSVPositiveTagInfos.clone(
0472                                         svTagInfos = cms.InputTag(btagPrefix+'pfInclusiveSecondaryVertexFinderTagInfos'+labelName+postfix)),
0473                                     process, task)
0474             if btagInfo == 'pfDeepCMVATagInfos':
0475                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0476                                     btag.pfDeepCMVATagInfos.clone(
0477                                         deepNNTagInfos = cms.InputTag(btagPrefix+'pfDeepCSVTagInfos'+labelName+postfix),
0478                                         ipInfoSrc = cms.InputTag(btagPrefix+"pfImpactParameterTagInfos"+labelName+postfix),
0479                                         muInfoSrc = cms.InputTag(btagPrefix+"softPFMuonsTagInfos"+labelName+postfix),
0480                                         elInfoSrc = cms.InputTag(btagPrefix+"softPFElectronsTagInfos"+labelName+postfix)),
0481                                     process, task)
0482                 if svClustering or fatJets != cms.InputTag(''):
0483                     setupSVClustering(getattr(process, btagPrefix+btagInfo+labelName+postfix), svClustering, algo, rParam, fatJets, groomedFatJets)
0484             if btagInfo == 'pfDeepCMVANegativeTagInfos':
0485                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0486                                     btag.pfDeepCMVATagInfos.clone(
0487                                         deepNNTagInfos = cms.InputTag(btagPrefix+'pfDeepCSVTagInfos'+labelName+postfix),
0488                                         ipInfoSrc = cms.InputTag(btagPrefix+"pfImpactParameterTagInfos"+labelName+postfix),
0489                                         muInfoSrc = cms.InputTag(btagPrefix+"softPFMuonsTagInfos"+labelName+postfix),
0490                                         elInfoSrc = cms.InputTag(btagPrefix+"softPFElectronsTagInfos"+labelName+postfix)),
0491                                     process, task)
0492                 if svClustering or fatJets != cms.InputTag(''):
0493                     setupSVClustering(getattr(process, btagPrefix+btagInfo+labelName+postfix), svClustering, algo, rParam, fatJets, groomedFatJets)
0494             if btagInfo == 'pfDeepCMVAPositiveTagInfos':
0495                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0496                                     btag.pfDeepCMVATagInfos.clone(
0497                                         deepNNTagInfos = cms.InputTag(btagPrefix+'pfDeepCSVTagInfos'+labelName+postfix),
0498                                         ipInfoSrc = cms.InputTag(btagPrefix+"pfImpactParameterTagInfos"+labelName+postfix),
0499                                         muInfoSrc = cms.InputTag(btagPrefix+"softPFMuonsTagInfos"+labelName+postfix),
0500                                         elInfoSrc = cms.InputTag(btagPrefix+"softPFElectronsTagInfos"+labelName+postfix)),
0501                                     process, task)
0502                 if svClustering or fatJets != cms.InputTag(''):
0503                     setupSVClustering(getattr(process, btagPrefix+btagInfo+labelName+postfix), svClustering, algo, rParam, fatJets, groomedFatJets)     
0504             if btagInfo == 'pfInclusiveSecondaryVertexFinderTagInfos':
0505                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0506                                     btag.pfInclusiveSecondaryVertexFinderTagInfos.clone(
0507                                         trackIPTagInfos = cms.InputTag(btagPrefix+'pfImpactParameterTagInfos'+labelName+postfix),
0508                                         extSVCollection=svSource),
0509                                     process, task)
0510                 if svClustering or fatJets != cms.InputTag(''):
0511                     setupSVClustering(getattr(process, btagPrefix+btagInfo+labelName+postfix), svClustering, algo, rParam, fatJets, groomedFatJets)
0512             if btagInfo == 'pfInclusiveSecondaryVertexFinderAK8TagInfos':
0513                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0514                                     btag.pfInclusiveSecondaryVertexFinderAK8TagInfos.clone(
0515                                         trackIPTagInfos = cms.InputTag(btagPrefix+'pfImpactParameterAK8TagInfos'+labelName+postfix),
0516                                         extSVCollection=svSource),
0517                                     process, task)
0518                 if svClustering or fatJets != cms.InputTag(''):
0519                     setupSVClustering(getattr(process, btagPrefix+btagInfo+labelName+postfix), svClustering, algo, rParam, fatJets, groomedFatJets)
0520             if btagInfo == 'pfBoostedDoubleSVAK8TagInfos':
0521                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0522                                     btag.pfBoostedDoubleSVAK8TagInfos.clone(
0523                                         svTagInfos = cms.InputTag(btagPrefix+'pfInclusiveSecondaryVertexFinderAK8TagInfos'+labelName+postfix)),
0524                                     process, task)
0525             if btagInfo == 'pfInclusiveSecondaryVertexFinderCA15TagInfos':
0526                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0527                                     btag.pfInclusiveSecondaryVertexFinderCA15TagInfos.clone(
0528                                         trackIPTagInfos = cms.InputTag(btagPrefix+'pfImpactParameterCA15TagInfos'+labelName+postfix),
0529                                         extSVCollection=svSource),
0530                                     process, task)
0531                 if svClustering or fatJets != cms.InputTag(''):
0532                     setupSVClustering(getattr(process, btagPrefix+btagInfo+labelName+postfix), svClustering, algo, rParam, fatJets, groomedFatJets)
0533             if btagInfo == 'pfBoostedDoubleSVCA15TagInfos':
0534                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0535                                     btag.pfBoostedDoubleSVCA15TagInfos.clone(
0536                                         svTagInfos = cms.InputTag(btagPrefix+'pfInclusiveSecondaryVertexFinderCA15TagInfos'+labelName+postfix)),
0537                                     process, task)
0538             if btagInfo == 'pfInclusiveSecondaryVertexFinderCvsLTagInfos':
0539                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0540                                     btag.pfInclusiveSecondaryVertexFinderCvsLTagInfos.clone(
0541                                         trackIPTagInfos = cms.InputTag(btagPrefix+'pfImpactParameterTagInfos'+labelName+postfix),
0542                                         extSVCollection=svSourceCvsL),
0543                                     process, task)
0544                 if svClustering or fatJets != cms.InputTag(''):
0545                     setupSVClustering(getattr(process, btagPrefix+btagInfo+labelName+postfix), svClustering, algo, rParam, fatJets, groomedFatJets)
0546             if btagInfo == 'pfInclusiveSecondaryVertexFinderNegativeCvsLTagInfos':
0547                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0548                                     btag.pfInclusiveSecondaryVertexFinderNegativeCvsLTagInfos.clone(
0549                                         trackIPTagInfos = cms.InputTag(btagPrefix+'pfImpactParameterTagInfos'+labelName+postfix),
0550                                         extSVCollection = btagPrefix+'inclusiveCandidateNegativeSecondaryVerticesCvsL'+labelName+postfix),
0551                                     process, task)
0552                 if svClustering or fatJets != cms.InputTag(''):
0553                     setupSVClustering(getattr(process, btagPrefix+btagInfo+labelName+postfix), svClustering, algo, rParam, fatJets, groomedFatJets)
0554             if btagInfo == 'pfGhostTrackVertexTagInfos':
0555                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0556                                     btag.pfGhostTrackVertexTagInfos.clone(
0557                                         trackIPTagInfos = cms.InputTag(btagPrefix+'pfImpactParameterTagInfos'+labelName+postfix)),
0558                                     process, task)
0559             if btagInfo == 'pfSecondaryVertexNegativeTagInfos':
0560                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0561                                     btag.pfSecondaryVertexNegativeTagInfos.clone(
0562                                         trackIPTagInfos = cms.InputTag(btagPrefix+'pfImpactParameterTagInfos'+labelName+postfix)),
0563                                     process, task)
0564                 if tightBTagNTkHits:
0565                     _btagInfo = getattr(process, btagPrefix+btagInfo+labelName+postfix)
0566                     _btagInfo.trackSelection.pixelHitsMin = cms.uint32(2)
0567                     _btagInfo.trackSelection.totalHitsMin = cms.uint32(8)
0568             if btagInfo == 'pfInclusiveSecondaryVertexFinderNegativeTagInfos':
0569                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0570                                     btag.pfInclusiveSecondaryVertexFinderNegativeTagInfos.clone(
0571                                         trackIPTagInfos = cms.InputTag(btagPrefix+'pfImpactParameterTagInfos'+labelName+postfix),
0572                                         extSVCollection=cms.InputTag(btagPrefix+'inclusiveCandidateNegativeSecondaryVertices'+labelName+postfix)),
0573                                     process, task)
0574                 if svClustering or fatJets != cms.InputTag(''):
0575                     setupSVClustering(getattr(process, btagPrefix+btagInfo+labelName+postfix), svClustering, algo, rParam, fatJets, groomedFatJets)
0576             if btagInfo == 'impactParameterTagInfos':
0577                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix, 
0578                                     btag.impactParameterTagInfos.clone(
0579                                         jetTracks = cms.InputTag('jetTracksAssociatorAtVertex'+labelName+postfix),
0580                                         primaryVertex=pvSource),
0581                                     process, task)
0582             if btagInfo == 'secondaryVertexTagInfos':
0583                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0584                                     btag.secondaryVertexTagInfos.clone(
0585                                         trackIPTagInfos = cms.InputTag(btagPrefix+'impactParameterTagInfos'+labelName+postfix)),
0586                                     process, task)
0587             if btagInfo == 'inclusiveSecondaryVertexFinderTagInfos':
0588                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0589                                     btag.inclusiveSecondaryVertexFinderTagInfos.clone(
0590                                         trackIPTagInfos = cms.InputTag(btagPrefix+'impactParameterTagInfos'+labelName+postfix)),
0591                                     process, task)
0592                 if svClustering or fatJets != cms.InputTag(''):
0593                     setupSVClustering(getattr(process, btagPrefix+btagInfo+labelName+postfix), svClustering, algo, rParam, fatJets, groomedFatJets)
0594             if btagInfo == 'inclusiveSecondaryVertexFinderFilteredTagInfos':
0595                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0596                                     btag.inclusiveSecondaryVertexFinderFilteredTagInfos.clone(
0597                                         trackIPTagInfos = cms.InputTag(btagPrefix+'impactParameterTagInfos'+labelName+postfix)),
0598                                     process, task)
0599                 if svClustering or fatJets != cms.InputTag(''):
0600                     setupSVClustering(getattr(process, btagPrefix+btagInfo+labelName+postfix), svClustering, algo, rParam, fatJets, groomedFatJets)
0601             if btagInfo == 'secondaryVertexNegativeTagInfos':
0602                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0603                                     btag.secondaryVertexNegativeTagInfos.clone(
0604                                         trackIPTagInfos = cms.InputTag(btagPrefix+'impactParameterTagInfos'+labelName+postfix)),
0605                                     process, task)
0606             if btagInfo == 'inclusiveSecondaryVertexFinderNegativeTagInfos':
0607                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0608                                     btag.inclusiveSecondaryVertexFinderNegativeTagInfos.clone(
0609                                         trackIPTagInfos = cms.InputTag(btagPrefix+'impactParameterTagInfos'+labelName+postfix)),
0610                                     process, task)
0611                 if svClustering or fatJets != cms.InputTag(''):
0612                     setupSVClustering(getattr(process, btagPrefix+btagInfo+labelName+postfix), svClustering, algo, rParam, fatJets, groomedFatJets)
0613             if btagInfo == 'inclusiveSecondaryVertexFinderFilteredNegativeTagInfos':
0614                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0615                                     btag.inclusiveSecondaryVertexFinderFilteredNegativeTagInfos.clone(
0616                                         trackIPTagInfos = cms.InputTag(btagPrefix+'impactParameterTagInfos'+labelName+postfix)),
0617                                     process, task)
0618                 if svClustering or fatJets != cms.InputTag(''):
0619                     setupSVClustering(getattr(process, btagPrefix+btagInfo+labelName+postfix), svClustering, algo, rParam, fatJets, groomedFatJets)
0620             if btagInfo == 'softMuonTagInfos':
0621                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0622                                     btag.softMuonTagInfos.clone(jets = jetSource, primaryVertex=pvSource),
0623                                     process, task)
0624             if btagInfo == 'softPFMuonsTagInfos':
0625                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0626                                     btag.softPFMuonsTagInfos.clone(jets = jetSource, primaryVertex=pvSource, muons=muSource),
0627                                     process, task)
0628             if btagInfo == 'softPFElectronsTagInfos':
0629                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0630                                     btag.softPFElectronsTagInfos.clone(jets = jetSource, primaryVertex=pvSource, electrons=elSource),
0631                                     process, task)
0632             if btagInfo == 'pixelClusterTagInfos':
0633                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0634                                     btag.pixelClusterTagInfos.clone(jets = jetSource, vertices=pvSource),
0635                                     process, task)
0636 
0637 
0638             if 'pfBoostedDouble' in btagInfo or 'SecondaryVertex' in btagInfo:
0639                 _btagInfo = getattr(process, btagPrefix+btagInfo+labelName+postfix)
0640                 _btagInfo.weights = cms.InputTag(puppi_value_map)
0641 
0642             if 'DeepFlavourTagInfos' in btagInfo:
0643                 svUsed = svSource
0644                 if btagInfo == 'pfNegativeDeepFlavourTagInfos':
0645                     deep_csv_tag_infos = 'pfDeepCSVNegativeTagInfos'
0646                     svUsed = cms.InputTag(btagPrefix+'inclusiveCandidateNegativeSecondaryVertices'+labelName+postfix)
0647                     flip = True 
0648                 else:
0649                     deep_csv_tag_infos = 'pfDeepCSVTagInfos'
0650                     flip = False
0651 
0652                 # use right input tags when running with RECO PF candidates, which actually
0653                 # depends of whether jets use "particleFlow"
0654                 if pfCandidates.value() == 'packedPFCandidates':
0655                     vertex_associator = cms.InputTag("")
0656                 else:
0657                     vertex_associator = cms.InputTag("primaryVertexAssociation","original")
0658 
0659                 # If this jet is a puppi jet, then set is_weighted_jet to true.
0660                 is_weighted_jet = False
0661                 if ('puppi' in jetSource.value().lower()):
0662                     is_weighted_jet = True
0663                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0664                                     btag.pfDeepFlavourTagInfos.clone(
0665                                       jets = jetSource,
0666                                       vertices=pvSource,
0667                                       secondary_vertices=svUsed,
0668                                       shallow_tag_infos = cms.InputTag(btagPrefix+deep_csv_tag_infos+labelName+postfix),
0669                                       puppi_value_map = puppi_value_map,
0670                                       vertex_associator = vertex_associator,
0671                                       is_weighted_jet = is_weighted_jet,
0672                                       flip = flip),
0673                                     process, task)
0674 
0675             if ('ParticleTransformerAK4TagInfos' in btagInfo) and ('UnifiedParticleTransformerAK4TagInfos' not in btagInfo): #We also have to veto UParT is we select ParT
0676                 svUsed = svSource
0677                 if btagInfo == 'pfNegativeParticleTransformerAK4TagInfos':
0678                     svUsed, flip, max_sip3dsig_for_flip = cms.InputTag(btagPrefix+'inclusiveCandidateNegativeSecondaryVertices'+labelName+postfix), True, 10.
0679                 else:
0680                     svUsed, flip, max_sip3dsig_for_flip = svSource, False, -1.
0681                 # use right input tags when running with RECO PF candidates, which actually
0682                 # depends of whether jets use "particleFlow"
0683                 if pfCandidates.value() == 'packedPFCandidates':
0684                     vertex_associator = cms.InputTag("")
0685                 else:
0686                     vertex_associator = cms.InputTag("primaryVertexAssociation","original")
0687 
0688                 # If this jet is a puppi jet, then set is_weighted_jet to true.
0689                 is_weighted_jet = False
0690                 if ('puppi' in jetSource.value().lower()):
0691                     is_weighted_jet = True
0692                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0693                                     btag.pfParticleTransformerAK4TagInfos.clone(
0694                                       jets = jetSource,
0695                                       vertices=pvSource,
0696                                       secondary_vertices=svUsed,
0697                                       puppi_value_map = puppi_value_map,
0698                                       vertex_associator = vertex_associator,
0699                                       is_weighted_jet = is_weighted_jet,
0700                                       flip = flip,
0701                                       max_sip3dsig_for_flip=max_sip3dsig_for_flip),
0702                                     process, task)
0703                 
0704             if 'UnifiedParticleTransformerAK4TagInfos' in btagInfo:
0705                 svUsed = svSource
0706                 if btagInfo == 'pfNegativeUnifiedParticleTransformerAK4TagInfos':
0707                     svUsed = cms.InputTag(btagPrefix+'inclusiveCandidateNegativeSecondaryVertices'+labelName+postfix)
0708                     flip = True 
0709                 else:
0710                     flip = False
0711                 # use right input tags when running with RECO PF candidates, which actually
0712                 # depends of whether jets use "particleFlow"
0713                 if pfCandidates.value() == 'packedPFCandidates':
0714                     vertex_associator = cms.InputTag("")
0715                 else:
0716                     vertex_associator = cms.InputTag("primaryVertexAssociation","original")
0717 
0718                 # If this jet is a puppi jet, then set is_weighted_jet to true.
0719                 is_weighted_jet = False
0720                 if ('puppi' in jetSource.value().lower()):
0721                     is_weighted_jet = True
0722                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0723                                     btag.pfUnifiedParticleTransformerAK4TagInfos.clone(
0724                                       jets = jetSource,
0725                                       vertices=pvSource,
0726                                       secondary_vertices=svUsed,
0727                                       puppi_value_map = puppi_value_map,
0728                                       vertex_associator = vertex_associator,
0729                                       is_weighted_jet = is_weighted_jet,
0730                                       flip = flip),
0731                                     process, task)
0732 
0733             if 'UnifiedParticleTransformerAK4V1TagInfos' in btagInfo:
0734                 svUsed = svSource
0735                 if btagInfo == 'pfNegativeUnifiedParticleTransformerAK4V1TagInfos':
0736                     svUsed = cms.InputTag(btagPrefix+'inclusiveCandidateNegativeSecondaryVertices'+labelName+postfix)
0737                     flip = True 
0738                 else:
0739                     flip = False
0740                 # use right input tags when running with RECO PF candidates, which actually
0741                 # depends of whether jets use "particleFlow"
0742                 if pfCandidates.value() == 'packedPFCandidates':
0743                     puppi_value_map = setupPuppiForPackedPF(process)[0]
0744                     vertex_associator = cms.InputTag("")
0745                 else:
0746                     puppi_value_map = cms.InputTag("puppi")
0747                     vertex_associator = cms.InputTag("primaryVertexAssociation","original")
0748 
0749                 # If this jet is a puppi jet, then set is_weighted_jet to true.
0750                 is_weighted_jet = False
0751                 if ('puppi' in jetSource.value().lower()):
0752                     is_weighted_jet = True
0753                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0754                                     btag.pfUnifiedParticleTransformerAK4V1TagInfos.clone(
0755                                         jets = jetSource,
0756                                         vertices=pvSource,
0757                                         secondary_vertices=svUsed,
0758                                         puppi_value_map = puppi_value_map,
0759                                         vertex_associator = vertex_associator,
0760                                         is_weighted_jet = is_weighted_jet,
0761                                         flip = flip),
0762                                     process, task)              
0763 
0764             if btagInfo == 'pfDeepDoubleXTagInfos':
0765                 # can only run on PAT jets, so the updater needs to be used
0766                 if 'updated' not in jetSource.value().lower():
0767                     raise ValueError("Invalid jet collection: %s. pfDeepDoubleXTagInfos only supports running via updateJetCollection." % jetSource.value())
0768                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0769                                     btag.pfDeepDoubleXTagInfos.clone(
0770                                       jets = jetSource,
0771                                       vertices=pvSource,
0772                                       secondary_vertices=svSource,
0773                                       shallow_tag_infos = cms.InputTag(btagPrefix+'pfBoostedDoubleSVAK8TagInfos'+labelName+postfix),
0774                                       puppi_value_map = puppi_value_map,
0775                                       ),
0776                                     process, task)
0777             if btagInfo == 'pfHiggsInteractionNetTagInfos':
0778                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0779                                     btag.pfHiggsInteractionNetTagInfos.clone(
0780                                       jets = jetSource,
0781                                       vertices = pvSource,
0782                                       secondary_vertices = svSource,
0783                                       pf_candidates = pfCandidates,
0784                                       puppi_value_map = puppi_value_map
0785                                       ),
0786                                     process, task)
0787 
0788             if btagInfo == 'pfDeepBoostedJetTagInfos':
0789                 if pfCandidates.value() == 'packedPFCandidates':
0790                     # case 1: running over jets whose daughters are PackedCandidates (only via updateJetCollection for now)
0791                     if 'updated' not in jetSource.value().lower():
0792                         raise ValueError("Invalid jet collection: %s. pfDeepBoostedJetTagInfos only supports running via updateJetCollection." % jetSource.value())
0793                     vertex_associator = ""
0794                 elif pfCandidates.value() == 'particleFlow':
0795                     raise ValueError("Running pfDeepBoostedJetTagInfos with reco::PFCandidates is currently not supported.")
0796                     # case 2: running on new jet collection whose daughters are PFCandidates (e.g., cluster jets in RECO/AOD)
0797                     # daughters are the particles used in jet clustering, so already scaled by their puppi weights
0798                     # Uncomment the lines below after running pfDeepBoostedJetTagInfos with reco::PFCandidates becomes supported
0799 #                     vertex_associator = "primaryVertexAssociation:original"
0800                 else:
0801                     raise ValueError("Invalid pfCandidates collection: %s." % pfCandidates.value())
0802                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0803                                     btag.pfDeepBoostedJetTagInfos.clone(
0804                                       jets = jetSource,
0805                                       vertices = pvSource,
0806                                       secondary_vertices = svSource,
0807                                       pf_candidates = pfCandidates,
0808                                       puppi_value_map = puppi_value_map,
0809                                       vertex_associator = vertex_associator,
0810                                       ),
0811                                     process, task)
0812 
0813             if btagInfo == 'pfParticleNetTagInfos' or btagInfo == 'pfGlobalParticleTransformerAK8TagInfos':
0814                 if pfCandidates.value() == 'packedPFCandidates':
0815                     # case 1: running over jets whose daughters are PackedCandidates (only via updateJetCollection for now)
0816                     vertex_associator = ""
0817                 elif pfCandidates.value() == 'particleFlow':
0818                     raise ValueError("Running pfDeepBoostedJetTagInfos with reco::PFCandidates is currently not supported.")
0819                     # case 2: running on new jet collection whose daughters are PFCandidates (e.g., cluster jets in RECO/AOD)
0820                     vertex_associator = "primaryVertexAssociation:original"
0821                 else:
0822                     raise ValueError("Invalid pfCandidates collection: %s." % pfCandidates.value())
0823                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0824                                     getattr(btag, btagInfo).clone(
0825                                       jets = jetSource,
0826                                       vertices = pvSource,
0827                                       secondary_vertices = svSource,
0828                                       pf_candidates = pfCandidates,
0829                                       puppi_value_map = puppi_value_map,
0830                                       vertex_associator = vertex_associator,
0831                                       ),
0832                                     process, task)
0833 
0834             if 'ParticleNetAK4TagInfos' in btagInfo:
0835                 if btagInfo == 'pfNegativeParticleNetAK4TagInfos':
0836                     secondary_vertices = btagPrefix + \
0837                         'inclusiveCandidateNegativeSecondaryVertices' + labelName + postfix
0838                     flip_ip_sign = True
0839                     sip3dSigMax = 10
0840                 else:
0841                     secondary_vertices = svSource
0842                     flip_ip_sign = False
0843                     sip3dSigMax = -1
0844                 if pfCandidates.value() == 'packedPFCandidates':
0845                     # case 1: running over jets whose daughters are PackedCandidates (only via updateJetCollection for now)
0846                     vertex_associator = ""
0847                 elif pfCandidates.value() == 'particleFlow':
0848                     raise ValueError("Running pfDeepBoostedJetTagInfos with reco::PFCandidates is currently not supported.")
0849                     # case 2: running on new jet collection whose daughters are PFCandidates (e.g., cluster jets in RECO/AOD)
0850                     vertex_associator = "primaryVertexAssociation:original"
0851                 else:
0852                     raise ValueError("Invalid pfCandidates collection: %s." % pfCandidates.value())
0853                 # If this jet is a Puppi jet, use puppi-weighted p4.
0854                 use_puppiP4 = False
0855                 if "puppi" in jetSource.value().lower():
0856                     use_puppiP4 = True
0857                 addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0858                                     btag.pfParticleNetAK4TagInfos.clone(
0859                                       jets = jetSource,
0860                                       vertices = pvSource,
0861                                       secondary_vertices = secondary_vertices,
0862                                       pf_candidates = pfCandidates,
0863                                       puppi_value_map = puppi_value_map,
0864                                       vertex_associator = vertex_associator,
0865                                       flip_ip_sign = flip_ip_sign,
0866                                       sip3dSigMax = sip3dSigMax,
0867                                       use_puppiP4 = use_puppiP4
0868                                       ),
0869                                     process, task)
0870 
0871             acceptedTagInfos.append(btagInfo)
0872         elif hasattr(toptag, btagInfo) :
0873             acceptedTagInfos.append(btagInfo)
0874         elif btagInfo == 'pfParticleNetFromMiniAODAK4PuppiCentralTagInfos' or btagInfo == 'pfNegativeParticleNetFromMiniAODAK4PuppiCentralTagInfos':
0875             # ParticleNetFromMiniAOD cannot be run on RECO inputs, so need a workaround
0876             if btagInfo == 'pfNegativeParticleNetFromMiniAODAK4PuppiCentralTagInfos':
0877                 svUsed, flip_ip_sign, max_sip3dsig_for_flip = cms.InputTag(btagPrefix+'inclusiveCandidateNegativeSecondaryVertices'+labelName+postfix), True, 10.
0878             else:
0879                 svUsed, flip_ip_sign, max_sip3dsig_for_flip = svSource, False, -1.
0880             if pfCandidates.value() != 'packedPFCandidates':
0881                 raise ValueError("Invalid pfCandidates collection: %s." % pfCandidates.value())
0882             addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0883                                 pfParticleNetFromMiniAODAK4PuppiCentralTagInfos.clone(
0884                                   jets = jetSource,
0885                                   vertices = pvSource,
0886                                   secondary_vertices = svUsed,
0887                                   pf_candidates = pfCandidates,
0888                                   puppi_value_map = puppi_value_map,
0889                                   flip_ip_sign = flip_ip_sign,
0890                                   max_sip3dsig_for_flip = max_sip3dsig_for_flip,
0891                                   ),
0892                                 process, task)
0893             acceptedTagInfos.append(btagInfo)
0894         elif btagInfo == 'pfParticleNetFromMiniAODAK4PuppiForwardTagInfos':
0895             # ParticleNetFromMiniAOD cannot be run on RECO inputs, so need a workaround
0896             if pfCandidates.value() != 'packedPFCandidates':
0897                 raise ValueError("Invalid pfCandidates collection: %s." % pfCandidates.value())
0898             addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0899                                 pfParticleNetFromMiniAODAK4PuppiForwardTagInfos.clone(
0900                                   jets = jetSource,
0901                                   vertices = pvSource,
0902                                   secondary_vertices = svSource,
0903                                   pf_candidates = pfCandidates,
0904                                   puppi_value_map = puppi_value_map
0905                                   ),
0906                                 process, task)
0907             acceptedTagInfos.append(btagInfo)
0908         elif btagInfo == 'pfParticleNetFromMiniAODAK4CHSCentralTagInfos' or btagInfo == 'pfNegativeParticleNetFromMiniAODAK4CHSCentralTagInfos':
0909             # ParticleNetFromMiniAOD cannot be run on RECO inputs, so need a workaround
0910             if btagInfo == 'pfNegativeParticleNetFromMiniAODAK4CHSCentralTagInfos':
0911                 svUsed, flip_ip_sign, max_sip3dsig_for_flip = cms.InputTag(btagPrefix+'inclusiveCandidateNegativeSecondaryVertices'+labelName+postfix), True, 10.
0912             else:
0913                 svUsed, flip_ip_sign, max_sip3dsig_for_flip = svSource, False, -1.
0914             if pfCandidates.value() != 'packedPFCandidates':
0915                 raise ValueError("Invalid pfCandidates collection: %s." % pfCandidates.value())
0916             addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0917                                 pfParticleNetFromMiniAODAK4CHSCentralTagInfos.clone(
0918                                   jets = jetSource,
0919                                   vertices = pvSource,
0920                                   secondary_vertices = svUsed,
0921                                   pf_candidates = pfCandidates,
0922                                   puppi_value_map = puppi_value_map,
0923                                   flip_ip_sign = flip_ip_sign,
0924                                   max_sip3dsig_for_flip = max_sip3dsig_for_flip,
0925                                   ),
0926                                 process, task)
0927             acceptedTagInfos.append(btagInfo)
0928         elif btagInfo == 'pfParticleNetFromMiniAODAK4CHSForwardTagInfos':
0929             # ParticleNetFromMiniAOD cannot be run on RECO inputs, so need a workaround
0930             if pfCandidates.value() != 'packedPFCandidates':
0931                 raise ValueError("Invalid pfCandidates collection: %s." % pfCandidates.value())
0932             addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0933                                 pfParticleNetFromMiniAODAK4CHSForwardTagInfos.clone(
0934                                   jets = jetSource,
0935                                   vertices = pvSource,
0936                                   secondary_vertices = svSource,
0937                                   pf_candidates = pfCandidates,
0938                                   puppi_value_map = puppi_value_map,
0939                                   ),
0940                                 process, task)
0941             acceptedTagInfos.append(btagInfo)
0942         elif btagInfo == 'pfParticleNetFromMiniAODAK8TagInfos':
0943             # ParticleNetFromMiniAOD cannot be run on RECO inputs, so need a workaround
0944             if pfCandidates.value() != 'packedPFCandidates':
0945                 raise ValueError("Invalid pfCandidates collection: %s." % pfCandidates.value())
0946             addToProcessAndTask(btagPrefix+btagInfo+labelName+postfix,
0947                                 pfParticleNetFromMiniAODAK8TagInfos.clone(
0948                                   jets = jetSource,
0949                                   vertices = pvSource,
0950                                   secondary_vertices = svSource,
0951                                   pf_candidates = pfCandidates,
0952                                   puppi_value_map = puppi_value_map,
0953                                   ),
0954                                 process, task)
0955             acceptedTagInfos.append(btagInfo)
0956         else:
0957             print('  --> %s ignored, since not available via RecoBTag.Configuration.RecoBTag_cff!'%(btagInfo))
0958     # setup all required btagDiscriminators
0959     acceptedBtagDiscriminators = list()
0960     for discriminator_name in btagDiscriminators :
0961         btagDiscr = discriminator_name.split(':')[0] #split input tag to get the producer label
0962         #print discriminator_name, '-->', btagDiscr
0963         newDiscr = btagPrefix+btagDiscr+labelName+postfix #new discriminator name
0964         if hasattr(btag,btagDiscr): 
0965             if hasattr(process, newDiscr):
0966                 pass 
0967             elif hasattr(getattr(btag, btagDiscr), 'tagInfos'):
0968                 addToProcessAndTask(
0969                     newDiscr,
0970                     getattr(btag, btagDiscr).clone(
0971                         tagInfos = cms.VInputTag(
0972                             *[ cms.InputTag(btagPrefix+x+labelName+postfix) \
0973                             for x in supportedBtagDiscr[discriminator_name][0] ]
0974                         )
0975                     ),
0976                     process,
0977                     task
0978                 )
0979             elif hasattr(getattr(btag, btagDiscr), 'src'):
0980                 addToProcessAndTask(
0981                     newDiscr,
0982                     getattr(btag, btagDiscr).clone(
0983                         src = cms.InputTag(btagPrefix+supportedBtagDiscr[discriminator_name][0][0]+labelName+postfix)
0984                     ),
0985                     process,
0986                     task
0987                 )
0988             else:
0989                 raise ValueError('I do not know how to update %s it does not have neither "tagInfos" nor "src" attributes' % btagDiscr)
0990             acceptedBtagDiscriminators.append(discriminator_name)
0991         elif btagDiscr=='pfParticleNetFromMiniAODAK4PuppiCentralJetTags':
0992             if hasattr(process, newDiscr):
0993                 pass
0994             addToProcessAndTask(
0995                 newDiscr,
0996                 pfParticleNetFromMiniAODAK4PuppiCentralJetTags.clone(
0997                     src = cms.InputTag(btagPrefix+supportedBtagDiscr[discriminator_name][0][0]+labelName+postfix)
0998                 ),
0999                 process,
1000                 task
1001             )
1002             acceptedBtagDiscriminators.append(discriminator_name)
1003         elif btagDiscr=='pfNegativeParticleNetFromMiniAODAK4PuppiCentralJetTags':
1004             if hasattr(process, newDiscr):
1005                 pass
1006             addToProcessAndTask(
1007                 newDiscr,
1008                 pfNegativeParticleNetFromMiniAODAK4PuppiCentralJetTags.clone(
1009                     src = cms.InputTag(btagPrefix+supportedBtagDiscr[discriminator_name][0][0]+labelName+postfix)
1010                 ),
1011                 process,
1012                 task
1013             )
1014             acceptedBtagDiscriminators.append(discriminator_name)
1015         elif btagDiscr=='pfParticleNetFromMiniAODAK4PuppiForwardJetTags':
1016             if hasattr(process, newDiscr):
1017                 pass
1018             addToProcessAndTask(
1019                 newDiscr,
1020                 pfParticleNetFromMiniAODAK4PuppiForwardJetTags.clone(
1021                     src = cms.InputTag(btagPrefix+supportedBtagDiscr[discriminator_name][0][0]+labelName+postfix)
1022                 ),
1023                 process,
1024                 task
1025             )
1026             acceptedBtagDiscriminators.append(discriminator_name)
1027         elif btagDiscr=='pfParticleNetFromMiniAODAK4CHSCentralJetTags':
1028             if hasattr(process, newDiscr):
1029                 pass
1030             addToProcessAndTask(
1031                 newDiscr,
1032                 pfParticleNetFromMiniAODAK4CHSCentralJetTags.clone(
1033                     src = cms.InputTag(btagPrefix+supportedBtagDiscr[discriminator_name][0][0]+labelName+postfix)
1034                 ),
1035                 process,
1036                 task
1037             )
1038             acceptedBtagDiscriminators.append(discriminator_name)
1039         elif btagDiscr=='pfNegativeParticleNetFromMiniAODAK4CHSCentralJetTags':
1040             if hasattr(process, newDiscr):
1041                 pass
1042             addToProcessAndTask(
1043                 newDiscr,
1044                 pfNegativeParticleNetFromMiniAODAK4CHSCentralJetTags.clone(
1045                     src = cms.InputTag(btagPrefix+supportedBtagDiscr[discriminator_name][0][0]+labelName+postfix)
1046                 ),
1047                 process,
1048                 task
1049             )
1050             acceptedBtagDiscriminators.append(discriminator_name)
1051         elif btagDiscr=='pfParticleNetFromMiniAODAK4CHSForwardJetTags':
1052             if hasattr(process, newDiscr):
1053                 pass
1054             addToProcessAndTask(
1055                 newDiscr,
1056                 pfParticleNetFromMiniAODAK4CHSForwardJetTags.clone(
1057                     src = cms.InputTag(btagPrefix+supportedBtagDiscr[discriminator_name][0][0]+labelName+postfix)
1058                 ),
1059                 process,
1060                 task
1061             )
1062             acceptedBtagDiscriminators.append(discriminator_name)
1063         elif btagDiscr=='pfParticleNetFromMiniAODAK8JetTags':
1064             if hasattr(process, newDiscr):
1065                 pass
1066             addToProcessAndTask(
1067                 newDiscr,
1068                 pfParticleNetFromMiniAODAK8JetTags.clone(
1069                     src = cms.InputTag(btagPrefix+supportedBtagDiscr[discriminator_name][0][0]+labelName+postfix)
1070                 ),
1071                 process,
1072                 task
1073             )
1074             acceptedBtagDiscriminators.append(discriminator_name)
1075         else:
1076             print('  --> %s ignored, since not available via RecoBTag.Configuration.RecoBTag_cff!'%(btagDiscr))
1077             
1078     #update meta-taggers, if any
1079     for meta_tagger in present_meta:
1080         btagDiscr = meta_tagger.split(':')[0] #split input tag to get the producer label
1081         #print discriminator_name, '-->', btagDiscr
1082         newDiscr = btagPrefix+btagDiscr+labelName+postfix #new discriminator name
1083         if hasattr(btag,btagDiscr): 
1084             if hasattr(process, newDiscr):
1085                 pass 
1086             else:
1087                 addToProcessAndTask(
1088                     newDiscr,
1089                     getattr(btag, btagDiscr).clone(),
1090                     process,
1091                     task
1092                 )
1093                 for dependency in supportedMetaDiscr[meta_tagger]:
1094                     if ':' in dependency:
1095                         new_dep = btagPrefix+dependency.split(':')[0]+labelName+postfix+':'+dependency.split(':')[1]
1096                     else:
1097                         new_dep = btagPrefix+dependency+labelName+postfix
1098                     replace = MassSearchReplaceAnyInputTagVisitor(dependency, new_dep)
1099                     replace.doIt(getattr(process, newDiscr), newDiscr)
1100             acceptedBtagDiscriminators.append(meta_tagger)
1101         elif btagDiscr=='pfParticleNetFromMiniAODAK4PuppiCentralDiscriminatorsJetTags':
1102             if hasattr(process, newDiscr):
1103                 pass 
1104             else:
1105                 addToProcessAndTask(
1106                     newDiscr,
1107                     pfParticleNetFromMiniAODAK4PuppiCentralDiscriminatorsJetTags.clone(),
1108                     process,
1109                     task
1110                 )
1111                 for dependency in supportedMetaDiscr[meta_tagger]:
1112                     if ':' in dependency:
1113                         new_dep = btagPrefix+dependency.split(':')[0]+labelName+postfix+':'+dependency.split(':')[1]
1114                     else:
1115                         new_dep = btagPrefix+dependency+labelName+postfix
1116                     replace = MassSearchReplaceAnyInputTagVisitor(dependency, new_dep)
1117                     replace.doIt(getattr(process, newDiscr), newDiscr)
1118             acceptedBtagDiscriminators.append(meta_tagger)
1119         elif btagDiscr=='pfParticleNetFromMiniAODAK4PuppiForwardDiscriminatorsJetTags':
1120             if hasattr(process, newDiscr):
1121                 pass 
1122             else:
1123                 addToProcessAndTask(
1124                     newDiscr,
1125                     pfParticleNetFromMiniAODAK4PuppiForwardDiscriminatorsJetTags.clone(),
1126                     process,
1127                     task
1128                 )
1129                 for dependency in supportedMetaDiscr[meta_tagger]:
1130                     if ':' in dependency:
1131                         new_dep = btagPrefix+dependency.split(':')[0]+labelName+postfix+':'+dependency.split(':')[1]
1132                     else:
1133                         new_dep = btagPrefix+dependency+labelName+postfix
1134                     replace = MassSearchReplaceAnyInputTagVisitor(dependency, new_dep)
1135                     replace.doIt(getattr(process, newDiscr), newDiscr)
1136             acceptedBtagDiscriminators.append(meta_tagger)
1137         elif btagDiscr=='pfParticleNetFromMiniAODAK4CHSCentralDiscriminatorsJetTags':
1138             if hasattr(process, newDiscr):
1139                 pass 
1140             else:
1141                 addToProcessAndTask(
1142                     newDiscr,
1143                     pfParticleNetFromMiniAODAK4CHSCentralDiscriminatorsJetTags.clone(),
1144                     process,
1145                     task
1146                 )
1147                 for dependency in supportedMetaDiscr[meta_tagger]:
1148                     if ':' in dependency:
1149                         new_dep = btagPrefix+dependency.split(':')[0]+labelName+postfix+':'+dependency.split(':')[1]
1150                     else:
1151                         new_dep = btagPrefix+dependency+labelName+postfix
1152                     replace = MassSearchReplaceAnyInputTagVisitor(dependency, new_dep)
1153                     replace.doIt(getattr(process, newDiscr), newDiscr)
1154             acceptedBtagDiscriminators.append(meta_tagger)
1155         elif btagDiscr=='pfParticleNetFromMiniAODAK4CHSForwardDiscriminatorsJetTags':
1156             if hasattr(process, newDiscr):
1157                 pass 
1158             else:
1159                 addToProcessAndTask(
1160                     newDiscr,
1161                     pfParticleNetFromMiniAODAK4CHSForwardDiscriminatorsJetTags.clone(),
1162                     process,
1163                     task
1164                 )
1165                 for dependency in supportedMetaDiscr[meta_tagger]:
1166                     if ':' in dependency:
1167                         new_dep = btagPrefix+dependency.split(':')[0]+labelName+postfix+':'+dependency.split(':')[1]
1168                     else:
1169                         new_dep = btagPrefix+dependency+labelName+postfix
1170                     replace = MassSearchReplaceAnyInputTagVisitor(dependency, new_dep)
1171                     replace.doIt(getattr(process, newDiscr), newDiscr)
1172             acceptedBtagDiscriminators.append(meta_tagger)
1173         elif btagDiscr=='pfParticleNetFromMiniAODAK8DiscriminatorsJetTags':
1174             if hasattr(process, newDiscr):
1175                 pass 
1176             else:
1177                 addToProcessAndTask(
1178                     newDiscr,
1179                     pfParticleNetFromMiniAODAK8DiscriminatorsJetTags.clone(),
1180                     process,
1181                     task
1182                 )
1183                 for dependency in supportedMetaDiscr[meta_tagger]:
1184                     if ':' in dependency:
1185                         new_dep = btagPrefix+dependency.split(':')[0]+labelName+postfix+':'+dependency.split(':')[1]
1186                     else:
1187                         new_dep = btagPrefix+dependency+labelName+postfix
1188                     replace = MassSearchReplaceAnyInputTagVisitor(dependency, new_dep)
1189                     replace.doIt(getattr(process, newDiscr), newDiscr)
1190             acceptedBtagDiscriminators.append(meta_tagger)
1191                         
1192         else:
1193             print('  --> %s ignored, since not available via RecoBTag.Configuration.RecoBTag_cff!'%(btagDiscr))
1194         
1195     ## replace corresponding tags for pat jet production
1196     patJets.tagInfoSources = cms.VInputTag( *[ cms.InputTag(btagPrefix+x+labelName+postfix) for x in acceptedTagInfos ] )
1197     patJets.discriminatorSources = cms.VInputTag(*[ 
1198         cms.InputTag(btagPrefix+x+labelName+postfix) \
1199           if ':' not in x else \
1200           cms.InputTag(btagPrefix+x.split(':')[0]+labelName+postfix+':'+x.split(':')[1]) \
1201           for x in acceptedBtagDiscriminators 
1202         ])
1203     if len(acceptedBtagDiscriminators) > 0 :
1204         patJets.addBTagInfo = True
1205     ## if re-running IVF
1206     if runIVF:
1207         if not tightBTagNTkHits:
1208             if pvSource.getModuleLabel() == 'offlineSlimmedPrimaryVertices': ## MiniAOD case
1209                 if not runIVFforCTagOnly: rerunningIVFMiniAOD()
1210             else:
1211                 rerunningIVF()
1212         from PhysicsTools.PatAlgos.tools.helpers import loadWithPrefix
1213         ivfbTagInfos = ['pfInclusiveSecondaryVertexFinderTagInfos', 'pfInclusiveSecondaryVertexFinderAK8TagInfos', 'pfInclusiveSecondaryVertexFinderCA15TagInfos']
1214         if any(i in acceptedTagInfos for i in ivfbTagInfos) and not runIVFforCTagOnly:
1215             if not hasattr( process, btagPrefix+'inclusiveCandidateVertexFinder' ):
1216                 loadWithPrefix(process, 'RecoVertex.AdaptiveVertexFinder.inclusiveVertexing_cff', btagPrefix, task.label())
1217             if tightBTagNTkHits:
1218                 if hasattr( process, btagPrefix+'inclusiveCandidateVertexFinder' ):
1219                     _temp = getattr(process, btagPrefix+'inclusiveCandidateVertexFinder')
1220                     _temp.minHits = cms.uint32(8)
1221             ## MiniAOD case
1222             if pvSource.getModuleLabel() == 'offlineSlimmedPrimaryVertices':
1223                 if hasattr( process, btagPrefix+'inclusiveCandidateVertexFinder' ):
1224                     _temp = getattr(process, btagPrefix+'inclusiveCandidateVertexFinder')
1225                     _temp.primaryVertices = pvSource
1226                     _temp.tracks = pfCandidates
1227                 if hasattr( process, btagPrefix+'candidateVertexArbitrator' ):
1228                     _temp = getattr(process, btagPrefix+'candidateVertexArbitrator')
1229                     _temp.primaryVertices = pvSource
1230                     _temp.tracks = pfCandidates
1231                 if hasattr( process, btagPrefix+'inclusiveCandidateSecondaryVertices' ) and not hasattr( process, svSource.getModuleLabel() ):
1232                     addToProcessAndTask(svSource.getModuleLabel(),
1233                                         getattr(process, btagPrefix+'inclusiveCandidateSecondaryVertices').clone(),
1234                                         process, task)
1235         if any(i in acceptedTagInfos for i in ivfcTagInfos):
1236             if not hasattr( process, btagPrefix+'inclusiveCandidateVertexFinderCvsL' ):
1237                 loadWithPrefix(process, 'RecoVertex.AdaptiveVertexFinder.inclusiveVertexing_cff', btagPrefix, task.label())
1238             if tightBTagNTkHits:
1239                 if hasattr( process, btagPrefix+'inclusiveCandidateVertexFinderCvsL' ):
1240                     _temp = getattr(process, btagPrefix+'inclusiveCandidateVertexFinderCvsL')
1241                     _temp.minHits = cms.uint32(8)
1242             ## MiniAOD case
1243             if pvSource.getModuleLabel() == 'offlineSlimmedPrimaryVertices':
1244                 if hasattr( process, btagPrefix+'inclusiveCandidateVertexFinderCvsL' ):
1245                     _temp = getattr(process, btagPrefix+'inclusiveCandidateVertexFinderCvsL')
1246                     _temp.primaryVertices = pvSource
1247                     _temp.tracks = pfCandidates
1248                 if hasattr( process, btagPrefix+'candidateVertexArbitratorCvsL' ):
1249                     _temp = getattr(process, btagPrefix+'candidateVertexArbitratorCvsL')
1250                     _temp.primaryVertices = pvSource
1251                     _temp.tracks = pfCandidates
1252                 if hasattr( process, btagPrefix+'inclusiveCandidateSecondaryVerticesCvsL' ) and not hasattr( process, svSourceCvsL.getModuleLabel() ):
1253                     addToProcessAndTask(svSourceCvsL.getModuleLabel(),
1254                                         getattr(process, btagPrefix+'inclusiveCandidateSecondaryVerticesCvsL').clone(),
1255                                         process, task)
1256         if 'inclusiveSecondaryVertexFinderTagInfos' in acceptedTagInfos:
1257             if not hasattr( process, 'inclusiveVertexing' ):
1258                 process.load( 'RecoVertex.AdaptiveVertexFinder.inclusiveVertexing_cff' )
1259                 task.add(process.inclusiveVertexingTask)
1260                 task.add(process.inclusiveCandidateVertexingTask)
1261                 task.add(process.inclusiveCandidateVertexingCvsLTask)
1262         if 'inclusiveSecondaryVertexFinderFilteredTagInfos' in acceptedTagInfos:
1263             if not hasattr( process, 'inclusiveVertexing' ):
1264                 process.load( 'RecoVertex.AdaptiveVertexFinder.inclusiveVertexing_cff' )
1265                 task.add(process.inclusiveVertexingTask)
1266                 task.add(process.inclusiveCandidateVertexingTask)
1267                 task.add(process.inclusiveCandidateVertexingCvsLTask)
1268     if 'inclusiveSecondaryVertexFinderFilteredTagInfos' in acceptedTagInfos:
1269         if not hasattr( process, 'inclusiveSecondaryVerticesFiltered' ):
1270             process.load( 'RecoBTag.SecondaryVertex.inclusiveSecondaryVerticesFiltered_cfi' )
1271             task.add(process.inclusiveSecondaryVerticesFiltered)
1272             task.add(process.bVertexFilter)
1273         if not hasattr( process, 'bToCharmDecayVertexMerged' ):
1274             process.load( 'RecoBTag.SecondaryVertex.bToCharmDecayVertexMerger_cfi' )
1275             task.add(process.bToCharmDecayVertexMerged)
1276     if 'caTopTagInfos' in acceptedTagInfos :
1277         patJets.addTagInfos = True
1278         if not hasattr( process, 'caTopTagInfos' ) and not hasattr( process, 'caTopTagInfosAK8' ):
1279             process.load( 'RecoJets.JetProducers.caTopTaggers_cff' )
1280             task.add(process.caTopTaggersTask)
1281 
1282 class AddJetCollection(ConfigToolBase):
1283     """
1284     Tool to add a new jet collection to your PAT Tuple or to modify an existing one.
1285     """
1286     _label='addJetCollection'
1287     _defaultParameters=dicttypes.SortedKeysDict()
1288 
1289     def __init__(self):
1290         """
1291         Initialize elements of the class. Note that the tool needs to be derived from ConfigToolBase to be usable in the configEditor.
1292         """
1293         ## initialization of the base class
1294         ConfigToolBase.__init__(self)
1295         ## add all parameters that should be known to the class
1296         self.addParameter(self._defaultParameters,'labelName', 'UNDEFINED', "Label name of the new patJet collection.", str)
1297         self.addParameter(self._defaultParameters,'postfix','', "Postfix from usePF2PAT.", str)
1298         self.addParameter(self._defaultParameters,'btagPrefix','', "Prefix to be added to b-tag discriminator and TagInfo names", str)
1299         self.addParameter(self._defaultParameters,'jetSource','', "Label of the input collection from which the new patJet collection should be created", cms.InputTag)
1300         self.addParameter(self._defaultParameters,'pfCandidates',cms.InputTag('particleFlow'), "Label of the input collection for candidatecandidatese used in b-tagging", cms.InputTag)
1301         self.addParameter(self._defaultParameters,'explicitJTA', False, "Use explicit jet-track association")
1302         self.addParameter(self._defaultParameters,'pvSource',cms.InputTag('offlinePrimaryVertices'), "Label of the input collection for primary vertices used in b-tagging", cms.InputTag)
1303         self.addParameter(self._defaultParameters,'svSource',cms.InputTag('inclusiveCandidateSecondaryVertices'), "Label of the input collection for IVF vertices used in b-tagging", cms.InputTag)
1304         self.addParameter(self._defaultParameters,'elSource',cms.InputTag('gedGsfElectrons'), "Label of the input collection for electrons used in b-tagging", cms.InputTag)
1305         self.addParameter(self._defaultParameters,'muSource',cms.InputTag('muons'), "Label of the input collection for muons used in b-tagging", cms.InputTag)
1306         self.addParameter(self._defaultParameters,'runIVF', False, "Re-run IVF secondary vertex reconstruction")
1307         self.addParameter(self._defaultParameters,'tightBTagNTkHits', False, "Enable legacy tight b-tag track selection")
1308         self.addParameter(self._defaultParameters,'loadStdRecoBTag', False, "Load the standard reconstruction b-tagging modules")
1309         self.addParameter(self._defaultParameters,'svClustering', False, "Secondary vertices ghost-associated to jets using jet clustering (mostly intended for subjets)")
1310         self.addParameter(self._defaultParameters,'fatJets', cms.InputTag(''), "Fat jet collection used for secondary vertex clustering", cms.InputTag)
1311         self.addParameter(self._defaultParameters,'groomedFatJets', cms.InputTag(''), "Groomed fat jet collection used for secondary vertex clustering", cms.InputTag)
1312         self.addParameter(self._defaultParameters,'algo', 'AK', "Jet algorithm of the input collection from which the new patJet collection should be created")
1313         self.addParameter(self._defaultParameters,'rParam', 0.4, "Jet size (distance parameter R used in jet clustering)")
1314         self.addParameter(self._defaultParameters,'getJetMCFlavour', True, "Get jet MC truth flavour")
1315         self.addParameter(self._defaultParameters,'genJetCollection', cms.InputTag("ak4GenJets"), "GenJet collection to match to", cms.InputTag)
1316         self.addParameter(self._defaultParameters,'genParticles', cms.InputTag("genParticles"), "GenParticle collection to be used", cms.InputTag)
1317         self.addParameter(self._defaultParameters,'jetCorrections',None, "Add all relevant information about jet energy corrections that you want to be added to your new patJet \
1318         collection. The format has to be given in a python tuple of type: (\'AK4Calo\',[\'L2Relative\', \'L3Absolute\'], patMet). Here the first argument corresponds to the payload \
1319         in the CMS Conditions database for the given jet collection; the second argument corresponds to the jet energy correction levels that you want to be embedded into your \
1320         new patJet collection. This should be given as a list of strings. Available values are L1Offset, L1FastJet, L1JPTOffset, L2Relative, L3Absolute, L5Falvour, L7Parton; the \
1321         third argument indicates whether MET(Type1/2) corrections should be applied corresponding to the new patJetCollection. If so a new patMet collection will be added to your PAT \
1322         Tuple in addition to the raw patMet. This new patMet collection will have the MET(Type1/2) corrections applied. The argument can have the following types: \'type-1\' for \
1323         type-1 corrected MET; \'type-2\' for type-1 plus type-2 corrected MET; \'\' or \'none\' if no further MET corrections should be applied to your MET. The arguments \'type-1\' \
1324         and \'type-2\' are not case sensitive.", tuple, acceptNoneValue=True)
1325         self.addParameter(self._defaultParameters,'btagDiscriminators',['None'], "If you are interested in btagging, in most cases just the labels of the btag discriminators that \
1326         you are interested in is all relevant information that you need for a high level analysis. Add here all btag discriminators, that you are interested in as a list of strings. \
1327         If this list is empty no btag discriminator information will be added to your new patJet collection.", allowedValues=(list(set().union(supportedBtagDiscr.keys(),supportedMetaDiscr.keys()))),Type=list)
1328         self.addParameter(self._defaultParameters,'btagInfos',['None'], "The btagInfos objects contain all relevant information from which all discriminators of a certain \
1329         type have been calculated. You might be interested in keeping this information for low level tests or to re-calculate some discriminators from hand. Note that this information \
1330         on the one hand can be very space consuming and that it is not necessary to access the pre-calculated btag discriminator information that has been derived from it. Only in very \
1331         special cases the btagInfos might really be needed in your analysis. Add here all btagInfos, that you are interested in as a list of strings. If this list is empty no btagInfos \
1332         will be added to your new patJet collection.", allowedValues=supportedBtagInfos,Type=list)
1333         self.addParameter(self._defaultParameters,'jetTrackAssociation',False, "Add JetTrackAssociation and JetCharge from reconstructed tracks to your new patJet collection. This \
1334         switch is only of relevance if you don\'t add any btag information to your new patJet collection (btagDiscriminators or btagInfos) and still want this information added to \
1335         your new patJetCollection. If btag information of any form is added to the new patJet collection this information will be added automatically.")
1336         self.addParameter(self._defaultParameters,'outputModules',['out'],"Add a list of all output modules to which you would like the new jet collection to be added. Usually this is \
1337         just one single output module with name \'out\', which corresponds also the default configuration of the tool. There is cases though where you might want to add this collection \
1338         to more than one output module.")
1339         ## set defaults
1340         self._parameters=copy.deepcopy(self._defaultParameters)
1341         ## add comments
1342         self._comment = "This is a tool to add more patJet collectinos to your PAT Tuple or to re-configure the default collection. You can add and embed additional information like jet\
1343         energy correction factors, btag information and generator match information to the new patJet collection depending on the parameters that you pass on to this function. Consult \
1344         the descriptions of each parameter for more information."
1345 
1346     def getDefaultParameters(self):
1347         """
1348         Return default parameters of the class
1349         """
1350         return self._defaultParameters
1351 
1352     def __call__(self,process,labelName=None,postfix=None,btagPrefix=None,jetSource=None,pfCandidates=None,explicitJTA=None,pvSource=None,svSource=None,elSource=None,muSource=None,runIVF=None,tightBTagNTkHits=None,loadStdRecoBTag=None,svClustering=None,fatJets=None,groomedFatJets=None,algo=None,rParam=None,getJetMCFlavour=None,genJetCollection=None,genParticles=None,jetCorrections=None,btagDiscriminators=None,btagInfos=None,jetTrackAssociation=None,outputModules=None):
1353         """
1354         Function call wrapper. This will check the parameters and call the actual implementation that
1355         can be found in toolCode via the base class function apply.
1356         """
1357         if labelName is None:
1358             labelName=self._defaultParameters['labelName'].value
1359         self.setParameter('labelName', labelName)
1360         if postfix is None:
1361             postfix=self._defaultParameters['postfix'].value
1362         self.setParameter('postfix', postfix)
1363         if btagPrefix is None:
1364             btagPrefix=self._defaultParameters['btagPrefix'].value
1365         self.setParameter('btagPrefix', btagPrefix)
1366         if jetSource is None:
1367             jetSource=self._defaultParameters['jetSource'].value
1368         self.setParameter('jetSource', jetSource)
1369         if pfCandidates is None:
1370             pfCandidates=self._defaultParameters['pfCandidates'].value
1371         self.setParameter('pfCandidates', pfCandidates)
1372         if explicitJTA is None:
1373             explicitJTA=self._defaultParameters['explicitJTA'].value
1374         self.setParameter('explicitJTA', explicitJTA)
1375         if pvSource is None:
1376             pvSource=self._defaultParameters['pvSource'].value
1377         self.setParameter('pvSource', pvSource)
1378         if svSource is None:
1379             svSource=self._defaultParameters['svSource'].value
1380         self.setParameter('svSource', svSource)
1381         if elSource is None:
1382             elSource=self._defaultParameters['elSource'].value
1383         self.setParameter('elSource', elSource)
1384         if muSource is None:
1385             muSource=self._defaultParameters['muSource'].value
1386         self.setParameter('muSource', muSource)
1387         if runIVF is None:
1388             runIVF=self._defaultParameters['runIVF'].value
1389         self.setParameter('runIVF', runIVF)
1390         if tightBTagNTkHits is None:
1391             tightBTagNTkHits=self._defaultParameters['tightBTagNTkHits'].value
1392         self.setParameter('tightBTagNTkHits', tightBTagNTkHits)
1393         if loadStdRecoBTag is None:
1394             loadStdRecoBTag=self._defaultParameters['loadStdRecoBTag'].value
1395         self.setParameter('loadStdRecoBTag', loadStdRecoBTag)
1396         if svClustering is None:
1397             svClustering=self._defaultParameters['svClustering'].value
1398         self.setParameter('svClustering', svClustering)
1399         if fatJets is None:
1400             fatJets=self._defaultParameters['fatJets'].value
1401         self.setParameter('fatJets', fatJets)
1402         if groomedFatJets is None:
1403             groomedFatJets=self._defaultParameters['groomedFatJets'].value
1404         self.setParameter('groomedFatJets', groomedFatJets)
1405         if algo is None:
1406             algo=self._defaultParameters['algo'].value
1407         self.setParameter('algo', algo)
1408         if rParam is None:
1409             rParam=self._defaultParameters['rParam'].value
1410         self.setParameter('rParam', rParam)
1411         if getJetMCFlavour is None:
1412             getJetMCFlavour=self._defaultParameters['getJetMCFlavour'].value
1413         self.setParameter('getJetMCFlavour', getJetMCFlavour)
1414         if genJetCollection is None:
1415             genJetCollection=self._defaultParameters['genJetCollection'].value
1416         self.setParameter('genJetCollection', genJetCollection)
1417         if genParticles is None:
1418             genParticles=self._defaultParameters['genParticles'].value
1419         self.setParameter('genParticles', genParticles)
1420         if jetCorrections is None:
1421             jetCorrections=self._defaultParameters['jetCorrections'].value
1422         self.setParameter('jetCorrections', jetCorrections)
1423         if btagDiscriminators is None:
1424             btagDiscriminators=self._defaultParameters['btagDiscriminators'].value
1425         self.setParameter('btagDiscriminators', btagDiscriminators)
1426         if btagInfos is None:
1427             btagInfos=self._defaultParameters['btagInfos'].value
1428         self.setParameter('btagInfos', btagInfos)
1429         if jetTrackAssociation is None:
1430             jetTrackAssociation=self._defaultParameters['jetTrackAssociation'].value
1431         self.setParameter('jetTrackAssociation', jetTrackAssociation)
1432         if outputModules is None:
1433             outputModules=self._defaultParameters['outputModules'].value
1434         self.setParameter('outputModules', outputModules)
1435         self.apply(process)
1436 
1437     def toolCode(self, process):
1438         """
1439         Tool code implementation
1440         """
1441         task = getPatAlgosToolsTask(process)
1442 
1443         ## initialize parameters
1444         labelName=self._parameters['labelName'].value
1445         postfix=self._parameters['postfix'].value
1446         btagPrefix=self._parameters['btagPrefix'].value
1447         jetSource=self._parameters['jetSource'].value
1448         pfCandidates=self._parameters['pfCandidates'].value
1449         explicitJTA=self._parameters['explicitJTA'].value
1450         pvSource=self._parameters['pvSource'].value
1451         svSource=self._parameters['svSource'].value
1452         elSource=self._parameters['elSource'].value
1453         muSource=self._parameters['muSource'].value
1454         runIVF=self._parameters['runIVF'].value
1455         tightBTagNTkHits=self._parameters['tightBTagNTkHits'].value
1456         loadStdRecoBTag=self._parameters['loadStdRecoBTag'].value
1457         svClustering=self._parameters['svClustering'].value
1458         fatJets=self._parameters['fatJets'].value
1459         groomedFatJets=self._parameters['groomedFatJets'].value
1460         algo=self._parameters['algo'].value
1461         rParam=self._parameters['rParam'].value
1462         getJetMCFlavour=self._parameters['getJetMCFlavour'].value
1463         genJetCollection=self._parameters['genJetCollection'].value
1464         genParticles=self._parameters['genParticles'].value
1465         jetCorrections=self._parameters['jetCorrections'].value
1466         btagDiscriminators=list(self._parameters['btagDiscriminators'].value)
1467         btagInfos=list(self._parameters['btagInfos'].value)
1468         jetTrackAssociation=self._parameters['jetTrackAssociation'].value
1469         outputModules=list(self._parameters['outputModules'].value)
1470 
1471         ## added jets must have a defined 'labelName'
1472         if labelName=='UNDEFINED':
1473             undefinedLabelName(self)
1474 
1475         ## a list of all producer modules, which are already known to process
1476         knownModules = process.producerNames().split()
1477         ## determine whether btagging information is required or not
1478         if btagDiscriminators.count('None')>0:
1479             btagDiscriminators.remove('None')
1480         if btagInfos.count('None')>0:
1481             btagInfos.remove('None')
1482         bTagging=(len(btagDiscriminators)>0 or len(btagInfos)>0)
1483         ## check if any legacy btag discriminators are being used
1484         infos = 0
1485         for info in btagInfos:
1486             if info.startswith('pf'): infos = infos + 1
1487             if 'softpf' in info.lower(): infos = infos + 1
1488         tags = 0
1489         for tag in btagDiscriminators:
1490             if tag.startswith('pf'): tags = tags + 1
1491             if 'softpf' in tag.lower(): tags = tags + 1
1492         bTaggingLegacy=(len(btagDiscriminators)>tags or len(btagInfos)>infos)
1493         ## construct postfix label for auxiliary modules; this postfix
1494         ## label will start with a capitalized first letter following
1495         ## the CMS naming conventions and for improved readablility
1496         _labelName=labelName[:1].upper()+labelName[1:]
1497 
1498         ## supported algo types are ak, ca, and kt
1499         _algo=''
1500         for x in ["ak", "ca", "kt"]:
1501             if x in algo.lower():
1502                 _algo=supportedJetAlgos[x]
1503                 break
1504         if _algo=='':
1505             unsupportedJetAlgorithm(self)
1506         ## add new patJets to process (keep instance for later further modifications)
1507         from PhysicsTools.PatAlgos.producersLayer1.jetProducer_cfi import _patJets as patJets
1508         if 'patJets'+_labelName+postfix in knownModules :
1509             _newPatJets=getattr(process, 'patJets'+_labelName+postfix)
1510             _newPatJets.jetSource=jetSource
1511         else :
1512             addToProcessAndTask('patJets'+_labelName+postfix, patJets.clone(jetSource=jetSource), process, task)
1513             _newPatJets=getattr(process, 'patJets'+_labelName+postfix)
1514             knownModules.append('patJets'+_labelName+postfix)
1515         ## add new selectedPatJets to process
1516         from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets
1517         if 'selectedPatJets'+_labelName+postfix in knownModules :
1518             _newSelectedPatJets=getattr(process, 'selectedPatJets'+_labelName+postfix)
1519             _newSelectedPatJets.src='patJets'+_labelName+postfix
1520         else :
1521             addToProcessAndTask('selectedPatJets'+_labelName+postfix,
1522                                 selectedPatJets.clone(src='patJets'+_labelName+postfix),
1523                                 process, task)
1524             knownModules.append('selectedPatJets'+_labelName+postfix)
1525 
1526         ## add new patJetPartonMatch to process
1527         from PhysicsTools.PatAlgos.mcMatchLayer0.jetMatch_cfi import patJetPartonMatch
1528         if 'patJetPartonMatch'+_labelName+postfix in knownModules :
1529             _newPatJetPartonMatch=getattr(process, 'patJetPartonMatch'+_labelName+postfix)
1530             _newPatJetPartonMatch.src=jetSource
1531             _newPatJetPartonMatch.matched=genParticles
1532         else :
1533             addToProcessAndTask('patJetPartonMatch'+_labelName+postfix,
1534                                 patJetPartonMatch.clone(src=jetSource, matched=genParticles),
1535                                 process, task)
1536             knownModules.append('patJetPartonMatch'+_labelName+postfix)
1537         ## add new patJetGenJetMatch to process
1538         from PhysicsTools.PatAlgos.mcMatchLayer0.jetMatch_cfi import patJetGenJetMatch
1539         if 'patJetGenJetMatch'+_labelName+postfix in knownModules :
1540             _newPatJetGenJetMatch=getattr(process, 'patJetGenJetMatch'+_labelName+postfix)
1541             _newPatJetGenJetMatch.src=jetSource
1542             _newPatJetGenJetMatch.maxDeltaR=rParam
1543             _newPatJetGenJetMatch.matched=genJetCollection
1544         else :
1545             addToProcessAndTask('patJetGenJetMatch'+_labelName+postfix,
1546                                 patJetGenJetMatch.clone(src=jetSource, maxDeltaR=rParam, matched=genJetCollection),
1547                                 process, task)
1548             knownModules.append('patJetGenJetMatch'+_labelName+postfix)
1549         ## modify new patJets collection accordingly
1550         _newPatJets.genJetMatch.setModuleLabel('patJetGenJetMatch'+_labelName+postfix)
1551         _newPatJets.genPartonMatch.setModuleLabel('patJetPartonMatch'+_labelName+postfix)
1552         ## get jet MC truth flavour if required by user
1553         if (getJetMCFlavour):
1554             ## legacy jet flavour (see https://twiki.cern.ch/twiki/bin/view/CMSPublic/SWGuideBTagMCTools)
1555             ## add new patJetPartonsLegacy to process
1556             from PhysicsTools.PatAlgos.mcMatchLayer0.jetFlavourId_cff import patJetPartonsLegacy
1557             if 'patJetPartonsLegacy'+postfix not in knownModules :
1558                 addToProcessAndTask('patJetPartonsLegacy'+postfix, patJetPartonsLegacy.clone(src=genParticles),
1559                                     process, task)
1560                 knownModules.append('patJetPartonsLegacy'+postfix)
1561             else:
1562                 getattr(process, 'patJetPartonsLegacy'+postfix).src=genParticles
1563             ## add new patJetPartonAssociationLegacy to process
1564             from PhysicsTools.PatAlgos.mcMatchLayer0.jetFlavourId_cff import patJetPartonAssociationLegacy
1565             if 'patJetPartonAssociationLegacy'+_labelName+postfix in knownModules :
1566                 _newPatJetPartonAssociation=getattr(process, 'patJetPartonAssociationLegacy'+_labelName+postfix)
1567                 _newPatJetPartonAssociation.jets=jetSource
1568             else :
1569                 addToProcessAndTask('patJetPartonAssociationLegacy'+_labelName+postfix,
1570                                     patJetPartonAssociationLegacy.clone(jets=jetSource), process, task)
1571                 knownModules.append('patJetPartonAssociationLegacy'+_labelName+postfix)
1572             ## add new patJetPartonAssociationLegacy to process
1573             from PhysicsTools.PatAlgos.mcMatchLayer0.jetFlavourId_cff import patJetFlavourAssociationLegacy
1574             if 'patJetFlavourAssociationLegacy'+_labelName+postfix in knownModules :
1575                 _newPatJetFlavourAssociation=getattr(process, 'patJetFlavourAssociationLegacy'+_labelName+postfix)
1576                 _newPatJetFlavourAssociation.srcByReference='patJetPartonAssociationLegacy'+_labelName+postfix
1577             else:
1578                 addToProcessAndTask('patJetFlavourAssociationLegacy'+_labelName+postfix,
1579                                     patJetFlavourAssociationLegacy.clone(
1580                                         srcByReference='patJetPartonAssociationLegacy'+_labelName+postfix),
1581                                     process, task)
1582                 knownModules.append('patJetFlavourAssociationLegacy'+_labelName+postfix)
1583             ## modify new patJets collection accordingly
1584             _newPatJets.JetPartonMapSource.setModuleLabel('patJetFlavourAssociationLegacy'+_labelName+postfix)
1585             ## new jet flavour (see https://twiki.cern.ch/twiki/bin/view/CMSPublic/SWGuideBTagMCTools)
1586             ## add new patJetPartons to process
1587             from PhysicsTools.PatAlgos.mcMatchLayer0.jetFlavourId_cff import patJetPartons
1588             if 'patJetPartons'+postfix not in knownModules :
1589                 addToProcessAndTask('patJetPartons'+postfix, patJetPartons.clone(particles=genParticles), process, task)
1590                 knownModules.append('patJetPartons'+postfix)
1591             else:
1592                 getattr(process, 'patJetPartons'+postfix).particles=genParticles
1593             ## add new patJetFlavourAssociation to process
1594             from PhysicsTools.PatAlgos.mcMatchLayer0.jetFlavourId_cff import patJetFlavourAssociation
1595             if 'patJetFlavourAssociation'+_labelName+postfix in knownModules :
1596                 _newPatJetFlavourAssociation=getattr(process, 'patJetFlavourAssociation'+_labelName+postfix)
1597                 _newPatJetFlavourAssociation.jets=jetSource
1598                 _newPatJetFlavourAssociation.jetAlgorithm=_algo
1599                 _newPatJetFlavourAssociation.rParam=rParam
1600                 _newPatJetFlavourAssociation.bHadrons=cms.InputTag("patJetPartons"+postfix,"bHadrons")
1601                 _newPatJetFlavourAssociation.cHadrons=cms.InputTag("patJetPartons"+postfix,"cHadrons")
1602                 _newPatJetFlavourAssociation.partons=cms.InputTag("patJetPartons"+postfix,"physicsPartons")
1603                 _newPatJetFlavourAssociation.leptons=cms.InputTag("patJetPartons"+postfix,"leptons")
1604             else :
1605                 addToProcessAndTask('patJetFlavourAssociation'+_labelName+postfix,
1606                                     patJetFlavourAssociation.clone(
1607                                         jets=jetSource,
1608                                         jetAlgorithm=_algo,
1609                                         rParam=rParam,
1610                                         bHadrons = cms.InputTag("patJetPartons"+postfix,"bHadrons"),
1611                                         cHadrons = cms.InputTag("patJetPartons"+postfix,"cHadrons"),
1612                                         partons = cms.InputTag("patJetPartons"+postfix,"physicsPartons"),
1613                                         leptons = cms.InputTag("patJetPartons"+postfix,"leptons")),
1614                                     process, task)
1615 
1616                 knownModules.append('patJetFlavourAssociation'+_labelName+postfix)
1617             if 'Puppi' in jetSource.value() and pfCandidates.value() == 'particleFlow':
1618                 _newPatJetFlavourAssociation=getattr(process, 'patJetFlavourAssociation'+_labelName+postfix)
1619                 _newPatJetFlavourAssociation.weights = cms.InputTag("puppi")
1620             ## modify new patJets collection accordingly
1621             _newPatJets.JetFlavourInfoSource.setModuleLabel('patJetFlavourAssociation'+_labelName+postfix)
1622             ## if the jets is actually a subjet
1623             if fatJets != cms.InputTag('') and groomedFatJets != cms.InputTag(''):
1624                 _newPatJetFlavourAssociation=getattr(process, 'patJetFlavourAssociation'+_labelName+postfix)
1625                 _newPatJetFlavourAssociation.jets=fatJets
1626                 _newPatJetFlavourAssociation.groomedJets=groomedFatJets
1627                 _newPatJetFlavourAssociation.subjets=jetSource
1628                 _newPatJets.JetFlavourInfoSource=cms.InputTag('patJetFlavourAssociation'+_labelName+postfix,'SubJets')
1629         else:
1630             _newPatJets.getJetMCFlavour = False
1631             _newPatJets.addJetFlavourInfo = False
1632 
1633         ## add jetTrackAssociation for legacy btagging (or jetTracksAssociation only) if required by user
1634         if (jetTrackAssociation or bTaggingLegacy):
1635             ## add new jetTracksAssociationAtVertex to process
1636             from RecoJets.JetAssociationProducers.ak4JTA_cff import ak4JetTracksAssociatorAtVertex, ak4JetTracksAssociatorExplicit
1637             if 'jetTracksAssociationAtVertex'+_labelName+postfix in knownModules :
1638                 _newJetTracksAssociationAtVertex=getattr(process, 'jetTracksAssociatorAtVertex'+_labelName+postfix)
1639                 _newJetTracksAssociationAtVertex.jets=jetSource
1640                 _newJetTracksAssociationAtVertex.pvSrc=pvSource
1641             else:
1642                 jetTracksAssociator=ak4JetTracksAssociatorAtVertex
1643                 if explicitJTA:
1644                     jetTracksAssociator=ak4JetTracksAssociatorExplicit
1645                 addToProcessAndTask('jetTracksAssociatorAtVertex'+_labelName+postfix,
1646                                     jetTracksAssociator.clone(jets=jetSource,pvSrc=pvSource),
1647                                     process, task)
1648                 knownModules.append('jetTracksAssociationAtVertex'+_labelName+postfix)
1649             ## add new patJetCharge to process
1650             from PhysicsTools.PatAlgos.recoLayer0.jetTracksCharge_cff import patJetCharge
1651             if 'patJetCharge'+_labelName+postfix in knownModules :
1652                 _newPatJetCharge=getattr(process, 'patJetCharge'+_labelName+postfix)
1653                 _newPatJetCharge.src='jetTracksAssociatorAtVertex'+_labelName+postfix
1654             else:
1655                 addToProcessAndTask('patJetCharge'+_labelName+postfix,
1656                                     patJetCharge.clone(src = 'jetTracksAssociatorAtVertex'+_labelName+postfix),
1657                                     process, task)
1658                 knownModules.append('patJetCharge'+_labelName+postfix)
1659             ## modify new patJets collection accordingly
1660             _newPatJets.addAssociatedTracks=True
1661             _newPatJets.trackAssociationSource=cms.InputTag('jetTracksAssociatorAtVertex'+_labelName+postfix)
1662             _newPatJets.addJetCharge=True
1663             _newPatJets.jetChargeSource=cms.InputTag('patJetCharge'+_labelName+postfix)
1664         else:
1665             ## modify new patJets collection accordingly
1666             _newPatJets.addAssociatedTracks=False
1667             _newPatJets.trackAssociationSource=''
1668             _newPatJets.addJetCharge=False
1669             _newPatJets.jetChargeSource=''
1670         ## run btagging if required by user
1671         if (bTagging):
1672             setupBTagging(process, jetSource, pfCandidates, explicitJTA, pvSource, svSource, elSource, muSource, runIVF, tightBTagNTkHits, loadStdRecoBTag, svClustering, fatJets, groomedFatJets,
1673                           _algo, rParam, btagDiscriminators, btagInfos, _newPatJets, _labelName, btagPrefix, postfix)
1674         else:
1675             _newPatJets.addBTagInfo = False
1676             _newPatJets.addTagInfos = False
1677             ## adjust output module; these collections will be empty anyhow, but we do it to stay clean
1678             for outputModule in outputModules:
1679                     if hasattr(process,outputModule):
1680                         getattr(process,outputModule).outputCommands.append("drop *_"+'selected'+_labelName+postfix+"_tagInfos_*")
1681 
1682         ## add jet correction factors if required by user
1683         if (jetCorrections != None):
1684             ## check the jet corrections format
1685             checkJetCorrectionsFormat(jetCorrections)
1686             ## setup jet energy corrections and MET corrections
1687             setupJetCorrections(process, knownModules, jetCorrections, jetSource, pvSource, _newPatJets, _labelName, postfix)
1688         else:
1689             ## switch jetCorrFactors off
1690             _newPatJets.addJetCorrFactors=False
1691 
1692 addJetCollection=AddJetCollection()
1693 
1694 class SwitchJetCollection(ConfigToolBase):
1695     """
1696     Tool to switch parameters of the PAT jet collection to your PAT Tuple.
1697     """
1698     _label='switchJetCollection'
1699     _defaultParameters=dicttypes.SortedKeysDict()
1700 
1701     def __init__(self):
1702         """
1703         Initialize elements of the class. Note that the tool needs to be derived from ConfigToolBase to be usable in the configEditor.
1704         """
1705         ## initialization of the base class
1706         ConfigToolBase.__init__(self)
1707         ## add all parameters that should be known to the class
1708         self.addParameter(self._defaultParameters,'postfix','', "postfix from usePF2PAT")
1709         self.addParameter(self._defaultParameters,'btagPrefix','', "Prefix to be added to b-tag discriminator and TagInfo names", str)
1710         self.addParameter(self._defaultParameters,'jetSource','', "Label of the input collection from which the new patJet collection should be created", cms.InputTag)
1711         self.addParameter(self._defaultParameters,'pfCandidates',cms.InputTag('particleFlow'), "Label of the input collection for candidatecandidatese used in b-tagging", cms.InputTag)
1712         self.addParameter(self._defaultParameters,'explicitJTA', False, "Use explicit jet-track association")
1713         self.addParameter(self._defaultParameters,'pvSource',cms.InputTag('offlinePrimaryVertices'), "Label of the input collection for primary vertices used in b-tagging", cms.InputTag)
1714         self.addParameter(self._defaultParameters,'svSource',cms.InputTag('inclusiveCandidateSecondaryVertices'), "Label of the input collection for IVF vertices used in b-tagging", cms.InputTag)
1715         self.addParameter(self._defaultParameters,'elSource',cms.InputTag('gedGsfElectrons'), "Label of the input collection for electrons used in b-tagging", cms.InputTag)
1716         self.addParameter(self._defaultParameters,'muSource',cms.InputTag('muons'), "Label of the input collection for muons used in b-tagging", cms.InputTag)
1717         self.addParameter(self._defaultParameters,'runIVF', False, "Re-run IVF secondary vertex reconstruction")
1718         self.addParameter(self._defaultParameters,'tightBTagNTkHits', False, "Enable legacy tight b-tag track selection")
1719         self.addParameter(self._defaultParameters,'loadStdRecoBTag', False, "Load the standard reconstruction b-tagging modules")
1720         self.addParameter(self._defaultParameters,'svClustering', False, "Secondary vertices ghost-associated to jets using jet clustering (mostly intended for subjets)")
1721         self.addParameter(self._defaultParameters,'fatJets', cms.InputTag(''), "Fat jet collection used for secondary vertex clustering", cms.InputTag)
1722         self.addParameter(self._defaultParameters,'groomedFatJets', cms.InputTag(''), "Groomed fat jet collection used for secondary vertex clustering", cms.InputTag)
1723         self.addParameter(self._defaultParameters,'algo', 'AK', "Jet algorithm of the input collection from which the new patJet collection should be created")
1724         self.addParameter(self._defaultParameters,'rParam', 0.4, "Jet size (distance parameter R used in jet clustering)")
1725         self.addParameter(self._defaultParameters,'getJetMCFlavour', True, "Get jet MC truth flavour")
1726         self.addParameter(self._defaultParameters,'genJetCollection', cms.InputTag("ak4GenJets"), "GenJet collection to match to")
1727         self.addParameter(self._defaultParameters,'genParticles', cms.InputTag("genParticles"), "GenParticle collection to be used", cms.InputTag)
1728         self.addParameter(self._defaultParameters,'jetCorrections',None, "Add all relevant information about jet energy corrections that you want to be added to your new patJet \
1729         collection. The format is to be passed on in a python tuple: e.g. (\'AK4Calo\',[\'L2Relative\', \'L3Absolute\'], patMet). The first argument corresponds to the payload \
1730         in the CMS Conditions database for the given jet collection; the second argument corresponds to the jet energy correction level that you want to be embedded into your \
1731         new patJet collection. This should be given as a list of strings. Available values are L1Offset, L1FastJet, L1JPTOffset, L2Relative, L3Absolute, L5Falvour, L7Parton; the \
1732         third argument indicates whether MET(Type1) corrections should be applied corresponding to the new patJetCollection. If so a new patMet collection will be added to your PAT \
1733         Tuple in addition to the raw patMet with the MET(Type1) corrections applied. The argument corresponds to the patMet collection to which the MET(Type1) corrections should be \
1734         applied. If you are not interested in MET(Type1) corrections to this new patJet collection pass None as third argument of the python tuple.", tuple, acceptNoneValue=True)
1735         self.addParameter(self._defaultParameters,'btagDiscriminators',['None'], "If you are interested in btagging in general the btag discriminators is all relevant \
1736         information that you need for a high level analysis. Add here all btag discriminators, that you are interested in as a list of strings. If this list is empty no btag \
1737         discriminator information will be added to your new patJet collection.", allowedValues=(list(set().union(supportedBtagDiscr.keys(),supportedMetaDiscr.keys()))),Type=list)
1738         self.addParameter(self._defaultParameters,'btagInfos',['None'], "The btagInfos objects conatin all relevant information from which all discriminators of a certain \
1739         type have been calculated. Note that this information on the one hand can be very space consuming and on the other hand is not necessary to access the btag discriminator \
1740         information that has been derived from it. Only in very special cases the btagInfos might really be needed in your analysis. Add here all btagInfos, that you are interested \
1741         in as a list of strings. If this list is empty no btagInfos will be added to your new patJet collection.", allowedValues=supportedBtagInfos,Type=list)
1742         self.addParameter(self._defaultParameters,'jetTrackAssociation',False, "Add JetTrackAssociation and JetCharge from reconstructed tracks to your new patJet collection. This \
1743         switch is only of relevance if you don\'t add any btag information to your new patJet collection (btagDiscriminators or btagInfos) and still want this information added to \
1744         your new patJetCollection. If btag information is added to the new patJet collection this information will be added automatically.")
1745         self.addParameter(self._defaultParameters,'outputModules',['out'],"Output module labels. Add a list of all output modules to which you would like the new jet collection to \
1746         be added, in case you use more than one output module.")
1747         ## set defaults
1748         self._parameters=copy.deepcopy(self._defaultParameters)
1749         ## add comments
1750         self._comment = "This is a tool to add more patJet collectinos to your PAT Tuple. You can add and embed additional information like jet energy correction factors, btag \
1751         information and generator match information to the new patJet collection depending on the parameters that you pass on to this function. Consult the descriptions of each \
1752         parameter for more information."
1753 
1754     def getDefaultParameters(self):
1755         """
1756         Return default parameters of the class
1757         """
1758         return self._defaultParameters
1759 
1760     def __call__(self,process,postfix=None,btagPrefix=None,jetSource=None,pfCandidates=None,explicitJTA=None,pvSource=None,svSource=None,elSource=None,muSource=None,runIVF=None,tightBTagNTkHits=None,loadStdRecoBTag=None,svClustering=None,fatJets=None,groomedFatJets=None,algo=None,rParam=None,getJetMCFlavour=None,genJetCollection=None,genParticles=None,jetCorrections=None,btagDiscriminators=None,btagInfos=None,jetTrackAssociation=None,outputModules=None):
1761         """
1762         Function call wrapper. This will check the parameters and call the actual implementation that
1763         can be found in toolCode via the base class function apply.
1764         """
1765         if postfix is None:
1766             postfix=self._defaultParameters['postfix'].value
1767         self.setParameter('postfix', postfix)
1768         if btagPrefix is None:
1769             btagPrefix=self._defaultParameters['btagPrefix'].value
1770         self.setParameter('btagPrefix', btagPrefix)
1771         if jetSource is None:
1772             jetSource=self._defaultParameters['jetSource'].value
1773         self.setParameter('jetSource', jetSource)
1774         if pfCandidates is None:
1775             pfCandidates=self._defaultParameters['pfCandidates'].value
1776         self.setParameter('pfCandidates', pfCandidates)
1777         if explicitJTA is None:
1778             explicitJTA=self._defaultParameters['explicitJTA'].value
1779         self.setParameter('explicitJTA', explicitJTA)
1780         if pvSource is None:
1781             pvSource=self._defaultParameters['pvSource'].value
1782         self.setParameter('pvSource', pvSource)
1783         if svSource is None:
1784             svSource=self._defaultParameters['svSource'].value
1785         self.setParameter('svSource', svSource)
1786         if elSource is None:
1787             elSource=self._defaultParameters['elSource'].value
1788         self.setParameter('elSource', elSource)
1789         if muSource is None:
1790             muSource=self._defaultParameters['muSource'].value
1791         self.setParameter('muSource', muSource)
1792         if runIVF is None:
1793             runIVF=self._defaultParameters['runIVF'].value
1794         self.setParameter('runIVF', runIVF)
1795         if tightBTagNTkHits is None:
1796             tightBTagNTkHits=self._defaultParameters['tightBTagNTkHits'].value
1797         self.setParameter('tightBTagNTkHits', tightBTagNTkHits)
1798         if loadStdRecoBTag is None:
1799             loadStdRecoBTag=self._defaultParameters['loadStdRecoBTag'].value
1800         self.setParameter('loadStdRecoBTag', loadStdRecoBTag)
1801         if svClustering is None:
1802             svClustering=self._defaultParameters['svClustering'].value
1803         self.setParameter('svClustering', svClustering)
1804         if fatJets is None:
1805             fatJets=self._defaultParameters['fatJets'].value
1806         self.setParameter('fatJets', fatJets)
1807         if groomedFatJets is None:
1808             groomedFatJets=self._defaultParameters['groomedFatJets'].value
1809         self.setParameter('groomedFatJets', groomedFatJets)
1810         if algo is None:
1811             algo=self._defaultParameters['algo'].value
1812         self.setParameter('algo', algo)
1813         if rParam is None:
1814             rParam=self._defaultParameters['rParam'].value
1815         self.setParameter('rParam', rParam)
1816         if getJetMCFlavour is None:
1817             getJetMCFlavour=self._defaultParameters['getJetMCFlavour'].value
1818         self.setParameter('getJetMCFlavour', getJetMCFlavour)
1819         if genJetCollection is None:
1820             genJetCollection=self._defaultParameters['genJetCollection'].value
1821         self.setParameter('genJetCollection', genJetCollection)
1822         if genParticles is None:
1823             genParticles=self._defaultParameters['genParticles'].value
1824         self.setParameter('genParticles', genParticles)
1825         if jetCorrections is None:
1826             jetCorrections=self._defaultParameters['jetCorrections'].value
1827         self.setParameter('jetCorrections', jetCorrections)
1828         if btagDiscriminators is None:
1829             btagDiscriminators=self._defaultParameters['btagDiscriminators'].value
1830         self.setParameter('btagDiscriminators', btagDiscriminators)
1831         if btagInfos is None:
1832             btagInfos=self._defaultParameters['btagInfos'].value
1833         self.setParameter('btagInfos', btagInfos)
1834         if jetTrackAssociation is None:
1835             jetTrackAssociation=self._defaultParameters['jetTrackAssociation'].value
1836         self.setParameter('jetTrackAssociation', jetTrackAssociation)
1837         if outputModules is None:
1838             outputModules=self._defaultParameters['outputModules'].value
1839         self.setParameter('outputModules', outputModules)
1840         self.apply(process)
1841 
1842     def toolCode(self, process):
1843         """
1844         Tool code implementation
1845         """
1846         ## initialize parameters
1847         postfix=self._parameters['postfix'].value
1848         btagPrefix=self._parameters['btagPrefix'].value
1849         jetSource=self._parameters['jetSource'].value
1850         pfCandidates=self._parameters['pfCandidates'].value
1851         explicitJTA=self._parameters['explicitJTA'].value
1852         pvSource=self._parameters['pvSource'].value
1853         svSource=self._parameters['svSource'].value
1854         elSource=self._parameters['elSource'].value
1855         muSource=self._parameters['muSource'].value
1856         runIVF=self._parameters['runIVF'].value
1857         tightBTagNTkHits=self._parameters['tightBTagNTkHits'].value
1858         loadStdRecoBTag=self._parameters['loadStdRecoBTag'].value
1859         svClustering=self._parameters['svClustering'].value
1860         fatJets=self._parameters['fatJets'].value
1861         groomedFatJets=self._parameters['groomedFatJets'].value
1862         algo=self._parameters['algo'].value
1863         rParam=self._parameters['rParam'].value
1864         getJetMCFlavour=self._parameters['getJetMCFlavour'].value
1865         genJetCollection=self._parameters['genJetCollection'].value
1866         genParticles=self._parameters['genParticles'].value
1867         jetCorrections=self._parameters['jetCorrections'].value
1868         btagDiscriminators=self._parameters['btagDiscriminators'].value
1869         btagInfos=self._parameters['btagInfos'].value
1870         jetTrackAssociation=self._parameters['jetTrackAssociation'].value
1871         outputModules=self._parameters['outputModules'].value
1872 
1873         ## call addJetCollections w/o labelName; this will act on the default patJets collection
1874         addJetCollection(
1875             process,
1876             labelName='',
1877             postfix=postfix,
1878             btagPrefix=btagPrefix,
1879             jetSource=jetSource,
1880             pfCandidates=pfCandidates,
1881             explicitJTA=explicitJTA,
1882             pvSource=pvSource,
1883             svSource=svSource,
1884             elSource=elSource,
1885             muSource=muSource,
1886             runIVF=runIVF,
1887             tightBTagNTkHits=tightBTagNTkHits,
1888             loadStdRecoBTag=loadStdRecoBTag,
1889             svClustering=svClustering,
1890             fatJets=fatJets,
1891             groomedFatJets=groomedFatJets,
1892             algo=algo,
1893             rParam=rParam,
1894             getJetMCFlavour=getJetMCFlavour,
1895             genJetCollection=genJetCollection,
1896             genParticles=genParticles,
1897             jetCorrections=jetCorrections,
1898             btagDiscriminators=btagDiscriminators,
1899             btagInfos=btagInfos,
1900             jetTrackAssociation=jetTrackAssociation,
1901             outputModules=outputModules,
1902             )
1903 
1904 switchJetCollection=SwitchJetCollection()
1905 
1906 
1907 class UpdateJetCollection(ConfigToolBase):
1908     """
1909     Tool to update a jet collection in your PAT Tuple (primarily intended for MiniAOD for which the default input argument values have been set).
1910     """
1911     _label='updateJetCollection'
1912     _defaultParameters=dicttypes.SortedKeysDict()
1913 
1914     def __init__(self):
1915         """
1916         Initialize elements of the class. Note that the tool needs to be derived from ConfigToolBase to be usable in the configEditor.
1917         """
1918         ## initialization of the base class
1919         ConfigToolBase.__init__(self)
1920         ## add all parameters that should be known to the class
1921         self.addParameter(self._defaultParameters,'labelName', '', "Label name of the new patJet collection.", str)
1922         self.addParameter(self._defaultParameters,'postfix','', "Postfix from usePF2PAT.", str)
1923         self.addParameter(self._defaultParameters,'btagPrefix','', "Prefix to be added to b-tag discriminator and TagInfo names", str)
1924         self.addParameter(self._defaultParameters,'jetSource','', "Label of the input collection from which the new patJet collection should be created", cms.InputTag)
1925         self.addParameter(self._defaultParameters,'pfCandidates',cms.InputTag('packedPFCandidates'), "Label of the input collection for candidatecandidatese used in b-tagging", cms.InputTag)
1926         self.addParameter(self._defaultParameters,'explicitJTA', False, "Use explicit jet-track association")
1927         self.addParameter(self._defaultParameters,'pvSource',cms.InputTag('offlineSlimmedPrimaryVertices'), "Label of the input collection for primary vertices used in b-tagging", cms.InputTag)
1928         self.addParameter(self._defaultParameters,'svSource',cms.InputTag('slimmedSecondaryVertices'), "Label of the input collection for IVF vertices used in b-tagging", cms.InputTag)
1929         self.addParameter(self._defaultParameters,'elSource',cms.InputTag('slimmedElectrons'), "Label of the input collection for electrons used in b-tagging", cms.InputTag)
1930         self.addParameter(self._defaultParameters,'muSource',cms.InputTag('slimmedMuons'), "Label of the input collection for muons used in b-tagging", cms.InputTag)
1931         self.addParameter(self._defaultParameters,'runIVF', False, "Re-run IVF secondary vertex reconstruction")
1932         self.addParameter(self._defaultParameters,'tightBTagNTkHits', False, "Enable legacy tight b-tag track selection")
1933         self.addParameter(self._defaultParameters,'loadStdRecoBTag', False, "Load the standard reconstruction b-tagging modules")
1934         self.addParameter(self._defaultParameters,'svClustering', False, "Secondary vertices ghost-associated to jets using jet clustering (mostly intended for subjets)")
1935         self.addParameter(self._defaultParameters,'fatJets', cms.InputTag(''), "Fat jet collection used for secondary vertex clustering", cms.InputTag)
1936         self.addParameter(self._defaultParameters,'groomedFatJets', cms.InputTag(''), "Groomed fat jet collection used for secondary vertex clustering", cms.InputTag)
1937         self.addParameter(self._defaultParameters,'algo', 'AK', "Jet algorithm of the input collection from which the new patJet collection should be created")
1938         self.addParameter(self._defaultParameters,'rParam', 0.4, "Jet size (distance parameter R used in jet clustering)")
1939         self.addParameter(self._defaultParameters,'sortByPt', True, "Set to False to not modify incoming jet order")
1940         self.addParameter(self._defaultParameters,'printWarning', True, "To be use as False in production to reduce log size")
1941         self.addParameter(self._defaultParameters,'jetCorrections',None, "Add all relevant information about jet energy corrections that you want to be added to your new patJet \
1942         collection. The format has to be given in a python tuple of type: (\'AK4Calo\',[\'L2Relative\', \'L3Absolute\'], patMet). Here the first argument corresponds to the payload \
1943         in the CMS Conditions database for the given jet collection; the second argument corresponds to the jet energy correction levels that you want to be embedded into your \
1944         new patJet collection. This should be given as a list of strings. Available values are L1Offset, L1FastJet, L1JPTOffset, L2Relative, L3Absolute, L5Falvour, L7Parton; the \
1945         third argument indicates whether MET(Type1/2) corrections should be applied corresponding to the new patJetCollection. If so a new patMet collection will be added to your PAT \
1946         Tuple in addition to the raw patMet. This new patMet collection will have the MET(Type1/2) corrections applied. The argument can have the following types: \'type-1\' for \
1947         type-1 corrected MET; \'type-2\' for type-1 plus type-2 corrected MET; \'\' or \'none\' if no further MET corrections should be applied to your MET. The arguments \'type-1\' \
1948         and \'type-2\' are not case sensitive.", tuple, acceptNoneValue=True)
1949         self.addParameter(self._defaultParameters,'btagDiscriminators',['None'], "If you are interested in btagging, in most cases just the labels of the btag discriminators that \
1950         you are interested in is all relevant information that you need for a high level analysis. Add here all btag discriminators, that you are interested in as a list of strings. \
1951         If this list is empty no btag discriminator information will be added to your new patJet collection.", allowedValues=(list(set().union(supportedBtagDiscr.keys(),supportedMetaDiscr.keys()))),Type=list)
1952         self.addParameter(self._defaultParameters,'btagInfos',['None'], "The btagInfos objects contain all relevant information from which all discriminators of a certain \
1953         type have been calculated. You might be interested in keeping this information for low level tests or to re-calculate some discriminators from hand. Note that this information \
1954         on the one hand can be very space consuming and that it is not necessary to access the pre-calculated btag discriminator information that has been derived from it. Only in very \
1955         special cases the btagInfos might really be needed in your analysis. Add here all btagInfos, that you are interested in as a list of strings. If this list is empty no btagInfos \
1956         will be added to your new patJet collection.", allowedValues=supportedBtagInfos,Type=list)
1957         self.addParameter(self._defaultParameters,'outputModules',['out'],"Add a list of all output modules to which you would like the new jet collection to be added. Usually this is \
1958         just one single output module with name \'out\', which corresponds also the default configuration of the tool. There is cases though where you might want to add this collection \
1959         to more than one output module.")
1960         ## set defaults
1961         self._parameters=copy.deepcopy(self._defaultParameters)
1962         ## add comments
1963         self._comment = "This is a tool to add more patJet collectinos to your PAT Tuple or to re-configure the default collection. You can add and embed additional information like jet\
1964         energy correction factors, btag information and generator match information to the new patJet collection depending on the parameters that you pass on to this function. Consult \
1965         the descriptions of each parameter for more information."
1966 
1967     def getDefaultParameters(self):
1968         """
1969         Return default parameters of the class
1970         """
1971         return self._defaultParameters
1972 
1973     def __call__(self,process,labelName=None,postfix=None,btagPrefix=None,jetSource=None,pfCandidates=None,explicitJTA=None,pvSource=None,svSource=None,elSource=None,muSource=None,runIVF=None,tightBTagNTkHits=None,loadStdRecoBTag=None,svClustering=None,fatJets=None,groomedFatJets=None,algo=None,rParam=None,sortByPt=None,printWarning=None,jetCorrections=None,btagDiscriminators=None,btagInfos=None):
1974         """
1975         Function call wrapper. This will check the parameters and call the actual implementation that
1976         can be found in toolCode via the base class function apply.
1977         """
1978         if labelName is None:
1979             labelName=self._defaultParameters['labelName'].value
1980         self.setParameter('labelName', labelName)
1981         if postfix is None:
1982             postfix=self._defaultParameters['postfix'].value
1983         self.setParameter('postfix', postfix)
1984         if btagPrefix is None:
1985             btagPrefix=self._defaultParameters['btagPrefix'].value
1986         self.setParameter('btagPrefix', btagPrefix)
1987         if jetSource is None:
1988             jetSource=self._defaultParameters['jetSource'].value
1989         self.setParameter('jetSource', jetSource)
1990         if pfCandidates is None:
1991             pfCandidates=self._defaultParameters['pfCandidates'].value
1992         self.setParameter('pfCandidates', pfCandidates)
1993         if explicitJTA is None:
1994             explicitJTA=self._defaultParameters['explicitJTA'].value
1995         self.setParameter('explicitJTA', explicitJTA)
1996         if pvSource is None:
1997             pvSource=self._defaultParameters['pvSource'].value
1998         self.setParameter('pvSource', pvSource)
1999         if svSource is None:
2000             svSource=self._defaultParameters['svSource'].value
2001         self.setParameter('svSource', svSource)
2002         if elSource is None:
2003             elSource=self._defaultParameters['elSource'].value
2004         self.setParameter('elSource', elSource)
2005         if muSource is None:
2006             muSource=self._defaultParameters['muSource'].value
2007         self.setParameter('muSource', muSource)
2008         if runIVF is None:
2009             runIVF=self._defaultParameters['runIVF'].value
2010         self.setParameter('runIVF', runIVF)
2011         if tightBTagNTkHits is None:
2012             tightBTagNTkHits=self._defaultParameters['tightBTagNTkHits'].value
2013         self.setParameter('tightBTagNTkHits', tightBTagNTkHits)
2014         if loadStdRecoBTag is None:
2015             loadStdRecoBTag=self._defaultParameters['loadStdRecoBTag'].value
2016         self.setParameter('loadStdRecoBTag', loadStdRecoBTag)
2017         if svClustering is None:
2018             svClustering=self._defaultParameters['svClustering'].value
2019         self.setParameter('svClustering', svClustering)
2020         if fatJets is None:
2021             fatJets=self._defaultParameters['fatJets'].value
2022         self.setParameter('fatJets', fatJets)
2023         if groomedFatJets is None:
2024             groomedFatJets=self._defaultParameters['groomedFatJets'].value
2025         self.setParameter('groomedFatJets', groomedFatJets)
2026         if algo is None:
2027             algo=self._defaultParameters['algo'].value
2028         self.setParameter('algo', algo)
2029         if rParam is None:
2030             rParam=self._defaultParameters['rParam'].value
2031         self.setParameter('rParam', rParam)
2032         if sortByPt is None:
2033             sortByPt=self._defaultParameters['sortByPt'].value
2034         self.setParameter('sortByPt', sortByPt)
2035         if printWarning is None:
2036             printWarning=self._defaultParameters['printWarning'].value
2037         self.setParameter('printWarning', printWarning)
2038         if jetCorrections is None:
2039             jetCorrections=self._defaultParameters['jetCorrections'].value
2040         self.setParameter('jetCorrections', jetCorrections)
2041         if btagDiscriminators is None:
2042             btagDiscriminators=self._defaultParameters['btagDiscriminators'].value
2043         self.setParameter('btagDiscriminators', btagDiscriminators)
2044         if btagInfos is None:
2045             btagInfos=self._defaultParameters['btagInfos'].value
2046         self.setParameter('btagInfos', btagInfos)
2047         self.apply(process)
2048 
2049     def toolCode(self, process):
2050         """
2051         Tool code implementation
2052         """
2053         ## initialize parameters
2054         labelName=self._parameters['labelName'].value
2055         postfix=self._parameters['postfix'].value
2056         btagPrefix=self._parameters['btagPrefix'].value
2057         jetSource=self._parameters['jetSource'].value
2058         pfCandidates=self._parameters['pfCandidates'].value
2059         explicitJTA=self._parameters['explicitJTA'].value
2060         pvSource=self._parameters['pvSource'].value
2061         svSource=self._parameters['svSource'].value
2062         elSource=self._parameters['elSource'].value
2063         muSource=self._parameters['muSource'].value
2064         runIVF=self._parameters['runIVF'].value
2065         tightBTagNTkHits=self._parameters['tightBTagNTkHits'].value
2066         loadStdRecoBTag=self._parameters['loadStdRecoBTag'].value
2067         svClustering=self._parameters['svClustering'].value
2068         fatJets=self._parameters['fatJets'].value
2069         groomedFatJets=self._parameters['groomedFatJets'].value
2070         algo=self._parameters['algo'].value
2071         rParam=self._parameters['rParam'].value
2072         sortByPt=self._parameters['sortByPt'].value
2073         printWarning=self._parameters['printWarning'].value
2074         jetCorrections=self._parameters['jetCorrections'].value
2075         btagDiscriminators=list(self._parameters['btagDiscriminators'].value)
2076         btagInfos=list(self._parameters['btagInfos'].value)
2077 
2078         ## a list of all producer modules, which are already known to process
2079         knownModules = process.producerNames().split()
2080         ## determine whether btagging information is required or not
2081         if btagDiscriminators.count('None')>0:
2082             btagDiscriminators.remove('None')
2083         if btagInfos.count('None')>0:
2084             btagInfos.remove('None')
2085         bTagging=(len(btagDiscriminators)>0 or len(btagInfos)>0)
2086 
2087         ## construct postfix label for auxiliary modules; this postfix
2088         ## label will start with a capitalized first letter following
2089         ## the CMS naming conventions and for improved readablility
2090         _labelName=labelName[:1].upper()+labelName[1:]
2091 
2092         ## supported algo types are ak, ca, and kt
2093         _algo=''
2094         for x in ["ak", "ca", "kt"]:
2095             if x in algo.lower():
2096                 _algo=supportedJetAlgos[x]
2097                 break
2098         if _algo=='':
2099             unsupportedJetAlgorithm(self)
2100 
2101         task = getPatAlgosToolsTask(process)
2102 
2103         ## add new updatedPatJets to process (keep instance for later further modifications)
2104         from PhysicsTools.PatAlgos.producersLayer1.jetUpdater_cfi import updatedPatJets
2105         if not sortByPt: # default is True
2106             updatedPatJets.sort = cms.bool(False)
2107         if 'updatedPatJets'+_labelName+postfix in knownModules :
2108             _newPatJets=getattr(process, 'updatedPatJets'+_labelName+postfix)
2109             _newPatJets.jetSource=jetSource
2110         else :
2111             addToProcessAndTask('updatedPatJets'+_labelName+postfix,
2112                                 updatedPatJets.clone(jetSource=jetSource,
2113                                 printWarning=printWarning), process, task)
2114             _newPatJets=getattr(process, 'updatedPatJets'+_labelName+postfix)
2115             knownModules.append('updatedPatJets'+_labelName+postfix)
2116         ## add new selectedUpdatedPatJets to process
2117         from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets
2118         if 'selectedUpdatedPatJets'+_labelName+postfix in knownModules :
2119             _newSelectedPatJets=getattr(process, 'selectedUpdatedPatJets'+_labelName+postfix)
2120             _newSelectedPatJets.src='updatedPatJets'+_labelName+postfix
2121         else :
2122             addToProcessAndTask('selectedUpdatedPatJets'+_labelName+postfix,
2123                                 selectedPatJets.clone(src='updatedPatJets'+_labelName+postfix),
2124                                 process, task)
2125             knownModules.append('selectedUpdatedPatJets'+_labelName+postfix)
2126 
2127         ## run btagging if required by user
2128         if (bTagging):
2129             if printWarning:
2130                sys.stderr.write("**************************************************************\n")
2131                sys.stderr.write("b tagging needs to be run on uncorrected jets. Hence, the JECs\n")
2132                sys.stderr.write("will first be undone for 'updatedPatJets%s' and then applied to\n" % (_labelName+postfix) )
2133                sys.stderr.write("'updatedPatJetsTransientCorrected%s'.\n" % (_labelName+postfix) )
2134                sys.stderr.write("**************************************************************\n")
2135             _jetSource = cms.InputTag('updatedPatJets'+_labelName+postfix)
2136             ## insert new jet collection with jet corrections applied and btag info added
2137             self(
2138                 process,
2139                 labelName = ('TransientCorrected'+_labelName),
2140                 jetSource = _jetSource,
2141                 pfCandidates=pfCandidates,
2142                 explicitJTA=explicitJTA,
2143                 pvSource=pvSource,
2144                 svSource=svSource,
2145                 elSource=elSource,
2146                 muSource=muSource,
2147                 runIVF=runIVF,
2148                 tightBTagNTkHits=tightBTagNTkHits,
2149                 loadStdRecoBTag=loadStdRecoBTag,
2150                 svClustering=svClustering,
2151                 fatJets=fatJets,
2152                 groomedFatJets=groomedFatJets,
2153                 algo=algo,
2154                 rParam=rParam,
2155                 jetCorrections = jetCorrections,
2156                 btagPrefix = btagPrefix,
2157                 postfix = postfix
2158             )
2159             ## setup btagging
2160             _patJets=getattr(process, 'updatedPatJetsTransientCorrected'+_labelName+postfix)
2161             setupBTagging(process, _jetSource, pfCandidates, explicitJTA, pvSource, svSource, elSource, muSource, runIVF, tightBTagNTkHits, loadStdRecoBTag, svClustering, fatJets, groomedFatJets,
2162                           _algo, rParam, btagDiscriminators, btagInfos, _patJets, _labelName, btagPrefix, postfix)
2163             ## update final selected jets
2164             _newSelectedPatJets=getattr(process, 'selectedUpdatedPatJets'+_labelName+postfix)
2165             _newSelectedPatJets.src='updatedPatJetsTransientCorrected'+_labelName+postfix
2166             ## remove automatically added but redundant 'TransientCorrected' selected jets
2167             delattr(process, 'selectedUpdatedPatJetsTransientCorrected'+_labelName+postfix)
2168         else:
2169             _newPatJets.addBTagInfo = False
2170             _newPatJets.addTagInfos = False
2171 
2172         ## add jet correction factors if required by user
2173         if (jetCorrections is not None or bTagging):
2174             ## check the jet corrections format
2175             if jetCorrections is None and bTagging:
2176                 raise ValueError("Passing jetCorrections = None while running bTagging is likely not intended.")
2177             else:
2178                 checkJetCorrectionsFormat(jetCorrections)
2179             ## reset MET corrrection
2180             if jetCorrections[2].lower() != 'none' and jetCorrections[2] != '':
2181                 sys.stderr.write("-------------------------------------------------------------------\n")
2182                 sys.stderr.write(" Warning: MET correction was set to " + jetCorrections[2] + " but\n")
2183                 sys.stderr.write("          will be ignored. Please set it to \"None\" to avoid\n")
2184                 sys.stderr.write("          getting this warning.\n")
2185                 sys.stderr.write("-------------------------------------------------------------------\n")
2186                 jetCorrectionsList = list(jetCorrections)
2187                 jetCorrectionsList[2] = 'None'
2188                 jetCorrections = tuple(jetCorrectionsList)
2189             ## if running b tagging, need to use uncorrected jets
2190             if (bTagging):
2191                 jetCorrections = ('AK4PFchs', cms.vstring([]), 'None')
2192             ## setup jet energy corrections
2193             setupJetCorrections(process, knownModules, jetCorrections, jetSource, pvSource, _newPatJets, _labelName, postfix)
2194         else:
2195             ## switch jetCorrFactors off
2196             _newPatJets.addJetCorrFactors=False
2197 
2198 updateJetCollection=UpdateJetCollection()
2199 
2200 
2201 class AddJetID(ConfigToolBase):
2202     """
2203     Compute jet id for process
2204     """
2205     _label='addJetID'
2206     _defaultParameters=dicttypes.SortedKeysDict()
2207     def __init__(self):
2208         ConfigToolBase.__init__(self)
2209         self.addParameter(self._defaultParameters,'jetSrc','', "", Type=cms.InputTag)
2210         self.addParameter(self._defaultParameters,'jetIdTag','', "Tag to append to jet id map", Type=str)
2211         self._parameters=copy.deepcopy(self._defaultParameters)
2212         self._comment = ""
2213 
2214     def getDefaultParameters(self):
2215         return self._defaultParameters
2216 
2217     def __call__(self,process,
2218                  jetSrc     = None,
2219                  jetIdTag    = None) :
2220         if  jetSrc is None:
2221             jetSrc=self._defaultParameters['jetSrc'].value
2222         if  jetIdTag is None:
2223             jetIdTag=self._defaultParameters['jetIdTag'].value
2224         self.setParameter('jetSrc',jetSrc)
2225         self.setParameter('jetIdTag',jetIdTag)
2226         self.apply(process)
2227 
2228     def toolCode(self, process):
2229         jetSrc=self._parameters['jetSrc'].value
2230         jetIdTag=self._parameters['jetIdTag'].value
2231 
2232         jetIdLabel = jetIdTag + 'JetID'
2233         sys.stderr.write("Making new jet ID label with label " + jetIdTag + "\n")
2234 
2235         ## replace jet id sequence
2236         task = getPatAlgosToolsTask(process)
2237         process.load("RecoJets.JetProducers.ak4JetID_cfi")
2238         task.add(process.ak4JetID)
2239         addToProcessAndTask(jetIdLabel, process.ak4JetID.clone(src = jetSrc),
2240                             process, task)
2241 
2242 
2243 addJetID=AddJetID()
2244 
2245 
2246 class SetTagInfos(ConfigToolBase):
2247     """
2248     Replace tag infos for collection jetSrc
2249     """
2250     _label='setTagInfos'
2251     _defaultParameters=dicttypes.SortedKeysDict()
2252     def __init__(self):
2253         ConfigToolBase.__init__(self)
2254         self.addParameter(self._defaultParameters,'coll',"patJets","jet collection to set tag infos for")
2255         self.addParameter(self._defaultParameters,'tagInfos',cms.vstring( ), "tag infos to set")
2256         self._parameters=copy.deepcopy(self._defaultParameters)
2257         self._comment = ""
2258 
2259     def getDefaultParameters(self):
2260         return self._defaultParameters
2261 
2262     def __call__(self,process,
2263                  coll         = None,
2264                  tagInfos     = None) :
2265         if  coll is None:
2266             coll=self._defaultParameters['coll'].value
2267         if  tagInfos is None:
2268             tagInfos=self._defaultParameters['tagInfos'].value
2269         self.setParameter('coll',coll)
2270         self.setParameter('tagInfos',tagInfos)
2271         self.apply(process)
2272 
2273     def toolCode(self, process):
2274         coll=self._parameters['coll'].value
2275         tagInfos=self._parameters['tagInfos'].value
2276 
2277         found = False
2278         newTags = cms.VInputTag()
2279         iNewTags = 0
2280         for k in tagInfos :
2281             for j in getattr( process, coll ).tagInfoSources :
2282                 vv = j.value();
2283                 if ( vv.find(k) != -1 ):
2284                     found = True
2285                     newTags.append( j )
2286 
2287         if not found:
2288             raise RuntimeError("""
2289             Cannot replace tag infos in jet collection""" % (coll))
2290         else :
2291             getattr(process,coll).tagInfoSources = newTags
2292 
2293 setTagInfos=SetTagInfos()
2294 
2295 def deprecatedOptionOutputModule(obj):
2296     sys.stderr.write("-------------------------------------------------------\n")
2297     sys.stderr.write(" Error: the option 'outputModule' is not supported\n")
2298     sys.stderr.write("        anymore by:\n")
2299     sys.stderr.write("                     " + obj._label + "\n")
2300     sys.stderr.write("        please use 'outputModules' now and specify the\n")
2301     sys.stderr.write("        names of all needed OutModules in there\n")
2302     sys.stderr.write("        (default: ['out'])\n")
2303     sys.stderr.write("-------------------------------------------------------\n")
2304     raise KeyError("Unsupported option 'outputModule' used in '"+obj._label+"'")
2305 
2306 def undefinedLabelName(obj):
2307     sys.stderr.write("-------------------------------------------------------\n")
2308     sys.stderr.write(" Error: the jet 'labelName' is not defined.\n")
2309     sys.stderr.write("        All added jets must have 'labelName' defined.\n")
2310     sys.stderr.write("-------------------------------------------------------\n")
2311     raise KeyError("Undefined jet 'labelName' used in '"+obj._label+"'")
2312 
2313 def unsupportedJetAlgorithm(obj):
2314     sys.stderr.write("-------------------------------------------------------\n")
2315     sys.stderr.write(" Error: Unsupported jet algorithm detected.\n")
2316     sys.stderr.write("        The supported algorithms are:\n")
2317     for key in supportedJetAlgos.keys():
2318         sys.stderr.write("        " + key.upper() + ", " + key.lower() + ": " + supportedJetAlgos[key] + "\n")
2319     sys.stderr.write("-------------------------------------------------------\n")
2320     raise KeyError("Unsupported jet algorithm used in '"+obj._label+"'")
2321 
2322 def rerunningIVF():
2323     sys.stderr.write("-------------------------------------------------------------------\n")
2324     sys.stderr.write(" Warning: You are attempting to remake the IVF secondary vertices\n")
2325     sys.stderr.write("          already produced by the standard reconstruction. This\n")
2326     sys.stderr.write("          option is not enabled by default so please use it only if\n")
2327     sys.stderr.write("          you know what you are doing.\n")
2328     sys.stderr.write("-------------------------------------------------------------------\n")
2329 
2330 def rerunningIVFMiniAOD():
2331     sys.stderr.write("-------------------------------------------------------------------\n")
2332     sys.stderr.write(" Warning: You are attempting to remake IVF secondary vertices from\n")
2333     sys.stderr.write("          MiniAOD. If that was your intention, note that secondary\n")
2334     sys.stderr.write("          vertices remade from MiniAOD will have somewhat degraded\n")
2335     sys.stderr.write("          performance compared to those remade from RECO/AOD.\n")
2336     sys.stderr.write("-------------------------------------------------------------------\n")