예제 #1
0
def loadPF2PAT(process,mcInfo,JetMetCorrections,postfix):
    #-- PAT standard config -------------------------------------------------------
    process.load("PhysicsTools.PatAlgos.patSequences_cff")
    #-- Jet corrections -----------------------------------------------------------
    process.patJetCorrFactors.corrSample = JetMetCorrections 
    #-- PF2PAT config -------------------------------------------------------------
    from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
    usePF2PAT(process,runPF2PAT=True, jetAlgo='AK5',runOnMC=mcInfo,postfix=postfix)
    process.patJetsPF.embedGenJetMatch = False
    process.patJetsPF.embedPFCandidates = False
예제 #2
0
def addPF2PAT(process, dataVersion, postfix="PFlow",
              doTauHLTMatching=True, matchingTauTrigger=None, 
              ):
#    if hasattr(process, "patDefaultSequence"):
#        raise Exception("PAT should not exist before calling addPF2PAT at the moment")

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

    outputCommands = []

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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



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

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

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

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

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

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

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

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

    return sequence
  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)
# subtraction (CHS) applied. The latter is used to identify and remove
# particles from pileup, by associating their tracks with the non-main
# primary vertex. (The primary vertex collection is sorted by
# decreasing sum pT^2; the first one in the collection is usually
# taken as *the* primary vertex.) CHS is what is meant when the name
# "PFnoPileUp" is used.
#
# typeIMetCorrections = True indicates we want to apply the jet energy
# corrections in the MET calculation.

from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
usePF2PAT(process,
          runPF2PAT = True,
          postfix = 'PF',
          runOnMC = runOnMC,
          pvCollection = cms.InputTag('goodOfflinePrimaryVertices'),
          jetAlgo = 'AK5',
          jetCorrections = ('AK5PFchs', jecLevels),
          typeIMetCorrections = True,
          )




# Turn on the "top projections". This has nothing to do with top quark
# physics, but rather refers to separating sequentially out from the
# entire list of PF candidates the ones identified as pileup (from
# "wrong" primary vertices), muons, electrons, jets, and taus. The
# "No" in each collection name indicates the thing referred to has
# been removed. (See the above first set of slides for a example
# picture.) The input to the jet clustering is then taken from the
예제 #5
0
def customisePAT(process, runOnMC, outputModules = []):
    ## Load PAT
    process.load("PhysicsTools.PatAlgos.patSequences_cff")

    ## Apply MVA
    process.load('EgammaAnalysis.ElectronTools.electronIdMVAProducer_cfi')
    process.eidMVASequence = cms.Sequence(  process.mvaTrigV0 + process.mvaNonTrigV0 )
    process.patElectrons.electronIDSources.mvaTrigV0    = cms.InputTag("mvaTrigV0")
    process.patElectrons.electronIDSources.mvaNonTrigV0 = cms.InputTag("mvaNonTrigV0")
    process.patDefaultSequence.replace( process.patElectrons, process.eidMVASequence * process.patElectrons )

    ## Load trigger matching
    process.load("KrAFT.Configuration.hltFilters_cff")
    #from PhysicsTools.PatAlgos.tools.trigTools import *
    #switchOnTriggerMatchEmbedding(process, outputModule="")

    ## Apply PF2PAT
    from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
    if runOnMC: jecLevels = ['L1FastJet','L2Relative','L3Absolute']
    else: jecLevels = ['L1FastJet','L2Relative', 'L3Absolute', 'L2L3Residual']

    #usePFBRECO(process,runPFBRECO=True,
    usePF2PAT(process, runPF2PAT=True,
              runOnMC=runOnMC, outputModules = outputModules, postfix="PFlow",
              jetAlgo="AK5", jetCorrections=("AK5PFchs", jecLevels),
              typeIMetCorrections=True)

    # top projections in PF2PAT:
    process.pfNoPileUpPFlow.enable = True
    process.pfNoMuonPFlow.enable = True
    process.pfNoElectronPFlow.enable = True
    process.pfNoTauPFlow.enable = False
    process.pfNoJetPFlow.enable = True

    # verbose flags for the PF2PAT modules
    process.pfNoMuonPFlow.verbose = False

    # Use non-isolated muons and electrons
    process.patMuonsPFlow.pfMuonSource = "pfMuonsPFlow"
    process.patElectronsPFlow.pfElectronSource = "pfElectronsPFlow"

    # And turn on delta-beta corrections while building pfIsolated*PFlow
    process.pfIsolatedMuonsPFlow.doDeltaBetaCorrection = True
    process.pfIsolatedElectronsPFlow.doDeltaBetaCorrection = True

    # Change DR cone size to 0.3
    process.pfIsolatedMuonsPFlow.isolationValueMapsCharged  = cms.VInputTag(cms.InputTag('muPFIsoValueCharged03PFlow'))
    process.pfIsolatedMuonsPFlow.deltaBetaIsolationValueMap = cms.InputTag('muPFIsoValuePU03PFlow')
    process.pfIsolatedMuonsPFlow.isolationValueMapsNeutral  = cms.VInputTag(cms.InputTag('muPFIsoValueNeutral03PFlow'),
                                                                         cms.InputTag('muPFIsoValueGamma03PFlow'),)
    process.pfMuonsPFlow.isolationValueMapsCharged  = cms.VInputTag(cms.InputTag('muPFIsoValueCharged03PFlow') )
    process.pfMuonsPFlow.deltaBetaIsolationValueMap = cms.InputTag('muPFIsoValuePU03PFlow')
    process.pfMuonsPFlow.isolationValueMapsNeutral  = cms.VInputTag(cms.InputTag('muPFIsoValueNeutral03PFlow'),
                                                                 cms.InputTag('muPFIsoValueGamma03PFlow'),)
    process.patMuonsPFlow.isolationValues.pfNeutralHadrons   = cms.InputTag('muPFIsoValueNeutral03PFlow')
    process.patMuonsPFlow.isolationValues.pfChargedAll       = cms.InputTag('muPFIsoValueChargedAll03PFlow')
    process.patMuonsPFlow.isolationValues.pfPUChargedHadrons = cms.InputTag('muPFIsoValuePU03PFlow')
    process.patMuonsPFlow.isolationValues.pfPhotons          = cms.InputTag('muPFIsoValueGamma03PFlow')
    process.patMuonsPFlow.isolationValues.pfChargedHadrons   = cms.InputTag('muPFIsoValueCharged03PFlow')

    process.pfIsolatedElectronsPFlow.isolationValueMapsCharged  = cms.VInputTag(cms.InputTag('elPFIsoValueCharged03PFIdPFlow'))
    process.pfIsolatedElectronsPFlow.deltaBetaIsolationValueMap = cms.InputTag('elPFIsoValuePU03PFIdPFlow')
    process.pfIsolatedElectronsPFlow.isolationValueMapsNeutral  = cms.VInputTag(cms.InputTag('elPFIsoValueNeutral03PFIdPFlow'),
                                                                             cms.InputTag('elPFIsoValueGamma03PFIdPFlow'))
    process.pfElectronsPFlow.isolationValueMapsCharged  = cms.VInputTag(cms.InputTag('elPFIsoValueCharged03PFIdPFlow'))
    process.pfElectronsPFlow.deltaBetaIsolationValueMap = cms.InputTag('elPFIsoValuePU03PFIdPFlow')
    process.pfElectronsPFlow.isolationValueMapsNeutral  = cms.VInputTag(cms.InputTag('elPFIsoValueNeutral03PFIdPFlow'),
                                                                     cms.InputTag('elPFIsoValueGamma03PFIdPFlow'))
    process.patElectronsPFlow.isolationValues.pfNeutralHadrons   = cms.InputTag('elPFIsoValueNeutral03PFIdPFlow')
    process.patElectronsPFlow.isolationValues.pfChargedAll       = cms.InputTag('elPFIsoValueChargedAll03PFIdPFlow')
    process.patElectronsPFlow.isolationValues.pfPUChargedHadrons = cms.InputTag('elPFIsoValuePU03PFIdPFlow')
    process.patElectronsPFlow.isolationValues.pfPhotons          = cms.InputTag('elPFIsoValueGamma03PFIdPFlow')
    process.patElectronsPFlow.isolationValues.pfChargedHadrons   = cms.InputTag('elPFIsoValueCharged03PFIdPFlow')
예제 #6
0
def initialise(runOnMC, decayMode, doOutModule=False, doPAT=True):
    process = cms.Process("KrAFT")

    process.load("Configuration.StandardSequences.Services_cff")
    process.load("Configuration.Geometry.GeometryDB_cff")
    process.load("Configuration.StandardSequences.MagneticField_cff")
    process.options   = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )
    process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )

    process.load("FWCore.MessageLogger.MessageLogger_cfi")
    process.MessageLogger.cerr.FwkReport.reportEvery = 10000

    process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring())

    process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
    from Configuration.AlCa.autoCond import autoCond
    if runOnMC: process.GlobalTag.globaltag = autoCond['startup']
    else: process.GlobalTag.globaltag = autoCond['com10']

    outputModuleForTriggerMatch = ""
    outputModules = []
    if doOutModule:
        from PhysicsTools.PatAlgos.patEventContent_cff import patEventContentNoCleaning
        process.out = cms.OutputModule("PoolOutputModule",
            fileName = cms.untracked.string("out.root"),
            outputCommands = cms.untracked.vstring(
                'drop *',
                'keep recoPFCandidates_particleFlow_*_*',
                *patEventContentNoCleaning
            )
        )
        process.outPath = cms.EndPath(process.out)

        outputModuleForTriggerMatch = "out"
        outputModules.append(process.out)

    ## Load PAT
    process.load("PhysicsTools.PatAlgos.patSequences_cff")

    ## Apply MVA
    process.load('EgammaAnalysis.ElectronTools.electronIdMVAProducer_cfi')
    process.eidMVASequence = cms.Sequence(  process.mvaTrigV0 + process.mvaNonTrigV0 )
    process.patElectrons.electronIDSources.mvaTrigV0    = cms.InputTag("mvaTrigV0")
    process.patElectrons.electronIDSources.mvaNonTrigV0 = cms.InputTag("mvaNonTrigV0")
    process.patDefaultSequence.replace( process.patElectrons, process.eidMVASequence * process.patElectrons )

    ## Load trigger matching
    process.load("KrAFT.Configuration.hltFilters_cff")
    #from PhysicsTools.PatAlgos.tools.trigTools import *
    #switchOnTriggerMatchEmbedding(process, outputModule="")

    ## Apply PF2PAT
    from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
    if runOnMC: jecLevels = ['L1FastJet','L2Relative','L3Absolute']
    else: jecLevels = ['L1FastJet','L2Relative', 'L3Absolute', 'L2L3Residual']

    #usePFBRECO(process,runPFBRECO=True,
    usePF2PAT(process, runPF2PAT=True,
              runOnMC=runOnMC, outputModules = outputModules, postfix="PFlow",
              jetAlgo="AK5", jetCorrections=("AK5PFchs", jecLevels),
              typeIMetCorrections=True)

    # top projections in PF2PAT:
    process.pfNoPileUpPFlow.enable = True
    process.pfNoMuonPFlow.enable = True
    process.pfNoElectronPFlow.enable = True
    process.pfNoTauPFlow.enable = False
    process.pfNoJetPFlow.enable = True

    # verbose flags for the PF2PAT modules
    process.pfNoMuonPFlow.verbose = False

    # Use non-isolated muons and electrons
    process.patMuonsPFlow.pfMuonSource = "pfMuonsPFlow"
    process.patElectronsPFlow.pfElectronSource = "pfElectronsPFlow"

    # And turn on delta-beta corrections while building pfIsolated*PFlow
    process.pfIsolatedMuonsPFlow.doDeltaBetaCorrection = True
    process.pfIsolatedElectronsPFlow.doDeltaBetaCorrection = True

    # Change DR cone size to 0.3
    process.pfIsolatedMuonsPFlow.isolationValueMapsCharged  = cms.VInputTag(cms.InputTag('muPFIsoValueCharged03PFlow'))
    process.pfIsolatedMuonsPFlow.deltaBetaIsolationValueMap = cms.InputTag('muPFIsoValuePU03PFlow')
    process.pfIsolatedMuonsPFlow.isolationValueMapsNeutral  = cms.VInputTag(cms.InputTag('muPFIsoValueNeutral03PFlow'),
                                                                         cms.InputTag('muPFIsoValueGamma03PFlow'),)
    process.pfMuonsPFlow.isolationValueMapsCharged  = cms.VInputTag(cms.InputTag('muPFIsoValueCharged03PFlow') )
    process.pfMuonsPFlow.deltaBetaIsolationValueMap = cms.InputTag('muPFIsoValuePU03PFlow')
    process.pfMuonsPFlow.isolationValueMapsNeutral  = cms.VInputTag(cms.InputTag('muPFIsoValueNeutral03PFlow'),
                                                                 cms.InputTag('muPFIsoValueGamma03PFlow'),)
    process.patMuonsPFlow.isolationValues.pfNeutralHadrons   = cms.InputTag('muPFIsoValueNeutral03PFlow')
    process.patMuonsPFlow.isolationValues.pfChargedAll       = cms.InputTag('muPFIsoValueChargedAll03PFlow')
    process.patMuonsPFlow.isolationValues.pfPUChargedHadrons = cms.InputTag('muPFIsoValuePU03PFlow')
    process.patMuonsPFlow.isolationValues.pfPhotons          = cms.InputTag('muPFIsoValueGamma03PFlow')
    process.patMuonsPFlow.isolationValues.pfChargedHadrons   = cms.InputTag('muPFIsoValueCharged03PFlow')

    process.pfIsolatedElectronsPFlow.isolationValueMapsCharged  = cms.VInputTag(cms.InputTag('elPFIsoValueCharged03PFIdPFlow'))
    process.pfIsolatedElectronsPFlow.deltaBetaIsolationValueMap = cms.InputTag('elPFIsoValuePU03PFIdPFlow')
    process.pfIsolatedElectronsPFlow.isolationValueMapsNeutral  = cms.VInputTag(cms.InputTag('elPFIsoValueNeutral03PFIdPFlow'),
                                                                             cms.InputTag('elPFIsoValueGamma03PFIdPFlow'))
    process.pfElectronsPFlow.isolationValueMapsCharged  = cms.VInputTag(cms.InputTag('elPFIsoValueCharged03PFIdPFlow'))
    process.pfElectronsPFlow.deltaBetaIsolationValueMap = cms.InputTag('elPFIsoValuePU03PFIdPFlow')
    process.pfElectronsPFlow.isolationValueMapsNeutral  = cms.VInputTag(cms.InputTag('elPFIsoValueNeutral03PFIdPFlow'),
                                                                     cms.InputTag('elPFIsoValueGamma03PFIdPFlow'))
    process.patElectronsPFlow.isolationValues.pfNeutralHadrons   = cms.InputTag('elPFIsoValueNeutral03PFIdPFlow')
    process.patElectronsPFlow.isolationValues.pfChargedAll       = cms.InputTag('elPFIsoValueChargedAll03PFIdPFlow')
    process.patElectronsPFlow.isolationValues.pfPUChargedHadrons = cms.InputTag('elPFIsoValuePU03PFIdPFlow')
    process.patElectronsPFlow.isolationValues.pfPhotons          = cms.InputTag('elPFIsoValueGamma03PFIdPFlow')
    process.patElectronsPFlow.isolationValues.pfChargedHadrons   = cms.InputTag('elPFIsoValueCharged03PFIdPFlow')

    ## Add common filters
    process.load( "TopQuarkAnalysis.Configuration.patRefSel_goodVertex_cfi" )
    process.goodOfflinePrimaryVertices.filter = True

    process.load( 'TopQuarkAnalysis.Configuration.patRefSel_eventCleaning_cff' )
    process.trackingFailureFilter.VertexSource = cms.InputTag('goodOfflinePrimaryVertices')
    if runOnMC: process.eventCleaning += process.eventCleaningMC
    else: process.eventCleaning += process.eventCleaningData

    ## Lepton veto filters for L+J channels
    process.muonVetoFilter = cms.EDFilter("PATCandViewCountFilter",
        src = cms.InputTag("selectedPatMuonsPFlow"),
        maxNumber = cms.uint32(0),
        minNumber = cms.uint32(0),
    )
    process.electronVetoFilter = cms.EDFilter("PATCandViewCountFilter",
        src = cms.InputTag("selectedPatElectronsPFlow"),
        maxNumber = cms.uint32(0),
        minNumber = cms.uint32(0),
    )

    # event counters
    process.nEventsTotal = cms.EDProducer("EventCountProducer")
    process.nEventsClean = cms.EDProducer("EventCountProducer")
    process.nEventsPAT   = cms.EDProducer("EventCountProducer")
    process.nEventsHLTElEl = cms.EDProducer("EventCountProducer")
    process.nEventsHLTMuMu = cms.EDProducer("EventCountProducer")
    process.nEventsHLTMuEl = cms.EDProducer("EventCountProducer")
    process.nEventsHLTMuJets = cms.EDProducer("EventCountProducer")
    process.nEventsHLTElJets = cms.EDProducer("EventCountProducer")

    process.commonFilterSequence = cms.Sequence(
        process.goodOfflinePrimaryVertices
      #* process.eventCleaning
      + process.nEventsClean
    )

    process.patSequenceComplete = cms.Sequence(
    #  + process.patDefaultSequence
    #  + process.patPFBRECOSequencePFlow
        process.patPF2PATSequencePFlow
      + process.nEventsPAT
    )

    ## Defile paths
    if decayMode in ("all", "dilepton", "ElEl", "ee"):
        process.pElEl = cms.Path(
            process.nEventsTotal
          + process.commonFilterSequence
          + process.hltElEl + process.nEventsHLTElEl
        )
        if doPAT: process.pElEl += process.patSequenceComplete
    if decayMode in ("all", "dilepton", "MuMu", "mumu"):
        process.pMuMu = cms.Path(
            process.nEventsTotal
          + process.commonFilterSequence
          + process.hltMuMu + process.nEventsHLTMuMu
        )
        if doPAT: process.pMuMu += process.patSequenceComplete
    if decayMode in ("all", "dilepton", "MuEl", "emu"):
        process.pMuEl = cms.Path(
            process.nEventsTotal
          + process.commonFilterSequence
          + process.hltMuEl + process.nEventsHLTMuEl
        )
        if doPAT: process.pMuEl += process.patSequenceComplete
    if decayMode in ("all", "MuJets"):
        process.selectedPatMuonsPFlow.cut = 'isPFMuon && (isGlobalMuon || isTrackerMuon) && pt > 10 && abs(eta) < 2.5 && (chargedHadronIso + max(0.,neutralHadronIso+photonIso-0.5*puChargedHadronIso))/pt < 0.15'
        process.selectedPatElectronsPFlow.cut = 'pt > 20 && abs(eta) < 2.5 && electronID("mvaTrigV0") > 0. && (chargedHadronIso + max(0.,neutralHadronIso+photonIso-0.5*puChargedHadronIso))/pt < 0.15'
        process.muonVetoFilter.maxNumber = 1

        process.pMuJets = cms.Path(
            process.nEventsTotal
          + process.commonFilterSequence
          + process.hltMuJets + process.nEventsHLTMuJets
        )
        if doPAT: process.pMuJets += process.patSequenceComplete
        process.pMuJets *= process.muonVetoFilter
        process.pMuJets += process.electronVetoFilter

        if runOnMC: process.pMuJets.remove(process.hltMuJets)
    if decayMode in ("all", "ElJets"):
        process.selectedPatMuonsPFlow.cut = 'isPFMuon && (isGlobalMuon || isTrackerMuon) && pt > 10 && abs(eta) < 2.5 && (chargedHadronIso + max(0.,neutralHadronIso+photonIso-0.5*puChargedHadronIso))/pt < 0.15'
        process.selectedPatElectronsPFlow.cut = 'pt > 20 && abs(eta) < 2.5 && electronID("mvaTrigV0") > 0. && (chargedHadronIso + max(0.,neutralHadronIso+photonIso-0.5*puChargedHadronIso))/pt < 0.15'
        process.electronVetoFilter.maxNumber = 1

        process.pElJets = cms.Path(
            process.nEventsTotal
          + process.commonFilterSequence
          + process.hltElJets + process.nEventsHLTElJets
        )
        if doPAT: process.pElJets += process.patSequenceComplete
        process.pElJets *= process.muonVetoFilter
        process.pElJets += process.electronVetoFilter

        if runOnMC: process.pElJets.remove(process.hltElJets)

    return process
