removeMCMatching(process, ['All'], outputModules=[])

## ============================== ##
## Python tools --> Order matters ##
## ============================== ##

from PhysicsTools.PatAlgos.tools.coreTools import removeCleaning
from PhysicsTools.PatAlgos.tools.coreTools import removeSpecificPATObjects
if (cmsswRelease == 42):
    removeCleaning(process, False)
elif (cmsswRelease == 44):
    removeCleaning(process, outputModules=[])
else:
    removeCleaning(process, outputModules=[])
    removeSpecificPATObjects(process,
                             names=['Jets', 'Taus', 'METs'],
                             outputModules=[])

# Special change for saving good products in data
if isData:
    process.out.outputCommands = cms.untracked.vstring("keep *")

#--- Trigger matching ---#
process.load("HeavyNu.AnalysisModules.hnutrigmatch_cfi")
from PhysicsTools.PatAlgos.tools.trigTools import *
if isData:
    if (runMuonAnalysis or topStudy) and runElectronAnalysis:
        triggerMatchersList = [
            'muonTriggerMatchHLTMuons', 'electronTriggerMatchHLTElectrons'
        ]
    elif runMuonAnalysis or topStudy or doDijet:
Beispiel #2
0
if isData:
    from PhysicsTools.PatAlgos.tools.coreTools import *
    if isPFJets:
        removeMCMatchingPF2PAT( process, '' )
    if cmsswRelease == 53:
        removeMCMatching(process, ['All'], outputModules = [])    

## ============================== ##
## Python tools --> Order matters ##
## ============================== ##
from PhysicsTools.PatAlgos.tools.coreTools import removeCleaning
from PhysicsTools.PatAlgos.tools.coreTools import removeSpecificPATObjects
if cmsswRelease == 53:
    removeCleaning( process, outputModules = [] )
    removeSpecificPATObjects(process, names = ['Jets','Taus','METs'], outputModules = [])

#-------------------------------#
#--- Output Module specifics ---#
#-------------------------------#
#--- Restore the event content after PAT ---#
process.out.outputCommands = cms.untracked.vstring("keep *","drop *_*_*_HNUSKIMS","keep edmTriggerResults_TriggerResults__HNUSKIMS")
#--- List of skims that will be kept ---#
process.out.SelectEvents = cms.untracked.PSet(SelectEvents=cms.vstring('plep35_35_prescale','plep50_35','pemu50_35'))

#----------------#
#--- LumiList ---#
#----------------#
process.lumilist = cms.EDAnalyzer('LumiList')
if not isMC:
    process.llPath = cms.Path(process.lumilist + process.boolFalse)
Beispiel #3
0
def usePF2PAT_WREdition(process, runPF2PAT=True, jetAlgo='AK5', runOnMC=True, postfix="", jetCorrections=('AK5PFchs', ['L1FastJet','L2Relative','L3Absolute']), pvCollection=cms.InputTag('offlinePrimaryVertices'), typeIMetCorrections=False, outputModules=['out']):
    # PLEASE DO NOT CLOBBER THIS FUNCTION WITH CODE SPECIFIC TO A GIVEN PHYSICS OBJECT.
    # CREATE ADDITIONAL FUNCTIONS IF NEEDED.

    """Switch PAT to use PF2PAT instead of AOD sources. if 'runPF2PAT' is true, we'll also add PF2PAT in front of the PAT sequence"""

    # -------- CORE ---------------
    if runPF2PAT:
        process.load("CommonTools.ParticleFlow.PF2PAT_cff")
        process.patPF2PATSequence = cms.Sequence( process.PF2PAT + process.patDefaultSequence)
    else:
        process.patPF2PATSequence = cms.Sequence( process.patDefaultSequence )

    if not postfix == "":
        from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet
        cloneProcessingSnippet(process, process.patPF2PATSequence, postfix)

    removeCleaning(process, postfix=postfix, outputModules=outputModules)

    # Photons
    print "Temporarily switching off photons completely"

    removeSpecificPATObjects(process,names=['Photons', 'Taus', "Muons", "Electrons"],outputModules=outputModules,postfix=postfix)
    removeIfInSequence(process,"patPhotonIsolation","patDefaultSequence",postfix)

    # Jets
    if runOnMC :
        switchToPFJets( process, cms.InputTag('pfNoTau'+postfix), jetAlgo, postfix=postfix,
                        jetCorrections=jetCorrections, type1=typeIMetCorrections, outputModules=outputModules )
        applyPostfix(process,"patDefaultSequence",postfix).replace(
            applyPostfix(process,"patJetGenJetMatch",postfix),
            getattr(process,"genForPF2PATSequence") *
            applyPostfix(process,"patJetGenJetMatch",postfix)
            )
    else :
        if not 'L2L3Residual' in jetCorrections[1]:
            print '#################################################'
            print 'WARNING! Not using L2L3Residual but this is data.'
            print 'If this is okay with you, disregard this message.'
            print '#################################################'
        switchToPFJets( process, cms.InputTag('pfNoTau'+postfix), jetAlgo, postfix=postfix,
                        jetCorrections=jetCorrections, type1=typeIMetCorrections, outputModules=outputModules )
                        

    # Taus
    if ishpsPFTau:
        adaptPFTaus( process, tauType='hpsPFTau', postfix=postfix )

    # MET
    switchToPFMET(process, cms.InputTag('pfMET'+postfix), type1=typeIMetCorrections, postfix=postfix)
    if not runOnMC :
        if hasattr(process,'patPFMet'+postfix):
            getattr(process,'patPFMet'+postfix).addGenMET = cms.bool(False)

    # Unmasked PFCandidates
    addPFCandidates(process,cms.InputTag('pfNoJet'+postfix),patLabel='PFParticles'+postfix,cut="",postfix=postfix)

    # adapt primary vertex collection
    adaptPVs(process, pvCollection=pvCollection, postfix=postfix)

    if runOnMC:
        process.load("CommonTools.ParticleFlow.genForPF2PAT_cff")
        getattr(process, "patDefaultSequence"+postfix).replace(
            applyPostfix(process,"patCandidates",postfix),
            process.genForPF2PATSequence+applyPostfix(process,"patCandidates",postfix)
            )
    else:
        removeMCMatchingPF2PAT(process,postfix=postfix,outputModules=outputModules)

    print "Done: PF2PAT interfaced to PAT, postfix=", postfix
  def usePF2PATForAnalysis(jetAlgo, postfix, useTypeIMET, usePFNoPU):

    # Jet corrections
    # No L2L3 Residual on purpose
    if usePFNoPU:
      jetCorrections = ("%sPFchs" % algo, ['L1FastJet', 'L2Relative', 'L3Absolute'])
      postfix += "chs"
    else:
      jetCorrections = ("%sPF" % algo, ['L1FastJet', 'L2Relative', 'L3Absolute'])

    #if not runOnMC:
    #  jetCorrections[1].append('L2L3Residual')

    p = postfix

    usePF2PAT(process, runPF2PAT=True, jetAlgo=jetAlgo, runOnMC=runOnMC, postfix=p, jetCorrections=jetCorrections, typeIMetCorrections = useTypeIMET)
    getattr(process, "pfPileUp" + p).Enable = True
    getattr(process, "pfPileUp" + p).Vertices = 'goodOfflinePrimaryVertices'
    getattr(process, "pfPileUp" + p).checkClosestZVertex = cms.bool(False)

    getattr(process, "pfJets" + p).doAreaFastjet = cms.bool(True)
    getattr(process, "pfJets" + p).doRhoFastjet = False
    getattr(process, 'patJetCorrFactors' + p).rho = cms.InputTag("kt6PFJets", "rho") # Do not use kt6PFJetsPFlowAK5, it's not ok for L1FastJet.

    # top projections in PF2PAT:
    getattr(process,"pfNoPileUp" + p).enable = cms.bool(usePFNoPU)
    getattr(process,"pfNoMuon" + p).enable = True
    getattr(process,"pfNoElectron" + p).enable = True
    getattr(process,"pfNoTau" + p).enable = True
    getattr(process,"pfNoJet" + p).enable = True

    getattr(process,"patElectrons" + p).embedTrack = True

    getattr(process,"patMuons" + p).embedTrack = True
    # enable delta beta correction for muon selection in PF2PAT?
    getattr(process,"pfIsolatedMuons" + p).doDeltaBetaCorrection = True

    getattr(process, "patJets" + p).embedPFCandidates = False
    # Keep only jets with pt > 2 Gev
    getattr(process, "selectedPatJets" + p).cut = "pt > 2";

    # Use a cone of 0.3 for photon isolation
    #adaptPFIsoPhotons(process, applyPostfix(process, "patPhotons", postfix), postfix, "03")

    # 2012 Photon ID

    # Electron conversion
    setattr(process, "patConversions" + p, cms.EDProducer("PATConversionProducer",
        # input collection
        electronSource = cms.InputTag("selectedPatElectrons" + p)
    ))

    # Switch electron isolation to dR = 0.3, for PF2PAT
    getattr(process, "pfIsolatedElectrons" + p).isolationValueMapsCharged = cms.VInputTag(cms.InputTag("elPFIsoValueCharged03PFId" + p))
    getattr(process, "pfIsolatedElectrons" + p).deltaBetaIsolationValueMap = cms.InputTag("elPFIsoValuePU03PFId" + p)
    getattr(process, "pfIsolatedElectrons" + p).isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("elPFIsoValueNeutral03PFId" + p), cms.InputTag("elPFIsoValueGamma03PFId" + p))

    getattr(process, "pfElectrons" + p).isolationValueMapsCharged  = cms.VInputTag(cms.InputTag("elPFIsoValueCharged03PFId" + p))
    getattr(process, "pfElectrons" + p).deltaBetaIsolationValueMap = cms.InputTag("elPFIsoValuePU03PFId" + p)
    getattr(process, "pfElectrons" + p).isolationValueMapsNeutral  = cms.VInputTag(cms.InputTag( "elPFIsoValueNeutral03PFId" + p), cms.InputTag("elPFIsoValueGamma03PFId" + p))

    # ... And for PAT
    adaptPFIsoElectrons(process, getattr(process, "pfElectrons" + p), p, "03")

    
    if runOnMC:
      cloneProcessingSnippet(process, getattr(process, "makePatMuons" + p), "Loose" + p, p)
      getattr(process, "muonMatchLoose" + p).src = cms.InputTag("pfMuons" + p)
      getattr(process, "patMuonsLoose" + p).pfMuonSource = cms.InputTag("pfMuons" + p)
      getattr(process, "patDefaultSequence" + p).replace(getattr(process, "makePatMuons" + p), getattr(process, "makePatMuons" + p) + getattr(process, "makePatMuonsLoose" + p))
    else:
      setattr(process, "patMuonsLoose" + p, getattr(process, "patMuons" + p).clone(
          pfMuonSource = cms.InputTag("pfMuons" + p)
        )
      )

    setattr(process, "selectedPatMuonsLoose" + p, getattr(process, "selectedPatMuons" + p).clone(
        src = cms.InputTag("patMuonsLoose" + p)
      )
    )
    sequence = getattr(process, "patDefaultSequence" + p)

    if not runOnMC:
      sequence += getattr(process, "patMuonsLoose" + p)

    sequence += (getattr(process, "selectedPatMuonsLoose" + p))

    setattr(process, "patElectronsLoose" + p, getattr(process, "patElectrons" + p).clone(
        pfElectronSource = cms.InputTag("pfElectrons" + p)
      )
    )
    setattr(process, "selectedPatElectronsLoose" + p, getattr(process, "selectedPatElectrons" + p).clone(
        src = cms.InputTag("patElectronsLoose" + p)
      )
    )
    adaptPFIsoElectrons(process, getattr(process, "patElectronsLoose" + p), postfix, "03")
    sequence = getattr(process, "patDefaultSequence" + p)
    sequence += (getattr(process, "patElectronsLoose" + p) * getattr(process, "selectedPatElectronsLoose" + p))


    #giulia turn off qg tagger
    ## Setup quark gluon tagger
    #process.load('QuarkGluonTagger.EightTeV.QGTagger_RecoJets_cff')
    #cloneProcessingSnippet(process, process.QuarkGluonTagger, p)
    #getattr(process, "QGTagger" + p).srcJets = cms.InputTag("selectedPatJets" + p)
    #getattr(process, "QGTagger" + p).isPatJet = cms.untracked.bool(True)
    #getattr(process, "QGTagger" + p).useCHS = cms.untracked.bool(usePFNoPU)

    ## Remove the processing of primary vertices, as it's already what we do here
    #getattr(process, 'QGTagger' + p).srcPV = cms.InputTag('goodOfflinePrimaryVertices')
    #getattr(process, 'QuarkGluonTagger' + p).remove(getattr(process, 'goodOfflinePrimaryVerticesQG' + p))

    if not runOnMC:
      if 'L2L3Residual' in jetCorrections:
        getattr(process, 'patPFJetMETtype1p2Corr' + p).jetCorrLabel = 'L2L3Residual'
      getattr(process, 'patPFMet' + p).addGenMET = cms.bool(False)

    names = ["Taus"]
    #if jetAlgo != "AK5":
      #names += ["Electrons", "Muons"]
    if len(names) > 0:
      removeSpecificPATObjects(process, names = names, outputModules = ['out'], postfix = p) 

    adaptPVs(process, pvCollection = cms.InputTag("goodOfflinePrimaryVertices"), postfix = p)

    getattr(process, "patDefaultSequence" + p).replace(getattr(process, "selectedPatElectrons" + p), getattr(process, "selectedPatElectrons" + p) + getattr(process, "patConversions" + p))

    #getattr(process, "patDefaultSequence" + p).replace(getattr(process, "selectedPatJets" + p), getattr(process, "selectedPatJets" + p) + getattr(process, "QuarkGluonTagger" + p))

    return getattr(process, "patPF2PATSequence" + p)
Beispiel #5
0
)

process.selectionSequence = cms.Sequence()

from PhysicsTools.PatAlgos.tools.coreTools import removeSpecificPATObjects, removeCleaning
from HiggsAnalysis.HeavyChHiggsToTauNu.HChPatTuple import addPat
from HiggsAnalysis.HeavyChHiggsToTauNu.HChDataSelection import addDataSelection

