Пример #1
0
def addBoostedTaus(process):
    from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet
    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag

    process.load("RecoTauTag.Configuration.boostedHPSPFTaus_cff")
    patAlgosToolsTask = configtools.getPatAlgosToolsTask(process)
    patAlgosToolsTask.add(process.boostedHPSPFTausTask)

    process.load("RecoTauTag.Configuration.RecoPFTauTag_cff")
    process.ptau = cms.Path( process.PFTau )
    process.PATTauSequence = cms.Sequence(process.PFTau+process.makePatTaus+process.selectedPatTaus)
    process.PATTauSequenceBoosted = cloneProcessingSnippet(process,process.PATTauSequence, "Boosted", addToTask = True)
    process.recoTauAK4PFJets08RegionBoosted.src = cms.InputTag('boostedTauSeeds')
    process.recoTauAK4PFJets08RegionBoosted.pfCandSrc = cms.InputTag('particleFlow')
    process.recoTauAK4PFJets08RegionBoosted.pfCandAssocMapSrc = cms.InputTag('boostedTauSeeds', 'pfCandAssocMapForIsolation')
    process.ak4PFJetsLegacyHPSPiZerosBoosted.jetSrc = cms.InputTag('boostedTauSeeds')
    process.ak4PFJetsRecoTauChargedHadronsBoosted.jetSrc = cms.InputTag('boostedTauSeeds')
    process.ak4PFJetsRecoTauChargedHadronsBoosted.builders[1].dRcone = cms.double(0.3)
    process.ak4PFJetsRecoTauChargedHadronsBoosted.builders[1].dRconeLimitedToJetArea = cms.bool(True)
    process.combinatoricRecoTausBoosted.jetSrc = cms.InputTag('boostedTauSeeds')
    process.combinatoricRecoTausBoosted.modifiers.remove(process.combinatoricRecoTausBoosted.modifiers[3])
    #process.combinatoricRecoTausBoosted.builders[0].pfCandSrc = cms.InputTag('pfNoPileUpForBoostedTaus')
    process.combinatoricRecoTausBoosted.builders[0].pfCandSrc = cms.InputTag('particleFlow')
    #Note JetArea is not defined for subjets and restiction to jetArea is turned to dRMatch=0.1, so better use the latter explicitely
    #process.hpsPFTauDiscriminationByLooseMuonRejection3Boosted.dRmuonMatchLimitedToJetArea = cms.bool(True)
    #process.hpsPFTauDiscriminationByTightMuonRejection3Boosted.dRmuonMatchLimitedToJetArea = cms.bool(True)
    process.hpsPFTauDiscriminationByLooseMuonRejection3Boosted.dRmuonMatch = 0.1
    process.hpsPFTauDiscriminationByTightMuonRejection3Boosted.dRmuonMatch = 0.1
    massSearchReplaceAnyInputTag(process.PATTauSequenceBoosted,cms.InputTag("ak4PFJets"),cms.InputTag("boostedTauSeeds"))  
    process.slimmedTausBoosted = process.slimmedTaus.clone(src = cms.InputTag("selectedPatTausBoosted"))
    patAlgosToolsTask.add(process.slimmedTausBoosted)

    return process
Пример #2
0
def addBoostedTaus(process):
    from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet
    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag

    process.load("RecoTauTag.Configuration.boostedHPSPFTaus_cff")
    patAlgosToolsTask = configtools.getPatAlgosToolsTask(process)
    patAlgosToolsTask.add(process.boostedHPSPFTausTask)

    process.load("RecoTauTag.Configuration.RecoPFTauTag_cff")
    process.ptau = cms.Path( process.PFTau )
    process.PATTauSequence = cms.Sequence(process.PFTau+process.makePatTaus+process.selectedPatTaus)
    process.PATTauSequenceBoosted = cloneProcessingSnippet(process,process.PATTauSequence, "Boosted", addToTask = True)
    process.recoTauAK4PFJets08RegionBoosted.src = cms.InputTag('boostedTauSeeds')
    process.recoTauAK4PFJets08RegionBoosted.pfCandSrc = cms.InputTag('particleFlow')
    process.recoTauAK4PFJets08RegionBoosted.pfCandAssocMapSrc = cms.InputTag('boostedTauSeeds', 'pfCandAssocMapForIsolation')
    process.ak4PFJetsLegacyHPSPiZerosBoosted.jetSrc = cms.InputTag('boostedTauSeeds')
    process.ak4PFJetsRecoTauChargedHadronsBoosted.jetSrc = cms.InputTag('boostedTauSeeds')
    process.ak4PFJetsRecoTauChargedHadronsBoosted.builders[1].dRcone = cms.double(0.3)
    process.ak4PFJetsRecoTauChargedHadronsBoosted.builders[1].dRconeLimitedToJetArea = cms.bool(True)
    process.combinatoricRecoTausBoosted.jetSrc = cms.InputTag('boostedTauSeeds')
    process.combinatoricRecoTausBoosted.builders[0].pfCandSrc = cms.InputTag('particleFlow')
    ## Note JetArea is not defined for subjets (-> do not switch to True in hpsPFTauDiscriminationByLooseMuonRejection3Boosted, False is default)
    ## The restiction to jetArea is turned to dRMatch=0.1 (-> use explicitly this modified value)
    process.hpsPFTauDiscriminationByMuonRejection3Boosted.dRmuonMatch = 0.1
    massSearchReplaceAnyInputTag(process.PATTauSequenceBoosted,cms.InputTag("ak4PFJets"),cms.InputTag("boostedTauSeeds"))  
    process.slimmedTausBoosted = process.slimmedTaus.clone(src = cms.InputTag("selectedPatTausBoosted"))
    patAlgosToolsTask.add(process.slimmedTausBoosted)

    return process
Пример #3
0
def _setTriggerProcess(process, triggerTag, **kwargs):
	# Set the input tag for the HLT

	# update InputTag for all modules in sequence
	for processAttrName in dir(process):
		processAttr = getattr(process, processAttrName)
		if isinstance(processAttr, cms.Sequence):
            #print "--> Resetting HLT input tag for sequence:", processAttrName
			patutils.massSearchReplaceAnyInputTag(processAttr, cms.InputTag("TriggerResults", "", "HLT"), triggerTag)
			patutils.massSearchReplaceAnyInputTag(processAttr, cms.InputTag("TriggerResults::HLT"), triggerTag)

	# update InputTag for PAT trigger tools
        if hasattr("process", "patTrigger"):
            process.patTrigger.processName = triggerTag.getProcessName()
        if hasattr("process", "patTriggerEvent"):    
            process.patTriggerEvent.processName = triggerTag.getProcessName()

	# update InputTag for all histogram managers,
	# binner and event-dump plugins of GenericAnalyzer module
	for processAttrName in dir(process):
		processAttr = getattr(process, processAttrName)
		if isinstance(processAttr, cms.EDAnalyzer):
			if processAttr.type_() == "GenericAnalyzer":
				if hasattr(processAttr, "analyzers"):
					analyzerPlugins = getattr(processAttr, "analyzers")
					for analyzerPlugin in analyzerPlugins:
						_setattr_ifexists(analyzerPlugin, "hltResultsSource", triggerTag)
				if hasattr(processAttr, "eventDumps"):
					eventDumps = getattr(processAttr, "eventDumps")
					for eventDump in eventDumps:
						_setattr_ifexists(eventDump, "hltResultsSource", triggerTag)
Пример #4
0
def switchToAOD(process, triggerHistManager = None, eventDumpPlugin = None):

    # call "standard" PAT function to restrict all InputTags to AOD event content
    restrictInputToAOD(process, [ "All", ])

    # switch collection of ECAL recHits used as input for IsoDeposit computation
    # from list of all ECAL recHits in the event to "reduced" collections
    # limited to cones of size dR = 0.6 around electron candidates
    if hasattr(process, "p"):
        massSearchReplaceAnyInputTag(process.p, cms.InputTag("ecalRecHit", "EcalRecHitsEB"), cms.InputTag("reducedEcalRecHitsEB"))
        massSearchReplaceAnyInputTag(process.p, cms.InputTag("ecalRecHit", "EcalRecHitsEE"), cms.InputTag("reducedEcalRecHitsEE")) 

    # disable PAT trigger matching
    # (not yet implemented for photons and jets)
    if hasattr(process, "patTriggerSequence"):
        process.patDefaultSequence.remove(process.patTriggerSequence)
    process.patElectrons.embedHighLevelSelection = cms.bool(False)
    #process.patPhotons.embedHighLevelSelection = cms.bool(False)
    process.patMuons.embedHighLevelSelection = cms.bool(False)
    process.patTaus.embedHighLevelSelection = cms.bool(False)
    #process.patJets.embedHighLevelSelection = cms.bool(False)
    process.patMETs.embedHighLevelSelection = cms.bool(False)
    if hasattr(process, "patPFMETs"):
        process.patPFMETs.embedHighLevelSelection = cms.bool(False)

    if triggerHistManager is not None:
        triggerHistManager.hltResultsSource = cms.InputTag('')
        triggerHistManager.l1Bits = cms.vstring()
        triggerHistManager.hltPaths = cms.vstring()
       
    if eventDumpPlugin is not None:
        eventDumpPlugin.l1GtReadoutRecordSource = cms.InputTag('')
        eventDumpPlugin.l1GtObjectMapRecordSource = cms.InputTag('')
        eventDumpPlugin.hltResultsSource = cms.InputTag('')
Пример #5
0
def cloneTagSequenceForEachSystematic(process,
                                      systlabels,
                                      phosystlabels,
                                      jetsystlabels,
                                      jetSystematicsInputTags,
                                      ZPlusJetMode=False):
    for systlabel in systlabels:
        if systlabel == "":
            continue
        from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet, massSearchReplaceAnyInputTag
        newseq = cloneProcessingSnippet(process, process.flashggTagSequence,
                                        systlabel)
        if systlabel in phosystlabels:
            massSearchReplaceAnyInputTag(
                newseq, cms.InputTag("flashggDiPhotonSystematics"),
                cms.InputTag("flashggDiPhotonSystematics", systlabel))
        if systlabel in jetsystlabels:
            for i in range(len(jetSystematicsInputTags)):
                massSearchReplaceAnyInputTag(
                    newseq, jetSystematicsInputTags[i],
                    cms.InputTag(jetSystematicsInputTags[i].moduleLabel,
                                 systlabel))
        for name in newseq.moduleNames():
            module = getattr(process, name)
            if hasattr(module, "SystLabel"):
                module.SystLabel = systlabel
        process.systematicsTagSequences += newseq
        if ZPlusJetMode:
            process.flashggSystTagMerger.src.append(
                cms.InputTag("flashggZPlusJetTag" + systlabel))
        else:
            process.flashggSystTagMerger.src.append(
                cms.InputTag("flashggTagSorter" + systlabel))
Пример #6
0
def addBoostedTaus(process):
    from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet
    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
    process.load("RecoTauTag.Configuration.boostedHPSPFTaus_cff")
    process.load("RecoTauTag.Configuration.RecoPFTauTag_cff")
    process.ptau = cms.Path( process.PFTau )
    process.PATTauSequence = cms.Sequence(process.PFTau+process.makePatTaus+process.selectedPatTaus)
    process.PATTauSequenceBoosted = cloneProcessingSnippet(process,process.PATTauSequence, "Boosted")
    process.recoTauAK4PFJets08RegionBoosted.src = cms.InputTag('boostedTauSeeds')
    process.recoTauAK4PFJets08RegionBoosted.pfCandSrc = cms.InputTag('particleFlow')
    process.recoTauAK4PFJets08RegionBoosted.pfCandAssocMapSrc = cms.InputTag('boostedTauSeeds', 'pfCandAssocMapForIsolation')
    process.ak4PFJetsLegacyHPSPiZerosBoosted.jetSrc = cms.InputTag('boostedTauSeeds')
    process.ak4PFJetsRecoTauChargedHadronsBoosted.jetSrc = cms.InputTag('boostedTauSeeds')
    process.ak4PFJetsRecoTauChargedHadronsBoosted.builders[1].dRcone = cms.double(0.3)
    process.ak4PFJetsRecoTauChargedHadronsBoosted.builders[1].dRconeLimitedToJetArea = cms.bool(True)
    process.combinatoricRecoTausBoosted.jetSrc = cms.InputTag('boostedTauSeeds')
    process.combinatoricRecoTausBoosted.modifiers.remove(process.combinatoricRecoTausBoosted.modifiers[3])
    #process.combinatoricRecoTausBoosted.builders[0].pfCandSrc = cms.InputTag('pfNoPileUpForBoostedTaus')
    process.combinatoricRecoTausBoosted.builders[0].pfCandSrc = cms.InputTag('particleFlow')
    process.hpsPFTauDiscriminationByLooseMuonRejection3Boosted.dRmuonMatchLimitedToJetArea = cms.bool(True)
    process.hpsPFTauDiscriminationByTightMuonRejection3Boosted.dRmuonMatchLimitedToJetArea = cms.bool(True)
    massSearchReplaceAnyInputTag(process.PATTauSequenceBoosted,cms.InputTag("ak4PFJets"),cms.InputTag("boostedTauSeeds"))  
    process.slimmedTausBoosted = process.slimmedTaus.clone(src = cms.InputTag("selectedPatTausBoosted"))
    
    return process
Пример #7
0
def configurePrePatMuon(process) :
    process.selectedPrimaryVertexQuality = cms.EDFilter("VertexSelector",
                                                        src = cms.InputTag('offlinePrimaryVertices'),
                                                        cut = cms.string("isValid & ndof >= 4 & chi2 > 0 & tracksSize > 0"), # CV: cut >= 4 if using 'offlinePrimaryVertices', # >= 7 if using 'offlinePrimaryVerticesWithBS' as input
                                                        filter = cms.bool(False)
                                                        )
    process.selectedPrimaryVertexPosition = cms.EDFilter("VertexSelector",
                                                         src = cms.InputTag('selectedPrimaryVertexQuality'),
                                                         cut = cms.string("abs(z) < 24 & abs(position.Rho) < 2."),
                                                         filter = cms.bool(False)
                                                         )
    process.load("CommonTools.ParticleFlow.pfNoPileUp_cff")
    process.pfPileUp.Enable = cms.bool(True)
    process.pfPileUp.checkClosestZVertex = cms.bool(True)
    process.pfPileUp.Vertices = cms.InputTag('selectedPrimaryVertexPosition')
    process.load("CommonTools.ParticleFlow.pfParticleSelection_cff")

    process.pfPileUp.PFCandidates = 'particleFlow'
    process.pfNoPileUp.bottomCollection = 'particleFlow'
    process.pfPileUpIso.PFCandidates = 'particleFlow'
    process.pfNoPileUpIso.bottomCollection='particleFlow'
    
    process.load("RecoMuon.MuonIsolation.muonPFIsolation_cff")
    import PhysicsTools.PatAlgos.tools.helpers as patutils
    patutils.massSearchReplaceAnyInputTag(process.muonPFIsolationDepositsSequence, cms.InputTag('muons1stStep'), cms.InputTag('muons'))
    process.produceMuonPFIsoPrePat = cms.Sequence(
        process.selectedPrimaryVertexQuality
        * process.selectedPrimaryVertexPosition
        * process.pfNoPileUpSequence
        * process.pfParticleSelectionSequence
        * process.muonPFIsolationDepositsSequence)
Пример #8
0
def MassReplaceInputTag(process,old="rawDataCollector",new="rawDataRepacker",verbose=False,moduleLabelOnly=False,skipLabelTest=False):
#   replace InputTag values (adapted from Configuration/Applications/python/ConfigBuilder.py)
    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
    for s in process.paths_().keys():
        massSearchReplaceAnyInputTag(getattr(process,s),old,new,verbose,moduleLabelOnly,skipLabelTest)
    for s in process.endpaths_().keys():
        massSearchReplaceAnyInputTag(getattr(process,s),old,new,verbose,moduleLabelOnly,skipLabelTest)
    return(process)
Пример #9
0
def MassReplaceInputTag(process,
                        old="rawDataCollector",
                        new="rawDataRepacker"):
    #   replace InputTag values (adapted from Configuration/Applications/python/ConfigBuilder.py)
    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
    for s in process.paths_().keys():
        massSearchReplaceAnyInputTag(getattr(process, s), old, new)
    return (process)
def changeRecoMuonInput(process,
                        recoMuonCollectionTag,
                        oldRecoMuonCollectionTag=cms.InputTag("muons")):
    "Use a different input collection of reco muons"
    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
    massSearchReplaceAnyInputTag(process.patMuonsWithTriggerSequence,
                                 oldRecoMuonCollectionTag,
                                 recoMuonCollectionTag)
Пример #11
0
def MassReplaceInputTag(process,old="rawDataCollector",new="rawDataRepacker",verbose=False,moduleLabelOnly=False,skipLabelTest=False):
#   replace InputTag values (adapted from Configuration/Applications/python/ConfigBuilder.py)
    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
    for s in process.paths_().keys():
        massSearchReplaceAnyInputTag(getattr(process,s),old,new,verbose,moduleLabelOnly,skipLabelTest)
    for s in process.endpaths_().keys():
        massSearchReplaceAnyInputTag(getattr(process,s),old,new,verbose,moduleLabelOnly,skipLabelTest)
    return(process)
Пример #12
0
def rerunParticleFlow(process, inputProcess):

    # load event-setup definitions necessary to rerun particle-flow sequence
    loadIfNecessary(
        process, "TrackPropagation.SteppingHelixPropagator.SteppingHelixPropagatorAny_cfi", "SteppingHelixPropagatorAny"
    )
    loadIfNecessary(
        process,
        "CalibTracker.SiPixelESProducers.SiPixelTemplateDBObjectESProducer_cfi",
        "siPixelTemplateDBObjectESProducer",
    )
    loadIfNecessary(process, "RecoTracker.MeasurementDet.MeasurementTrackerESProducer_cfi", "MeasurementTracker")
    loadIfNecessary(process, "RecoLocalCalo.EcalRecAlgos.EcalSeverityLevelESProducer_cfi", "ecalSeverityLevel")
    loadIfNecessary(
        process, "RecoEcal.EgammaCoreTools.EcalNextToDeadChannelESProducer_cff", "ecalNextToDeadChannelESProducer"
    )
    loadIfNecessary(process, "RecoLocalCalo.HcalRecAlgos.hcalRecAlgoESProd_cfi", "hcalRecAlgos")

    if not hasattr(process, "UpdaterService"):
        process.UpdaterService = cms.Service("UpdaterService")

    # load module definitions necessary to rerun particle-flow sequence
    loadIfNecessary(process, "RecoParticleFlow.PFClusterProducer.particleFlowCluster_cff", "particleFlowCluster")
    loadIfNecessary(
        process, "RecoEgamma.EgammaElectronProducers.gsfElectronSequence_cff", "gsfEcalDrivenElectronSequence"
    )
    loadIfNecessary(process, "RecoParticleFlow.Configuration.RecoParticleFlow_cff", "particleFlowReco")
    loadIfNecessary(process, "RecoMuon.MuonIsolation.muonPFIsolationValues_cff", "muonPFIsolationSequence")

    # define complete sequence of all modules necessary to rerun particle-flow algorithm
    process.rerunParticleFlowSequence = cms.Sequence(
        process.particleFlowCluster
        + process.particleFlowTrackWithDisplacedVertex
        + process.gsfEcalDrivenElectronSequence
        + process.particleFlowReco
        + process.particleFlowLinks
    )

    # CV: clone sequence and give it a different name so that particle-flow algorithm
    #     can be run using "official" module labels on embedded event later
    configtools.cloneProcessingSnippet(process, process.rerunParticleFlowSequence, "ForPFMuonCleaning")

    # CV: run particle-flow algorithm on final RECO muon collection
    #    (rather than running muon reconstruction sequence in steps)
    process.pfTrackForPFMuonCleaning.MuColl = cms.InputTag("muons")
    process.particleFlowBlockForPFMuonCleaning.RecMuons = cms.InputTag("muons")
    process.particleFlowTmpForPFMuonCleaning.muons = cms.InputTag("muons")
    process.particleFlowForPFMuonCleaning.FillMuonRefs = False

    # CV: make sure that all particle-flow based isolation is computed wrt. 'particleFlowTmp' collection
    #    (PAT may overwrite configuration parameters to refer to 'particleFlow' instead)
    configtools.massSearchReplaceAnyInputTag(
        process.rerunParticleFlowSequenceForPFMuonCleaning,
        cms.InputTag("particleFlow"),
        cms.InputTag("particleFlowTmp"),
    )

    return process.rerunParticleFlowSequenceForPFMuonCleaning