예제 #7
0
def loadPF2PAT(process,mcInfo,jetMetCorrections,extMatch,doSusyTopProjection,postfix):
    #-- PAT standard config -------------------------------------------------------
    process.load("PhysicsTools.PatAlgos.patSequences_cff")
    #-- Jet corrections -----------------------------------------------------------
    process.patJetCorrFactors.levels = jetMetCorrections 
    #-- PF2PAT config -------------------------------------------------------------
    from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
    usePF2PAT(process,runPF2PAT=True, jetAlgo='AK5',runOnMC=(mcInfo==1),postfix=postfix, jetCorrections=('AK5PFchs', jetMetCorrections))

    #process.patJetsPF.embedGenJetMatch = False
    #process.patJetsPF.embedPFCandidates = False
    #drop tracks 
    process.patElectronsPF.embedTrack = True
    process.patMuonsPF.embedTrack   = True
    process.electronMatchPF.maxDeltaR   = cms.double(0.2)
    process.electronMatchPF.maxDPtRel   = cms.double(999999.)
    process.electronMatchPF.checkCharge = False
    process.muonMatchPF.maxDeltaR   = cms.double(0.2)
    process.muonMatchPF.maxDPtRel   = cms.double(999999.)
    process.muonMatchPF.checkCharge = False
    if extMatch:
        process.electronMatchPF.mcStatus = cms.vint32(1,5)
        process.electronMatchPF.matched = "mergedTruth"
        process.muonMatchPF.mcStatus = cms.vint32(1,5)
        process.muonMatchPF.matched = "mergedTruth"
        process.genParticlesForJets.src = "mergedTruth"
        process.genParticlesForJetsNoMuNoNu.src = "mergedTruth"
        process.genParticlesForJetsNoNu.src = "mergedTruth"
        process.patJetPartonMatchPF.matched = "mergedTruth"
        process.patJetPartonsPF.src = "mergedTruth"
        process.photonMatchPF.matched = "mergedTruth"
        #process.tauGenJetsPF.GenParticles = "mergedTruth"
        #process.tauMatchPF.matched = "mergedTruth"
        
    #Remove jet pt cut
    #process.pfJetsPF.ptMin = 0.
    #include tau decay mode in pat::Taus (elese it will just be uninitialized)
    #process.patTausPF.addDecayMode = True
    #process.patTausPF.decayModeSrc = "shrinkingConePFTauDecayModeProducerPF" 


    # TODO: Fix type I MET
    #PF type I corrected MET
	# Temporarily disabled for first 44X recipe -- Benjamin
    # addPFTypeIMet(process)

    #Set isolation cone to 0.3 for PF leptons
    # TODO: fix this for electrons and muons
    #process.pfElectrons.isolationValueMapsCharged = cms.VInputTag(cms.InputTag("elPFIsoValueCharged03PFId"))
    #process.pfElectrons.deltaBetaIsolationValueMap = cms.InputTag("elPFIsoValuePU03PFId")
    #process.pfElectrons.isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("elPFIsoValueNeutral03PFId"), cms.InputTag("elPFIsoValueGamma03PFId"))
    #process.pfIsolatedElectrons.isolationValueMapsCharged = cms.VInputTag(cms.InputTag("elPFIsoValueCharged03PFId"))
    #process.pfIsolatedElectrons.deltaBetaIsolationValueMap = cms.InputTag("elPFIsoValuePU03PFId")
    #process.pfIsolatedElectrons.isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("elPFIsoValueNeutral03PFId"), cms.InputTag("elPFIsoValueGamma03PFId"))
    
    #process.pfElectronsPF.isolationValueMapsCharged = cms.VInputTag(cms.InputTag("elPFIsoValueCharged03PFIdPF"))
    #process.pfElectronsPF.deltaBetaIsolationValueMap = cms.InputTag("elPFIsoValuePU03PFIdPF")
    #process.pfElectronsPF.isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("elPFIsoValueNeutral03PFIdPF"), cms.InputTag("elPFIsoValueGamma03PFIdPF"))
    #process.pfIsolatedElectronsPF.isolationValueMapsCharged = cms.VInputTag(cms.InputTag("elPFIsoValueCharged03PFIdPF"))
    #process.pfIsolatedElectronsPF.deltaBetaIsolationValueMap = cms.InputTag("elPFIsoValuePU03PFIdPF")
    #process.pfIsolatedElectronsPF.isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("elPFIsoValueNeutral03PFIdPF"), cms.InputTag("elPFIsoValueGamma03PFIdPF"))

    #process.pfMuons.isolationValueMapsCharged = cms.VInputTag(cms.InputTag("muPFIsoValueCharged03mu03"))
    #process.pfMuons.deltaBetaIsolationValueMap = cms.InputTag("muPFIsoValuePU03")
    #process.pfMuons.isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("muPFIsoValueNeutral03"), cms.InputTag("muPFIsoValueGamma03"))
    #process.pfIsolatedMuons.isolationValueMapsCharged = cms.VInputTag(cms.InputTag("muPFIsoValueCharged03mu03"))
    #process.pfIsolatedMuons.deltaBetaIsolationValueMap = cms.InputTag("muPFIsoValuePU03")
    #process.pfIsolatedMuons.isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("muPFIsoValueNeutral03"), cms.InputTag("muPFIsoValueGamma03"))

    #process.pfMuonsPF.isolationValueMapsCharged = cms.VInputTag(cms.InputTag("muPFIsoValueCharged03mu03PF"))
    #process.pfMuonsPF.deltaBetaIsolationValueMap = cms.InputTag("muPFIsoValuePU03PF")
    #process.pfMuonsPF.isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("muPFIsoValueNeutral03PF"), cms.InputTag("muPFIsoValueGamma03PF"))
    #process.pfIsolatedMuonsPF.isolationValueMapsCharged = cms.VInputTag(cms.InputTag("muPFIsoValueCharged03mu03PF"))
    #process.pfIsolatedMuonsPF.deltaBetaIsolationValueMap = cms.InputTag("muPFIsoValuePU03PF")
    #process.pfIsolatedMuonsPF.isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("muPFIsoValueNeutral03PF"), cms.InputTag("muPFIsoValueGamma03PF"))

    #-- Enable pileup sequence -------------------------------------------------------------
    #Vertices
    process.goodVertices = cms.EDFilter("VertexSelector",
        src = cms.InputTag("offlinePrimaryVertices"),
        cut = cms.string("!isFake && ndof > 4 && abs(z) <= 24 && position.Rho <= 2"),
        filter = cms.bool(False),
    )

    process.pfPileUpPF.Vertices = "goodVertices"
    process.pfPileUpPF.Enable = True

    process.pfNoPileUpSequencePF.replace(process.pfPileUpPF,
                                         process.goodVertices + process.pfPileUpPF)

    if not doSusyTopProjection:
        return
    #-- Top projection selection -----------------------------------------------------------
    #Electrons
    #relax all selectors *before* pat-lepton creation
    process.pfElectronsFromVertexPF.dzCut = 9999.0
    process.pfElectronsFromVertexPF.d0Cut = 9999.0
    process.pfSelectedElectronsPF.cut = ""
    process.pfRelaxedElectronsPF = process.pfIsolatedElectronsPF.clone(isolationCut = 3.)
    process.pfIsolatedElectronsPF.isolationCut = 0.15
    
    process.pfElectronsFromGoodVertex = cms.EDFilter(
        "IPCutPFCandidateSelector",
        src = cms.InputTag("pfIsolatedElectronsPF"),  # PFCandidate source
        vertices = cms.InputTag("goodVertices"),  # vertices source
        d0Cut = cms.double(0.04),  # transverse IP
        dzCut = cms.double(1.),  # longitudinal IP
        d0SigCut = cms.double(99.),  # transverse IP significance
        dzSigCut = cms.double(99.),  # longitudinal IP significance
    )
   
    electronSelection =  "abs( eta ) < 2.5 & pt > 5"
    electronSelection += " & mva_e_pi > 0.4" # same as patElectron::mva()
    #electronSelection += " & (isEB & (sigmaIetaIeta < 0.024 & hadronicOverEm < 0.15) | isEE & (sigmaIetaIeta < 0.040 & hadronicOverEm < 0.10))" #caloIdVL
    #electronSelection += " & (isEB & (deltaPhiSuperClusterTrackAtVtx < 0.15 & deltaEtaSuperClusterTrackAtVtx < 0.01) | isEE & (deltaPhiSuperClusterTrackAtVtx < 0.10 & deltaEtaSuperClusterTrackAtVtx < 0.01))" #trkIdVL
    electronSelection += " & gsfTrackRef().isNonnull() & gsfTrackRef().trackerExpectedHitsInner().numberOfHits() <= 0"
    process.pfUnclusteredElectronsPF = cms.EDFilter( "GenericPFCandidateSelector",
        src = cms.InputTag("pfElectronsFromGoodVertex"), #pfSelectedElectronsPF
        cut = cms.string(electronSelection)
    )    
    process.pfElectronSequencePF.replace(process.pfIsolatedElectronsPF,
                                         process.pfIsolatedElectronsPF + 
                                         process.goodVertices * process.pfElectronsFromGoodVertex + 
                                         process.pfUnclusteredElectronsPF + process.pfRelaxedElectronsPF)
    process.patElectronsPF.pfElectronSource = "pfRelaxedElectronsPF"
    process.pfNoElectronPF.topCollection  = "pfUnclusteredElectronsPF"
    #Muons
    #relaxe built-in preselection
    process.pfMuonsFromVertexPF.dzCut = 9999.0
    process.pfMuonsFromVertexPF.d0Cut = 9999.0
    process.pfSelectedMuonsPF.cut = ""
    process.pfRelaxedMuonsPF = process.pfIsolatedMuonsPF.clone(isolationCut = 3)
    process.pfIsolatedMuonsPF.isolationCut = 0.15
    
    process.pfMuonsFromGoodVertex = cms.EDFilter(
        "IPCutPFCandidateSelector",
        src = cms.InputTag("pfIsolatedMuonsPF"),  # PFCandidate source
        vertices = cms.InputTag("goodVertices"),  # vertices source
        d0Cut = cms.double(0.02),  # transverse IP
        dzCut = cms.double(1.),  # longitudinal IP
        d0SigCut = cms.double(99.),  # transverse IP significance
        dzSigCut = cms.double(99.),  # longitudinal IP significance
    )
    muonSelection =  "abs( eta ) < 2.5 & pt > 5"
    #GlobalMuonPromptTight
    muonSelection += " & muonRef().isNonnull & muonRef().isGlobalMuon()"
    muonSelection += " & muonRef().isTrackerMuon() & muonRef().numberOfMatches > 1"
    muonSelection += " & muonRef().globalTrack().normalizedChi2() < 10"
    muonSelection += " & muonRef().track().numberOfValidHits() > 10"
    muonSelection += " & muonRef().globalTrack().hitPattern().numberOfValidMuonHits() > 0"
    muonSelection += " & muonRef().innerTrack().hitPattern().numberOfValidPixelHits() > 0"
    process.pfUnclusteredMuonsPF = cms.EDFilter( "GenericPFCandidateSelector",
        src = cms.InputTag("pfMuonsFromGoodVertex"), #pfSelectedMuonsPF
        cut = cms.string(muonSelection)
    )    
    process.pfMuonSequencePF.replace(process.pfIsolatedMuonsPF,
                                     process.pfIsolatedMuonsPF + 
                                     process.goodVertices * process.pfMuonsFromGoodVertex +
                                     process.pfUnclusteredMuonsPF + process.pfRelaxedMuonsPF)
    process.patMuonsPF.pfMuonSource  = "pfRelaxedMuonsPF"
    process.pfNoMuonPF.topCollection = "pfUnclusteredMuonsPF"
예제 #8
0
# subtraction (CHS) applied. The latter is used to identify and remove
# particles from pileup, by associating their tracks with the non-main
# primary vertex. (The primary vertex collection is sorted by
# decreasing sum pT^2; the first one in the collection is usually
# taken as *the* primary vertex.) CHS is what is meant when the name
# "PFnoPileUp" is used.
#
# typeIMetCorrections = True indicates we want to apply the jet energy
# corrections in the MET calculation.

from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
usePF2PAT(
    process,
    runPF2PAT=True,
    postfix='PF',
    runOnMC=runOnMC,
    pvCollection=cms.InputTag('goodOfflinePrimaryVertices'),
    jetAlgo='AK5',
    jetCorrections=('AK5PFchs', jecLevels),
    typeIMetCorrections=True,
)

# Turn on the "top projections". This has nothing to do with top quark
# physics, but rather refers to separating sequentially out from the
# entire list of PF candidates the ones identified as pileup (from
# "wrong" primary vertices), muons, electrons, jets, and taus. The
# "No" in each collection name indicates the thing referred to has
# been removed. (See the above first set of slides for a example
# picture.) The input to the jet clustering is then taken from the
# pfNoTauPF -> pfJetsPF collection.

process.pfNoPileUpPF.enable = True
#switchOnTrigger(process) #create pat trigger objects

#process.load("RecoTauTag.Configuration.RecoPFTauTag_cff")

#removeMCMatching(process, ['All'])

from PhysicsTools.PatAlgos.tools.jetTools import *
from PhysicsTools.PatAlgos.tools import pfTools

jetCorrFactors = cms.vstring( 'L1FastJet', 'L2Relative', 'L3Absolute' )

pfTools.usePF2PAT( process,
                   runPF2PAT = True,
                   jetAlgo = 'AK5',
                   jetCorrections = ( 'AK5PFchs', jetCorrFactors, "" ),
                   #jetCorrections = ['L1FastJet', 'L2Relative', 'L3Absolute'],
                   runOnMC = runOnMC,
                   postfix = "PFlow",
                   pvCollection = cms.InputTag( 'goodOfflinePrimaryVertices' ),
                   outputModules = []
                   )

#switchJetCollection(
#        process,
#        cms.InputTag('ak5PFJets')
#        #doJTA = True
#        #doBTagging = True
#        #jetCorrLabel = _jetCorrections,
#        #doType1MET = False,
#        #doJetID = True,
#        #jetIdLabel = "ak5"
#)
예제 #10
0
process.maxEvents = cms.untracked.PSet(input=cms.untracked.int32(-1))
process.out.fileName = cms.untracked.string(
    os.path.expandvars('/tmp/${USER}/patTuple_PATandPF2PAT.root'))

# load the PAT config
process.load("PhysicsTools.PatAlgos.patSequences_cff")
process.load('CMGTools.ZmumuJetsTutorial.patTriggerMatching_cff')

#run PF2PAT
from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT

postfix = "PFlow"
usePF2PAT(process,
          runPF2PAT=True,
          jetAlgo="AK5",
          runOnMC=runOnMC,
          postfix=postfix)

# a loose offline muon selection
process.patMuonSelector = cms.EDFilter(
    "PATMuonSelector",
    src=cms.InputTag('patMuonsPFlow'),
    cut=cms.string("pt >= 10 && abs(eta) < 2.4"))
# we require 2 muons
process.patMuonFilter = cms.EDFilter("CandViewCountFilter",
                                     src=cms.InputTag('patMuonSelector'),
                                     minNumber=cms.uint32(2))
process.dimuonSkim = cms.Sequence(process.patMuonSelector +
                                  process.patMuonFilter)
예제 #11
0
                                                                numberOfFiles = 10
                                                               )
                                          )
        )

process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )
process.out.fileName = cms.untracked.string(os.path.expandvars('/tmp/${USER}/patTuple_PATandPF2PAT.root'))

# load the PAT config
process.load("PhysicsTools.PatAlgos.patSequences_cff")
process.load('CMGTools.ZmumuJetsTutorial.patTriggerMatching_cff')

#run PF2PAT
from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
postfix = "PFlow"
usePF2PAT(process,runPF2PAT=True, jetAlgo="AK5", runOnMC=runOnMC, postfix=postfix) 

# a loose offline muon selection
process.patMuonSelector = cms.EDFilter("PATMuonSelector",
    src = cms.InputTag('patMuonsPFlow'),
    cut =cms.string("pt >= 10 && abs(eta) < 2.4")
    )
# we require 2 muons
process.patMuonFilter = cms.EDFilter("CandViewCountFilter",
  src = cms.InputTag('patMuonSelector'),
  minNumber = cms.uint32(2)
)
process.dimuonSkim = cms.Sequence(process.patMuonSelector+process.patMuonFilter)