if options.doPat != 0:
    process.collisionDataSelection = cms.Sequence()
    if dataVersion.isData():
        process.collisionDataSelection = addDataSelection(process, dataVersion, trigger)
    
    process.patSequence = addPat(process, dataVersion, doPatTrigger=False, doTauHLTMatching=False,
                                 doPatTaus=False, doPatElectronID=False)
    removeSpecificPATObjects(process, ["Photons"], False)
    removeCleaning(process, False)    
    process.patMuons.embedTrack = False # In order to avoid transient references and generalTracks is available anyway

    process.selectionSequence = cms.Sequence(
        process.collisionDataSelection * 
        process.patSequence
    )

# Override the outputCommands here, since PAT modifies it
process.out.outputCommands = cms.untracked.vstring(
    "drop *",
    "keep edmMergeableCounter_*_*_*", # in lumi block
    "keep *_muonNtp_*_MUONNTUPLE",
    "keep *_metNtp_*_MUONNTUPLE",
    "keep *_jetNtp_*_MUONNTUPLE",
import TopQuarkAnalysis.Configuration.patRefSel_refMuJets_cfi as patRefSel_refMuJets_cfi

# remove MC matching, object cleaning, objects etc.
## remove MCMatching if run on Data
if options.runOnData:
  from PhysicsTools.PatAlgos.tools.coreTools import runOnData
  runOnData(process, names = [ 'PFAll' ],postfix =postfix)
  print "removeMatching"
if not runOnMC:
  runOnData( process
           , names = [ 'PFAll' ]
           , postfix = postfix
           )
PhysPatAlgCoreTools.removeSpecificPATObjects( process
                        , names = [ 'Photons', 'Taus' ]
                        , postfix = postfix
                        ) # includes 'removeCleaning'
# additional event content has to be (re-)added _after_ the call to 'removeCleaning()':
process.out.outputCommands += [ 'keep edmTriggerResults_*_*_*'
                              , 'keep *_hltTriggerSummaryAOD_*_*'
                              # vertices and beam spot
                              , 'keep *_offlineBeamSpot_*_*'
                              , 'keep *_offlinePrimaryVertices*_*_*'
                              , 'keep *_goodOfflinePrimaryVertices*_*_*'
                              ]
if runOnMC:
  process.out.outputCommands += [ 'keep GenEventInfoProduct_*_*_*'
                                , 'keep recoGenParticles_*_*_*'
                                , 'keep *_addPileupInfo_*_*'
                                ]
Beispiel #7
0
from HiggsAnalysis.HeavyChHiggsToTauNu.HChPatTuple import addPat
from HiggsAnalysis.HeavyChHiggsToTauNu.HChDataSelection import addDataSelection

if options.doPat != 0:
    process.collisionDataSelection = cms.Sequence()
    if dataVersion.isData():
        process.collisionDataSelection = addDataSelection(
            process, dataVersion, trigger)

    process.patSequence = addPat(process,
                                 dataVersion,
                                 doPatTrigger=False,
                                 doTauHLTMatching=False,
                                 doPatTaus=False,
                                 doPatElectronID=False)
    removeSpecificPATObjects(process, ["Photons"], False)
    removeCleaning(process, False)
    process.patMuons.embedTrack = False  # In order to avoid transient references and generalTracks is available anyway

    process.selectionSequence = cms.Sequence(process.collisionDataSelection *
                                             process.patSequence)

# Override the outputCommands here, since PAT modifies it
process.out.outputCommands = cms.untracked.vstring(
    "drop *",
    "keep edmMergeableCounter_*_*_*",  # in lumi block
    "keep *_muonNtp_*_MUONNTUPLE",
    "keep *_metNtp_*_MUONNTUPLE",
    "keep *_jetNtp_*_MUONNTUPLE",
    "keep *_jetIdNtp_*_MUONNTUPLE",
)
  def usePF2PATForAnalysis(jetAlgo, postfix, useTypeIMET, usePFNoPU):

    # Jet corrections
    # No L2L3 Residual on purpose
    if usePFNoPU:
      jetCorrections = ("%sPFchs" % algo, ['L1FastJet', 'L2Relative', 'L3Absolute'])
      postfix += "chs"
    else:
      jetCorrections = ("%sPF" % algo, ['L1FastJet', 'L2Relative', 'L3Absolute'])

    #if not runOnMC:
    #  jetCorrections[1].append('L2L3Residual')

    p = postfix

    usePF2PAT(process, runPF2PAT=True, jetAlgo=jetAlgo, runOnMC=runOnMC, postfix=p, jetCorrections=jetCorrections, typeIMetCorrections = useTypeIMET)
    getattr(process, "pfPileUp" + p).Enable = True
    getattr(process, "pfPileUp" + p).Vertices = 'goodOfflinePrimaryVertices'
    getattr(process, "pfPileUp" + p).checkClosestZVertex = cms.bool(False)

    getattr(process, "pfJets" + p).doAreaFastjet = cms.bool(True)
    getattr(process, "pfJets" + p).doRhoFastjet = False
    getattr(process, 'patJetCorrFactors' + p).rho = cms.InputTag("kt6PFJets", "rho") # Do not use kt6PFJetsPFlowAK5, it's not ok for L1FastJet.

    # top projections in PF2PAT:
    getattr(process,"pfNoPileUp" + p).enable = cms.bool(usePFNoPU)
    getattr(process,"pfNoMuon" + p).enable = True
    getattr(process,"pfNoElectron" + p).enable = True
    getattr(process,"pfNoTau" + p).enable = True
    getattr(process,"pfNoJet" + p).enable = True

    getattr(process,"patElectrons" + p).embedTrack = True

    getattr(process,"patMuons" + p).embedTrack = True
    # enable delta beta correction for muon selection in PF2PAT?
    getattr(process,"pfIsolatedMuons" + p).doDeltaBetaCorrection = True

    getattr(process, "patJets" + p).embedPFCandidates = False
    # Keep only jets with pt > 2 Gev
    getattr(process, "selectedPatJets" + p).cut = "pt > 2";

    # Use a cone of 0.3 for photon isolation
    #adaptPFIsoPhotons(process, applyPostfix(process, "patPhotons", postfix), postfix, "03")

    # 2012 Photon ID

    # Electron conversion
    setattr(process, "patConversions" + p, cms.EDProducer("PATConversionProducer",
        # input collection
        electronSource = cms.InputTag("selectedPatElectrons" + p)
    ))

    # Switch electron isolation to dR = 0.3, for PF2PAT
    getattr(process, "pfIsolatedElectrons" + p).isolationValueMapsCharged = cms.VInputTag(cms.InputTag("elPFIsoValueCharged03PFId" + p))
    getattr(process, "pfIsolatedElectrons" + p).deltaBetaIsolationValueMap = cms.InputTag("elPFIsoValuePU03PFId" + p)
    getattr(process, "pfIsolatedElectrons" + p).isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("elPFIsoValueNeutral03PFId" + p), cms.InputTag("elPFIsoValueGamma03PFId" + p))

    getattr(process, "pfElectrons" + p).isolationValueMapsCharged  = cms.VInputTag(cms.InputTag("elPFIsoValueCharged03PFId" + p))
    getattr(process, "pfElectrons" + p).deltaBetaIsolationValueMap = cms.InputTag("elPFIsoValuePU03PFId" + p)
    getattr(process, "pfElectrons" + p).isolationValueMapsNeutral  = cms.VInputTag(cms.InputTag( "elPFIsoValueNeutral03PFId" + p), cms.InputTag("elPFIsoValueGamma03PFId" + p))

    # ... And for PAT
    adaptPFIsoElectrons(process, getattr(process, "pfElectrons" + p), p, "03")

##there used to be a modulo to keep track of muons gen info, doesnt work anymore and we don't use that info - so removed for now.
    setattr(process, "patMuonsLoose" + p, getattr(process, "patMuons" + p).clone(
        pfMuonSource = cms.InputTag("pfMuons" + p),
        embedGenMatch = False,
        addGenMatch = False
      )
    )

    setattr(process, "selectedPatMuonsLoose" + p, getattr(process, "selectedPatMuons" + p).clone(
        src = cms.InputTag("patMuonsLoose" + p)
      )
    )
    sequence = getattr(process, "patDefaultSequence" + p)

    sequence += getattr(process, "patMuonsLoose" + p)

    sequence += (getattr(process, "selectedPatMuonsLoose" + p))

    setattr(process, "patElectronsLoose" + p, getattr(process, "patElectrons" + p).clone(
        pfElectronSource = cms.InputTag("pfElectrons" + p)
      )
    )
    setattr(process, "selectedPatElectronsLoose" + p, getattr(process, "selectedPatElectrons" + p).clone(
        src = cms.InputTag("patElectronsLoose" + p)
      )
    )
    adaptPFIsoElectrons(process, getattr(process, "patElectronsLoose" + p), postfix, "03")
    sequence = getattr(process, "patDefaultSequence" + p)
    sequence += (getattr(process, "patElectronsLoose" + p) * getattr(process, "selectedPatElectronsLoose" + p))


    # Setup quark gluon tagger
    #process.load('QuarkGluonTagger.EightTeV.QGTagger_RecoJets_cff')
    #cloneProcessingSnippet(process, process.QuarkGluonTagger, p)
    #getattr(process, "QGTagger" + p).srcJets = cms.InputTag("selectedPatJets" + p)
    #getattr(process, "QGTagger" + p).isPatJet = cms.untracked.bool(True)
    #getattr(process, "QGTagger" + p).useCHS = cms.untracked.bool(usePFNoPU)

    ## Remove the processing of primary vertices, as it's already what we do here
    #getattr(process, 'QGTagger' + p).srcPV = cms.InputTag('goodOfflinePrimaryVertices')
    #getattr(process, 'QuarkGluonTagger' + p).remove(getattr(process, 'goodOfflinePrimaryVerticesQG' + p))

    if not runOnMC:
      if 'L2L3Residual' in jetCorrections:
        getattr(process, 'patPFJetMETtype1p2Corr' + p).jetCorrLabel = 'L2L3Residual'
      getattr(process, 'patPFMet' + p).addGenMET = cms.bool(False)

    names = ["Taus"]
    #if jetAlgo != "AK5":
      #names += ["Electrons", "Muons"]
    if len(names) > 0:
      removeSpecificPATObjects(process, names = names, outputModules = ['out'], postfix = p) 

    adaptPVs(process, pvCollection = cms.InputTag("goodOfflinePrimaryVertices"), postfix = p)

    getattr(process, "patDefaultSequence" + p).replace(getattr(process, "selectedPatElectrons" + p), getattr(process, "selectedPatElectrons" + p) + getattr(process, "patConversions" + p))

    #getattr(process, "patDefaultSequence" + p).replace(getattr(process, "selectedPatJets" + p), getattr(process, "selectedPatJets" + p) + getattr(process, "QuarkGluonTagger" + p))

    return getattr(process, "patPF2PATSequence" + p)
if not runOnMC:
    runOnData(process, names = ['PFAll'], postfix = 'PF')




# We remove PAT photons here because they are not fully commisssioned
# in PF. (You could turn them on to check their performance.) This
# also turns off a cleaning step, which in the default PAT workflow
# tries to remove overlap between the physics object collections
# (e.g. removing muons from being reconstructed as degenerate "jets"),
# but this is not necessary with PF/the GED, especially with the top
# projections described above enabled.

from PhysicsTools.PatAlgos.tools.coreTools import removeSpecificPATObjects
removeSpecificPATObjects(process, names = ['Photons'], postfix = 'PF')




# Now we configure the job to keep ttbar events in all three decay
# modes. For hadronic, we will require that there be four
# reconstructed jets (the main hadronic trigger requires this anyway).
#
# For leptonic and dileptonic, we want to keep events with either one
# or two leptons (electrons or muons -- tau reconstruction is
# harder). What we will call a lepton depends on the mode: with one
# lepton, we need to cut a bit harder to increase the ttbar signal
# over the (W+jets) background. If we have two leptons, we don't have
# to cut as hard.
#
Beispiel #10
0
def addPat(process, isData, doRECO, doTTEffShrinkingConePFTau):
    sequence = cms.Sequence()

    # If running together with RECO
    # We get another kt6PFJets from PAT, and as-is they clash producing an exception
    runningWithReco = hasattr(process, "recoAllPFJets")
    if runningWithReco:
        process.recoAllPFJets.remove(process.kt6PFJets)
        process.recoPFJets.remove(process.kt6PFJets)

    process.load("PhysicsTools.PatAlgos.patSequences_cff")

    if runningWithReco:
        process.recoAllPFJets.replace(process.kt4PFJets,
                                      process.kt4PFJets * process.kt6PFJets)
        process.recoPFJets.replace(process.kt4PFJets,
                                   process.kt4PFJets * process.kt6PFJets)

#    process.load("PhysicsTools.PatAlgos.producersLayer1.patCandidates_cff")