Пример #13
0
def addLowPtTaus(process):
    from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet
    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag

    process.load("RecoTauTag.Configuration.LowPtHPSPFTaus_cff")
    patAlgosToolsTask = configtools.getPatAlgosToolsTask(process)
    patAlgosToolsTask.add(process.LowPtHPSPFTausTask)

    process.load("RecoTauTag.Configuration.RecoPFTauTag_cff")
    process.ptau = cms.Path(process.PFTau)
    process.PATTauSequence = cms.Sequence(process.PFTau + process.makePatTaus +
                                          process.selectedPatTaus)
    process.PATTauSequenceLowPt = cloneProcessingSnippet(
        process, process.PATTauSequence, "LowPt", addToTask=True)
    process.recoTauAK4PFJets08RegionLowPt.src = cms.InputTag('LowPtTauSeeds')
    process.recoTauAK4PFJets08RegionLowPt.pfCandSrc = cms.InputTag(
        'particleFlow')
    process.recoTauAK4PFJets08RegionLowPt.pfCandAssocMapSrc = cms.InputTag(
        'LowPtTauSeeds', 'pfCandAssocMapForIsolation')
    process.selectedPatTausLowPt.cut = cms.string(
        "pt > 1. && tauID(\'decayModeFindingNewDMs\')> 0.5"
    )  #tau pt> 1 GeV of threshold output
    process.ak4PFJetsLegacyHPSPiZerosLowPt.jetSrc = cms.InputTag(
        'LowPtTauSeeds')
    process.ak4PFJetsLegacyHPSPiZerosLowPt.minJetPt = cms.double(
        1)  #jet pt> 1 GeV of threshold in input
    process.ak4PFJetsRecoTauChargedHadronsLowPt.jetSrc = cms.InputTag(
        'LowPtTauSeeds')
    process.ak4PFJetsRecoTauChargedHadronsLowPt.builders[
        1].dRcone = cms.double(0.3)
    process.ak4PFJetsRecoTauChargedHadronsLowPt.builders[
        1].dRconeLimitedToJetArea = cms.bool(True)
    process.combinatoricRecoTausLowPt.jetSrc = cms.InputTag('LowPtTauSeeds')
    _allModifiers = cms.VPSet()
    for modifier in process.combinatoricRecoTausLowPt.modifiers:
        _allModifiers.append(modifier)
    process.combinatoricRecoTausLowPt.modifiers.remove(
        process.combinatoricRecoTausLowPt.modifiers[3])
    from Configuration.Eras.Modifier_run2_miniAOD_80XLegacy_cff import run2_miniAOD_80XLegacy
    from Configuration.Eras.Modifier_run2_miniAOD_94XFall17_cff import run2_miniAOD_94XFall17
    for era in [run2_miniAOD_80XLegacy, run2_miniAOD_94XFall17]:
        era.toModify(process.combinatoricRecoTausLowPt,
                     modifiers=_allModifiers)
    process.combinatoricRecoTausLowPt.builders[0].pfCandSrc = cms.InputTag(
        'particleFlow')
    ## Note JetArea is not defined for subjets (-> do not switch to True in hpsPFTauDiscriminationByLooseMuonRejection3LowPt, False is default)
    ## The restiction to jetArea is turned to dRMatch=0.1 (-> use explicitly this modified value)
    #process.hpsPFTauDiscriminationByLooseMuonRejection3LowPt.dRmuonMatch = 0.1
    #process.hpsPFTauDiscriminationByTightMuonRejection3LowPt.dRmuonMatch = 0.1
    massSearchReplaceAnyInputTag(process.PATTauSequenceLowPt,
                                 cms.InputTag("ak4PFJets"),
                                 cms.InputTag("LowPtTauSeeds"))
    process.slimmedTausLowPt = process.slimmedTaus.clone(
        src=cms.InputTag("selectedPatTausLowPt"))
    patAlgosToolsTask.add(process.slimmedTausLowPt)

    return process
Пример #14
0
def useExistingPATMuons(process, newPatMuonTag, addL1Info=False):
    "Start from existing pat Muons instead of producing them"
    process.patMuonsWithTriggerSequence.remove(process.patMuonsWithoutTrigger)
    process.patMuonsWithTriggerSequence.remove(process.muonL1Info)
    process.patMuonsWithTrigger.src = newPatMuonTag
    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
    massSearchReplaceAnyInputTag(process.patMuonsWithTriggerSequence, cms.InputTag('patMuonsWithoutTrigger'), newPatMuonTag)
    if addL1Info:
        process.muonL1Info.src = newPatMuonTag.muonSource
        addL1UserData(getattr(process,newPatMuonTag.moduleLabel), 'muonL1Info')
Пример #15
0
def useExistingPATMuons(process, newPatMuonTag, addL1Info=False):
    "Start from existing pat Muons instead of producing them"
    process.patMuonsWithTriggerSequence.remove(process.patMuonsWithoutTrigger)
    process.patMuonsWithTriggerSequence.remove(process.muonL1Info)
    process.patMuonsWithTrigger.src = newPatMuonTag
    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
    massSearchReplaceAnyInputTag(process.patMuonsWithTriggerSequence, cms.InputTag('patMuonsWithoutTrigger'), newPatMuonTag)
    if addL1Info:
        process.muonL1Info.src = newPatMuonTag.muonSource
        addL1UserData(getattr(process,newPatMuonTag.moduleLabel), 'muonL1Info')
Пример #16
0
def replaceInputTagInAllSequences(process, oldName, newName, exceptions=[], pathExceptions=[], verbose=False):
    if verbose:
        print "Replacing %s -> %s" % (oldName, newName)
    for seqName, seq in process.sequences_().iteritems():
        if seqName not in exceptions:
            if verbose:
                print "  in sequence %s" % seqName
            helpers.massSearchReplaceAnyInputTag(seq, cms.InputTag(oldName), cms.InputTag(newName), verbose=verbose)
    for pathName, path in process.paths_().iteritems():
        if pathName not in pathExceptions:
            if verbose:
                print "  in path %s" % pathName
            helpers.massSearchReplaceAnyInputTag(path, cms.InputTag(oldName), cms.InputTag(newName), verbose=verbose)
def backupJetsSecondStep(process, sequences, badMuons, verbose=False):
    """Deploy the snapshots after the change of PFCandidates"""
    # put back the old input tags
    for sequence in sequences.itervalues():
        massSearchReplaceAnyInputTag(sequence, "pfCandidatesBadMuonsCleaned", "particleFlow")
        massSearchReplaceAnyInputTag(sequence, "muonsCleaned", "muons")
    # gate the input collections to avoid re-running most of PAT on good events
    reduceInputJetCollection(process, process.ak4PFJetsCHSBackup, badMuons)
    reduceInputJetCollection(process, process.ak4PFJetsPuppiBackup, badMuons)
    # fix names in the valuemaps
    process.patJetsBackup.userData.userInts.labelPostfixesToStrip = cms.vstring("Backup",)
    process.patJetsBackup.userData.userFloats.labelPostfixesToStrip = cms.vstring("Backup",)
    process.patJetsAK8Backup.userData.userFloats.labelPostfixesToStrip = cms.vstring("Backup",)
    process.patJetsAK8PuppiBackup.userData.userFloats.labelPostfixesToStrip = cms.vstring("Backup",)    
    #
    # now deal with daughter links
    # for these we can keep the daughters
    process.slimmedJetsBackup.mixedDaughters = True
    process.slimmedJetsBackup.packedPFCandidates = cms.InputTag("oldPFCandToPackedOrDiscarded")
    process.slimmedJetsAK8PFCHSSoftDropSubjetsBackup.mixedDaughters = True
    process.slimmedJetsAK8PFCHSSoftDropSubjetsBackup.packedPFCandidates = cms.InputTag("oldPFCandToPackedOrDiscarded")
    # for these we can't
    process.slimmedJetsPuppiBackup.dropDaughters = '1'
    process.slimmedJetsAK8PFPuppiSoftDropSubjetsBackup.dropDaughters = '1'
    # for these we do even if we wouldn't have done in the standard case, since we couldn't for the subjets
    process.packedPatJetsAK8Backup.fixDaughters = False
    process.slimmedJetsAK8Backup.rekeyDaughters = '1'
    process.slimmedJetsAK8Backup.mixedDaughters = True
    process.slimmedJetsAK8Backup.packedPFCandidates = cms.InputTag("oldPFCandToPackedOrDiscarded")
    #
    reduceFinalJetCollection(process, process.slimmedJetsBackup, badMuons)
    reduceFinalJetCollection(process, process.slimmedJetsPuppiBackup, badMuons)
    reduceFinalJetCollection(process, process.slimmedJetsAK8Backup, badMuons)
    #
    addKeepStatement(process,
                     "keep *_slimmedJets_*_*",
                     ["keep *_slimmedJetsBackup_*_*"],
                     verbose=verbose)
    addKeepStatement(process, "keep *_slimmedJetsPuppi_*_*",
                     ["keep *_slimmedJetsPuppiBackup_*_*"],
                     verbose=verbose)
    addKeepStatement(process,
                     "keep *_slimmedJetsAK8_*_*",
                     ["keep *_slimmedJetsAK8Backup_*_*"],
                     verbose=verbose)
    addKeepStatement(process,"keep *_slimmedJetsAK8PFCHSSoftDropPacked_SubJets_*",
                     ["keep *_slimmedJetsAK8PFCHSSoftDropPackedBackup_SubJets_*"],
                     verbose=verbose)
    addKeepStatement(process,"keep *_slimmedJetsAK8PFPuppiSoftDropPacked_SubJets_*",
                     ["keep *_slimmedJetsAK8PFPuppiSoftDropPackedBackup_SubJets_*"],
                     verbose=verbose)
def modifyBTagDiscs(process, algo, newMinDisc, newMaxDisc):

    getattr(process, algo + "BJets").cut = 'bDiscriminator("' + algo + 'BJetTags") > ' + str(newMinDisc)
    process.analyseFullHadronicSelection.replace(process.trackCountingHighEffBJets, getattr(process, algo + "BJets"))

    process.kinFitTtFullHadEventHypothesis.bTagAlgo = algo + 'BJetTags'
    process.fullHadTopReco_2.analyze.bTagAlgo       = algo + 'BJetTags' 
    process.fullHadTopReco_3.analyze.bTagAlgo       = algo + 'BJetTags' 

    process.kinFitTtFullHadEventHypothesis.minBTagValueBJet    = newMinDisc
    process.kinFitTtFullHadEventHypothesis.maxBTagValueNonBJet = newMaxDisc

    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
    massSearchReplaceAnyInputTag(process.analyseFullHadronicSelection, 'trackCountingHighEffBJets', algo + 'BJets')
Пример #19
0
def modifyTagSequenceForSystematics(process,
                                    jetSystematicsInputTags,
                                    ZPlusJetMode=False):
    process.flashggTagSequence.remove(
        process.flashggUnpackedJets)  # to avoid unnecessary cloning
    process.flashggTagSequence.remove(process.flashggUpdatedIdMVADiPhotons
                                      )  # Needs to be run before systematics
    from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet, massSearchReplaceAnyInputTag
    massSearchReplaceAnyInputTag(process.flashggTagSequence,
                                 cms.InputTag("flashggUpdatedIdMVADiPhotons"),
                                 cms.InputTag("flashggDiPhotonSystematics"))
    massSearchReplaceAnyInputTag(process.flashggTagSequence,
                                 cms.InputTag("flashggSelectedElectrons"),
                                 cms.InputTag("flashggElectronSystematics"))
    massSearchReplaceAnyInputTag(process.flashggTagSequence,
                                 cms.InputTag("flashggSelectedMuons"),
                                 cms.InputTag("flashggMuonSystematics"))
    from flashgg.Taggers.flashggTags_cff import UnpackedJetCollectionVInputTag
    for i in range(len(jetSystematicsInputTags)):
        massSearchReplaceAnyInputTag(process.flashggTagSequence,
                                     UnpackedJetCollectionVInputTag[i],
                                     jetSystematicsInputTags[i])

    if ZPlusJetMode == 2:  # VBF
        process.flashggSystTagMerger = cms.EDProducer(
            "VBFTagMerger", src=cms.VInputTag("flashggVBFTag"))
    elif ZPlusJetMode:
        process.flashggSystTagMerger = cms.EDProducer(
            "ZPlusJetTagMerger", src=cms.VInputTag("flashggZPlusJetTag"))
    else:
        process.flashggSystTagMerger = cms.EDProducer(
            "TagMerger", src=cms.VInputTag("flashggTagSorter"))
    process.systematicsTagSequences = cms.Sequence()
def runOnCalo(process):
    print "++++++++++++++++++++++++++++++++++++++++++++"
    print "switching all inputs in to run on Calo"
    print "goodJetsPF -> goodJets"
    print "patMETsPF  -> patMETs"
    print "++++++++++++++++++++++++++++++++++++++++++++"
    process.analyseFullHadronicSelection.replace(process.goodJetsPF, process.goodJets)

    ## exchange PFJetID cuts to JetID
    process.tight4LeadingJets.cut = tight4JetCut  # + tightCaloJetID
    process.tight5LeadingJets.cut = tight5JetCut  # + tightCaloJetID
    # process.tightLeadingJets.cut  = tight6JetCut #+ tightCaloJetID
    process.tight6LeadingJets.cut = tight6JetCut  # + tightCaloJetID
    process.tightLeadingJets.cut = tightJetCut  # + tightCaloJetID
    # process.tightBottomJets.cut   = tight6JetCut #+ tightCaloJetID
    process.tightBottomJets.cut = tightJetCut  # + tightCaloJetID

    ## exchange resolutions for CaloJets
    from TopQuarkAnalysis.TopObjectResolutions.stringResolutions_etEtaPhi_cff import udscResolution, bjetResolution

    process.kinFitTtFullHadEventHypothesis.udscResolutions = udscResolution.functions
    process.kinFitTtFullHadEventHypothesis.bResolutions = bjetResolution.functions

    # for suf in listOfMonitoringSuffixes:
    #    if(hasattr(process, 'kinFitQuality'+suf)):
    #        getattr(process, 'kinFitQuality'+suf).analyze.udscResolutions = udscResolution.functions
    #        getattr(process, 'kinFitQuality'+suf).analyze.bResolutions    = bjetResolution.functions

    ## run kinematic fit for CaloJets with L1L2L3(Res)L5 correted jets
    process.kinFitTtFullHadEventHypothesis.jetCorrectionLevel = "L5Hadron"
    process.ttFullHadHypGenMatch.jetCorrectionLevel = "L5Hadron"

    ## replace PFJets and PFMET with CaloJets and CaloMET
    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag

    massSearchReplaceAnyInputTag(process.analyseFullHadronicSelection, "goodJetsPF", "goodJets")
    massSearchReplaceAnyInputTag(process.analyseFullHadronicSelection, "patMETsPF", "patMETs")

    ## give correct resolutions for background estimation if done
    if hasattr(process, "analyzeFullHadQCDEstimation"):
        process.analyzeFullHadQCDEstimation.analyze.udscResolutions = udscResolution.functions
        process.analyzeFullHadQCDEstimation.analyze.bResolutions = bjetResolution.functions

    ## in case of mc, smear the energy resolution additionally
    if hasattr(process, "scaledJetEnergy"):
        process.scaledJetEnergy.inputJets = "selectedPatJets"
        process.scaledJetEnergy.inputMETs = "patMETs"
        process.scaledJetEnergy.payload = "AK5Calo"
def switch_hlt_process_name(process, name):
    # JMTBAD better place for this fcn
    class warn_hlt_visitor(object):
        def enter(self, visitee):
            for attr in dir(visitee):
                if str(getattr(visitee, attr)) == 'HLT':
                    print 'warning: visitee %s, attribute %s has value HLT' % (visitee, attr)
        def leave(self, visitee):
            pass
    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
    for path_name, path in process.paths.iteritems(): # why does values() throw an exception?
        for label in ['TriggerResults', 'hltL1GtObjectMap', 'hltTriggerSummaryAOD']:
            old = cms.InputTag(label, '', 'HLT')
            new = cms.InputTag(label, '', name)
            massSearchReplaceAnyInputTag(path, old, new, verbose=False)
        path.visit(warn_hlt_visitor())
Пример #22
0
def rerunParticleFlow(process, inputProcess):

    # load event-setup definitions necessary to rerun particle-flow sequence
    loadIfNecessary(process, "TrackPropagation.SteppingHelixPropagator.SteppingHelixPropagatorAny_cfi", "SteppingHelixPropagatorAny")
    loadIfNecessary(process, "CalibTracker.SiPixelESProducers.SiPixelTemplateDBObjectESProducer_cfi", "siPixelTemplateDBObjectESProducer")
    loadIfNecessary(process, "RecoTracker.MeasurementDet.MeasurementTrackerESProducer_cfi", "MeasurementTracker")
    loadIfNecessary(process, "RecoLocalCalo.EcalRecAlgos.EcalSeverityLevelESProducer_cfi", "ecalSeverityLevel")
    loadIfNecessary(process, "RecoEcal.EgammaCoreTools.EcalNextToDeadChannelESProducer_cff", "ecalNextToDeadChannelESProducer")
    loadIfNecessary(process, "RecoLocalCalo.HcalRecAlgos.hcalRecAlgoESProd_cfi", "hcalRecAlgos")

    if not hasattr(process, "UpdaterService"):
        process.UpdaterService = cms.Service("UpdaterService")

    # load module definitions necessary to rerun particle-flow sequence
    loadIfNecessary(process, "RecoParticleFlow.PFClusterProducer.particleFlowCluster_cff", "particleFlowCluster")    
    loadIfNecessary(process, "RecoEgamma.EgammaElectronProducers.gsfElectronSequence_cff", "gsfEcalDrivenElectronSequence")
    loadIfNecessary(process, "RecoParticleFlow.Configuration.RecoParticleFlow_cff", "particleFlowReco")
    loadIfNecessary(process, "RecoMuon.MuonIsolation.muonPFIsolationValues_cff", "muonPFIsolationSequence")

    # define complete sequence of all modules necessary to rerun particle-flow algorithm
    process.rerunParticleFlowSequence = cms.Sequence(
        process.particleFlowCluster 
       + process.particleFlowTrackWithDisplacedVertex
       + process.gsfEcalDrivenElectronSequence
       + process.particleFlowReco
       + process.particleFlowLinks
    )

    # CV: clone sequence and give it a different name so that particle-flow algorithm
    #     can be run using "official" module labels on embedded event later
    configtools.cloneProcessingSnippet(process, process.rerunParticleFlowSequence, "ForPFMuonCleaning")

    # CV: run particle-flow algorithm on final RECO muon collection
    #    (rather than running muon reconstruction sequence in steps)    
    process.pfTrackForPFMuonCleaning.MuColl = cms.InputTag('muons')
    process.particleFlowBlockForPFMuonCleaning.RecMuons = cms.InputTag('muons')
    process.particleFlowTmpForPFMuonCleaning.muons = cms.InputTag('muons')
    process.particleFlowForPFMuonCleaning.FillMuonRefs = False

    # CV: make sure that all particle-flow based isolation is computed wrt. 'particleFlowTmp' collection
    #    (PAT may overwrite configuration parameters to refer to 'particleFlow' instead)
    configtools.massSearchReplaceAnyInputTag(process.rerunParticleFlowSequenceForPFMuonCleaning, cms.InputTag('particleFlow'), cms.InputTag('particleFlowTmp'))

    return process.rerunParticleFlowSequenceForPFMuonCleaning