#this is used for bookeeping 
process.load("CMGTools.Common.countingSequences_cff")
def addPF2PATNoTauJets(process, mcInfo=True, jetCorrections=["L2Relative", "L3Absolute"]):
    ##Add the PF2PAT-no-tau-cleaning jet collection : postfix = PFLOW
    ##-- PAT standard config -------------------------------------------------------
    # process.load("PhysicsTools.PatAlgos.patSequences_cff")
    ##-- Jet corrections -----------------------------------------------------------
    # process.patJetCorrFactors.levels = options.jetCorrections
    from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT

    # -- PF2PAT config -------------------------------------------------------------
    usePF2PAT(
        process,
        runPF2PAT=True,
        jetAlgo="AK5",
        runOnMC=(mcInfo == 1),
        postfix="PFLOW",
        jetCorrections=("AK5PFchs", jetCorrections),
    )
    from PhysicsTools.PatAlgos.tools.pfTools import switchToPFJets

    switchToPFJets(
        process, cms.InputTag("pfJets" + "PFLOW"), "AK5", postfix="PFLOW", jetCorrections=("AK5PFchs", jetCorrections)
    )
    process.patJetsPFLOW.addTagInfos = cms.bool(True)
    process.patJetsPFLOW.tagInfoSources = cms.VInputTag("secondaryVertexTagInfosAODPFLOW")
    if "L1FastJet" in jetCorrections:
        process.pfJetsPFLOW.doAreaFastjet = True
    # from JetMETCorrections.Type1MET.MetType1Corrections_cff import metJESCorAK5PFJet
    # process.metJESCorAK5PFLOWTypeI = metJESCorAK5PFJet.clone(
    #    inputUncorJetsLabel = "patJetsPFLOW",
    #    metType = "pat",
    #    inputUncorMetLabel = "pfMet",
    #    )
    # process.patMETsTypeIPFLOW = process.patMETsPFLOW.clone(
    #    metSource = cms.InputTag("metJESCorAK5PFLOWTypeI")
    #    )
    ## Add to producersLayer1 sequence
    ##process.patDefaultSequencePFLOW.replace(
    # process.patPF2PATSequencePFLOW.replace(
    #    process.patMETsPFLOW,
    #    process.patMETsPFLOW+
    #    process.metJESCorAK5PFLOWTypeI+
    #    process.patMETsTypeIPFLOW
    #    )
    # Set isolation cone to 0.3
    process.isoValElectronWithChargedPFLOW.deposits[0].deltaR = 0.3
    process.isoValElectronWithNeutralPFLOW.deposits[0].deltaR = 0.3
    process.isoValElectronWithPhotonsPFLOW.deposits[0].deltaR = 0.3
    process.isoValMuonWithChargedPFLOW.deposits[0].deltaR = 0.3
    process.isoValMuonWithNeutralPFLOW.deposits[0].deltaR = 0.3
    process.isoValMuonWithPhotonsPFLOW.deposits[0].deltaR = 0.3

    # -- Enable pileup sequence -------------------------------------------------------------
    # Vertices
    process.goodVerticesPFLOW = cms.EDFilter(
        "VertexSelector",
        src=cms.InputTag("offlinePrimaryVertices"),
        cut=cms.string("!isFake && ndof > 4 && abs(z) <= 24 && position.Rho <= 2"),
        filter=cms.bool(False),
    )
    process.pfPileUpPFLOW.Vertices = "goodVerticesPFLOW"
    process.pfPileUpPFLOW.Enable = True

    process.pfNoPileUpSequencePFLOW.replace(process.pfPileUpPFLOW, process.goodVerticesPFLOW + process.pfPileUpPFLOW)
예제 #13
0
#addMETCollection(process, labelName='patMETsTypeIcorrected', metSource='pfType1CorrectedMet')
#addMETCollection(process, labelName='patMETTC', metSource='tcMet')

runOnMC=True
# An empty postfix means that only PF2PAT is run,
# otherwise both standard PAT and PF2PAT are run. In the latter case PF2PAT
# collections have standard names + postfix (e.g. patElectronPFlow)
postfix = ""
jetAlgo = "AK5"
#Define Objects to be excluded from Top Projection. Default is Tau, so objects are not cleaned for taus
excludeFromTopProjection=['Tau']

# Configure PAT to use PF2PAT instead of AOD sources
# this function will modify the PAT sequences.
from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
usePF2PAT(process, runPF2PAT=True, jetAlgo=jetAlgo, runOnMC=runOnMC, postfix=postfix, excludeFromTopProjection=excludeFromTopProjection)

#from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection
#from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection

## uncomment the following lines to add ak5PFJetsCHS to your PAT output
#postfixAK5PFCHS = 'Copy'
#addJetCollection(
#   process,
#   postfix = postfixAK5PFCHS,
#   labelName = 'AK5PFCHS',
#   jetSource = cms.InputTag('ak5PFJetsCHS'),
#   jetCorrections = ('AK5PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'Type-2')
#)
#process.out.outputCommands.append( 'drop *_selectedPatJetsAK5PFCHS%s_caloTowers_*'%( postfixAK5PFCHS ) )
예제 #14
0
## Create and define reco objects 
if runOnAOD:
    muonTag = 'patMuons' + pfpostfix  
    metTag = 'patMETs' + pfpostfix  
    
    ## Output module for edm files (needed for PAT sequence, even if not used in EndPath) 
    from Configuration.EventContent.EventContent_cff import FEVTEventContent
    process.out = cms.OutputModule("PoolOutputModule",
                                   FEVTEventContent,
                                   dataset = cms.untracked.PSet(dataTier = cms.untracked.string('RECO')),
                                   fileName = cms.untracked.string("eh.root"),
                                   )
    # add particle flow
    process.load("PhysicsTools.PatAlgos.patSequences_cff")
    from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
    usePF2PAT(process, runPF2PAT=True, jetAlgo='AK4', runOnMC=runOnMC, postfix=pfpostfix, 
              jetCorrections=jetCorr, pvCollection=cms.InputTag(opt.primaryVertexOptions['outputCollection']),typeIMetCorrections=True) 

    getattr(process, 'pfPileUp'+pfpostfix).checkClosestZVertex = False
    
    # switch off all top projections
    getattr(process,'pfNoMuon'+pfpostfix).enable = False
    getattr(process,'pfNoElectron'+pfpostfix).enable = False
    getattr(process,'pfNoJet'+pfpostfix).enable = False
    getattr(process,'pfNoTau'+pfpostfix).enable = False
    # agrohsje don't require isolation on cmsRun level !!! 
    # seems not to work -> check with python -i ?
    getattr(process,'pfIsolatedElectrons'+pfpostfix).isolationCut = cms.double(999999.) 
    getattr(process,'pfIsolatedMuons'+pfpostfix).isolationCut = cms.double(999999.)


else :
if useL3Absolute:
  jecLevels.append( 'L3Absolute' )
if useL2L3Residual and not runOnMC:
  jecLevels.append( 'L2L3Residual' )
if useL5Flavor:
  jecLevels.append( 'L5Flavor' )
if useL7Parton:
  jecLevels.append( 'L7Parton' )

### Switch configuration
import PhysicsTools.PatAlgos.tools.pfTools as pfTools
pfTools.usePF2PAT( process
         , runPF2PAT      = True #runPF2PAT
         , runOnMC        = runOnMC
         , jetAlgo        = patRefSel_refMuJets.jetAlgo
         , postfix        = postfix
         , jetCorrections = ( jecSetPF
                            , jecLevels
                            )
         )

pfTools.adaptPFTaus( process, tauType='hpsPFTau', postfix=postfix )
pfTools.applyPostfix( process, 'pfNoPileUp'  , postfix ).enable = usePFnoPU
pfTools.applyPostfix( process, 'pfNoMuon'    , postfix ).enable = useNoMuon
pfTools.applyPostfix( process, 'pfNoElectron', postfix ).enable = useNoElectron
pfTools.applyPostfix( process, 'pfNoJet'     , postfix ).enable = useNoJet
pfTools.applyPostfix( process, 'pfNoTau'     , postfix ).enable = useNoTau
pfTools.applyPostfix( process, 'pfPileUp', postfix ).Vertices = cms.InputTag( patRefSel_refMuJets.pfVertices )
if useL1FastJet:
  pfTools.applyPostfix( process, 'pfPileUp'   , postfix ).checkClosestZVertex = False
  pfTools.applyPostfix( process, 'pfPileUpIso', postfix ).checkClosestZVertex = usePfIsoLessCHS
예제 #16
0
if useL7Parton:
  jecLevels.append( 'L7Parton' )

### Switch configuration

if runPF2PAT:
  if useMuonCutBasePF:
    pfMuonSelectionCut += ' && %s'%( muonCutBase )
  if useElectronCutBasePF:
    pfElectronSelectionCut += ' && %s'%( electronCutBase )
  from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
  usePF2PAT( process
           , runPF2PAT      = runPF2PAT
           , runOnMC        = runOnMC
           , jetAlgo        = jetAlgo
           , postfix        = postfix
           , jetCorrections = ( jecSetPF
                              , jecLevels
                              )
           )
  applyPostfix( process, 'pfNoPileUp'  , postfix ).enable = usePFnoPU
  applyPostfix( process, 'pfNoMuon'    , postfix ).enable = useNoMuon
  applyPostfix( process, 'pfNoElectron', postfix ).enable = useNoElectron
  applyPostfix( process, 'pfNoJet'     , postfix ).enable = useNoJet
  applyPostfix( process, 'pfNoTau'     , postfix ).enable = useNoTau
  applyPostfix( process, 'pfPileUp', postfix ).Vertices = cms.InputTag( pfVertices )
  if useL1FastJet:
    applyPostfix( process, 'pfPileUp', postfix ).checkClosestZVertex = False
    applyPostfix( process, 'pfJets', postfix ).doAreaFastjet = True
    applyPostfix( process, 'pfJets', postfix ).doRhoFastjet  = False
  applyPostfix( process, 'pfMuonsFromVertex'    , postfix ).vertices = cms.InputTag( pfVertices )
예제 #17
0
## Load trigger matching
## Trigger matching with PAT
process.load("MuonAnalysis.MuonAssociators.patMuonsWithTrigger_cff")
process.muonMatchHLTL2.maxDeltaR = 0.3  # Zoltan tuning - it was 0.5
process.muonMatchHLTL3.maxDeltaR = 0.1

## Apply PF2PAT
from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
if runOnMC: jecLevels = ['L1FastJet', 'L2Relative', 'L3Absolute']
else: jecLevels = ['L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual']

#usePFBRECO(process,runPFBRECO=True,
usePF2PAT(process,
          runPF2PAT=True,
          runOnMC=runOnMC,
          outputModules=outputModules,
          postfix="PFlow",
          jetAlgo="AK5",
          jetCorrections=("AK5PFchs", jecLevels),
          typeIMetCorrections=True)

# top projections in PF2PAT:
process.pfNoPileUpPFlow.enable = True
process.pfNoMuonPFlow.enable = True
process.pfNoElectronPFlow.enable = True
process.pfNoTauPFlow.enable = False
process.pfNoJetPFlow.enable = True