# Calculate PF isolation of the muon
#process.muonPFIsolationSequence = MuonPFIsolation.addMuonPFIsolation(process, "muons", process.patMuons)
#sequence += process.muonPFIsolationSequence

    if doRECO:
        process.pfPileUpIso.PFCandidates = "particleFlowTmp"  # I don't know why I have to do this
        process.pfNoPileUpIso.bottomCollection = "particleFlowTmp"

    jetCorr = ["L1FastJet", "L2Relative", "L3Absolute"]
    if isData:
        jetCorr.append("L2L3Residual")
        #        coreTools.removeMCMatching(process, ["All"], outputInProcess=False)
        coreTools.removeMCMatching(process, ["All"], outputModules=[])
        ####    coreTools.removeCleaning(process, False)
        coreTools.removeCleaning(process, outputModules=[])
        ####    coreTools.removeSpecificPATObjects(process, ["Electrons", "Photons", "METs"], False)
        coreTools.removeSpecificPATObjects(process,
                                           ["Electrons", "Photons", "METs"],
                                           outputModules=[])
    tauTools.addTauCollection(process,
                              cms.InputTag('hpsPFTauProducer'),
                              algoLabel="hps",
                              typeLabel="PFTau")

    jetTools.switchJetCollection(process,
                                 cms.InputTag('ak5PFJets'),
                                 doJTA=True,
                                 doBTagging=True,
                                 jetCorrLabel=('AK5PF', jetCorr),
                                 doType1MET=False,
                                 genJetCollection=cms.InputTag("ak5GenJets"),
                                 doJetID=False,
                                 jetIdLabel="ak5",
                                 outputModules=[])

    # If the reference tau should be the old TTEff shrinking cone
    # if doTTEffShrinkingConePFTau:
    #     process.patTaus.tauSource = "TTEffShrinkingConePFTauProducer"
    #     for module in [process.tauIsoDepositPFCandidates, process.tauIsoDepositPFChargedHadrons, process.tauIsoDepositPFGammas, process.tauIsoDepositPFNeutralHadrons]:
    #         module.src = "TTEffShrinkingConePFTauProducer"
    #         module.ExtractorPSet.tauSource = "TTEffShrinkingConePFTauProducer"
    #     process.tauMatch.src = "TTEffShrinkingConePFTauProducer"
    #     process.patTaus.tauIDSources.leadingPionPtCut = "TTEffPFTauDiscriminationByLeadingPionPtCut"
    #     process.patTaus.tauIDSources.byIsolationUsingLeadingPion = "TTEffPFTauDiscriminationByIsolationUsingLeadingPion"
    #     process.patTaus.tauIDSources.leadingTrackFinding = "TTEffPFTauDiscriminationByLeadingTrackFinding"
    #     process.patTaus.tauIDSources.againstMuon = "TTEffPFTauDiscriminationAgainstMuon"
    #     process.patTaus.tauIDSources.againstElectron = "TTEffPFTauDiscriminationAgainstElectron"
    #     process.selectedPatTaus.cut = "pt() > 15 && abs(eta()) < 2.5 && tauID('leadingPionPtCut')"

    sequence += process.patDefaultSequence
    return sequence
def createProcess(runOnMC, runCHS, correctMETWithT1, processCaloJets, globalTag):

  ## import skeleton process
  from PhysicsTools.PatAlgos.patTemplate_cfg import process

  # load the PAT config
  process.load("PhysicsTools.PatAlgos.patSequences_cff")
  process.load("JetMETCorrections.Configuration.JetCorrectionProducers_cff")

  # Do some CHS stuff
  process.ak5PFchsL1Fastjet  = process.ak5PFL1Fastjet.clone(algorithm = 'AK5PFchs')
  process.ak5PFchsL2Relative = process.ak5PFL2Relative.clone(algorithm = 'AK5PFchs')
  process.ak5PFchsL3Absolute = process.ak5PFL3Absolute.clone(algorithm = 'AK5PFchs')
  process.ak5PFchsResidual   = process.ak5PFResidual.clone(algorithm = 'AK5PFchs')
  process.ak5PFchsL1FastL2L3 = cms.ESProducer(
      'JetCorrectionESChain',
      correctors = cms.vstring('ak5PFchsL1Fastjet', 'ak5PFchsL2Relative','ak5PFchsL3Absolute')
      )


  from PhysicsTools.SelectorUtils.pvSelector_cfi import pvSelector

  ## The good primary vertex filter ____________________________________________||
  ## This filter throw events with no primary vertex
  process.primaryVertexFilter = cms.EDFilter(
      "VertexSelector",
      src = cms.InputTag("offlinePrimaryVertices"),
      cut = cms.string("!isFake && ndof > 4 && abs(z) <= 24 && position.Rho <= 2"),
      filter = cms.bool(True)
      )

  process.goodOfflinePrimaryVertices = cms.EDFilter("PrimaryVertexObjectFilter",
      filterParams = pvSelector.clone( minNdof = cms.double(4.0), maxZ = cms.double(24.0) ),
      src = cms.InputTag('offlinePrimaryVertices')
      )

  # Configure PAT to use PF2PAT instead of AOD sources
  # this function will modify the PAT sequences.
  from PhysicsTools.PatAlgos.tools.coreTools import removeSpecificPATObjects, removeMCMatching
  from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT, adaptPFIsoElectrons, adaptPVs, usePFIso
  #from PhysicsTools.PatAlgos.tools.metTools import *

  def usePF2PATForAnalysis(jetAlgo, postfix, useTypeIMET, usePFNoPU):

    # Jet corrections
    # No L2L3 Residual on purpose
    if usePFNoPU:
      jetCorrections = ("%sPFchs" % algo, ['L1FastJet', 'L2Relative', 'L3Absolute'])
      postfix += "chs"
    else:
      jetCorrections = ("%sPF" % algo, ['L1FastJet', 'L2Relative', 'L3Absolute'])

    #if not runOnMC:
    #  jetCorrections[1].append('L2L3Residual')

    p = postfix

    usePF2PAT(process, runPF2PAT=True, jetAlgo=jetAlgo, runOnMC=runOnMC, postfix=p, jetCorrections=jetCorrections, typeIMetCorrections = useTypeIMET)
    getattr(process, "pfPileUp" + p).Enable = True
    getattr(process, "pfPileUp" + p).Vertices = 'goodOfflinePrimaryVertices'
    getattr(process, "pfPileUp" + p).checkClosestZVertex = cms.bool(False)

    getattr(process, "pfJets" + p).doAreaFastjet = cms.bool(True)
    getattr(process, "pfJets" + p).doRhoFastjet = False
    getattr(process, 'patJetCorrFactors' + p).rho = cms.InputTag("kt6PFJets", "rho") # Do not use kt6PFJetsPFlowAK5, it's not ok for L1FastJet.

    # top projections in PF2PAT:
    getattr(process,"pfNoPileUp" + p).enable = cms.bool(usePFNoPU)
    getattr(process,"pfNoMuon" + p).enable = True
    getattr(process,"pfNoElectron" + p).enable = True
    getattr(process,"pfNoTau" + p).enable = True
    getattr(process,"pfNoJet" + p).enable = True

    getattr(process,"patElectrons" + p).embedTrack = True

    getattr(process,"patMuons" + p).embedTrack = True
    # enable delta beta correction for muon selection in PF2PAT?
    getattr(process,"pfIsolatedMuons" + p).doDeltaBetaCorrection = True

    getattr(process, "patJets" + p).embedPFCandidates = False
    # Keep only jets with pt > 2 Gev
    getattr(process, "selectedPatJets" + p).cut = "pt > 2";

    # Use a cone of 0.3 for photon isolation
    #adaptPFIsoPhotons(process, applyPostfix(process, "patPhotons", postfix), postfix, "03")

    # 2012 Photon ID

    # Electron conversion
    setattr(process, "patConversions" + p, cms.EDProducer("PATConversionProducer",
        # input collection
        electronSource = cms.InputTag("selectedPatElectrons" + p)
    ))

    # Switch electron isolation to dR = 0.3, for PF2PAT
    getattr(process, "pfIsolatedElectrons" + p).isolationValueMapsCharged = cms.VInputTag(cms.InputTag("elPFIsoValueCharged03PFId" + p))
    getattr(process, "pfIsolatedElectrons" + p).deltaBetaIsolationValueMap = cms.InputTag("elPFIsoValuePU03PFId" + p)
    getattr(process, "pfIsolatedElectrons" + p).isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("elPFIsoValueNeutral03PFId" + p), cms.InputTag("elPFIsoValueGamma03PFId" + p))

    getattr(process, "pfElectrons" + p).isolationValueMapsCharged  = cms.VInputTag(cms.InputTag("elPFIsoValueCharged03PFId" + p))
    getattr(process, "pfElectrons" + p).deltaBetaIsolationValueMap = cms.InputTag("elPFIsoValuePU03PFId" + p)
    getattr(process, "pfElectrons" + p).isolationValueMapsNeutral  = cms.VInputTag(cms.InputTag( "elPFIsoValueNeutral03PFId" + p), cms.InputTag("elPFIsoValueGamma03PFId" + p))

    # ... And for PAT
    adaptPFIsoElectrons(process, getattr(process, "pfElectrons" + p), p, "03")

##there used to be a modulo to keep track of muons gen info, doesnt work anymore and we don't use that info - so removed for now.
    setattr(process, "patMuonsLoose" + p, getattr(process, "patMuons" + p).clone(
        pfMuonSource = cms.InputTag("pfMuons" + p),
        embedGenMatch = False,
        addGenMatch = False
      )
    )

    setattr(process, "selectedPatMuonsLoose" + p, getattr(process, "selectedPatMuons" + p).clone(
        src = cms.InputTag("patMuonsLoose" + p)
      )
    )
    sequence = getattr(process, "patDefaultSequence" + p)

    sequence += getattr(process, "patMuonsLoose" + p)

    sequence += (getattr(process, "selectedPatMuonsLoose" + p))

    setattr(process, "patElectronsLoose" + p, getattr(process, "patElectrons" + p).clone(
        pfElectronSource = cms.InputTag("pfElectrons" + p)
      )
    )
    setattr(process, "selectedPatElectronsLoose" + p, getattr(process, "selectedPatElectrons" + p).clone(
        src = cms.InputTag("patElectronsLoose" + p)
      )
    )
    adaptPFIsoElectrons(process, getattr(process, "patElectronsLoose" + p), postfix, "03")
    sequence = getattr(process, "patDefaultSequence" + p)
    sequence += (getattr(process, "patElectronsLoose" + p) * getattr(process, "selectedPatElectronsLoose" + p))


    # Setup quark gluon tagger
    #process.load('QuarkGluonTagger.EightTeV.QGTagger_RecoJets_cff')
    #cloneProcessingSnippet(process, process.QuarkGluonTagger, p)
    #getattr(process, "QGTagger" + p).srcJets = cms.InputTag("selectedPatJets" + p)
    #getattr(process, "QGTagger" + p).isPatJet = cms.untracked.bool(True)
    #getattr(process, "QGTagger" + p).useCHS = cms.untracked.bool(usePFNoPU)

    ## Remove the processing of primary vertices, as it's already what we do here
    #getattr(process, 'QGTagger' + p).srcPV = cms.InputTag('goodOfflinePrimaryVertices')
    #getattr(process, 'QuarkGluonTagger' + p).remove(getattr(process, 'goodOfflinePrimaryVerticesQG' + p))

    if not runOnMC:
      if 'L2L3Residual' in jetCorrections:
        getattr(process, 'patPFJetMETtype1p2Corr' + p).jetCorrLabel = 'L2L3Residual'
      getattr(process, 'patPFMet' + p).addGenMET = cms.bool(False)

    names = ["Taus"]
    #if jetAlgo != "AK5":
      #names += ["Electrons", "Muons"]
    if len(names) > 0:
      removeSpecificPATObjects(process, names = names, outputModules = ['out'], postfix = p) 

    adaptPVs(process, pvCollection = cms.InputTag("goodOfflinePrimaryVertices"), postfix = p)

    getattr(process, "patDefaultSequence" + p).replace(getattr(process, "selectedPatElectrons" + p), getattr(process, "selectedPatElectrons" + p) + getattr(process, "patConversions" + p))

    #getattr(process, "patDefaultSequence" + p).replace(getattr(process, "selectedPatJets" + p), getattr(process, "selectedPatJets" + p) + getattr(process, "QuarkGluonTagger" + p))

    return getattr(process, "patPF2PATSequence" + p)

  if correctMETWithT1:
    process.load("PhysicsTools.PatUtils.patPFMETCorrections_cff")
    
  from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet

  print "##########################"
  print "PF jets with PF2PAT"
  print "Using Type I met" if correctMETWithT1 else "NOT using Type I met"
  print "##########################"

  #runCHS = False

  #postfixes = {'PFlowAK5': 'AK5', 'PFlowAK7': 'AK7'}
  postfixes = {'PFlowAK5': 'AK5'}

  # Setup quark gluon tagger
  process.load('QuarkGluonTagger.EightTeV.QGTagger_RecoJets_cff')

  process.sequence_chs = cms.Sequence()
  process.sequence_nochs = cms.Sequence()
  for p, algo in postfixes.items():
    process.sequence_nochs += usePF2PATForAnalysis(jetAlgo=algo, postfix=p, usePFNoPU=False, useTypeIMET=correctMETWithT1)
    if runCHS:
      process.sequence_chs   += usePF2PATForAnalysis(jetAlgo=algo, postfix=p, usePFNoPU=True, useTypeIMET=correctMETWithT1)

    setattr(process, 'QGTagger' + p, process.QGTagger.clone())
    getattr(process, "QGTagger" + p).srcJets = cms.InputTag("selectedPatJets" + p)
    getattr(process, "QGTagger" + p).isPatJet = cms.untracked.bool(True)
    getattr(process, "QGTagger" + p).useCHS = cms.untracked.bool(False)

    process.QuarkGluonTagger.replace(process.QGTagger, getattr(process, 'QGTagger' + p))

    if runCHS:
      chsP = p + "chs"

      setattr(process, 'QGTagger' + chsP, process.QGTagger.clone())
      getattr(process, "QGTagger" + chsP).srcJets = cms.InputTag("selectedPatJets" + chsP)
      getattr(process, "QGTagger" + chsP).isPatJet = cms.untracked.bool(True)
      getattr(process, "QGTagger" + chsP).useCHS = cms.untracked.bool(True)

      process.QuarkGluonTagger.replace(getattr(process, 'QGTagger' + p), getattr(process, 'QGTagger' + p) + getattr(process, 'QGTagger' + chsP))

  print "##########################"
  print "Calo jets" if processCaloJets else "No processing of calo jets"
  print "##########################"

  usePFIso(process, "")
  #adaptPFIsoPhotons(process,  process.patPhotons, "", "03")

  if processCaloJets:

    # No L2L3 Residual on purpose
    jetCorrections = ('AK5Calo', ['L1Offset', 'L2Relative', 'L3Absolute'])

    addJetCollection(process, cms.InputTag('ak7CaloJets'),
        'AK7',
        'Calo',
        doJTA            = True,
        doBTagging       = True,
        jetCorrLabel     = jetCorrections,
        doType1MET       = correctMETWithT1,
        doL1Cleaning     = False,
        doL1Counters     = False,
        genJetCollection = cms.InputTag("ak7GenJets"),
        doJetID          = True,
        jetIdLabel       = "ak7"
        )

    switchJetCollection(process, cms.InputTag('ak5CaloJets'),
        doJTA            = True,
        doBTagging       = True,
        jetCorrLabel     = jetCorrections,
        doType1MET       = correctMETWithT1,
        genJetCollection = cms.InputTag("ak5GenJets"),
        doJetID          = True,
        jetIdLabel       = "ak5"
        )

    process.selectedPatJets.cut = "pt > 2"
    process.selectedPatJetsAK7Calo.cut = "pt > 2"

  else:
    removeSpecificPATObjects(process, names = ['Jets', 'METs'])

  if not runOnMC:
    # Remove MC Matching
    removeMCMatching(process, names = ["All"])

  removeSpecificPATObjects(process, names = ['Electrons', 'Muons', 'Taus'])

  if runCHS:
    print "##########################"
    print "Running CHS sequence"
    print "##########################"

  process.analysisSequence = cms.Sequence()

  process.analysisSequence *= process.sequence_nochs
  if runCHS:
    process.analysisSequence *= process.sequence_chs

  # Quark Gluon tagging
  process.analysisSequence *= process.QuarkGluonTagger

  # Add default pat sequence to our path
  # This brings to life TcMET, Calo jets and Photons
  process.analysisSequence *= process.patDefaultSequence

  # Add our PhotonIsolationProducer to the analysisSequence. This producer compute pf isolations
  # for our photons
  process.photonPFIsolation = cms.EDProducer("PhotonIsolationProducer",
      src = cms.InputTag("selectedPatPhotons")
      )

  process.analysisSequence *= process.photonPFIsolation

  # Filtering

  # require physics declared
  process.load('HLTrigger.special.hltPhysicsDeclared_cfi')
  process.hltPhysicsDeclared.L1GtReadoutRecordTag = 'gtDigis'

  # require scraping filter
  process.scrapingVeto = cms.EDFilter("FilterOutScraping",
      applyfilter = cms.untracked.bool(True),
      debugOn = cms.untracked.bool(False),
      numtrack = cms.untracked.uint32(10),
      thresh = cms.untracked.double(0.25)
      )

  # Count events
  process.nEventsTotal    = cms.EDProducer("EventCountProducer")
  process.nEventsFiltered = cms.EDProducer("EventCountProducer")

  # MET Filters
  process.load("RecoMET.METFilters.metFilters_cff")

  # HCAL Laser filter : work only on Winter13 rereco
  process.load("EventFilter.HcalRawToDigi.hcallaserFilterFromTriggerResult_cff")

  #needed fot photon energy regression calculation
  process.load('Calibration.EleNewEnergiesProducer.elenewenergiesproducer_cfi')
  #getattr(process,"patPhotons" + p)
  process.patPhotons.userData.userFloats.src = [
        cms.InputTag("eleNewEnergiesProducer","energySCEleJoshPhoSemiParamV5ecorr")
            ]
