CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_5_2_7_hltpatch2/src/PhysicsTools/PatAlgos/python/tools/pfTools.py

Go to the documentation of this file.
00001 import FWCore.ParameterSet.Config as cms
00002 
00003 from PhysicsTools.PatAlgos.tools.coreTools import *
00004 from PhysicsTools.PatAlgos.tools.jetTools import *
00005 from PhysicsTools.PatAlgos.tools.tauTools import *
00006 
00007 from PhysicsTools.PatAlgos.tools.helpers import listModules, applyPostfix
00008 
00009 from copy import deepcopy
00010 
00011 #def applyPostfix(process, label, postfix):
00012 #    ''' If a module is in patDefaultSequence use the cloned module.
00013 #    Will crash if patDefaultSequence has not been cloned with 'postfix' beforehand'''
00014 #    result = None
00015 #    defaultLabels = [ m.label()[:-len(postfix)] for m in listModules( getattr(process,"patDefaultSequence"+postfix))]
00016 #    if label in defaultLabels:
00017 #        result = getattr(process, label+postfix)
00018 #    else:
00019 #        print "WARNING: called applyPostfix for module %s which is not in patDefaultSequence!"%label
00020 #        result = getattr(process, label)
00021 #    return result
00022 
00023 #def removeFromSequence(process, seq, postfix, baseSeq='patDefaultSequence'):
00024 #    defaultLabels = [ m.label()[:-len(postfix)] for m in listModules( getattr(process,baseSeq+postfix))]
00025 #    for module in listModules( seq ):
00026 #        if module.label() in defaultLabels:
00027 #            getattr(process,baseSeq+postfix).remove(getattr(process, module.label()+postfix))
00028 
00029 def warningIsolation():
00030     print "WARNING: particle based isolation must be studied"
00031 
00032 
00033 def adaptPFIsoElectrons(process,module, postfix = "PFIso"):
00034     #FIXME: adaptPFElectrons can use this function.
00035     module.isoDeposits = cms.PSet(
00036         pfChargedHadrons = cms.InputTag("elPFIsoDepositCharged" + postfix),
00037         pfChargedAll = cms.InputTag("elPFIsoDepositChargedAll" + postfix),
00038         pfPUChargedHadrons = cms.InputTag("elPFIsoDepositPU" + postfix),
00039         pfNeutralHadrons = cms.InputTag("elPFIsoDepositNeutral" + postfix),
00040         pfPhotons = cms.InputTag("elPFIsoDepositGamma" + postfix)
00041         )
00042     module.isolationValues = cms.PSet(
00043         pfChargedHadrons = cms.InputTag("elPFIsoValueCharged04PFId"+ postfix),
00044         pfChargedAll = cms.InputTag("elPFIsoValueChargedAll04PFId"+ postfix),
00045         pfPUChargedHadrons = cms.InputTag("elPFIsoValuePU04PFId" + postfix),
00046         pfNeutralHadrons = cms.InputTag("elPFIsoValueNeutral04PFId" + postfix),
00047         pfPhotons = cms.InputTag("elPFIsoValueGamma04PFId" + postfix)
00048         )
00049     module.isolationValuesNoPFId = cms.PSet(
00050         pfChargedHadrons = cms.InputTag("elPFIsoValueCharged04NoPFId"+ postfix),
00051         pfChargedAll = cms.InputTag("elPFIsoValueChargedAll04NoPFId"+ postfix),
00052         pfPUChargedHadrons = cms.InputTag("elPFIsoValuePU04NoPFId" + postfix),
00053         pfNeutralHadrons = cms.InputTag("elPFIsoValueNeutral04NoPFId" + postfix),
00054         pfPhotons = cms.InputTag("elPFIsoValueGamma04NoPFId" + postfix)
00055         )
00056 
00057 def adaptPFIsoMuons(process,module, postfix = "PFIso"):
00058     #FIXME: adaptPFMuons can use this function.
00059     module.isoDeposits = cms.PSet(
00060         pfChargedHadrons = cms.InputTag("muPFIsoDepositCharged" + postfix),
00061         pfChargedAll = cms.InputTag("muPFIsoDepositChargedAll" + postfix),
00062         pfPUChargedHadrons = cms.InputTag("muPFIsoDepositPU" + postfix),
00063         pfNeutralHadrons = cms.InputTag("muPFIsoDepositNeutral" + postfix),
00064         pfPhotons = cms.InputTag("muPFIsoDepositGamma" + postfix)
00065         )
00066     module.isolationValues = cms.PSet(
00067         pfChargedHadrons = cms.InputTag("muPFIsoValueCharged04"+ postfix),
00068         pfChargedAll = cms.InputTag("muPFIsoValueChargedAll04"+ postfix),
00069         pfPUChargedHadrons = cms.InputTag("muPFIsoValuePU04" + postfix),
00070         pfNeutralHadrons = cms.InputTag("muPFIsoValueNeutral04" + postfix),
00071         pfPhotons = cms.InputTag("muPFIsoValueGamma04" + postfix)
00072         )
00073 
00074 from CommonTools.ParticleFlow.Tools.pfIsolation import setupPFElectronIso, setupPFMuonIso
00075 
00076 def usePFIso(process, postfix = "PFIso"):
00077     print "Building particle-based isolation "
00078     print "***************** "
00079     process.eleIsoSequence = setupPFElectronIso(process, 'gsfElectrons', postfix)
00080     process.muIsoSequence = setupPFMuonIso(process, 'muons', postfix)
00081     adaptPFIsoMuons( process, applyPostfix(process,"patMuons",""), postfix)
00082     adaptPFIsoElectrons( process, applyPostfix(process,"patElectrons",""), postfix)
00083     getattr(process,'patDefaultSequence').replace( getattr(process,"patCandidates"),
00084                                                    process.pfParticleSelectionSequence +
00085                                                    process.eleIsoSequence +
00086                                                    process.muIsoSequence +
00087                                                    getattr(process,"patCandidates") )
00088 
00089 def adaptPFMuons(process,module,postfix="" ):
00090     print "Adapting PF Muons "
00091     print "***************** "
00092     warningIsolation()
00093     print
00094     module.useParticleFlow = True
00095     module.userIsolation   = cms.PSet()
00096     module.isoDeposits = cms.PSet(
00097         pfChargedHadrons = cms.InputTag("muPFIsoDepositCharged" + postfix),
00098         pfChargedAll = cms.InputTag("muPFIsoDepositChargedAll" + postfix),
00099         pfPUChargedHadrons = cms.InputTag("muPFIsoDepositPU" + postfix),
00100         pfNeutralHadrons = cms.InputTag("muPFIsoDepositNeutral" + postfix),
00101         pfPhotons = cms.InputTag("muPFIsoDepositGamma" + postfix)
00102         )
00103     module.isolationValues = cms.PSet(
00104         pfChargedHadrons = cms.InputTag("muPFIsoValueCharged04"+ postfix),
00105         pfChargedAll = cms.InputTag("muPFIsoValueChargedAll04"+ postfix),
00106         pfPUChargedHadrons = cms.InputTag("muPFIsoValuePU04" + postfix),
00107         pfNeutralHadrons = cms.InputTag("muPFIsoValueNeutral04" + postfix),
00108         pfPhotons = cms.InputTag("muPFIsoValueGamma04" + postfix)
00109         )
00110     # matching the pfMuons, not the standard muons.
00111     applyPostfix(process,"muonMatch",postfix).src = module.pfMuonSource
00112 
00113     print " muon source:", module.pfMuonSource
00114     print " isolation  :",
00115     print module.isolationValues
00116     print " isodeposits: "
00117     print module.isoDeposits
00118     print
00119 
00120 
00121 def adaptPFElectrons(process,module, postfix):
00122     # module.useParticleFlow = True
00123     print "Adapting PF Electrons "
00124     print "********************* "
00125     warningIsolation()
00126     print
00127     module.useParticleFlow = True
00128     module.userIsolation   = cms.PSet()
00129     module.isoDeposits = cms.PSet(
00130         pfChargedHadrons = cms.InputTag("elPFIsoDepositCharged" + postfix),
00131         pfChargedAll = cms.InputTag("elPFIsoDepositChargedAll" + postfix),
00132         pfPUChargedHadrons = cms.InputTag("elPFIsoDepositPU" + postfix),
00133         pfNeutralHadrons = cms.InputTag("elPFIsoDepositNeutral" + postfix),
00134         pfPhotons = cms.InputTag("elPFIsoDepositGamma" + postfix)
00135         )
00136     module.isolationValues = cms.PSet(
00137         pfChargedHadrons = cms.InputTag("elPFIsoValueCharged04PFId"+ postfix),
00138         pfChargedAll = cms.InputTag("elPFIsoValueChargedAll04PFId"+ postfix),
00139         pfPUChargedHadrons = cms.InputTag("elPFIsoValuePU04PFId" + postfix),
00140         pfNeutralHadrons = cms.InputTag("elPFIsoValueNeutral04PFId" + postfix),
00141         pfPhotons = cms.InputTag("elPFIsoValueGamma04PFId" + postfix)
00142         )
00143 
00144     # COLIN: since we take the egamma momentum for pat Electrons, we must
00145     # match the egamma electron to the gen electrons, and not the PFElectron.
00146     # -> do not uncomment the line below.
00147     # process.electronMatch.src = module.pfElectronSource
00148     # COLIN: how do we depend on this matching choice?
00149 
00150     print " PF electron source:", module.pfElectronSource
00151     print " isolation  :"
00152     print module.isolationValues
00153     print " isodeposits: "
00154     print module.isoDeposits
00155     print
00156 
00157     print "removing traditional isolation"
00158 
00159     removeIfInSequence(process,  "patElectronIsolation",  "patDefaultSequence", postfix)
00160 
00161 def adaptPFPhotons(process,module):
00162     raise RuntimeError, "Photons are not supported yet"
00163 
00164 from RecoTauTag.RecoTau.TauDiscriminatorTools import adaptTauDiscriminator, producerIsTauTypeMapper
00165 
00166 def reconfigurePF2PATTaus(process,
00167       tauType='shrinkingConePFTau',
00168       pf2patSelection=["DiscriminationByIsolation", "DiscriminationByLeadingPionPtCut"],
00169       selectionDependsOn=["DiscriminationByLeadingTrackFinding"],
00170       producerFromType=lambda producer: producer+"Producer",
00171       postfix = ""):
00172    print "patTaus will be produced from taus of type: %s that pass %s" \
00173          % (tauType, pf2patSelection)
00174 
00175    #get baseSequence
00176    baseSequence = getattr(process,"pfTausBaseSequence"+postfix)
00177    #clean baseSequence from old modules
00178    for oldBaseModuleName in baseSequence.moduleNames():
00179        oldBaseModule = getattr(process,oldBaseModuleName)
00180        baseSequence.remove(oldBaseModule)
00181 
00182    # Get the prototype of tau producer to make, i.e. fixedConePFTauProducer
00183    producerName = producerFromType(tauType)
00184    # Set as the source for the pf2pat taus (pfTaus) selector
00185    applyPostfix(process,"pfTaus", postfix).src = producerName+postfix
00186    # Start our pf2pat taus base sequence
00187    oldTauSansRefs = getattr(process,'pfTausProducerSansRefs'+postfix)
00188    oldTau = getattr(process,'pfTausProducer'+postfix)
00189    ## copy tau and setup it properly
00190    newTauSansRefs = None
00191    newTau = getattr(process,producerName).clone()
00192    ## adapted to new structure in RecoTauProducers PLEASE CHECK!!!
00193    if tauType=='shrinkingConePFTau':
00194        newTauSansRefs = getattr(process,producerName+"SansRefs").clone()
00195        newTauSansRefs.modifiers[1] = cms.PSet(
00196            pfTauTagInfoSrc = cms.InputTag("pfTauTagInfoProducer"+postfix),
00197            name = cms.string('pfTauTTIworkaround'+postfix),
00198            plugin = cms.string('RecoTauTagInfoWorkaroundModifer')
00199            )
00200        newTau.modifiers[1] = newTauSansRefs.modifiers[1]
00201        newTauSansRefs.piZeroSrc = "pfJetsLegacyTaNCPiZeros"+postfix
00202        newTau.piZeroSrc = newTauSansRefs.piZeroSrc
00203        newTauSansRefs.builders[0].pfCandSrc = oldTauSansRefs.builders[0].pfCandSrc
00204        newTauSansRefs.jetRegionSrc = oldTauSansRefs.jetRegionSrc
00205        newTauSansRefs.jetSrc = oldTauSansRefs.jetSrc
00206    elif tauType=='fixedConePFTau':
00207        newTau.piZeroSrc = "pfJetsLegacyTaNCPiZeros"+postfix
00208    elif tauType=='hpsPFTau':
00209        newTau = process.combinatoricRecoTaus.clone()
00210        newTau.piZeroSrc="pfJetsLegacyHPSPiZeros"+postfix
00211        newTau.modifiers[3] = cms.PSet(
00212            pfTauTagInfoSrc = cms.InputTag("pfTauTagInfoProducer"+postfix),
00213            name = cms.string('pfTauTTIworkaround'+postfix),
00214            plugin = cms.string('RecoTauTagInfoWorkaroundModifer')
00215            )
00216        from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet
00217        cloneProcessingSnippet(process, process.produceHPSPFTaus, postfix)
00218        massSearchReplaceParam(getattr(process,"produceHPSPFTaus"+postfix),
00219                               "PFTauProducer",
00220                               cms.InputTag("combinatoricRecoTaus"),
00221                               cms.InputTag("pfTausBase"+postfix) )
00222        massSearchReplaceParam(getattr(process,"produceHPSPFTaus"+postfix),
00223                               "src",
00224                               cms.InputTag("combinatoricRecoTaus"),
00225                               cms.InputTag("pfTausBase"+postfix) )
00226        getattr(process,"hpsPFTauProducer"+postfix).src = "pfTausBase"+postfix
00227 
00228    newTau.builders[0].pfCandSrc = oldTau.builders[0].pfCandSrc
00229    newTau.jetRegionSrc = oldTau.jetRegionSrc
00230    newTau.jetSrc = oldTau.jetSrc
00231 
00232    # replace old tau producer by new one put it into baseSequence
00233    setattr(process,"pfTausBase"+postfix,newTau)
00234    if tauType=='shrinkingConePFTau':
00235        setattr(process,"pfTausBaseSansRefs"+postfix,newTauSansRefs)
00236        getattr(process,"pfTausBase"+postfix).src = "pfTausBaseSansRefs"+postfix
00237        baseSequence += getattr(process,"pfTausBaseSansRefs"+postfix)
00238    baseSequence += getattr(process,"pfTausBase"+postfix)
00239    if tauType=='hpsPFTau':
00240        baseSequence += getattr(process,"produceHPSPFTaus"+postfix)
00241    #make custom mapper to take postfix into account (could have gone with lambda of lambda but... )
00242    def producerIsTauTypeMapperWithPostfix(tauProducer):
00243        return lambda x: producerIsTauTypeMapper(tauProducer)+x.group(1)+postfix
00244 
00245    def recoTauTypeMapperWithGroup(tauProducer):
00246        return "%s(.*)"%recoTauTypeMapper(tauProducer)
00247 
00248    # Get our prediscriminants
00249    for predisc in selectionDependsOn:
00250       # Get the prototype
00251       originalName = tauType+predisc # i.e. fixedConePFTauProducerDiscriminationByLeadingTrackFinding
00252       clonedName = "pfTausBase"+predisc+postfix
00253       clonedDisc = getattr(process, originalName).clone()
00254       # Register in our process
00255       setattr(process, clonedName, clonedDisc)
00256       baseSequence += getattr(process, clonedName)
00257 
00258       tauCollectionToSelect = None
00259       if tauType != 'hpsPFTau' :
00260           tauCollectionToSelect = "pfTausBase"+postfix
00261           #cms.InputTag(clonedDisc.PFTauProducer.value()+postfix)
00262       else:
00263           tauCollectionToSelect = "hpsPFTauProducer"+postfix
00264       # Adapt this discriminator for the cloned prediscriminators
00265       adaptTauDiscriminator(clonedDisc, newTauProducer="pfTausBase",
00266                             oldTauTypeMapper=recoTauTypeMapperWithGroup,
00267                             newTauTypeMapper=producerIsTauTypeMapperWithPostfix,
00268                             preservePFTauProducer=True)
00269       clonedDisc.PFTauProducer = tauCollectionToSelect
00270 
00271    # Reconfigure the pf2pat PFTau selector discrimination sources
00272    applyPostfix(process,"pfTaus", postfix).discriminators = cms.VPSet()
00273    for selection in pf2patSelection:
00274       # Get our discriminator that will be used to select pfTaus
00275       originalName = tauType+selection
00276       clonedName = "pfTausBase"+selection+postfix
00277       clonedDisc = getattr(process, originalName).clone()
00278       # Register in our process
00279       setattr(process, clonedName, clonedDisc)
00280 
00281       tauCollectionToSelect = None
00282 
00283       if tauType != 'hpsPFTau' :
00284           tauCollectionToSelect = cms.InputTag("pfTausBase"+postfix)
00285           #cms.InputTag(clonedDisc.PFTauProducer.value()+postfix)
00286       else:
00287           tauCollectionToSelect = cms.InputTag("hpsPFTauProducer"+postfix)
00288       #Adapt our cloned discriminator to the new prediscriminants
00289       adaptTauDiscriminator(clonedDisc, newTauProducer="pfTausBase",
00290                             oldTauTypeMapper=recoTauTypeMapperWithGroup,
00291                             newTauTypeMapper=producerIsTauTypeMapperWithPostfix,
00292                             preservePFTauProducer=True)
00293       clonedDisc.PFTauProducer = tauCollectionToSelect
00294       baseSequence += clonedDisc
00295       # Add this selection to our pfTau selectors
00296       applyPostfix(process,"pfTaus", postfix).discriminators.append(cms.PSet(
00297          discriminator=cms.InputTag(clonedName), selectionCut=cms.double(0.5)))
00298       # Set the input of the final selector.
00299       if tauType != 'hpsPFTau':
00300           applyPostfix(process,"pfTaus", postfix).src = "pfTausBase"+postfix
00301       else:
00302           # If we are using HPS taus, we need to take the output of the clenaed
00303           # collection
00304           applyPostfix(process,"pfTaus", postfix).src = "hpsPFTauProducer"+postfix
00305 
00306 
00307 
00308 def adaptPFTaus(process,tauType = 'shrinkingConePFTau', postfix = ""):
00309     # Set up the collection used as a preselection to use this tau type
00310     if tauType != 'hpsPFTau' :
00311         reconfigurePF2PATTaus(process, tauType, postfix=postfix)
00312     else:
00313         reconfigurePF2PATTaus(process, tauType,
00314                               ["DiscriminationByLooseCombinedIsolationDBSumPtCorr"],
00315                               ["DiscriminationByDecayModeFinding"],
00316                               postfix=postfix)
00317     # new default use unselected taus (selected only for jet cleaning)
00318     if tauType != 'hpsPFTau' :
00319         applyPostfix(process,"patTaus", postfix).tauSource = cms.InputTag("pfTausBase"+postfix)
00320     else:
00321         applyPostfix(process,"patTaus", postfix).tauSource = cms.InputTag("hpsPFTauProducer"+postfix)
00322     # to use preselected collection (old default) uncomment line below
00323     #applyPostfix(process,"patTaus", postfix).tauSource = cms.InputTag("pfTaus"+postfix)
00324 
00325 
00326     redoPFTauDiscriminators(process,
00327                             cms.InputTag(tauType+'Producer'),
00328                             applyPostfix(process,"patTaus", postfix).tauSource,
00329                             tauType, postfix=postfix)
00330 
00331     switchToPFTauByType(process, pfTauType=tauType,
00332                         pfTauLabelNew=applyPostfix(process,"patTaus", postfix).tauSource,
00333                         pfTauLabelOld=cms.InputTag(tauType+'Producer'),
00334                         postfix=postfix)
00335 
00336     applyPostfix(process,"makePatTaus", postfix).remove(
00337         applyPostfix(process,"patPFCandidateIsoDepositSelection", postfix)
00338         )
00339 
00340 #helper function for PAT on PF2PAT sample
00341 def tauTypeInPF2PAT(process,tauType='shrinkingConePFTau', postfix = ""):
00342     process.load("CommonTools.ParticleFlow.pfTaus_cff")
00343     applyPostfix(process, "pfTaus",postfix).src = cms.InputTag(tauType+'Producer'+postfix)
00344 
00345 
00346 def addPFCandidates(process,src,patLabel='PFParticles',cut="",postfix=""):
00347     from PhysicsTools.PatAlgos.producersLayer1.pfParticleProducer_cfi import patPFParticles
00348     # make modules
00349     producer = patPFParticles.clone(pfCandidateSource = src)
00350     filter   = cms.EDFilter("PATPFParticleSelector",
00351                     src = cms.InputTag("pat" + patLabel),
00352                     cut = cms.string(cut))
00353     counter  = cms.EDFilter("PATCandViewCountFilter",
00354                     minNumber = cms.uint32(0),
00355                     maxNumber = cms.uint32(999999),
00356                     src       = cms.InputTag("pat" + patLabel))
00357     # add modules to process
00358     setattr(process, "pat"         + patLabel, producer)
00359     setattr(process, "selectedPat" + patLabel, filter)
00360     setattr(process, "countPat"    + patLabel, counter)
00361     # insert into sequence
00362     getattr(process, "patDefaultSequence"+postfix).replace(
00363         applyPostfix(process, "patCandidateSummary", postfix),
00364         producer+applyPostfix(process, "patCandidateSummary", postfix)
00365     )
00366     getattr(process, "patDefaultSequence"+postfix).replace(
00367         applyPostfix(process, "selectedPatCandidateSummary", postfix),
00368         filter+applyPostfix(process, "selectedPatCandidateSummary", postfix)
00369     )
00370     index = len( applyPostfix( process, "patDefaultSequence", postfix ).moduleNames() )
00371     applyPostfix( process, "patDefaultSequence", postfix ).insert( index, counter )
00372     # summary tables
00373     applyPostfix(process, "patCandidateSummary", postfix).candidates.append(cms.InputTag('pat' + patLabel))
00374     applyPostfix(process, "selectedPatCandidateSummary", postfix).candidates.append(cms.InputTag('selectedPat' + patLabel))
00375 
00376 
00377 def switchToPFMET(process,input=cms.InputTag('pfMET'), type1=False, postfix=""):
00378     print 'MET: using ', input
00379     if( not type1 ):
00380         oldMETSource = applyPostfix(process, "patMETs",postfix).metSource
00381         applyPostfix(process, "patMETs",postfix).metSource = input
00382         applyPostfix(process, "patMETs",postfix).addMuonCorrections = False
00383         getattr(process, "patDefaultSequence"+postfix).remove(applyPostfix(process, "patMETCorrections",postfix))
00384     else:
00385         # type1 corrected MET
00386         # name of corrected MET hardcoded in PAT and meaningless
00387         print 'Apply TypeI corrections for MET'
00388         getattr(process, "patDefaultSequence"+postfix).remove(applyPostfix(process, "patMETCorrections",postfix))
00389         jecLabel = getattr(process,'patJetCorrFactors'+postfix).payload.pythonValue().replace("'","")
00390         getattr(process,jecLabel+'CorMet'+postfix).inputUncorMetLabel = input.getModuleLabel()
00391         getattr(process,'patMETs'+postfix).metSource = jecLabel+'CorMet'+postfix
00392         getattr(process,'patMETs'+postfix).addMuonCorrections = False
00393 
00394 def switchToPFJets(process, input=cms.InputTag('pfNoTau'), algo='AK5', postfix = "", jetCorrections=('AK5PFchs', ['L1FastJet','L2Relative', 'L3Absolute']), type1=False, outputModules=['out']):
00395 
00396     print "Switching to PFJets,  ", algo
00397     print "************************ "
00398     print "input collection: ", input
00399 
00400     if( algo == 'IC5' ):
00401         genJetCollection = cms.InputTag('iterativeCone5GenJetsNoNu')
00402     elif algo == 'AK5':
00403         genJetCollection = cms.InputTag('ak5GenJetsNoNu')
00404     elif algo == 'AK7':
00405         genJetCollection = cms.InputTag('ak7GenJetsNoNu')
00406     else:
00407         print 'bad jet algorithm:', algo, '! for now, only IC5, AK5 and AK7 are allowed. If you need other algorithms, please contact Colin'
00408         sys.exit(1)
00409 
00410     # changing the jet collection in PF2PAT:
00411     from CommonTools.ParticleFlow.Tools.jetTools import jetAlgo
00412     inputCollection = getattr(process,"pfJets"+postfix).src
00413     setattr(process,"pfJets"+postfix,jetAlgo(algo)) # problem for cfgBrowser
00414     getattr(process,"pfJets"+postfix).src = inputCollection
00415     inputJetCorrLabel=jetCorrections
00416     switchJetCollection(process,
00417                         input,
00418                         jetIdLabel = algo,
00419                         doJTA=True,
00420                         doBTagging=True,
00421                         jetCorrLabel=inputJetCorrLabel,
00422                         doType1MET=type1,
00423                         genJetCollection = genJetCollection,
00424                         doJetID = True,
00425                         postfix = postfix,
00426                         outputModules = outputModules
00427                         )
00428     # check whether L1FastJet is in the list of correction levels or not
00429     applyPostfix(process, "patJetCorrFactors", postfix).useRho = False
00430     for corr in inputJetCorrLabel[1]:
00431         if corr == 'L1FastJet':
00432             applyPostfix(process, "patJetCorrFactors", postfix).useRho = True
00433             applyPostfix(process, "pfJets", postfix).doAreaFastjet = True
00434             applyPostfix(process, "kt6PFJets", postfix).src = inputCollection
00435             # do correct treatment for TypeI MET corrections
00436             if type1:
00437                 for mod in getattr(process,'patPF2PATSequence'+postfix).moduleNames():
00438                     if mod.startswith("kt6"):
00439                         prefix = mod.replace(postfix,'')
00440                         prefix = prefix.replace('kt6PFJets','')
00441                         prefix = prefix.replace('kt6CaloJets','')
00442                         prefix = getattr(process,'patJetCorrFactors'+prefix+postfix).payload.pythonValue().replace("'","")
00443                         for essource in process.es_sources_().keys():
00444                             if essource == prefix+'L1FastJet':
00445                                 setattr(process,essource+postfix,getattr(process,essource).clone(srcRho=cms.InputTag(mod,'rho')))
00446                                 setattr(process,prefix+'CombinedCorrector'+postfix,getattr(process,prefix+'CombinedCorrector').clone())
00447                                 getattr(process,prefix+'CorMet'+postfix).corrector = prefix+'CombinedCorrector'+postfix
00448                                 for cor in getattr(process,prefix+'CombinedCorrector'+postfix).correctors:
00449                                     if cor == essource:
00450                                         idx = getattr(process,prefix+'CombinedCorrector'+postfix).correctors.index(essource);
00451                                         getattr(process,prefix+'CombinedCorrector'+postfix).correctors[idx] = essource+postfix
00452 
00453     applyPostfix(process, "patJets", postfix).embedCaloTowers   = False
00454     applyPostfix(process, "patJets", postfix).embedPFCandidates = True
00455 
00456 #-- Remove MC dependence ------------------------------------------------------
00457 def removeMCMatchingPF2PAT( process, postfix="", outputModules=['out'] ):
00458     from PhysicsTools.PatAlgos.tools.coreTools import removeMCMatching
00459     removeIfInSequence(process, "genForPF2PATSequence", "patDefaultSequence", postfix)
00460     removeMCMatching(process, names=['All'], postfix=postfix, outputModules=outputModules)
00461 
00462 
00463 def adaptPVs(process, pvCollection=cms.InputTag('offlinePrimaryVertices'), postfix=''):
00464 
00465     print "Switching PV collection for PF2PAT:", pvCollection
00466     print "***********************************"
00467 
00468     # PV sources to be exchanged:
00469     pvExchange = ['Vertices','vertices','pvSrc','primaryVertices','srcPVs']
00470     # PV sources NOT to be exchanged:
00471     #noPvExchange = ['src','PVProducer','primaryVertexSrc','vertexSrc','primaryVertex']
00472 
00473     # find out all added jet collections (they don't belong to PF2PAT)
00474     interPostfixes = []
00475     for m in getattr(process,'patPF2PATSequence'+postfix).moduleNames():
00476         if m.startswith('patJets') and m.endswith(postfix) and not len(m)==len('patJets')+len(postfix):
00477             interPostfix = m.replace('patJets','')
00478             interPostfix = interPostfix.replace(postfix,'')
00479             interPostfixes.append(interPostfix)
00480 
00481     # exchange the primary vertex source of all relevant modules
00482     for m in getattr(process,'patPF2PATSequence'+postfix).moduleNames():
00483         modName = m.replace(postfix,'')
00484         # only if the module has a source with a relevant name
00485         for namePvSrc in pvExchange:
00486             if hasattr(getattr(process,m),namePvSrc):
00487                 # only if the module is not coming from an added jet collection
00488                 interPostFixFlag = False
00489                 for pfix in interPostfixes:
00490                     if modName.endswith(pfix):
00491                         interPostFixFlag = True
00492                         break
00493                 if not interPostFixFlag:
00494                     setattr(getattr(process,m),namePvSrc,deepcopy(pvCollection))
00495 
00496 
00497 def usePF2PAT(process, runPF2PAT=True, jetAlgo='AK5', runOnMC=True, postfix="", jetCorrections=('AK5PFchs', ['L1FastJet','L2Relative','L3Absolute']), pvCollection=cms.InputTag('offlinePrimaryVertices'), typeIMetCorrections=False, outputModules=['out']):
00498     # PLEASE DO NOT CLOBBER THIS FUNCTION WITH CODE SPECIFIC TO A GIVEN PHYSICS OBJECT.
00499     # CREATE ADDITIONAL FUNCTIONS IF NEEDED.
00500 
00501     """Switch PAT to use PF2PAT instead of AOD sources. if 'runPF2PAT' is true, we'll also add PF2PAT in front of the PAT sequence"""
00502 
00503     # -------- CORE ---------------
00504     if runPF2PAT:
00505         process.load("CommonTools.ParticleFlow.PF2PAT_cff")
00506         #add Pf2PAT *before* cloning so that overlapping modules are cloned too
00507         #process.patDefaultSequence.replace( process.patCandidates, process.PF2PAT+process.patCandidates)
00508         process.patPF2PATSequence = cms.Sequence( process.PF2PAT + process.patDefaultSequence)
00509     else:
00510         process.patPF2PATSequence = cms.Sequence( process.patDefaultSequence )
00511 
00512     if not postfix == "":
00513         from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet
00514         cloneProcessingSnippet(process, process.patPF2PATSequence, postfix)
00515         #delete everything pat PF2PAT modules! if you want to test the postfixing for completeness
00516         #from PhysicsTools.PatAlgos.tools.helpers import listModules,listSequences
00517         #for module in listModules(process.patDefaultSequence):
00518         #    if not module.label() is None: process.__delattr__(module.label())
00519         #for sequence in listSequences(process.patDefaultSequence):
00520         #    if not sequence.label() is None: process.__delattr__(sequence.label())
00521         #del process.patDefaultSequence
00522 
00523     removeCleaning(process, postfix=postfix, outputModules=outputModules)
00524 
00525     # -------- OBJECTS ------------
00526     # Muons
00527     adaptPFMuons(process,
00528                  applyPostfix(process,"patMuons",postfix),
00529                  postfix)
00530 
00531     # Electrons
00532     adaptPFElectrons(process,
00533                      applyPostfix(process,"patElectrons",postfix),
00534                      postfix)
00535 
00536     # Photons
00537     print "Temporarily switching off photons completely"
00538 
00539     removeSpecificPATObjects(process,names=['Photons'],outputModules=outputModules,postfix=postfix)
00540     removeIfInSequence(process,"patPhotonIsolation","patDefaultSequence",postfix)
00541 
00542     # Jets
00543     if runOnMC :
00544         switchToPFJets( process, cms.InputTag('pfNoTau'+postfix), jetAlgo, postfix=postfix,
00545                         jetCorrections=jetCorrections, type1=typeIMetCorrections, outputModules=outputModules )
00546         applyPostfix(process,"patDefaultSequence",postfix).replace(
00547             applyPostfix(process,"patJetGenJetMatch",postfix),
00548             getattr(process,"genForPF2PATSequence") *
00549             applyPostfix(process,"patJetGenJetMatch",postfix)
00550             )
00551     else :
00552         if not 'L2L3Residual' in jetCorrections[1]:
00553             print '#################################################'
00554             print 'WARNING! Not using L2L3Residual but this is data.'
00555             print 'If this is okay with you, disregard this message.'
00556             print '#################################################'
00557         switchToPFJets( process, cms.InputTag('pfNoTau'+postfix), jetAlgo, postfix=postfix,
00558                         jetCorrections=jetCorrections, type1=typeIMetCorrections, outputModules=outputModules )
00559 
00560     # Taus
00561     #adaptPFTaus( process, tauType='shrinkingConePFTau', postfix=postfix )
00562     #adaptPFTaus( process, tauType='fixedConePFTau', postfix=postfix )
00563     adaptPFTaus( process, tauType='hpsPFTau', postfix=postfix )
00564 
00565     # MET
00566     switchToPFMET(process, cms.InputTag('pfMET'+postfix), type1=typeIMetCorrections, postfix=postfix)
00567 
00568     # Unmasked PFCandidates
00569     addPFCandidates(process,cms.InputTag('pfNoJet'+postfix),patLabel='PFParticles'+postfix,cut="",postfix=postfix)
00570 
00571     # adapt primary vertex collection
00572     adaptPVs(process, pvCollection=pvCollection, postfix=postfix)
00573 
00574     if runOnMC:
00575         process.load("CommonTools.ParticleFlow.genForPF2PAT_cff")
00576         getattr(process, "patDefaultSequence"+postfix).replace(
00577             applyPostfix(process,"patCandidates",postfix),
00578             process.genForPF2PATSequence+applyPostfix(process,"patCandidates",postfix)
00579             )
00580     else:
00581         removeMCMatchingPF2PAT(process,postfix=postfix,outputModules=outputModules)
00582 
00583     print "Done: PF2PAT interfaced to PAT, postfix=", postfix