# verbose flags for the PF2PAT modules
process.pfNoMuonPFlow.verbose = False
"""
# Change DR cone size to 0.3
예제 #18
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
def createProcess(isMC, globalTag):

    import FWCore.ParameterSet.Config as cms

    #####
    # Init the process with some default options
    #####

    process = cms.Process("PAT")

    ## MessageLogger
    process.load("FWCore.MessageLogger.MessageLogger_cfi")

    ## Options and Output Report
    process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True),
            allowUnscheduled = cms.untracked.bool(True) )

    ## Source
    process.source = cms.Source("PoolSource",
            fileNames = cms.untracked.vstring()
            )

    ## Maximal Number of Events
    process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) )

    ## Geometry and Detector Conditions (needed for a few patTuple production steps)
    process.load("Configuration.Geometry.GeometryIdeal_cff")
    process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
    process.GlobalTag.globaltag = cms.string("%s::All" % globalTag)
    process.load("Configuration.StandardSequences.MagneticField_cff")

    ## Output Module Configuration (expects a path 'p')
    from PhysicsTools.PatAlgos.patEventContent_cff import patEventContentNoCleaning
    process.out = cms.OutputModule("PoolOutputModule",
            fileName = cms.untracked.string('patTuple.root'),
            ## save only events passing the full path
            #SelectEvents = cms.untracked.PSet( SelectEvents = cms.vstring('p') ),
            ## save PAT output; you need a '*' to unpack the list of commands
            ## 'patEventContent'
            outputCommands = cms.untracked.vstring('drop *', *patEventContentNoCleaning )
            )

    process.outpath = cms.EndPath(process.out)

    #####
    # Customize process for top pat Tuples production
    #####

    print("Loading python config...")

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

    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 = cms.PSet(minNdof = cms.double(4.), maxZ = cms.double(24.) , maxRho = cms.double(2.)),
            filter = cms.bool(True),
            src = cms.InputTag('offlinePrimaryVertices')
            )

    from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT, adaptPFIsoElectrons

    postfix = "PFlow"
    jetAlgo = "AK5"
    # Jet corrections when using CHS (L2L3Residual IS mandatory on data)

    if isMC:
        jetCorrections = ('AK5PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'] )
    else:
        jetCorrections = ('AK5PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual'] )

    # Jet corrections when NOT using CHS
    #jetCorrections = ('AK5PF', ['L1FastJet','L2Relative','L3Absolute'] )

    # Type I MET enabled
    usePF2PAT(process, runPF2PAT=True, jetAlgo=jetAlgo, runOnMC=isMC , postfix=postfix, jetCorrections = jetCorrections, typeIMetCorrections=True, pvCollection = cms.InputTag('goodOfflinePrimaryVertices'))

    # We want:
    # - Uncorrected MEt: patMETsRawPFlow
    # - Type I corrected MEt: patMETsPFlow
    # - Type 0+I correct MEt: patMETsType0p1PFlow

    # Create PAT MEt from raw MEt collection (pfMET<postfix>))
    setattr(process, "patMETsRaw%s" % postfix, getattr(process, "patMETs%s" % postfix).clone( metSource = cms.InputTag("pfMET%s" % (postfix)) ))

    # Type 0, 1 or 2 corrected MEt is produced by the module CorrectedPFMETProducer

    # Clone the module <jetcorrectorlabel>Type1CorMet<postfix> (eg, AK5PFchschsTypeICorMetPFlow),
    # to create a Type 0 + I MEt

    setattr(process, "%sType0p1CorMet%s" % (jetCorrections[0], postfix), getattr(process, "%sType1CorMet%s" % (jetCorrections[0], postfix)).clone( applyType0Corrections = cms.bool(True), srcCHSSums = cms.VInputTag("pfchsMETcorr%s:type0" % postfix) ))

    # Now, convert the PF met to patMET. Clone patMETs<postfix>

    setattr(process, "patMETsType0p1%s" % postfix, getattr(process, "patMETs%s" % postfix).clone( metSource = cms.InputTag("%sType0p1CorMet%s" % (jetCorrections[0], postfix)) ))

    #####
    # Add sys shift correction to our Met
    #####

    # Output:
    # - Type I + sys shift: patMETsSysShiftPFlow
    # - Type 0 + I + sys shift: patMETsType0p1pSysShiftPFlow

    #process.load("JetMETCorrections.Type1MET.pfMETCorrections_cff")
    process.load("JetMETCorrections.Type1MET.pfMETsysShiftCorrections_cfi")

    if not isMC:
        process.pfMEtSysShiftCorr.parameter = process.pfMEtSysShiftCorrParameters_2012runABCDvsNvtx_data
    else:
        process.pfMEtSysShiftCorr.parameter = process.pfMEtSysShiftCorrParameters_2012runABCDvsNvtx_mc

    # Clone the Type I MEt producer and add Sys Shift corrections
    setattr(process, "%sType1pSysShiftCorMet%s" % (jetCorrections[0], postfix), getattr(process, "%sType1CorMet%s" % (jetCorrections[0], postfix)).clone())
    getattr(process, "%sType1pSysShiftCorMet%s" % (jetCorrections[0], postfix)).srcType1Corrections.append(
            cms.InputTag('pfMEtSysShiftCorr')
            )

    # Clone the Type 0+I MEt producer and add Sys Shift corrections
    setattr(process, "%sType0p1pSysShiftCorMet%s" % (jetCorrections[0], postfix), getattr(process, "%sType0p1CorMet%s" % (jetCorrections[0], postfix)).clone())
    getattr(process, "%sType0p1pSysShiftCorMet%s" % (jetCorrections[0], postfix)).srcType1Corrections.append(
            cms.InputTag('pfMEtSysShiftCorr')
            )

    # Convert PF MEt to PAT MEt
    setattr(process, "patMETsSysShift%s" % postfix, getattr(process, "patMETs%s" % postfix).clone( metSource = cms.InputTag("%sType1pSysShiftCorMet%s" % (jetCorrections[0], postfix)) ))

    setattr(process, "patMETsType0p1pShiftCorr%s" % postfix, getattr(process, "patMETs%s" % postfix).clone( metSource = cms.InputTag("%sType0p1pSysShiftCorMet%s" % (jetCorrections[0], postfix)) ))

    getattr(process, "pfJets%s" % postfix).doAreaFastjet = True
    getattr(process, "pfJets%s" % postfix).doRhoFastjet = False

    # Should be fine in recent version of PAT, but in case of...
    #process.patJetCorrFactorsPFlow.rho = cms.InputTag("kt6PFJets", "rho")

    #####
    # Configure muon & electron isolation cuts
    #####

    # Electrons need a deltaR = 0.3 cone for isolation values.

    from PhysicsTools.PatAlgos.tools.helpers import loadWithPostfix

    loadWithPostfix(process, "CommonTools.ParticleFlow.Isolation.pfElectronIsolation_cff", postfix)

    # Fix input tags
    deposit = getattr(process, "elPFIsoDepositCharged%s" % postfix)
    deposit.src = cms.InputTag("pfSelectedElectrons%s" % postfix)
    deposit.ExtractorPSet.inputCandView = cms.InputTag("pfAllChargedHadrons%s" % postfix)

    deposit = getattr(process, "elPFIsoDepositChargedAll%s" % postfix)
    deposit.src = cms.InputTag("pfSelectedElectrons%s" % postfix)
    deposit.ExtractorPSet.inputCandView = cms.InputTag("pfAllChargedParticles%s" % postfix)

    deposit = getattr(process, "elPFIsoDepositGamma%s" % postfix)
    deposit.src = cms.InputTag("pfSelectedElectrons%s" % postfix)
    deposit.ExtractorPSet.inputCandView = cms.InputTag("pfAllPhotons%s" % postfix)

    deposit = getattr(process, "elPFIsoDepositNeutral%s" % postfix)
    deposit.src = cms.InputTag("pfSelectedElectrons%s" % postfix)
    deposit.ExtractorPSet.inputCandView = cms.InputTag("pfAllNeutralHadrons%s" % postfix)

    deposit = getattr(process, "elPFIsoDepositPU%s" % postfix)
    deposit.src = cms.InputTag("pfSelectedElectrons%s" % postfix)
    deposit.ExtractorPSet.inputCandView = cms.InputTag("pfPileUpAllChargedParticles%s" % postfix)

    # Adapt cut for pfSelectedElectrons
    # Default cut: pt > 5 & gsfElectronRef.isAvailable() & gsfTrackRef.trackerExpectedHitsInner.numberOfLostHits<2

    setattr(process, "pfSelectedElectrons%s" % postfix, cms.EDFilter(
        "GenericPFCandidateSelector",
        src = cms.InputTag("pfElectronsFromVertex%s" % postfix),
        cut = cms.string("pt > 10 && gsfTrackRef.isNonnull && gsfTrackRef.trackerExpectedHitsInner.numberOfLostHits<2")
        )
        )

    process.pfIsolatedElectronsClones  = cms.EDFilter(
            "IsolatedPFCandidateSelector",
            src = cms.InputTag("pfSelectedElectrons%s" % postfix),
            isolationValueMapsCharged = cms.VInputTag(
                cms.InputTag("elPFIsoValueCharged03PFId%s" % postfix),
                ),
            isolationValueMapsNeutral = cms.VInputTag(
                cms.InputTag("elPFIsoValueNeutral03PFId%s" % postfix),
                cms.InputTag("elPFIsoValueGamma03PFId%s" % postfix)
                ),
            doDeltaBetaCorrection = cms.bool(False),
            deltaBetaIsolationValueMap = cms.InputTag("elPFIsoValuePU03PFId%s" % postfix),
            deltaBetaFactor = cms.double(-0.5),
            ## if True isolation is relative to pT
            isRelative = cms.bool(True),
            isolationCut = cms.double(0.10),
            ## Added in attached patch
            doEffectiveAreaCorrection = cms.bool(True),
            effectiveAreas = cms.InputTag("elEffectiveAreas03%s" % postfix),
            rho = cms.InputTag("kt6PFJets", "rho")
            )

    pfIsolatedElectrons = cms.EDFilter("PFCandidateFwdPtrCollectionStringFilter",
            src = cms.InputTag("pfIsolatedElectronsClones"),
            cut = cms.string(""),
            makeClones = cms.bool(True)
            )

    # Override default electron collection by our new one
    setattr(process, "pfIsolatedElectrons%s" % postfix, pfIsolatedElectrons) 

    # Set correct isolation deposits for patElectron production
    # FIXME: This should be enable if we want to recompute isolation from the pat electrons collections.
    # Unfortunately, it crashes sometimes when accessing deposits, because they are created from
    # pfSelectedElectrons<postfix> and patElectrons<postfix> red deposits using electrons coming from
    # pfIsolatedElectrons<postfix>.

    # adaptPFIsoElectrons(process, getattr(process, "patElectrons%s" % postfix), postfix, "03")

    # Produce electron conversions selection for Electron ID
    process.patConversions = cms.EDProducer("PATConversionProducer",
            # input collection
            electronSource = cms.InputTag("selectedPatElectrons%s" % postfix)
            # this should be your last selected electron collection name since currently index is used to match with electron later. We can fix this using reference pointer.
            )

    # Produce electron conversions selection for Electron ID
    process.patConversionsLoose = cms.EDProducer("PATConversionProducer",
            # input collection
            electronSource = cms.InputTag("selectedPatElectronsLoose%s" % postfix)
            # this should be your last selected electron collection name since currently index is used to match with electron later. We can fix this using reference pointer.
            )

    # Enable deltaBeta correction for muon isolation
    # Default cut from https://github.com/cms-sw/cmssw/blob/CMSSW_6_2_X/CommonTools/ParticleFlow/python/Isolation/pfIsolatedMuons_cfi.py
    # pt > 5 & muonRef.isAvailable() & muonRef.pfIsolationR04().sumChargedHadronPt + muonRef.pfIsolationR04().sumNeutralHadronEt + 
    #   muonRef.pfIsolationR04().sumPhotonEt < 0.15 * pt
    # deltaBeta isolation is: [sumChargedHadronPt + max(0., sumNeutralHadronPt + sumPhotonPt - 0.5 * sumPUPt] / pt

    # pt > 10, global muon, deltaBeta isolation < 0.12
    cut = "pt > 10 & muonRef.isAvailable() & muonRef.isGlobalMuon() & ((muonRef.pfIsolationR04().sumChargedHadronPt + max(0.0, muonRef.pfIsolationR04().sumNeutralHadronEt + muonRef.pfIsolationR04().sumPhotonEt - 0.5 * muonRef.pfIsolationR04().sumPUPt)) < 0.12 * pt)"
    getattr(process, "pfIsolatedMuons%s" % postfix).cut = cut

    #process.load('EGamma.EGammaAnalysisTools.electronIdMVAProducer_cfi') 
    #process.eidMVASequence = cms.Sequence(process.mvaTrigV0 + process.mvaNonTrigV0)
    ##Electron ID
    #process.patElectronsPFlow.electronIDSources.mvaTrigV0    = cms.InputTag("mvaTrigV0")
    #process.patElectronsPFlow.electronIDSources.mvaNonTrigV0 = cms.InputTag("mvaNonTrigV0") 
    #process.patDefaultSequencePFlow.replace(process.patElectronsPFlow, process.eidMVASequence * process.patElectronsPFlow)

    # Compute effective areas for correcting isolation
    loadWithPostfix(process, "PatTopProduction.Tools.electronEffectiveAreaProducer_cfi", postfix)

    getattr(process, "elEffectiveAreas03%s" % postfix).src = cms.InputTag("pfSelectedElectrons%s" % postfix)

    if isMC:
        getattr(process, "elEffectiveAreas03%s" % postfix).target = cms.string("EAFall11MC")

    #####
    # PAT object configuration
    #####

    # jets
    process.selectedPatJetsPFlow.cut = 'pt > 10. & abs(eta) < 3.'

    # muons
    process.patMuonsPFlow.usePV = False
    process.patMuonsPFlow.embedTrack = True

    # electrons
    process.patElectronsPFlow.usePV = False
    process.patElectronsPFlow.embedTrack = True

    #####
    # Loose collections with no isolation cut applied
    # Clone selectedPatMuons / selectedPatElectrons, and use in input pfMuons / pfElectrons
    #####

    setattr(process, "selectedPatMuonsLoose%s" % postfix, getattr(process, "patMuons%s" % postfix).clone(
        pfMuonSource = cms.InputTag("pfMuons%s" % postfix),
        embedGenMatch = False,
        addGenMatch = False
        )
        )

    setattr(process, "selectedPatElectronsLoose%s" % postfix, getattr(process, "patElectrons%s" % postfix).clone(
        pfElectronSource = cms.InputTag("pfSelectedElectrons%s" % postfix),
        embedGenMatch = False,
        addGenMatch = False
        )
        )


    adaptPFIsoElectrons(process, getattr(process, "selectedPatElectronsLoose%s" % postfix), postfix, "03")

    if not isMC:
        removeMCMatchingPF2PAT(process, '') 

    #####
    # P2FPAT is done. Now setup some filters
    #####

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

    # require scraping filter
    if not isMC:
        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)
                )

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

    # Remove uneeded filter
    del(process.tobtecfakesfilter)

    # Add PF2PAT output to the created file
    from PhysicsTools.PatAlgos.patEventContent_cff import patEventContentNoCleaning
    process.out.outputCommands = cms.untracked.vstring('drop *',
            'keep GenEventInfoProduct_generator_*_*',
            'keep *_genParticles*_*_*',
            'keep edmTriggerResults_*_*_*',
            'keep *_*fflinePrimaryVertices_*_*', # It's NOT a typo
            'keep recoPFCandidates_particleFlow_*_*',
            'keep PileupSummaryInfos_*_*_*',
            'keep double_kt6PFJets*_rho_*',
            'keep *_patConversions*_*_*',
            *patEventContentNoCleaning ) 

    process.out.outputCommands += [
            'drop *_selectedPatJetsForMET*_*_*',
            'drop *_selectedPatJets*_pfCandidates_*',
            'keep *_patMETsRaw*_*_PAT', # Keep raw met
            'keep *_allConversions*_*_*',

            # For isolations and conversions vetoes
            'keep *_gsfElectron*_*_*',
            'keep *_offlineBeamSpot*_*_*'
            ]

    # RelVal in inputs
    #from PhysicsTools.PatAlgos.tools.cmsswVersionTools import pickRelValInputFiles
    #process.source.fileNames = pickRelValInputFiles(cmsswVersion = "CMSSW_5_3_6", globalTag = "PU_START53_V14", debug = True, numberOfFiles = 1)

    process.options.wantSummary = False

    process.MessageLogger.cerr.FwkReport.reportEvery = 1

    print("Config loaded")

    return process
  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)
예제 #21
0
def loadPF2PAT(process,mcInfo,jetMetCorrections,extMatch,doSusyTopProjection,postfix):
    #-- PAT standard config -------------------------------------------------------
    process.load("PhysicsTools.PatAlgos.patSequences_cff")
    #-- Jet corrections -----------------------------------------------------------
    process.patJetCorrFactors.levels = jetMetCorrections 
    #-- PF2PAT config -------------------------------------------------------------
    from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
    usePF2PAT(process,runPF2PAT=True, jetAlgo='AK5',runOnMC=(mcInfo==1),postfix=postfix)
    #process.patJetsPF.embedGenJetMatch = False
    #process.patJetsPF.embedPFCandidates = False
    #drop tracks 
    process.patElectronsPF.embedTrack = True
    process.patMuonsPF.embedTrack   = True
    process.electronMatchPF.maxDeltaR   = cms.double(0.2)
    process.electronMatchPF.maxDPtRel   = cms.double(999999.)
    process.electronMatchPF.checkCharge = False
    process.muonMatchPF.maxDeltaR   = cms.double(0.2)
    process.muonMatchPF.maxDPtRel   = cms.double(999999.)
    process.muonMatchPF.checkCharge = False
    if extMatch:
        process.electronMatchPF.mcStatus = cms.vint32(1,5)
        process.electronMatchPF.matched = "mergedTruth"
        process.muonMatchPF.mcStatus = cms.vint32(1,5)
        process.muonMatchPF.matched = "mergedTruth"
        process.genParticlesForJets.src = "mergedTruth"
        process.genParticlesForJetsNoMuNoNu.src = "mergedTruth"
        process.genParticlesForJetsNoNu.src = "mergedTruth"
        process.patJetPartonMatchPF.matched = "mergedTruth"
        process.patJetPartonsPF.src = "mergedTruth"
        process.photonMatchPF.matched = "mergedTruth"
        process.tauGenJetsPF.GenParticles = "mergedTruth"
        process.tauMatchPF.matched = "mergedTruth"
        
    #Remove jet pt cut
    #process.pfJetsPF.ptMin = 0.
    #include tau decay mode in pat::Taus (elese it will just be uninitialized)
    #process.patTausPF.addDecayMode = True
    #process.patTausPF.decayModeSrc = "shrinkingConePFTauDecayModeProducerPF" 

    #PF type I corrected MET
    addPFTypeIMet(process)

    #Set isolation cone to 0.3
    process.isoValElectronWithChargedPF.deposits.deltaR = 0.3
    process.isoValElectronWithNeutralPF.deposits.deltaR = 0.3
    process.isoValElectronWithPhotonsPF.deposits.deltaR = 0.3
    process.isoValMuonWithChargedPF.deposits.deltaR = 0.3
    process.isoValMuonWithNeutralPF.deposits.deltaR = 0.3
    process.isoValMuonWithPhotonsPF.deposits.deltaR = 0.3

    #-- Enable pileup sequence -------------------------------------------------------------
    process.pfPileUpPF.Vertices = "offlinePrimaryVertices"
    process.pfPileUpPF.Enable = True    

    if not doSusyTopProjection:
        return
    #-- Top projection selection -----------------------------------------------------------
    #Vertices
    process.goodVertices = cms.EDFilter("VertexSelector",
        src = cms.InputTag("offlinePrimaryVertices"),
        cut = cms.string("!isFake && ndof > 4 && abs(z) <= 24 && position.Rho <= 2"),
        filter = cms.bool(False),
    )
    #Electrons
    #relax all selectors *before* pat-lepton creation
    process.pfElectronsFromVertexPF.dzCut = 9999.0
    process.pfElectronsFromVertexPF.d0Cut = 9999.0
    process.pfSelectedElectronsPF.cut = ""
    process.pfRelaxedElectronsPF = process.pfIsolatedElectronsPF.clone(combinedIsolationCut = 3.)
    
    process.pfIsolatedElectronsPF.combinedIsolationCut = 0.15
    process.pfElectronsFromGoodVertex = cms.EDFilter(
        "IPCutPFCandidateSelector",
        src = cms.InputTag("pfIsolatedElectronsPF"),  # PFCandidate source
        vertices = cms.InputTag("goodVertices"),  # vertices source
        d0Cut = cms.double(0.04),  # transverse IP
        dzCut = cms.double(1.),  # longitudinal IP
        d0SigCut = cms.double(99.),  # transverse IP significance
        dzSigCut = cms.double(99.),  # longitudinal IP significance
    )
   
    electronSelection =  "abs( eta ) < 2.5 & pt > 5"
    electronSelection += " & mva_e_pi > 0.4" # same as patElectron::mva()
    electronSelection += " & gsfTrackRef().isNonnull() & gsfTrackRef().trackerExpectedHitsInner().numberOfHits() < 1"
    process.pfUnclusteredElectronsPF = cms.EDFilter( "GenericPFCandidateSelector",
        src = cms.InputTag("pfElectronsFromGoodVertex"), #pfSelectedElectronsPF
        cut = cms.string(electronSelection)
    )    
    process.pfElectronSequencePF.replace(process.pfIsolatedElectronsPF,
                                         process.pfIsolatedElectronsPF + 
                                         process.goodVertices * process.pfElectronsFromGoodVertex + 
                                         process.pfUnclusteredElectronsPF + process.pfRelaxedElectronsPF)
    process.patElectronsPF.pfElectronSource = "pfRelaxedElectronsPF"
    process.pfNoElectronPF.topCollection  = "pfUnclusteredElectronsPF"
    #Muons
    #relaxe built-in preselection
    process.pfMuonsFromVertexPF.dzCut = 9999.0
    process.pfMuonsFromVertexPF.d0Cut = 9999.0
    process.pfSelectedMuonsPF.cut = ""
    process.pfRelaxedMuonsPF = process.pfIsolatedMuonsPF.clone(combinedIsolationCut = 3)
    
    process.pfIsolatedMuonsPF.combinedIsolationCut = 0.15
    process.pfMuonsFromGoodVertex = cms.EDFilter(
        "IPCutPFCandidateSelector",
        src = cms.InputTag("pfIsolatedMuonsPF"),  # PFCandidate source
        vertices = cms.InputTag("goodVertices"),  # vertices source
        d0Cut = cms.double(0.02),  # transverse IP
        dzCut = cms.double(1.),  # longitudinal IP
        d0SigCut = cms.double(99.),  # transverse IP significance
        dzSigCut = cms.double(99.),  # longitudinal IP significance
    )
    muonSelection =  "abs( eta ) < 2.5 & pt > 5"
    #GlobalMuonPromptTight
    muonSelection += " & muonRef().isNonnull & muonRef().isGlobalMuon()"
    muonSelection += " & muonRef().isTrackerMuon() & muonRef().numberOfMatches > 1"
    muonSelection += " & muonRef().globalTrack().normalizedChi2() < 10"
    muonSelection += " & muonRef().track().numberOfValidHits() > 10"
    muonSelection += " & muonRef().globalTrack().hitPattern().numberOfValidMuonHits() > 0"
    muonSelection += " & muonRef().innerTrack().hitPattern().numberOfValidPixelHits() > 0"
    process.pfUnclusteredMuonsPF = cms.EDFilter( "GenericPFCandidateSelector",
        src = cms.InputTag("pfMuonsFromGoodVertex"), #pfSelectedMuonsPF
        cut = cms.string(muonSelection)
    )    
    process.pfMuonSequencePF.replace(process.pfIsolatedMuonsPF,
                                     process.pfIsolatedMuonsPF + 
                                     process.goodVertices * process.pfMuonsFromGoodVertex +
                                     process.pfUnclusteredMuonsPF + process.pfRelaxedMuonsPF)
    process.patMuonsPF.pfMuonSource  = "pfRelaxedMuonsPF"
    process.pfNoMuonPF.topCollection = "pfUnclusteredMuonsPF"
    #Taus
    process.pfTausPF.discriminators = cms.VPSet()
    process.pfUnclusteredTausPF = process.pfTausPF.clone(
        cut = cms.string("pt < 0")
    )
    process.pfTauSequencePF.replace(process.pfTausPF, process.pfTausPF+ process.pfUnclusteredTausPF)
    process.pfNoTauPF.topCollection = "pfUnclusteredTausPF"
예제 #22
0
    "PoolOutputModule",
    fileName=cms.untracked.string('patTuple.root'),
    # save only events passing the full path
    SelectEvents=cms.untracked.PSet(SelectEvents=cms.vstring('p')),
    # save PAT Layer 1 output; you need a '*' to
    # unpack the list of commands 'patEventContent'
    outputCommands=cms.untracked.vstring('drop *', *patEventContent))
#from PhysicsTools.PatAlgos.tools.coreTools import *
#removeAllPATObjectsBut(process, ['Jets'])
from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
postfix = "PFlow"
usePF2PAT(process,
          runPF2PAT=True,
          jetAlgo='AK5',
          runOnMC=False,
          postfix=postfix,
          jetCorrections=('AK5PFchs', [
              'L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual'
          ]),
          pvCollection=cms.InputTag('offlinePrimaryVertices'))
process.pfPileUpPFlow.checkClosestZVertex = False
getattr(process, "patPF2PATSequence" + postfix).remove(
    getattr(process, "cleanPatCandidates" + postfix))
getattr(process, "patPF2PATSequence" + postfix).remove(
    getattr(process, "countPatCandidates" + postfix))
process.patseq = cms.Sequence(getattr(process, "patPF2PATSequence" + postfix))
process.pat_step = cms.Path(process.patseq)

######Pileup Jet ID (Hendrik)
#https://twiki.cern.ch/twiki/bin/view/CMS/PileupJetID#Running_the_algorithm_on_reco_je
from CMGTools.External.pujetidsequence_cff import puJetId, puJetMva
예제 #23
0
    inputJetCorrLabel = ('AK5PF', ['L1FastJet', 'L2Relative', 'L3Absolute'])
else:
    inputJetCorrLabel = ('AK5PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'])

if runOnData:
    inputJetCorrLabel[1].append('L2L3Residual')


# PF2PAT setup. The code snippet is inspired by [1]. In order to make life simplier, the (empty)
# postfix is hard-coded. See [2] for information on MET corrections with PFBRECO and PAT
# [1] http://cmssw.cvs.cern.ch/cgi-bin/cmssw.cgi/CMSSW/PhysicsTools/PatExamples/test/patTuple_52x_jec_cfg.py?revision=1.1&view=markup
# [2] https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookMetAnalysis#Type_I_II_0_with_PF2PAT
from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
usePF2PAT(process, runPF2PAT = True, runOnMC = not runOnData, postfix = '',
    jetAlgo = 'AK5', jetCorrections = inputJetCorrLabel,
    pvCollection = cms.InputTag('goodOfflinePrimaryVertices'),
    typeIMetCorrections = runOnData,  # in case of MC the corrections are added with MET unc. tool
    outputModules = [])

# A recommended setting for JEC with CHS
# https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookJetEnergyCorrections#JetEnCorPFnoPU2012
process.pfPileUp.checkClosestZVertex = False


# We do not consider tau-leptons in the analysis (they are included in jets)
process.pfNoTau.enable = False



# Define the leptons
from UserCode.SingleTop.ObjectsDefinitions_cff import *
예제 #24
0
if useL2L3Residual and not runOnMC:
  jecLevels.append( 'L2L3Residual' )
if useL5Flavor:
  jecLevels.append( 'L5Flavor' )
if useL7Parton:
  jecLevels.append( 'L7Parton' )

### Switch configuration

if runPF2PAT:
  from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
  usePF2PAT( process
           , runPF2PAT      = runPF2PAT
           , runOnMC        = runOnMC
           , jetAlgo        = jetAlgo
           , postfix        = postfix
           , jetCorrections = ( jecSetPF
                              , jecLevels
                              )
           )
  applyPostfix( process, 'pfNoPileUp'  , postfix ).enable = usePFnoPU
  applyPostfix( process, 'pfNoMuon'    , postfix ).enable = useNoMuon
  applyPostfix( process, 'pfNoElectron', postfix ).enable = useNoElectron
  applyPostfix( process, 'pfNoJet'     , postfix ).enable = useNoJet
  applyPostfix( process, 'pfNoTau'     , postfix ).enable = useNoTau
  if useL1FastJet:
    applyPostfix( process, 'pfPileUp', postfix ).Vertices            = cms.InputTag( pfVertices )
    applyPostfix( process, 'pfPileUp', postfix ).checkClosestZVertex = False
    applyPostfix( process, 'pfJets', postfix ).doAreaFastjet = True
    applyPostfix( process, 'pfJets', postfix ).doRhoFastjet  = False
  applyPostfix( process, 'pfMuonsFromVertex'    , postfix ).vertices = cms.InputTag( pfVertices )
예제 #25
0
def addPATSequences(process, runMC):
    # Load the PAT config
    from PhysicsTools.PatAlgos.patEventContent_cff import patEventContent
    process.out = cms.OutputModule(
        "PoolOutputModule",
        fileName=cms.untracked.string('patTuple.root'),
        SelectEvents=cms.untracked.PSet(SelectEvents=cms.vstring('pat_step')),
        outputCommands=cms.untracked.vstring('drop *', *patEventContent))
    ###
    process.load('PhysicsTools.PatAlgos.patSequences_cff')

    from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
    postfix = "PFlow"
    jetAlgo = "AK5"
    jetCorrections = None
    if runMC:
        jetCorrections = ('AK5PFchs',
                          ['L1FastJet', 'L2Relative', 'L3Absolute'])
    else:
        jetCorrections = ('AK5PFchs', [
            'L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual'
        ])

    usePF2PAT(process,
              runPF2PAT=True,
              jetAlgo=jetAlgo,
              runOnMC=runMC,
              postfix=postfix,
              jetCorrections=jetCorrections)

    #from PhysicsTools.PatAlgos.tools.coreTools import removeMCMatching
    #if not runMC:
    #    removeMCMatching(process, ['All'],"")

    #-----------------Customization----------------
    process.pfPileUpPFlow.Enable = True
    process.pfPileUpPFlow.checkClosestZVertex = False
    process.pfPileUpPFlow.Vertices = cms.InputTag('goodOfflinePrimaryVertices')
    process.pfPileUpPFlow.verbose = True
    process.pfJetsPFlow.doAreaFastjet = True
    process.pfJetsPFlow.doRhoFastjet = False

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

    # Compute the mean pt per unit area (rho) from the PFCHS inputs
    #from RecoJets.Configuration.RecoPFJets_cff import kt6PFJets,ak5PFJets
    #process.kt6PFJetsPFlow = kt6PFJets.clone(
    #	src = cms.InputTag('pfNoElectron'+postfix),
    #	doAreaFastjet = cms.bool(True),
    #	doRhoFastjet = cms.bool(True)
    #	)
    #process.patJetCorrFactorsPFlow.rho = cms.InputTag("kt6PFJetsPFlow", "rho")
    from RecoJets.JetProducers.kt4PFJets_cfi import kt4PFJets
    process.kt6PFJetsForPAT = kt4PFJets.clone(rParam=cms.double(0.6),
                                              doAreaFastjet=cms.bool(True),
                                              doRhoFastjet=cms.bool(True))
    process.patJetCorrFactorsPFlow.rho = cms.InputTag("kt6PFJetsForPAT", "rho")

    from RecoJets.JetProducers.ak5PFJets_cfi import ak5PFJets
    process.ak5PFJetsPileUp = ak5PFJets.clone(src=cms.InputTag('pfPileUp' +
                                                               postfix))

    # Switch on PAT trigger
    from PhysicsTools.PatAlgos.tools.trigTools import switchOnTrigger
    #switchOnTrigger( process,triggerProducer = 'patTrigger', triggerEventProducer = 'patTriggerEvent', sequence = 'patPF2PATSequence',hltProcess = 'HLT', outputModule = 'out')

    switchOnTrigger(process, sequence='patPF2PATSequence' + postfix)
    process.patTrigger.addL1Algos = cms.bool(True)
    switchOnTrigger(process, sequence='patPF2PATSequence' +
                    postfix)  # to fix event content
    #-------------------------------------------------------------------------------------------------------------

    # Add modules to default sequence
    #if runMC:
    #    getattr(process, "patElectrons"+postfix).embedGenMatch = True
    #    getattr(process, "patMuons"+postfix).embedGenMatch = True
    #else:
    #    getattr(process, "patElectrons"+postfix).embedGenMatch = False
    #    getattr(process, "patMuons"+postfix).embedGenMatch = False

    # Add modules to default sequence
    getattr(process, "patPF2PATSequence" + postfix).replace(
        getattr(process, "pfNoElectron" + postfix),
        getattr(process, "pfNoElectron" + postfix) * process.kt6PFJetsForPAT)

    getattr(process, "patPF2PATSequence" + postfix).replace(
        getattr(process, "pfNoPileUp" + postfix),
        getattr(process, "pfNoPileUp" + postfix) * process.ak5PFJetsPileUp)

    #----------------------------------------------
    # Let it run
    process.pat_step = cms.Path(
        process.goodOfflinePrimaryVertices *
        #process.patDefaultSequence  +
        getattr(process, "patPF2PATSequence" + postfix))

    # Add PatTrigger output to the created file
    from PhysicsTools.PatAlgos.patEventContent_cff import patTriggerEventContent
    # Add PF2PAT output to the created file
    from PhysicsTools.PatAlgos.patEventContent_cff import patEventContentNoCleaning
    patOutputCommands = cms.untracked.vstring(
        'drop *', 'keep recoPFCandidates_particleFlow_*_*',
        *patEventContentNoCleaning)

    # Adjust the event content
    patOutputCommands += [
        #'keep *_selectedPat*_*_*',
        'keep *_genParticles*_*_*',
        'keep *_offlinePrimaryVertices*_*_*',
        'keep *_goodOfflinePrimaryVertices*_*_*',
        #'keep *_pileUpN*PrimaryVertices_*_*',
        #'keep *_pfPileUpExclN*_*_*',
        'keep *_pfPileUpPFlow*_*_*',
        'keep *_pfNoPileUpPFlow*_*_*',
        'keep *_ak5PFJetsPileUp_*_*',
        'keep *_ak5PFJets_*_*',
        'keep recoTracks_generalTracks_*_*',
        'keep HcalNoiseSummary_hcalnoise_*_*',
        'keep *_BeamHaloSummary_*_*',
        #------- Trigger collections ------
        'keep edmTriggerResults_TriggerResults_*_*',
        'keep *_hltTriggerSummaryAOD_*_*',
        'keep L1GlobalTriggerObjectMapRecord_*_*_*',
        'keep L1GlobalTriggerReadoutRecord_*_*_*',
        #------- CASTOR rec hits ------
        'keep *_logErrorHarvester_*_*',
        'keep *_castorreco_*_*',
        #------- Calo towers (just for now) ------
        'keep *_towerMaker_*_*',
        #---------------PatTrigger----------------
        'keep patTriggerObjects_patTrigger*_*_*',
        'keep patTriggerFilters_patTrigger*_*_*',
        'keep patTriggerPaths_patTrigger*_*_*',
        'keep patTriggerEvent_patTriggerEvent*_*_*'
    ]
    process.out.outputCommands = patOutputCommands

    # top projections in PF2PAT:
    getattr(process, "pfNoPileUp" + postfix).enable = True
    getattr(process, "pfNoMuon" + postfix).enable = True
    getattr(process, "pfNoElectron" + postfix).enable = True
    getattr(process, "pfNoTau" + postfix).enable = False
    getattr(process, "pfNoJet" + postfix).enable = True

    # verbose flags for the PF2PAT modules
    getattr(process, "pfNoJet" + postfix).verbose = False
def createProcess(isMC, globalTag):

    import FWCore.ParameterSet.Config as cms

    #####
    # Init the process with some default options
    #####

    process = cms.Process("PAT")

    ## MessageLogger
    process.load("FWCore.MessageLogger.MessageLogger_cfi")

    ## Options and Output Report
    process.options = cms.untracked.PSet(
        wantSummary=cms.untracked.bool(True),
        allowUnscheduled=cms.untracked.bool(True))

    ## Source
    process.source = cms.Source("PoolSource",
                                fileNames=cms.untracked.vstring())

    ## Maximal Number of Events
    process.maxEvents = cms.untracked.PSet(input=cms.untracked.int32(100))

    ## Geometry and Detector Conditions (needed for a few patTuple production steps)
    process.load("Configuration.Geometry.GeometryIdeal_cff")
    process.load(
        "Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
    process.GlobalTag.globaltag = cms.string("%s::All" % globalTag)
    process.load("Configuration.StandardSequences.MagneticField_cff")

    ## Output Module Configuration (expects a path 'p')
    from PhysicsTools.PatAlgos.patEventContent_cff import patEventContentNoCleaning
    process.out = cms.OutputModule(
        "PoolOutputModule",
        fileName=cms.untracked.string('patTuple.root'),
        ## save only events passing the full path
        #SelectEvents = cms.untracked.PSet( SelectEvents = cms.vstring('p') ),
        ## save PAT output; you need a '*' to unpack the list of commands
        ## 'patEventContent'
        outputCommands=cms.untracked.vstring('drop *',
                                             *patEventContentNoCleaning))

    process.outpath = cms.EndPath(process.out)

    #####
    # Customize process for top pat Tuples production
    #####

    print("Loading python config...")

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

    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=cms.PSet(minNdof=cms.double(4.),
                              maxZ=cms.double(24.),
                              maxRho=cms.double(2.)),
        filter=cms.bool(True),
        src=cms.InputTag('offlinePrimaryVertices'))

    from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT, adaptPFIsoElectrons

    postfix = "PFlow"
    jetAlgo = "AK5"
    # Jet corrections when using CHS (L2L3Residual IS mandatory on data)

    if isMC:
        jetCorrections = ('AK5PFchs',
                          ['L1FastJet', 'L2Relative', 'L3Absolute'])
    else:
        jetCorrections = ('AK5PFchs', [
            'L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual'
        ])

    # Jet corrections when NOT using CHS
    #jetCorrections = ('AK5PF', ['L1FastJet','L2Relative','L3Absolute'] )

    # Type I MET enabled
    usePF2PAT(process,
              runPF2PAT=True,
              jetAlgo=jetAlgo,
              runOnMC=isMC,
              postfix=postfix,
              jetCorrections=jetCorrections,
              typeIMetCorrections=True,
              pvCollection=cms.InputTag('goodOfflinePrimaryVertices'))

    # We want:
    # - Uncorrected MEt: patMETsRawPFlow
    # - Type I corrected MEt: patMETsPFlow
    # - Type 0+I correct MEt: patMETsType0p1PFlow

    # Create PAT MEt from raw MEt collection (pfMET<postfix>))
    setattr(
        process, "patMETsRaw%s" % postfix,
        getattr(process, "patMETs%s" %
                postfix).clone(metSource=cms.InputTag("pfMET%s" % (postfix))))

    # Type 0, 1 or 2 corrected MEt is produced by the module CorrectedPFMETProducer

    # Clone the module <jetcorrectorlabel>Type1CorMet<postfix> (eg, AK5PFchschsTypeICorMetPFlow),
    # to create a Type 0 + I MEt

    setattr(
        process, "%sType0p1CorMet%s" % (jetCorrections[0], postfix),
        getattr(
            process, "%sType1CorMet%s" % (jetCorrections[0], postfix)).clone(
                applyType0Corrections=cms.bool(True),
                srcCHSSums=cms.VInputTag("pfchsMETcorr%s:type0" % postfix)))

    # Now, convert the PF met to patMET. Clone patMETs<postfix>

    setattr(
        process, "patMETsType0p1%s" % postfix,
        getattr(process, "patMETs%s" % postfix).clone(
            metSource=cms.InputTag("%sType0p1CorMet%s" %
                                   (jetCorrections[0], postfix))))

    #####
    # Add sys shift correction to our Met
    #####

    # Output:
    # - Type I + sys shift: patMETsSysShiftPFlow
    # - Type 0 + I + sys shift: patMETsType0p1pSysShiftPFlow

    #process.load("JetMETCorrections.Type1MET.pfMETCorrections_cff")
    process.load("JetMETCorrections.Type1MET.pfMETsysShiftCorrections_cfi")

    if not isMC:
        process.pfMEtSysShiftCorr.parameter = process.pfMEtSysShiftCorrParameters_2012runABCDvsNvtx_data
    else:
        process.pfMEtSysShiftCorr.parameter = process.pfMEtSysShiftCorrParameters_2012runABCDvsNvtx_mc

    # Clone the Type I MEt producer and add Sys Shift corrections
    setattr(
        process, "%sType1pSysShiftCorMet%s" % (jetCorrections[0], postfix),
        getattr(process,
                "%sType1CorMet%s" % (jetCorrections[0], postfix)).clone())
    getattr(process, "%sType1pSysShiftCorMet%s" %
            (jetCorrections[0], postfix)).srcType1Corrections.append(
                cms.InputTag('pfMEtSysShiftCorr'))

    # Clone the Type 0+I MEt producer and add Sys Shift corrections
    setattr(
        process, "%sType0p1pSysShiftCorMet%s" % (jetCorrections[0], postfix),
        getattr(process,
                "%sType0p1CorMet%s" % (jetCorrections[0], postfix)).clone())
    getattr(process, "%sType0p1pSysShiftCorMet%s" %
            (jetCorrections[0], postfix)).srcType1Corrections.append(
                cms.InputTag('pfMEtSysShiftCorr'))

    # Convert PF MEt to PAT MEt
    setattr(
        process, "patMETsSysShift%s" % postfix,
        getattr(process, "patMETs%s" % postfix).clone(
            metSource=cms.InputTag("%sType1pSysShiftCorMet%s" %
                                   (jetCorrections[0], postfix))))

    setattr(
        process, "patMETsType0p1pShiftCorr%s" % postfix,
        getattr(process, "patMETs%s" % postfix).clone(
            metSource=cms.InputTag("%sType0p1pSysShiftCorMet%s" %
                                   (jetCorrections[0], postfix))))

    getattr(process, "pfJets%s" % postfix).doAreaFastjet = True
    getattr(process, "pfJets%s" % postfix).doRhoFastjet = False

    # Should be fine in recent version of PAT, but in case of...
    #process.patJetCorrFactorsPFlow.rho = cms.InputTag("kt6PFJets", "rho")

    #####
    # Configure muon & electron isolation cuts
    #####

    # Electrons need a deltaR = 0.3 cone for isolation values.

    from PhysicsTools.PatAlgos.tools.helpers import loadWithPostfix

    loadWithPostfix(
        process, "CommonTools.ParticleFlow.Isolation.pfElectronIsolation_cff",
        postfix)

    # Fix input tags
    deposit = getattr(process, "elPFIsoDepositCharged%s" % postfix)
    deposit.src = cms.InputTag("pfSelectedElectrons%s" % postfix)
    deposit.ExtractorPSet.inputCandView = cms.InputTag(
        "pfAllChargedHadrons%s" % postfix)

    deposit = getattr(process, "elPFIsoDepositChargedAll%s" % postfix)
    deposit.src = cms.InputTag("pfSelectedElectrons%s" % postfix)
    deposit.ExtractorPSet.inputCandView = cms.InputTag(
        "pfAllChargedParticles%s" % postfix)

    deposit = getattr(process, "elPFIsoDepositGamma%s" % postfix)
    deposit.src = cms.InputTag("pfSelectedElectrons%s" % postfix)
    deposit.ExtractorPSet.inputCandView = cms.InputTag("pfAllPhotons%s" %
                                                       postfix)

    deposit = getattr(process, "elPFIsoDepositNeutral%s" % postfix)
    deposit.src = cms.InputTag("pfSelectedElectrons%s" % postfix)
    deposit.ExtractorPSet.inputCandView = cms.InputTag(
        "pfAllNeutralHadrons%s" % postfix)

    deposit = getattr(process, "elPFIsoDepositPU%s" % postfix)
    deposit.src = cms.InputTag("pfSelectedElectrons%s" % postfix)
    deposit.ExtractorPSet.inputCandView = cms.InputTag(
        "pfPileUpAllChargedParticles%s" % postfix)

    # Adapt cut for pfSelectedElectrons
    # Default cut: pt > 5 & gsfElectronRef.isAvailable() & gsfTrackRef.trackerExpectedHitsInner.numberOfLostHits<2

    setattr(
        process, "pfSelectedElectrons%s" % postfix,
        cms.EDFilter(
            "GenericPFCandidateSelector",
            src=cms.InputTag("pfElectronsFromVertex%s" % postfix),
            cut=cms.string(
                "pt > 10 && gsfTrackRef.isNonnull && gsfTrackRef.trackerExpectedHitsInner.numberOfLostHits<2"
            )))

    process.pfIsolatedElectronsClones = cms.EDFilter(
        "IsolatedPFCandidateSelector",
        src=cms.InputTag("pfSelectedElectrons%s" % postfix),
        isolationValueMapsCharged=cms.VInputTag(
            cms.InputTag("elPFIsoValueCharged03PFId%s" % postfix), ),
        isolationValueMapsNeutral=cms.VInputTag(
            cms.InputTag("elPFIsoValueNeutral03PFId%s" % postfix),
            cms.InputTag("elPFIsoValueGamma03PFId%s" % postfix)),
        doDeltaBetaCorrection=cms.bool(False),
        deltaBetaIsolationValueMap=cms.InputTag("elPFIsoValuePU03PFId%s" %
                                                postfix),
        deltaBetaFactor=cms.double(-0.5),
        ## if True isolation is relative to pT
        isRelative=cms.bool(True),
        isolationCut=cms.double(0.10),
        ## Added in attached patch
        doEffectiveAreaCorrection=cms.bool(True),
        effectiveAreas=cms.InputTag("elEffectiveAreas03%s" % postfix),
        rho=cms.InputTag("kt6PFJets", "rho"))

    pfIsolatedElectrons = cms.EDFilter(
        "PFCandidateFwdPtrCollectionStringFilter",
        src=cms.InputTag("pfIsolatedElectronsClones"),
        cut=cms.string(""),
        makeClones=cms.bool(True))

    # Override default electron collection by our new one
    setattr(process, "pfIsolatedElectrons%s" % postfix, pfIsolatedElectrons)

    # Set correct isolation deposits for patElectron production
    # FIXME: This should be enable if we want to recompute isolation from the pat electrons collections.
    # Unfortunately, it crashes sometimes when accessing deposits, because they are created from
    # pfSelectedElectrons<postfix> and patElectrons<postfix> red deposits using electrons coming from
    # pfIsolatedElectrons<postfix>.

    # adaptPFIsoElectrons(process, getattr(process, "patElectrons%s" % postfix), postfix, "03")

    # Produce electron conversions selection for Electron ID
    process.patConversions = cms.EDProducer(
        "PATConversionProducer",
        # input collection
        electronSource=cms.InputTag("selectedPatElectrons%s" % postfix)
        # this should be your last selected electron collection name since currently index is used to match with electron later. We can fix this using reference pointer.
    )

    # Produce electron conversions selection for Electron ID
    process.patConversionsLoose = cms.EDProducer(
        "PATConversionProducer",
        # input collection
        electronSource=cms.InputTag("selectedPatElectronsLoose%s" % postfix)
        # this should be your last selected electron collection name since currently index is used to match with electron later. We can fix this using reference pointer.
    )

    # Enable deltaBeta correction for muon isolation
    # Default cut from https://github.com/cms-sw/cmssw/blob/CMSSW_6_2_X/CommonTools/ParticleFlow/python/Isolation/pfIsolatedMuons_cfi.py
    # pt > 5 & muonRef.isAvailable() & muonRef.pfIsolationR04().sumChargedHadronPt + muonRef.pfIsolationR04().sumNeutralHadronEt +
    #   muonRef.pfIsolationR04().sumPhotonEt < 0.15 * pt
    # deltaBeta isolation is: [sumChargedHadronPt + max(0., sumNeutralHadronPt + sumPhotonPt - 0.5 * sumPUPt] / pt

    # pt > 10, global muon, deltaBeta isolation < 0.12
    cut = "pt > 10 & muonRef.isAvailable() & muonRef.isGlobalMuon() & ((muonRef.pfIsolationR04().sumChargedHadronPt + max(0.0, muonRef.pfIsolationR04().sumNeutralHadronEt + muonRef.pfIsolationR04().sumPhotonEt - 0.5 * muonRef.pfIsolationR04().sumPUPt)) < 0.12 * pt)"
    getattr(process, "pfIsolatedMuons%s" % postfix).cut = cut

    #process.load('EGamma.EGammaAnalysisTools.electronIdMVAProducer_cfi')
    #process.eidMVASequence = cms.Sequence(process.mvaTrigV0 + process.mvaNonTrigV0)
    ##Electron ID
    #process.patElectronsPFlow.electronIDSources.mvaTrigV0    = cms.InputTag("mvaTrigV0")
    #process.patElectronsPFlow.electronIDSources.mvaNonTrigV0 = cms.InputTag("mvaNonTrigV0")
    #process.patDefaultSequencePFlow.replace(process.patElectronsPFlow, process.eidMVASequence * process.patElectronsPFlow)

    # Compute effective areas for correcting isolation
    loadWithPostfix(
        process, "PatTopProduction.Tools.electronEffectiveAreaProducer_cfi",
        postfix)

    getattr(process, "elEffectiveAreas03%s" % postfix).src = cms.InputTag(
        "pfSelectedElectrons%s" % postfix)

    if isMC:
        getattr(process, "elEffectiveAreas03%s" %
                postfix).target = cms.string("EAFall11MC")

    #####
    # PAT object configuration
    #####

    # jets
    process.selectedPatJetsPFlow.cut = 'pt > 10. & abs(eta) < 3.'

    # muons
    process.patMuonsPFlow.usePV = False
    process.patMuonsPFlow.embedTrack = True

    # electrons
    process.patElectronsPFlow.usePV = False
    process.patElectronsPFlow.embedTrack = True

    #####
    # Loose collections with no isolation cut applied
    # Clone selectedPatMuons / selectedPatElectrons, and use in input pfMuons / pfElectrons
    #####

    setattr(
        process, "selectedPatMuonsLoose%s" % postfix,
        getattr(process, "patMuons%s" % postfix).clone(
            pfMuonSource=cms.InputTag("pfMuons%s" % postfix),
            embedGenMatch=False,
            addGenMatch=False))

    setattr(
        process, "selectedPatElectronsLoose%s" % postfix,
        getattr(process, "patElectrons%s" % postfix).clone(
            pfElectronSource=cms.InputTag("pfSelectedElectrons%s" % postfix),
            embedGenMatch=False,
            addGenMatch=False))

    adaptPFIsoElectrons(
        process, getattr(process, "selectedPatElectronsLoose%s" % postfix),
        postfix, "03")

    if not isMC:
        removeMCMatchingPF2PAT(process, '')

    #####
    # P2FPAT is done. Now setup some filters
    #####

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

    # require scraping filter
    if not isMC:
        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))

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

    # Remove uneeded filter
    del (process.tobtecfakesfilter)

    # Add PF2PAT output to the created file
    from PhysicsTools.PatAlgos.patEventContent_cff import patEventContentNoCleaning
    process.out.outputCommands = cms.untracked.vstring(
        'drop *',
        'keep GenEventInfoProduct_generator_*_*',
        'keep *_genParticles*_*_*',
        'keep edmTriggerResults_*_*_*',
        'keep *_*fflinePrimaryVertices_*_*',  # It's NOT a typo
        'keep recoPFCandidates_particleFlow_*_*',
        'keep PileupSummaryInfos_*_*_*',
        'keep double_kt6PFJets*_rho_*',
        'keep *_patConversions*_*_*',
        *patEventContentNoCleaning)

    process.out.outputCommands += [
        'drop *_selectedPatJetsForMET*_*_*',
        'drop *_selectedPatJets*_pfCandidates_*',
        'keep *_patMETsRaw*_*_PAT',  # Keep raw met
        'keep *_allConversions*_*_*',

        # For isolations and conversions vetoes
        'keep *_gsfElectron*_*_*',
        'keep *_offlineBeamSpot*_*_*'
    ]

    # RelVal in inputs
    #from PhysicsTools.PatAlgos.tools.cmsswVersionTools import pickRelValInputFiles
    #process.source.fileNames = pickRelValInputFiles(cmsswVersion = "CMSSW_5_3_6", globalTag = "PU_START53_V14", debug = True, numberOfFiles = 1)

    process.options.wantSummary = False

    process.MessageLogger.cerr.FwkReport.reportEvery = 1

    print("Config loaded")

    return process
예제 #27
0
process.load( "PhysicsTools.PatAlgos.patSequences_cff" )

# Misc
from PhysicsTools.PatAlgos.tools.coreTools import *
removeSpecificPATObjects( process
                        , names = [ 'Photons', 'Taus' ]
                        )

# PF2PAT
from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
usePF2PAT( process
         , runOnMC             = True
         , jetAlgo             = jetAlgo
         , jetCorrections      = ( '%sPFchs'%( jetAlgo )
                                 , jecLevels
                                 )
         , typeIMetCorrections = useTypeICorr
         , pvCollection        = cms.InputTag( pvCollection )
         )
# still need to fix event content afterwards :-(
process.out.outputCommands.append( 'keep *_addPileupInfo_*_*' )
process.out.outputCommands.append( 'keep edmTriggerResults_*_*_*' )
process.out.outputCommands.append( 'keep *_offlinePrimaryVertices_*_*' )
process.out.outputCommands.append( 'keep *_%s_*_*'%( pvCollection ) )

process.patPF2PATSequence.remove( process.ak7GenJetsNoNu )
process.patPF2PATSequence.remove( process.iterativeCone5GenJetsNoNu )

process.patPF2PATSequence.remove( process.patPFParticles )
process.patPF2PATSequence.remove( process.selectedPatPFParticles )
예제 #28
0
  jecLevels.append( 'L5Flavor' )
if useL7Parton:
  jecLevels.append( 'L7Parton' )

############################
### Switch configuration ###
############################
from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
usePF2PAT( process
         , runPF2PAT           = True
         , runOnMC             = runOnMC
         , jetAlgo             = jetAlgo
         , postfix             = postfix
         , jetCorrections      = ( jecSet
                                 , jecLevels
                                 )
         , typeIMetCorrections = typeIMetCorrections
         , pvCollection        = cms.InputTag( pfVertices )
         )

if useElectronCutBasePF:
  #process.load('EgammaAnalysis.ElectronTools.electronIdMVAProducer_cfi')
  from TopQuarkAnalysis.Configuration.patRefSel_pfIdentifiedElectrons_cfi import pfIdentifiedElectrons
  process.pfIdentifiedElectronsPF     = pfIdentifiedElectrons
  process.pfIdentifiedElectronsPF.src = cms.InputTag( 'pfElectronsFromVertexPF' )
  process.pfSelectedElectronsPF.src   = cms.InputTag( 'pfIdentifiedElectronsPF' )
  process.patPF2PATSequencePF.replace( process.pfSelectedElectronsPF, process.pfIdentifiedElectronsPF + process.pfSelectedElectronsPF )
  pfElectronSelectionCut += ' && %s'%( electronCutPF )

process.pfNoPileUpPF.enable   = usePFnoPU	# True
process.pfNoMuonPF.enable     = useNoMuon	# True
예제 #29
0
def initialise(runOnMC, decayMode, doOutModule=False, doPAT=True):
    process = cms.Process("KrAFT")

    process.load("Configuration.StandardSequences.Services_cff")
    process.load("Configuration.Geometry.GeometryDB_cff")
    process.load("Configuration.StandardSequences.MagneticField_cff")
    process.options = cms.untracked.PSet(wantSummary=cms.untracked.bool(True))
    process.maxEvents = cms.untracked.PSet(input=cms.untracked.int32(-1))

    process.load("FWCore.MessageLogger.MessageLogger_cfi")
    process.MessageLogger.cerr.FwkReport.reportEvery = 10000

    process.source = cms.Source("PoolSource",
                                fileNames=cms.untracked.vstring())
    process.source.inputCommands = cms.untracked.vstring(
        "keep *", "drop *_MEtoEDMConverter_*_*")

    process.load(
        "Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
    from Configuration.AlCa.autoCond import autoCond
    if runOnMC: process.GlobalTag.globaltag = autoCond['startup']
    else: process.GlobalTag.globaltag = autoCond['com10']

    outputModuleForTriggerMatch = ""
    outputModules = []
    if doOutModule:
        from PhysicsTools.PatAlgos.patEventContent_cff import patEventContentNoCleaning
        process.out = cms.OutputModule(
            "PoolOutputModule",
            fileName=cms.untracked.string("out.root"),
            outputCommands=cms.untracked.vstring(
                'drop *', 'keep recoPFCandidates_particleFlow_*_*',
                *patEventContentNoCleaning))
        process.outPath = cms.EndPath(process.out)

        outputModuleForTriggerMatch = "out"
        outputModules.append(process.out)

    ## Load PAT
    process.load("PhysicsTools.PatAlgos.patSequences_cff")

    ## Apply MVA
    process.load('EgammaAnalysis.ElectronTools.electronIdMVAProducer_cfi')
    process.eidMVASequence = cms.Sequence(process.mvaTrigV0 +
                                          process.mvaNonTrigV0)
    process.patElectrons.electronIDSources.mvaTrigV0 = cms.InputTag(
        "mvaTrigV0")
    process.patElectrons.electronIDSources.mvaNonTrigV0 = cms.InputTag(
        "mvaNonTrigV0")
    process.patDefaultSequence.replace(
        process.patElectrons, process.eidMVASequence * process.patElectrons)

    ## Load trigger matching
    process.load("KrAFT.Configuration.hltFilters_cff")
    #from PhysicsTools.PatAlgos.tools.trigTools import *
    #switchOnTriggerMatchEmbedding(process, outputModule="")

    ## Apply PF2PAT
    from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
    if runOnMC: jecLevels = ['L1FastJet', 'L2Relative', 'L3Absolute']
    else: jecLevels = ['L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual']

    postfix = "PFlow"
    #usePFBRECO(process,runPFBRECO=True,
    usePF2PAT(process,
              runPF2PAT=True,
              runOnMC=runOnMC,
              outputModules=outputModules,
              postfix=postfix,
              jetAlgo="AK5",
              jetCorrections=("AK5PFchs", jecLevels),
              pvCollection=cms.InputTag('goodOfflinePrimaryVertices'),
              typeIMetCorrections=True)

    #
    process.pfPileUpPFlow.checkClosestZVertex = cms.bool(False)

    # top projections in PF2PAT:
    process.pfNoPileUpPFlow.enable = True
    process.pfNoMuonPFlow.enable = True
    process.pfNoElectronPFlow.enable = True
    process.pfNoTauPFlow.enable = False
    process.pfNoJetPFlow.enable = False

    # verbose flags for the PF2PAT modules
    process.pfNoMuonPFlow.verbose = False

    # Use non-isolated muons and electrons
    process.patMuonsPFlow.pfMuonSource = "pfMuonsPFlow"
    process.patElectronsPFlow.pfElectronSource = "pfElectronsPFlow"

    # And turn on delta-beta corrections while building pfIsolated*PFlow
    process.pfIsolatedMuonsPFlow.doDeltaBetaCorrection = True
    process.pfIsolatedElectronsPFlow.doDeltaBetaCorrection = True

    # Change DR cone size to 0.3
    process.pfIsolatedMuonsPFlow.isolationValueMapsCharged = cms.VInputTag(
        cms.InputTag('muPFIsoValueCharged03PFlow'))
    process.pfIsolatedMuonsPFlow.deltaBetaIsolationValueMap = cms.InputTag(
        'muPFIsoValuePU03PFlow')
    process.pfIsolatedMuonsPFlow.isolationValueMapsNeutral = cms.VInputTag(
        cms.InputTag('muPFIsoValueNeutral03PFlow'),
        cms.InputTag('muPFIsoValueGamma03PFlow'),
    )
    process.pfMuonsPFlow.isolationValueMapsCharged = cms.VInputTag(
        cms.InputTag('muPFIsoValueCharged03PFlow'))
    process.pfMuonsPFlow.deltaBetaIsolationValueMap = cms.InputTag(
        'muPFIsoValuePU03PFlow')
    process.pfMuonsPFlow.isolationValueMapsNeutral = cms.VInputTag(
        cms.InputTag('muPFIsoValueNeutral03PFlow'),
        cms.InputTag('muPFIsoValueGamma03PFlow'),
    )
    process.patMuonsPFlow.isolationValues.pfNeutralHadrons = cms.InputTag(
        'muPFIsoValueNeutral03PFlow')
    process.patMuonsPFlow.isolationValues.pfChargedAll = cms.InputTag(
        'muPFIsoValueChargedAll03PFlow')
    process.patMuonsPFlow.isolationValues.pfPUChargedHadrons = cms.InputTag(
        'muPFIsoValuePU03PFlow')
    process.patMuonsPFlow.isolationValues.pfPhotons = cms.InputTag(
        'muPFIsoValueGamma03PFlow')
    process.patMuonsPFlow.isolationValues.pfChargedHadrons = cms.InputTag(
        'muPFIsoValueCharged03PFlow')

    process.pfIsolatedElectronsPFlow.isolationValueMapsCharged = cms.VInputTag(
        cms.InputTag('elPFIsoValueCharged03PFIdPFlow'))
    process.pfIsolatedElectronsPFlow.deltaBetaIsolationValueMap = cms.InputTag(
        'elPFIsoValuePU03PFIdPFlow')
    process.pfIsolatedElectronsPFlow.isolationValueMapsNeutral = cms.VInputTag(
        cms.InputTag('elPFIsoValueNeutral03PFIdPFlow'),
        cms.InputTag('elPFIsoValueGamma03PFIdPFlow'))
    process.pfElectronsPFlow.isolationValueMapsCharged = cms.VInputTag(
        cms.InputTag('elPFIsoValueCharged03PFIdPFlow'))
    process.pfElectronsPFlow.deltaBetaIsolationValueMap = cms.InputTag(
        'elPFIsoValuePU03PFIdPFlow')
    process.pfElectronsPFlow.isolationValueMapsNeutral = cms.VInputTag(
        cms.InputTag('elPFIsoValueNeutral03PFIdPFlow'),
        cms.InputTag('elPFIsoValueGamma03PFIdPFlow'))
    process.patElectronsPFlow.isolationValues.pfNeutralHadrons = cms.InputTag(
        'elPFIsoValueNeutral03PFIdPFlow')
    process.patElectronsPFlow.isolationValues.pfChargedAll = cms.InputTag(
        'elPFIsoValueChargedAll03PFIdPFlow')
    process.patElectronsPFlow.isolationValues.pfPUChargedHadrons = cms.InputTag(
        'elPFIsoValuePU03PFIdPFlow')
    process.patElectronsPFlow.isolationValues.pfPhotons = cms.InputTag(
        'elPFIsoValueGamma03PFIdPFlow')
    process.patElectronsPFlow.isolationValues.pfChargedHadrons = cms.InputTag(
        'elPFIsoValueCharged03PFIdPFlow')

    ## Add common filters
    process.primaryVertexFilter = cms.EDFilter(
        "GoodVertexFilter",
        vertexCollection=cms.InputTag('offlinePrimaryVertices'),
        minimumNDOF=cms.uint32(4),
        maxAbsZ=cms.double(24),
        maxd0=cms.double(2))

    from PhysicsTools.SelectorUtils.pvSelector_cfi import pvSelector
    process.goodOfflinePrimaryVertices = cms.EDFilter(
        "PrimaryVertexObjectFilter",
        filterParams=pvSelector.clone(maxZ=cms.double(24.0)),
        src=cms.InputTag('offlinePrimaryVertices'))

    #process.load( "TopQuarkAnalysis.Configuration.patRefSel_goodVertex_cfi" )
    #process.goodOfflinePrimaryVertices.filter = True

    process.load('TopQuarkAnalysis.Configuration.patRefSel_eventCleaning_cff')
    process.trackingFailureFilter.VertexSource = cms.InputTag(
        'goodOfflinePrimaryVertices')
    if runOnMC: process.eventCleaning += process.eventCleaningMC
    else: process.eventCleaning += process.eventCleaningData

    #reason : removing many events.
    process.eventCleaning.remove(process.CSCTightHaloFilter)

    ## Lepton veto filters for L+J channels
    process.muonVetoFilter = cms.EDFilter(
        "PATCandViewCountFilter",
        src=cms.InputTag("selectedPatMuonsPFlow"),
        maxNumber=cms.uint32(0),
        minNumber=cms.uint32(0),
    )
    process.electronVetoFilter = cms.EDFilter(
        "PATCandViewCountFilter",
        src=cms.InputTag("selectedPatElectronsPFlow"),
        maxNumber=cms.uint32(0),
        minNumber=cms.uint32(0),
    )

    # event counters
    process.nEventsTotal = cms.EDProducer("EventCountProducer")
    process.nEventsClean = cms.EDProducer("EventCountProducer")
    process.nEventsPAT = cms.EDProducer("EventCountProducer")
    process.nEventsHLTElEl = cms.EDProducer("EventCountProducer")
    process.nEventsHLTMuMu = cms.EDProducer("EventCountProducer")
    process.nEventsHLTMuEl = cms.EDProducer("EventCountProducer")
    process.nEventsHLTMuJets = cms.EDProducer("EventCountProducer")
    process.nEventsHLTElJets = cms.EDProducer("EventCountProducer")

    ###############################
    ### Add AK5GenJetsNoNu ####
    ###############################
    #process.load("RecoJets.Configuration.GenJetParticles_cff")
    from RecoJets.Configuration.GenJetParticles_cff import genParticlesForJetsNoNu
    from RecoJets.JetProducers.ak5GenJets_cfi import ak5GenJets
    process.ak5GenJetsNoNu = ak5GenJets.clone(
        src=cms.InputTag("genParticlesForJetsNoNu"))

    process.ak5GenJetsSeq = cms.Sequence(process.genParticlesForJets *
                                         process.genParticlesForJetsNoNu *
                                         process.ak5GenJetsNoNu)

    # Flavor history stuff
    process.load("PhysicsTools.HepMCCandAlgos.flavorHistoryPaths_cfi")
    process.flavorHistoryFilter.pathToSelect = cms.int32(-1)
    process.cFlavorHistoryProducer.matchedSrc = cms.InputTag("ak5GenJetsNoNu")
    process.bFlavorHistoryProducer.matchedSrc = cms.InputTag("ak5GenJetsNoNu")
    #ptMinParticle = cms.double(0.0)
    #ptMinShower = cms.double(0.0)

    #process.load( "RecoJets.Configuration.GenJetParticles_cff")
    #process.load( "RecoJets.Configuration.RecoGenJets_cff")

    #process.ReGenJetSequence = cms.Sequence(
    #    process.genParticlesForJets
    #  + process.genParticlesForJetsNoNu
    #  + process.ak5GenJets
    #  + process.ak5GenJetsNoNu
    #)

    process.commonFilterSequence = cms.Sequence(
        process.goodOfflinePrimaryVertices * process.eventCleaning *
        process.ak5GenJetsSeq * process.primaryVertexFilter *
        process.nEventsClean *
        getattr(process, "patPF2PATSequence" + postfix)  # main PF2PAT 
        * process.nEventsPAT * process.flavorHistorySeq)

    #    process.patSequenceComplete = cms.Sequence(
    #  + process.patDefaultSequence
    #  + process.patPFBRECOSequencePFlow
    #        process.patPF2PATSequencePFlow
    #      + process.nEventsPAT
    #    )

    process.load("KrAFT.GeneratorTools.ttbar2bFilter_cfi")

    ## Defile paths
    if decayMode in ("all", "dilepton", "ElEl", "ee"):
        process.pElEl = cms.Path(
            process.nEventsTotal * process.commonFilterSequence *
            process.ttbar2bFilter * process.hltElEl * process.nEventsHLTElEl)
#        if doPAT: process.pElEl += process.patSequenceComplete
    if decayMode in ("all", "dilepton", "MuMu", "mumu"):
        process.pMuMu = cms.Path(process.nEventsTotal *
                                 process.commonFilterSequence *
                                 process.hltMuMu * process.nEventsHLTMuMu)
#        if doPAT: process.pMuMu += process.patSequenceComplete
    if decayMode in ("all", "dilepton", "MuEl", "emu"):
        process.pMuEl = cms.Path(process.nEventsTotal *
                                 process.commonFilterSequence *
                                 process.hltMuEl * process.nEventsHLTMuEl)


#        if doPAT: process.pMuEl += process.patSequenceComplete
    if decayMode in ("all", "MuJets"):
        process.selectedPatMuonsPFlow.cut = 'isPFMuon && (isGlobalMuon || isTrackerMuon) && pt > 10 && abs(eta) < 2.5 && (chargedHadronIso + max(0.,neutralHadronIso+photonIso-0.5*puChargedHadronIso))/pt < 0.15'
        process.selectedPatElectronsPFlow.cut = 'pt > 20 && abs(eta) < 2.5 && electronID("mvaTrigV0") > 0. && (chargedHadronIso + max(0.,neutralHadronIso+photonIso-0.5*puChargedHadronIso))/pt < 0.15'
        process.muonVetoFilter.maxNumber = 1

        process.pMuJets = cms.Path(
            process.nEventsTotal * process.commonFilterSequence *
            process.hltMuJets * process.nEventsHLTMuJets)
        #        if doPAT: process.pMuJets += process.patSequenceComplete
        process.pMuJets *= process.muonVetoFilter
        process.pMuJets += process.electronVetoFilter

        if runOnMC: process.pMuJets.remove(process.hltMuJets)
    if decayMode in ("all", "ElJets"):
        process.selectedPatMuonsPFlow.cut = 'isPFMuon && (isGlobalMuon || isTrackerMuon) && pt > 10 && abs(eta) < 2.5 && (chargedHadronIso + max(0.,neutralHadronIso+photonIso-0.5*puChargedHadronIso))/pt < 0.15'
        process.selectedPatElectronsPFlow.cut = 'pt > 20 && abs(eta) < 2.5 && electronID("mvaTrigV0") > 0. && (chargedHadronIso + max(0.,neutralHadronIso+photonIso-0.5*puChargedHadronIso))/pt < 0.15'
        process.electronVetoFilter.maxNumber = 1

        process.pElJets = cms.Path(
            process.nEventsTotal * process.commonFilterSequence *
            process.hltElJets * process.nEventsHLTElJets)
        #        if doPAT: process.pElJets += process.patSequenceComplete
        process.pElJets *= process.muonVetoFilter
        process.pElJets += process.electronVetoFilter

        if runOnMC: process.pElJets.remove(process.hltElJets)

    return process
def loadPF2PAT(process,mcInfo,jetMetCorrections,extMatch,doSusyTopProjection,postfix):
    #-- PAT standard config -------------------------------------------------------
    process.load("PhysicsTools.PatAlgos.patSequences_cff")
    #-- Jet corrections -----------------------------------------------------------
    process.patJetCorrFactors.levels = jetMetCorrections 
    #-- PF2PAT config -------------------------------------------------------------
    from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
    #usePF2PAT(process,runPF2PAT=True, jetAlgo='AK5',runOnMC=(mcInfo==1),postfix=postfix, jetCorrections=('AK5PFchs', jetMetCorrections), pvCollection=cms.InputTag('goodOfflinePrimaryVertices'))
    usePF2PAT(process,runPF2PAT=True, jetAlgo='AK5',runOnMC=(mcInfo==1),postfix=postfix, jetCorrections=('AK5PFchs', jetMetCorrections))
    # Get a list of good primary vertices, in 42x, these are DAF vertices
    from PhysicsTools.SelectorUtils.pvSelector_cfi import pvSelector
    process.goodOfflinePrimaryVertices = cms.EDFilter(
    	"PrimaryVertexObjectFilter",
    	filterParams = pvSelector.clone( minNdof = cms.double(4.0), maxZ = cms.double(24.0) ),
    	src=cms.InputTag('offlinePrimaryVertices')
    	)

    #process.patJetsPF.embedGenJetMatch = False
    #process.patJetsPF.embedPFCandidates = False
    #drop tracks 
    process.patElectronsPF.embedTrack = True
    process.patMuonsPF.embedTrack   = True
    process.electronMatchPF.maxDeltaR   = cms.double(0.2)
    process.electronMatchPF.maxDPtRel   = cms.double(999999.)
    process.electronMatchPF.checkCharge = False
    process.muonMatchPF.maxDeltaR   = cms.double(0.2)
    process.muonMatchPF.maxDPtRel   = cms.double(999999.)
    process.muonMatchPF.checkCharge = False
    process.pfPileUpPF.checkClosestZVertex = False
    process.pfPileUpPF.Vertices = "goodOfflinePrimaryVertices"
    if extMatch:
        process.electronMatchPF.mcStatus = cms.vint32(1,5)
        process.electronMatchPF.matched = "mergedTruth"
        process.muonMatchPF.mcStatus = cms.vint32(1,5)
        process.muonMatchPF.matched = "mergedTruth"
        process.genParticlesForJets.src = "mergedTruth"
        process.genParticlesForJetsNoMuNoNu.src = "mergedTruth"
        process.genParticlesForJetsNoNu.src = "mergedTruth"
        process.patJetPartonMatchPF.matched = "mergedTruth"
        process.patJetPartonsPF.src = "mergedTruth"
        process.photonMatchPF.matched = "mergedTruth"
        #process.tauGenJetsPF.GenParticles = "mergedTruth"
        #process.tauMatchPF.matched = "mergedTruth"
        
    #Remove jet pt cut
    #process.pfJetsPF.ptMin = 0.
    #include tau decay mode in pat::Taus (elese it will just be uninitialized)
    #process.patTausPF.addDecayMode = True
    #process.patTausPF.decayModeSrc = "shrinkingConePFTauDecayModeProducerPF" 

    #Set isolation cone to 0.3 for PF leptons
    # TODO: fix this for electrons and muons
    #process.pfElectrons.isolationValueMapsCharged = cms.VInputTag(cms.InputTag("elPFIsoValueCharged03PFId"))
    #process.pfElectrons.deltaBetaIsolationValueMap = cms.InputTag("elPFIsoValuePU03PFId")
    #process.pfElectrons.isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("elPFIsoValueNeutral03PFId"), cms.InputTag("elPFIsoValueGamma03PFId"))
    #process.pfIsolatedElectrons.isolationValueMapsCharged = cms.VInputTag(cms.InputTag("elPFIsoValueCharged03PFId"))
    #process.pfIsolatedElectrons.deltaBetaIsolationValueMap = cms.InputTag("elPFIsoValuePU03PFId")
    #process.pfIsolatedElectrons.isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("elPFIsoValueNeutral03PFId"), cms.InputTag("elPFIsoValueGamma03PFId"))
    
    #process.pfElectronsPF.isolationValueMapsCharged = cms.VInputTag(cms.InputTag("elPFIsoValueCharged03PFIdPF"))
    #process.pfElectronsPF.deltaBetaIsolationValueMap = cms.InputTag("elPFIsoValuePU03PFIdPF")
    #process.pfElectronsPF.isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("elPFIsoValueNeutral03PFIdPF"), cms.InputTag("elPFIsoValueGamma03PFIdPF"))
    #process.pfIsolatedElectronsPF.isolationValueMapsCharged = cms.VInputTag(cms.InputTag("elPFIsoValueCharged03PFIdPF"))
    #process.pfIsolatedElectronsPF.deltaBetaIsolationValueMap = cms.InputTag("elPFIsoValuePU03PFIdPF")
    #process.pfIsolatedElectronsPF.isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("elPFIsoValueNeutral03PFIdPF"), cms.InputTag("elPFIsoValueGamma03PFIdPF"))

    #process.pfMuons.isolationValueMapsCharged = cms.VInputTag(cms.InputTag("muPFIsoValueCharged03mu03"))
    #process.pfMuons.deltaBetaIsolationValueMap = cms.InputTag("muPFIsoValuePU03")
    #process.pfMuons.isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("muPFIsoValueNeutral03"), cms.InputTag("muPFIsoValueGamma03"))
    #process.pfIsolatedMuons.isolationValueMapsCharged = cms.VInputTag(cms.InputTag("muPFIsoValueCharged03mu03"))
    #process.pfIsolatedMuons.deltaBetaIsolationValueMap = cms.InputTag("muPFIsoValuePU03")
    #process.pfIsolatedMuons.isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("muPFIsoValueNeutral03"), cms.InputTag("muPFIsoValueGamma03"))

    #process.pfMuonsPF.isolationValueMapsCharged = cms.VInputTag(cms.InputTag("muPFIsoValueCharged03mu03PF"))
    #process.pfMuonsPF.deltaBetaIsolationValueMap = cms.InputTag("muPFIsoValuePU03PF")
    #process.pfMuonsPF.isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("muPFIsoValueNeutral03PF"), cms.InputTag("muPFIsoValueGamma03PF"))
    #process.pfIsolatedMuonsPF.isolationValueMapsCharged = cms.VInputTag(cms.InputTag("muPFIsoValueCharged03mu03PF"))
    #process.pfIsolatedMuonsPF.deltaBetaIsolationValueMap = cms.InputTag("muPFIsoValuePU03PF")
    #process.pfIsolatedMuonsPF.isolationValueMapsNeutral = cms.VInputTag(cms.InputTag("muPFIsoValueNeutral03PF"), cms.InputTag("muPFIsoValueGamma03PF"))

    #-- Enable pileup sequence -------------------------------------------------------------
    #Vertices
    process.goodVertices = cms.EDFilter("VertexSelector",
        src = cms.InputTag("offlinePrimaryVertices"),
        cut = cms.string("!isFake && ndof > 4 && abs(z) <= 24 && position.Rho <= 2"),
        filter = cms.bool(False),
    )

    #process.pfPileUpPF.Vertices = "goodVertices"
    #process.pfPileUpPF.Enable = True

    process.pfNoPileUpSequencePF.replace(process.pfPileUpPF,
                                         process.goodVertices + process.pfPileUpPF)

    if not doSusyTopProjection:
        return
    #-- Top projection selection -----------------------------------------------------------
    #Electrons
    #relax all selectors *before* pat-lepton creation
    process.pfElectronsFromVertexPF.dzCut = 9999.0
    process.pfElectronsFromVertexPF.d0Cut = 9999.0
    process.pfSelectedElectronsPF.cut = ""
    process.pfRelaxedElectronsPF = process.pfIsolatedElectronsPF.clone(isolationCut = 3.)
    process.pfIsolatedElectronsPF.isolationCut = 0.15
    
    process.pfElectronsFromGoodVertex = cms.EDFilter(
        "IPCutPFCandidateSelector",
        src = cms.InputTag("pfIsolatedElectronsPF"),  # PFCandidate source
        vertices = cms.InputTag("goodVertices"),  # vertices source
        d0Cut = cms.double(0.04),  # transverse IP
        dzCut = cms.double(1.),  # longitudinal IP
        d0SigCut = cms.double(99.),  # transverse IP significance
        dzSigCut = cms.double(99.),  # longitudinal IP significance
    )
   
    electronSelection =  "abs( eta ) < 2.5 & pt > 5"
    electronSelection += " & mva_e_pi > 0.4" # same as patElectron::mva()
    #electronSelection += " & (isEB & (sigmaIetaIeta < 0.024 & hadronicOverEm < 0.15) | isEE & (sigmaIetaIeta < 0.040 & hadronicOverEm < 0.10))" #caloIdVL
    #electronSelection += " & (isEB & (deltaPhiSuperClusterTrackAtVtx < 0.15 & deltaEtaSuperClusterTrackAtVtx < 0.01) | isEE & (deltaPhiSuperClusterTrackAtVtx < 0.10 & deltaEtaSuperClusterTrackAtVtx < 0.01))" #trkIdVL
    electronSelection += " & gsfTrackRef().isNonnull() & gsfTrackRef().trackerExpectedHitsInner().numberOfHits() <= 0"
    process.pfUnclusteredElectronsPF = cms.EDFilter( "GenericPFCandidateSelector",
        src = cms.InputTag("pfElectronsFromGoodVertex"), #pfSelectedElectronsPF
        cut = cms.string(electronSelection)
    )    
    process.pfElectronSequencePF.replace(process.pfIsolatedElectronsPF,
                                         process.pfIsolatedElectronsPF + 
                                         process.goodVertices * process.pfElectronsFromGoodVertex + 
                                         process.pfUnclusteredElectronsPF + process.pfRelaxedElectronsPF)
    process.patElectronsPF.pfElectronSource = "pfRelaxedElectronsPF"
    process.pfNoElectronPF.topCollection  = "pfUnclusteredElectronsPF"
    #Muons
    #relaxe built-in preselection
    process.pfMuonsFromVertexPF.dzCut = 9999.0
    process.pfMuonsFromVertexPF.d0Cut = 9999.0
    process.pfSelectedMuonsPF.cut = ""
    process.pfRelaxedMuonsPF = process.pfIsolatedMuonsPF.clone(isolationCut = 3)
    process.pfIsolatedMuonsPF.isolationCut = 0.15
    
    process.pfMuonsFromGoodVertex = cms.EDFilter(
        "IPCutPFCandidateSelector",
        src = cms.InputTag("pfIsolatedMuonsPF"),  # PFCandidate source
        vertices = cms.InputTag("goodVertices"),  # vertices source
        d0Cut = cms.double(0.02),  # transverse IP
        dzCut = cms.double(1.),  # longitudinal IP
        d0SigCut = cms.double(99.),  # transverse IP significance
        dzSigCut = cms.double(99.),  # longitudinal IP significance
    )
    muonSelection =  "abs( eta ) < 2.5 & pt > 5"
    #GlobalMuonPromptTight
    muonSelection += " & muonRef().isNonnull & muonRef().isGlobalMuon()"
    muonSelection += " & muonRef().isTrackerMuon() & muonRef().numberOfMatches > 1"
    muonSelection += " & muonRef().globalTrack().normalizedChi2() < 10"
    muonSelection += " & muonRef().track().numberOfValidHits() > 10"
    muonSelection += " & muonRef().globalTrack().hitPattern().numberOfValidMuonHits() > 0"
    muonSelection += " & muonRef().innerTrack().hitPattern().numberOfValidPixelHits() > 0"
    process.pfUnclusteredMuonsPF = cms.EDFilter( "GenericPFCandidateSelector",
        src = cms.InputTag("pfMuonsFromGoodVertex"), #pfSelectedMuonsPF
        cut = cms.string(muonSelection)
    )    
    process.pfMuonSequencePF.replace(process.pfIsolatedMuonsPF,
                                     process.pfIsolatedMuonsPF + 
                                     process.goodVertices * process.pfMuonsFromGoodVertex +
                                     process.pfUnclusteredMuonsPF + process.pfRelaxedMuonsPF)
    process.patMuonsPF.pfMuonSource  = "pfRelaxedMuonsPF"
    process.pfNoMuonPF.topCollection = "pfUnclusteredMuonsPF"
예제 #31
0
    ## Output module for edm files (needed for PAT sequence, even if not used in EndPath)
    from Configuration.EventContent.EventContent_cff import FEVTEventContent
    process.out = cms.OutputModule(
        "PoolOutputModule",
        FEVTEventContent,
        dataset=cms.untracked.PSet(dataTier=cms.untracked.string('RECO')),
        fileName=cms.untracked.string("eh.root"),
    )
    # add particle flow
    process.load("PhysicsTools.PatAlgos.patSequences_cff")
    from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
    usePF2PAT(process,
              runPF2PAT=True,
              jetAlgo='AK4',
              runOnMC=runOnMC,
              postfix=pfpostfix,
              jetCorrections=jetCorr,
              pvCollection=cms.InputTag(
                  opt.primaryVertexOptions['outputCollection']),
              typeIMetCorrections=True)

    getattr(process, 'pfPileUp' + pfpostfix).checkClosestZVertex = False

    # switch off all top projections
    getattr(process, 'pfNoMuon' + pfpostfix).enable = False
    getattr(process, 'pfNoElectron' + pfpostfix).enable = False
    getattr(process, 'pfNoJet' + pfpostfix).enable = False
    getattr(process, 'pfNoTau' + pfpostfix).enable = False
    # agrohsje don't require isolation on cmsRun level !!!
    # seems not to work -> check with python -i ?
    getattr(process, 'pfIsolatedElectrons' +
def addPATSequences(process,runMC):
    # Load the PAT config
    from PhysicsTools.PatAlgos.patEventContent_cff import patEventContent
    process.out = cms.OutputModule("PoolOutputModule",
	    fileName = cms.untracked.string('patTuple.root'),
	    SelectEvents   = cms.untracked.PSet( SelectEvents = cms.vstring('pat_step') ),
	    outputCommands = cms.untracked.vstring('drop *', *patEventContent )
            )
    ###
    process.load('PhysicsTools.PatAlgos.patSequences_cff')

    from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
    postfix = "PFlow"
    jetAlgo="AK5"
    jetCorrections = None
    if runMC:
	jetCorrections = ('AK5PFchs', ['L1FastJet','L2Relative','L3Absolute'])
    else:
	jetCorrections = ('AK5PFchs', ['L1FastJet','L2Relative','L3Absolute','L2L3Residual'])

    usePF2PAT(process,runPF2PAT=True,
                      jetAlgo=jetAlgo, runOnMC=runMC, postfix=postfix,jetCorrections=jetCorrections)

    #from PhysicsTools.PatAlgos.tools.coreTools import removeMCMatching
    #if not runMC:
    #    removeMCMatching(process, ['All'],"")

 
    #-----------------Customization----------------
    process.pfPileUpPFlow.Enable = True
    process.pfPileUpPFlow.checkClosestZVertex = False
    process.pfPileUpPFlow.Vertices = cms.InputTag('goodOfflinePrimaryVertices')
    process.pfPileUpPFlow.verbose = True
    process.pfJetsPFlow.doAreaFastjet = True
    process.pfJetsPFlow.doRhoFastjet = False

    from PhysicsTools.SelectorUtils.pvSelector_cfi import pvSelector
    process.goodOfflinePrimaryVertices = cms.EDFilter(
	"PrimaryVertexObjectFilter",
	filterParams = pvSelector.clone( minNdof = cms.double(4.0), maxZ = cms.double(24.0) ),
	src=cms.InputTag('offlinePrimaryVertices')
	)
    
    # Compute the mean pt per unit area (rho) from the PFCHS inputs
    #from RecoJets.Configuration.RecoPFJets_cff import kt6PFJets,ak5PFJets
    #process.kt6PFJetsPFlow = kt6PFJets.clone(
    #	src = cms.InputTag('pfNoElectron'+postfix),
    #	doAreaFastjet = cms.bool(True),
    #	doRhoFastjet = cms.bool(True)
    #	)
    #process.patJetCorrFactorsPFlow.rho = cms.InputTag("kt6PFJetsPFlow", "rho")
    from RecoJets.JetProducers.kt4PFJets_cfi import kt4PFJets
    process.kt6PFJetsForPAT = kt4PFJets.clone(
	    rParam = cms.double(0.6),
	    doAreaFastjet = cms.bool(True),
	    doRhoFastjet = cms.bool(True)
	    )
    process.patJetCorrFactorsPFlow.rho = cms.InputTag("kt6PFJetsForPAT", "rho")

    from RecoJets.JetProducers.ak5PFJets_cfi import ak5PFJets
    process.ak5PFJetsPileUp = ak5PFJets.clone( src = cms.InputTag('pfPileUp'+postfix) )

    # Switch on PAT trigger
    from PhysicsTools.PatAlgos.tools.trigTools import switchOnTrigger
    #switchOnTrigger( process,triggerProducer = 'patTrigger', triggerEventProducer = 'patTriggerEvent', sequence = 'patPF2PATSequence',hltProcess = 'HLT', outputModule = 'out')
    
    switchOnTrigger( process ,sequence ='patPF2PATSequence'+postfix)
    process.patTrigger.addL1Algos = cms.bool( True )
    switchOnTrigger( process ,sequence = 'patPF2PATSequence'+postfix) # to fix event content
    #-------------------------------------------------------------------------------------------------------------
    
    # Add modules to default sequence
    #if runMC:
    #    getattr(process, "patElectrons"+postfix).embedGenMatch = True
    #    getattr(process, "patMuons"+postfix).embedGenMatch = True
    #else:
    #    getattr(process, "patElectrons"+postfix).embedGenMatch = False
    #    getattr(process, "patMuons"+postfix).embedGenMatch = False

    # Add modules to default sequence
    getattr(process,"patPF2PATSequence"+postfix).replace(
	getattr(process,"pfNoElectron"+postfix),
	getattr(process,"pfNoElectron"+postfix)*process.kt6PFJetsForPAT
	)

    getattr(process,"patPF2PATSequence"+postfix).replace(
	getattr(process,"pfNoPileUp"+postfix),
	getattr(process,"pfNoPileUp"+postfix) * process.ak5PFJetsPileUp
	)

    #----------------------------------------------
    # Let it run
    process.pat_step = cms.Path(
	process.goodOfflinePrimaryVertices * 
	#process.patDefaultSequence  +
	getattr(process,"patPF2PATSequence"+postfix)
    )

    # Add PatTrigger output to the created file
    from PhysicsTools.PatAlgos.patEventContent_cff import patTriggerEventContent
    # Add PF2PAT output to the created file
    from PhysicsTools.PatAlgos.patEventContent_cff import patEventContentNoCleaning
    patOutputCommands = cms.untracked.vstring('drop *',
	    'keep recoPFCandidates_particleFlow_*_*',
	    *patEventContentNoCleaning) 

    # Adjust the event content
    patOutputCommands += [
	#'keep *_selectedPat*_*_*',
	'keep *_genParticles*_*_*',
	'keep *_offlinePrimaryVertices*_*_*',
	'keep *_goodOfflinePrimaryVertices*_*_*',
	#'keep *_pileUpN*PrimaryVertices_*_*',
	#'keep *_pfPileUpExclN*_*_*',
	'keep *_pfPileUpPFlow*_*_*',
	'keep *_pfNoPileUpPFlow*_*_*',
	'keep *_ak5PFJetsPileUp_*_*',
	'keep *_ak5PFJets_*_*',
	'keep recoTracks_generalTracks_*_*',
	'keep HcalNoiseSummary_hcalnoise_*_*',
	'keep *_BeamHaloSummary_*_*', 
     #------- Trigger collections ------
	'keep edmTriggerResults_TriggerResults_*_*',
	'keep *_hltTriggerSummaryAOD_*_*',
	'keep L1GlobalTriggerObjectMapRecord_*_*_*',
	'keep L1GlobalTriggerReadoutRecord_*_*_*',
     #------- CASTOR rec hits ------
	'keep *_logErrorHarvester_*_*', 
	'keep *_castorreco_*_*',
     #------- Calo towers (just for now) ------ 
	'keep *_towerMaker_*_*',
     #---------------PatTrigger----------------
	'keep patTriggerObjects_patTrigger*_*_*',
	'keep patTriggerFilters_patTrigger*_*_*',
	'keep patTriggerPaths_patTrigger*_*_*',
	'keep patTriggerEvent_patTriggerEvent*_*_*'
    ]
    process.out.outputCommands = patOutputCommands

    # top projections in PF2PAT:
    getattr(process,"pfNoPileUp"+postfix).enable = True 
    getattr(process,"pfNoMuon"+postfix).enable = True 
    getattr(process,"pfNoElectron"+postfix).enable = True 
    getattr(process,"pfNoTau"+postfix).enable = False 
    getattr(process,"pfNoJet"+postfix).enable = True

    # verbose flags for the PF2PAT modules
    getattr(process,"pfNoJet"+postfix).verbose = False
예제 #33
0
## Create and define reco objects 
if runOnAOD:
    muonTag = 'patMuons' + pfpostfix  
    metTag = 'patMETs' + pfpostfix  
    
    ## Output module for edm files (needed for PAT sequence, even if not used in EndPath) 
    from Configuration.EventContent.EventContent_cff import FEVTEventContent
    process.out = cms.OutputModule("PoolOutputModule",
                                   FEVTEventContent,
                                   dataset = cms.untracked.PSet(dataTier = cms.untracked.string('RECO')),
                                   fileName = cms.untracked.string("eh.root"),
                                   )
    # add particle flow
    process.load("PhysicsTools.PatAlgos.patSequences_cff")
    from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
    usePF2PAT(process, runPF2PAT=True, jetAlgo='AK4', runOnMC=runOnMC, postfix=pfpostfix, 
              jetCorrections=jetCorr, pvCollection=cms.InputTag('offlinePrimaryVertices'),typeIMetCorrections=True) 

    getattr(process, 'pfPileUp'+pfpostfix).checkClosestZVertex = False
    
    # switch off all top projections
    getattr(process,'pfNoMuon'+pfpostfix).enable = False
    getattr(process,'pfNoElectron'+pfpostfix).enable = False
    getattr(process,'pfNoJet'+pfpostfix).enable = False
    getattr(process,'pfNoTau'+pfpostfix).enable = False
    # agrohsje don't require isolation on cmsRun level !!!
    # tarndt especially don't require it in the default pf2pat process
    #        PFBRECO is subset of pf2pat processes 
    getattr(process,'pfIsolatedElectronsPFBRECO'+pfpostfix).cut=''
    getattr(process,'pfElectronsFromVertexPFBRECO'+pfpostfix).d0Cut = cms.double(999999.)
    getattr(process,'pfElectronsFromVertexPFBRECO'+pfpostfix).dzCut = cms.double(999999.) 
    getattr(process,'pfIsolatedMuonsPFBRECO'+pfpostfix).cut = ''
예제 #34
0
process.patDefaultSequence.replace( process.patElectrons, process.eidMVASequence * process.patElectrons )

## Load trigger matching
## Trigger matching with PAT
process.load("MuonAnalysis.MuonAssociators.patMuonsWithTrigger_cff")
process.muonMatchHLTL2.maxDeltaR = 0.3 # Zoltan tuning - it was 0.5
process.muonMatchHLTL3.maxDeltaR = 0.1

## Apply PF2PAT
from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
if runOnMC: jecLevels = ['L1FastJet','L2Relative','L3Absolute']
else: jecLevels = ['L1FastJet','L2Relative', 'L3Absolute', 'L2L3Residual']

#usePFBRECO(process,runPFBRECO=True,
usePF2PAT(process, runPF2PAT=True,
          runOnMC=runOnMC, outputModules = outputModules, postfix="PFlow",
          jetAlgo="AK5", jetCorrections=("AK5PFchs", jecLevels),
          typeIMetCorrections=True)

# top projections in PF2PAT:
process.pfNoPileUpPFlow.enable = True
process.pfNoMuonPFlow.enable = True
process.pfNoElectronPFlow.enable = True
process.pfNoTauPFlow.enable = False
process.pfNoJetPFlow.enable = True

# verbose flags for the PF2PAT modules
process.pfNoMuonPFlow.verbose = False

"""
# Change DR cone size to 0.3
process.pfIsolatedMuonsPFlow.isolationValueMapsCharged  = cms.VInputTag(cms.InputTag('muPFIsoValueCharged03PFlow'))
예제 #35
0
  #, PdfSetNames = cms.untracked.vstring( 'cteq66.LHgrid', 'CT10.LHgrid' )
  )