## uncomment to run interactive
##  process.eleNewEnergiesProducer.regrPhoJoshV5_SemiParamFile = cms.string('../../../../src/HiggsAnalysis/GBRLikelihoodEGTools/data/regweights_v5_forest_ph.root')
##  process.eleNewEnergiesProducer.regrEleJoshV5_SemiParamFile = cms.string('../../../../src/HiggsAnalysis/GBRLikelihoodEGTools/data/regweights_v5_forest_ele.root')

        
  process.eleNewEnergiesProducer.electronCollection = getattr(process,"patPhotons" + p).photonSource

  # Let it run
  process.p = cms.Path(
      process.nEventsTotal +

      # Filters
      process.hcalfilter +
      process.primaryVertexFilter +
      process.scrapingVeto +
      process.metFilters +

      process.goodOfflinePrimaryVertices +
      # photon energy regression
      process.eleNewEnergiesProducer +
      # Physics
      process.analysisSequence +

      process.nEventsFiltered
      )

  if runOnMC:
    process.p.remove(process.hcalfilter)
    process.p.remove(process.scrapingVeto)

  # Add PF2PAT output to the created file
  from PhysicsTools.PatAlgos.patEventContent_cff import patEventContentNoCleaning
  #process.load("CommonTools.ParticleFlow.PF2PAT_EventContent_cff")
  process.out.outputCommands = cms.untracked.vstring('drop *',
      'keep *_photonCore_*_*',
      'keep double_kt6*Jets*_rho_*',
      'keep *_goodOfflinePrimaryVertices_*_*',
      'keep recoPFCandidates_particleFlow_*_*',
      # Content of *patEventContentNoCleaning
      'keep *_selectedPatPhotons*_*_*', 'keep *_selectedPatElectrons*_*_*', 'keep *_selectedPatMuons*_*_*', 'keep *_selectedPatTaus*_*_*', 'keep *_selectedPatJets*_*_*', 'drop *_selectedPatJets_pfCandidates_*', 'drop *_*PF_caloTowers_*', 'drop *_*JPT_pfCandidates_*', 'drop *_*Calo_pfCandidates_*', 'keep *_patMETs*_*_*', 'keep *_selectedPatPFParticles*_*_*', 'keep *_selectedPatTrackCands*_*_*',
      'keep *_cleanPatPhotons*_*_*', 'keep *_cleanPatElectrons*_*_*', 'keep *_cleanPatMuons*_*_*', 'keep *_cleanPatTaus*_*_*',
      'keep *_cleanPatJets*_*_*', 'keep *_cleanPatHemispheres*_*_*', 'keep *_cleanPatPFParticles*_*_*',
      'keep *_cleanPatTrackCands*_*_*',
      'drop *_*PFlow_caloTowers_*',
      # Type I residual
      'drop *_selectedPatJetsForMET*_*_PAT',
      'keep *_patPFMet*_*_PAT', # Keep raw met
      # Trigger
      'keep *_TriggerResults_*_HLT',
      # Debug
      #'keep *_pf*_*_PAT'
      # Photon ID
      'keep *_patConversions*_*_*',
      'keep *_photonPFIsolation*_*_*',
      # Quark Gluon tagging
      'keep *_QGTagger*_*_*',
      'drop *_kt6PFJetsIsoQG_*_PAT',
      'drop *_kt6PFJetsQG_*_PAT',
      # MC truth
      'keep *_genParticles_*_*',
      # RecHits
      'keep *EcalRecHit*_*_*_*',
      # Beam spot
      'keep *_offlineBeamSpot_*_*',
      #photon energy regression
      'keep *_eleNewEnergiesProducer_*_*' 
      )

  if runOnMC:
    process.out.outputCommands.extend(['keep *_addPileupInfo_*_*', 'keep *_generator_*_*'])

  # switch on PAT trigger
  # from PhysicsTools.PatAlgos.tools.trigTools import switchOnTrigger
  # switchOnTrigger( process )

  ## ------------------------------------------------------
  #  In addition you usually want to change the following
  #  parameters:
  ## ------------------------------------------------------
  #
  process.GlobalTag.globaltag = "%s::All" % (globalTag) ##  (according to https://twiki.cern.ch/twiki/bin/view/CMS/SWGuideFrontierConditions)
  #                                         ##
  #process.source.fileNames =  cms.untracked.vstring('file:input_data.root')  ##  (e.g. 'file:AOD.root')
  #                                         ##
  process.maxEvents.input = 2500
  #                                         ##
  #   process.out.outputCommands = [ ... ]  ##  (e.g. taken from PhysicsTools/PatAlgos/python/patEventContent_cff.py)
  #                                         ##
  process.options.wantSummary = False   ##  (to suppress the long output at the end of the job)
  process.MessageLogger.cerr.FwkReport.reportEvery = 1000

  # Remove annoying ecalLaser messages
  process.MessageLogger.suppressError = cms.untracked.vstring ('ecalLaserCorrFilter')

  return process
Beispiel #12
0
def addPat(process, isData, doRECO, doTTEffShrinkingConePFTau):
    sequence = cms.Sequence()

    # If running together with RECO
    # We get another kt6PFJets from PAT, and as-is they clash producing an exception
    runningWithReco = hasattr(process, "recoAllPFJets")
    if runningWithReco:
        process.recoAllPFJets.remove(process.kt6PFJets)
        process.recoPFJets.remove(process.kt6PFJets)
    
    process.load("PhysicsTools.PatAlgos.patSequences_cff")

    if runningWithReco:
        process.recoAllPFJets.replace(process.kt4PFJets, process.kt4PFJets*process.kt6PFJets)
        process.recoPFJets.replace(process.kt4PFJets, process.kt4PFJets*process.kt6PFJets)

#    process.load("PhysicsTools.PatAlgos.producersLayer1.patCandidates_cff")

    # Calculate PF isolation of the muon
    #process.muonPFIsolationSequence = MuonPFIsolation.addMuonPFIsolation(process, "muons", process.patMuons)
    #sequence += process.muonPFIsolationSequence
    
    if doRECO:
        process.pfPileUpIso.PFCandidates = "particleFlowTmp" # I don't know why I have to do this
        process.pfNoPileUpIso.bottomCollection = "particleFlowTmp"

    jetCorr = ["L1FastJet", "L2Relative", "L3Absolute"]
    if isData:
        jetCorr.append("L2L3Residual")
#        coreTools.removeMCMatching(process, ["All"], outputInProcess=False)
	coreTools.removeMCMatching(process, ["All"], outputModules = [])
####    coreTools.removeCleaning(process, False)
        coreTools.removeCleaning(process, outputModules = [])
####    coreTools.removeSpecificPATObjects(process, ["Electrons", "Photons", "METs"], False)
        coreTools.removeSpecificPATObjects(process, ["Electrons", "Photons", "METs"], outputModules = [])
    tauTools.addTauCollection(process, cms.InputTag('hpsPFTauProducer'),
                              algoLabel = "hps", typeLabel = "PFTau")
    
    jetTools.switchJetCollection(process, cms.InputTag('ak5PFJets'),   
                                 doJTA            = True,            
                                 doBTagging       = True,            
                                 jetCorrLabel     = ('AK5PF', jetCorr),
                                 doType1MET       = False,            
                                 genJetCollection = cms.InputTag("ak5GenJets"),
                                 doJetID      = False,
                                 jetIdLabel   = "ak5",
                                 outputModules = [])
    
    # If the reference tau should be the old TTEff shrinking cone
    # if doTTEffShrinkingConePFTau:
    #     process.patTaus.tauSource = "TTEffShrinkingConePFTauProducer"
    #     for module in [process.tauIsoDepositPFCandidates, process.tauIsoDepositPFChargedHadrons, process.tauIsoDepositPFGammas, process.tauIsoDepositPFNeutralHadrons]:
    #         module.src = "TTEffShrinkingConePFTauProducer"
    #         module.ExtractorPSet.tauSource = "TTEffShrinkingConePFTauProducer"
    #     process.tauMatch.src = "TTEffShrinkingConePFTauProducer"
    #     process.patTaus.tauIDSources.leadingPionPtCut = "TTEffPFTauDiscriminationByLeadingPionPtCut"
    #     process.patTaus.tauIDSources.byIsolationUsingLeadingPion = "TTEffPFTauDiscriminationByIsolationUsingLeadingPion"
    #     process.patTaus.tauIDSources.leadingTrackFinding = "TTEffPFTauDiscriminationByLeadingTrackFinding"
    #     process.patTaus.tauIDSources.againstMuon = "TTEffPFTauDiscriminationAgainstMuon"
    #     process.patTaus.tauIDSources.againstElectron = "TTEffPFTauDiscriminationAgainstElectron"
    #     process.selectedPatTaus.cut = "pt() > 15 && abs(eta()) < 2.5 && tauID('leadingPionPtCut')"

    sequence += process.patDefaultSequence
    return sequence
