CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_5_3_10/src/PhysicsTools/PatAlgos/python/tools/tauTools.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 FWCore.GuiBrowsers.ConfigToolBase import *
00005 from PhysicsTools.PatAlgos.tools.helpers import applyPostfix
00006 from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet
00007 from RecoTauTag.RecoTau.TauDiscriminatorTools import *
00008 
00009 def redoPFTauDiscriminators(process,
00010                             oldPFTauLabel = cms.InputTag('hpsPFTauProducer'),
00011                             newPFTauLabel = cms.InputTag('hpsPFTauProducer'),
00012                             tauType = 'hpsPFTau', postfix = ""):
00013     print 'Tau discriminators: ', oldPFTauLabel, '->', newPFTauLabel
00014     print 'Tau type: ', tauType
00015     #oldPFTauLabel.setModuleLabel(oldPFTauLabel.getModuleLabel()+postfix)
00016     tauSrc = 'PFTauProducer'
00017 
00018     tauDiscriminationSequence = None
00019 
00020     if tauType == 'hpsPFTau':
00021         process.patHPSPFTauDiscrimination = process.produceAndDiscriminateHPSPFTaus.copy()
00022         # remove producers
00023         for iname in process.patHPSPFTauDiscrimination.moduleNames():
00024             if not (iname.find("DiscriminationBy")>-1 or iname.find("DiscriminationAgainst")>-1):
00025                 process.patHPSPFTauDiscrimination.remove(getattr(process,iname) )
00026         tauDiscriminationSequence = cloneProcessingSnippet(process, process.patHPSPFTauDiscrimination, postfix)
00027 
00028     elif tauType == 'hpsTancTaus': #to be checked if correct
00029         process.patHPSTaNCPFTauDiscrimination = process.hpsTancTauInitialSequence.copy()
00030         process.patHPSTaNCPFTauDiscrimination *= process.hpsTancTauDiscriminantSequence
00031         # remove producers
00032         for iname in process.patHPSTaNCPFTauDiscrimination.moduleNames():
00033             if not (iname.find("DiscriminationBy")>-1 or iname.find("DiscriminationAgainst")>-1):
00034                 process.patHPSTaNCPFTauDiscrimination.remove(getattr(process,iname) )
00035         tauDiscriminationSequence = cloneProcessingSnippet(process, process.patHPSTaNCPFTauDiscrimination, postfix)
00036 
00037     elif tauType == 'fixedConePFTau':
00038         process.patFixedConePFTauDiscrimination = process.produceAndDiscriminateFixedConePFTaus.copy()
00039         # remove producers
00040         for iname in process.patFixedConePFTauDiscrimination.moduleNames():
00041             if not (iname.find("DiscriminationBy")>-1 or iname.find("DiscriminationAgainst")>-1):
00042                 process.patFixedConePFTauDiscrimination.remove(getattr(process,iname) )
00043         tauDiscriminationSequence =  cloneProcessingSnippet(process, process.patFixedConePFTauDiscrimination, postfix)
00044 
00045     elif tauType == 'shrinkingConePFTau': #shr cone with TaNC
00046         process.patShrinkingConePFTauDiscrimination = process.produceAndDiscriminateShrinkingConePFTaus.copy()
00047         process.patShrinkingConePFTauDiscrimination *= process.produceShrinkingConeDiscriminationByTauNeuralClassifier
00048         # remove producers
00049         for iname in process.patShrinkingConePFTauDiscrimination.moduleNames():
00050             if not (iname.find("DiscriminationBy")>-1 or iname.find("DiscriminationAgainst")>-1):
00051                 process.patShrinkingConePFTauDiscrimination.remove(getattr(process,iname) )
00052         tauDiscriminationSequence =  cloneProcessingSnippet(process, process.patShrinkingConePFTauDiscrimination, postfix)
00053 
00054     elif tauType == 'caloTau':
00055         # fill calo sequence by discriminants
00056         process.patCaloTauDiscrimination = process.tautagging.copy()
00057         # remove producers
00058         for iname in process.patCaloTauDiscrimination.moduleNames():
00059             if not (iname.find("DiscriminationBy")>-1 or iname.find("DiscriminationAgainst")>-1):
00060                 process.patCaloTauDiscrimination.remove(getattr(process,iname) )
00061         tauDiscriminationSequence =  cloneProcessingSnippet(process, process.patCaloTauDiscrimination, postfix)
00062         tauSrc = 'CaloTauProducer'
00063     else:
00064         raise StandardError, "Unkown tauType: '%s'"%tauType
00065 
00066     applyPostfix(process,"patDefaultSequence",postfix).replace(
00067         applyPostfix(process,"patTaus",postfix),
00068         tauDiscriminationSequence*applyPostfix(process,"patTaus",postfix)
00069     )
00070 
00071     massSearchReplaceParam(tauDiscriminationSequence, tauSrc, oldPFTauLabel, newPFTauLabel)
00072 
00073 # switch to CaloTau collection
00074 def switchToCaloTau(process,
00075                     pfTauLabelOld = cms.InputTag('hpsPFTauProducer'),
00076                     pfTauLabelNew = cms.InputTag('caloRecoTauProducer'),
00077                     patTauLabel = "",
00078                     postfix = ""):
00079     print ' Taus: ', pfTauLabelOld, '->', pfTauLabelNew
00080 
00081     caloTauLabel = pfTauLabelNew
00082     applyPostfix(process, "tauMatch" + patTauLabel, postfix).src = caloTauLabel
00083     applyPostfix(process, "tauGenJetMatch"+ patTauLabel, postfix).src = caloTauLabel
00084 
00085     applyPostfix(process, "patTaus" + patTauLabel, postfix).tauSource = caloTauLabel
00086     applyPostfix(process, "patTaus" + patTauLabel, postfix).tauIDSources = _buildIDSourcePSet('caloRecoTau', classicTauIDSources, postfix)
00087 #    applyPostfix(process, "patTaus" + patTauLabel, postfix).tauIDSources = cms.PSet(
00088 #        leadingTrackFinding = cms.InputTag("caloRecoTauDiscriminationByLeadingTrackFinding" + postfix),
00089 #        leadingTrackPtCut   = cms.InputTag("caloRecoTauDiscriminationByLeadingTrackPtCut" + postfix),
00090 #        trackIsolation      = cms.InputTag("caloRecoTauDiscriminationByTrackIsolation" + postfix),
00091 #        ecalIsolation       = cms.InputTag("caloRecoTauDiscriminationByECALIsolation" + postfix),
00092 #        byIsolation         = cms.InputTag("caloRecoTauDiscriminationByIsolation" + postfix),
00093 #        againstElectron     = cms.InputTag("caloRecoTauDiscriminationAgainstElectron" + postfix),
00094 #        againstMuon         = cms.InputTag("caloRecoTauDiscriminationAgainstMuon" + postfix)
00095 #    )
00096     ## Isolation is somewhat an issue, so we start just by turning it off
00097     print "NO PF Isolation will be computed for CaloTau (this could be improved later)"
00098     applyPostfix(process, "patTaus" + patTauLabel, postfix).isolation   = cms.PSet()
00099     applyPostfix(process, "patTaus" + patTauLabel, postfix).isoDeposits = cms.PSet()
00100     applyPostfix(process, "patTaus" + patTauLabel, postfix).userIsolation = cms.PSet()
00101 
00102     ## no tau-jet energy corrections determined for CaloTaus yet
00103 #    applyPostfix(process, "patTauJetCorrFactors" + patTauLabel, postfix).src = caloTauLabel
00104 #    applyPostfix(process, "patTaus" + patTauLabel, postfix).addTauJetCorrFactors = cms.bool(False)
00105 
00106     ## adapt cleanPatTaus
00107     if hasattr(process, "cleanPatTaus" + patTauLabel + postfix):
00108         getattr(process, "cleanPatTaus" + patTauLabel + postfix).preselection = \
00109       'tauID("leadingTrackFinding") > 0.5 & tauID("leadingTrackPtCut") > 0.5' \
00110      + ' & tauID("byIsolation") > 0.5 & tauID("againstElectron") > 0.5 & (signalTracks.size() = 1 | signalTracks.size() = 3)'
00111 
00112 def _buildIDSourcePSet(pfTauType, idSources, postfix =""):
00113     """ Build a PSet defining the tau ID sources to embed into the pat::Tau """
00114     output = cms.PSet()
00115     for label, discriminator in idSources:
00116         setattr(output, label, cms.InputTag(pfTauType + discriminator + postfix))
00117     return output
00118 
00119 def _switchToPFTau(process,
00120                    pfTauLabelOld,
00121                    pfTauLabelNew,
00122                    pfTauType,
00123                    idSources,
00124                    jecLevels, jecPayloadMapping,
00125                    patTauLabel = "",
00126                    postfix = ""):
00127     """internal auxiliary function to switch to **any** PFTau collection"""
00128     print ' Taus: ', pfTauLabelOld, '->', pfTauLabelNew
00129 
00130     applyPostfix(process, "tauMatch" + patTauLabel, postfix).src = pfTauLabelNew
00131     applyPostfix(process, "tauGenJetMatch" + patTauLabel, postfix).src = pfTauLabelNew
00132 
00133     applyPostfix(process, "tauIsoDepositPFCandidates" + patTauLabel, postfix).src = pfTauLabelNew
00134     applyPostfix(process, "tauIsoDepositPFCandidates" + patTauLabel, postfix).ExtractorPSet.tauSource = pfTauLabelNew
00135     applyPostfix(process, "tauIsoDepositPFChargedHadrons" + patTauLabel, postfix).src = pfTauLabelNew
00136     applyPostfix(process, "tauIsoDepositPFChargedHadrons" + patTauLabel, postfix).ExtractorPSet.tauSource = pfTauLabelNew
00137     applyPostfix(process, "tauIsoDepositPFNeutralHadrons" + patTauLabel, postfix).src = pfTauLabelNew
00138     applyPostfix(process, "tauIsoDepositPFNeutralHadrons" + patTauLabel, postfix).ExtractorPSet.tauSource = pfTauLabelNew
00139     applyPostfix(process, "tauIsoDepositPFGammas" + patTauLabel, postfix).src = pfTauLabelNew
00140     applyPostfix(process, "tauIsoDepositPFGammas" + patTauLabel, postfix).ExtractorPSet.tauSource = pfTauLabelNew
00141 
00142 #    applyPostfix(process, "patTauJetCorrFactors" + patTauLabel, postfix).src = pfTauLabelNew
00143 #    if len(jecLevels) > 0:
00144 #        applyPostfix(process, "patTaus" + patTauLabel, postfix).addTauJetCorrFactors = cms.bool(True)
00145 #        applyPostfix(process, "patTauJetCorrFactors" + patTauLabel, postfix).parameters = jecPayloadMapping
00146 #    else:
00147 #        applyPostfix(process, "patTaus" + patTauLabel, postfix).addTauJetCorrFactors = cms.bool(False)
00148 
00149     applyPostfix(process, "patTaus" + patTauLabel, postfix).tauSource = pfTauLabelNew
00150     applyPostfix(process, "patTaus" + patTauLabel, postfix).tauIDSources = _buildIDSourcePSet(pfTauType, idSources, postfix)
00151 
00152     if hasattr(process, "cleanPatTaus" + patTauLabel + postfix):
00153         getattr(process, "cleanPatTaus" + patTauLabel + postfix).preselection = \
00154           'tauID("leadingTrackFinding") > 0.5 & tauID("leadingPionPtCut") > 0.5 & tauID("byIsolationUsingLeadingPion") > 0.5' \
00155          + ' & tauID("againstMuon") > 0.5 & tauID("againstElectron") > 0.5' \
00156          + ' & (signalPFChargedHadrCands.size() = 1 | signalPFChargedHadrCands.size() = 3)'
00157 
00158 # Name mapping for classic tau ID sources (present for fixed and shrinkingCones)
00159 classicTauIDSources = [
00160     ("leadingTrackFinding", "DiscriminationByLeadingTrackFinding"),
00161     ("leadingTrackPtCut", "DiscriminationByLeadingTrackPtCut"),
00162     ("trackIsolation", "DiscriminationByTrackIsolation"),
00163     ("ecalIsolation", "DiscriminationByECALIsolation"),
00164     ("byIsolation", "DiscriminationByIsolation"),
00165     ("againstElectron", "DiscriminationAgainstElectron"),
00166     ("againstMuon", "DiscriminationAgainstMuon") ]
00167 
00168 classicPFTauIDSources = [
00169     ("leadingPionPtCut", "DiscriminationByLeadingPionPtCut"),
00170     ("trackIsolationUsingLeadingPion", "DiscriminationByTrackIsolationUsingLeadingPion"),
00171     ("ecalIsolationUsingLeadingPion", "DiscriminationByECALIsolationUsingLeadingPion"),
00172     ("byIsolationUsingLeadingPion", "DiscriminationByIsolationUsingLeadingPion")]
00173 
00174 # Tau Neural Classifier Discriminators
00175 tancTauIDSources = [
00176     ("byTaNC", "DiscriminationByTaNC"),
00177     ("byTaNCfrOnePercent", "DiscriminationByTaNCfrOnePercent"),
00178     ("byTaNCfrHalfPercent", "DiscriminationByTaNCfrHalfPercent"),
00179     ("byTaNCfrQuarterPercent", "DiscriminationByTaNCfrQuarterPercent"),
00180     ("byTaNCfrTenthPercent", "DiscriminationByTaNCfrTenthPercent") ]
00181 
00182 # Hadron-plus-strip(s) (HPS) Tau Discriminators
00183 hpsTauIDSources = [
00184     ("decayModeFinding", "DiscriminationByDecayModeFinding"),
00185     ("byVLooseIsolation", "DiscriminationByVLooseIsolation"),
00186     ("byLooseIsolation", "DiscriminationByLooseIsolation"),
00187     ("byMediumIsolation", "DiscriminationByMediumIsolation"),
00188     ("byTightIsolation", "DiscriminationByTightIsolation"),
00189     ("byVLooseIsolationDeltaBetaCorr", "DiscriminationByVLooseIsolationDBSumPtCorr"),
00190     ("byLooseIsolationDeltaBetaCorr", "DiscriminationByLooseIsolationDBSumPtCorr"),
00191     ("byMediumIsolationDeltaBetaCorr", "DiscriminationByMediumIsolationDBSumPtCorr"),
00192     ("byTightIsolationDeltaBetaCorr", "DiscriminationByTightIsolationDBSumPtCorr"),
00193     ("byVLooseCombinedIsolationDeltaBetaCorr", "DiscriminationByVLooseCombinedIsolationDBSumPtCorr"),
00194     ("byLooseCombinedIsolationDeltaBetaCorr", "DiscriminationByLooseCombinedIsolationDBSumPtCorr"),
00195     ("byMediumCombinedIsolationDeltaBetaCorr", "DiscriminationByMediumCombinedIsolationDBSumPtCorr"),
00196     ("byTightCombinedIsolationDeltaBetaCorr", "DiscriminationByTightCombinedIsolationDBSumPtCorr"),
00197     ("againstElectronLoose", "DiscriminationByLooseElectronRejection"),
00198     ("againstElectronMedium", "DiscriminationByMediumElectronRejection"),
00199     ("againstElectronTight", "DiscriminationByTightElectronRejection"),
00200     ("againstElectronMVA", "DiscriminationByMVAElectronRejection"),
00201     ("againstMuonLoose", "DiscriminationByLooseMuonRejection"),
00202     ("againstMuonMedium", "DiscriminationByMediumMuonRejection"),
00203     ("againstMuonTight", "DiscriminationByTightMuonRejection") ]
00204 
00205 # Discriminators of new HPS + TaNC combined Tau id. algorithm
00206 hpsTancTauIDSources = [
00207     ("leadingTrackFinding", "DiscriminationByLeadingTrackFinding"),
00208     ("leadingTrackPtCut", "DiscriminationByLeadingTrackPtCut"),
00209     ("leadingPionPtCut", "DiscriminationByLeadingPionPtCut"),
00210     ("byTaNCraw", "DiscriminationByTancRaw"),
00211     ("byTaNC", "DiscriminationByTanc"),
00212     ("byTaNCvloose", "DiscriminationByTancVLoose"),
00213     ("byTaNCloose", "DiscriminationByTancLoose"),
00214     ("byTaNCmedium", "DiscriminationByTancMedium"),
00215     ("byTaNCtight", "DiscriminationByTancTight"),
00216     ("decayModeFinding", "DiscriminationByDecayModeSelection"),
00217     ("byHPSvloose", "DiscriminationByVLooseIsolation"),
00218     ("byHPSloose", "DiscriminationByLooseIsolation"),
00219     ("byHPSmedium", "DiscriminationByMediumIsolation"),
00220     ("byHPStight", "DiscriminationByTightIsolation"),
00221     ("againstElectronLoose", "DiscriminationByLooseElectronRejection"),
00222     ("againstElectronMedium", "DiscriminationByMediumElectronRejection"),
00223     ("againstElectronTight", "DiscriminationByTightElectronRejection"),
00224     ("againstMuonLoose", "DiscriminationByLooseMuonRejection"),
00225     ("againstMuonTight", "DiscriminationByTightMuonRejection") ]
00226 
00227 # use tau-jet energy corrections determined for HPS taus for all PFTaus
00228 from RecoTauTag.TauTagTools.tauDecayModes_cfi import *
00229 pfTauJECpayloadMapping = cms.VPSet(
00230     cms.PSet(
00231         payload    = cms.string('AK5tauHPSlooseCombDBcorrOneProng0Pi0'),
00232         decayModes = cms.vstring('%i' % tauToOneProng0PiZero)
00233     ),
00234     cms.PSet(
00235         payload    = cms.string('AK5tauHPSlooseCombDBcorrOneProng1Pi0'),
00236         decayModes = cms.vstring('%i' % tauToOneProng1PiZero)
00237     ),
00238     cms.PSet(
00239         payload    = cms.string('AK5tauHPSlooseCombDBcorrOneProng2Pi0'),
00240         decayModes = cms.vstring('%i' % tauToOneProng2PiZero)
00241     ),
00242     cms.PSet(
00243         payload    = cms.string('AK5tauHPSlooseCombDBcorrThreeProng0Pi0'),
00244         decayModes = cms.vstring('%i' % tauToThreeProng0PiZero)
00245     ),
00246     cms.PSet(
00247         payload    = cms.string('AK5tauHPSlooseCombDBcorr'),
00248         decayModes = cms.vstring('*')
00249     )
00250 )
00251 
00252 # switch to PFTau collection produced for fixed dR = 0.07 signal cone size
00253 def switchToPFTauFixedCone(process,
00254                            pfTauLabelOld = cms.InputTag('hpsPFTauProducer'),
00255                            pfTauLabelNew = cms.InputTag('fixedConePFTauProducer'),
00256                            patTauLabel = "",
00257                            jecLevels = [],
00258                            postfix = ""):
00259     fixedConeIDSources = copy.copy(classicTauIDSources)
00260     fixedConeIDSources.extend(classicPFTauIDSources)
00261 
00262     fixedConeJECpayloadMapping = pfTauJECpayloadMapping
00263 
00264     _switchToPFTau(process, pfTauLabelOld, pfTauLabelNew, 'fixedConePFTau', fixedConeIDSources,
00265                    jecLevels, fixedConeJECpayloadMapping,
00266                    patTauLabel = patTauLabel, postfix = postfix)
00267 
00268 # switch to PFTau collection produced for shrinking signal cone of size dR = 5.0/Et(PFTau)
00269 def switchToPFTauShrinkingCone(process,
00270                                pfTauLabelOld = cms.InputTag('hpsPFTauProducer'),
00271                                pfTauLabelNew = cms.InputTag('shrinkingConePFTauProducer'),
00272                                patTauLabel = "",
00273                                jecLevels = [],
00274                                postfix = ""):
00275     shrinkingIDSources = copy.copy(classicTauIDSources)
00276     shrinkingIDSources.extend(classicPFTauIDSources)
00277     # Only shrinkingCone has associated TaNC discriminators, so add them here
00278     shrinkingIDSources.extend(tancTauIDSources)
00279 
00280     shrinkingConeJECpayloadMapping = pfTauJECpayloadMapping
00281 
00282     _switchToPFTau(process, pfTauLabelOld, pfTauLabelNew, 'shrinkingConePFTau', shrinkingIDSources,
00283                    jecLevels, shrinkingConeJECpayloadMapping,
00284                    patTauLabel = patTauLabel, postfix = postfix)
00285 
00286 # switch to hadron-plus-strip(s) (HPS) PFTau collection
00287 def switchToPFTauHPS(process,
00288                      pfTauLabelOld = cms.InputTag('hpsPFTauProducer'),
00289                      pfTauLabelNew = cms.InputTag('hpsPFTauProducer'),
00290                      patTauLabel = "",
00291                      jecLevels = [],
00292                      postfix = ""):
00293 
00294     hpsTauJECpayloadMapping = pfTauJECpayloadMapping
00295 
00296     _switchToPFTau(process, pfTauLabelOld, pfTauLabelNew, 'hpsPFTau', hpsTauIDSources,
00297                    jecLevels, hpsTauJECpayloadMapping,
00298                    patTauLabel = patTauLabel, postfix = postfix)
00299 
00300     ## adapt cleanPatTaus
00301     if hasattr(process, "cleanPatTaus" + patTauLabel + postfix):
00302         getattr(process, "cleanPatTaus" + patTauLabel + postfix).preselection = \
00303       'pt > 15 & abs(eta) < 2.3 & tauID("decayModeFinding") > 0.5 & tauID("byLooseIsolation") > 0.5' \
00304      + ' & tauID("againstMuonTight") > 0.5 & tauID("againstElectronLoose") > 0.5'
00305 
00306 # switch to hadron-plus-strip(s) (HPS) PFTau collection
00307 def switchToPFTauHPSpTaNC(process,
00308                           pfTauLabelOld = cms.InputTag('hpsPFTauProducer'),
00309                           pfTauLabelNew = cms.InputTag('hpsTancTaus'),
00310                           patTauLabel = "",
00311                           jecLevels = [],
00312                           postfix = ""):
00313 
00314     hpsTancTauJECpayloadMapping = pfTauJECpayloadMapping
00315 
00316     _switchToPFTau(process, pfTauLabelOld, pfTauLabelNew, 'hpsTancTaus', hpsTancTauIDSources,
00317                    jecLevels, hpsTancTauJECpayloadMapping,
00318                    patTauLabel = patTauLabel, postfix = postfix)
00319 
00320     ## adapt cleanPatTaus
00321     if hasattr(process, "cleanPatTaus" + patTauLabel + postfix):
00322         getattr(process, "cleanPatTaus" + patTauLabel + postfix).preselection = \
00323       'pt > 15 & abs(eta) < 2.3 & tauID("decayModeFinding") > 0.5 & tauID("byHPSloose") > 0.5' \
00324      + ' & tauID("againstMuonTight") > 0.5 & tauID("againstElectronLoose") > 0.5'
00325 
00326 # Select switcher by string
00327 def switchToPFTauByType(process,
00328                         pfTauType = None,
00329                         pfTauLabelNew = None,
00330                         pfTauLabelOld = cms.InputTag('hpsPFTauProducer'),
00331                         patTauLabel = "",
00332                         jecLevels = [],
00333                         postfix = "" ):
00334     mapping = { 'shrinkingConePFTau' : switchToPFTauShrinkingCone,
00335                 'fixedConePFTau' : switchToPFTauFixedCone,
00336                 'hpsPFTau' : switchToPFTauHPS,
00337                 'caloRecoTau' : switchToCaloTau,
00338                 'hpsTancPFTau' : switchToPFTauHPSpTaNC }
00339     mapping[pfTauType](process, pfTauLabelOld = pfTauLabelOld, pfTauLabelNew = pfTauLabelNew,
00340                        jecLevels = jecLevels,
00341                        patTauLabel = patTauLabel, postfix = postfix)
00342 
00343 # switch to PFTau collection that was default in PAT production in CMSSW_3_1_x release series
00344 def switchTo31Xdefaults(process):
00345     switchToPFTauFixedCone(process)
00346     process.cleanPatTaus.preselection = cms.string('tauID("byIsolation") > 0')
00347 
00348 class AddTauCollection(ConfigToolBase):
00349 
00350     """ Add a new collection of taus. Takes the configuration from the
00351     already configured standard tau collection as starting point;
00352     replaces before calling addTauCollection will also affect the
00353     new tau collections
00354     """
00355     _label='addTauCollection'
00356     _defaultParameters=dicttypes.SortedKeysDict()
00357     def __init__(self):
00358         ConfigToolBase.__init__(self)
00359         self.addParameter(self._defaultParameters, 'tauCollection',
00360                           self._defaultValue, 'Input tau collection', cms.InputTag)
00361         self.addParameter(self._defaultParameters, 'algoLabel',
00362                           self._defaultValue, "label to indicate the tau algorithm (e.g.'hps')", str)
00363         self.addParameter(self._defaultParameters, 'typeLabel',
00364                           self._defaultValue, "label to indicate the type of constituents (either 'PFTau' or 'Tau')", str)
00365         self.addParameter(self._defaultParameters, 'doPFIsoDeposits',
00366                           True, "run sequence for computing particle-flow based IsoDeposits")
00367         ##self.addParameter(self._defaultParameters, 'jetCorrLabel',
00368         ##                  (pfTauJECpayloadMapping, ['L2Relative', 'L3Absolute']),
00369         ##                  "payload and list of new jet correction labels", tuple, acceptNoneValue = True)
00370         self.addParameter(self._defaultParameters, 'jetCorrLabel',
00371                           None, "payload and list of new jet correction labels", tuple, acceptNoneValue = True)
00372         self.addParameter(self._defaultParameters, 'standardAlgo',
00373                           "hps", "standard algorithm label of the collection from which the clones " \
00374                          + "for the new tau collection will be taken from " \
00375                          + "(note that this tau collection has to be available in the event before hand)")
00376         self.addParameter(self._defaultParameters, 'standardType',
00377                           "PFTau", "standard constituent type label of the collection from which the clones " \
00378                          + " for the new tau collection will be taken from "\
00379                          + "(note that this tau collection has to be available in the event before hand)")
00380 
00381         self._parameters=copy.deepcopy(self._defaultParameters)
00382         self._comment = ""
00383 
00384     def getDefaultParameters(self):
00385         return self._defaultParameters
00386 
00387     def __call__(self,process,
00388                  tauCollection      = None,
00389                  algoLabel          = None,
00390                  typeLabel          = None,
00391                  doPFIsoDeposits    = None,
00392                  jetCorrLabel       = None,
00393                  standardAlgo       = None,
00394                  standardType       = None):
00395 
00396         if tauCollection is None:
00397             tauCollection = self._defaultParameters['tauCollection'].value
00398         if algoLabel is None:
00399             algoLabel = self._defaultParameters['algoLabel'].value
00400         if typeLabel is None:
00401             typeLabel = self._defaultParameters['typeLabel'].value
00402         if doPFIsoDeposits is None:
00403             doPFIsoDeposits = self._defaultParameters['doPFIsoDeposits'].value
00404         if jetCorrLabel is None:
00405             jetCorrLabel = self._defaultParameters['jetCorrLabel'].value
00406         if standardAlgo is None:
00407             standardAlgo = self._defaultParameters['standardAlgo'].value
00408         if standardType is None:
00409             standardType = self._defaultParameters['standardType'].value
00410 
00411         self.setParameter('tauCollection', tauCollection)
00412         self.setParameter('algoLabel', algoLabel)
00413         self.setParameter('typeLabel', typeLabel)
00414         self.setParameter('doPFIsoDeposits', doPFIsoDeposits)
00415         self.setParameter('jetCorrLabel', jetCorrLabel)
00416         self.setParameter('standardAlgo', standardAlgo)
00417         self.setParameter('standardType', standardType)
00418 
00419         self.apply(process)
00420 
00421     def toolCode(self, process):
00422         tauCollection = self._parameters['tauCollection'].value
00423         algoLabel = self._parameters['algoLabel'].value
00424         typeLabel = self._parameters['typeLabel'].value
00425         doPFIsoDeposits = self._parameters['doPFIsoDeposits'].value
00426         jetCorrLabel = self._parameters['jetCorrLabel'].value
00427         standardAlgo = self._parameters['standardAlgo'].value
00428         standardType = self._parameters['standardType'].value
00429 
00430         ## disable computation of particle-flow based IsoDeposits
00431         ## in case tau is of CaloTau type
00432         if typeLabel == 'Tau':
00433 #            print "NO PF Isolation will be computed for CaloTau (this could be improved later)"
00434             doPFIsoDeposits = False
00435 
00436         ## create old module label from standardAlgo
00437         ## and standardType and return
00438         def oldLabel(prefix = ''):
00439             if prefix == '':
00440                 return "patTaus"
00441             else:
00442                 return prefix + "PatTaus"
00443 
00444         ## capitalize first character of appended part
00445         ## when creating new module label
00446         ## (giving e.g. "patTausCaloRecoTau")
00447         def capitalize(label):
00448             return label[0].capitalize() + label[1:]
00449 
00450         ## create new module label from old module
00451         ## label and return
00452         def newLabel(oldLabel):
00453             newLabel = oldLabel
00454             if ( oldLabel.find(standardAlgo) >= 0 and oldLabel.find(standardType) >= 0 ):
00455                 oldLabel = oldLabel.replace(standardAlgo, algoLabel).replace(standardType, typeLabel)
00456             else:
00457                 oldLabel = oldLabel + capitalize(algoLabel + typeLabel)
00458             return oldLabel
00459 
00460         ## clone module and add it to the patDefaultSequence
00461         def addClone(hook, **replaceStatements):
00462             ## create a clone of the hook with corresponding
00463             ## parameter replacements
00464             newModule = getattr(process, hook).clone(**replaceStatements)
00465             ## add the module to the sequence
00466             addModuleToSequence(hook, newModule)
00467 
00468         ## clone module for computing particle-flow IsoDeposits
00469         def addPFIsoDepositClone(hook, **replaceStatements):
00470             newModule = getattr(process, hook).clone(**replaceStatements)
00471             newModuleIsoDepositExtractor = getattr(newModule, "ExtractorPSet")
00472             setattr(newModuleIsoDepositExtractor, "tauSource", getattr(newModule, "src"))
00473             addModuleToSequence(hook, newModule)
00474 
00475         ## add module to the patDefaultSequence
00476         def addModuleToSequence(hook, newModule):
00477             hookModule = getattr(process, hook)
00478             ## add the new module with standardAlgo &
00479             ## standardType replaced in module label
00480             setattr(process, newLabel(hook), newModule)
00481             ## add new module to default sequence
00482             ## just behind the hookModule
00483             process.patDefaultSequence.replace( hookModule, hookModule*newModule )
00484 
00485         ## add a clone of patTaus
00486         addClone(oldLabel(), tauSource = tauCollection)
00487 
00488         ## add a clone of selectedPatTaus
00489         addClone(oldLabel('selected'), src = cms.InputTag(newLabel(oldLabel())))
00490 
00491         ## add a clone of cleanPatTaus
00492         addClone(oldLabel('clean'), src=cms.InputTag(newLabel(oldLabel('selected'))))
00493 
00494         ## get attributes of new module
00495         newTaus = getattr(process, newLabel(oldLabel()))
00496 
00497         ## add a clone of gen tau matching
00498         addClone('tauMatch', src = tauCollection)
00499         addClone('tauGenJetMatch', src = tauCollection)
00500 
00501         ## add a clone of IsoDeposits computed based on particle-flow
00502         if doPFIsoDeposits:
00503             addPFIsoDepositClone('tauIsoDepositPFCandidates', src = tauCollection)
00504             addPFIsoDepositClone('tauIsoDepositPFChargedHadrons', src = tauCollection)
00505             addPFIsoDepositClone('tauIsoDepositPFNeutralHadrons', src = tauCollection)
00506             addPFIsoDepositClone('tauIsoDepositPFGammas', src = tauCollection)
00507 
00508         if jetCorrLabel:
00509             addClone('patTauJetCorrFactors', src = tauCollection)
00510             getattr(process,newLabel('patTauJetCorrFactors')).payload = jetCorrLabel[0]
00511             getattr(process,newLabel('patTauJetCorrFactors')).levels = jetCorrLabel[1]
00512             getattr(process, newLabel('patTaus')).tauJetCorrFactorsSource = cms.VInputTag(cms.InputTag(newLabel('patTauJetCorrFactors')))
00513 
00514         ## fix label for input tag
00515         def fixInputTag(x): x.setModuleLabel(newLabel(x.moduleLabel))
00516 
00517         ## provide patTau inputs with individual labels
00518         fixInputTag(newTaus.genParticleMatch)
00519         fixInputTag(newTaus.genJetMatch)
00520         fixInputTag(newTaus.isoDeposits.pfAllParticles)
00521         fixInputTag(newTaus.isoDeposits.pfNeutralHadron)
00522         fixInputTag(newTaus.isoDeposits.pfChargedHadron)
00523         fixInputTag(newTaus.isoDeposits.pfGamma)
00524         fixInputTag(newTaus.userIsolation.pfAllParticles.src)
00525         fixInputTag(newTaus.userIsolation.pfNeutralHadron.src)
00526         fixInputTag(newTaus.userIsolation.pfChargedHadron.src)
00527         fixInputTag(newTaus.userIsolation.pfGamma.src)
00528 
00529         ## set discriminators
00530         ## (using switchTauCollection functions)
00531         oldTaus = getattr(process, oldLabel())
00532 #        if typeLabel == 'Tau':
00533 #            switchToCaloTau(process,
00534 #                            pfTauLabel = getattr(oldTaus, "tauSource"),
00535 #                            caloTauLabel = getattr(newTaus, "tauSource"),
00536 #                            patTauLabel = capitalize(algoLabel + typeLabel))
00537 #        else:
00538         switchToPFTauByType(process, pfTauType = algoLabel + typeLabel,
00539                                 pfTauLabelNew = getattr(newTaus, "tauSource"),
00540                                 pfTauLabelOld = getattr(oldTaus, "tauSource"),
00541                                 patTauLabel = capitalize(algoLabel + typeLabel))
00542 
00543 addTauCollection=AddTauCollection()