Пример #23
0
def switch_reco_process_name(process, name):
    # JMTBAD better place for this fcn
    class warn_hlt_visitor(object):
        def enter(self, visitee):
            for attr in dir(visitee):
                if str(getattr(visitee, attr)) == 'HLT':
                    print 'warning: visitee %s, attribute %s has value HLT' % (
                        visitee, attr)

        def leave(self, visitee):
            pass

    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
    for path_name, path in process.paths.iteritems(
    ):  # why does values() throw an exception?
        for label in ['TriggerResults']:
            old = cms.InputTag(label, '', 'RECO')
            new = cms.InputTag(label, '', name)
            massSearchReplaceAnyInputTag(path, old, new, verbose=False)
Пример #24
0
def modifyTagSequenceForSystematics(process,jetSystematicsInputTags,ZPlusJetMode=False):
    process.flashggTagSequence.remove(process.flashggUnpackedJets) # to avoid unnecessary cloning
    process.flashggTagSequence.remove(process.flashggUpdatedIdMVADiPhotons) # Needs to be run before systematics
    from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet,massSearchReplaceAnyInputTag
    massSearchReplaceAnyInputTag(process.flashggTagSequence,cms.InputTag("flashggUpdatedIdMVADiPhotons"),cms.InputTag("flashggDiPhotonSystematics"))
    massSearchReplaceAnyInputTag(process.flashggTagSequence,cms.InputTag("flashggSelectedElectrons"),cms.InputTag("flashggElectronSystematics"))
    massSearchReplaceAnyInputTag(process.flashggTagSequence,cms.InputTag("flashggSelectedMuons"),cms.InputTag("flashggMuonSystematics"))
    massSearchReplaceAnyInputTag(process.flashggTagSequence,cms.InputTag("flashggMetsCorr"),cms.InputTag("flashggMetSystematics"))
    from flashgg.Taggers.flashggTags_cff import UnpackedJetCollectionVInputTag
    for i in range(len(jetSystematicsInputTags)):
        massSearchReplaceAnyInputTag(process.flashggTagSequence,UnpackedJetCollectionVInputTag[i],jetSystematicsInputTags[i])

    if ZPlusJetMode == 2:  # VBF    
        process.flashggSystTagMerger = cms.EDProducer("VBFTagMerger",src=cms.VInputTag("flashggVBFTag"))
    elif ZPlusJetMode:    
        process.flashggSystTagMerger = cms.EDProducer("ZPlusJetTagMerger",src=cms.VInputTag("flashggZPlusJetTag"))
    else:
        process.flashggSystTagMerger = cms.EDProducer("TagMerger",src=cms.VInputTag("flashggTagSorter"))
    process.systematicsTagSequences = cms.Sequence()
Пример #25
0
def dummy_beamspot(process, params):
    params = getattr(DummyBeamSpots, params)

    process.myBeamSpot = cms.EDProducer('DummyBeamSpotProducer', params)

    for name, path in process.paths.items():
        path.insert(0, process.myBeamSpot)

    for name, out in process.outputModules.items():
        new_cmds = []
        for cmd in out.outputCommands:
            if 'offlineBeamSpot' in cmd:
                new_cmds.append(cmd.replace('offlineBeamSpot', 'myBeamSpot'))
        out.outputCommands += new_cmds

    import itertools
    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
    for path_name, path in itertools.chain(process.paths.iteritems(), process.endpaths.iteritems()):
        massSearchReplaceAnyInputTag(path, cms.InputTag('offlineBeamSpot'), cms.InputTag('myBeamSpot'), verbose=True)
Пример #26
0
def cloneTagSequenceForEachSystematic(process,systlabels,phosystlabels,jetsystlabels,jetSystematicsInputTags,ZPlusJetMode=False):
    for systlabel in systlabels:
        if systlabel == "":
            continue
        from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet,massSearchReplaceAnyInputTag
        newseq = cloneProcessingSnippet(process,process.flashggTagSequence,systlabel)
        if systlabel in phosystlabels:
            massSearchReplaceAnyInputTag(newseq,cms.InputTag("flashggDiPhotonSystematics"),cms.InputTag("flashggDiPhotonSystematics",systlabel))
        if systlabel in jetsystlabels:
            for i in range(len(jetSystematicsInputTags)):
                massSearchReplaceAnyInputTag(newseq,jetSystematicsInputTags[i],cms.InputTag(jetSystematicsInputTags[i].moduleLabel,systlabel))
        for name in newseq.moduleNames():
            module = getattr(process,name)
            if hasattr(module,"SystLabel"):
                module.SystLabel = systlabel
        process.systematicsTagSequences += newseq
        if ZPlusJetMode:
            process.flashggSystTagMerger.src.append(cms.InputTag("flashggZPlusJetTag" + systlabel))
        else:
            process.flashggSystTagMerger.src.append(cms.InputTag("flashggTagSorter" + systlabel))
def modifyBTagDiscs(process, algo, newMinDisc, newMaxDisc):

    getattr(process, algo + "BJets").cut = 'bDiscriminator("' + algo + 'BJetTags") > ' + str(newMinDisc)
    process.analyseFullHadronicSelection.replace(process.trackCountingHighEffBJets, getattr(process, algo + "BJets"))

    for suf in listOfMonitoringSuffixes:
        if hasattr(process, "fullHadTopReco" + suf):
            getattr(process, "fullHadTopReco" + suf).analyze.bTagAlgo = algo + "BJetTags"

    process.kinFitTtFullHadEventHypothesis.bTagAlgo = algo + "BJetTags"
    process.kinFitTtFullHadEventHypothesis.minBTagValueBJet = newMinDisc
    process.kinFitTtFullHadEventHypothesis.maxBTagValueNonBJet = newMaxDisc

    if hasattr(process, "analyzeFullHadEventMixer"):
        process.analyzeFullHadEventMixer.bTagAlgo = algo + "BJetTags"
        process.analyzeFullHadEventMixer.minBTagValueBJet = newMinDisc
        process.analyzeFullHadEventMixer.maxBTagValueNonBJet = newMaxDisc

    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag

    massSearchReplaceAnyInputTag(process.analyseFullHadronicSelection, "trackCountingHighEffBJets", algo + "BJets")
Пример #28
0
def addBoostedTaus(process):
    from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet
    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
    process.load("RecoTauTag.Configuration.boostedHPSPFTaus_cff")
    process.load("RecoTauTag.Configuration.RecoPFTauTag_cff")
    process.ptau = cms.Path( process.PFTau )
    process.PATTauSequence = cms.Sequence(process.PFTau+process.makePatTaus+process.selectedPatTaus)
    process.PATTauSequenceBoosted = cloneProcessingSnippet(process,process.PATTauSequence, "Boosted")
    process.recoTauAK4PFJets08RegionBoosted.src = cms.InputTag('boostedTauSeeds')
    process.recoTauAK4PFJets08RegionBoosted.pfCandSrc = cms.InputTag('particleFlow')
    process.recoTauAK4PFJets08RegionBoosted.pfCandAssocMapSrc = cms.InputTag('boostedTauSeeds', 'pfCandAssocMapForIsolation')
    process.ak4PFJetsLegacyHPSPiZerosBoosted.jetSrc = cms.InputTag('boostedTauSeeds')
    process.ak4PFJetsRecoTauChargedHadronsBoosted.jetSrc = cms.InputTag('boostedTauSeeds')
    process.ak4PFJetsRecoTauChargedHadronsBoosted.builders[1].dRcone = cms.double(0.3)
    process.ak4PFJetsRecoTauChargedHadronsBoosted.builders[1].dRconeLimitedToJetArea = cms.bool(True)
    process.combinatoricRecoTausBoosted.jetSrc = cms.InputTag('boostedTauSeeds')
    process.combinatoricRecoTausBoosted.modifiers.remove(process.combinatoricRecoTausBoosted.modifiers[3])
    #process.combinatoricRecoTausBoosted.builders[0].pfCandSrc = cms.InputTag('pfNoPileUpForBoostedTaus')
    process.combinatoricRecoTausBoosted.builders[0].pfCandSrc = cms.InputTag('particleFlow')
    massSearchReplaceAnyInputTag(process.PATTauSequenceBoosted,cms.InputTag("ak4PFJets"),cms.InputTag("boostedTauSeeds"))  
    process.slimmedTausBoosted = process.slimmedTaus.clone(src = cms.InputTag("selectedPatTausBoosted"))
    
    return process
def runOnCalo(process):
    print '++++++++++++++++++++++++++++++++++++++++++++'
    print 'switching all inputs in to run on Calo'
    print 'goodJetsPF -> goodJets'
    print 'patMETsPF  -> patMETs'
    print '++++++++++++++++++++++++++++++++++++++++++++'
    process.analyseFullHadronicSelection.replace(process.goodJetsPF, process.goodJets)

    ## exchange PFJetID cuts to JetID
    process.tightLeadingJets.cut = tightJetCut + tightCaloJetID
    process.tightBottomJets.cut  = tightJetCut + tightCaloJetID
    process.monitoredTightBottomJets.cut = tightJetCut + tightCaloJetID

    ## exchange resolutions for CaloJets
    process.load("TopQuarkAnalysis.TopObjectResolutions.stringResolutions_etEtaPhi_cff")
    process.kinFitTtFullHadEventHypothesis.udscResolutions = process.udscResolutionPF.functions
    process.kinFitTtFullHadEventHypothesis.bResolutions    = process.bjetResolutionPF.functions

    #process.kinFitQuality_2.analyze.udscResolutions        = process.udscResolutionPF.functions
    #process.kinFitQuality_2.analyze.bResolutions           = process.bjetResolutionPF.functions
    #process.kinFitQuality_3.analyze.udscResolutions        = process.udscResolutionPF.functions
    #process.kinFitQuality_3.analyze.bResolutions           = process.bjetResolutionPF.functions

    ## run kinematic fit for CaloJets with L1L2L3L5 correted jets
    process.kinFitTtFullHadEventHypothesis.jetCorrectionLevel = 'L5Hadron'
    process.ttFullHadHypGenMatch.jetCorrectionLevel           = 'L5Hadron'

    ## replace PFJets and PFMET with CaloJets and CaloMET
    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
    massSearchReplaceAnyInputTag(process.analyseFullHadronicSelection, 'goodJetsPF', 'goodJets')
    massSearchReplaceAnyInputTag(process.analyseFullHadronicSelection, 'patMETsPF' , 'patMETs')

    # in case of mc, smear the energy resolution additionally
    if(hasattr(process, 'scaledJetEnergy')):
        process.scaledJetEnergy.inputJets = "selectedPatJets"
        process.scaledJetEnergy.inputMETs = "patMETs"
        process.scaledJetEnergy.payload   = "AK5Calo"
Пример #30
0
def replaceInputTagInAllSequences(process,
                                  oldName,
                                  newName,
                                  exceptions=[],
                                  pathExceptions=[],
                                  verbose=False):
    if verbose:
        print "Replacing %s -> %s" % (oldName, newName)
    for seqName, seq in process.sequences_().iteritems():
        if seqName not in exceptions:
            if verbose:
                print "  in sequence %s" % seqName
            helpers.massSearchReplaceAnyInputTag(seq,
                                                 cms.InputTag(oldName),
                                                 cms.InputTag(newName),
                                                 verbose=verbose)
    for pathName, path in process.paths_().iteritems():
        if pathName not in pathExceptions:
            if verbose:
                print "  in path %s" % pathName
            helpers.massSearchReplaceAnyInputTag(path,
                                                 cms.InputTag(oldName),
                                                 cms.InputTag(newName),
                                                 verbose=verbose)
Пример #31
0
def dummy_beamspot(process, tag):
    params = getattr(DummyBeamSpots, tag)

    process.myBeamSpot = cms.EDProducer('DummyBeamSpotProducer', params)

    for name, path in process.paths.items():
        if path._seq is not None:
            path.insert(0, process.myBeamSpot)

    for name, out in process.outputModules.items():
        new_cmds = []
        for cmd in out.outputCommands:
            if 'offlineBeamSpot' in cmd:
                new_cmds.append(cmd.replace('offlineBeamSpot', 'myBeamSpot'))
        out.outputCommands += new_cmds

    import itertools
    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
    for path_name, path in itertools.chain(process.paths.iteritems(),
                                           process.endpaths.iteritems()):
        massSearchReplaceAnyInputTag(path,
                                     cms.InputTag('offlineBeamSpot'),
                                     cms.InputTag('myBeamSpot'),
                                     verbose=True)
Пример #32
0
def _setTriggerProcess(process, triggerTag, **kwargs):
    # Set the input tag for the HLT

    # update InputTag for all modules in sequence
    for processAttrName in dir(process):
        processAttr = getattr(process, processAttrName)
        if isinstance(processAttr, cms.Sequence):
            #print "--> Resetting HLT input tag for sequence:", processAttrName
            patutils.massSearchReplaceAnyInputTag(
                processAttr, cms.InputTag("TriggerResults", "", "HLT"),
                triggerTag)
            patutils.massSearchReplaceAnyInputTag(
                processAttr, cms.InputTag("TriggerResults::HLT"), triggerTag)

    # update InputTag for PAT trigger tools
    if hasattr("process", "patTrigger"):
        process.patTrigger.processName = triggerTag.getProcessName()
    if hasattr("process", "patTriggerEvent"):
        process.patTriggerEvent.processName = triggerTag.getProcessName()

    # update InputTag for all histogram managers,
    # binner and event-dump plugins of GenericAnalyzer module
    for processAttrName in dir(process):
        processAttr = getattr(process, processAttrName)
        if isinstance(processAttr, cms.EDAnalyzer):
            if processAttr.type_() == "GenericAnalyzer":
                if hasattr(processAttr, "analyzers"):
                    analyzerPlugins = getattr(processAttr, "analyzers")
                    for analyzerPlugin in analyzerPlugins:
                        _setattr_ifexists(analyzerPlugin, "hltResultsSource",
                                          triggerTag)
                if hasattr(processAttr, "eventDumps"):
                    eventDumps = getattr(processAttr, "eventDumps")
                    for eventDump in eventDumps:
                        _setattr_ifexists(eventDump, "hltResultsSource",
                                          triggerTag)
# Add selectors for the different decay modes
for decayMode in [0, 1, 2, 10]:
    selectorName = "selectedHpsTancTrainTausDecayMode%i" % decayMode
    setattr(process, selectorName, cms.EDFilter(
        "PFTauViewRefSelector",
        src = cms.InputTag("hpsTancTausPassingDecayMode"),
        cut = cms.string("decayMode = %i" % decayMode),
        filter = cms.bool(False)
    ))
    process.recoTauHPSTancSequence += getattr(process, selectorName)

# Make copies of the signal and background tau production sequences
configtools.cloneProcessingSnippet(
    process, process.recoTauHPSTancSequence, "Signal")
configtools.massSearchReplaceAnyInputTag(
    process.recoTauHPSTancSequenceSignal,
    cms.InputTag("ak5PFJets"), cms.InputTag("preselectedSignalJets")
)
configtools.cloneProcessingSnippet(
    process, process.recoTauHPSTancSequence, "Background")
configtools.massSearchReplaceAnyInputTag(
    process.recoTauHPSTancSequenceBackground,
    cms.InputTag("ak5PFJets"), cms.InputTag("preselectedBackgroundJets")
)
process.buildTaus += process.recoTauHPSTancSequenceSignal
process.buildTaus += process.recoTauHPSTancSequenceBackground

################################################################################
#  Define signal path
################################################################################