Beispiel #13
0
def usePF2PAT_WREdition(
        process,
        runPF2PAT=True,
        jetAlgo='AK5',
        runOnMC=True,
        postfix="",
        jetCorrections=('AK5PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute']),
        pvCollection=cms.InputTag('offlinePrimaryVertices'),
        typeIMetCorrections=False,
        outputModules=['out']):

    # -------- CORE ---------------
    if runPF2PAT:
        process.load("CommonTools.ParticleFlow.PF2PAT_cff")
        #add Pf2PAT *before* cloning so that overlapping modules are cloned too
        #process.patDefaultSequence.replace( process.patCandidates, process.PF2PAT+process.patCandidates)
        process.patPF2PATSequence = cms.Sequence(process.PF2PAT +
                                                 process.patDefaultSequence)
    else:
        process.patPF2PATSequence = cms.Sequence(process.patDefaultSequence)

    if not postfix == "":
        from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet
        cloneProcessingSnippet(process, process.patPF2PATSequence, postfix)
        #delete everything pat PF2PAT modules! if you want to test the postfixing for completeness
        #from PhysicsTools.PatAlgos.tools.helpers import listModules,listSequences
        #for module in listModules(process.patDefaultSequence):
        #    if not module.label() is None: process.__delattr__(module.label())
        #for sequence in listSequences(process.patDefaultSequence):
        #    if not sequence.label() is None: process.__delattr__(sequence.label())
        #del process.patDefaultSequence

    removeCleaning(process, postfix=postfix, outputModules=outputModules)

    # -------- OBJECTS ------------
    # Muons
    #adaptPFMuons(process,
    #             applyPostfix(process,"patMuons",postfix),
    #             postfix)

    # Electrons
    #adaptPFElectrons(process,
    #                 applyPostfix(process,"patElectrons",postfix),
    #                 postfix)

    # Photons
    print "Temporarily switching off photons completely"

    removeSpecificPATObjects(process,
                             names=['Photons', 'Taus', "Muons", "Electrons"],
                             outputModules=outputModules,
                             postfix=postfix)
    removeIfInSequence(process, "patPhotonIsolation", "patDefaultSequence",
                       postfix)

    # Jets
    if runOnMC:
        if ishpsPFTau:
            switchToPFJets(process,
                           cms.InputTag('pfNoTau' + postfix),
                           jetAlgo,
                           postfix=postfix,
                           jetCorrections=jetCorrections,
                           type1=typeIMetCorrections,
                           outputModules=outputModules)
        else:
            switchToPFJets(process,
                           cms.InputTag('pfJets' + postfix),
                           jetAlgo,
                           postfix=postfix,
                           jetCorrections=jetCorrections,
                           type1=typeIMetCorrections,
                           outputModules=outputModules)
            applyPostfix(process, "patDefaultSequence", postfix).replace(
                applyPostfix(process, "patJetGenJetMatch", postfix),
                getattr(process, "genForPF2PATSequence") *
                applyPostfix(process, "patJetGenJetMatch", postfix))
    else:
        if not 'L2L3Residual' in jetCorrections[1]:
            print '#################################################'
            print 'WARNING! Not using L2L3Residual but this is data.'
            print 'If this is okay with you, disregard this message.'
            print '#################################################'
        if ishpsPFTau:
            switchToPFJets(process,
                           cms.InputTag('pfNoTau' + postfix),
                           jetAlgo,
                           postfix=postfix,
                           jetCorrections=jetCorrections,
                           type1=typeIMetCorrections,
                           outputModules=outputModules)
        else:
            switchToPFJets(process,
                           cms.InputTag('pfJets' + postfix),
                           jetAlgo,
                           postfix=postfix,
                           jetCorrections=jetCorrections,
                           type1=typeIMetCorrections,
                           outputModules=outputModules)

    # Taus
    #adaptPFTaus( process, tauType='shrinkingConePFTau', postfix=postfix )
    #adaptPFTaus( process, tauType='fixedConePFTau', postfix=postfix )
    if ishpsPFTau:
        adaptPFTaus(process, tauType='hpsPFTau', postfix=postfix)

    # MET
    switchToPFMET(process,
                  cms.InputTag('pfMET' + postfix),
                  type1=typeIMetCorrections,
                  postfix=postfix)

    # Unmasked PFCandidates
    addPFCandidates(process,
                    cms.InputTag('pfNoJet' + postfix),
                    patLabel='PFParticles' + postfix,
                    cut="",
                    postfix=postfix)

    # adapt primary vertex collection
    adaptPVs(process, pvCollection=pvCollection, postfix=postfix)

    if runOnMC:
        process.load("CommonTools.ParticleFlow.genForPF2PAT_cff")
        getattr(process, "patDefaultSequence" + postfix).replace(
            applyPostfix(process, "patCandidates",
                         postfix), process.genForPF2PATSequence +
            applyPostfix(process, "patCandidates", postfix))
    else:
        removeMCMatchingPF2PAT(process,
                               postfix=postfix,
                               outputModules=outputModules)

    print "Done: PF2PAT interfaced to PAT, postfix=", postfix
Beispiel #14
0
def usePF2PAT_WREdition(process, runPF2PAT=True, jetAlgo='AK5', runOnMC=True, postfix="", jetCorrections=('AK5PFchs', ['L1FastJet','L2Relative','L3Absolute']), pvCollection=cms.InputTag('offlinePrimaryVertices'), typeIMetCorrections=False, outputModules=['out']):

    # -------- CORE ---------------
    if runPF2PAT:
        process.load("CommonTools.ParticleFlow.PF2PAT_cff")
        #add Pf2PAT *before* cloning so that overlapping modules are cloned too
        #process.patDefaultSequence.replace( process.patCandidates, process.PF2PAT+process.patCandidates)
        process.patPF2PATSequence = cms.Sequence( process.PF2PAT + process.patDefaultSequence)
    else:
        process.patPF2PATSequence = cms.Sequence( process.patDefaultSequence )

    if not postfix == "":
        from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet
        cloneProcessingSnippet(process, process.patPF2PATSequence, postfix)
        #delete everything pat PF2PAT modules! if you want to test the postfixing for completeness
        #from PhysicsTools.PatAlgos.tools.helpers import listModules,listSequences
        #for module in listModules(process.patDefaultSequence):
        #    if not module.label() is None: process.__delattr__(module.label())
        #for sequence in listSequences(process.patDefaultSequence):
        #    if not sequence.label() is None: process.__delattr__(sequence.label())
        #del process.patDefaultSequence

    removeCleaning(process, postfix=postfix, outputModules=outputModules)

    # -------- OBJECTS ------------
    # Muons
    #adaptPFMuons(process,
    #             applyPostfix(process,"patMuons",postfix),
    #             postfix)

    # Electrons
    #adaptPFElectrons(process,
    #                 applyPostfix(process,"patElectrons",postfix),
    #                 postfix)

    # Photons
    print "Temporarily switching off photons completely"

    removeSpecificPATObjects(process,names=['Photons', 'Taus', "Muons", "Electrons"],outputModules=outputModules,postfix=postfix)
    removeIfInSequence(process,"patPhotonIsolation","patDefaultSequence",postfix)

    # Jets
    if runOnMC :
       if ishpsPFTau:
         switchToPFJets( process, cms.InputTag('pfNoTau'+postfix), jetAlgo, postfix=postfix,
                        jetCorrections=jetCorrections, type1=typeIMetCorrections, outputModules=outputModules )
       else:
         switchToPFJets( process, cms.InputTag('pfJets'+postfix), jetAlgo, postfix=postfix,
                           jetCorrections=jetCorrections, type1=typeIMetCorrections, outputModules=outputModules )
         applyPostfix(process,"patDefaultSequence",postfix).replace(
            applyPostfix(process,"patJetGenJetMatch",postfix),
            getattr(process,"genForPF2PATSequence") *
            applyPostfix(process,"patJetGenJetMatch",postfix)
            )
    else :
        if not 'L2L3Residual' in jetCorrections[1]:
            print '#################################################'
            print 'WARNING! Not using L2L3Residual but this is data.'
            print 'If this is okay with you, disregard this message.'
            print '#################################################'
        if ishpsPFTau:
            switchToPFJets( process, cms.InputTag('pfNoTau'+postfix), jetAlgo, postfix=postfix,
                            jetCorrections=jetCorrections, type1=typeIMetCorrections, outputModules=outputModules )
        else:
            switchToPFJets( process, cms.InputTag('pfJets'+postfix), jetAlgo, postfix=postfix,
                            jetCorrections=jetCorrections, type1=typeIMetCorrections, outputModules=outputModules )

    # Taus
    #adaptPFTaus( process, tauType='shrinkingConePFTau', postfix=postfix )
    #adaptPFTaus( process, tauType='fixedConePFTau', postfix=postfix )
    if ishpsPFTau:
        adaptPFTaus( process, tauType='hpsPFTau', postfix=postfix )

    # MET
    switchToPFMET(process, cms.InputTag('pfMET'+postfix), type1=typeIMetCorrections, postfix=postfix)

    # Unmasked PFCandidates
    addPFCandidates(process,cms.InputTag('pfNoJet'+postfix),patLabel='PFParticles'+postfix,cut="",postfix=postfix)

    # adapt primary vertex collection
    adaptPVs(process, pvCollection=pvCollection, postfix=postfix)

    if runOnMC:
        process.load("CommonTools.ParticleFlow.genForPF2PAT_cff")
        getattr(process, "patDefaultSequence"+postfix).replace(
            applyPostfix(process,"patCandidates",postfix),
            process.genForPF2PATSequence+applyPostfix(process,"patCandidates",postfix)
            )
    else:
        removeMCMatchingPF2PAT(process,postfix=postfix,outputModules=outputModules)

    print "Done: PF2PAT interfaced to PAT, postfix=", postfix
def usePF2PAT_WREdition(
        process,
        runPF2PAT=True,
        jetAlgo='AK5',
        runOnMC=True,
        postfix="",
        jetCorrections=('AK5PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute']),
        pvCollection=cms.InputTag('offlinePrimaryVertices'),
        typeIMetCorrections=False,
        outputModules=['out']):
    # PLEASE DO NOT CLOBBER THIS FUNCTION WITH CODE SPECIFIC TO A GIVEN PHYSICS OBJECT.
    # CREATE ADDITIONAL FUNCTIONS IF NEEDED.
    """Switch PAT to use PF2PAT instead of AOD sources. if 'runPF2PAT' is true, we'll also add PF2PAT in front of the PAT sequence"""

    # -------- CORE ---------------
    if runPF2PAT:
        process.load("CommonTools.ParticleFlow.PF2PAT_cff")
        process.patPF2PATSequence = cms.Sequence(process.PF2PAT +
                                                 process.patDefaultSequence)
    else:
        process.patPF2PATSequence = cms.Sequence(process.patDefaultSequence)

    if not postfix == "":
        from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet
        cloneProcessingSnippet(process, process.patPF2PATSequence, postfix)

    removeCleaning(process, postfix=postfix, outputModules=outputModules)

    # Photons
    print "Temporarily switching off photons completely"

    removeSpecificPATObjects(process,
                             names=['Photons', 'Taus', "Muons", "Electrons"],
                             outputModules=outputModules,
                             postfix=postfix)
    removeIfInSequence(process, "patPhotonIsolation", "patDefaultSequence",
                       postfix)

    # Jets
    if runOnMC:
        switchToPFJets(process,
                       cms.InputTag('pfNoTau' + postfix),
                       jetAlgo,
                       postfix=postfix,
                       jetCorrections=jetCorrections,
                       type1=typeIMetCorrections,
                       outputModules=outputModules)
        applyPostfix(process, "patDefaultSequence", postfix).replace(
            applyPostfix(process, "patJetGenJetMatch", postfix),
            getattr(process, "genForPF2PATSequence") *
            applyPostfix(process, "patJetGenJetMatch", postfix))
    else:
        if not 'L2L3Residual' in jetCorrections[1]:
            print '#################################################'
            print 'WARNING! Not using L2L3Residual but this is data.'
            print 'If this is okay with you, disregard this message.'
            print '#################################################'
        switchToPFJets(process,
                       cms.InputTag('pfNoTau' + postfix),
                       jetAlgo,
                       postfix=postfix,
                       jetCorrections=jetCorrections,
                       type1=typeIMetCorrections,
                       outputModules=outputModules)

    # Taus
    if ishpsPFTau:
        adaptPFTaus(process, tauType='hpsPFTau', postfix=postfix)

    # MET
    switchToPFMET(process,
                  cms.InputTag('pfMET' + postfix),
                  type1=typeIMetCorrections,
                  postfix=postfix)
    if not runOnMC:
        if hasattr(process, 'patPFMet' + postfix):
            getattr(process, 'patPFMet' + postfix).addGenMET = cms.bool(False)

    # Unmasked PFCandidates
    addPFCandidates(process,
                    cms.InputTag('pfNoJet' + postfix),
                    patLabel='PFParticles' + postfix,
                    cut="",
                    postfix=postfix)

    # adapt primary vertex collection
    adaptPVs(process, pvCollection=pvCollection, postfix=postfix)

    if runOnMC:
        process.load("CommonTools.ParticleFlow.genForPF2PAT_cff")
        getattr(process, "patDefaultSequence" + postfix).replace(
            applyPostfix(process, "patCandidates",
                         postfix), process.genForPF2PATSequence +
            applyPostfix(process, "patCandidates", postfix))
    else:
        removeMCMatchingPF2PAT(process,
                               postfix=postfix,
                               outputModules=outputModules)

    print "Done: PF2PAT interfaced to PAT, postfix=", postfix
Beispiel #16
0
    process.higgssequence = cms.Sequence(process.makeGenEvtHiggs * process.generatorHiggsFilter)
else:
    process.higgssequence = cms.Sequence()

if signal or higgsSignal or zGenInfo:
    process.ntupleInRecoSeq = cms.Sequence()
else:
    process.ntupleInRecoSeq = cms.Sequence(process.zsequence * process.writeNTuple)


####################################################################
## Remove all the tau stuff

from PhysicsTools.PatAlgos.tools.coreTools import removeSpecificPATObjects