### PAT

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

# Misc
if len( jecLevels ) is 0:
  typeIMetCorrections = False
from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
usePF2PAT( process
         , runOnMC             = runOnMC
         , jetAlgo             = jetAlgo
         , jetCorrections      = ( jetAlgo + 'PFchs'
                                 , jecLevels
                                 )
         , typeIMetCorrections = typeIMetCorrections
         , pvCollection        = cms.InputTag( pvCollection )
         , outputModules       = outputModules
         )
from PhysicsTools.PatAlgos.tools.helpers import removeIfInSequence
removeIfInSequence( process, 'patPFParticles', 'patPF2PATSequence', '' )
removeIfInSequence( process, 'selectedPatPFParticles', 'patPF2PATSequence', '' )
removeIfInSequence( process, 'countPatPFParticles', 'patPF2PATSequence', '' )
from PhysicsTools.PatAlgos.tools.coreTools import *
removeSpecificPATObjects( process
                        , names          = [ 'Photons', 'Taus' ]
                        , outputModules  = outputModules
                        )
# The following is not performed (properly) by 'removeSpecificPATObjects()'
process.cleanPatCandidateSummary.candidates.remove( cms.InputTag( 'cleanPatPhotons' ) )
if useL2L3Residual and not runOnMC:
  jecLevels.append( 'L2L3Residual' )