process.selectSignal = cms.Path(
Пример #34
0
# use custum TMVA weights
process.flashggVBFMVA.vbfMVAweightfile = cms.FileInPath("flashgg/Taggers/data/Flashgg_VBF_CHS_STD_BDTG.weights.xml")
process.flashggVBFMVA.MVAMethod        = cms.string("BDTG")

# QCD Recovery 
# process.flashggVBFMVA.merge3rdJet   = cms.untracked.bool(False)
# process.flashggVBFMVA.thirdJetDRCut = cms.untracked.double(1.5)

# combined MVA boundary set
process.flashggVBFTag.Boundaries    = cms.vdouble(-2,0,2)


# use the trigger-diphoton-preselection
from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
massSearchReplaceAnyInputTag(process.flashggTagSequence,cms.InputTag("flashggDiPhotons"),cms.InputTag("flashggPreselectedDiPhotons"))

'''
# set the VBF dumper
process.vbfTagDumper = createTagDumper("VBFTag")
process.vbfTagDumper.dumpTrees     = True
process.vbfTagDumper.dumpHistos    = True
process.vbfTagDumper.dumpWorkspace = False

# get the variable list
import flashgg.Taggers.VBFTagVariables as var
all_variables = var.dijet_variables + var.dipho_variables + var.truth_variables

cfgTools.addCategories(process.vbfTagDumper,
                       [
                           ("VBFDiJet","leadingJet.pt>0",0),
Пример #35
0
selectStableElectrons = genParticlesForJets.clone(src = cms.InputTag("selectElectrons"))

#objectTypeSelectedTauValDenominatorModule = copy.deepcopy(iterativeCone5GenJets)
#objectTypeSelectedTauValDenominatorModule.src = cms.InputTag("selectElectronsForGenJets")

kinematicSelectedTauValDenominatorZEE = cms.EDFilter(
   "TauValGenPRefSelector", #"GenJetSelector"
   src = cms.InputTag('selectStableElectrons'),
   cut = kinematicSelectedTauValDenominatorCut,#cms.string('pt > 5. && abs(eta) < 2.5'), #Defined: Validation.RecoTau.RecoTauValidation_cfi 
   filter = cms.bool(False)
)

procAttributes = dir(proc) #Takes a snapshot of what there in the process
helpers.cloneProcessingSnippet( proc, proc.TauValNumeratorAndDenominator, 'ZEE') #clones the sequence inside the process with ZEE postfix
helpers.cloneProcessingSnippet( proc, proc.TauEfficiencies, 'ZEE') #clones the sequence inside the process with ZEE postfix
helpers.massSearchReplaceAnyInputTag(proc.TauValNumeratorAndDenominatorZEE, 'kinematicSelectedTauValDenominator', 'kinematicSelectedTauValDenominatorZEE') #sets the correct input tag

#adds to TauValNumeratorAndDenominator modules in the sequence ZEE to the extention name
zttLabeler = lambda module : SetValidationExtention(module, 'ZEE')
zttModifier = ApplyFunctionToSequence(zttLabeler)
proc.TauValNumeratorAndDenominatorZEE.visit(zttModifier)

#Sets the correct naming to efficiency histograms
proc.efficienciesZEE.streamTag = cms.InputTag("ZEE")

#checks what's new in the process (the cloned sequences and modules in them)
newProcAttributes = filter( lambda x: (x not in procAttributes) and (x.find('ZEE') != -1), dir(proc) )

#spawns a local variable with the same name as the proc attribute, needed for future process.load
for newAttr in newProcAttributes:
    locals()[newAttr] = getattr(proc,newAttr)
Пример #36
0
process.CondDBCommon.connect = "sqlite_file:flatparms_PbPb_2011.db"
process.PoolDBESSource2 = cms.ESSource(
    "PoolDBESSource",
    process.CondDBCommon,
    toGet=cms.VPSet(
        cms.PSet(record=cms.string('HeavyIonRPRcd'),
                 tag=cms.string('flatParamtest'))))

# add event plane information
process.ProdEvtPlane = cms.Path(process.centralityBin * process.hiEvtPlane *
                                process.hiEvtPlaneFlat)

process.e = cms.EndPath(process.outOnia2MuMu)

#process.patMuonSequence = cms.Sequence(
#    process.bscOrHfCoinc *
#    process.hltOniaHI *
#    process.collisionEventSelection *
#    process.patMuonsWithTriggerSequence
#    )

process.schedule = cms.Schedule(process.ProdEvtPlane, process.Onia2MuMuPAT,
                                process.e)

# RegIT: replace everywhere the names of the new muon collections
from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag

massSearchReplaceAnyInputTag(process.Onia2MuMuPAT, 'muons', 'remuons')
massSearchReplaceAnyInputTag(process.Onia2MuMuPAT, 'globalMuons',
                             'reglobalMuons')
	)

BestZee = cms.EDProducer(
    "BestMassZArbitrationProducer", # returns the Z with mass closest to 91.18 GeV
	ZCandidateCollection = cms.InputTag("ZeeCandElectronTrack")
	)

ElZLegs  = cms.EDProducer(
    "CollectionFromZLegProducer", 
    ZCandidateCollection  = cms.InputTag("BestZee"),      
	)

procAttributes = dir(proc) #Takes a snapshot of what there in the process
helpers.cloneProcessingSnippet( proc, proc.TauValNumeratorAndDenominator, 'RealElectronsData') #clones the sequence inside the process with RealElectronsData postfix
helpers.cloneProcessingSnippet( proc, proc.TauEfficiencies, 'RealElectronsData') #clones the sequence inside the process with RealElectronsData postfix
helpers.massSearchReplaceAnyInputTag(proc.TauValNumeratorAndDenominatorRealElectronsData, 'kinematicSelectedTauValDenominator', cms.InputTag("ElZLegs","theProbeLeg")) #sets the correct input tag

#adds to TauValNumeratorAndDenominator modules in the sequence RealElectronsData to the extention name
zttLabeler = lambda module : SetValidationExtention(module, 'RealElectronsData')
zttModifier = ApplyFunctionToSequence(zttLabeler)
proc.TauValNumeratorAndDenominatorRealElectronsData.visit(zttModifier)

binning = cms.PSet(
    pt = cms.PSet( nbins = cms.int32(10), min = cms.double(0.), max = cms.double(100.) ), #hinfo(75, 0., 150.)
    eta = cms.PSet( nbins = cms.int32(4), min = cms.double(-3.), max = cms.double(3.) ), #hinfo(60, -3.0, 3.0);
    phi = cms.PSet( nbins = cms.int32(4), min = cms.double(-180.), max = cms.double(180.) ), #hinfo(36, -180., 180.);
    pileup = cms.PSet( nbins = cms.int32(18), min = cms.double(0.), max = cms.double(72.) ),#hinfo(25, 0., 25.0);
    )
zttModifier = ApplyFunctionToSequence(lambda m: setBinning(m,binning))
proc.TauValNumeratorAndDenominatorRealElectronsData.visit(zttModifier)
#-----------------------------------------
import flashgg.Taggers.dumperConfigTools as cfgTools
from  flashgg.Taggers.tagsDumpers_cfi import createTagDumper

if doSystematics:
    from flashgg.Taggers.flashggTags_cff import UnpackedJetCollectionVInputTag
    from flashgg.Systematics.flashggJetSystematics_cfi import createJetSystematics
    process.RandomNumberGeneratorService = cms.Service("RandomNumberGeneratorService")
    jetSystematicsInputTags = createJetSystematics(process,UnpackedJetCollectionVInputTag)

process.load("flashgg.Taggers.flashggTagSequence_cfi")
process.load("flashgg.Taggers.flashggTagTester_cfi")

if doSystematics:
    process.flashggTagSequence.remove(process.flashggUnpackedJets)
    for i in range(len(UnpackedJetCollectionVInputTag)):
        massSearchReplaceAnyInputTag(process.flashggTagSequence,UnpackedJetCollectionVInputTag[i],jetSystematicsInputTags[i])
    process.flashggVBFTagMerger = cms.EDProducer("VBFTagMerger",src=cms.VInputTag("flashggVBFTag"))

# Use JetID
process.flashggVBFMVA.UseJetID      = cms.bool(True)
process.flashggVBFMVA.JetIDLevel    = cms.string("Loose")

# use custum TMVA weights
process.flashggVBFMVA.vbfMVAweightfile = cms.FileInPath("flashgg/Taggers/data/Flashgg_VBF_CHS_STD_BDTG.weights.xml")
process.flashggVBFMVA.MVAMethod        = cms.string("BDTG")

# QCD Recovery 
# process.flashggVBFMVA.merge3rdJet   = cms.untracked.bool(False)
# process.flashggVBFMVA.thirdJetDRCut = cms.untracked.double(1.5)

# combined MVA boundary set
switchToPFTauHPS(process)
process.cleanPatTaus.preselection = cms.string(
    "pt > 15 & abs(eta) < 2.3 & tauID('decayModeFinding') > 0.5 & tauID('byLooseIsolation') > 0.5" \
  + " & tauID('againstMuonTight') > 0.5 & tauID('againstElectronLoose') > 0.5"
)
#--------------------------------------------------------------------------------

process.p = cms.Path(
    process.offlinePrimaryVerticesDAwithBS
   + process.PFTau
   + process.patDefaultSequence
)

# use offlinePrimaryVerticesDAwithBS Vertex collection as input for PFTau reconstruction
from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag 
massSearchReplaceAnyInputTag(process.p, cms.InputTag("offlinePrimaryVerticesDA"), cms.InputTag('offlinePrimaryVerticesDAwithBS'))

process.patTupleEventContent = cms.PSet(
    outputCommands = cms.untracked.vstring(
        'drop *',
        # keep pat::Electrons, Muons and Taus
        # ( cf. PhysicsTools/PatAlgos/python/patEventContent_cff.py )
        #'keep *_cleanPatElectrons*_*_*',
        'keep *_cleanPatMuons*_*_*',
        'keep *_cleanPatTaus*_*_*',
        # keep generator level information 
        'keep *_genParticles*_*_*',
        # keep all PFCandidates
        # ( cf. RecoParticleFlow/Configuration/python/RecoParticleFlow_EventContent_cff.py )
        'keep recoPFCandidates_particleFlow_*_*',
        # keep reco::PFJets reconstructed by anti-kT algorithm with dR = 0.5
                      process.semiLeptonicSelection                 *
                      ## muon selection
                      process.muonSelection                         *
                      ## veto on additional leptons
                      process.secondMuonVeto                        *
                      process.electronVeto                          *
                      ## jet selection
                      process.leadingJetSelectionNjets              *
		      ## b tag Eff determination on MC
	              process.bTagEff
  )


## remove CaloJetCollections as not available anymore in Spring11
from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
massSearchReplaceAnyInputTag(process.p1, 'goodJets'        , 'goodJetsPF30'      )
process.p1.remove(process.centralJets)
process.p1.remove(process.reliableJets)
process.p1.remove(process.goodJets)
process.p1.remove(process.tightLeadingJets)
process.p1.remove(process.tightBottomJets)

# switch to PF2PAT
if(pfToPAT):
    from TopAnalysis.TopUtils.usePatTupleWithParticleFlow_cff import prependPF2PATSequence
    allpaths  = process.paths_().keys()
    recoPaths=['p1']
    # define general options
    PFoptions = {
        'runOnMC': True,
        'runOnAOD': True,
Пример #41
0
# Add selectors for the different decay modes
for decayMode in [0, 1, 2, 10]:
    selectorName = "selectedHpsTancTrainTausDecayMode%i" % decayMode
    setattr(
        process, selectorName,
        cms.EDFilter("PFTauViewRefSelector",
                     src=cms.InputTag("hpsTancTausPassingDecayMode"),
                     cut=cms.string("decayMode = %i" % decayMode),
                     filter=cms.bool(False)))
    process.recoTauHPSTancSequence += getattr(process, selectorName)

# Make copies of the signal and background tau production sequences
configtools.cloneProcessingSnippet(process, process.recoTauHPSTancSequence,
                                   "Signal")
configtools.massSearchReplaceAnyInputTag(process.recoTauHPSTancSequenceSignal,
                                         cms.InputTag("ak5PFJets"),
                                         cms.InputTag("preselectedSignalJets"))
configtools.cloneProcessingSnippet(process, process.recoTauHPSTancSequence,
                                   "Background")
configtools.massSearchReplaceAnyInputTag(
    process.recoTauHPSTancSequenceBackground, cms.InputTag("ak5PFJets"),
    cms.InputTag("preselectedBackgroundJets"))
process.buildTaus += process.recoTauHPSTancSequenceSignal
process.buildTaus += process.recoTauHPSTancSequenceBackground

################################################################################
#  Define signal path
################################################################################

process.selectSignal = cms.Path(
    process.tauGenJets * process.trueCommonHadronicTaus *
Пример #42
0
#process.MessageLogger.cerr.FwkReport.reportEvery = cms.untracked.int32( 100 )

# Uncomment the following if you notice you have a memory leak
# This is a lightweight tool to digg further
#process.SimpleMemoryCheck = cms.Service("SimpleMemoryCheck",
#                                        ignoreTotal = cms.untracked.int32(1),
#                                        monitorPssAndPrivate = cms.untracked.bool(True)
#                                       )

#process.source = cms.Source ("PoolSource",fileNames = cms.untracked.vstring("file:myMicroAODOutputFile.root"))
process.source = cms.Source("PoolSource",fileNames = cms.untracked.vstring("/store/group/phys_higgs/cmshgg/mdonega/flashgg/RunIISpring15-50ns/Spring15BetaV2/ttHJetToGG_M125_13TeV_amcatnloFXFX_madspin_pythia8/RunIISpring15-50ns-Spring15BetaV2-v0-RunIISpring15DR74-Asympt50ns_MCRUN2_74_V9A-v1/150716_155334/0000/myMicroAODOutputFile_3.root"))

process.load("flashgg/Taggers/flashggTagSequence_cfi")
process.load("flashgg/Taggers/flashggTagTester_cfi")

from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
massSearchReplaceAnyInputTag(process.flashggTagSequence,cms.InputTag("selectedFlashggJets"),cms.InputTag("flashggJets"))
massSearchReplaceAnyInputTag(process.flashggTagSequence,cms.InputTag("selectedFlashggMuons"),cms.InputTag("flashggMuons"))
massSearchReplaceAnyInputTag(process.flashggTagSequence,cms.InputTag("selectedFlashggElectrons"),cms.InputTag("flashggElectrons"))


from flashgg.Taggers.flashggTagOutputCommands_cff import tagDefaultOutputCommand

process.out = cms.OutputModule("PoolOutputModule", fileName = cms.untracked.string('myTagOutputFile.root'),
                               outputCommands = tagDefaultOutputCommand			       
                               )

process.p = cms.Path(process.flashggTagSequence*process.flashggTagTester)

process.e = cms.EndPath(process.out)
Пример #43
0
def addPF2PAT(process, dataVersion, postfix="PFlow",
              doTauHLTMatching=True, matchingTauTrigger=None, 
              ):
#    if hasattr(process, "patDefaultSequence"):
#        raise Exception("PAT should not exist before calling addPF2PAT at the moment")

    # Hack to not to crash if something in PAT assumes process.out
    hasOut = hasattr(process, "out")
    outputCommands = []
    outputCommandsBackup = []
    if hasOut:
        outputCommandsBackup = process.out.outputCommands[:]
    else:
        process.out = cms.OutputModule("PoolOutputModule",
            fileName = cms.untracked.string('dummy.root'),
            outputCommands = cms.untracked.vstring()
        )

    outputCommands = []

    # Jet modifications
    # PhysicsTools/PatExamples/test/patTuple_42x_jec_cfg.py
    jetCorrFactors = patJetCorrLevels(dataVersion, True)
    jetCorrPayload = "AK5PFchs"

    process.load("PhysicsTools.PatAlgos.patSequences_cff")
    pfTools.usePF2PAT(process, runPF2PAT=True, jetAlgo="AK5", jetCorrections=(jetCorrPayload, jetCorrFactors),
                      runOnMC=dataVersion.isMC(), postfix=postfix)

    outputCommands = [
#        "keep *_selectedPatPhotons%s_*_*" % postfix,
#        'keep *_selectedPatElectrons%s_*_*' % postfix, 
        'keep *_selectedPatMuons%s_*_*' % postfix,
        'keep *_selectedPatJets%s*_*_*' % postfix,
        'keep *_selectedPatTaus%s_*_*' % postfix,
        'keep *_selectedPatPFParticles%s_*_*' % postfix,
        'keep *_selectedPatJets%s_pfCandidates_*' % postfix,
        'drop *_*PF_caloTowers_*',
        'drop *_*JPT_pfCandidates_*',
        'drop *_*Calo_pfCandidates_*',
        'keep *_patMETs%s_*_*' % postfix,
        ]

    # Enable PFnoPU
    getattr(process, "pfPileUp"+postfix).Enable = True
    getattr(process, "pfPileUp"+postfix).checkClosestZVertex = False
    getattr(process, "pfPileUp"+postfix).Vertices = "offlinePrimaryVertices"

    # Jet modifications
    # L1FastJet
    # https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookJetEnergyCorrections#OffsetJEC
    # https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookJetEnergyCorrections#JetEnCor2011
    # https://hypernews.cern.ch/HyperNews/CMS/get/jes/184.html
    kt6name = "kt6PFJets"+postfix
    process.load('RecoJets.Configuration.RecoPFJets_cff')
    from RecoJets.JetProducers.kt4PFJets_cfi import kt4PFJets
    setattr(process, kt6name, kt4PFJets.clone(
        rParam = 0.6,
        src = 'pfNoElectron'+postfix,
        doRhoFastjet = True,
        doAreaFastJet = cms.bool(True),
    ))
    getattr(process, "patPF2PATSequence"+postfix).replace(
        getattr(process, "pfNoElectron"+postfix),
        getattr(process, "pfNoElectron"+postfix) * getattr(process, kt6name))
    getattr(process, "patJetCorrFactors"+postfix).rho = cms.InputTag(kt6name, "rho")
    getattr(process, "patJetCorrFactors"+postfix).useRho = True

    # ak5PFJets
    getattr(process, "pfJets"+postfix).doAreaFastjet = cms.bool(True)
    getattr(process, "pfJets"+postfix).doRhoFastjet = False
#    getattr(process, "pfJets"+postfix).Vertices = cms.InputTag("goodPrimaryVertices")

    setPatJetDefaults(getattr(process, "patJets"+postfix))


    # Use HPS taus
    # Add and recalculate the discriminators
    addHChTauDiscriminators()
    if not hasattr(process, "hpsPFTauDiscriminationForChargedHiggsByLeadingTrackPtCut"):
        import RecoTauTag.RecoTau.PFRecoTauDiscriminationForChargedHiggs_cfi as HChPFTauDiscriminators
        import RecoTauTag.RecoTau.CaloRecoTauDiscriminationForChargedHiggs_cfi as HChCaloTauDiscriminators

        tauAlgos = ["hpsPFTau"]
#        tauAlgos = ["pfTaus"+postfix]
        HChPFTauDiscriminators.addPFTauDiscriminationSequenceForChargedHiggs(process, tauAlgos)
        HChPFTauDiscriminatorsCont.addPFTauDiscriminationSequenceForChargedHiggsCont(process, tauAlgos)
        PFTauTestDiscrimination.addPFTauTestDiscriminationSequence(process, tauAlgos)

        fixFlightPath(process, tauAlgos[0])
        fixFlightPath(process, tauAlgos[0], "Cont")
    
    patHelpers.cloneProcessingSnippet(process, process.hpsPFTauHplusDiscriminationSequence, postfix)
    patHelpers.cloneProcessingSnippet(process, process.hpsPFTauHplusDiscriminationSequenceCont, postfix)
    patHelpers.cloneProcessingSnippet(process, process.hpsPFTauHplusTestDiscriminationSequence, postfix)

    patTauSeq = cms.Sequence(
        getattr(process, "hpsPFTauHplusDiscriminationSequence"+postfix) *
        getattr(process, "hpsPFTauHplusDiscriminationSequenceCont"+postfix) * 
        getattr(process, "hpsPFTauHplusTestDiscriminationSequence"+postfix)
#        getattr(process, "pfTaus"+postfix+"HplusDiscriminationSequence") *
#        getattr(process, "pfTaus"+postfix+"HplusDiscriminationSequenceCont") * 
#        getattr(process, "pfTaus"+postfix+"HplusTestDiscriminationSequence")
    )
    setattr(process, "hplusPatTauSequence"+postfix, patTauSeq)
    patHelpers.massSearchReplaceParam(patTauSeq, "PFTauProducer", cms.InputTag("hpsPFTauProducer"), cms.InputTag("pfTaus"+postfix))
    patHelpers.massSearchReplaceAnyInputTag(patTauSeq, cms.InputTag("hpsPFTauDiscriminationByDecayModeFinding"), cms.InputTag("hpsPFTauDiscriminationByDecayModeFinding"+postfix))

    pfTools.adaptPFTaus(process, "hpsPFTau", postfix=postfix)

    setPatTauDefaults(getattr(process, "patTaus"+postfix), False)
    addPatTauIsolationEmbedding(process, getattr(process, "patDefaultSequence"+postfix), postfix)
    getattr(process, "selectedPatTaus"+postfix).cut = tauPreSelection

    # The prediscriminant of pfTausBaseDiscriminationByLooseIsolation
    # is missing from the default sequence, but since we don't want to
    # apply any tau selections as a part of PF2PAT anyway, let's just
    # remove this too
    getattr(process, "pfTaus"+postfix).discriminators = cms.VPSet()
#    getattr(process, "pfTauSequence"+postfix).remove(getattr(process, "pfTaus"+postfix))
#    delattr(process, "pfTaus"+postfix)
#    getattr(process, "pfTausBaseSequence"+postfix).remove(getattr(process, "pfTausBaseDiscriminationByLooseIsolation"+postfix))
    

    # Remove the shrinking cone altogether, we don't care about it
#    getattr(process, "patDefaultSequence"+postfix).remove(getattr(process, "patShrinkingConePFTauDiscrimination"+postfix))

    # Override the tau source (this is WRONG in the standard PF2PAT, the expers should know it already)
#    getattr(process, "patTaus"+postfix).tauSource = "hpsPFTauProducer"+postfix
#    patHelpers.massSearchReplaceAnyInputTag(getattr(process, "patHPSPFTauDiscrimination"+postfix),
#                                            cms.InputTag("pfTaus"+postfix),
#                                            cms.InputTag("hpsPFTauProducer"+postfix))
#    getattr(process, "pfNoTau"+postfix).topCollection = cms.InputTag("hpsPFTauProducer"+postfix)

    # Disable iso deposits, they take a LOT of space
    getattr(process, "patTaus"+postfix).isoDeposits = cms.PSet()

    # Disable tau top projection, the taus are identified and removed
    # from jets as a part of the analysis
    getattr(process, "pfNoTau"+postfix).enable = False



    # Lepton modifications
    setPatLeptonDefaults(getattr(process, "patMuons"+postfix), False)
    #setPatLeptonDefaults(getattr(process, "patElectrons"+postfix), False)
    #addPatElectronID(process, getattr(process, "patElectrons"+postfix), getattr(process, "makePatElectrons"+postfix))

    # PATElectronProducer segfaults, and we don't really need them now
    getattr(process, "patDefaultSequence"+postfix).remove(getattr(process, "makePatElectrons"+postfix))
    getattr(process, "patDefaultSequence"+postfix).remove(getattr(process, "selectedPatElectrons"+postfix))
    getattr(process, "patDefaultSequence"+postfix).remove(getattr(process, "countPatElectrons"+postfix))
    getattr(process, "patDefaultSequence"+postfix).remove(getattr(process, "countPatLeptons"+postfix))

    # Disable muon and electron top projections, needs wider
    # discussion about lepton definitions
    getattr(process, "pfNoMuon"+postfix).enable = False
    getattr(process, "pfNoElectron"+postfix).enable = False

    # Remove photon MC matcher in order to avoid keeping photons in the event content
    #process.patDefaultSequencePFlow.remove(process.photonMatchPFlow)

    if hasOut:
        process.out.outputCommands = outputCommandsBackup
        process.out.outputCommands.extend(outputCommands)
    else:
        del process.out

    getattr(process, "patDefaultSequence"+postfix).replace(
        getattr(process, "patTaus"+postfix),
        patTauSeq *
        getattr(process, "patTaus"+postfix)
    )

    sequence = cms.Sequence(
        getattr(process, "patPF2PATSequence"+postfix)
    )

    if doTauHLTMatching:
        sequence *= HChTriggerMatching.addTauHLTMatching(process, matchingTauTrigger, collections=["selectedPatTaus"+postfix], postfix=postfix)

    return sequence
Пример #44
0
def addBoostedTaus(process):
    from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet
    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag

    process.load("RecoTauTag.Configuration.boostedHPSPFTaus_cff")
    patAlgosToolsTask = configtools.getPatAlgosToolsTask(process)
    patAlgosToolsTask.add(process.boostedHPSPFTausTask)

    process.load("RecoTauTag.Configuration.RecoPFTauTag_cff")
    # BDT-based tauIDs removed from standard tau sequence, but still used by boosed taus
    process.PFTauMVAIdSequence = cms.Sequence(
        process.hpsPFTauDiscriminationByMVA6rawElectronRejection+
        process.hpsPFTauDiscriminationByMVA6ElectronRejection+
        process.hpsPFTauDiscriminationByIsolationMVArun2v1DBoldDMwLTraw+
        process.hpsPFTauDiscriminationByIsolationMVArun2v1DBoldDMwLT+
        process.hpsPFTauDiscriminationByIsolationMVArun2v1DBnewDMwLTraw+
        process.hpsPFTauDiscriminationByIsolationMVArun2v1DBnewDMwLT
    )
    process.PATTauSequence = cms.Sequence(
        process.PFTau+process.PFTauMVAIdSequence+
        process.makePatTaus+process.selectedPatTaus)
    process.PATTauSequenceBoosted = cloneProcessingSnippet(process,process.PATTauSequence, "Boosted", addToTask = True)
    process.recoTauAK4PFJets08RegionBoosted.src = 'boostedTauSeeds'
    process.recoTauAK4PFJets08RegionBoosted.pfCandSrc = 'particleFlow'
    process.recoTauAK4PFJets08RegionBoosted.pfCandAssocMapSrc = ('boostedTauSeeds', 'pfCandAssocMapForIsolation')
    process.ak4PFJetsLegacyHPSPiZerosBoosted.jetSrc = 'boostedTauSeeds'
    process.ak4PFJetsRecoTauChargedHadronsBoosted.jetSrc = 'boostedTauSeeds'
    process.ak4PFJetsRecoTauChargedHadronsBoosted.builders[1].dRcone = 0.3
    process.ak4PFJetsRecoTauChargedHadronsBoosted.builders[1].dRconeLimitedToJetArea = True
    process.combinatoricRecoTausBoosted.jetSrc = 'boostedTauSeeds'
    process.combinatoricRecoTausBoosted.builders[0].pfCandSrc = cms.InputTag('particleFlow')
    ## Note JetArea is not defined for subjets (-> do not switch to True in hpsPFTauDiscriminationByLooseMuonRejection3Boosted, False is default)
    ## The restiction to jetArea is turned to dRMatch=0.1 (-> use explicitly this modified value)
    process.hpsPFTauDiscriminationByMuonRejection3Boosted.dRmuonMatch = 0.1
    massSearchReplaceAnyInputTag(process.PATTauSequenceBoosted,cms.InputTag("ak4PFJets"),cms.InputTag("boostedTauSeeds"))  
    #Add BDT-based tauIDs still used by boosed taus
    from PhysicsTools.PatAlgos.producersLayer1.tauProducer_cfi import containerID
    containerID(process.patTausBoosted.tauIDSources, "hpsPFTauDiscriminationByIsolationMVArun2v1DBoldDMwLTBoosted", "rawValues", [
        ["byIsolationMVArun2DBoldDMwLTraw", "discriminator"]
    ])
    containerID(process.patTausBoosted.tauIDSources, "hpsPFTauDiscriminationByIsolationMVArun2v1DBoldDMwLTBoosted", "workingPoints", [
        ["byVVLooseIsolationMVArun2DBoldDMwLT", "_VVLoose"],
        ["byVLooseIsolationMVArun2DBoldDMwLT", "_VLoose"],
        ["byLooseIsolationMVArun2DBoldDMwLT", "_Loose"],
        ["byMediumIsolationMVArun2DBoldDMwLT", "_Medium"],
        ["byTightIsolationMVArun2DBoldDMwLT", "_Tight"],
        ["byVTightIsolationMVArun2DBoldDMwLT", "_VTight"],
        ["byVVTightIsolationMVArun2DBoldDMwLT", "_VVTight"]
    ])
    containerID(process.patTausBoosted.tauIDSources, "hpsPFTauDiscriminationByIsolationMVArun2v1DBnewDMwLTBoosted", "rawValues", [
        ["byIsolationMVArun2DBnewDMwLTraw", "discriminator"]
    ])
    containerID(process.patTausBoosted.tauIDSources, "hpsPFTauDiscriminationByIsolationMVArun2v1DBnewDMwLTBoosted", "workingPoints", [
        ["byVVLooseIsolationMVArun2DBnewDMwLT", "_VVLoose"],
        ["byVLooseIsolationMVArun2DBnewDMwLT", "_VLoose"],
        ["byLooseIsolationMVArun2DBnewDMwLT", "_Loose"],
        ["byMediumIsolationMVArun2DBnewDMwLT", "_Medium"],
        ["byTightIsolationMVArun2DBnewDMwLT", "_Tight"],
        ["byVTightIsolationMVArun2DBnewDMwLT", "_VTight"],
        ["byVVTightIsolationMVArun2DBnewDMwLT", "_VVTight"]
    ])
    containerID(process.patTausBoosted.tauIDSources, "hpsPFTauDiscriminationByMVA6ElectronRejectionBoosted", "rawValues", [
        ["againstElectronMVA6Raw", "discriminator"],
        ["againstElectronMVA6category", "category"]
    ])
    containerID(process.patTausBoosted.tauIDSources, "hpsPFTauDiscriminationByMVA6ElectronRejectionBoosted", "workingPoints", [
        ["againstElectronVLooseMVA6", "_VLoose"],
        ["againstElectronLooseMVA6", "_Loose"],
        ["againstElectronMediumMVA6", "_Medium"],
        ["againstElectronTightMVA6", "_Tight"],
        ["againstElectronVTightMVA6", "_VTight"]
    ])
    process.slimmedTausBoosted = process.slimmedTaus.clone(src = "selectedPatTausBoosted")
    patAlgosToolsTask.add(process.slimmedTausBoosted)

    return process
Пример #45
0
####################################################
######## CLEANED JET COLLECTION FOR MU-TAUH ########
####################################################
process.load('CMGTools.Common.PAT.addFilterPaths_cff')
print "Cleaning the jet collection for mu-tauh channel"
from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag

process.load("ExoDiBosonResonances.PATtupleProduction.CleanJets_cff")
process.PATCMGSequence += process.primaryVertexFilter
process.PATCMGSequence += process.CleanJetsMuTauSequence
process.PATTauSequenceMuTau = cloneProcessingSnippet(process,
                                                     process.PATTauSequence,
                                                     "MuTau")
massSearchReplaceAnyInputTag(process.PATTauSequenceMuTau,
                             cms.InputTag("pfJetsForHPSTauMuTau"),
                             cms.InputTag("ak5PFJetsNoMu"))
process.PATTauSequenceMuTau.replace(
    process.pfJetsForHPSTauMuTau,
    process.primaryVertexFilter + process.CleanJetsMuTauSequence)
process.PATCMGSequence += process.PATTauSequenceMuTau
patEventContentCMG += ['keep *_*selectedPatTausMuTau*_*_*']

#####################################################
######### CLEANED JET COLLECTION FOR EL-TAUH ########
#####################################################
print "Cleaning the jet collection for ele-tauh channel"
process.PATCMGSequence += process.CleanJetsETauSequence
process.PATTauSequenceEleTau = cloneProcessingSnippet(process,
                                                      process.PATTauSequence,
                                                      "EleTau")
Пример #46
0
        process.schedule.append(process.rerunMCMatchPath)
        fs_daughter_inputs['electrons'] = 'cleanPatElectronsRematched'
        fs_daughter_inputs['muons'] = 'cleanPatMuonsRematched'
        fs_daughter_inputs['taus'] = 'cleanPatTausRematched'
        fs_daughter_inputs['photons'] = 'photonParentage'
        fs_daughter_inputs['jets'] = 'selectedPatJetsRematched'

    if options.rerunQGJetID:
        process.schedule.append(
            rerun_QGJetID(process, fs_daughter_inputs)
            )
        
    if options.runNewElectronMVAID:
        process.load("FinalStateAnalysis.PatTools.electrons.patElectronSummer13MVAID_cfi")
        helpers.massSearchReplaceAnyInputTag(
            process.runAndEmbedSummer13Id,
            'fixme',
            fs_daughter_inputs['electrons'])
        fs_daughter_inputs['electrons'] = 'patElectrons2013MVAID'
        process.runNewElectronMVAID = cms.Path(process.runAndEmbedSummer13Id)
        process.schedule.append(process.runNewElectronMVAID) 
        
        
    # Eventually, set buildFSAEvent to False, currently working around bug
    # in pat tuples.
    produce_final_states(process, fs_daughter_inputs, [], process.buildFSASeq,
                         'puTagDoesntMatter', buildFSAEvent=True,
                         noTracks=True, noPhotons=options.noPhotons)
    process.buildFSAPath = cms.Path(process.buildFSASeq)
    # Don't crash if some products are missing (like tracks)
    process.patFinalStateEventProducer.forbidMissing = cms.bool(False)
    process.schedule.append(process.buildFSAPath)
    process.fjSequence*
    process.patDefaultSequence*
    process.kt6PFJetsNeutral*
    process.selectedPatMuonsTriggerMatchUserEmbedded*
    process.selectedPatElectronsTriggerMatchUserEmbedded*
    process.selectedPatTausTriggerMatchUserEmbedded*
    process.muSequence+
    process.elecSequence+
    process.tauSequence+
    process.tauNTuplizer+
    process.printTree1
    )


massSearchReplaceAnyInputTag(process.run,
                             "offlinePrimaryVertices",
                             "selectedPrimaryVertices",
                             verbose=False)
process.selectedPrimaryVertices.src = cms.InputTag('offlinePrimaryVertices')


if not runOnMC:
    process.run.remove(process.printTree1)

process.p = cms.Path(process.run)


########################## output ###############################

from PhysicsTools.PatAlgos.patEventContent_cff import patEventContentNoCleaning
process.out.outputCommands = cms.untracked.vstring('drop *',
                                                   *patEventContentNoCleaning ) 
    ZCandidateCollection=cms.InputTag("ZmmCandMuonTrack"))

MuZLegs = cms.EDProducer(
    "CollectionFromZLegProducer",
    ZCandidateCollection=cms.InputTag("BestZmm"),
)

procAttributes = dir(proc)  #Takes a snapshot of what there in the process
helpers.cloneProcessingSnippet(
    proc, proc.TauValNumeratorAndDenominator, 'RealMuonsData'
)  #clones the sequence inside the process with RealMuonsData postfix
helpers.cloneProcessingSnippet(
    proc, proc.TauEfficiencies, 'RealMuonsData'
)  #clones the sequence inside the process with RealMuonsData postfix
helpers.massSearchReplaceAnyInputTag(
    proc.TauValNumeratorAndDenominatorRealMuonsData,
    'kinematicSelectedTauValDenominator',
    cms.InputTag("MuZLegs", "theProbeLeg"))  #sets the correct input tag

#adds to TauValNumeratorAndDenominator modules in the sequence RealMuonsData to the extention name
zttLabeler = lambda module: SetValidationExtention(module, 'RealMuonsData')
zttModifier = ApplyFunctionToSequence(zttLabeler)
proc.TauValNumeratorAndDenominatorRealMuonsData.visit(zttModifier)

binning = cms.PSet(
    pt=cms.PSet(nbins=cms.int32(10), min=cms.double(0.),
                max=cms.double(100.)),  #hinfo(75, 0., 150.)
    eta=cms.PSet(nbins=cms.int32(4), min=cms.double(-3.),
                 max=cms.double(3.)),  #hinfo(60, -3.0, 3.0);
    phi=cms.PSet(nbins=cms.int32(4),
                 min=cms.double(-180.),
                 max=cms.double(180.)),  #hinfo(36, -180., 180.);
Пример #49
0
    "TauValPFJetSelector",
    src = cms.InputTag('kinematicSelectedPFJets'),
    cut = cms.string("chargedHadronEnergyFraction > 0.0 & neutralHadronEnergyFraction < 0.99 & neutralHadronEnergyFraction < 0.99 & chargedEmEnergyFraction < 0.99 & chargedEmEnergyFraction < 0.99 & neutralEmEnergyFraction < 0.99 & chargedMultiplicity > 0 & nConstituents > 1"),
    filter = cms.bool(False)
	)

CleanedPFJets = cms.EDProducer("TauValJetViewCleaner",
    srcObject            = cms.InputTag( "kinematicSelectedPFJets" ),
    srcObjectsToRemove   = cms.VInputTag( cms.InputTag("muons"), cms.InputTag("gedGsfElectrons") ),
    deltaRMin            = cms.double(0.15)
)

procAttributes = dir(proc) #Takes a snapshot of what there in the process
helpers.cloneProcessingSnippet( proc, proc.TauValNumeratorAndDenominator, 'RealData') #clones the sequence inside the process with RealData postfix
helpers.cloneProcessingSnippet( proc, proc.TauEfficiencies, 'RealData') #clones the sequence inside the process with RealData postfix
helpers.massSearchReplaceAnyInputTag(proc.TauValNumeratorAndDenominatorRealData, 'kinematicSelectedTauValDenominator', 'CleanedPFJets') #sets the correct input tag

#adds to TauValNumeratorAndDenominator modules in the sequence RealData to the extention name
zttLabeler = lambda module : SetValidationExtention(module, 'RealData')
zttModifier = ApplyFunctionToSequence(zttLabeler)
proc.TauValNumeratorAndDenominatorRealData.visit(zttModifier)

binning = cms.PSet(
	pt = cms.PSet( nbins = cms.int32(25), min = cms.double(0.), max = cms.double(250.) ), #hinfo(75, 0., 150.)
	eta = cms.PSet( nbins = cms.int32(4), min = cms.double(-3.), max = cms.double(3.) ), #hinfo(60, -3.0, 3.0);
	phi = cms.PSet( nbins = cms.int32(4), min = cms.double(-180.), max = cms.double(180.) ), #hinfo(36, -180., 180.);
	pileup = cms.PSet( nbins = cms.int32(18), min = cms.double(0.), max = cms.double(72.) ),#hinfo(25, 0., 25.0);
	)
zttModifier = ApplyFunctionToSequence(lambda m: setBinning(m,binning))
proc.TauValNumeratorAndDenominatorRealData.visit(zttModifier)
#-----------------------------------------
Пример #50
0
def switchToData(process):

    # remove MC matching from standard PAT sequences
    if hasattr(process, "patDefaultSequence"):
        removeMCMatching(process, ["All"], outputModules=[])
        process.patDefaultSequence.remove(process.patJetPartonMatch)

    #------------------------------------------------------------------------
    # CV: temporary work-around for W --> tau nu channel
    modulesToRemove = [
        "patJetPartonMatchAK5PF", "patJetGenJetMatchAK5PF", "patJetPartons",
        "patJetPartonAssociation", "patJetPartonAssociationAK5PF",
        "patJetFlavourAssociation", "patJetFlavourAssociationAK5PF"
    ]
    for moduleToRemove in modulesToRemove:
        if hasattr(process, moduleToRemove):
            process.patDefaultSequence.remove(getattr(process, moduleToRemove))
    if hasattr(process, "patJetCorrFactorsAK5PF"):
        process.patJetCorrFactorsAK5PF.levels.append("L2L3Residual")
    #------------------------------------------------------------------------

    # add data-quality cuts which work on "real" data only
    if hasattr(process, "dataQualityFilters"):
        process.dataQualityFilters._seq = process.dataQualityFilters._seq * process.hltPhysicsDeclared
        process.dataQualityFilters._seq = process.dataQualityFilters._seq * process.dcsstatus

    # apply L2/L3 residual jet energy corrections
    # (for improved Data and Monte-Carlo agreement)
    if hasattr(process, "pfMEtType1and2corrected"):
        setattr(process.pfMEtType1and2corrected, "corrector",
                cms.string('ak5PFL2L3Residual'))

    if hasattr(process, "patPFMETs"):
        process.patPFMETs.addGenMET = cms.bool(False)
    if hasattr(process, "patPFtype1METs"):
        process.patPFtype1METs.addGenMET = cms.bool(False)

    # remove modules from pre-PAT production running on genParticles
    if hasattr(process, "producePrePat"):
        process.producePrePat.remove(process.genParticlesForJets)
        process.producePrePat.remove(process.ak5GenJets)

    # remove modules from PAT-tuple production sequence running on genParticles
    if hasattr(process, "producePatTuple"):
        if hasattr(process, "genParticlesForJets"):
            process.producePatTuple.remove(process.genParticlesForJets)
        if hasattr(process, "ak5GenJets"):
            process.producePatTuple.remove(process.ak5GenJets)

    # remove modules from post-PAT production running on genParticles
    if hasattr(process, "producePostPat"):
        process.producePostPat.remove(process.produceGenObjects)

    # iterate over all sequences attached to process object and
    # recursively disable gen. matching for all modules in sequence
    for processAttrName in dir(process):
        processAttr = getattr(process, processAttrName)
        if isinstance(processAttr, cms.Sequence):
            print "--> Disabling gen. Matching for sequence:", processAttrName
            # replace all InputTags referring to
            #  o genParticleSource = cms.InputTag('genParticles') --> ""
            #  o genJetSource = cms.InputTag('iterativeCone5GenJets') --> ""
            #  o genJetSource = cms.InputTag('ak5GenJets') --> ""
            #  o genTauJetSource = cms.InputTag('tauGenJets') --> ""
            #  o genMEtSource = cms.InputTag('genMetTrue') --> ""
            patutils.massSearchReplaceAnyInputTag(processAttr,
                                                  cms.InputTag('genParticles'),
                                                  cms.InputTag(''))
            patutils.massSearchReplaceAnyInputTag(
                processAttr, cms.InputTag('iterativeCone5GenJets'),
                cms.InputTag(''))
            patutils.massSearchReplaceAnyInputTag(processAttr,
                                                  cms.InputTag('ak5GenJets'),
                                                  cms.InputTag(''))
            patutils.massSearchReplaceAnyInputTag(processAttr,
                                                  cms.InputTag('tauGenJets'),
                                                  cms.InputTag(''))
            patutils.massSearchReplaceAnyInputTag(processAttr,
                                                  cms.InputTag('genMetTrue'),
                                                  cms.InputTag(''))

            # replace all InputTags referring to gen. Z decay products
            # in electron + tau-jet Zee (muon + tau-jet Zmumu) hypotheses
            patutils.massSearchReplaceAnyInputTag(
                processAttr, cms.InputTag('genElectronsFromZs'),
                cms.InputTag(''))
            patutils.massSearchReplaceAnyInputTag(
                processAttr, cms.InputTag('genMuonsFromZs'), cms.InputTag(''))

    # disable generator level matching for all PATJetProducer modules
    for processAttrName in dir(process):
        processAttr = getattr(process, processAttrName)
        if isinstance(
                processAttr,
                cms.EDProducer) and processAttr.type_() == "PATJetProducer":
            print "--> Disabling gen. Matching for module:", processAttrName
            setattr(processAttr, "addGenJetMatch", cms.bool(False))
            setattr(processAttr, "addGenPartonMatch", cms.bool(False))
            setattr(processAttr, "addPartonJetMatch", cms.bool(False))

    # disable access to generator level information in all
    # histogram managers, binner and event-dump plugins of GenericAnalyzer module
    for processAttrName in dir(process):
        processAttr = getattr(process, processAttrName)
        if isinstance(
                processAttr,
                cms.EDAnalyzer) and processAttr.type_() == "GenericAnalyzer":
            # disable matching between gen. and rec. particles
            # in all histogram managers and binner plugins by setting
            #  o genParticleSource = cms.InputTag('genParticles') --> ""
            #  o genJetSource = cms.InputTag('iterativeCone5GenJets') --> ""
            #  o genJetSource = cms.InputTag('ak5GenJets') --> ""
            #  o genTauJetSource = cms.InputTag('tauGenJets') --> ""
            #  o genMEtSource = cms.InputTag('genMetTrue') --> ""
            if hasattr(processAttr, "analyzers"):
                analyzerPlugins = getattr(processAttr, "analyzers")
                for analyzerPlugin in analyzerPlugins:
                    _setattr_ifexists(analyzerPlugin, "genParticleSource",
                                      cms.InputTag(''))
                    _setattr_ifexists(analyzerPlugin, "genJetSource",
                                      cms.InputTag(''))
                    _setattr_ifexists(analyzerPlugin, "genTauJetSource",
                                      cms.InputTag(''))
                    _setattr_ifexists(analyzerPlugin, "genMEtSource",
                                      cms.InputTag(''))

            # remove from all analysis sequences the following objects:
            #  o genPhaseSpaceInfoHistManager
            #  o modelBinnerForMuTauGenTauLeptonPairAcc
            #  o modelBinnerForMuTauWrtGenTauLeptonPairAcc
            #  o modelBinnerForMuTauGenTauLeptonPairAcc3mZbins
            #  o modelBinnerForMuTauWrtGenTauLeptonPairAcc3mZbins
            #  o modelBinnerForMuTauCentralJetVetoWrtGenTauLeptonPairAcc
            #  o modelBinnerForMuTauCentralJetBtagWrtGenTauLeptonPairAcc
            #  o sysUncertaintyBinnerForMuTau
            #  o diTauCandidateCollinearApproxHistManagerBinnedForMuTau
            analyzerPluginsToRemove = [
                "genPhaseSpaceEventInfoHistManager", "genTauHistManager",
                "cutFlowHistManagerGenMultiplicity",
                "modelBinnerForMuTauGenTauLeptonPairAcc",
                "modelBinnerForMuTauWrtGenTauLeptonPairAcc",
                "modelBinnerForMuTauGenTauLeptonPairAcc3mZbins",
                "modelBinnerForMuTauWrtGenTauLeptonPairAcc3mZbins",
                "modelBinnerForMuTauCentralJetVetoWrtGenTauLeptonPairAcc",
                "modelBinnerForMuTauCentralJetBtagWrtGenTauLeptonPairAcc",
                "sysUncertaintyBinnerForMuTau",
                "diTauCandidateCollinearApproxHistManagerBinnedForMuTau"
            ]
            for analyzerPluginName in analyzerPluginsToRemove:
                if hasattr(process, analyzerPluginName):
                    analyzerPlugin = getattr(process, analyzerPluginName)
                    if processAttr.analyzers.count(analyzerPlugin) > 0:
                        processAttr.analyzers.remove(analyzerPlugin)
                    removeAnalyzer(processAttr.analysisSequence,
                                   analyzerPluginName)

            # disable matching between gen. and rec. particles in all event-dump plugins by setting
            #  o doGenInfo = cms.bool(True) --> cms.bool(False)
            #  o genParticleSource = cms.InputTag('genParticles') --> ""
            if hasattr(processAttr, "eventDumps"):
                eventDumpPlugins = getattr(processAttr, "eventDumps")
                for eventDumpPlugin in eventDumpPlugins:
                    eventDumpPlugin.doGenInfo = cms.bool(False)
                    eventDumpPlugin.genParticleSource = cms.InputTag('')

            # disable estimation of systematic uncertainties by setting
            #  o analyzers_systematic = cms.VPSet(..) --> cms.VPSet()
            processAttr.analyzers.analyzers_systematic = cms.VPSet()

    for processAttrName in dir(process):
        processAttr = getattr(process, processAttrName)
        _setattr_ifexists(processAttr, "isData", cms.bool(True))
def configurePatTupleProduction(process,
                                patSequenceBuilder=buildGenericTauSequence,
                                patPFTauCleanerPrototype=None,
                                patCaloTauCleanerPrototype=None,
                                addSVfitInfo=False,
                                hltProcess="HLT",
                                isMC=False,
                                applyTauVertexMatch=True):

    # check that patSequenceBuilder and patTauCleanerPrototype are defined and non-null
    if patSequenceBuilder is None:
        raise ValueError("Undefined 'patSequenceBuilder' Parameter !!")
    if patPFTauCleanerPrototype is None or patCaloTauCleanerPrototype is None:
        raise ValueError("Undefined 'patTauCleanerPrototype' Parameter !!")

    #--------------------------------------------------------------------------------
    # produce PAT objects
    #--------------------------------------------------------------------------------

    process.load("PhysicsTools.PatAlgos.patSequences_cff")
    process.load("PhysicsTools.PatAlgos.producersLayer1.tauProducer_cff")
    process.load("PhysicsTools.PatAlgos.producersLayer1.muonProducer_cff")
    process.load("PhysicsTools.PatAlgos.producersLayer1.metProducer_cff")
    process.load("TauAnalysis.CandidateTools.muTauPairProduction_cff")

    # per default, do **not** run SVfit algorithm
    if not addSVfitInfo:
        process.allMuTauPairs.doSVreco = cms.bool(False)
        process.allMuTauPairs.doPFMEtSign = cms.bool(False)
        process.allMuTauPairsLooseMuonIsolation.doSVreco = cms.bool(False)
        process.allMuTauPairsLooseMuonIsolation.doPFMEtSign = cms.bool(False)

    if not isMC:
        removeMCMatching(process, ["All"], outputModules=[])
    else:
        # match pat::Taus to all genJets
        # (including to genJets build from electrons/muons produced in tau --> e/mu decays)
        process.tauGenJetMatch.matched = cms.InputTag("tauGenJets")

    #--------------------------------------------------------------------------------
    # configure PAT trigger matching
    switchOnTrigger(process, hltProcess=hltProcess, outputModule='')
    # CV: disable L1Algos in MC for now, to prevent error messages
    #
    #     %MSG-e L1GlobalTriggerObjectMapRecord:  PATTriggerProducer:patTrigger
    #
    #       ERROR: The requested algorithm name = L1_DoubleEG1
    #       does not exists in the trigger menu.
    #       Returning zero pointer for getObjectMap
    #
    #     to be printed for every event (06/05/2011)
    #
    #     for Data the L1Algos flag needs to be enabled,
    #     in order for the prescale computation/correction for Data
    #     implemented in TauAnalysis/TauIdEfficiency/bin/FWLiteTauIdEffAnalyzer.cc to work
    if isMC:
        process.patTrigger.addL1Algos = cms.bool(False)
    else:
        process.patTrigger.addL1Algos = cms.bool(True)

    process.patTauTriggerMatchHLTprotoType = cms.EDProducer(
        "PATTriggerMatcherDRLessByR",
        src=cms.InputTag("cleanLayer1Taus"),
        matched=cms.InputTag("patTrigger"),
        matchedCuts=cms.string('path("HLT_Jet30_v*")'),
        maxDPtRel=cms.double(1.e+3),
        maxDeltaR=cms.double(0.5),
        resolveAmbiguities=cms.bool(True),
        resolveByMatchQuality=cms.bool(True))
    #--------------------------------------------------------------------------------

    #--------------------------------------------------------------------------------
    # compute Pt sum of charged + neutral hadrons and photons within isolation cones of size dR = 0.4/0.6

    process.load("RecoMuon/MuonIsolation/muonPFIsolation_cff")
    patutils.massSearchReplaceAnyInputTag(
        process.muonPFIsolationDepositsSequence, cms.InputTag('muons1stStep'),
        cms.InputTag('muons'))
    process.patMuons.isoDeposits = cms.PSet(
        # CV: strings for IsoDeposits defined in PhysicsTools/PatAlgos/plugins/PATMuonProducer.cc
        pfChargedHadrons=cms.InputTag("muPFIsoDepositCharged"),
        pfNeutralHadrons=cms.InputTag("muPFIsoDepositNeutral"),
        pfPhotons=cms.InputTag("muPFIsoDepositGamma"),
        user=cms.VInputTag(cms.InputTag("muPFIsoDepositChargedAll"),
                           cms.InputTag("muPFIsoDepositPU")))

    process.patMuons.userIsolation = cms.PSet(
        # CV: strings for Isolation values defined in PhysicsTools/PatAlgos/src/MultiIsolator.cc
        pfChargedHadron=cms.PSet(
            deltaR=cms.double(0.4),
            src=process.patMuons.isoDeposits.pfChargedHadrons,
            vetos=process.muPFIsoValueCharged04.deposits[0].vetos,
            skipDefaultVeto=process.muPFIsoValueCharged04.deposits[0].
            skipDefaultVeto),
        pfNeutralHadron=cms.PSet(
            deltaR=cms.double(0.4),
            src=process.patMuons.isoDeposits.pfNeutralHadrons,
            vetos=process.muPFIsoValueNeutral04.deposits[0].vetos,
            skipDefaultVeto=process.muPFIsoValueNeutral04.deposits[0].
            skipDefaultVeto),
        pfGamma=cms.PSet(deltaR=cms.double(0.4),
                         src=process.patMuons.isoDeposits.pfPhotons,
                         vetos=process.muPFIsoValueGamma04.deposits[0].vetos,
                         skipDefaultVeto=process.muPFIsoValueGamma04.
                         deposits[0].skipDefaultVeto),
        user=cms.VPSet(
            cms.PSet(deltaR=cms.double(0.4),
                     src=process.patMuons.isoDeposits.user[0],
                     vetos=process.muPFIsoValueChargedAll04.deposits[0].vetos,
                     skipDefaultVeto=process.muPFIsoValueChargedAll04.
                     deposits[0].skipDefaultVeto),
            cms.PSet(deltaR=cms.double(0.4),
                     src=process.patMuons.isoDeposits.user[1],
                     vetos=process.muPFIsoValuePU04.deposits[0].vetos,
                     skipDefaultVeto=process.muPFIsoValuePU04.deposits[0].
                     skipDefaultVeto)))

    process.patMuonsWithinAcc = cms.EDFilter(
        "PATMuonSelector",
        src=cms.InputTag('patMuons'),
        cut=cms.string("pt > 15. & abs(eta) < 2.1"),
        filter=cms.bool(False))
    process.selectedPatMuonsVBTFid = cms.EDFilter(
        "PATMuonIdSelector",
        src=cms.InputTag('patMuonsWithinAcc'),
        vertexSource=cms.InputTag('selectedPrimaryVertexPosition'),
        beamSpotSource=cms.InputTag('offlineBeamSpot'),
        filter=cms.bool(False))
    #--------------------------------------------------------------------------------

    #--------------------------------------------------------------------------------
    #
    # produce collections of pat::Jets for CaloJets and PFJets
    #
    # NOTE: needed for evaluating jetId for Calo/TCTaus and PFTaus
    #
    jec = ['L1FastJet', 'L2Relative', 'L3Absolute']
    if not isMC:
        jec.extend(['L2L3Residual'])

    addJetCollection(process,
                     cms.InputTag('ak5PFJets'),
                     'AK5',
                     'PF',
                     doJTA=False,
                     doBTagging=False,
                     jetCorrLabel=('AK5PF', cms.vstring(jec)),
                     doType1MET=False,
                     genJetCollection=cms.InputTag("ak5GenJets"),
                     doJetID=True,
                     jetIdLabel="ak5",
                     outputModules=[])

    addJetCollection(process,
                     cms.InputTag('ak5CaloJets'),
                     'AK5',
                     'Calo',
                     doJTA=False,
                     doBTagging=False,
                     jetCorrLabel=('AK5Calo', cms.vstring(jec)),
                     doType1MET=False,
                     genJetCollection=cms.InputTag("ak5GenJets"),
                     doJetID=True,
                     jetIdLabel="ak5",
                     outputModules=[])
    #--------------------------------------------------------------------------------

    #--------------------------------------------------------------------------------
    #
    # configure Jet Energy Corrections
    #
    process.load("TauAnalysis.Configuration.jetCorrectionParameters_cfi")
    #--------------------------------------------------------------------------------

    #--------------------------------------------------------------------------------
    # add pfMET
    process.load("PhysicsTools.PatUtils.patPFMETCorrections_cff")
    if isMC:
        import PhysicsTools.PatAlgos.tools.helpers as configtools
        configtools.cloneProcessingSnippet(process,
                                           process.producePatPFMETCorrections,
                                           "NoSmearing")
        process.selectedPatJetsForMETtype1p2CorrNoSmearing.src = cms.InputTag(
            'patJetsNotOverlappingWithLeptonsForMEtUncertainty')
        process.selectedPatJetsForMETtype2CorrNoSmearing.src = process.selectedPatJetsForMETtype1p2CorrNoSmearing.src

    process.patMEtProductionSequence = cms.Sequence()
    process.patMEtProductionSequence += process.patDefaultSequence

    from PhysicsTools.PatUtils.tools.metUncertaintyTools import runMEtUncertainties
    doSmearJets = None
    if isMC:
        doSmearJets = True
    else:
        doSmearJets = False
    runMEtUncertainties(
        process,
        electronCollection='',
        photonCollection='',
        muonCollection=cms.InputTag('selectedPatMuonsVBTFid'),
        tauCollection='',
        jetCollection=cms.InputTag('patJetsAK5PF'),
        doSmearJets=doSmearJets,
        doApplyType0corr=True,
        sysShiftCorrParameter=None,
        doApplySysShiftCorr=False,
        # CV: shift Jet energy by 3 standard-deviations,
        #     so that template morphing remains an interpolation and no extrapolation is needed
        varyByNsigmas=3.0,
        addToPatDefaultSequence=False)

    if isMC:
        process.patPFMet.addGenMET = cms.bool(True)
        process.patPFJetMETtype1p2Corr.jetCorrLabel = cms.string("L3Absolute")

        process.patMEtProductionSequence += process.metUncertaintySequence
    else:
        process.patPFMet.addGenMET = cms.bool(False)
        process.patPFJetMETtype1p2Corr.jetCorrLabel = cms.string(
            "L2L3Residual")

        process.patMEtProductionSequence += process.patJetsAK5PFnotOverlappingWithLeptonsForMEtUncertainty
        process.patMEtProductionSequence += process.producePatPFMETCorrections
    #--------------------------------------------------------------------------------

    pfJetCollection = 'patJetsAK5PFnotOverlappingWithLeptonsForMEtUncertainty'
    pfMEtCollection = 'patType1CorrectedPFMet'
    if isMC:
        pfJetCollection = 'smearedPatJetsAK5PF'

    #--------------------------------------------------------------------------------
    #
    # produce combinations of muon + tau-jet pairs
    # for collection of pat::Tau objects representing CaloTaus
    #
    switchToCaloTau(process)
    process.patCaloTauProducer = copy.deepcopy(process.patTaus)

    retVal_caloTau = patSequenceBuilder(
        process,
        collectionName=["patCaloTaus", ""],
        jetCollectionName="patJetsAK5Calo",
        patTauProducerPrototype=process.patCaloTauProducer,
        patTauCleanerPrototype=patCaloTauCleanerPrototype,
        triggerMatcherProtoType=process.patTauTriggerMatchHLTprotoType,
        addGenInfo=isMC,
        applyTauJEC=False,
        applyTauVertexMatch=applyTauVertexMatch)
    process.caloTauSequence = retVal_caloTau["sequence"]

    process.patMuonCaloTauPairs = process.allMuTauPairs.clone(
        srcLeg1=cms.InputTag('selectedPatMuonsVBTFid'),
        srcLeg2=cms.InputTag(retVal_caloTau["collection"]),
        srcMET=cms.InputTag('patMETs'),
        srcGenParticles=cms.InputTag(''),
        doSVreco=cms.bool(False),
        doPFMEtSign=cms.bool(False))
    if hasattr(process.patMuonCaloTauPairs, "nSVfit"):
        delattr(process.patMuonCaloTauPairs, "nSVfit")
    if hasattr(process.patMuonCaloTauPairs, "pfMEtSign"):
        delattr(process.patMuonCaloTauPairs, "pfMEtSign")
    #--------------------------------------------------------------------------------

    #--------------------------------------------------------------------------------
    #
    # produce collection of pat::Tau objects representing PFTaus
    # reconstructed by fixed signal cone algorithm
    # (plus combinations of muon + tau-jet pairs)
    #
    #switchToPFTauFixedCone(process)
    #process.patPFTauProducerFixedCone = copy.deepcopy(process.patTaus)
    #
    #retVal_pfTauFixedCone = patSequenceBuilder(
    #    process,
    #    collectionName = [ "patPFTaus", "FixedCone" ],
    #    jetCollectionName = pfJetCollection,
    #    patTauProducerPrototype = process.patPFTauProducerFixedCone,
    #    patTauCleanerPrototype = patPFTauCleanerPrototype,
    #    triggerMatcherProtoType = process.patTauTriggerMatchHLTprotoType,
    #    addGenInfo = isMC,
    #    applyTauJEC = False,
    #    applyTauVertexMatch = applyTauVertexMatch
    #)
    #process.pfTauSequenceFixedCone = retVal_pfTauFixedCone["sequence"]
    #
    #process.patMuonPFTauPairsFixedCone = process.allMuTauPairs.clone(
    #    srcLeg1 = cms.InputTag('selectedPatMuonsVBTFid'),
    #    srcLeg2 = cms.InputTag(retVal_pfTauFixedCone["collection"]),
    #    srcMET = cms.InputTag(pfMEtCollection),
    #    srcGenParticles = cms.InputTag(''),
    #    doSVreco = cms.bool(False)
    #)
    #if hasattr(process.patMuonPFTauPairsFixedCone, "nSVfit"):
    #    delattr(process.patMuonPFTauPairsFixedCone, "nSVfit")
    #if hasattr(process.patMuonPFTauPairsFixedCone, "pfMEtSign"):
    #    delattr(process.patMuonPFTauPairsFixedCone, "pfMEtSign")
    #--------------------------------------------------------------------------------

    #--------------------------------------------------------------------------------
    #
    # produce collection of pat::Tau objects representing PFTaus
    # reconstructed by shrinking signal cone algorithm
    # (plus combinations of muon + tau-jet pairs)
    #
    #switchToPFTauShrinkingCone(process)
    #process.patPFTauProducerShrinkingCone = copy.deepcopy(process.patTaus)
    #
    #retVal_pfTauShrinkingCone = patSequenceBuilder(
    #    process,
    #    collectionName = [ "patPFTaus", "ShrinkingCone" ],
    #    jetCollectionName = pfJetCollection,
    #    patTauProducerPrototype = process.patPFTauProducerShrinkingCone,
    #    patTauCleanerPrototype = patPFTauCleanerPrototype,
    #    triggerMatcherProtoType = process.patTauTriggerMatchHLTprotoType,
    #    addGenInfo = isMC,
    #    applyTauJEC = False,
    #    applyTauVertexMatch = applyTauVertexMatch
    #)
    #process.pfTauSequenceShrinkingCone = retVal_pfTauShrinkingCone["sequence"]
    #
    #process.patMuonPFTauPairsShrinkingCone = process.allMuTauPairs.clone(
    #    srcLeg1 = cms.InputTag('selectedPatMuonsVBTFid'),
    #    srcLeg2 = cms.InputTag(retVal_pfTauShrinkingCone["collection"]),
    #    srcMET = cms.InputTag(pfMEtCollection),
    #    srcGenParticles = cms.InputTag(''),
    #    doSVreco = cms.bool(False)
    #)
    #if hasattr(process.patMuonPFTauPairsShrinkingCone, "nSVfit"):
    #    delattr(process.patMuonPFTauPairsShrinkingCone, "nSVfit")
    #if hasattr(process.patMuonPFTauPairsShrinkingCone, "pfMEtSign"):
    #    delattr(process.patMuonPFTauPairsShrinkingCone, "pfMEtSign")
    #--------------------------------------------------------------------------------

    #--------------------------------------------------------------------------------
    #
    # produce collection of pat::Tau objects representing PFTaus
    # reconstructed by hadron + strips (HPS) algorithm
    # (plus combinations of muon + tau-jet pairs)
    #
    # NOTE: switchToPFTauHPS function overwrites process.cleanPatTaus.preselection using HPS specific discriminators;
    #       undo overwriting, in order to prevent run-time errors in case of subsequence _switchToPFTau call,
    #       arising from the fact that HPS specific discriminators are not available for all tau types
    #
    switchToPFTauHPS(process)
    process.cleanPatTaus.preselection = cms.string('')
    process.patPFTauProducerHPS = copy.deepcopy(process.patTaus)

    retVal_pfTauHPS = patSequenceBuilder(
        process,
        collectionName=["patPFTaus", "HPS"],
        jetCollectionName=pfJetCollection,
        patTauProducerPrototype=process.patPFTauProducerHPS,
        patTauCleanerPrototype=patPFTauCleanerPrototype,
        triggerMatcherProtoType=process.patTauTriggerMatchHLTprotoType,
        addGenInfo=isMC,
        applyTauJEC=True,
        applyTauVertexMatch=applyTauVertexMatch)
    process.pfTauSequenceHPS = retVal_pfTauHPS["sequence"]

    process.patMuonPFTauPairsHPS = process.allMuTauPairs.clone(
        srcLeg1=cms.InputTag('selectedPatMuonsVBTFid'),
        srcLeg2=cms.InputTag(retVal_pfTauHPS["collection"]),
        srcMET=cms.InputTag(pfMEtCollection),
        srcGenParticles=cms.InputTag(''),
        doSVreco=cms.bool(False))
    if hasattr(process.patMuonPFTauPairsHPS, "nSVfit"):
        delattr(process.patMuonPFTauPairsHPS, "nSVfit")
    if hasattr(process.patMuonPFTauPairsHPS, "pfMEtSign"):
        delattr(process.patMuonPFTauPairsHPS, "pfMEtSign")
    #--------------------------------------------------------------------------------

    #--------------------------------------------------------------------------------
    #
    # produce collection of pat::Tau objects representing PFTaus
    # reconstructed by HPS + TaNC combined tau id. algorithm
    # (plus combinations of muon + tau-jet pairs)
    #
    switchToPFTauHPSpTaNC(process)
    process.cleanPatTaus.preselection = cms.string('')
    process.patPFTauProducerHPSpTaNC = copy.deepcopy(process.patTaus)

    retVal_pfTauHPSpTaNC = patSequenceBuilder(
        process,
        collectionName=["patPFTaus", "HPSpTaNC"],
        jetCollectionName=pfJetCollection,
        patTauProducerPrototype=process.patPFTauProducerHPSpTaNC,
        patTauCleanerPrototype=patPFTauCleanerPrototype,
        triggerMatcherProtoType=process.patTauTriggerMatchHLTprotoType,
        addGenInfo=isMC,
        applyTauJEC=True,
        applyTauVertexMatch=applyTauVertexMatch)
    process.pfTauSequenceHPSpTaNC = retVal_pfTauHPSpTaNC["sequence"]

    process.patMuonPFTauPairsHPSpTaNC = process.allMuTauPairs.clone(
        srcLeg1=cms.InputTag('selectedPatMuonsVBTFid'),
        srcLeg2=cms.InputTag(retVal_pfTauHPSpTaNC["collection"]),
        srcMET=cms.InputTag(pfMEtCollection),
        srcGenParticles=cms.InputTag(''),
        doSVreco=cms.bool(False))
    if hasattr(process.patMuonPFTauPairsHPSpTaNC, "nSVfit"):
        delattr(process.patMuonPFTauPairsHPSpTaNC, "nSVfit")
    if hasattr(process.patMuonPFTauPairsHPSpTaNC, "pfMEtSign"):
        delattr(process.patMuonPFTauPairsHPSpTaNC, "pfMEtSign")
    #--------------------------------------------------------------------------------

    process.patTupleProductionSequence = cms.Sequence(
        process.muonPFIsolationSequence + process.patDefaultSequence
        ##+ process.patTrigger + process.patTriggerEvent
        + process.patMuonsWithinAcc + process.selectedPatMuonsVBTFid +
        process.patMEtProductionSequence + process.caloTauSequence
        # store TaNC inputs as discriminators
        #+ process.produceTancMVAInputDiscriminators
        #+ process.pfTauSequenceFixedCone
        #+ process.pfTauSequenceShrinkingCone
        + process.pfTauSequenceHPS + process.pfTauSequenceHPSpTaNC +
        process.patMuonCaloTauPairs
        #+ process.patMuonPFTauPairsFixedCone
        #+ process.patMuonPFTauPairsShrinkingCone
        + process.patMuonPFTauPairsHPS + process.patMuonPFTauPairsHPSpTaNC)

    # return names of "final" collections of CaloTaus/different types of PFTaus
    # to be used as InputTag for further processing
    retVal = {}
    retVal["caloTauCollection"] = retVal_caloTau["collection"]
    retVal["muonCaloTauCollection"] = process.patMuonCaloTauPairs.label()
    #retVal["pfTauCollectionFixedCone"] = retVal_pfTauFixedCone["collection"]
    #retVal["muonPFTauCollectionFixedCone"] = process.patMuonPFTauPairsFixedCone.label()
    #retVal["pfTauCollectionShrinkingCone"] = retVal_pfTauShrinkingCone["collection"]
    #retVal["muonPFTauCollectionShrinkingCone"] = process.patMuonPFTauPairsShrinkingCone.label()
    retVal["pfTauCollectionHPS"] = retVal_pfTauHPS["collection"]
    retVal["muonPFTauCollectionHPS"] = process.patMuonPFTauPairsHPS.label()
    retVal["pfTauCollectionHPSpTaNC"] = retVal_pfTauHPSpTaNC["collection"]
    retVal[
        "muonPFTauCollectionHPSpTaNC"] = process.patMuonPFTauPairsHPSpTaNC.label(
        )
    return retVal
flashggUnpackedJets = cms.EDProducer("FlashggVectorVectorJetUnpacker",
                                     JetsTag = cms.InputTag("flashggFinalJets"),
                                     NCollections = cms.uint32(maxJetCollections)
                                     )

UnpackedJetCollectionVInputTag = cms.VInputTag()
for i in range(0,maxJetCollections):
    UnpackedJetCollectionVInputTag.append(cms.InputTag('flashggUnpackedJets',str(i)))

############################
#       Systematics        #
############################
process.load("flashgg.Systematics.flashggDiPhotonSystematics_cfi")
from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet,massSearchReplaceAnyInputTag
massSearchReplaceAnyInputTag(process.flashggTagSequence,cms.InputTag("flashggDiPhotons"),cms.InputTag("flashggDiPhotonSystematics"))
massSearchReplaceAnyInputTag(process.flashggTagSequence,cms.InputTag("flashggPreselectedDiPhotons"),cms.InputTag("flashggDiPhotonSystematics"))

process.flashggSystTagMerger = cms.EDProducer("TagMerger",src=cms.VInputTag("flashggTagSorter"))
process.systematicsTagSequences = cms.Sequence()
systlabels = [""]
phosystlabels = []

#if customize.processId.count("h_") or customize.processId.count("vbf_"): # convention: ggh vbf wzh tth    
if customize.processId == "signal":
    print "Signal MC, so adding systematics and dZ"
    #variablesToUse = minimalVariables
    for direction in ["Up","Down"]:
        #phosystlabels.append("MvaShift%s01sigma" % direction)
        #phosystlabels.append("SigmaEOverEShift%s01sigma" % direction)
        #jetsystlabels.append("JEC%s01sigma" % direction)
Пример #53
0
        fs_daughter_inputs['photons'] = 'photonParentage'
        fs_daughter_inputs['jets'] = 'selectedPatJetsRematched'

    if options.rerunQGJetID:
        process.schedule.append(
            rerun_QGJetID(process, fs_daughter_inputs)
        )

    if options.rerunJets:
        process.schedule.append(rerun_jets(process))

    if options.runNewElectronMVAID:
        process.load("FinalStateAnalysis.PatTools."
                     "electrons.patElectronSummer13MVAID_cfi")
        helpers.massSearchReplaceAnyInputTag(
            process.runAndEmbedSummer13Id,
            'fixme',
            fs_daughter_inputs['electrons'])
        fs_daughter_inputs['electrons'] = 'patElectrons2013MVAID'
        process.runNewElectronMVAID = cms.Path(process.runAndEmbedSummer13Id)
        process.schedule.append(process.runNewElectronMVAID)

    # Eventually, set buildFSAEvent to False, currently working around bug
    # in pat tuples.
    produce_final_states(process, fs_daughter_inputs, [], process.buildFSASeq,
                         'puTagDoesntMatter', buildFSAEvent=True,
                         noTracks=True, noPhotons=options.noPhotons,
                         zzMode=options.zzMode, rochCor=options.rochCor,
                         eleCor=options.eleCor)
    process.buildFSAPath = cms.Path(process.buildFSASeq)
    # Don't crash if some products are missing (like tracks)
    process.patFinalStateEventProducer.forbidMissing = cms.bool(False)
Пример #54
0
kinematicSelectedTauValDenominatorQCD = cms.EDFilter(
    "GenJetSelector",  #"GenJetSelector"
    src=cms.InputTag('ak4GenJets'),
    cut=
    kinematicSelectedTauValDenominatorCut,  #cms.string('pt > 5. && abs(eta) < 2.5'), #Defined: Validation.RecoTau.RecoTauValidation_cfi 
    filter=cms.bool(False))

procAttributes = dir(proc)  #Takes a snapshot of what there in the process
helpers.cloneProcessingSnippet(
    proc, proc.TauValNumeratorAndDenominator,
    'QCD')  #clones the sequence inside the process with QCD postfix
helpers.cloneProcessingSnippet(
    proc, proc.TauEfficiencies,
    'QCD')  #clones the sequence inside the process with QCD postfix
helpers.massSearchReplaceAnyInputTag(
    proc.TauValNumeratorAndDenominatorQCD,
    'kinematicSelectedTauValDenominator',
    'kinematicSelectedTauValDenominatorQCD')  #sets the correct input tag

#adds to TauValNumeratorAndDenominator modules in the sequence QCD to the extention name
zttLabeler = lambda module: SetValidationExtention(module, 'QCD')
zttModifier = ApplyFunctionToSequence(zttLabeler)
proc.TauValNumeratorAndDenominatorQCD.visit(zttModifier)

#Set discriminators
discs_to_retain = [
    'ByDecayModeFinding', 'CombinedIsolationDBSumPtCorr3Hits',
    'IsolationMVArun2v1DBoldDMwLT', 'IsolationMVArun2v1DBnewDMwLT'
]
proc.RunHPSValidationQCD.discriminators = cms.VPSet([
    p for p in proc.RunHPSValidationQCD.discriminators
    if any(disc in p.discriminator.value() for disc in discs_to_retain)
def addExtraMETCollections(process, unCleanPFCandidateCollection,
                           cleanElectronCollection,
                           cleanPhotonCollection,
                           unCleanElectronCollection,
                           unCleanPhotonCollection ):

    # Muon/EGamma un/corrected pfMET ============
    from PhysicsTools.PatUtils.tools.corMETFromMuonAndEG import corMETFromMuonAndEG
    from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncForMiniAODProduction
    
    # uncorrected MET
    cloneProcessingSnippet(process, getattr(process,"makePatJets"),"BackupAllEvents")
    massSearchReplaceAnyInputTag(getattr(process,"makePatJetsBackupAllEvents"), "ak4PFJetsCHS", "ak4PFJetsCHSBackupAllEvents")
    massSearchReplaceAnyInputTag(getattr(process,"makePatJetsBackupAllEvents"), "pfCandidatesBadMuonsCleaned", "particleFlow")
    del process.patJetsBackupAllEvents.userData
    process.patJetsBackupAllEvents.addAssociatedTracks = cms.bool(False)
    process.patJetsBackupAllEvents.addBTagInfo = cms.bool(False)
    process.patJetsBackupAllEvents.addDiscriminators = cms.bool(False)
    process.patJetsBackupAllEvents.addGenJetMatch = cms.bool(False)
    process.patJetsBackupAllEvents.addGenPartonMatch = cms.bool(False)
    process.patJetsBackupAllEvents.addJetCharge = cms.bool(False)
    process.patJetsBackupAllEvents.addJetCorrFactors = cms.bool(True)
    process.patJetsBackupAllEvents.addJetFlavourInfo = cms.bool(False)
    process.patJetsBackupAllEvents.addJetID = cms.bool(False)
    process.patJetsBackupAllEvents.addPartonJetMatch = cms.bool(False)
    process.patJetsBackupAllEvents.addResolutions = cms.bool(False)
    process.patJetsBackupAllEvents.addTagInfos = cms.bool(False)
    process.patJetsBackupAllEvents.discriminatorSources = cms.VInputTag()
    process.patJetsBackupAllEvents.embedGenJetMatch = cms.bool(False)
  
    runMetCorAndUncForMiniAODProduction(process,
                                        metType="PF",
                                        pfCandColl=cms.InputTag(unCleanPFCandidateCollection),
                                        recoMetFromPFCs=True,
                                        jetCollUnskimmed="patJetsBackupAllEvents",
                                        postfix="Uncorrected"
                                        )

    if not hasattr(process, "slimmedMETs"):
        process.load('PhysicsTools.PatAlgos.slimming.slimmedMETs_cfi')
        
    process.slimmedMETsUncorrected = process.slimmedMETs.clone()
    process.slimmedMETsUncorrected.src = cms.InputTag("patPFMetT1Uncorrected")
    process.slimmedMETsUncorrected.rawVariation =  cms.InputTag("patPFMetUncorrected")
    process.slimmedMETsUncorrected.t1Uncertainties = cms.InputTag("patPFMetT1%sUncorrected") 
    process.slimmedMETsUncorrected.t01Variation = cms.InputTag("patPFMetT0pcT1Uncorrected")
    process.slimmedMETsUncorrected.t1SmearedVarsAndUncs = cms.InputTag("patPFMetT1Smear%sUncorrected")
    process.slimmedMETsUncorrected.tXYUncForRaw = cms.InputTag("patPFMetTxyUncorrected")
    process.slimmedMETsUncorrected.tXYUncForT1 = cms.InputTag("patPFMetT1TxyUncorrected")
    process.slimmedMETsUncorrected.tXYUncForT01 = cms.InputTag("patPFMetT0pcT1TxyUncorrected")
    process.slimmedMETsUncorrected.tXYUncForT1Smear = cms.InputTag("patPFMetT1SmearTxyUncorrected")
    process.slimmedMETsUncorrected.tXYUncForT01Smear = cms.InputTag("patPFMetT0pcT1SmearTxyUncorrected")
    del process.slimmedMETsUncorrected.caloMET
    
    # EG corrected MET
    corMETFromMuonAndEG(process,
                        pfCandCollection="", #not needed
                        electronCollection=unCleanElectronCollection,
                        photonCollection=unCleanPhotonCollection,
                        corElectronCollection=cleanElectronCollection,
                        corPhotonCollection=cleanPhotonCollection,
                        allMETEGCorrected=True,
                        muCorrection=False,
                        eGCorrection=True,
                        runOnMiniAOD=False,
                        eGPFix="Uncorrected",
                        postfix="EGOnly"
                        )
    process.slimmedMETsEGClean = process.slimmedMETs.clone()
    process.slimmedMETsEGClean.src = cms.InputTag("patPFMetT1UncorrectedEGOnly")
    process.slimmedMETsEGClean.rawVariation =  cms.InputTag("patPFMetRawUncorrectedEGOnly")
    process.slimmedMETsEGClean.t1Uncertainties = cms.InputTag("patPFMetT1%sUncorrectedEGOnly") 
    process.slimmedMETsEGClean.t01Variation = cms.InputTag("patPFMetT0pcT1UncorrectedEGOnly")
    process.slimmedMETsEGClean.t1SmearedVarsAndUncs = cms.InputTag("patPFMetT1Smear%sUncorrectedEGOnly")
    process.slimmedMETsEGClean.tXYUncForRaw = cms.InputTag("patPFMetTxyUncorrectedEGOnly")
    process.slimmedMETsEGClean.tXYUncForT1 = cms.InputTag("patPFMetT1TxyUncorrectedEGOnly")
    process.slimmedMETsEGClean.tXYUncForT01 = cms.InputTag("patPFMetT0pcT1TxyUncorrectedEGOnly")
    process.slimmedMETsEGClean.tXYUncForT1Smear = cms.InputTag("patPFMetT1SmearTxyUncorrectedEGOnly")
    process.slimmedMETsEGClean.tXYUncForT01Smear = cms.InputTag("patPFMetT0pcT1SmearTxyUncorrectedEGOnly")
    del process.slimmedMETsEGClean.caloMET
 
    # fully corrected MET
    corMETFromMuonAndEG(process,
                        pfCandCollection="", #not needed
                        electronCollection=unCleanElectronCollection,
                        photonCollection=unCleanPhotonCollection,
                        corElectronCollection=cleanElectronCollection,
                        corPhotonCollection=cleanPhotonCollection,
                        allMETEGCorrected=True,
                        muCorrection=False,
                        eGCorrection=True,
                        runOnMiniAOD=False,
                        postfix="MuEGClean"
                        )
    process.slimmedMETsMuEGClean = process.slimmedMETs.clone()
    process.slimmedMETsMuEGClean.src = cms.InputTag("patPFMetT1MuEGClean")
    process.slimmedMETsMuEGClean.rawVariation =  cms.InputTag("patPFMetRawMuEGClean")
    process.slimmedMETsMuEGClean.t1Uncertainties = cms.InputTag("patPFMetT1%sMuEGClean") 
    process.slimmedMETsMuEGClean.t01Variation = cms.InputTag("patPFMetT0pcT1MuEGClean")
    process.slimmedMETsMuEGClean.t1SmearedVarsAndUncs = cms.InputTag("patPFMetT1Smear%sMuEGClean")
    process.slimmedMETsMuEGClean.tXYUncForRaw = cms.InputTag("patPFMetTxyMuEGClean")
    process.slimmedMETsMuEGClean.tXYUncForT1 = cms.InputTag("patPFMetT1TxyMuEGClean")
    process.slimmedMETsMuEGClean.tXYUncForT01 = cms.InputTag("patPFMetT0pcT1TxyMuEGClean")
    process.slimmedMETsMuEGClean.tXYUncForT1Smear = cms.InputTag("patPFMetT1SmearTxyMuEGClean")
    process.slimmedMETsMuEGClean.tXYUncForT01Smear = cms.InputTag("patPFMetT0pcT1SmearTxyMuEGClean")
    del process.slimmedMETsMuEGClean.caloMET

    addKeepStatement(process, "keep *_slimmedMETs_*_*",
                    ["keep *_slimmedMETsUncorrected_*_*", "keep *_slimmedMETsEGClean_*_*", "keep *_slimmedMETsMuEGClean_*_*"])
Пример #56
0
process.load('HeavyIonsAnalysis.JetAnalysis.EventSelection_cff')
#process.phltJetHI = cms.Path( process.hltJetHI )
process.pcollisionEventSelection = cms.Path(process.collisionEventSelection)
#process.pHBHENoiseFilter = cms.Path( process.HBHENoiseFilter )
process.phfCoincFilter = cms.Path(process.hfCoincFilter )
process.phfCoincFilter3 = cms.Path(process.hfCoincFilter3 )
process.pprimaryVertexFilter = cms.Path(process.primaryVertexFilter )
process.phltPixelClusterShapeFilter = cms.Path(process.siPixelRecHits*process.hltPixelClusterShapeFilter )
process.phiEcalRecHitSpikeFilter = cms.Path(process.hiEcalRecHitSpikeFilter )

process.pAna = cms.EndPath(process.skimanalysis)
#process.output_step = cms.EndPath(process.allOutput)

# Customization                                                                                                                                                  
process.HiGenParticleAna.ptMin = 2.
process.HiGenParticleAna.genParticleSrc = cms.untracked.InputTag("genParticles") 
process.HiGenParticleAna.stableOnly = cms.untracked.bool(False)

oldGenParticleTag=cms.InputTag("hiGenParticles")
newGenParticleTag=cms.InputTag("genParticles")
oldProcLabelTag=cms.InputTag("hiSignal")
newProcLabelTag=cms.InputTag("generator")

from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
for s in process.paths_().keys():
    massSearchReplaceAnyInputTag(getattr(process,s),oldGenParticleTag,newGenParticleTag)
    #massSearchReplaceAnyInputTag(getattr(process,s),newGenParticleTag,oldGenParticleTag)  // go back to hiGenParticles
    massSearchReplaceAnyInputTag(getattr(process,s),oldProcLabelTag,newProcLabelTag)

Пример #57
0
        process.patMetShiftCorrected
        )
process.PATCMGSequence += process.metphiCorretionSequence
patEventContentCMG+=['keep *_patMetShiftCorrected_*_*']

####################################################
######## CLEANED JET COLLECTION FOR MU-TAUH ########
####################################################
process.load('CMGTools.Common.PAT.addFilterPaths_cff')
print "Cleaning the jet collection for mu-tauh channel"
from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
process.load("ExoDiBosonResonances.PATtupleProduction.CleanJets_cff")
process.PATCMGSequence += process.primaryVertexFilter
process.PATCMGSequence += process.CleanJetsMuTauSequence
process.PATTauSequenceMuTau = cloneProcessingSnippet(process,process.PATTauSequence, "MuTau")
massSearchReplaceAnyInputTag(process.PATTauSequenceMuTau,cms.InputTag("pfJetsForHPSTauMuTau"),cms.InputTag("ak5PFJetsNoMu"))
process.PATTauSequenceMuTau.replace( process.pfJetsForHPSTauMuTau, process.primaryVertexFilter+process.CleanJetsMuTauSequence )
process.PATCMGSequence += process.PATTauSequenceMuTau
patEventContentCMG+=['keep *_*selectedPatTausMuTau*_*_*']

#####################################################
######### CLEANED JET COLLECTION FOR EL-TAUH ########
#####################################################
print "Cleaning the jet collection for ele-tauh channel"
process.PATCMGSequence += process.CleanJetsETauSequence
process.PATTauSequenceEleTau = cloneProcessingSnippet(process,process.PATTauSequence, "EleTau")
massSearchReplaceAnyInputTag(process.PATTauSequenceEleTau,cms.InputTag("pfJetsForHPSTauEleTau"),cms.InputTag("ak5PFJetsNoEle"))
process.PATTauSequenceEleTau.replace( process.pfJetsForHPSTauEleTau, process.primaryVertexFilter+process.CleanJetsETauSequence )
process.PATCMGSequence += process.PATTauSequenceEleTau
patEventContentCMG+=['keep *_*selectedPatTausEleTau*_*_*']
def customiseForPreMixingInput(process):
    from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag

    # Replace TrackingParticles and TrackingVertices globally
    # only apply on validation and dqm: we don't want to apply this in the mixing and digitization sequences
    for s in process.paths_().keys() + process.endpaths_().keys():
        if s.lower().find("validation") >= 0 or s.lower().find("dqm") >= 0:
            massSearchReplaceAnyInputTag(getattr(process, s),
                                         cms.InputTag("mix",
                                                      "MergedTrackTruth"),
                                         cms.InputTag("mixData",
                                                      "MergedTrackTruth"),
                                         skipLabelTest=True)

    # Replace Pixel/StripDigiSimLinks only for the known modules
    def replaceInputTag(tag, old, new):
        if tag.value() == old:
            tag.setValue(new)

    def replacePixelDigiSimLink(tag):
        replaceInputTag(tag, "simSiPixelDigis", "mixData:PixelDigiSimLink")

    def replaceStripDigiSimLink(tag):
        replaceInputTag(tag, "simSiStripDigis", "mixData:StripDigiSimLink")

    for label, producer in process.producers_().iteritems():
        if producer.type_() == "ClusterTPAssociationProducer":
            replacePixelDigiSimLink(producer.pixelSimLinkSrc)
            replaceStripDigiSimLink(producer.stripSimLinkSrc)
        if producer.type_() == "QuickTrackAssociatorByHitsProducer":
            replacePixelDigiSimLink(producer.pixelSimLinkSrc)
            replaceStripDigiSimLink(producer.stripSimLinkSrc)
        if producer.type_() == "TrackAssociatorByHitsProducer":
            replacePixelDigiSimLink(producer.pixelSimLinkSrc)
            replaceStripDigiSimLink(producer.stripSimLinkSrc)
        if producer.type_() == "MuonAssociatorEDProducer":
            producer.DTdigisimlinkTag = cms.InputTag("mixData",
                                                     "simMuonDTDigis")
            producer.CSClinksTag = cms.InputTag("mixData",
                                                "MuonCSCStripDigiSimLinks")
            producer.CSCwireLinksTag = cms.InputTag("mixData",
                                                    "MuonCSCWireDigiSimLinks")
            producer.RPCdigisimlinkTag = cms.InputTag("mixData",
                                                      "RPCDigiSimLink")
            replacePixelDigiSimLink(producer.pixelSimLinkSrc)
            replaceStripDigiSimLink(producer.stripSimLinkSrc)
        if producer.type_() == "MuonToTrackingParticleAssociatorEDProducer":
            producer.DTdigisimlinkTag = cms.InputTag("mixData",
                                                     "simMuonDTDigis")
            producer.CSClinksTag = cms.InputTag("mixData",
                                                "MuonCSCStripDigiSimLinks")
            producer.CSCwireLinksTag = cms.InputTag("mixData",
                                                    "MuonCSCWireDigiSimLinks")
            producer.RPCdigisimlinkTag = cms.InputTag("mixData",
                                                      "RPCDigiSimLink")
            replacePixelDigiSimLink(producer.pixelSimLinkSrc)
            replaceStripDigiSimLink(producer.stripSimLinkSrc)

    for label, analyzer in process.analyzers_().iteritems():
        if analyzer.type_() == "GlobalRecHitsAnalyzer":
            replacePixelDigiSimLink(analyzer.pixelSimLinkSrc)
            replaceStripDigiSimLink(analyzer.stripSimLinkSrc)
        if analyzer.type_() == "SiPixelTrackingRecHitsValid":
            replacePixelDigiSimLink(analyzer.pixelSimLinkSrc)
            replaceStripDigiSimLink(analyzer.stripSimLinkSrc)
        if analyzer.type_() == "SiStripTrackingRecHitsValid":
            replacePixelDigiSimLink(analyzer.pixelSimLinkSrc)
            replaceStripDigiSimLink(analyzer.stripSimLinkSrc)
        if analyzer.type_() == "SiPixelRecHitsValid":
            replacePixelDigiSimLink(analyzer.pixelSimLinkSrc)
            replaceStripDigiSimLink(analyzer.stripSimLinkSrc)
        if analyzer.type_() == "SiStripRecHitsValid":
            replacePixelDigiSimLink(analyzer.pixelSimLinkSrc)
            replaceStripDigiSimLink(analyzer.stripSimLinkSrc)

    return process
Пример #59
0
def switchToData(process):

	# remove MC matching from standard PAT sequences
	if hasattr(process, "patDefaultSequence"):
		removeMCMatching(process, ["All"], outputModules = [])
		process.patDefaultSequence.remove(process.patJetPartonMatch)

	#------------------------------------------------------------------------
	# CV: temporary work-around for W --> tau nu channel
	modulesToRemove = [
	    "patJetPartonMatchAK5PF",
	    "patJetGenJetMatchAK5PF",
	    "patJetPartons",
	    "patJetPartonAssociation",
	    "patJetPartonAssociationAK5PF",
	    "patJetFlavourAssociation",
	    "patJetFlavourAssociationAK5PF"
	]
	for moduleToRemove in modulesToRemove:
		if hasattr(process, moduleToRemove):
  		        process.patDefaultSequence.remove(getattr(process, moduleToRemove))
	if hasattr(process, "patJetCorrFactorsAK5PF"):
		process.patJetCorrFactorsAK5PF.levels.append("L2L3Residual")
	#------------------------------------------------------------------------

	# add data-quality cuts which work on "real" data only
	if hasattr(process, "dataQualityFilters"):
		process.dataQualityFilters._seq = process.dataQualityFilters._seq * process.hltPhysicsDeclared
		process.dataQualityFilters._seq = process.dataQualityFilters._seq * process.dcsstatus

	# apply L2/L3 residual jet energy corrections
	# (for improved Data and Monte-Carlo agreement)
	if hasattr(process, "pfMEtType1and2corrected"):
		setattr(process.pfMEtType1and2corrected, "corrector", cms.string('ak5PFL2L3Residual'))	

	if hasattr(process, "patPFMETs"):
		process.patPFMETs.addGenMET = cms.bool(False)
	if hasattr(process, "patPFtype1METs"):
		process.patPFtype1METs.addGenMET = cms.bool(False)

	# remove modules from pre-PAT production running on genParticles
	if hasattr(process, "producePrePat"):
		process.producePrePat.remove(process.genParticlesForJets)
		process.producePrePat.remove(process.ak5GenJets)

	# remove modules from PAT-tuple production sequence running on genParticles
	if hasattr(process, "producePatTuple"):
		if hasattr(process, "genParticlesForJets"):
			process.producePatTuple.remove(process.genParticlesForJets)
		if hasattr(process, "ak5GenJets"):
			process.producePatTuple.remove(process.ak5GenJets)
			
	# remove modules from post-PAT production running on genParticles
	if hasattr(process, "producePostPat"):
		process.producePostPat.remove(process.produceGenObjects)

	# iterate over all sequences attached to process object and
	# recursively disable gen. matching for all modules in sequence
	for processAttrName in dir(process):
		processAttr = getattr(process, processAttrName)
		if isinstance(processAttr, cms.Sequence):
			print "--> Disabling gen. Matching for sequence:", processAttrName
			# replace all InputTags referring to
			#  o genParticleSource = cms.InputTag('genParticles') --> ""
			#  o genJetSource = cms.InputTag('iterativeCone5GenJets') --> ""
			#  o genJetSource = cms.InputTag('ak5GenJets') --> ""
			#  o genTauJetSource = cms.InputTag('tauGenJets') --> ""
			#  o genMEtSource = cms.InputTag('genMetTrue') --> ""
			patutils.massSearchReplaceAnyInputTag(processAttr, cms.InputTag('genParticles'), cms.InputTag(''))
			patutils.massSearchReplaceAnyInputTag(processAttr, cms.InputTag('iterativeCone5GenJets'), cms.InputTag(''))
			patutils.massSearchReplaceAnyInputTag(processAttr, cms.InputTag('ak5GenJets'), cms.InputTag(''))
			patutils.massSearchReplaceAnyInputTag(processAttr, cms.InputTag('tauGenJets'), cms.InputTag(''))
			patutils.massSearchReplaceAnyInputTag(processAttr, cms.InputTag('genMetTrue'), cms.InputTag(''))
			
			# replace all InputTags referring to gen. Z decay products
			# in electron + tau-jet Zee (muon + tau-jet Zmumu) hypotheses
			patutils.massSearchReplaceAnyInputTag(processAttr, cms.InputTag('genElectronsFromZs'), cms.InputTag(''))
			patutils.massSearchReplaceAnyInputTag(processAttr, cms.InputTag('genMuonsFromZs'), cms.InputTag(''))
			
	# disable generator level matching for all PATJetProducer modules
	for processAttrName in dir(process):
		processAttr = getattr(process, processAttrName)
		if isinstance(processAttr, cms.EDProducer) and processAttr.type_() == "PATJetProducer":
		    print "--> Disabling gen. Matching for module:", processAttrName
		    setattr(processAttr, "addGenJetMatch", cms.bool(False))
		    setattr(processAttr, "addGenPartonMatch", cms.bool(False))
		    setattr(processAttr, "addPartonJetMatch", cms.bool(False))

	# disable access to generator level information in all
	# histogram managers, binner and event-dump plugins of GenericAnalyzer module
	for processAttrName in dir(process):
		processAttr = getattr(process, processAttrName)
		if isinstance(processAttr, cms.EDAnalyzer) and processAttr.type_() == "GenericAnalyzer":
			# disable matching between gen. and rec. particles
			# in all histogram managers and binner plugins by setting
			#  o genParticleSource = cms.InputTag('genParticles') --> ""
			#  o genJetSource = cms.InputTag('iterativeCone5GenJets') --> ""
			#  o genJetSource = cms.InputTag('ak5GenJets') --> ""
			#  o genTauJetSource = cms.InputTag('tauGenJets') --> ""
			#  o genMEtSource = cms.InputTag('genMetTrue') --> ""
			if hasattr(processAttr, "analyzers"):
				analyzerPlugins = getattr(processAttr, "analyzers")
				for analyzerPlugin in analyzerPlugins:
					_setattr_ifexists(analyzerPlugin, "genParticleSource", cms.InputTag(''))
					_setattr_ifexists(analyzerPlugin, "genJetSource", cms.InputTag(''))
					_setattr_ifexists(analyzerPlugin, "genTauJetSource", cms.InputTag(''))
					_setattr_ifexists(analyzerPlugin, "genMEtSource", cms.InputTag(''))

			# remove from all analysis sequences the following objects:
			#  o genPhaseSpaceInfoHistManager
			#  o modelBinnerForMuTauGenTauLeptonPairAcc
			#  o modelBinnerForMuTauWrtGenTauLeptonPairAcc
			#  o modelBinnerForMuTauGenTauLeptonPairAcc3mZbins
			#  o modelBinnerForMuTauWrtGenTauLeptonPairAcc3mZbins 
			#  o modelBinnerForMuTauCentralJetVetoWrtGenTauLeptonPairAcc
			#  o modelBinnerForMuTauCentralJetBtagWrtGenTauLeptonPairAcc
			#  o sysUncertaintyBinnerForMuTau
			#  o diTauCandidateCollinearApproxHistManagerBinnedForMuTau
			analyzerPluginsToRemove = [
				"genPhaseSpaceEventInfoHistManager",
				"genTauHistManager",
				"cutFlowHistManagerGenMultiplicity",
				"modelBinnerForMuTauGenTauLeptonPairAcc",
				"modelBinnerForMuTauWrtGenTauLeptonPairAcc",
				"modelBinnerForMuTauGenTauLeptonPairAcc3mZbins",
				"modelBinnerForMuTauWrtGenTauLeptonPairAcc3mZbins",
				"modelBinnerForMuTauCentralJetVetoWrtGenTauLeptonPairAcc",
				"modelBinnerForMuTauCentralJetBtagWrtGenTauLeptonPairAcc",
				"sysUncertaintyBinnerForMuTau",
				"diTauCandidateCollinearApproxHistManagerBinnedForMuTau"
			]
			for analyzerPluginName in analyzerPluginsToRemove:
				if hasattr(process, analyzerPluginName):
					analyzerPlugin = getattr(process, analyzerPluginName)
					if processAttr.analyzers.count(analyzerPlugin) > 0:
						processAttr.analyzers.remove(analyzerPlugin)
					removeAnalyzer(processAttr.analysisSequence, analyzerPluginName)

			# disable matching between gen. and rec. particles in all event-dump plugins by setting
			#  o doGenInfo = cms.bool(True) --> cms.bool(False)
			#  o genParticleSource = cms.InputTag('genParticles') --> ""
			if hasattr(processAttr, "eventDumps"):
				eventDumpPlugins = getattr(processAttr, "eventDumps")
				for eventDumpPlugin in eventDumpPlugins:
					eventDumpPlugin.doGenInfo = cms.bool(False)
					eventDumpPlugin.genParticleSource = cms.InputTag('')

			# disable estimation of systematic uncertainties by setting
			#  o analyzers_systematic = cms.VPSet(..) --> cms.VPSet()
			processAttr.analyzers.analyzers_systematic = cms.VPSet()

	for processAttrName in dir(process):
		processAttr = getattr(process, processAttrName)
		_setattr_ifexists(processAttr, "isData", cms.bool(True) )
process.neuralMtautauNtupleProductionSequence += process.kt6PFJets
process.neuralMtautauNtupleProductionSequence += process.ak5PFJets
process.patDefaultSequence.remove(process.patMETs)
process.patDefaultSequence.remove(process.patMETCorrections)
process.neuralMtautauNtupleProductionSequence += process.patDefaultSequence
process.neuralMtautauNtupleProductionSequence += process.producePatPFMETCorrections

# switch to HPS PFTaus (and disable all "cleaning" cuts)
from PhysicsTools.PatAlgos.tools.tauTools import *
switchToPFTauHPS(process)
process.cleanPatTaus.preselection = cms.string('')

# switch to generator level matched collections of electrons, muons and tau-jets
from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
massSearchReplaceAnyInputTag(process.patDefaultSequence,
                             cms.InputTag('gsfElectrons'),
                             cms.InputTag('genMatchedElectrons'))
massSearchReplaceAnyInputTag(process.patDefaultSequence, cms.InputTag('muons'),
                             cms.InputTag('genMatchedMuons'))
massSearchReplaceAnyInputTag(process.patDefaultSequence,
                             cms.InputTag('hpsPFTauProducer'),
                             cms.InputTag('genMatchedTaus'))

# disable matching pat::Electrons, pat::Muons and pat::Taus to generator level quantities
import PhysicsTools.PatAlgos.tools.helpers as patutils
removeMCMatching(process, ["All"], outputInProcess=False)
process.patDefaultSequence.remove(process.patJetPartonMatch)

# disable all pat::Electron embedding
for objSelAttrName in dir(process.patElectrons):
    objSelAttr = getattr(process.patElectrons, objSelAttrName)