removeSpecificPATObjects(process, names=["Taus", "Photons"], outputModules=[], postfix=pfpostfix)
# Remove the full pftau sequence as it is not needed for us
getattr(process, "patPF2PATSequence" + pfpostfix).remove(getattr(process, "pfTauPFJets08Region" + pfpostfix))
getattr(process, "patPF2PATSequence" + pfpostfix).remove(getattr(process, "pfTauPileUpVertices" + pfpostfix))
getattr(process, "patPF2PATSequence" + pfpostfix).remove(getattr(process, "pfTauTagInfoProducer" + pfpostfix))
getattr(process, "patPF2PATSequence" + pfpostfix).remove(getattr(process, "pfJetsPiZeros" + pfpostfix))
getattr(process, "patPF2PATSequence" + pfpostfix).remove(getattr(process, "pfJetsLegacyTaNCPiZeros" + pfpostfix))
getattr(process, "patPF2PATSequence" + pfpostfix).remove(getattr(process, "pfJetsLegacyHPSPiZeros" + pfpostfix))
getattr(process, "patPF2PATSequence" + pfpostfix).remove(getattr(process, "pfTausBase" + pfpostfix))
getattr(process, "patPF2PATSequence" + pfpostfix).remove(getattr(process, "hpsSelectionDiscriminator" + pfpostfix))
getattr(process, "patPF2PATSequence" + pfpostfix).remove(getattr(process, "hpsPFTauProducerSansRefs" + pfpostfix))
getattr(process, "patPF2PATSequence" + pfpostfix).remove(getattr(process, "hpsPFTauProducer" + pfpostfix))
getattr(process, "patPF2PATSequence" + pfpostfix).remove(
    getattr(process, "pfTausBaseDiscriminationByDecayModeFinding" + pfpostfix)
)
getattr(process, "patPF2PATSequence" + pfpostfix).remove(
Beispiel #17
0
    process.higgssequence = cms.Sequence()

if signal or higgsSignal or zGenInfo:
    process.ntupleInRecoSeq = cms.Sequence()
else:
    process.ntupleInRecoSeq = cms.Sequence(process.zsequence * process.writeNTuple)
    


####################################################################
## Remove all the tau stuff

from PhysicsTools.PatAlgos.tools.coreTools import removeSpecificPATObjects
removeSpecificPATObjects( process
                        , names = ['Taus', 'Photons']
                        , outputModules = []
                        , postfix = pfpostfix
                        )
if not createMvaMet:
    # Remove the full pftau sequence as it is not needed for us
    getattr(process,'patPF2PATSequence'+pfpostfix).remove(getattr(process,'pfTauPFJets08Region'+pfpostfix))
    getattr(process,'patPF2PATSequence'+pfpostfix).remove(getattr(process,'pfTauPileUpVertices'+pfpostfix))
    getattr(process,'patPF2PATSequence'+pfpostfix).remove(getattr(process,'pfTauTagInfoProducer'+pfpostfix))
    getattr(process,'patPF2PATSequence'+pfpostfix).remove(getattr(process,'pfJetsPiZeros'+pfpostfix))
    getattr(process,'patPF2PATSequence'+pfpostfix).remove(getattr(process,'pfJetsLegacyTaNCPiZeros'+pfpostfix))
    getattr(process,'patPF2PATSequence'+pfpostfix).remove(getattr(process,'pfJetsLegacyHPSPiZeros'+pfpostfix))
    getattr(process,'patPF2PATSequence'+pfpostfix).remove(getattr(process,'pfTausBase'+pfpostfix))
    getattr(process,'patPF2PATSequence'+pfpostfix).remove(getattr(process,'hpsSelectionDiscriminator'+pfpostfix))
    getattr(process,'patPF2PATSequence'+pfpostfix).remove(getattr(process,'hpsPFTauProducerSansRefs'+pfpostfix))
    getattr(process,'patPF2PATSequence'+pfpostfix).remove(getattr(process,'hpsPFTauProducer'+pfpostfix))
    getattr(process,'patPF2PATSequence'+pfpostfix).remove(getattr(process,'pfTausBaseDiscriminationByDecayModeFinding'+pfpostfix))
def createProcess(runOnMC, runCHS, correctMETWithT1, processCaloJets, processCA8Jets, globalTag):

  ## import skeleton process
  from PhysicsTools.PatAlgos.patTemplate_cfg import process

  # load the PAT config
  process.load("PhysicsTools.PatAlgos.patSequences_cff")
  process.load("JetMETCorrections.Configuration.JetCorrectionProducers_cff")

  # Do some CHS stuff
  process.ak5PFchsL1Fastjet  = process.ak5PFL1Fastjet.clone(algorithm = 'AK5PFchs')
  process.ak5PFchsL2Relative = process.ak5PFL2Relative.clone(algorithm = 'AK5PFchs')
  process.ak5PFchsL3Absolute = process.ak5PFL3Absolute.clone(algorithm = 'AK5PFchs')
  process.ak5PFchsResidual   = process.ak5PFResidual.clone(algorithm = 'AK5PFchs')
  process.ak5PFchsL1FastL2L3 = cms.ESProducer(
      'JetCorrectionESChain',
      correctors = cms.vstring('ak5PFchsL1Fastjet', 'ak5PFchsL2Relative','ak5PFchsL3Absolute')
      )


  from PhysicsTools.SelectorUtils.pvSelector_cfi import pvSelector

  ## The good primary vertex filter ____________________________________________||
  ## This filter throw events with no primary vertex
  process.primaryVertexFilter = cms.EDFilter(
      "VertexSelector",
      src = cms.InputTag("offlinePrimaryVertices"),
      cut = cms.string("!isFake && ndof > 4 && abs(z) <= 24 && position.Rho <= 2"),
      filter = cms.bool(True)
      )

  process.goodOfflinePrimaryVertices = cms.EDFilter("PrimaryVertexObjectFilter",
      filterParams = pvSelector.clone( minNdof = cms.double(4.0), maxZ = cms.double(24.0) ),
      src = cms.InputTag('offlinePrimaryVertices')
      )

  # Configure PAT to use PF2PAT instead of AOD sources
  # this function will modify the PAT sequences.
  from PhysicsTools.PatAlgos.tools.coreTools import removeSpecificPATObjects, removeMCMatching
  from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT, adaptPFIsoElectrons, adaptPVs, usePFIso
  #from PhysicsTools.PatAlgos.tools.metTools import *

  def usePF2PATForAnalysis(jetAlgo, postfix, useTypeIMET, usePFNoPU):

    # Jet corrections
    # No L2L3 Residual on purpose
    if usePFNoPU:
      jetCorrections = ("%sPFchs" % algo, ['L1FastJet', 'L2Relative', 'L3Absolute'])
      postfix += "chs"
    else:
      jetCorrections = ("%sPF" % algo, ['L1FastJet', 'L2Relative', 'L3Absolute'])

    #if not runOnMC:
    #  jetCorrections[1].append('L2L3Residual')

    p = postfix

    usePF2PAT(process, runPF2PAT=True, jetAlgo=jetAlgo, runOnMC=runOnMC, postfix=p, jetCorrections=jetCorrections, typeIMetCorrections = useTypeIMET)
    getattr(process, "pfPileUp" + p).Enable = True
    getattr(process, "pfPileUp" + p).Vertices = 'goodOfflinePrimaryVertices'
    getattr(process, "pfPileUp" + p).checkClosestZVertex = cms.bool(False)

    getattr(process, "pfJets" + p).doAreaFastjet = cms.bool(True)
    getattr(process, "pfJets" + p).doRhoFastjet = False
    getattr(process, 'patJetCorrFactors' + p).rho = cms.InputTag("kt6PFJets", "rho") # Do not use kt6PFJetsPFlowAK5, it's not ok for L1FastJet.

    # top projections in PF2PAT:
    getattr(process,"pfNoPileUp" + p).enable = cms.bool(usePFNoPU)
    getattr(process,"pfNoMuon" + p).enable = True
    getattr(process,"pfNoElectron" + p).enable = True
    getattr(process,"pfNoTau" + p).enable = True
    getattr(process,"pfNoJet" + p).enable = True

    getattr(process,"patElectrons" + p).embedTrack = True

    getattr(process,"patMuons" + p).embedTrack = True
    # enable delta beta correction for muon selection in PF2PAT?
    getattr(process,"pfIsolatedMuons" + p).doDeltaBetaCorrection = True

    getattr(process, "patJets" + p).embedPFCandidates = False
    # Keep only jets with pt > 2 Gev
    getattr(process, "selectedPatJets" + p).cut = "pt > 2";

    # Use a cone of 0.3 for photon isolation
    #adaptPFIsoPhotons(process, applyPostfix(process, "patPhotons", postfix), postfix, "03")

    # 2012 Photon ID

    # Electron conversion
    setattr(process, "patConversions" + p, cms.EDProducer("PATConversionProducer",
        # input collection
        electronSource = cms.InputTag("selectedPatElectrons" + p)
    ))

    # Switch electron isolation to dR = 0.3, for PF2PAT
    getattr(process, "pfIsolatedElectrons" + p).isolationValueMapsCharged = cms.VInputTag(cms.InputTag("elPFIsoValueCharged03PFId" + p))
    getattr(process, "pfIsolatedElectrons" + p).deltaBetaIsolationValueMap = cms.InputTag("elPFIsoValuePU03PFId" + p)
    getattr(process, "pfIsolatedElectrons" + p).isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("elPFIsoValueNeutral03PFId" + p), cms.InputTag("elPFIsoValueGamma03PFId" + p))

    getattr(process, "pfElectrons" + p).isolationValueMapsCharged  = cms.VInputTag(cms.InputTag("elPFIsoValueCharged03PFId" + p))
    getattr(process, "pfElectrons" + p).deltaBetaIsolationValueMap = cms.InputTag("elPFIsoValuePU03PFId" + p)
    getattr(process, "pfElectrons" + p).isolationValueMapsNeutral  = cms.VInputTag(cms.InputTag( "elPFIsoValueNeutral03PFId" + p), cms.InputTag("elPFIsoValueGamma03PFId" + p))

    # ... And for PAT
    adaptPFIsoElectrons(process, getattr(process, "pfElectrons" + p), p, "03")

    
    if runOnMC:
      cloneProcessingSnippet(process, getattr(process, "makePatMuons" + p), "Loose" + p, p)
      getattr(process, "muonMatchLoose" + p).src = cms.InputTag("pfMuons" + p)
      getattr(process, "patMuonsLoose" + p).pfMuonSource = cms.InputTag("pfMuons" + p)
      getattr(process, "patDefaultSequence" + p).replace(getattr(process, "makePatMuons" + p), getattr(process, "makePatMuons" + p) + getattr(process, "makePatMuonsLoose" + p))
    else:
      setattr(process, "patMuonsLoose" + p, getattr(process, "patMuons" + p).clone(
          pfMuonSource = cms.InputTag("pfMuons" + p)
        )
      )

    setattr(process, "selectedPatMuonsLoose" + p, getattr(process, "selectedPatMuons" + p).clone(
        src = cms.InputTag("patMuonsLoose" + p)
      )
    )
    sequence = getattr(process, "patDefaultSequence" + p)

    if not runOnMC:
      sequence += getattr(process, "patMuonsLoose" + p)

    sequence += (getattr(process, "selectedPatMuonsLoose" + p))

    setattr(process, "patElectronsLoose" + p, getattr(process, "patElectrons" + p).clone(
        pfElectronSource = cms.InputTag("pfElectrons" + p)
      )
    )
    setattr(process, "selectedPatElectronsLoose" + p, getattr(process, "selectedPatElectrons" + p).clone(
        src = cms.InputTag("patElectronsLoose" + p)
      )
    )
    adaptPFIsoElectrons(process, getattr(process, "patElectronsLoose" + p), postfix, "03")
    sequence = getattr(process, "patDefaultSequence" + p)
    sequence += (getattr(process, "patElectronsLoose" + p) * getattr(process, "selectedPatElectronsLoose" + p))


    #giulia turn off qg tagger
    ## Setup quark gluon tagger
    #process.load('QuarkGluonTagger.EightTeV.QGTagger_RecoJets_cff')
    #cloneProcessingSnippet(process, process.QuarkGluonTagger, p)
    #getattr(process, "QGTagger" + p).srcJets = cms.InputTag("selectedPatJets" + p)
    #getattr(process, "QGTagger" + p).isPatJet = cms.untracked.bool(True)
    #getattr(process, "QGTagger" + p).useCHS = cms.untracked.bool(usePFNoPU)

    ## Remove the processing of primary vertices, as it's already what we do here
    #getattr(process, 'QGTagger' + p).srcPV = cms.InputTag('goodOfflinePrimaryVertices')
    #getattr(process, 'QuarkGluonTagger' + p).remove(getattr(process, 'goodOfflinePrimaryVerticesQG' + p))

    if not runOnMC:
      if 'L2L3Residual' in jetCorrections:
        getattr(process, 'patPFJetMETtype1p2Corr' + p).jetCorrLabel = 'L2L3Residual'
      getattr(process, 'patPFMet' + p).addGenMET = cms.bool(False)

    names = ["Taus"]
    #if jetAlgo != "AK5":
      #names += ["Electrons", "Muons"]
    if len(names) > 0:
      removeSpecificPATObjects(process, names = names, outputModules = ['out'], postfix = p) 

    adaptPVs(process, pvCollection = cms.InputTag("goodOfflinePrimaryVertices"), postfix = p)

    getattr(process, "patDefaultSequence" + p).replace(getattr(process, "selectedPatElectrons" + p), getattr(process, "selectedPatElectrons" + p) + getattr(process, "patConversions" + p))

    #getattr(process, "patDefaultSequence" + p).replace(getattr(process, "selectedPatJets" + p), getattr(process, "selectedPatJets" + p) + getattr(process, "QuarkGluonTagger" + p))

    return getattr(process, "patPF2PATSequence" + p)

  if correctMETWithT1:
    process.load("PhysicsTools.PatUtils.patPFMETCorrections_cff")
    
  from PhysicsTools.PatAlgos.tools.helpers import cloneProcessingSnippet

  print "##########################"
  print "PF jets with PF2PAT"
  print "Using Type I met" if correctMETWithT1 else "NOT using Type I met"
  print "##########################"

  #runCHS = False

  postfixes = {'PFlowAK5': 'AK5'}
  #postfixes = {'PFlowAK5': 'AK5', 'PFlowAK7': 'AK7', 'PFlowCA8': 'CA8'}
  #postfixes = {'PFlowCA8': 'CA8'}

  ##giulia turn off qg tagger
  ## Setup quark gluon tagger
  #process.load('QuarkGluonTagger.EightTeV.QGTagger_RecoJets_cff')

  process.sequence_chs = cms.Sequence()
  process.sequence_nochs = cms.Sequence()
  for p, algo in postfixes.items():
    process.sequence_nochs += usePF2PATForAnalysis(jetAlgo=algo, postfix=p, usePFNoPU=False, useTypeIMET=correctMETWithT1)
    if runCHS:
      process.sequence_chs   += usePF2PATForAnalysis(jetAlgo=algo, postfix=p, usePFNoPU=True, useTypeIMET=correctMETWithT1)

  #  setattr(process, 'QGTagger' + p, process.QGTagger.clone())
  #  getattr(process, "QGTagger" + p).srcJets = cms.InputTag("selectedPatJets" + p)
  #  getattr(process, "QGTagger" + p).isPatJet = cms.untracked.bool(True)
  #  getattr(process, "QGTagger" + p).useCHS = cms.untracked.bool(False)
  #
  #  process.QuarkGluonTagger.replace(process.QGTagger, getattr(process, 'QGTagger' + p))

    if runCHS:
      chsP = p + "chs"
  
  #    setattr(process, 'QGTagger' + chsP, process.QGTagger.clone())
  #    getattr(process, "QGTagger" + chsP).srcJets = cms.InputTag("selectedPatJets" + chsP)
  #    getattr(process, "QGTagger" + chsP).isPatJet = cms.untracked.bool(True)
  #    getattr(process, "QGTagger" + chsP).useCHS = cms.untracked.bool(True)
  
  #    process.QuarkGluonTagger.replace(getattr(process, 'QGTagger' + p), getattr(process, 'QGTagger' + p) + getattr(process, 'QGTagger' + chsP))
  
  print "##########################"
  print "Calo jets" if processCaloJets else "No processing of calo jets"
  print "##########################"

  usePFIso(process, "")
  #adaptPFIsoPhotons(process,  process.patPhotons, "", "03")

  # chiara init ----------------------------------
  print "##########################"
  print "CA8 Jets" if processCA8Jets else "No processing of CA8 jets collection"
  print "##########################"

  if processCA8Jets:

    from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection

    # Reco CA 0.8 jets 
    # non sapendo quali parametri usare esattamente lascerei i default della reco per ora.
    # Per doAreaFastjet e doRhoFastjet per il momento usiamo quanto e' ridefinito sopra
    from RecoJets.JetProducers.ca4PFJets_cfi import ca4PFJets
    process.ca8PFJetsPFlow = ca4PFJets.clone(
      rParam = cms.double(0.8)
      # src = cms.InputTag('pfNoElectron'+postfix),    
      # doAreaFastjet = cms.bool(True),   
      # doRhoFastjet = cms.bool(True),    
      # Rho_EtaMax = cms.double(6.0),    
      # Ghost_EtaMax = cms.double(7.0)   
      )

    # Gen CA 0.8 jets
    from RecoJets.JetProducers.ca4GenJets_cfi import ca4GenJets
    process.ca8GenJetsNoNu = ca4GenJets.clone(
      rParam = cms.double(0.8),
      src = cms.InputTag("genParticlesForJetsNoNu")
      )
  # chiara end ----------------------------------

  
  if processCaloJets:

    # No L2L3 Residual on purpose
    jetCorrections = ('AK5Calo', ['L1Offset', 'L2Relative', 'L3Absolute'])

    addJetCollection(process, cms.InputTag('ak7CaloJets'),
        'AK7',
        'Calo',
        doJTA            = True,
        doBTagging       = True,
        jetCorrLabel     = jetCorrections,
        doType1MET       = correctMETWithT1,
        doL1Cleaning     = False,
        doL1Counters     = False,
        genJetCollection = cms.InputTag("ak7GenJets"),
        doJetID          = True,
        jetIdLabel       = "ak7"
        )



    switchJetCollection(process, cms.InputTag('ak5CaloJets'),
        doJTA            = True,
        doBTagging       = True,
        jetCorrLabel     = jetCorrections,
        doType1MET       = correctMETWithT1,
        genJetCollection = cms.InputTag("ak5GenJets"),
        doJetID          = True,
        jetIdLabel       = "ak5"
        )

    process.selectedPatJets.cut = "pt > 2"
    process.selectedPatJetsAK7Calo.cut = "pt > 2"

  else:
    removeSpecificPATObjects(process, names = ['Jets', 'METs'])

  if not runOnMC:
    # Remove MC Matching
    removeMCMatching(process, names = ["All"])

  removeSpecificPATObjects(process, names = ['Electrons', 'Muons', 'Taus'])

  if runCHS:
    print "##########################"
    print "Running CHS sequence"
    print "##########################"

  process.analysisSequence = cms.Sequence()

  process.analysisSequence *= process.sequence_nochs
  #if runCHS:
  #  process.analysisSequence *= process.sequence_chs

  # chiara init ----------------------------------
  if processCA8Jets:
    process.analysisSequence *= process.ca8PFJetsPFlow
    print("done process.ca8PFJetsPFlow")
    process.analysisSequence *= process.ca8GenJetsNoNu
    print("done process.ca8GenJetsNoNu")

    # nuovo


  # chiara end ----------------------------------


  #GIULIA
  # Quark Gluon tagging
  #process.analysisSequence *= process.QuarkGluonTagger

  # Add default pat sequence to our path
  # This brings to life TcMET, Calo jets and Photons
  ########process.analysisSequence *= process.patDefaultSequence

  # Add our PhotonIsolationProducer to the analysisSequence. This producer compute pf isolations
  # for our photons
  process.photonPFIsolation = cms.EDProducer("PhotonIsolationProducer",
      src = cms.InputTag("selectedPatPhotons")
      )

  ##########process.analysisSequence *= process.photonPFIsolation

  # Filtering

  # require physics declared
  process.load('HLTrigger.special.hltPhysicsDeclared_cfi')
  process.hltPhysicsDeclared.L1GtReadoutRecordTag = 'gtDigis'

  # require scraping filter
  process.scrapingVeto = cms.EDFilter("FilterOutScraping",
      applyfilter = cms.untracked.bool(True),
      debugOn = cms.untracked.bool(False),
      numtrack = cms.untracked.uint32(10),
      thresh = cms.untracked.double(0.25)
      )

  # Count events
  process.nEventsTotal    = cms.EDProducer("EventCountProducer")
  process.nEventsFiltered = cms.EDProducer("EventCountProducer")

  # MET Filters
  process.load("RecoMET.METFilters.metFilters_cff")

  # HCAL Laser filter : work only on Winter13 rereco
  process.load("EventFilter.HcalRawToDigi.hcallaserFilterFromTriggerResult_cff")

  # Let it run
  process.p = cms.Path(
      process.nEventsTotal +

      # Filters
      process.hcalfilter +
      process.primaryVertexFilter +
      process.scrapingVeto +
      process.metFilters +

      process.goodOfflinePrimaryVertices +

      # Physics
      process.analysisSequence +

      process.nEventsFiltered
      )

  if runOnMC:
    process.p.remove(process.hcalfilter)
    process.p.remove(process.scrapingVeto)

  # Add PF2PAT output to the created file
  from PhysicsTools.PatAlgos.patEventContent_cff import patEventContentNoCleaning
  #process.load("CommonTools.ParticleFlow.PF2PAT_EventContent_cff")
  process.out.outputCommands = cms.untracked.vstring('drop *',    
                                                     #process.out.outputCommands = cms.untracked.vstring('keep *')   #'drop *',
                                                     'keep *_*_*_SIM',
                                                     'keep *_*_*_HLT',
                                                     'keep *_*_*_RECO',
                                                     'keep *_*ca8*_*_PAT')
      #'keep *_photonCore_*_*',
      #'keep double_kt6*Jets*_rho_*',
      #'keep *_goodOfflinePrimaryVertices_*_*',
      #'keep recoPFCandidates_particleFlow_*_*',

      # Content of *patEventContentNoCleaning
      #'keep *_selectedPatPhotons*_*_*', 'keep *_selectedPatElectrons*_*_*', 'keep *_selectedPatMuons*_*_*', 'keep *_selectedPatTaus*_*_*', 'keep *_selectedPatJets*_*_*', 'drop *_selectedPatJets_pfCandidates_*', 'drop *_*PF_caloTowers_*', 'drop *_*JPT_pfCandidates_*', 'drop *_*Calo_pfCandidates_*', 'keep *_patMETs*_*_*', 'keep *_selectedPatPFParticles*_*_*', 'keep *_selectedPatTrackCands*_*_*',
      #'keep *_cleanPatPhotons*_*_*', 'keep *_cleanPatElectrons*_*_*', 'keep *_cleanPatMuons*_*_*', 'keep *_cleanPatTaus*_*_*',
      #'keep *_cleanPatJets*_*_*', 'keep *_cleanPatHemispheres*_*_*', 'keep *_cleanPatPFParticles*_*_*',
      #'keep *_cleanPatTrackCands*_*_*',
      #'drop *_*PFlow_caloTowers_*',
                                                     
      # Type I residual
      #'drop *_selectedPatJetsForMET*_*_PAT',
      #'keep *_patPFMet*_*_PAT', # Keep raw met

      # Trigger
      #'keep *_TriggerResults_*_HLT',

      # Debug
      #'keep *_pf*_*_PAT'

      # Photon ID
      #'keep *_patConversions*_*_*',
      #'keep *_photonPFIsolation*_*_*',

      # Quark Gluon tagging
      #'keep *_QGTagger*_*_*',
      #'drop *_kt6PFJetsIsoQG_*_PAT',
      #'drop *_kt6PFJetsQG_*_PAT',
      # MC truth
      #'keep *_genParticles_*_*'
      #)

  if runOnMC:
    process.out.outputCommands.extend(['keep *_addPileupInfo_*_*', 'keep *_generator_*_*'])

  # switch on PAT trigger
  # from PhysicsTools.PatAlgos.tools.trigTools import switchOnTrigger
  # switchOnTrigger( process )

  ## ------------------------------------------------------
  #  In addition you usually want to change the following
  #  parameters:
  ## ------------------------------------------------------
  #
  process.GlobalTag.globaltag = "%s::All" % (globalTag) ##  (according to https://twiki.cern.ch/twiki/bin/view/CMS/SWGuideFrontierConditions)
  #                                         ##
  #process.source.fileNames =  cms.untracked.vstring('file:input_data.root')  ##  (e.g. 'file:AOD.root')
  #                                         ##
  #process.maxEvents.input = 2500
  process.maxEvents.input = 5000
  #                                         ##
  #   process.out.outputCommands = [ ... ]  ##  (e.g. taken from PhysicsTools/PatAlgos/python/patEventContent_cff.py)
  #                                         ##
  process.options.wantSummary = False   ##  (to suppress the long output at the end of the job)
  process.MessageLogger.cerr.FwkReport.reportEvery = 1000

  # Remove annoying ecalLaser messages
  process.MessageLogger.suppressError = cms.untracked.vstring ('ecalLaserCorrFilter')

  return process