if useL5Flavor:
  jecLevels.append( 'L5Flavor' )
if useL7Parton:
  jecLevels.append( 'L7Parton' )

### Switch configuration

from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
usePF2PAT( process
         , runPF2PAT           = True
         , runOnMC             = runOnMC
         , jetAlgo             = jetAlgo
         , postfix             = postfix
         , jetCorrections      = ( jecSet
                                 , jecLevels
                                 )
         , typeIMetCorrections = typeIMetCorrections
         , pvCollection        = cms.InputTag( pfVertices )
         )

if useMuonCutBasePF:
  pfMuonSelectionCut += ' && %s'%( muonCut )
if useElectronCutBasePF:
  pfElectronSelectionCut += ' && %s'%( electronCut )

getattr( process, 'pfNoPileUp'   + postfix ).enable = usePFnoPU
getattr( process, 'pfNoMuon'     + postfix ).enable = useNoMuon
getattr( process, 'pfNoElectron' + postfix ).enable = useNoElectron
getattr( process, 'pfNoJet'      + postfix ).enable = useNoJet
예제 #37
0
    outputCommands = cms.untracked.vstring( 'keep *' ), 
    SelectEvents   = cms.untracked.PSet( SelectEvents = cms.vstring('patreco') ), 
    fileName=cms.untracked.string("SynchSelMuJets.root")
)

