File indexing completed on 2024-11-27 03:18:00
0001 import FWCore.ParameterSet.Config as cms
0002
0003 from PhysicsTools.PatAlgos.tools.coreTools import *
0004 from PhysicsTools.PatAlgos.tools.jetTools import *
0005 from PhysicsTools.PatAlgos.tools.tauTools import *
0006
0007 from PhysicsTools.PatAlgos.tools.helpers import listModules, applyPostfix, getPatAlgosToolsTask, addToProcessAndTask
0008
0009 from copy import deepcopy
0010
0011 def warningIsolation():
0012 print("WARNING: particle based isolation must be studied")
0013
0014 def adaptPFMuons(process,module,postfix="", muonMatchModule=None ):
0015 print("Adapting PF Muons ")
0016 print("***************** ")
0017
0018 print()
0019 module.useParticleFlow = True
0020 module.pfMuonSource = cms.InputTag("pfIsolatedMuonsPFBRECO" + postfix)
0021 module.userIsolation = cms.PSet()
0022
0023
0024
0025
0026
0027
0028
0029
0030
0031
0032
0033
0034
0035
0036
0037 if muonMatchModule == None :
0038 applyPostfix(process,"muonMatch",postfix).src = module.pfMuonSource
0039 else :
0040 muonMatchModule.src = module.pfMuonSource
0041
0042 print(" muon source:", module.pfMuonSource)
0043
0044
0045
0046
0047 print()
0048
0049
0050 def adaptPFElectrons(process,module, postfix):
0051
0052 print("Adapting PF Electrons ")
0053 print("********************* ")
0054
0055 print()
0056 module.useParticleFlow = True
0057 module.pfElectronSource = cms.InputTag("pfIsolatedElectronsPFBRECO" + postfix)
0058 module.userIsolation = cms.PSet()
0059
0060
0061
0062
0063
0064
0065
0066
0067
0068
0069
0070
0071
0072
0073
0074
0075
0076
0077
0078
0079
0080 print(" PF electron source:", module.pfElectronSource)
0081
0082
0083
0084
0085 print()
0086
0087
0088
0089
0090 def adaptPFPhotons(process,module):
0091 raise RuntimeError("Photons are not supported yet")
0092
0093 from RecoTauTag.RecoTau.TauDiscriminatorTools import adaptTauDiscriminator, producerIsTauTypeMapper
0094
0095 def reconfigurePF2PATTaus(process,
0096 tauType='shrinkingConePFTau',
0097 pf2patSelection=["DiscriminationByIsolation", "DiscriminationByLeadingPionPtCut"],
0098 selectionDependsOn=["DiscriminationByLeadingTrackFinding"],
0099 producerFromType=lambda producer: producer+"Producer",
0100 postfix = ""):
0101 print("patTaus will be produced from taus of type: %s that pass %s" \
0102 % (tauType, pf2patSelection))
0103
0104
0105
0106
0107 producerName = producerFromType(tauType)
0108
0109 applyPostfix(process,"pfTaus", postfix).src = producerName+postfix
0110
0111 oldTauSansRefs = getattr(process,'pfTausProducerSansRefs'+postfix)
0112 oldTau = getattr(process,'pfTausProducer'+postfix)
0113
0114 newTauSansRefs = None
0115 newTau = getattr(process,producerName+postfix).clone()
0116
0117
0118 if tauType=='shrinkingConePFTau':
0119 newTauSansRefs = getattr(process,producerName+"SansRefs").clone()
0120 newTauSansRefs.modifiers[1] = cms.PSet(
0121 pfTauTagInfoSrc = cms.InputTag("pfTauTagInfoProducer"+postfix),
0122 name = cms.string('pfTauTTIworkaround'+postfix),
0123 plugin = cms.string('RecoTauTagInfoWorkaroundModifer')
0124 )
0125 newTau.modifiers[1] = newTauSansRefs.modifiers[1]
0126 newTauSansRefs.piZeroSrc = "pfJetsLegacyTaNCPiZeros"+postfix
0127 newTau.piZeroSrc = newTauSansRefs.piZeroSrc
0128 newTauSansRefs.builders[0].pfCandSrc = oldTauSansRefs.builders[0].pfCandSrc
0129 newTauSansRefs.jetRegionSrc = oldTauSansRefs.jetRegionSrc
0130 newTauSansRefs.jetSrc = oldTauSansRefs.jetSrc
0131 elif tauType=='fixedConePFTau':
0132 newTau.piZeroSrc = "pfJetsLegacyTaNCPiZeros"+postfix
0133 elif tauType=='hpsPFTau':
0134 newTau = getattr(process,'combinatoricRecoTaus'+postfix).clone()
0135 newTau.piZeroSrc="pfJetsLegacyHPSPiZeros"+postfix
0136 newTau.modifiers[3] = cms.PSet(
0137 pfTauTagInfoSrc = cms.InputTag("pfTauTagInfoProducer"+postfix),
0138 name = cms.string('pfTauTTIworkaround'+postfix),
0139 plugin = cms.string('RecoTauTagInfoWorkaroundModifer')
0140 )
0141 from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet
0142
0143 setattr(process,'produceHPSPFTaus'+postfix,cms.Sequence(applyPostfix(process,'hpsSelectionDiscriminator',postfix)+applyPostfix(process,'hpsPFTauProducerSansRefs',postfix)+applyPostfix(process,'hpsPFTauProducer',postfix)))
0144 massSearchReplaceParam(getattr(process,"produceHPSPFTaus"+postfix),
0145 "PFTauProducer",
0146 cms.InputTag("combinatoricRecoTaus"+postfix),
0147 cms.InputTag("pfTausBase"+postfix) )
0148 massSearchReplaceParam(getattr(process,"produceHPSPFTaus"+postfix),
0149 "src",
0150 cms.InputTag("combinatoricRecoTaus"+postfix),
0151 cms.InputTag("pfTausBase"+postfix) )
0152
0153
0154
0155
0156
0157
0158
0159
0160 task = getPatAlgosToolsTask(process)
0161 addToProcessAndTask("pfTausBase"+postfix, newTau, process, task)
0162 if tauType=='shrinkingConePFTau':
0163 addToProcessAndTask("pfTausBaseSansRefs"+postfix, newTauSansRefs, process, task)
0164 getattr(process,"pfTausBase"+postfix).src = "pfTausBaseSansRefs"+postfix
0165 baseSequence += getattr(process,"pfTausBaseSansRefs"+postfix)
0166
0167
0168 def producerIsTauTypeMapperWithPostfix(tauProducer):
0169 return lambda x: producerIsTauTypeMapper(tauProducer)+x.group(1)+postfix
0170
0171 def recoTauTypeMapperWithGroup(tauProducer):
0172 return "%s(.*)"%recoTauTypeMapper(tauProducer)
0173
0174
0175 for predisc in selectionDependsOn:
0176
0177 originalName = tauType+predisc
0178 clonedName = "pfTausBase"+predisc+postfix
0179 clonedDisc = getattr(process, originalName).clone()
0180 addToProcessAndTask(clonedName, clonedDisc, process, task)
0181
0182 tauCollectionToSelect = None
0183 if tauType != 'hpsPFTau' :
0184 tauCollectionToSelect = "pfTausBase"+postfix
0185
0186 else:
0187 tauCollectionToSelect = "hpsPFTauProducer"+postfix
0188
0189 adaptTauDiscriminator(clonedDisc, newTauProducer="pfTausBase",
0190 oldTauTypeMapper=recoTauTypeMapperWithGroup,
0191 newTauTypeMapper=producerIsTauTypeMapperWithPostfix,
0192 preservePFTauProducer=True)
0193 clonedDisc.PFTauProducer = tauCollectionToSelect
0194
0195
0196 getattr(process,"pfTaus" + postfix).discriminators = cms.VPSet()
0197 for selection in pf2patSelection:
0198
0199 originalName = tauType+selection
0200 clonedName = "pfTausBase"+selection+postfix
0201 clonedDisc = getattr(process, originalName).clone()
0202 addToProcessAndTask(clonedName, clonedDisc, process, task)
0203
0204 tauCollectionToSelect = None
0205
0206 if tauType != 'hpsPFTau' :
0207 tauCollectionToSelect = cms.InputTag("pfTausBase"+postfix)
0208
0209 else:
0210 tauCollectionToSelect = cms.InputTag("hpsPFTauProducer"+postfix)
0211
0212 adaptTauDiscriminator(clonedDisc, newTauProducer="pfTausBase",
0213 oldTauTypeMapper=recoTauTypeMapperWithGroup,
0214 newTauTypeMapper=producerIsTauTypeMapperWithPostfix,
0215 preservePFTauProducer=True)
0216 clonedDisc.PFTauProducer = tauCollectionToSelect
0217
0218
0219 getattr(process,"pfTaus" + postfix).discriminators.append(cms.PSet(
0220 discriminator=cms.InputTag(clonedName), selectionCut=cms.double(0.5)))
0221
0222 if tauType != 'hpsPFTau':
0223 getattr(process,"pfTaus" + postfix).src = "pfTausBase"+postfix
0224 else:
0225
0226
0227 getattr(process,"pfTaus" + postfix).src = "hpsPFTauProducer"+postfix
0228
0229
0230
0231 def adaptPFTaus(process,tauType = 'shrinkingConePFTau', postfix = ""):
0232
0233 if tauType != 'hpsPFTau' :
0234 reconfigurePF2PATTaus(process, tauType, postfix=postfix)
0235 else:
0236 reconfigurePF2PATTaus(process, tauType,
0237 ["DiscriminationByDecayModeFinding"],
0238 ["DiscriminationByDecayModeFinding"],
0239 postfix=postfix)
0240
0241 if tauType != 'hpsPFTau' :
0242 getattr(process,"patTaus" + postfix).tauSource = cms.InputTag("pfTausBase"+postfix)
0243 else:
0244 getattr(process,"patTaus" + postfix).tauSource = cms.InputTag("hpsPFTauProducer"+postfix)
0245
0246
0247
0248
0249
0250
0251
0252
0253
0254
0255 if tauType != 'hpsPFTau' :
0256 switchToPFTauByType(process, pfTauType=tauType,
0257 patTauLabel="pfTausBase"+postfix,
0258 tauSource=cms.InputTag(tauType+'Producer'+postfix),
0259 postfix=postfix)
0260 getattr(process,"patTaus" + postfix).tauSource = cms.InputTag("pfTausBase"+postfix)
0261 else:
0262 switchToPFTauByType(process, pfTauType=tauType,
0263 patTauLabel="",
0264 tauSource=cms.InputTag(tauType+'Producer'+postfix),
0265 postfix=postfix)
0266 getattr(process,"patTaus" + postfix).tauSource = cms.InputTag("hpsPFTauProducer"+postfix)
0267
0268
0269
0270
0271 def tauTypeInPF2PAT(process,tauType='shrinkingConePFTau', postfix = ""):
0272 process.load("CommonTools.ParticleFlow.pfTaus_cff")
0273 applyPostfix(process, "pfTaus",postfix).src = cms.InputTag(tauType+'Producer'+postfix)
0274
0275
0276 def addPFCandidates(process,src,patLabel='PFParticles',cut="",postfix=""):
0277 from PhysicsTools.PatAlgos.producersLayer1.pfParticleProducer_cfi import patPFParticles
0278
0279 producer = patPFParticles.clone(pfCandidateSource = src)
0280 filter = cms.EDFilter("PATPFParticleSelector",
0281 src = cms.InputTag("pat" + patLabel),
0282 cut = cms.string(cut))
0283 counter = cms.EDFilter("PATCandViewCountFilter",
0284 minNumber = cms.uint32(0),
0285 maxNumber = cms.uint32(999999),
0286 src = cms.InputTag("pat" + patLabel))
0287
0288 task = getPatAlgosToolsTask(process)
0289 addToProcessAndTask("pat" + patLabel, producer, process, task)
0290 addToProcessAndTask("selectedPat" + patLabel, filter, process, task)
0291 addToProcessAndTask("countPat" + patLabel, counter, process, task)
0292
0293
0294 applyPostfix(process, "patCandidateSummary", postfix).candidates.append(cms.InputTag('pat' + patLabel))
0295 applyPostfix(process, "selectedPatCandidateSummary", postfix).candidates.append(cms.InputTag('selectedPat' + patLabel))
0296
0297
0298 def switchToPFMET(process,input=cms.InputTag('pfMETPFBRECO'), type1=False, postfix=""):
0299 print('MET: using ', input)
0300 if( not type1 ):
0301 oldMETSource = applyPostfix(process, "patMETs",postfix).metSource
0302 applyPostfix(process, "patMETs",postfix).metSource = input
0303 applyPostfix(process, "patMETs",postfix).addMuonCorrections = False
0304 else:
0305
0306
0307 print('Apply TypeI corrections for MET')
0308
0309 jecLabel = getattr(process,'patJetCorrFactors'+postfix).payload.pythonValue().replace("'","")
0310 getattr(process,jecLabel+'Type1CorMet'+postfix).src = input.getModuleLabel()
0311
0312
0313
0314 def switchToPFJets(process, input=cms.InputTag('pfNoTauClones'), algo='AK4', postfix = "", jetCorrections=('AK4PFchs', ['L1FastJet','L2Relative', 'L3Absolute']), type1=False, outputModules=['out']):
0315
0316 print("Switching to PFJets, ", algo)
0317 print("************************ ")
0318 print("input collection: ", input)
0319
0320 if algo == 'AK4':
0321 genJetCollection = cms.InputTag('ak4GenJetsNoNu'+postfix)
0322 rParam=0.4
0323 elif algo == 'AK7':
0324 genJetCollection = cms.InputTag('ak7GenJetsNoNu'+postfix)
0325 rParam=0.7
0326 else:
0327 print('bad jet algorithm:', algo, '! for now, only AK4 and AK7 are allowed. If you need other algorithms, please contact Colin')
0328 sys.exit(1)
0329
0330
0331 from CommonTools.ParticleFlow.Tools.jetTools import jetAlgo
0332 inputCollection = getattr(process,"pfJetsPFBRECO"+postfix).src
0333 setattr(process,"pfJetsPFBRECO"+postfix,jetAlgo(algo))
0334 getattr(process,"pfJetsPFBRECO"+postfix).src = inputCollection
0335 inputJetCorrLabel=jetCorrections
0336
0337 switchJetCollection(process,
0338 jetSource = input,
0339 algo=algo,
0340 rParam=rParam,
0341 genJetCollection=genJetCollection,
0342 postfix=postfix,
0343 jetTrackAssociation=True,
0344 jetCorrections=inputJetCorrLabel,
0345 outputModules = outputModules,
0346 )
0347
0348
0349 applyPostfix(process, "patJetCorrFactors", postfix).useRho = False
0350 task = getPatAlgosToolsTask(process)
0351 for corr in inputJetCorrLabel[1]:
0352 if corr == 'L1FastJet':
0353 applyPostfix(process, "patJetCorrFactors", postfix).useRho = True
0354 applyPostfix(process, "pfJetsPFBRECO", postfix).doAreaFastjet = True
0355
0356
0357 if type1:
0358 for mod in process.producerNames().split(' '):
0359
0360 if mod.startswith("kt6") and mod.endswith("Jets"+postfix) and not 'GenJets' in mod:
0361 prefix = mod.replace(postfix,'')
0362 prefix = prefix.replace('kt6PFJets','')
0363 prefix = prefix.replace('kt6CaloJets','')
0364 prefix = getattr(process,'patJetCorrFactors'+prefix+postfix).payload.pythonValue().replace("'","")
0365 for essource in process.es_sources_().keys():
0366 if essource == prefix+'L1FastJet':
0367 setattr(process,essource+postfix,getattr(process,essource).clone(srcRho=cms.InputTag(mod,'rho')))
0368 addToProcessAndTask(prefix+'CombinedCorrector'+postfix,
0369 getattr(process,prefix+'CombinedCorrector').clone(), process, task)
0370 getattr(process,prefix+'CorMet'+postfix).corrector = prefix+'CombinedCorrector'+postfix
0371 for cor in getattr(process,prefix+'CombinedCorrector'+postfix).correctors:
0372 if cor == essource:
0373 idx = getattr(process,prefix+'CombinedCorrector'+postfix).correctors.index(essource);
0374 getattr(process,prefix+'CombinedCorrector'+postfix).correctors[idx] = essource+postfix
0375
0376 if hasattr( getattr( process, "patJets" + postfix), 'embedCaloTowers' ):
0377 applyPostfix(process, "patJets", postfix).embedCaloTowers = False
0378 applyPostfix(process, "patJets", postfix).embedPFCandidates = True
0379
0380
0381 def removeMCMatchingPF2PAT( process, postfix="", outputModules=['out'] ):
0382
0383
0384
0385 removeMCMatching(process, names=['All'], postfix=postfix, outputModules=outputModules)
0386
0387
0388 def adaptPVs(process, pvCollection=cms.InputTag('offlinePrimaryVertices'), postfix=''):
0389 print("Switching PV collection for PF2PAT:", pvCollection)
0390 print("***********************************")
0391
0392
0393 pvExchange = ['Vertices','vertices','pvSrc','primaryVertices','srcPVs','primaryVertex']
0394
0395
0396
0397
0398 for m in (process.producerNames().split(' ') + process.filterNames().split(' ')):
0399
0400 for namePvSrc in pvExchange:
0401 if hasattr(getattr(process,m),namePvSrc):
0402
0403 setattr(getattr(process,m),namePvSrc,deepcopy(pvCollection))
0404
0405
0406 def usePF2PAT(process,runPF2PAT=True, jetAlgo='AK4', runOnMC=True, postfix="", jetCorrections=('AK4PFchs', ['L1FastJet','L2Relative','L3Absolute'],'None'), pvCollection=cms.InputTag('goodOfflinePrimaryVerticesPFlow',), typeIMetCorrections=False, outputModules=['out'],excludeFromTopProjection=['Tau']):
0407
0408
0409
0410 if typeIMetCorrections:
0411 jetCorrections = (jetCorrections[0],jetCorrections[1],'Type-1')
0412 """Switch PAT to use PF2PAT instead of AOD sources. if 'runPF2PAT' is true, we'll also add PF2PAT in front of the PAT sequence"""
0413
0414
0415 from PhysicsTools.PatAlgos.tools.helpers import loadWithPostfix
0416 patAlgosToolsTask = getPatAlgosToolsTask(process)
0417 taskLabel = patAlgosToolsTask.label()
0418 if runPF2PAT:
0419 loadWithPostfix(process,'PhysicsTools.PatAlgos.patSequences_cff',postfix, loadedProducersAndFilters=taskLabel)
0420 loadWithPostfix(process,"CommonTools.ParticleFlow.PFBRECO_cff",postfix, loadedProducersAndFilters=taskLabel)
0421 else:
0422 loadWithPostfix(process,'PhysicsTools.PatAlgos.patSequences_cff',postfix, loadedProducersAndFilters=taskLabel)
0423
0424
0425
0426
0427
0428
0429
0430 adaptPFMuons(process,
0431 applyPostfix(process,"patMuons",postfix),
0432 postfix)
0433
0434
0435
0436 adaptPFElectrons(process,
0437 applyPostfix(process,"patElectrons",postfix),
0438 postfix)
0439
0440
0441
0442
0443
0444
0445
0446 if runOnMC :
0447 switchToPFJets( process, cms.InputTag('pfNoTauClonesPFBRECO'+postfix), jetAlgo, postfix=postfix,
0448 jetCorrections=jetCorrections, type1=typeIMetCorrections, outputModules=outputModules )
0449
0450 else :
0451 if not 'L2L3Residual' in jetCorrections[1]:
0452
0453 print('#################################################')
0454 print('WARNING! Not using L2L3Residual but this is data.')
0455 print('If this is okay with you, disregard this message.')
0456 print('#################################################')
0457 switchToPFJets( process, cms.InputTag('pfNoTauClonesPFBRECO'+postfix), jetAlgo, postfix=postfix,
0458 jetCorrections=jetCorrections, type1=typeIMetCorrections, outputModules=outputModules )
0459
0460
0461
0462 adaptPFTaus( process, tauType='hpsPFTau', postfix=postfix )
0463
0464 switchToPFMET(process, cms.InputTag('pfMETPFBRECO'+postfix), type1=typeIMetCorrections, postfix=postfix)
0465
0466
0467 addPFCandidates(process,cms.InputTag('pfNoJetClones'+postfix),patLabel='PFParticles'+postfix,cut="",postfix=postfix)
0468
0469
0470 adaptPVs(process, pvCollection=pvCollection, postfix=postfix)
0471
0472 if not runOnMC:
0473 runOnData(process,postfix=postfix,outputModules=outputModules)
0474
0475
0476 getattr(process,"pfNoPileUpJME"+postfix).enable = True
0477 getattr(process,"pfNoMuonJMEPFBRECO"+postfix).enable = True
0478 getattr(process,"pfNoElectronJMEPFBRECO"+postfix).enable = True
0479 getattr(process,"pfNoTauPFBRECO"+postfix).enable = False
0480 getattr(process,"pfNoJetPFBRECO"+postfix).enable = True
0481 exclusionList = ''
0482 for object in excludeFromTopProjection:
0483 jme = ''
0484 if object in ['Muon','Electron']:
0485 jme = 'JME'
0486 getattr(process,"pfNo"+object+jme+'PFBRECO'+postfix).enable = False
0487 exclusionList=exclusionList+object+','
0488 exclusionList=exclusionList.rstrip(',')
0489 print("Done: PFBRECO interfaced to PAT, postfix=", postfix,", Excluded from Top Projection:",exclusionList)