Beispiel #19
0
# plugins/PAT2Ntuple.cc for an example of accessing these matches.)

from PhysicsTools.PatAlgos.tools.coreTools import runOnData
if not runOnMC:
    runOnData(process, names=['PFAll'], postfix='PF')

# We remove PAT photons here because they are not fully commisssioned
# in PF. (You could turn them on to check their performance.) This
# also turns off a cleaning step, which in the default PAT workflow
# tries to remove overlap between the physics object collections
# (e.g. removing muons from being reconstructed as degenerate "jets"),
# but this is not necessary with PF/the GED, especially with the top
# projections described above enabled.

from PhysicsTools.PatAlgos.tools.coreTools import removeSpecificPATObjects
removeSpecificPATObjects(process, names=['Photons'], postfix='PF')

# Now we configure the job to keep ttbar events in all three decay
# modes. For hadronic, we will require that there be four
# reconstructed jets (the main hadronic trigger requires this anyway).
#
# For leptonic and dileptonic, we want to keep events with either one
# or two leptons (electrons or muons -- tau reconstruction is
# harder). What we will call a lepton depends on the mode: with one
# lepton, we need to cut a bit harder to increase the ttbar signal
# over the (W+jets) background. If we have two leptons, we don't have
# to cut as hard.
#
# The next eight statements make separate EDProducers for each cut
# case so that a simple EDFilter module later ("countPatLeptons*") can
# count the number that pass. As discussed above, the lepton
Beispiel #20
0
def pat_tuple_process(runOnMC=True, suppress_stdout=True):
    process = cms.Process('PAT')
    process.maxEvents = cms.untracked.PSet(input = cms.untracked.int32(100))
    process.source = cms.Source('PoolSource', fileNames = cms.untracked.vstring('/store/mc/Summer12_DR53X/TTJets_HadronicMGDecays_8TeV-madgraph/AODSIM/PU_S10_START53_V7A-v1/00001/FCAF3F92-5A16-E211-ACCC-E0CB4E19F95A.root' if runOnMC else '/store/data/Run2012B/MultiJet1Parked/AOD/05Nov2012-v2/10000/0003D331-5C49-E211-8210-00259020081C.root'))
    process.options = cms.untracked.PSet(wantSummary = cms.untracked.bool(False))
    process.load('FWCore.MessageLogger.MessageLogger_cfi')
    process.MessageLogger.cerr.FwkReport.reportEvery = 1000000
    process.MessageLogger.cerr.threshold = 'INFO'
    process.MessageLogger.categories.append('PATSummaryTables')
    process.MessageLogger.cerr.PATSummaryTables = cms.untracked.PSet(limit = cms.untracked.int32(-1))
    for category in ['TwoTrackMinimumDistance']:
        process.MessageLogger.categories.append(category)
        setattr(process.MessageLogger.cerr, category, cms.untracked.PSet(limit=cms.untracked.int32(0)))
    process.load('Configuration.Geometry.GeometryIdeal_cff')
    process.load('Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff')
    process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')
    process.GlobalTag.globaltag = 'START53_V27::All' if runOnMC else 'FT53_V21A_AN6::All'
    
    from PhysicsTools.PatAlgos.patEventContent_cff import patEventContent
    process.out = cms.OutputModule('PoolOutputModule',
                                   fileName = cms.untracked.string('pat.root'),
                                   SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('p')),
                                   outputCommands = cms.untracked.vstring(*patEventContent),
                                   )
    process.outp = cms.EndPath(process.out)
    
    process.load('JMTucker.Tools.PATTupleSelection_cfi')
    
    # Event cleaning, with MET cleaning recommendations from
    # https://twiki.cern.ch/twiki/bin/view/CMS/MissingETOptionalFilters
    process.load('HLTrigger.special.hltPhysicsDeclared_cfi')
    process.hltPhysicsDeclared.L1GtReadoutRecordTag = 'gtDigis'
    from DPGAnalysis.Skims.goodvertexSkim_cff import noscraping as FilterOutScraping
    process.FilterOutScraping = FilterOutScraping
    process.load('CommonTools.ParticleFlow.goodOfflinePrimaryVertices_cfi')
    process.goodOfflinePrimaryVertices.filter = cms.bool(True)
    process.load('RecoMET.METFilters.metFilters_cff')
    process.trackingFailureFilter.VertexSource = 'goodOfflinePrimaryVertices'
    
    # Instead of filtering out events at tupling time, schedule separate
    # paths for all the "good data" filters so that the results of them
    # get stored in a small TriggerResults::PAT object, which can be
    # accessed later. Make one path for each so they can be accessed
    # separately in the TriggerResults object; the "All" path that is the
    # product of all of the filters isn't necessary but it's nice for
    # convenience.
    process.eventCleaningAll = cms.Path()
    for name in process.jtupleParams.eventFilters.value():
        negate = name.startswith('~')
        name = name.replace('~', '')
        filter_obj = getattr(process, name)
        if negate:
            filter_obj = ~filter_obj
        setattr(process, 'eventCleaning' + name, cms.Path(filter_obj))
        process.eventCleaningAll *= filter_obj
    
    ################################################################################
    
    # PAT/PF2PAT configuration inspired by TopQuarkAnalysis/Configuration
    # (test/patRefSel_allJets_cfg.py and included modules) with tag
    # V07-00-01.
    
    # First, turn off stdout so that the spam from PAT/PF2PAT doesn't
    # flood the screen (especially useful in batch job submission).
    if suppress_stdout:
        print 'tuple.py: PAT would spam a lot of stuff to stdout... hiding it.'
        from cStringIO import StringIO
        old_stdout = sys.stdout
        sys.stdout = buf = StringIO()
    
    jecLevels = ['L1FastJet', 'L2Relative', 'L3Absolute']
    if not runOnMC:
        jecLevels.append('L2L3Residual')
    #jecLevels += ['L5Flavor', 'L7Parton']
    
    postfix = 'PF'
    def processpostfix(name):
        return getattr(process, name + postfix)
    def setprocesspostfix(name, obj):
        setattr(process, name + postfix, obj)
    def InputTagPostFix(name):
        return cms.InputTag(name + postfix)
    
    process.load('PhysicsTools.PatAlgos.patSequences_cff')
    from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
    usePF2PAT(process,
              runPF2PAT = True,
              runOnMC = runOnMC,
              jetAlgo = 'AK5',
              postfix = postfix,
              jetCorrections = ('AK5PFchs', jecLevels), # 'chs': using PFnoPU
              typeIMetCorrections = True,
              pvCollection = cms.InputTag('goodOfflinePrimaryVertices'),
              )
    
    processpostfix('pfNoPileUp')  .enable = True  # usePFnoPU
    processpostfix('pfNoMuon')    .enable = True  # useNoMuon
    processpostfix('pfNoElectron').enable = True  # useNoElectron
    processpostfix('pfNoJet')     .enable = True  # useNoJet
    processpostfix('pfNoTau')     .enable = True  # useNoTau
    
    processpostfix('pfPileUp').checkClosestZVertex = False
    processpostfix('pfPileUpIso').checkClosestZVertex = False
    
    processpostfix('pfMuonsFromVertex').d0Cut = processpostfix('pfElectronsFromVertex').d0Cut = 2
    processpostfix('pfMuonsFromVertex').dzCut = processpostfix('pfElectronsFromVertex').dzCut = 2
    
    processpostfix('pfSelectedMuons').cut = 'pt > 5.'
    #processpostfix('pfSelectedMuons').cut += process.jtupleParams.muonCut
    processpostfix('pfIsolatedMuons').isolationCut = 0.2
    
    if False: # pfMuonIsoConeR03
        processpostfix('pfIsolatedMuons').isolationValueMapsCharged  = cms.VInputTag(InputTagPostFix('muPFIsoValueCharged03'))
        processpostfix('pfIsolatedMuons').deltaBetaIsolationValueMap = InputTagPostFix('muPFIsoValuePU03')
        processpostfix('pfIsolatedMuons').isolationValueMapsNeutral  = cms.VInputTag(InputTagPostFix('muPFIsoValueNeutral03'), InputTagPostFix('muPFIsoValueGamma03'))
        processpostfix('pfMuons').isolationValueMapsCharged  = cms.VInputTag(InputTagPostFix('muPFIsoValueCharged03'))
        processpostfix('pfMuons').deltaBetaIsolationValueMap = InputTagPostFix('muPFIsoValuePU03')
        processpostfix('pfMuons').isolationValueMapsNeutral  = cms.VInputTag(InputTagPostFix('muPFIsoValueNeutral03'), InputTagPostFix('muPFIsoValueGamma03'))
        processpostfix('patMuons').isolationValues.pfNeutralHadrons   = InputTagPostFix('muPFIsoValueNeutral03')
        processpostfix('patMuons').isolationValues.pfChargedAll       = InputTagPostFix('muPFIsoValueChargedAll03')
        processpostfix('patMuons').isolationValues.pfPUChargedHadrons = InputTagPostFix('muPFIsoValuePU03')
        processpostfix('patMuons').isolationValues.pfPhotons          = InputTagPostFix('muPFIsoValueGamma03')
        processpostfix('patMuons').isolationValues.pfChargedHadrons   = InputTagPostFix('muPFIsoValueCharged03')
    
    processpostfix('pfSelectedElectrons').cut = 'pt > 5. && gsfTrackRef.isNonnull && gsfTrackRef.trackerExpectedHitsInner.numberOfLostHits < 2'
    #processpostfix('pfSelectedElectrons').cut += ' && ' + process.jtupleParams.electronCut # disabled by default, but can use minimal (veto) electron selection cut on top of pfElectronSelectionCut
    processpostfix('pfIsolatedElectrons').isolationCut = 0.2
    
    if True: # pfElectronIsoConeR03
        processpostfix('pfIsolatedElectrons').isolationValueMapsCharged  = cms.VInputTag(InputTagPostFix('elPFIsoValueCharged03PFId'))
        processpostfix('pfIsolatedElectrons').deltaBetaIsolationValueMap = InputTagPostFix('elPFIsoValuePU03PFId')
        processpostfix('pfIsolatedElectrons').isolationValueMapsNeutral  = cms.VInputTag(InputTagPostFix('elPFIsoValueNeutral03PFId'), InputTagPostFix('elPFIsoValueGamma03PFId'))
        processpostfix('pfElectrons').isolationValueMapsCharged  = cms.VInputTag(InputTagPostFix('elPFIsoValueCharged03PFId'))
        processpostfix('pfElectrons').deltaBetaIsolationValueMap = InputTagPostFix('elPFIsoValuePU03PFId')
        processpostfix('pfElectrons').isolationValueMapsNeutral  = cms.VInputTag(InputTagPostFix('elPFIsoValueNeutral03PFId'), InputTagPostFix('elPFIsoValueGamma03PFId'))
        processpostfix('patElectrons').isolationValues.pfNeutralHadrons   = InputTagPostFix('elPFIsoValueNeutral03PFId')
        processpostfix('patElectrons').isolationValues.pfChargedAll       = InputTagPostFix('elPFIsoValueChargedAll03PFId')
        processpostfix('patElectrons').isolationValues.pfPUChargedHadrons = InputTagPostFix('elPFIsoValuePU03PFId')
        processpostfix('patElectrons').isolationValues.pfPhotons          = InputTagPostFix('elPFIsoValueGamma03PFId')
        processpostfix('patElectrons').isolationValues.pfChargedHadrons   = InputTagPostFix('elPFIsoValueCharged03PFId')
    
    process.load('EgammaAnalysis.ElectronTools.electronIdMVAProducer_cfi')
    processpostfix('patElectrons').electronIDSources.mvaTrigV0    = cms.InputTag("mvaTrigV0")
    processpostfix('patElectrons').electronIDSources.mvaNonTrigV0 = cms.InputTag("mvaNonTrigV0")
    processpostfix('patMuons').embedTrack = True
    processpostfix('patJets').addTagInfos = True
    processpostfix('selectedPatElectrons').cut = process.jtupleParams.electronCut
    processpostfix('selectedPatMuons').cut = process.jtupleParams.muonCut
    processpostfix('selectedPatJets').cut = process.jtupleParams.jetCut
    
    process.load('CMGTools.External.pujetidsequence_cff')
    for x in (process.puJetId, process.puJetMva, process.puJetIdChs, process.puJetMvaChs):
        x.jets = InputTagPostFix('selectedPatJets')
        # fix bug in V00-03-04 of CMGTools/External
        if hasattr(x, 'algos'):
            bad, good = 'RecoJets/JetProducers', 'CMGTools/External'
            for ps in x.algos:
                if hasattr(ps, 'tmvaWeights'):
                    s = ps.tmvaWeights.value()
                    if s.startswith(bad):
                        ps.tmvaWeights = s.replace(bad, good)
    
    from PhysicsTools.PatAlgos.tools.coreTools import runOnData, removeSpecificPATObjects
    if not runOnMC:
        runOnData(process, names = ['All'], postfix = postfix)
    removeSpecificPATObjects(process, names = ['Photons'], postfix = postfix) # will also remove cleaning
    
    # Make some extra SV producers for MFV studies. JMTBAD postfix junk
    for cut in (1., 1.5, 2., 2.5, 3., 3.5, 4., 4.5, 5., 5.5, 6.):
        cut_name = ('%.1f' % cut).replace('.', 'p')
                     
        tag_info_name = 'secondaryVertexMaxDR%sTagInfosAODPF' % cut_name
        tag_info_obj = process.secondaryVertexTagInfosAODPF.clone()
        tag_info_obj.vertexCuts.maxDeltaRToJetAxis = cut
        setattr(process, tag_info_name, tag_info_obj)
        process.patJetsPF.tagInfoSources.append(cms.InputTag(tag_info_name))
    
        processpostfix('patPF2PATSequence').replace(processpostfix('patJets'), tag_info_obj * processpostfix('patJets'))
    
    from JMTucker.Tools.PATTupleSelection_cfi import makeLeptonProducers
    makeLeptonProducers(process, postfix=postfix, params=process.jtupleParams)
    
    common_seq = cms.ignore(process.goodOfflinePrimaryVertices) + cms.ignore(process.mvaTrigV0) + cms.ignore(process.mvaNonTrigV0) + processpostfix('patPF2PATSequence') + process.puJetIdSqeuenceChs
    
    process.load('JMTucker.MFVNeutralino.Vertexer_cff')
    common_seq *= process.mfvVertices
    
    # Require numbers of jets based on the trigger: hadronic channel will
    # have at least a 4-jet trigger (maybe 6!), while semileptonic uses a
    # 3-jet trigger. Dileptonic has no jets in trigger, but we'll require
    # at least one b-tag anyway.
    setprocesspostfix('countPatJetsHadronic',     processpostfix('countPatJets').clone(minNumber = 4))
    setprocesspostfix('countPatJetsSemileptonic', processpostfix('countPatJets').clone(minNumber = 3))
    setprocesspostfix('countPatJetsDileptonic',   processpostfix('countPatJets').clone(minNumber = 1))
    
    channels = ('Hadronic', 'Semileptonic', 'Dileptonic')
    for channel in channels:
        setattr(process, 'p' + channel, cms.Path(common_seq))
    
    process.pHadronic     *= processpostfix('countPatJetsHadronic')
    process.pSemileptonic *= processpostfix('countPatJetsSemileptonic') + process.jtupleSemileptonSequence + process.countSemileptons
    process.pDileptonic   *= processpostfix('countPatJetsDileptonic')   + process.jtupleDileptonSequence   + process.countDileptons
    
    process.out.SelectEvents.SelectEvents = ['p' + channel for channel in channels]
    process.out.outputCommands = [
        'drop *',
        'keep *_selectedPatElectrons*_*_*',
        'keep *_selectedPatMuons*_*_*',
        'keep *_selectedPatJets*_*_*',
        'drop *_selectedPatJetsForMETtype1p2CorrPF_*_*',
        'drop *_selectedPatJetsForMETtype2CorrPF_*_*',
        'keep *_mfvVertices*_*_*',
        'drop CaloTowers_*_*_*',
        'keep *_patMETs*_*_*',
        'keep *_goodOfflinePrimaryVertices_*_*',
        'keep edmTriggerResults_TriggerResults__PAT', # for post-tuple filtering on the goodData paths
        'keep *_puJet*_*_*',
        ]
    
    # The normal TrigReport doesn't state how many events are written
    # total to the file in case of OutputModule's SelectEvents having
    # multiple paths. Add a summary to stdout that so that it is easy to
    # see what the total number of events should be (for debugging CRAB
    # jobs). (This means we can kill the normal TrigReport.)
    process.ORTrigReport = cms.EDAnalyzer('ORTrigReport',
                                          results_src = cms.InputTag('TriggerResults', '', process.name_()),
                                          paths = process.out.SelectEvents.SelectEvents
                                          )
    process.pORTrigReport = cms.EndPath(process.ORTrigReport) # Must be on an EndPath.
    
    # As a simple check of the paths' efficiencies, add some lines to the
    # summary showing stats on events with generator-level muons/electrons
    # in acceptance from W decays.
    if runOnMC:
        for name, cut in [('Muon',     'abs(pdgId) == 13 && abs(eta) < 2.4 && abs(mother.pdgId) == 24 && pt > 20'),
                          ('Electron', 'abs(pdgId) == 11 && abs(eta) < 2.5 && abs(mother.pdgId) == 24 && pt > 20'),
                          ('Lepton',   '((abs(pdgId) == 13 && abs(eta) < 2.4) || (abs(pdgId) == 11 && abs(eta) < 2.5)) && abs(mother.pdgId) == 24 && pt > 20'),
                          ]:
            name = 'gen' + name + 's'
            filter = cms.EDFilter('CandViewSelector', src = cms.InputTag('genParticles'), cut = cms.string(cut))
            counter = cms.EDFilter('CandViewCountFilter', src = cms.InputTag(name), minNumber = cms.uint32(1))
            setattr(process, name,           filter)
            setattr(process, name + 'Count', counter)
            setattr(process, 'p' + name + 'Count', cms.Path(filter*counter))
    
    # Check that the stdout spam from PAT was what we expect.
    if suppress_stdout:
        pat_output = buf.getvalue()
        sys.stdout = old_stdout
        buf.close()
        hsh = hash(pat_output)
        #open('pat_spam.txt', 'wt').write(pat_output)
        hsh_expected = 6563257886911239637 if runOnMC else 3125511795667431709
        print 'PAT is done (spam hash %s, expected %s).' % (hsh, hsh_expected)
        if hsh != hsh_expected:
            from JMTucker.Tools.general import big_warn
            big_warn('Unexpected spam hash! Did you change an option?')

    return process, common_seq