process.add_( 
    cms.Service( "TFileService", 
        fileName = cms.string( options.output ), 
        closeFileFast = cms.untracked.bool(True) 
    ) 
)

from TopQuarkAnalysis.Configuration.patRefSel_PF2PAT import *
process.load("PhysicsTools.PatAlgos.patSequences_cff")
from PhysicsTools.PatAlgos.tools.pfTools import usePF2PAT
topPF2PAT = usePF2PAT(process,runOnMC = not options.isData,typeIMetCorrections = True,pvCollection= "goodOfflinePrimaryVertices",postfix=options.postfix) #configuration object for patPF2PATSequence

process.GlobalTag.globaltag = options.globalTag + '::All'
process.options = cms.untracked.PSet(wantSummary = cms.untracked.bool( not options.quiet ))
process.MessageLogger.cerr.FwkReport.reportEvery = 1000 if options.quiet else 10
process.maxEvents = cms.untracked.PSet(input = cms.untracked.int32( options.maxEvents ))
if not options.isData : process.eventCleaning.remove( process.scrapingFilter )
for item in ['mvaNonTrigV0'] : delattr( process, item )


process.patreco = cms.Path( reduce(operator.add, [getattr(process, item) for item in ['goodOfflinePrimaryVertices',
                                                                                      'eventCleaning',
                                                                                      'mvaTrigV0',
                                                                                      'patPF2PATSequence'+options.postfix]]))

#process.load('TopQuarkAnalysis.TopRefTuple.lumi_cfi')