def addTagInfos(process, jetMetCorrections):
    from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection

    # print jetMetCorrections
    switchJetCollection(
        process, jetSource=cms.InputTag("ak5CaloJets"), jetCorrections=("AK5Calo", jetMetCorrections, "None")
    )
    def ak4JetReclustering(self, process, pfCandCollection,
                           patMetModuleSequence, postfix):

        if not hasattr(process, "ak4PFJets"):
            process.load("RecoJets.JetProducers.ak4PFJets_cfi")
            print "reclustering ak4pf", pfCandCollection
            process.ak4PFJets.src = pfCandCollection
            process.ak4PFJets.doAreaFastjet = True

            patMetModuleSequence += getattr(process, "ak4PFJets")

            switchJetCollection(process,
                                jetSource=cms.InputTag('ak4PFJets'),
                                jetCorrections=('AK4PF', [
                                    'L1FastJet', 'L2Relative', 'L3Absolute'
                                ], ''))

            process.patJets.addGenJetMatch = False
            process.patJets.addGenPartonMatch = False
            process.patJets.addPartonJetMatch = False
            del process.patJets.JetFlavourInfoSource
            del process.patJets.JetPartonMapSource
            process.patJets.getJetMCFlavour = False

            process.patJetCorrFactors.primaryVertices = cms.InputTag(
                "offlineSlimmedPrimaryVertices")

        return cms.InputTag("selectedPatJets")
    def ak4JetReclustering(self, process, pfCandCollection, patMetModuleSequence, postfix):

        if not hasattr(process, "ak4PFJets"):
            process.load("RecoJets.JetProducers.ak4PFJets_cfi")
            print "reclustering ak4pf", pfCandCollection
            process.ak4PFJets.src = pfCandCollection
            process.ak4PFJets.doAreaFastjet = True

            patMetModuleSequence += getattr(process, "ak4PFJets")

            switchJetCollection(
                process,
                jetSource=cms.InputTag("ak4PFJets"),
                jetCorrections=("AK4PF", ["L1FastJet", "L2Relative", "L3Absolute"], ""),
            )

            process.patJets.addGenJetMatch = False
            process.patJets.addGenPartonMatch = False
            process.patJets.addPartonJetMatch = False
            del process.patJets.JetFlavourInfoSource
            del process.patJets.JetPartonMapSource
            process.patJets.getJetMCFlavour = False

            process.patJetCorrFactors.primaryVertices = cms.InputTag("offlineSlimmedPrimaryVertices")

        return cms.InputTag("selectedPatJets")
def loadPAT(process, jetMetCorrections, mcInfo):
    #-- Changes for electron and photon ID ----------------------------------------
    # Turn off photon-electron cleaning (i.e., flag only)
    process.cleanPatPhotons.checkOverlaps.electrons.requireNoOverlaps = False

    # Add CiC electron ID's and WP eleID's
    process.load("TripHto4lep.Skim3lep.cicEleIdSequence_42_cff")
    process.load("TripHto4lep.Skim3lep.hzzEleIdSequence_cff")
    process.load("TripHto4lep.Skim3lep.simpleEleIdSequence_cff")

    process.patElectrons.electronIDSources = cms.PSet(
        eidVeryLoose=cms.InputTag("eidVeryLooseMC"),
        eidLoose=cms.InputTag("eidLooseMC"),
        eidMedium=cms.InputTag("eidMediumMC"),
        eidTight=cms.InputTag("eidTightMC"),
        eidSuperTight=cms.InputTag("eidSuperTightMC"),
        eidHyperTight1=cms.InputTag("eidHyperTight1MC"),
        eidHZZVeryLoose=cms.InputTag("eidHZZVeryLoose"),
        eidHZZLoose=cms.InputTag("eidHZZLoose"),
        eidHZZMedium=cms.InputTag("eidHZZMedium"),
        eidHZZTight=cms.InputTag("eidHZZTight"),
        eidHZZSuperTight=cms.InputTag("eidHZZSuperTight"),
        #    eidHZZHyperTight1= cms.InputTag("eidHZZHyperTight1"),
        simpleEleId95relIso=cms.InputTag("simpleEleId95relIso"),
        simpleEleId90relIso=cms.InputTag("simpleEleId90relIso"),
        simpleEleId85relIso=cms.InputTag("simpleEleId85relIso"),
        simpleEleId80relIso=cms.InputTag("simpleEleId80relIso"),
        simpleEleId70relIso=cms.InputTag("simpleEleId70relIso"),
        simpleEleId60relIso=cms.InputTag("simpleEleId60relIso"))
    process.patDefaultSequence.replace(
        process.patElectrons,
        process.simpleEleIdSequence + process.cicEleIdSequence +
        process.hzzEleIdSequence + process.patElectrons)

    # Switch to PF Jets
    from PhysicsTools.PatAlgos.tools.jetTools import *
    #switchJetCollection(process, jetCollection = cms.InputTag("ak5PFJets"), outputModule = 'out')
    switchJetCollection(
        process,
        cms.InputTag('ak5PFJets'),
        doJTA=True,
        doBTagging=True,
        jetCorrLabel=('AK5PF',
                      cms.vstring(['L1Offset', 'L2Relative', 'L3Absolute'])),
        doType1MET=True,
        genJetCollection=cms.InputTag("ak5GenJets"),
        doJetID=True)
    process.patJetCorrFactors.rho = cms.InputTag('')
Esempio n. 5
0
    def Pat(self) :

        from PhysicsTools.PatAlgos.tools.coreTools import removeMCMatching,removeCleaning,restrictInputToAOD,removeAllPATObjectsBut
        from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection 
        from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection 

        if self.options.isData: removeMCMatching(self.process, ['All'])
        restrictInputToAOD(self.process)
        removeCleaning(self.process)
        removeAllPATObjectsBut(self.process, ['Jets','METs','Muons'])
        addJetCollection(self.process,
	    		    cms.InputTag('ak5CaloJets'),
			    'AK5',
			    'Calo',
			    jetCorrLabel = ('AK5Calo',self.options.jetCorrections),
			    genJetCollection = cms.InputTag('ak5GenJets'),
			    doType1MET = False,
                       )
        switchJetCollection(self.process,
	    		    cms.InputTag('ak5PFJets'),
			    doJTA = True,
		  	    doBTagging = True,
			    doJetID = True,
			    jetCorrLabel = ('AK5PF',self.options.jetCorrections),
			    genJetCollection = cms.InputTag('ak5GenJets'),
			    doType1MET = False,
			    jetIdLabel = 'ak5pf'
                       )

        self.process.selectedPatJets.cut = cms.string("pt > 30 && \
                                                       abs(eta) < 3.0 && \
                                                       neutralHadronEnergyFraction < 0.9 && \
                                                       neutralEmEnergyFraction < 0.90 && \
                                                       nConstituents > 1 && \
                                                       (? abs(eta)<2.4 ? chargedHadronEnergyFraction : 1) > 0 && \
                                                       (? abs(eta)<2.4 ? chargedHadronMultiplicity : 1) > 0 && \
                                                       (? abs(eta)<2.4 ? chargedEmEnergyFraction : 0) < 0.99")

        del self.process.out
        del self.process.outpath
	return self.process.patDefaultSequence
Esempio n. 6
0
def metUncertainty(process):
    process.load("PhysicsTools.PatAlgos.patSequences_cff")
    #process.MetSequence += process.type0PFMEtCorrection
    #process.MetSequence += process.patPFMETtype0Corr
    #from PhysicsTools.PatAlgos.patTemplate_cfg import *
    #from PhysicsTools.PatAlgos.tools.coreTools import *
    from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection
    #from PhysicsTools.PatAlgos.tools.metTools import *
    switchJetCollection(
        process,
        cms.InputTag('ak5PFJets'),
        doJTA=True,
        doBTagging=False,
        jetCorrLabel=('AK5PF',
                      cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute'])),
        doType1MET=False,
        doJetID=True,
        jetIdLabel="ak5",
        outputModules=[]  # no PAT output module
    )
    from PhysicsTools.PatUtils.tools.metUncertaintyTools import runMEtUncertainties
    runMEtUncertainties(process)
def metUncertainty(process):
    process.load("PhysicsTools.PatAlgos.patSequences_cff")
    # process.MetSequence += process.type0PFMEtCorrection
    # process.MetSequence += process.patPFMETtype0Corr
    # from PhysicsTools.PatAlgos.patTemplate_cfg import *
    # from PhysicsTools.PatAlgos.tools.coreTools import *
    from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection

    # from PhysicsTools.PatAlgos.tools.metTools import *
    switchJetCollection(
        process,
        cms.InputTag("ak5PFJets"),
        doJTA=True,
        doBTagging=False,
        jetCorrLabel=("AK5PF", cms.vstring(["L1FastJet", "L2Relative", "L3Absolute"])),
        doType1MET=False,
        doJetID=True,
        jetIdLabel="ak5",
        outputModules=[],  # no PAT output module
    )
    from PhysicsTools.PatUtils.tools.metUncertaintyTools import runMEtUncertainties

    runMEtUncertainties(process)
Esempio n. 8
0
def ReRunJetsEMB(process):

  process.load("RecoJets.Configuration.RecoPFJets_cff") 
  import PhysicsTools.PatAlgos.tools.jetTools as jettools
  process.load("PhysicsTools.PatAlgos.patSequences_cff")
  process.load("UWAnalysis.Configuration.tools.patJetPUId_cfi")
  from RecoBTag.SoftLepton.softLepton_cff import *
  from RecoBTag.ImpactParameter.impactParameter_cff import *
  from RecoBTag.SecondaryVertex.secondaryVertex_cff import *
  from RecoBTau.JetTagComputer.combinedMVA_cff import *

  process.pileupJetIdProducer.applyJec = cms.bool(True)

  # Define options for BTagging - these are release dependent.
  btag_options = {'doBTagging': True}
  btag_options['btagInfo'] = [
            'secondaryVertexTagInfos',
  ]
  btag_options['btagdiscriminators'] = [
            'combinedSecondaryVertexMVABJetTags',
            'combinedSecondaryVertexBJetTags',
  ]

  jec = ['L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual']

  
  jettools.switchJetCollection(
        process,
        cms.InputTag('ak5PFJets'),
        doJTA=False,
        jetCorrLabel=('AK5PF', jec),
        #jetCorrLabel = None,
        doType1MET=False,
        doJetID=True,
        genJetCollection=cms.InputTag("ak5GenJets"),
        outputModules=[],
        **btag_options       
  )
  process.patJets.embedPFCandidates = False
  process.patJets.embedCaloTowers = False
  process.patJets.embedGenJetMatch = False
  process.patJets.addAssociatedTracks = False
  process.patJets.embedGenPartonMatch = False
  process.patJets.tagInfoSources = cms.VInputTag(cms.InputTag("secondaryVertexTagInfos"))
  process.patJets.discriminatorSources = cms.VInputTag(cms.InputTag("combinedSecondaryVertexMVABJetTags"), cms.InputTag("combinedSecondaryVertexBJetTags"))
  process.patJets.addBTagInfo = cms.bool(True)
  
  process.ak5JetTracksAssociatorAtVertex = cms.EDProducer("JetTracksAssociatorAtVertex",
   	  tracks       = cms.InputTag("tmfTracks"),
      jets         = cms.InputTag("ak5PFJets"),
      coneSize     = cms.double(0.5)
  )
  
  process.load('UWAnalysis.Configuration.tools.RecoBTag_cff')  
  process.patJetCharge.src = cms.InputTag("ak5JetTracksAssociatorAtVertex")
  process.NewSelectedPatJets = process.selectedPatJets.clone(src = cms.InputTag("patJetId"))
  process.analysisSequence = cms.Sequence(
  					process.analysisSequence*
  					process.ak5PFJets*
  					process.ak5JetTracksAssociatorAtVertex*
  					process.btagging*
  					process.pileupJetIdProducer*
  					process.makePatJets*
  					process.patJetsPUID*
  					process.patJetId*
  					process.NewSelectedPatJets  					
  					)
Esempio n. 9
0
   process,
   postfix   = postfixAK4PFCHS,
   labelName = labelAK4PFCHS,
   jetSource = cms.InputTag('ak4PFJetsCHS'),
   jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'Type-2')
   )
process.out.outputCommands.append( 'drop *_selectedPatJets%s%s_caloTowers_*'%( labelAK4PFCHS, postfixAK4PFCHS ) )

# uncomment the following lines to add ak4PFJets to your PAT output
switchJetCollection(
   process,
   jetSource = cms.InputTag('ak4PFJets'),
   jetCorrections = ('AK4PF', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'Type-1'),
   btagDiscriminators = [
       'pfJetBProbabilityBJetTags'
     , 'pfJetProbabilityBJetTags'
     , 'pfTrackCountingHighPurBJetTags'
     , 'pfTrackCountingHighEffBJetTags'
     , 'pfSimpleSecondaryVertexHighEffBJetTags'
     , 'pfSimpleSecondaryVertexHighPurBJetTags'
     , 'pfCombinedInclusiveSecondaryVertexV2BJetTags'
     ]
   )
process.out.outputCommands.append( 'drop *_selectedPatJets_caloTowers_*' )

# uncomment the following lines to add ak8PFJetsCHSSoftDrop to your PAT output
labelAK8PFCHSSoftDrop = 'AK8PFCHSSoftDrop'
addJetCollection(
   process,
   labelName = labelAK8PFCHSSoftDrop,
   jetSource = cms.InputTag('ak8PFJetsCHSSoftDrop',''),
   algo = 'AK',
Esempio n. 10
0
def addPlainPat(process, dataVersion, doPatTrigger=True, doPatTaus=True, doHChTauDiscriminators=True, doPatMET=True, doPatElectronID=True,
                doPatCalo=True, doBTagging=True, doPatMuonPFIsolation=False, doPatTauIsoDeposits=False,
                doTauHLTMatching=True, matchingTauTrigger=None, matchingJetTrigger=None,
                includePFCands=False):
    out = None
    outdict = process.outputModules_()
    if outdict.has_key("out"):
        out = outdict["out"]

    outputCommands = []

    # Tau Discriminators
    process.hplusPatTauSequence = cms.Sequence()
    if doPatTaus:
        process.hplusPatTauSequence = addPFTausAndDiscriminators(process, dataVersion, doPatCalo, doHChTauDiscriminators)

    # PAT Layer 0+1
    process.load("PhysicsTools.PatAlgos.patSequences_cff")

    sequence = cms.Sequence(
        process.hplusPatTauSequence
    )

    # Restrict input to AOD
    restrictInputToAOD(process, ["All"])

    # Remove MC stuff if we have collision data (has to be done any add*Collection!)
    # This also adds the L2L3Residual JEC correction to the process.patJetCorrFactors
    if dataVersion.isData():
        runOnData(process, outputInProcess = out!=None)

    # Jets
    # Produce kt6 rho for L1Fastjet
    process.load('RecoJets.Configuration.RecoPFJets_cff')
    process.kt6PFJets.doRhoFastjet = True
    process.ak5PFJets.doAreaFastjet = True
    process.ak5PFJetSequence = cms.Sequence(process.kt6PFJets * process.ak5PFJets)
   
    # Set defaults
    process.patJets.jetSource = cms.InputTag("ak5CaloJets")
    process.patJets.trackAssociationSource = cms.InputTag("ak5JetTracksAssociatorAtVertex")
    setPatJetDefaults(process.patJets)
    setPatJetCorrDefaults(process.patJetCorrFactors, dataVersion)
    process.patDefaultSequence.replace(process.patJetCorrFactors,
                                       process.ak5PFJetSequence*process.patJetCorrFactors)
    process.selectedPatJets.cut = jetPreSelection

    # The default JEC to be embedded to pat::Jets are L2Relative,
    # L3Absolute, L5Flavor and L7Parton. The default JEC to be applied
    # is L2L3Residual, or L3Absolute, or Uncorrected (in this order).

    if doPatCalo:
        # Add JPT jets
        # FIXME: Disabled for now until the JEC for JPT works again (with the latest JEC)
#        addJetCollection(process, cms.InputTag('JetPlusTrackZSPCorJetAntiKt5'),
#                         'AK5', 'JPT',
#                         doJTA        = True,
#                         doBTagging   = doBTagging,
#                         jetCorrLabel = ('AK5JPT', process.patJetCorrFactors.levels),
#                         doType1MET   = False,
#                         doL1Cleaning = False,
#                         doL1Counters = True,
#                         genJetCollection = cms.InputTag("ak5GenJets"),
#                         doJetID      = True
#        )
    
        # Add PF jets
        addJetCollection(process, cms.InputTag('ak5PFJets'),
                         'AK5', 'PF',
                         doJTA        = True,
                         doBTagging   = doBTagging,
                         jetCorrLabel = ('AK5PF', process.patJetCorrFactors.levels),
                         doType1MET   = False,
                         doL1Cleaning = False,
                         doL1Counters = True,
                         genJetCollection = cms.InputTag("ak5GenJets"),
                         doJetID      = True
        )
        setPatJetCorrDefaults(process.patJetCorrFactorsAK5PF, dataVersion, True)

    else:
        setPatJetCorrDefaults(process.patJetCorrFactors, dataVersion, True)
        switchJetCollection(process, cms.InputTag('ak5PFJets'),
                            doJTA        = True,
                            doBTagging   = doBTagging,
                            jetCorrLabel = ('AK5PF', process.patJetCorrFactors.levels),
                            doType1MET   = False,
                            genJetCollection = cms.InputTag("ak5GenJets"),
                            doJetID      = True
        )
    
    outputCommands.extend([
            "keep *_selectedPatJets_*_*",
            "keep *_selectedPatJetsAK5JPT_*_*",
            "keep *_selectedPatJetsAK5PF_*_*",
            'drop *_selectedPatJets_pfCandidates_*', ## drop for default patJets which are CaloJets
            'drop *_*PF_caloTowers_*',
            'drop *_*JPT_pfCandidates_*',
            'drop *_*Calo_pfCandidates_*',
            ])

    # Taus

    # Set default PATTauProducer options here, they should be
    # replicated to all added tau collections (and the first call to
    # addTauCollection should replace the default producer modified
    # here)
    setPatTauDefaults(process.patTaus, includePFCands)
    process.selectedPatTaus.cut = tauPreSelection

    if doPatTaus:
        if doHChTauDiscriminators:
            addHChTauDiscriminators()

        # Don't enable TCTau nor shrinking cone tau
        # if doPatCalo:
        #     tauTools.addTauCollection(process,cms.InputTag('caloRecoTauProducer'),
        #                      algoLabel = "caloReco",
        #                      typeLabel = "Tau")
        #     setPatTauDefaults(process.patTausCaloRecoTau, True)
        #     process.patTausCaloRecoTau.embedLeadTrack = not includePFCands
        #     process.patTausCaloRecoTau.embedLeadPFChargedHadrCand = False
    
        # tauTools.addTauCollection(process,cms.InputTag('shrinkingConePFTauProducer'),
        #                  algoLabel = "shrinkingCone",
        #                  typeLabel = "PFTau")
        # # Disable isoDeposits like this until the problem with doPFIsoDeposits is fixed 
        # if not doPatTauIsoDeposits:
        #     process.patTausShrinkingConePFTau.isoDeposits = cms.PSet()

        tauTools.addTauCollection(process,cms.InputTag('hpsPFTauProducer'),
                         algoLabel = "hps",
                         typeLabel = "PFTau")
        if not doPatTauIsoDeposits:
            process.patTausHpsPFTau.isoDeposits = cms.PSet()
        addPatTauIsolationEmbedding(process, process.patDefaultSequence, "HpsPFTau")

        tauTools.addTauCollection(process,cms.InputTag('hpsTancTaus'),
                                  algoLabel = "hpsTanc",
                                  typeLabel = "PFTau")
        if not doPatTauIsoDeposits:
            process.patTausHpsTancPFTau.isoDeposits = cms.PSet()
        # Disable discriminators which are not in AOD
#        del process.patTausHpsTancPFTau.tauIDSources.againstCaloMuon
#        del process.patTausHpsTancPFTau.tauIDSources.byHPSvloose
        addPatTauIsolationEmbedding(process, process.patDefaultSequence, "HpsTancPFTau")

        # Add visible taus    
        if dataVersion.isMC():
            process.VisibleTaus = cms.EDProducer("HLTTauMCProducer",
                GenParticles  = cms.untracked.InputTag("genParticles"),
                ptMinTau      = cms.untracked.double(3),
                ptMinMuon     = cms.untracked.double(3),
                ptMinElectron = cms.untracked.double(3),
                BosonID       = cms.untracked.vint32(23),
                EtaMax         = cms.untracked.double(2.5)
            )
            sequence *= process.VisibleTaus
            outputCommands.append("keep *_VisibleTaus_*_*")

    else:
        # FIXME: this is broken at the moment
        #removeSpecificPATObjects(process, ["Taus"], outputInProcess= out != None)
        process.patDefaultSequence.remove(process.patTaus)
        process.patDefaultSequence.remove(process.selectedPatTaus)

    outputCommands.extend(["drop *_selectedPatTaus_*_*",
#                           "keep *_selectedPatTausCaloRecoTau_*_*",
#                           "keep *_selectedPatTausShrinkingConePFTau_*_*",
                           "keep *_selectedPatTausHpsPFTau_*_*",
                           "keep *_selectedPatTausHpsTancPFTau_*_*",
                           #"keep *_cleanPatTaus_*_*",
                           #"drop *_cleanPatTaus_*_*",
                           #"keep *_patTaus*_*_*",
                           #"keep *_patPFTauProducerFixedCone_*_*",
                           # keep these until the embedding problem with pat::Tau is fixed
                           #"keep recoPFCandidates_particleFlow_*_*",
                           #"keep recoTracks_generalTracks_*_*"
                           ])

    # MET
    addPfMET(process, 'PF')
    if doPatCalo:
        addTcMET(process, 'TC')
    else:
        # FIXME: This is broken at the moment...
        #removeSpecificPATObjects(process, ["METs"], outputInProcess= out != None)
        #process.patDefaultSequen
        process.patDefaultSequence.remove(process.patMETCorrections)
        process.patDefaultSequence.remove(process.patMETs)
        del process.patMETCorrections
        del process.patMETs

    outputCommands.extend([
            "keep *_patMETs_*_*",
            "keep *_patMETsTC_*_*",
            "keep *_patMETsPF_*_*",
            "keep *_genMetTrue_*_*",
            ])

    # Muons
    setPatLeptonDefaults(process.patMuons, includePFCands)
    if doPatMuonPFIsolation:
        addPFMuonIsolation(process, process.patMuons, sequence, verbose=True)

    outputCommands.extend([
            "keep *_selectedPatMuons_*_*"
            ])

    # Electrons
    # In order to calculate the transverse impact parameter w.r.t.
    # beam spot instead of primary vertex, see
    setPatLeptonDefaults(process.patMuons, includePFCands)

    # Electron ID, see
    # https://twiki.cern.ch/twiki/bin/view/CMS/SimpleCutBasedEleID
    if doPatElectronID:
        addPatElectronID(process, process.patElectrons, process.patDefaultSequence)

    outputCommands.extend([
            "keep *_selectedPatElectrons_*_*"
            ])

    # Photons
#    process.patPhotons.embedGenMatch = False
    outputCommands.extend([
            "keep *_selectedPatPhotons_*_*"
            ])

    # Trigger
    if doPatTrigger:
        outMod= ''
        if out != None:
            outMod  = 'out'
        switchOnTrigger(process, hltProcess=dataVersion.getTriggerProcess(), outputModule=outMod)
        process.patTrigger.addL1Algos = cms.bool(True)
        process.patTrigger.l1ExtraMu = cms.InputTag("l1extraParticles")
        process.patTrigger.l1ExtraCenJet = cms.InputTag("l1extraParticles", "Central")
        process.patTrigger.l1ExtraTauJet = cms.InputTag("l1extraParticles", "Tau")
        process.patTrigger.l1ExtraForJet = cms.InputTag("l1extraParticles", "Forward")
        process.patTrigger.l1ExtraETM = cms.InputTag("l1extraParticles", "MET")
        process.patTrigger.l1ExtraHTM = cms.InputTag("l1extraParticles", "MHT")


        # Keep StandAlone trigger objects for enabling trigger
        # matching in the analysis phase with PAT tools
        outputCommands.extend(patTriggerStandAloneEventContent)


    # Remove cleaning step and set the event content
    if out == None:
        myRemoveCleaning(process)
    else:
        backup = out.outputCommands[:]
        myRemoveCleaning(process)
#        backup_pat = out.outputCommands[:]

        # Remove PFParticles here, they are explicitly included when needed
#        backup_pat = filter(lambda n: "selectedPatPFParticles" not in n, backup_pat)

        out.outputCommands = backup
#        out.outputCommands.extend(backup_pat)
        out.outputCommands.extend(outputCommands)

    # Build sequence
    sequence *= process.patDefaultSequence

    # Tau+HLT matching
    if doTauHLTMatching:
        sequence *= HChTriggerMatching.addTauHLTMatching(process, matchingTauTrigger, matchingJetTrigger)

    return sequence
Esempio n. 11
0
########################################

if isData:
    from PhysicsTools.PatAlgos.tools.coreTools import *
    removeMCMatching(process, ['All'], outputInProcess=False)

########################################
# PAT Jet Energy Corrections - MC vs Data
########################################
#

from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection
if isMC:
    switchJetCollection(process,
                        jetCollection=cms.InputTag('ak5CaloJets'),
                        jetCorrLabel=('AK5Calo',
                                      ['L1Offset', 'L2Relative',
                                       'L3Absolute']))
else:
    switchJetCollection(process,
                        jetCollection=cms.InputTag('ak5CaloJets'),
                        jetCorrLabel=('AK5Calo',
                                      ['L1Offset', 'L2Relative',
                                       'L3Absolute']))

########################################
# PAT Trigger matching
########################################
# imported directly from PhysicsTools/PatExamples/test/analyzePatTrigger_onTheFly_cfg.py
#
process.load("HeavyNu.AnalysisModules.hnutrigmatch_cfi")
Esempio n. 12
0
    rParam = 0.8,
    jetCorrections = ('AK7PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
    trackSource = cms.InputTag('unpackedTracksAndVertices'),
    pvSource = cms.InputTag('unpackedTracksAndVertices'),
    )                                                                                                                                                                                  
addJetCollection(
    process,
    labelName = 'AK8PFCHS',
    jetSource = cms.InputTag('ak8PFJetsCHS'),
    algo = 'ak8',
    rParam = 0.8,
    jetCorrections = ('AK7PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
    trackSource = cms.InputTag('unpackedTracksAndVertices'),
    pvSource = cms.InputTag('unpackedTracksAndVertices'),
    ) 
"""
switchJetCollection(
    process,
    jetSource = cms.InputTag('ak4PFJets'),
    algo = 'ak4',
    rParam = 0.4,
    jetCorrections = ('AK5PF', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'Type-1'),
    # btagDiscriminators = ['jetBProbabilityBJetTags',
    #                       'jetProbabilityBJetTags',
    #                       'trackCountingHighPurBJetTags',
    #                       'trackCountingHighEffBJetTags',
    #                       'simpleSecondaryVertexHighEffBJetTags',
    #                       'simpleSecondaryVertexHighPurBJetTags',
    #                       'combinedSecondaryVertexBJetTags'
    #                       ],
    trackSource = cms.InputTag('unpackedTracksAndVertices'),
def configurePatTuple(process, isMC=True, **kwargs):

    # Stuff we always keep
    output_commands = [
        #        '*',
        '*_addPileupInfo_*_*',
        'edmMergeableCounter_*_*_*',
        '*_lumiProducer_*_*',
        '*_particleFlow_*_*',
        '*_offlineBeamSpot_*_*',
        '*_generalTracks_*_*',
        '*_electronGsfTracks_*_*',
        '*_offlinePrimaryVertices*_*_*',
        '*_ak5GenJets_*_*',
        '*_hltTriggerSummaryAOD_*_*',
        'edmTriggerResults_TriggerResults_*_%s' % process.name_(),
        '*_MEtoEDMConverter*_*_%s' % process.name_(),
        'LHEEventProduct_*_*_*',
        'GenEventInfoProduct_generator_*_*',
        '*_kt6PFJetsForRhoComputationVoronoi_rho_*',
        '*_kt6PFJetsForIso_rho_*',
        '*_kt6PFJets_rho_*',
        '*_kt6PFJetsCentralHZGPho_rho_*',
        '*_kt6PFJetsCentralHZGEle_rho_*',
        '*_kt6PFJetsCentralHZGMu_rho_*',
        '*_kt6PFJetsCentralNeutralHZGMu_rho_*',
        '*_kt6PFJetsCentral_rho_*',
        '*_kt6PFJetsCentralNeutral_rho_*',  #for zz muons
        '*_photonCore_*_*',
        # for Zmumu -> embedded samples
        '*_generator_weight_*',  # 2k11
        "GenFilterInfo_generator_minVisPtFilter_*",  #2k12
        '*_genDaughters_*_*',
        '*_boosted*_*_*',
        '*_tmfTracks_*_*',
    ]
    # Define our patTuple production sequence
    process.tuplize = cms.Sequence()
    # Only keep interesting genParticles
    process.load("FinalStateAnalysis.RecoTools.genParticleTrimmer_cfi")
    process.genParticles = process.prunedGenParticles.clone()
    if isMC:
        #process.tuplize += process.genParticles
        #output_commands.append('*_genParticles_*_%s' % process.name_())
        output_commands.append('*_genParticles_*_*')

    output_commands.append('*_tauGenJetsSelectorAllHadrons_*_*')
    output_commands.append('*_tauGenJets_*_*')
    output_commands.append('*_ak5GenJets_*_*')
    # Select vertices
    process.load("FinalStateAnalysis.RecoTools.vertexSelection_cff")
    output_commands.append('*_selectedPrimaryVertex_*_*')
    output_commands.append('*_selectPrimaryVerticesQuality_*_*')
    process.tuplize += process.selectPrimaryVertices

    # Run the ZZ recipe for rho
    from RecoJets.JetProducers.kt4PFJets_cfi import kt4PFJets \
            as zzCantDoAnythingRight

    process.kt6PFJetsForIso = zzCantDoAnythingRight.clone(
        rParam=cms.double(0.6),
        doAreaFastjet=cms.bool(True),
        doRhoFastjet=cms.bool(True),
        Rho_EtaMax=cms.double(2.5),
        Ghost_EtaMax=cms.double(2.5),
    )
    process.tuplize += process.kt6PFJetsForIso

    # Standard services
    process.load('Configuration.StandardSequences.Services_cff')
    # tack on seeds for FSA PATTuple modules
    add_fsa_random_seeds(process)

    if cmssw_major_version() == 5 and cmssw_minor_version() >= 3:
        process.load('Configuration.Geometry.GeometryIdeal_cff')
    else:
        process.load('Configuration.StandardSequences.GeometryIdeal_cff')

    process.load('Configuration.StandardSequences.MagneticField_cff')
    process.load(
        'Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')

    # Rerun tau ID
    if cmssw_major_version() == 4:
        process.load("RecoTauTag.Configuration.RecoPFTauTag_cff")
        # Optimization - remove PFTauTagInfo compatibility layer
        process.recoTauClassicHPSSequence.remove(
            process.pfRecoTauTagInfoProducer)
        process.recoTauClassicHPSSequence.remove(
            process.ak5PFJetTracksAssociatorAtVertex)
        assert (process.combinatoricRecoTaus.modifiers[3].name.value() ==
                'TTIworkaround')
        del process.combinatoricRecoTaus.modifiers[3]
        # Don't build junky taus below 19 GeV
        process.combinatoricRecoTaus.builders[0].minPtToBuild = cms.double(17)
        process.tuplize += process.recoTauClassicHPSSequence
    else:
        # We can run less tau stuff in 52, since HPS taus already built.
        process.load("RecoTauTag.Configuration.updateHPSPFTaus_cff")
        process.tuplize += process.updateHPSPFTaus

    ## Run rho computation.  Only necessary in 42X
    if cmssw_major_version() == 4:
        from RecoJets.Configuration.RecoPFJets_cff import kt6PFJets
        kt6PFJets.Rho_EtaMax = cms.double(4.4)
        kt6PFJets.doRhoFastjet = True
        process.kt6PFJets = kt6PFJets
        process.tuplize += process.kt6PFJets

    # In 4_X we have to rerun ak5PFJets with area computation enabled.
    if cmssw_major_version() == 4:
        process.load("RecoJets.Configuration.RecoPFJets_cff")
        process.ak5PFJets.doAreaFastjet = True
        process.tuplize += process.ak5PFJets
        # Only keep the new ak5PFJets
        output_commands.append('*_ak5PFJets_*_%s' % process.name_())
    else:
        # Just keep the normal ones
        output_commands.append('*_ak5PFJets_*_*')

    # In the embedded samples, we need to re-run the b-tagging
    if kwargs['embedded']:
        process.load('RecoBTag/Configuration/RecoBTag_cff')
        process.load('RecoJets/JetAssociationProducers/ak5JTA_cff')
        process.ak5JetTracksAssociatorAtVertex.jets = cms.InputTag("ak5PFJets")
        process.ak5JetTracksAssociatorAtVertex.tracks = cms.InputTag(
            "tmfTracks")
        process.tuplize += process.ak5JetTracksAssociatorAtVertex
        process.tuplize += process.btagging

    # Run pat default sequence
    process.load("PhysicsTools.PatAlgos.patSequences_cff")
    # Embed PF Isolation in electrons & muons
    pfTools.usePFIso(process)
    # Setup H2Tau custom iso definitions
    setup_h2tau_iso(process)
    # Setup hZg custom iso definitions
    add_hZg_iso_needs(process)

    # Use POG recommendations for (these) electron Isos
    process.elPFIsoValueGamma04PFIdPFIso.deposits[0].vetos = cms.vstring(
        'EcalEndcaps:ConeVeto(0.08)')
    process.elPFIsoValueGamma04NoPFIdPFIso.deposits[0].vetos = cms.vstring(
        'EcalEndcaps:ConeVeto(0.08)')
    process.elPFIsoValueCharged04PFIdPFIso.deposits[0].vetos = cms.vstring(
        'EcalEndcaps:ConeVeto(0.015)')
    process.elPFIsoValueCharged04NoPFIdPFIso.deposits[0].vetos = cms.vstring(
        'EcalEndcaps:ConeVeto(0.015)')

    # Unembed junk
    process.patMuons.embedCaloMETMuonCorrs = False
    process.patMuons.embedTcMETMuonCorrs = False
    process.patMuons.embedTrack = True
    process.patMuons.pvSrc = cms.InputTag("selectedPrimaryVertex")

    # Do extra electron ID
    process.load("FinalStateAnalysis.PatTools.electrons.electronID_cff")
    process.tuplize += process.recoElectronID
    process.patElectrons.electronIDSources = process.electronIDSources
    process.patElectrons.embedTrack = True

    # Now run PAT
    process.tuplize += process.patDefaultSequence

    # Add FSR photons for ZZ analysis
    process.load("FinalStateAnalysis.PatTools.fsrPhotons_cff")
    process.tuplize += process.fsrPhotonSequence

    # Use HPS taus
    tautools.switchToPFTauHPS(process)
    # Disable tau IsoDeposits
    process.patDefaultSequence.remove(process.patPFTauIsolation)
    process.patTaus.isoDeposits = cms.PSet()
    process.patTaus.userIsolation = cms.PSet()

    # Disable gen match embedding - we keep it in the ntuple
    process.patMuons.embedGenMatch = False
    process.patElectrons.embedGenMatch = False
    process.patTaus.embedGenMatch = False
    process.patTaus.embedGenJetMatch = False

    # Use PFJets and turn on JEC
    jec = ['L1FastJet', 'L2Relative', 'L3Absolute']
    # If we are running on data (not MC), or embedded sample,
    # apply the MC-DATA residual correction.
    if not isMC or kwargs['embedded']:
        jec.extend(['L2L3Residual'])

    # Define options for BTagging - these are release dependent.
    btag_options = {'doBTagging': True}
    if cmssw_major_version() == 5:
        btag_options['btagInfo'] = [
            'impactParameterTagInfos', 'secondaryVertexTagInfos',
            'softMuonTagInfos', 'secondaryVertexNegativeTagInfos'
        ]
        btag_options['btagdiscriminators'] = [
            'trackCountingHighEffBJetTags',
            'simpleSecondaryVertexHighEffBJetTags',
            'combinedSecondaryVertexMVABJetTags',
            'combinedSecondaryVertexBJetTags',
        ]

    # Use AK5 PFJets
    jettools.switchJetCollection(
        process,
        cms.InputTag('ak5PFJets'),
        doJTA=False,
        jetCorrLabel=('AK5PF', jec),
        #jetCorrLabel = None,
        doType1MET=False,
        doJetID=True,
        genJetCollection=cms.InputTag("ak5GenJets"),
        **btag_options)
    process.patJets.embedPFCandidates = False
    process.patJets.embedCaloTowers = False
    process.patJets.embedGenJetMatch = False
    process.patJets.addAssociatedTracks = False
    process.patJets.embedGenPartonMatch = False
    #process.patJetCorrFactors.useRho = True
    ## Let's use the same rho as in the TauID, so we don't need to do it twice.
    #process.patJetCorrFactors.rho = cms.InputTag(
    #"kt6PFJetsForRhoComputationVoronoi", "rho")

    # Use PFMEt
    mettools.addPfMET(process)
    if not isMC:
        coreTools.runOnData(process)
        process.patMETsPF.addGenMET = False
    output_commands.append('*_selectedPatJets_*_*')

    # Customize/embed all our sequences
    process.load("FinalStateAnalysis.PatTools.patJetProduction_cff")
    # We have to keep all jets (for the MVA MET...)
    process.patJetGarbageRemoval.cut = 'pt > 0'

    final_jet_collection = chain_sequence(process.customizeJetSequence,
                                          "patJets")
    process.customizeJetSequence.insert(0, process.patJets)
    # Make it a "complete" sequence
    process.customizeJetSequence += process.selectedPatJets
    # We can't mess up the selected pat jets because the taus use them.
    process.selectedPatJets.src = final_jet_collection
    process.patDefaultSequence.replace(process.patJets,
                                       process.customizeJetSequence)

    # Produce the electron collections
    process.load("FinalStateAnalysis.PatTools.patElectronProduction_cff")
    final_electron_collection = chain_sequence(
        process.customizeElectronSequence, "selectedPatElectrons")
    process.tuplize += process.customizeElectronSequence
    process.customizeElectronSequence.insert(0, process.selectedPatElectrons)
    process.patDefaultSequence.replace(process.selectedPatElectrons,
                                       process.customizeElectronSequence)
    # We have to do the pat Jets before the pat electrons since we embed them
    process.customizeElectronSequence.insert(0, process.selectedPatJets)
    process.cleanPatElectrons.src = final_electron_collection
    #setup the energy regression for the specific dataset
    process.patElectronEnergyCorrections.isMC = cms.bool(bool(isMC))
    process.patElectronEnergyCorrections.isAOD = \
                                               cms.bool(bool(kwargs['isAOD']))
    process.patElectronEnergyCorrections.dataSet = \
                                     cms.string(kwargs['calibrationTarget'])

    process.load("FinalStateAnalysis.PatTools.patMuonProduction_cff")
    final_muon_collection = chain_sequence(process.customizeMuonSequence,
                                           "selectedPatMuons")
    process.customizeMuonSequence.insert(0, process.selectedPatMuons)
    process.patDefaultSequence.replace(process.selectedPatMuons,
                                       process.customizeMuonSequence)
    process.cleanPatMuons.src = final_muon_collection
    process.patMuonRochesterCorrectionEmbedder.isMC = cms.bool(bool(isMC))

    process.load("FinalStateAnalysis.PatTools.patTauProduction_cff")
    final_tau_collection = chain_sequence(process.customizeTauSequence,
                                          "selectedPatTaus")
    # Inject into the pat sequence
    process.customizeTauSequence.insert(0, process.selectedPatTaus)
    process.patDefaultSequence.replace(process.selectedPatTaus,
                                       process.customizeTauSequence)
    process.cleanPatTaus.src = final_tau_collection
    # Remove muons and electrons
    process.cleanPatTaus.checkOverlaps.muons.requireNoOverlaps = False
    process.cleanPatTaus.checkOverlaps.electrons.requireNoOverlaps = False
    # Apply a loose preselection
    process.cleanPatTaus.preselection = 'abs(eta) < 2.5 & pt > 17'
    # Don't apply any "final" cut
    process.cleanPatTaus.finalCut = ''

    # Setup pat::Photon Production
    process.load("FinalStateAnalysis.PatTools.patPhotonProduction_cff")
    final_photon_collection = chain_sequence(process.customizePhotonSequence,
                                             "selectedPatPhotons")
    #inject photons into pat sequence
    process.customizePhotonSequence.insert(0, process.selectedPatPhotons)
    process.patDefaultSequence.replace(process.selectedPatPhotons,
                                       process.customizePhotonSequence)
    process.cleanPatPhotons.src = final_photon_collection

    # Setup MET production
    process.load("FinalStateAnalysis.PatTools.patMETProduction_cff")
    final_met_collection = chain_sequence(process.customizeMETSequence,
                                          "patMETsPF")
    process.tuplize += process.customizeMETSequence
    # The MET systematics depend on all other systematics
    process.systematicsMET.tauSrc = cms.InputTag("cleanPatTaus")
    process.systematicsMET.muonSrc = cms.InputTag("cleanPatMuons")
    process.systematicsMET.electronSrc = cms.InputTag("cleanPatElectrons")

    # Keep all the data formats needed for the systematics
    output_commands.append('recoLeafCandidates_*_*_%s' % process.name_())

    # Define the default lepton cleaning
    process.cleanPatElectrons.preselection = cms.string('pt > 5')
    process.cleanPatElectrons.checkOverlaps.muons.requireNoOverlaps = False
    # Make sure we don't kill any good taus by calling them electrons
    # Note that we don't actually remove these overlaps.
    process.cleanPatElectrons.checkOverlaps.taus = cms.PSet(
        src=final_tau_collection,
        algorithm=cms.string("byDeltaR"),
        preselection=cms.string(
            "tauID('decayModeFinding') > 0.5 &&"
            "tauID('byLooseCombinedIsolationDeltaBetaCorr') > 0.5 &&"
            "tauID('againstElectronLoose') > 0.5 && "
            "pt > 10"),
        deltaR=cms.double(0.1),
        checkRecoComponents=cms.bool(False),
        pairCut=cms.string(""),
        requireNoOverlaps=cms.bool(False),
    )

    output_commands.append('*_cleanPatTaus_*_*')
    output_commands.append('*_cleanPatElectrons_*_*')
    output_commands.append('*_cleanPatMuons_*_*')
    output_commands.append('*_cleanPatPhotons_*_*')
    output_commands.append('*_%s_*_*' % final_met_collection.value())

    trigtools.switchOnTrigger(process)

    # Now build the PATFinalStateLS object, which holds LumiSection info.
    process.load(
        "FinalStateAnalysis.PatTools.finalStates.patFinalStateLSProducer_cfi")
    process.tuplize += process.finalStateLS
    output_commands.append('*_finalStateLS_*_*')
    if isMC:
        process.finalStateLS.xSec = kwargs['xSec']

    # Tell the framework to shut up!
    process.load("FWCore.MessageLogger.MessageLogger_cfi")
    process.MessageLogger.cerr.FwkReport.reportEvery = 1000

    # Which collections are used to build the final states
    fs_daughter_inputs = {
        'electrons': 'cleanPatElectrons',
        'muons': 'cleanPatMuons',
        'taus': 'cleanPatTaus',
        'photons': 'cleanPatPhotons',
        'jets': 'selectedPatJets',
        'met': final_met_collection,
    }

    # Setup all the PATFinalState objects
    produce_final_states(process, fs_daughter_inputs, output_commands,
                         process.tuplize, kwargs['puTag'])

    return process.tuplize, output_commands
                 jetSource=cms.InputTag('ak4PFJetsCHS'),
                 jetCorrections=('AK4PFchs',
                                 cms.vstring(
                                     ['L1FastJet', 'L2Relative',
                                      'L3Absolute']), 'Type-2'))
process.out.outputCommands.append('drop *_selectedPatJets%s%s_caloTowers_*' %
                                  (labelAK4PFCHS, postfixAK4PFCHS))

# uncomment the following lines to add ak4PFJets to your PAT output
switchJetCollection(
    process,
    jetSource=cms.InputTag('ak4PFJets'),
    jetCorrections=('AK4PF',
                    cms.vstring(['L1FastJet', 'L2Relative',
                                 'L3Absolute']), 'Type-1'),
    btagDiscriminators=[
        'pfJetBProbabilityBJetTags', 'pfJetProbabilityBJetTags',
        'pfTrackCountingHighPurBJetTags', 'pfTrackCountingHighEffBJetTags',
        'pfSimpleSecondaryVertexHighEffBJetTags',
        'pfSimpleSecondaryVertexHighPurBJetTags',
        'pfCombinedInclusiveSecondaryVertexV2BJetTags'
    ])
process.out.outputCommands.append('drop *_selectedPatJets_caloTowers_*')

# uncomment the following lines to add ak8PFJetsCHSSoftDrop to your PAT output
labelAK8PFCHSSoftDrop = 'AK8PFCHSSoftDrop'
addJetCollection(
    process,
    labelName=labelAK8PFCHSSoftDrop,
    jetSource=cms.InputTag('ak8PFJetsCHSSoftDrop', ''),
    algo='AK',
def configurePatTuple(process, isMC=True, **kwargs):

    # Stuff we always keep
    output_commands = [
#        '*',
        '*_addPileupInfo_*_*',
        'edmMergeableCounter_*_*_*',
        '*_lumiProducer_*_*',
        '*_particleFlow_*_*',
        '*_offlineBeamSpot_*_*',
        '*_generalTracks_*_*',
        '*_electronGsfTracks_*_*',
        '*_offlinePrimaryVertices*_*_*',
        '*_ak5GenJets_*_*',
        '*_hltTriggerSummaryAOD_*_*',
        'edmTriggerResults_TriggerResults_*_%s' % process.name_(),
        '*_MEtoEDMConverter*_*_%s' % process.name_(),
        'LHEEventProduct_*_*_*',
        'GenEventInfoProduct_generator_*_*',
        '*_kt6PFJetsForRhoComputationVoronoi_rho_*',
        '*_kt6PFJetsForIso_rho_*',
        '*_kt6PFJets_rho_*',
        '*_kt6PFJetsCentralHZGPho_rho_*',
        '*_kt6PFJetsCentralHZGEle_rho_*',
        '*_kt6PFJetsCentralHZGMu_rho_*',
        '*_kt6PFJetsCentralNeutralHZGMu_rho_*',
        '*_kt6PFJetsCentral_rho_*',
        '*_kt6PFJetsCentralNeutral_rho_*', #for zz muons
        '*_photonCore_*_*',
        # for Zmumu -> embedded samples
        '*_generator_weight_*', # 2k11
        "GenFilterInfo_generator_minVisPtFilter_*", #2k12
        '*_genDaughters_*_*',
        '*_boosted*_*_*',
        '*_tmfTracks_*_*',
    ]
    # Define our patTuple production sequence
    process.tuplize = cms.Sequence()
    # Only keep interesting genParticles
    process.load("FinalStateAnalysis.RecoTools.genParticleTrimmer_cfi")
    process.genParticles = process.prunedGenParticles.clone()
    if isMC:
        #process.tuplize += process.genParticles
        #output_commands.append('*_genParticles_*_%s' % process.name_())
        output_commands.append('*_genParticles_*_*')

    output_commands.append('*_tauGenJetsSelectorAllHadrons_*_*')
    output_commands.append('*_tauGenJets_*_*')
    output_commands.append('*_ak5GenJets_*_*')
    # Select vertices
    process.load("FinalStateAnalysis.RecoTools.vertexSelection_cff")
    output_commands.append('*_selectedPrimaryVertex_*_*')
    output_commands.append('*_selectPrimaryVerticesQuality_*_*')
    process.tuplize += process.selectPrimaryVertices

    # Run the ZZ recipe for rho
    from RecoJets.JetProducers.kt4PFJets_cfi import kt4PFJets \
            as zzCantDoAnythingRight

    process.kt6PFJetsForIso = zzCantDoAnythingRight.clone(
        rParam = cms.double(0.6),
        doAreaFastjet = cms.bool(True),
        doRhoFastjet = cms.bool(True),
        Rho_EtaMax = cms.double(2.5),
        Ghost_EtaMax = cms.double(2.5),
    )
    process.tuplize += process.kt6PFJetsForIso

    # Standard services
    process.load('Configuration.StandardSequences.Services_cff')
    # tack on seeds for FSA PATTuple modules
    add_fsa_random_seeds(process)
    
    
    if cmssw_major_version() == 5 and cmssw_minor_version() >= 3: 
        process.load('Configuration.Geometry.GeometryIdeal_cff')
    else:
        process.load('Configuration.StandardSequences.GeometryIdeal_cff')
        
    process.load('Configuration.StandardSequences.MagneticField_cff')
    process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')

    # Rerun tau ID
    if cmssw_major_version() == 4:
        process.load("RecoTauTag.Configuration.RecoPFTauTag_cff")
        # Optimization - remove PFTauTagInfo compatibility layer
        process.recoTauClassicHPSSequence.remove(process.pfRecoTauTagInfoProducer)
        process.recoTauClassicHPSSequence.remove(process.ak5PFJetTracksAssociatorAtVertex)
        assert(process.combinatoricRecoTaus.modifiers[3].name.value() == 'TTIworkaround')
        del process.combinatoricRecoTaus.modifiers[3]
        # Don't build junky taus below 19 GeV
        process.combinatoricRecoTaus.builders[0].minPtToBuild = cms.double(17)
        process.tuplize += process.recoTauClassicHPSSequence
    else:
        # We can run less tau stuff in 52, since HPS taus already built.
        process.load("RecoTauTag.Configuration.updateHPSPFTaus_cff")
        process.tuplize += process.updateHPSPFTaus

    ## Run rho computation.  Only necessary in 42X
    if cmssw_major_version() == 4:
        from RecoJets.Configuration.RecoPFJets_cff import kt6PFJets
        kt6PFJets.Rho_EtaMax = cms.double(4.4)
        kt6PFJets.doRhoFastjet = True
        process.kt6PFJets = kt6PFJets
        process.tuplize += process.kt6PFJets

    # In 4_X we have to rerun ak5PFJets with area computation enabled.
    if cmssw_major_version() == 4:
        process.load("RecoJets.Configuration.RecoPFJets_cff")
        process.ak5PFJets.doAreaFastjet = True
        process.tuplize += process.ak5PFJets
        # Only keep the new ak5PFJets
        output_commands.append('*_ak5PFJets_*_%s' % process.name_())
    else:
        # Just keep the normal ones
        output_commands.append('*_ak5PFJets_*_*')

    # In the embedded samples, we need to re-run the b-tagging
    if kwargs['embedded']:
       process.load('RecoBTag/Configuration/RecoBTag_cff')
       process.load('RecoJets/JetAssociationProducers/ak5JTA_cff')
       process.ak5JetTracksAssociatorAtVertex.jets   = cms.InputTag("ak5PFJets")
       process.ak5JetTracksAssociatorAtVertex.tracks = cms.InputTag("tmfTracks")
       process.tuplize += process.ak5JetTracksAssociatorAtVertex
       process.tuplize += process.btagging

    # Run pat default sequence
    process.load("PhysicsTools.PatAlgos.patSequences_cff")
    # Embed PF Isolation in electrons & muons
    pfTools.usePFIso(process)
    # Setup H2Tau custom iso definitions
    setup_h2tau_iso(process)
    # Setup hZg custom iso definitions
    add_hZg_iso_needs(process)
    
    # Use POG recommendations for (these) electron Isos
    process.elPFIsoValueGamma04PFIdPFIso.deposits[0].vetos = cms.vstring('EcalEndcaps:ConeVeto(0.08)')
    process.elPFIsoValueGamma04NoPFIdPFIso.deposits[0].vetos = cms.vstring('EcalEndcaps:ConeVeto(0.08)')
    process.elPFIsoValueCharged04PFIdPFIso.deposits[0].vetos = cms.vstring('EcalEndcaps:ConeVeto(0.015)')
    process.elPFIsoValueCharged04NoPFIdPFIso.deposits[0].vetos = cms.vstring('EcalEndcaps:ConeVeto(0.015)')

    # Unembed junk
    process.patMuons.embedCaloMETMuonCorrs = False
    process.patMuons.embedTcMETMuonCorrs = False
    process.patMuons.embedTrack = True
    process.patMuons.pvSrc = cms.InputTag("selectedPrimaryVertex")

    # Do extra electron ID
    process.load("FinalStateAnalysis.PatTools.electrons.electronID_cff")
    process.tuplize += process.recoElectronID
    process.patElectrons.electronIDSources = process.electronIDSources
    process.patElectrons.embedTrack = True

    # Now run PAT
    process.tuplize += process.patDefaultSequence

    # Add FSR photons for ZZ analysis
    process.load("FinalStateAnalysis.PatTools.fsrPhotons_cff")
    process.tuplize += process.fsrPhotonSequence

    # Use HPS taus
    tautools.switchToPFTauHPS(process)
    # Disable tau IsoDeposits
    process.patDefaultSequence.remove(process.patPFTauIsolation)
    process.patTaus.isoDeposits = cms.PSet()
    process.patTaus.userIsolation = cms.PSet()

    # Disable gen match embedding - we keep it in the ntuple
    process.patMuons.embedGenMatch = False
    process.patElectrons.embedGenMatch = False
    process.patTaus.embedGenMatch = False
    process.patTaus.embedGenJetMatch = False

    # Use PFJets and turn on JEC
    jec = [ 'L1FastJet', 'L2Relative', 'L3Absolute' ]
    # If we are running on data (not MC), or embedded sample,
    # apply the MC-DATA residual correction.
    if not isMC or kwargs['embedded']:
        jec.extend([ 'L2L3Residual' ])

    # Define options for BTagging - these are release dependent.
    btag_options = {'doBTagging' : True}
    if cmssw_major_version() == 5:
        btag_options['btagInfo'] = [
            'impactParameterTagInfos',
            'secondaryVertexTagInfos',
            'softMuonTagInfos',
            'secondaryVertexNegativeTagInfos'
        ]
        btag_options['btagdiscriminators'] = [
            'trackCountingHighEffBJetTags',
            'simpleSecondaryVertexHighEffBJetTags',
            'combinedSecondaryVertexMVABJetTags',
            'combinedSecondaryVertexBJetTags',
        ]

    # Use AK5 PFJets
    jettools.switchJetCollection(
        process,
        cms.InputTag('ak5PFJets'),
        doJTA = False,
        jetCorrLabel = ('AK5PF', jec),
        #jetCorrLabel = None,
        doType1MET = False,
        doJetID = True,
        genJetCollection = cms.InputTag("ak5GenJets"),
        **btag_options
    )
    process.patJets.embedPFCandidates = False
    process.patJets.embedCaloTowers = False
    process.patJets.embedGenJetMatch = False
    process.patJets.addAssociatedTracks = False
    process.patJets.embedGenPartonMatch = False
    #process.patJetCorrFactors.useRho = True
    ## Let's use the same rho as in the TauID, so we don't need to do it twice.
    #process.patJetCorrFactors.rho = cms.InputTag(
        #"kt6PFJetsForRhoComputationVoronoi", "rho")

    # Use PFMEt
    mettools.addPfMET(process)
    if not isMC:
        coreTools.runOnData(process)
        process.patMETsPF.addGenMET = False
    output_commands.append('*_selectedPatJets_*_*')

    # Customize/embed all our sequences
    process.load("FinalStateAnalysis.PatTools.patJetProduction_cff")
    # We have to keep all jets (for the MVA MET...)
    process.patJetGarbageRemoval.cut = 'pt > 0'

    final_jet_collection = chain_sequence(
        process.customizeJetSequence, "patJets")
    process.customizeJetSequence.insert(0, process.patJets)
    # Make it a "complete" sequence
    process.customizeJetSequence += process.selectedPatJets
    # We can't mess up the selected pat jets because the taus use them.
    process.selectedPatJets.src = final_jet_collection
    process.patDefaultSequence.replace(process.patJets,
                                       process.customizeJetSequence)

    # Produce the electron collections
    process.load("FinalStateAnalysis.PatTools.patElectronProduction_cff")
    final_electron_collection = chain_sequence(
        process.customizeElectronSequence, "selectedPatElectrons")
    process.tuplize += process.customizeElectronSequence
    process.customizeElectronSequence.insert(0, process.selectedPatElectrons)
    process.patDefaultSequence.replace(process.selectedPatElectrons,
                                       process.customizeElectronSequence)
    # We have to do the pat Jets before the pat electrons since we embed them
    process.customizeElectronSequence.insert(0, process.selectedPatJets)
    process.cleanPatElectrons.src = final_electron_collection
    #setup the energy regression for the specific dataset
    process.patElectronEnergyCorrections.isMC  = cms.bool(bool(isMC))
    process.patElectronEnergyCorrections.isAOD = \
                                               cms.bool(bool(kwargs['isAOD']))
    process.patElectronEnergyCorrections.dataSet = \
                                     cms.string(kwargs['calibrationTarget'])

    process.load("FinalStateAnalysis.PatTools.patMuonProduction_cff")
    final_muon_collection = chain_sequence(
        process.customizeMuonSequence, "selectedPatMuons")
    process.customizeMuonSequence.insert(0, process.selectedPatMuons)
    process.patDefaultSequence.replace(process.selectedPatMuons,
                                       process.customizeMuonSequence)
    process.cleanPatMuons.src = final_muon_collection
    process.patMuonRochesterCorrectionEmbedder.isMC = cms.bool(bool(isMC))
    

    process.load("FinalStateAnalysis.PatTools.patTauProduction_cff")
    final_tau_collection = chain_sequence(
        process.customizeTauSequence, "selectedPatTaus")
    # Inject into the pat sequence
    process.customizeTauSequence.insert(0, process.selectedPatTaus)
    process.patDefaultSequence.replace(process.selectedPatTaus,
                                       process.customizeTauSequence)
    process.cleanPatTaus.src = final_tau_collection
    # Remove muons and electrons
    process.cleanPatTaus.checkOverlaps.muons.requireNoOverlaps = False
    process.cleanPatTaus.checkOverlaps.electrons.requireNoOverlaps = False
    # Apply a loose preselection
    process.cleanPatTaus.preselection = 'abs(eta) < 2.5 & pt > 17'
    # Don't apply any "final" cut
    process.cleanPatTaus.finalCut = ''

    # Setup pat::Photon Production
    process.load("FinalStateAnalysis.PatTools.patPhotonProduction_cff")
    final_photon_collection = chain_sequence(process.customizePhotonSequence,
                                             "selectedPatPhotons")
    #inject photons into pat sequence
    process.customizePhotonSequence.insert(0,process.selectedPatPhotons)
    process.patDefaultSequence.replace(process.selectedPatPhotons,
                                       process.customizePhotonSequence)
    process.cleanPatPhotons.src = final_photon_collection

    # Setup MET production
    process.load("FinalStateAnalysis.PatTools.patMETProduction_cff")
    final_met_collection = chain_sequence(
        process.customizeMETSequence, "patMETsPF")
    process.tuplize += process.customizeMETSequence
    # The MET systematics depend on all other systematics
    process.systematicsMET.tauSrc = cms.InputTag("cleanPatTaus")
    process.systematicsMET.muonSrc = cms.InputTag("cleanPatMuons")
    process.systematicsMET.electronSrc = cms.InputTag("cleanPatElectrons")

    # Keep all the data formats needed for the systematics
    output_commands.append('recoLeafCandidates_*_*_%s'
                           % process.name_())

    # Define the default lepton cleaning
    process.cleanPatElectrons.preselection = cms.string('pt > 5')
    process.cleanPatElectrons.checkOverlaps.muons.requireNoOverlaps = False
    # Make sure we don't kill any good taus by calling them electrons
    # Note that we don't actually remove these overlaps.
    process.cleanPatElectrons.checkOverlaps.taus = cms.PSet(
        src = final_tau_collection,
        algorithm = cms.string("byDeltaR"),
        preselection = cms.string(
            "tauID('decayModeFinding') > 0.5 &&"
            "tauID('byLooseCombinedIsolationDeltaBetaCorr') > 0.5 &&"
            "tauID('againstElectronLoose') > 0.5 && "
            "pt > 10"
        ),
        deltaR = cms.double(0.1),
        checkRecoComponents = cms.bool(False),
        pairCut = cms.string(""),
        requireNoOverlaps = cms.bool(False),
    )

    output_commands.append('*_cleanPatTaus_*_*')
    output_commands.append('*_cleanPatElectrons_*_*')
    output_commands.append('*_cleanPatMuons_*_*')
    output_commands.append('*_cleanPatPhotons_*_*')
    output_commands.append('*_%s_*_*' % final_met_collection.value())

    trigtools.switchOnTrigger(process)

    # Now build the PATFinalStateLS object, which holds LumiSection info.
    process.load(
        "FinalStateAnalysis.PatTools.finalStates.patFinalStateLSProducer_cfi")
    process.tuplize += process.finalStateLS
    output_commands.append('*_finalStateLS_*_*')
    if isMC:
        process.finalStateLS.xSec = kwargs['xSec']

    # Tell the framework to shut up!
    process.load("FWCore.MessageLogger.MessageLogger_cfi")
    process.MessageLogger.cerr.FwkReport.reportEvery = 1000

    # Which collections are used to build the final states
    fs_daughter_inputs = {
        'electrons' : 'cleanPatElectrons',
        'muons' : 'cleanPatMuons',
        'taus' : 'cleanPatTaus',
        'photons' : 'cleanPatPhotons',
        'jets' : 'selectedPatJets',        
        'met' : final_met_collection,
    }

    # Setup all the PATFinalState objects
    produce_final_states(process, fs_daughter_inputs, output_commands,
                         process.tuplize, kwargs['puTag'])

    return process.tuplize, output_commands
Esempio n. 16
0
process.goodDataAll = cms.Path(process.hltPhysicsDeclared * process.primaryVertexFilter * process.noscraping)

# Add MET and jets. Configuration to be revisited later.
from PhysicsTools.PatAlgos.tools.metTools import addPfMET, addTcMET

addPfMET(process)
addTcMET(process)

from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection

switchJetCollection(
    process,
    cms.InputTag("ak5PFJets"),
    doJTA=True,
    doBTagging=True,
    jetCorrLabel=("AK5PF", ["L1FastJet", "L2Relative", "L3Absolute"]),
    doType1MET=False,
    genJetCollection=cms.InputTag("ak5GenJets"),
    doJetID=False,
    jetIdLabel="ak5",
)

# Make a collection of muons with our final selection applied so that
# the muon-jet cleaning will use only muons passing those cuts. This
# muon collection is not saved in the output.
from SUSYBSMAnalysis.Zprime2muAnalysis.OurSelectionDec2012_cff import loose_cut

process.muonsForJetCleaning = process.selectedPatMuons.clone(cut=loose_cut.replace("pt > 45", "pt > 30"))
process.patDefaultSequence.replace(process.selectedPatMuons, process.selectedPatMuons * process.muonsForJetCleaning)
process.cleanPatJets.checkOverlaps.muons.src = "muonsForJetCleaning"
process.cleanPatJets.checkOverlaps.muons.deltaR = 0.2
Esempio n. 17
0
    pvSource = 'offlinePrimaryVertices'
    svSource = cms.InputTag('inclusiveSecondaryVertices')
else:
    jetSource = 'ak4PFJetsCHS'
    trackSource = 'unpackedTracksAndVertices'
    pvSource = 'unpackedTracksAndVertices'
    svSource = cms.InputTag('unpackedTracksAndVertices', 'secondary')

from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection

## Switch the default jet collection (done in order to use the above specified b-tag infos and discriminators)
switchJetCollection(process,
                    jetSource=cms.InputTag(jetSource),
                    trackSource=cms.InputTag(trackSource),
                    pvSource=cms.InputTag(pvSource),
                    svSource=svSource,
                    btagInfos=bTagInfos,
                    btagDiscriminators=bTagDiscriminators,
                    jetCorrections=jetCorr,
                    genJetCollection=cms.InputTag(genJetCollection),
                    postfix=pfpostfix)

getattr(process, 'patJetPartons' +
        pfpostfix).particles = cms.InputTag(genParticleCollection)
getattr(process, 'patJetPartonMatch' +
        pfpostfix).matched = cms.InputTag(genParticleCollection)
getattr(process, 'patJetCorrFactors' +
        pfpostfix).primaryVertices = cms.InputTag(pvSource)

## agrohsje following lines needed ?
process.inclusiveVertexFinder.tracks = cms.InputTag(trackSource)
process.trackVertexArbitrator.tracks = cms.InputTag(trackSource)
Esempio n. 18
0
def setup_jets(process, cms, options, postfix="PFlow"):
    print "=" * 60
    print "Setting up Jets"
    print "=" * 60
    # MC setup
    inputJetCorrLabel = ("AK5PFchs", ["L1FastJet", "L2Relative", "L3Absolute"])
    caloJetCorrection = ("AK5Calo", ["L1Offset", "L2Relative", "L3Absolute"])

    if options.useData:  # data set up
        inputJetCorrLabel = ("AK5PFchs", ["L1FastJet", "L2Relative", "L3Absolute", "L2L3Residual"])
        caloJetCorrection = ("AK5Calo", ["L1Offset", "L2Relative", "L3Absolute", "L2L3Residual"])

    print "Using jet energy corrections: "
    print "Calo Jets"
    print caloJetCorrection
    print "PF Jets"
    print inputJetCorrLabel

    if options.CMSSW == "44X":
        process.patJetCorrFactorsPFlow.payload = inputJetCorrLabel[0]
        process.patJetCorrFactorsPFlow.levels = inputJetCorrLabel[1]
        process.patJetCorrFactorsPFlow.rho = cms.InputTag("kt6PFJets", "rho")

    ###############################
    #### Jet RECO includes ########
    ###############################

    from RecoJets.JetProducers.SubJetParameters_cfi import SubJetParameters

    ###############################
    #### Calo Jet Setup    ########
    ###############################
    # this has to run after PF2PAT and before removeMCMatching
    # see https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookPAT38xChanges#Details_with_PF2PAT
    from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection, addJetCollection

    #    print 'adding calo jets'
    switchJetCollection(
        process,
        jetCollection=cms.InputTag("ak5CaloJets"),
        jetCorrLabel=caloJetCorrection,
        doBTagging=True,
        doType1MET=False,
    )

    ###############################
    ###### Bare KT 0.6 jets #######
    ###############################

    from RecoJets.JetProducers.kt4PFJets_cfi import kt4PFJets

    process.kt6PFJets = kt4PFJets.clone(
        rParam=cms.double(0.6), doAreaFastjet=cms.bool(True), doRhoFastjet=cms.bool(True)
    )
    process.kt6PFJetsPFlow = kt4PFJets.clone(
        rParam=cms.double(0.6),
        src=cms.InputTag("pfNoElectron" + postfix),
        doAreaFastjet=cms.bool(True),
        doRhoFastjet=cms.bool(True),
    )
    process.kt4PFJetsPFlow = kt4PFJets.clone(
        rParam=cms.double(0.4),
        src=cms.InputTag("pfNoElectron" + postfix),
        doAreaFastjet=cms.bool(True),
        doRhoFastjet=cms.bool(True),
    )

    ###############################
    ### TagInfo and Matching Setup#
    ###############################

    # Do some configuration of the jet substructure things
    for jetcoll in [process.patJetsPFlow]:
        if options.useData == False:
            jetcoll.embedGenJetMatch = True
            jetcoll.getJetMCFlavour = True
            jetcoll.addGenPartonMatch = True
        # Add CATopTag info... piggy-backing on b-tag functionality
        jetcoll.addBTagInfo = True
        jetcoll.embedCaloTowers = True
        jetcoll.embedPFCandidates = True

    additionalJets = [
        getattr(process, "kt6PFJets"),
        getattr(process, "kt6PFJets" + postfix),
        getattr(process, "kt4PFJets" + postfix),
    ]
    pfNoElectron = getattr(process, "pfNoElectron" + postfix)
    for module in additionalJets:
        getattr(process, "patPF2PATSequence" + postfix).replace(pfNoElectron, pfNoElectron * module)
Esempio n. 19
0
# comment-out to take new HPS + TaNC combined tau id. algorithm
#tauTools.switchToPFTauHPSpTaNC(process)

# disable preselection on of pat::Taus
# (disabled also in TauAnalysis/RecoTools/python/patPFTauConfig_cfi.py ,
#  but re-enabled after switching tau collection)
process.cleanPatTaus.preselection = cms.string('')
#--------------------------------------------------------------------------------

#--------------------------------------------------------------------------------
# import utility function for managing pat::Jets
import PhysicsTools.PatAlgos.tools.jetTools as jetTools

# uncomment to replace caloJets by pfJets
jetTools.switchJetCollection(process, jetCollection = cms.InputTag("ak5PFJets"),
             		     doBTagging = True, outputModule = '')
#--------------------------------------------------------------------------------

#--------------------------------------------------------------------------------
# import utility function for managing pat::METs
import TauAnalysis.Configuration.tools.metTools as metTools

# uncomment to add pfMET
# set Boolean swich to true in order to apply type-1 corrections
metTools.addPFMet(process, correct = False)

# uncomment to replace caloMET by pfMET in all di-tau objects
process.load("TauAnalysis.CandidateTools.diTauPairProductionAllKinds_cff")
metTools.replaceMETforDiTaus(process, cms.InputTag('patMETs'), cms.InputTag('patPFMETs'))
#--------------------------------------------------------------------------------
def configurePatTuple(process, isMC=True, **kwargs):
    # Stuff we always keep
    output_commands = [
        '*_addPileupInfo_*_*',
        'edmMergeableCounter_*_*_*',
        '*_lumiProducer_*_*',
        '*_particleFlow_*_*',
        '*_offlineBeamSpot_*_*',
        '*_generalTracks_*_*',
        '*_electronGsfTracks_*_*',
        '*_gsfElectrons_*_*',
        '*_gsfElectronCores_*_*',
        '*_offlinePrimaryVertices*_*_*',
        '*_ak5GenJets_*_*',
        '*_hltTriggerSummaryAOD_*_*',
        'edmTriggerResults_TriggerResults_*_%s' % process.name_(),
        '*_MEtoEDMConverter*_*_%s' % process.name_(),
        'LHEEventProduct_*_*_*',
        'GenEventInfoProduct_generator_*_*',
        '*_kt6PFJetsForRhoComputationVoronoi_rho_*',
        '*_kt6PFJetsForIso_rho_*',
        '*_kt6PFJets_rho_*',
        '*_kt6PFJetsHZGPho_rho_*',
        '*_kt6PFJetsCentralHZGEle_rho_*',
        '*_kt6PFJetsCentralHZGMu_rho_*',
        '*_kt6PFJetsCentralNeutralHZGMu_rho_*',
        '*_kt6PFJetsCentral_rho_*',
        '*_kt6PFJetsCentralNeutral_rho_*',  # for zz muons
        '*_photonCore_*_*',
        '*_boostedFsrPhotons_*_*',
        # for Zmumu -> embedded samples
        # https://twiki.cern.ch/twiki/bin/view/CMS/MuonTauReplacementRecHit
        '*_generalTracksORG_*_EmbeddedRECO',
        '*_electronGsfTracksORG_*_EmbeddedRECO',
        'double_TauSpinnerReco_TauSpinnerWT_EmbeddedSPIN',
        'double_ZmumuEvtSelEffCorrWeightProducer_weight_EmbeddedRECO',
        'double_muonRadiationCorrWeightProducer_weight_EmbeddedRECO',
        'GenFilterInfo_generator_minVisPtFilter_EmbeddedRECO',
    ]
    # Define our patTuple production sequence
    process.tuplize = cms.Sequence()
    # Only keep interesting genParticles
    process.load("FinalStateAnalysis.RecoTools.genParticleTrimmer_cfi")
    process.genParticles = process.prunedGenParticles.clone()
    if isMC:
        #process.tuplize += process.genParticles
        #output_commands.append('*_genParticles_*_%s' % process.name_())
        output_commands.append('*_genParticles_*_*')

    output_commands.append('*_tauGenJetsSelectorAllHadrons_*_*')
    output_commands.append('*_tauGenJets_*_*')
    output_commands.append('*_ak5GenJets_*_*')
    # Select vertices
    process.load("FinalStateAnalysis.RecoTools.vertexSelection_cff")
    output_commands.append('*_selectedPrimaryVertex*_*_*')
    output_commands.append('*_selectPrimaryVerticesQuality*_*_*')
    process.tuplize += process.selectPrimaryVertices

    # Run the ZZ recipe for rho
    from RecoJets.JetProducers.kt4PFJets_cfi import kt4PFJets \
        as zzCantDoAnythingRight

    process.kt6PFJetsForIso = zzCantDoAnythingRight.clone(
        rParam=cms.double(0.6),
        doAreaFastjet=cms.bool(True),
        doRhoFastjet=cms.bool(True),
        Rho_EtaMax=cms.double(2.5),
        Ghost_EtaMax=cms.double(2.5),
    )
    process.tuplize += process.kt6PFJetsForIso

    # Standard services
    process.load('Configuration.StandardSequences.Services_cff')
    # tack on seeds for FSA PATTuple modules
    add_fsa_random_seeds(process)

    if cmssw_major_version() == 5 and cmssw_minor_version() >= 3:
        process.load('Configuration.Geometry.GeometryDB_cff')
    else:
        process.load('Configuration.StandardSequences.GeometryDB_cff')

    process.load('Configuration.StandardSequences.MagneticField_cff')
    process.load(
        'Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')

    # Rerun tau ID
    process.load("RecoTauTag.Configuration.RecoPFTauTag_cff")
    # Optimization - remove PFTauTagInfo compatibility layer
    process.recoTauClassicHPSSequence.remove(
        process.pfRecoTauTagInfoProducer)
    process.recoTauClassicHPSSequence.remove(
        process.ak5PFJetTracksAssociatorAtVertex)
    assert(process.combinatoricRecoTaus.modifiers[3].name.value() ==
           'TTIworkaround')
    del process.combinatoricRecoTaus.modifiers[3]
    # Don't build junky taus below 19 GeV
    process.combinatoricRecoTaus.builders[0].minPtToBuild = cms.double(17)
    process.tuplize += process.recoTauClassicHPSSequence

    ## Run rho computation.  Only necessary in 42X
    if cmssw_major_version() == 4:
        # This function call can klobber everything if it isn't done
        # before the other things are attached to the process, so do it now.
        # The klobbering would occur through usePFIso->setupPFIso->_loadPFBRECO
        from CommonTools.ParticleFlow.Tools.pfIsolation import _loadPFBRECO
        _loadPFBRECO(process)
        process.load("RecoJets.Configuration.RecoPFJets_cff")
        process.kt6PFJets.Rho_EtaMax = cms.double(4.4)
        process.kt6PFJets.doRhoFastjet = True
        process.tuplize += process.kt6PFJets

    # In 4_X we have to rerun ak5PFJets with area computation enabled.
    if cmssw_major_version() == 4:
        process.load("RecoJets.Configuration.RecoPFJets_cff")
        process.ak5PFJets.doAreaFastjet = True
        process.tuplize += process.ak5PFJets
        # Only keep the new ak5PFJets
        output_commands.append('*_ak5PFJets_*_%s' % process.name_())
    else:
        # Just keep the normal ones
        output_commands.append('*_ak5PFJets_*_*')

    # Run pat default sequence
    process.load("PhysicsTools.PatAlgos.patSequences_cff")
    # Embed PF Isolation in electrons & muons
    pfTools.usePFIso(process)
    # Setup H2Tau custom iso definitions
    setup_h2tau_iso(process)
    # Setup hZg custom iso definitions
    add_hZg_iso_needs(process)

    #alter the photon matching to accept various fakes
    # and sort matches by d-pt-rel
    if isMC:
        process.photonMatch = cms.EDProducer(
            "MCMatcherByPt",
            src=cms.InputTag("photons"),
            maxDPtRel=cms.double(100.0),
            mcPdgId=cms.vint32(),
            mcStatus=cms.vint32(1),
            resolveByMatchQuality=cms.bool(False),
            maxDeltaR=cms.double(0.3),
            checkCharge=cms.bool(False),
            resolveAmbiguities=cms.bool(True),
            matched=cms.InputTag("genParticles")
        )

    # Use POG recommendations for (these) electron Isos
    process.elPFIsoValueGamma04PFIdPFIso.deposits[0].vetos = cms.vstring(
        'EcalEndcaps:ConeVeto(0.08)')
    process.elPFIsoValueGamma04NoPFIdPFIso.deposits[0].vetos = cms.vstring(
        'EcalEndcaps:ConeVeto(0.08)')
    process.elPFIsoValueCharged04PFIdPFIso.deposits[0].vetos = cms.vstring(
        'EcalEndcaps:ConeVeto(0.015)')
    process.elPFIsoValueCharged04NoPFIdPFIso.deposits[0].vetos = cms.vstring(
        'EcalEndcaps:ConeVeto(0.015)')

    # Unembed junk
    process.patMuons.embedCaloMETMuonCorrs = False
    process.patMuons.embedTcMETMuonCorrs = False
    process.patMuons.embedTrack = True
    process.patMuons.pvSrc = cms.InputTag("selectedPrimaryVertex")

    # Do extra electron ID
    process.load("FinalStateAnalysis.PatTools.electrons.electronID_cff")
    if cmssw_major_version() == 4:
        process.patDefaultSequence.replace(process.patElectrons,
                                           process.recoElectronID42X +
                                           process.patElectrons)
        process.patElectrons.electronIDSources = process.electronIDSources42X
    else:
        process.patDefaultSequence.replace(process.patElectrons,
                                           process.recoElectronID5YX +
                                           process.patElectrons)
        process.patElectrons.electronIDSources = process.electronIDSources5YX

    process.electronMatch.checkCharge = cms.bool(False)
    process.patElectrons.embedTrack = False
    process.patElectrons.embedPFCandidate = False
    process.patElectrons.embedGsfElectronCore = False
    process.patElectrons.embedSuperCluster = True

    # Now run PAT
    process.tuplize += process.patDefaultSequence

    # Add FSR photons for ZZ analysis
    process.load("FinalStateAnalysis.PatTools.fsrPhotons_cff")
    process.tuplize += process.fsrPhotonSequence

    # Use HPS taus
    tautools.switchToPFTauHPS(process)
    # Disable tau IsoDeposits
    process.patDefaultSequence.remove(process.patPFTauIsolation)
    process.patTaus.isoDeposits = cms.PSet()
    process.patTaus.userIsolation = cms.PSet()

    # Disable gen match embedding - we keep it in the ntuple
    process.patMuons.embedGenMatch = False
    process.patElectrons.embedGenMatch = False
    process.patTaus.embedGenMatch = False
    process.patTaus.embedGenJetMatch = False
    process.patPhotons.embedGenMatch = False

    # Use PFJets and turn on JEC
    jec = ['L1FastJet', 'L2Relative', 'L3Absolute']
    # If we are running on data (not MC), or embedded sample,
    # apply the MC-DATA residual correction.
    if not isMC or kwargs['embedded']:
        jec.extend(['L2L3Residual'])

    # Define options for BTagging - these are release dependent.
    btag_options = {'doBTagging': True}
    if cmssw_major_version() == 5:
        btag_options['btagInfo'] = [
            'impactParameterTagInfos',
            'secondaryVertexTagInfos',
            'softMuonTagInfos',
            'secondaryVertexNegativeTagInfos'
        ]
        btag_options['btagdiscriminators'] = [
            'trackCountingHighEffBJetTags',
            'simpleSecondaryVertexHighEffBJetTags',
            'combinedSecondaryVertexMVABJetTags',
            'combinedSecondaryVertexBJetTags',
        ]

    # Use AK5 PFJets
    jettools.switchJetCollection(
        process,
        cms.InputTag('ak5PFJets'),
        doJTA=False,
        jetCorrLabel=('AK5PF', jec),
        #jetCorrLabel = None,
        doType1MET=False,
        doJetID=True,
        genJetCollection=cms.InputTag("ak5GenJets"),
        **btag_options
    )
    process.patJets.embedPFCandidates = False
    process.patJets.embedCaloTowers = False
    process.patJets.embedGenJetMatch = False
    process.patJets.addAssociatedTracks = False
    process.patJets.embedGenPartonMatch = False
    #process.patJetCorrFactors.useRho = True
    ## Let's use the same rho as in the TauID, so we don't need to do it twice.
    #process.patJetCorrFactors.rho = cms.InputTag(
        #"kt6PFJetsForRhoComputationVoronoi", "rho")

    # Use PFMEt
    mettools.addPfMET(process)
    if not isMC:
        coreTools.runOnData(process)
        process.patMETsPF.addGenMET = False
    output_commands.append('*_selectedPatJets_*_*')

    # Customize/embed all our sequences
    process.load("FinalStateAnalysis.PatTools.patJetProduction_cff")
    process.patJetGarbageRemoval.cut = 'pt > 12'

    final_jet_collection = chain_sequence(
        process.customizeJetSequence, "patJets")
    process.customizeJetSequence.insert(0, process.patJets)
    # Make it a "complete" sequence
    process.customizeJetSequence += process.selectedPatJets
    # We can't mess up the selected pat jets because the taus use them.
    process.selectedPatJets.src = final_jet_collection
    process.patDefaultSequence.replace(process.patJets,
                                       process.customizeJetSequence)

    # Produce the electron collections
    process.load("FinalStateAnalysis.PatTools.patElectronProduction_cff")

    # Electron Energy Regression and Calibrations
    process.load(
        "EgammaAnalysis.ElectronTools.electronRegressionEnergyProducer_cfi")
    process.load("EgammaAnalysis.ElectronTools.calibratedPatElectrons_cfi")

    #setup the energy regression for the specific dataset
    if kwargs['eleReg']:
        print "-- Applying Electron Regression and Calibration --"

        process.customizeElectronSequence += process.eleRegressionEnergy
        process.customizeElectronSequence += process.calibratedPatElectrons

        process.eleRegressionEnergy.energyRegressionType = cms.uint32(2)
        process.calibratedPatElectrons.correctionsType = cms.int32(2)

        if isMC:
            process.calibratedPatElectrons.inputDataset = cms.string(
                "Summer12_LegacyPaper")
        else:
            process.calibratedPatElectrons.inputDataset = cms.string(
                "22Jan2013ReReco")

        process.calibratedPatElectrons.combinationType = cms.int32(3)
        process.calibratedPatElectrons.lumiRatio = cms.double(1.0)
        process.calibratedPatElectrons.synchronization = cms.bool(True)
        process.calibratedPatElectrons.isMC = cms.bool(isMC == 1)
        process.calibratedPatElectrons.verbose = cms.bool(False)

    final_electron_collection = chain_sequence(
        process.customizeElectronSequence, "selectedPatElectrons",
        # Some of the EGamma modules have non-standard src InputTags,
        # specify them here.
        ("src", "inputPatElectronsTag", "inputElectronsTag")
    )

    process.tuplize += process.customizeElectronSequence
    process.customizeElectronSequence.insert(0, process.selectedPatElectrons)
    process.patDefaultSequence.replace(process.selectedPatElectrons,
                                       process.customizeElectronSequence)
    # We have to do the pat Jets before the pat electrons since we embed them
    process.customizeElectronSequence.insert(0, process.selectedPatJets)

    # Define cleanPatElectrons input collection
    process.cleanPatElectrons.src = final_electron_collection

    process.load("FinalStateAnalysis.PatTools.patMuonProduction_cff")
    final_muon_collection = chain_sequence(
        process.customizeMuonSequence, "selectedPatMuons")
    process.customizeMuonSequence.insert(0, process.selectedPatMuons)
    process.patDefaultSequence.replace(process.selectedPatMuons,
                                       process.customizeMuonSequence)
    process.cleanPatMuons.src = final_muon_collection
    process.patMuonRochesterCorrectionEmbedder.isMC = cms.bool(bool(isMC))

    process.load("FinalStateAnalysis.PatTools.patTauProduction_cff")
    # Require all taus to pass decay mode finding and have high PT
    process.patTauGarbageRemoval.cut = cms.string(
        "pt > 17 && abs(eta) < 2.5 && tauID('decayModeFinding')")
    final_tau_collection = chain_sequence(
        process.customizeTauSequence, "selectedPatTaus")
    # Inject into the pat sequence
    process.customizeTauSequence.insert(0, process.selectedPatTaus)
    process.patDefaultSequence.replace(process.selectedPatTaus,
                                       process.customizeTauSequence)
    process.cleanPatTaus.src = final_tau_collection
    # Remove muons and electrons
    process.cleanPatTaus.checkOverlaps.muons.requireNoOverlaps = False
    process.cleanPatTaus.checkOverlaps.electrons.requireNoOverlaps = False
    # Cuts already applied by the garbage removal
    process.cleanPatTaus.preselection = ''
    process.cleanPatTaus.finalCut = ''

    # Setup pat::Photon Production
    process.load("FinalStateAnalysis.PatTools.patPhotonProduction_cff")
    final_photon_collection = chain_sequence(process.customizePhotonSequence,
                                             "selectedPatPhotons")
    #setup PHOSPHOR for a specific dataset
    if cmssw_major_version() == 4:  # for now 2011 = CMSSW42X
        process.patPhotonPHOSPHOREmbedder.year = cms.uint32(2011)
    else:  # 2012 is 5YX
        process.patPhotonPHOSPHOREmbedder.year = cms.uint32(2012)
    process.patPhotonPHOSPHOREmbedder.isMC = cms.bool(bool(isMC))
    #inject photons into pat sequence
    process.customizePhotonSequence.insert(0, process.selectedPatPhotons)
    process.patDefaultSequence.replace(process.selectedPatPhotons,
                                       process.customizePhotonSequence)
    process.cleanPatPhotons.src = final_photon_collection

    # We cut out a lot of the junky taus and jets - but we need these
    # to correctly apply the MET uncertainties.  So, let's make a
    # non-cleaned version of the jet and tau sequence.
    process.jetsForMetSyst = helpers.cloneProcessingSnippet(
        process, process.customizeJetSequence, 'ForMETSyst')
    process.tausForMetSyst = helpers.cloneProcessingSnippet(
        process, process.customizeTauSequence, 'ForMETSyst')
    # Don't apply any cut for these
    process.patTauGarbageRemovalForMETSyst.cut = ''
    process.patJetGarbageRemovalForMETSyst.cut = ''
    process.tuplize += process.jetsForMetSyst
    process.tuplize += process.tausForMetSyst
    # We have to make our clone of cleanPatTaus separately, since e/mu
    # cleaning is applied - therefore it isn't in the customizeTausSequence.
    process.cleanPatTausForMETSyst = process.cleanPatTaus.clone(
        src=cms.InputTag(process.cleanPatTaus.src.value() + "ForMETSyst"))
    process.cleanPatTausForMETSyst.preselection = ''
    process.cleanPatTausForMETSyst.finalCut = ''
    process.patTausEmbedJetInfoForMETSyst.jetSrc = \
        final_jet_collection.value() + "ForMETSyst"
    process.tuplize += process.cleanPatTausForMETSyst

    # Setup MET production
    process.load("FinalStateAnalysis.PatTools.patMETProduction_cff")
    # The MET systematics depend on all other systematics
    process.systematicsMET.tauSrc = cms.InputTag("cleanPatTausForMETSyst")
    process.systematicsMET.muonSrc = cms.InputTag("cleanPatMuons")
    process.systematicsMET.electronSrc = cms.InputTag("cleanPatElectrons")

    final_met_collection = chain_sequence(
        process.customizeMETSequence, "patMETsPF")
    process.tuplize += process.customizeMETSequence
    output_commands.append('*_%s_*_*' % final_met_collection.value())

    # Make a version with the MVA MET reconstruction method
    process.load("FinalStateAnalysis.PatTools.met.mvaMetOnPatTuple_cff")
    process.tuplize += process.pfMEtMVAsequence
    mva_met_sequence = helpers.cloneProcessingSnippet(
        process, process.customizeMETSequence, "MVA")
    final_mvamet_collection = chain_sequence(
        mva_met_sequence, "patMEtMVA")
    process.tuplize += mva_met_sequence
    output_commands.append('*_%s_*_*' % final_mvamet_collection.value())

    # Keep all the data formats needed for the systematics
    output_commands.append('recoLeafCandidates_*_*_%s'
                           % process.name_())
    # We can drop to jet and tau MET specific products. They were only used for
    # computation of the MET numbers.
    output_commands.append('drop recoLeafCandidates_*ForMETSyst_*_%s'
                           % process.name_())

    # Define the default lepton cleaning
    process.cleanPatElectrons.preselection = cms.string(
        'pt > 5')
    process.cleanPatElectrons.checkOverlaps.muons.requireNoOverlaps = False
    # Make sure we don't kill any good taus by calling them electrons
    # Note that we don't actually remove these overlaps.
    process.cleanPatElectrons.checkOverlaps.taus = cms.PSet(
        src=final_tau_collection,
        algorithm=cms.string("byDeltaR"),
        preselection=cms.string(
            "tauID('decayModeFinding') > 0.5 &&"
            "tauID('byLooseCombinedIsolationDeltaBetaCorr') > 0.5 &&"
            "tauID('againstElectronLoose') > 0.5 && "
            "pt > 10"
        ),
        deltaR=cms.double(0.1),
        checkRecoComponents=cms.bool(False),
        pairCut=cms.string(""),
        requireNoOverlaps=cms.bool(False),
    )

    output_commands.append('*_cleanPatTaus_*_*')
    output_commands.append('*_cleanPatElectrons_*_*')
    output_commands.append('*_cleanPatMuons_*_*')
    output_commands.append('*_cleanPatPhotons_*_*')

    trigtools.switchOnTrigger(process)

    #configure the PAT trigger
    if kwargs['HLTprocess']:
        process.patTrigger.processName = cms.string(kwargs['HLTprocess'])
        process.patTriggerEvent.processName = cms.string(kwargs['HLTprocess'])

    # Now build the PATFinalStateLS object, which holds LumiSection info.
    process.load(
        "FinalStateAnalysis.PatTools.finalStates.patFinalStateLSProducer_cfi")
    process.tuplize += process.finalStateLS
    output_commands.append('*_finalStateLS_*_*')
    if isMC:
        process.finalStateLS.xSec = kwargs['xSec']

    # Tell the framework to shut up!
    process.load("FWCore.MessageLogger.MessageLogger_cfi")
    process.MessageLogger.cerr.FwkReport.reportEvery = 1000

    # Which collections are used to build the final states
    fs_daughter_inputs = {
        'electrons':  'cleanPatElectrons',
        'muons':  'cleanPatMuons',
        'taus':  'cleanPatTaus',
        'photons':  'cleanPatPhotons',
        'jets':  'selectedPatJets',
        'pfmet':  final_met_collection,
        'mvamet':  final_mvamet_collection,
    }

    # Setup all the PATFinalState objects
    produce_final_states(process, fs_daughter_inputs, output_commands,
                         process.tuplize, kwargs['puTag'],
                         zzMode=kwargs.get('zzMode', False))

    return process.tuplize, output_commands
Esempio n. 21
0
    'L1',
    doJTA=True,
    doBTagging=True,
    jetCorrLabel=('AK5PF',
                  cms.vstring(['L2Relative', 'L3Absolute', 'L2L3Residual'])),
    doL1Cleaning=True,
    doL1Counters=True,
    doType1MET=True,
    doJetID=True)

from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection
switchJetCollection(
    process,
    cms.InputTag('ak5PFJets'),
    doJTA=True,
    doBTagging=True,
    jetCorrLabel=('AK5PF',
                  cms.vstring(['L2Relative', 'L3Absolute', 'L2L3Residual'])),
    doType1MET=True,
    doJetID=True)

from PhysicsTools.PatAlgos.tools.trigTools import *
switchOnTrigger(process)

process.load("ElectroWeakAnalysis.WENu.simpleEleIdSequence_cff")

process.patElectrons.addElectronID = cms.bool(True)
process.patElectrons.electronIDSources = cms.PSet(
    simpleEleId95relIso=cms.InputTag("simpleEleId95relIso"),
    simpleEleId90relIso=cms.InputTag("simpleEleId90relIso"),
    simpleEleId85relIso=cms.InputTag("simpleEleId85relIso"),
Esempio n. 22
0
addJetCollection(
    process,
    labelName = 'AK8PFCHS',
    jetSource = cms.InputTag('ak8PFJetsCHS'),
    algo = 'ak8',
    rParam = 0.8,
    jetCorrections = ('AK7PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None')
    )

switchJetCollection(
    process,
    jetSource = cms.InputTag('ak4PFJets'),
    rParam = 0.4,
    jetCorrections = ('AK5PF', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'Type-1'),
    btagDiscriminators = ['jetBProbabilityBJetTags',
                          'jetProbabilityBJetTags',
                          'trackCountingHighPurBJetTags',
                          'trackCountingHighEffBJetTags',
                          'simpleSecondaryVertexHighEffBJetTags',
                          'simpleSecondaryVertexHighPurBJetTags',
                          'combinedSecondaryVertexBJetTags'
                          ],
    )

#process.patJetGenJetMatchCA8PFCHS.matched = cms.InputTag("ca8GenJetsNoNu")

patJetsAK4 = process.patJetsAK4PFCHS
patJetsCA8 = process.patJetsCA8PFCHS
patJetsAK8 = process.patJetsAK8PFCHS

process.out.outputCommands += ['keep *_ak4PFJetsCHS_*_*',
                               'keep *_patJetsAK4PFCHS_*_*',
   genJetCollection = cms.InputTag('ak4GenJets'),
   jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'), # FIXME: Use proper JECs, as soon as available
   btagDiscriminators = [
       'combinedSecondaryVertexBJetTags'
     ],
   )
process.out.outputCommands.append( 'drop *_selectedPatJets%s_caloTowers_*'%( labelCA8PFCHSPruned ) )

# uncomment the following lines to switch to ak4CaloJets in your PAT output
switchJetCollection(
   process,
   jetSource = cms.InputTag('ak5CaloJets'),
   jetCorrections = ('AK5Calo', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'Type-1'), # FIXME: Use proper JECs, as soon as available
   btagDiscriminators = [
       'jetBProbabilityBJetTags'
     , 'jetProbabilityBJetTags'
     , 'trackCountingHighPurBJetTags'
     , 'trackCountingHighEffBJetTags'
     , 'simpleSecondaryVertexHighEffBJetTags'
     , 'simpleSecondaryVertexHighPurBJetTags'
     , 'combinedSecondaryVertexBJetTags'
     ],
   )
## JetID works only with RECO input for the CaloTowers (s. below for 'process.source.fileNames')
#process.patJets.addJetID=True
#process.load("RecoJets.JetProducers.ak4JetID_cfi")
#process.patJets.jetIDMap="ak4JetID"
process.patJets.useLegacyJetMCFlavour=True # Need to use legacy flavour since the new flavour requires jet constituents which are dropped for CaloJets from AOD
process.out.outputCommands.append( 'keep *_selectedPatJets_caloTowers_*' )
process.out.outputCommands.append( 'drop *_selectedPatJets_pfCandidates_*' )

#print process.out.outputCommands
Esempio n. 24
0
    rParam = 0.8,
    jetCorrections = ('AK8PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None')
    )

addJetCollection(
    process,
    labelName = 'AK8PFCHS',
    jetSource = cms.InputTag('ak8PFJetsCHS'),
    algo = 'ak8',
    rParam = 0.8,
    jetCorrections = ('AK8PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None')
    )

switchJetCollection(
    process,
    jetSource = cms.InputTag('ak4PFJets'),
    rParam = 0.4,
    jetCorrections = ('AK4PF', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'Type-1'),
    )

#process.patJetGenJetMatchCA8PFCHS.matched = cms.InputTag("ca8GenJetsNoNu")

patJetsAK4 = process.patJetsAK4PFCHS
patJetsCA8 = process.patJetsCA8PFCHS
patJetsAK8 = process.patJetsAK8PFCHS

process.out.outputCommands += ['keep *_ak4PFJetsCHS_*_*',
                               'keep *_patJetsAK4PFCHS_*_*',
                               'keep *_ca8PFJetsCHS_*_*',
                               'keep *_patJetsCA8PFCHS_*_*',
                               'keep *_ak8PFJetsCHS_*_*',
                               'keep *_patJetsAK8PFCHS_*_*']
Esempio n. 25
0
process.goodDataHLTPhysicsDeclared = cms.Path(process.hltPhysicsDeclared)
process.goodDataPrimaryVertexFilter = cms.Path(process.primaryVertexFilter)
process.goodDataNoScraping = cms.Path(process.noscraping)
process.goodDataAll = cms.Path(process.hltPhysicsDeclared * process.primaryVertexFilter * process.noscraping)

# Add MET and jets. Configuration to be revisited later.
from PhysicsTools.PatAlgos.tools.metTools import addPfMET, addTcMET
addPfMET(process)
addTcMET(process)

from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection
switchJetCollection(process, 
                    cms.InputTag('ak5PFJets'),   
                    doJTA            = True,            
                    doBTagging       = True,            
                    jetCorrLabel     = ('AK5PF', ['L1FastJet', 'L2Relative', 'L3Absolute']),  
                    doType1MET       = False,            
                    genJetCollection = cms.InputTag("ak5GenJets"),
                    doJetID      = False,
                    jetIdLabel   = "ak5"
                    )

# Make a collection of muons with our final selection applied so that
# the muon-jet cleaning will use only muons passing those cuts. This
# muon collection is not saved in the output.
from SUSYBSMAnalysis.Zprime2muAnalysis.OurSelectionDec2012_cff import loose_cut
process.muonsForJetCleaning = process.selectedPatMuons.clone(cut = loose_cut.replace('pt > 45', 'pt > 30'))
process.patDefaultSequence.replace(process.selectedPatMuons, process.selectedPatMuons * process.muonsForJetCleaning)
process.cleanPatJets.checkOverlaps.muons.src = 'muonsForJetCleaning'
process.cleanPatJets.checkOverlaps.muons.deltaR = 0.2
process.cleanPatJets.checkOverlaps.muons.requireNoOverlaps = True
process.cleanPatJets.finalCut = 'pt > 30.0'
Esempio n. 26
0
def addPat(process, isData, doRECO, doTTEffShrinkingConePFTau):
    sequence = cms.Sequence()

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

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

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

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

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

    sequence += process.patDefaultSequence
    return sequence
def addInvHiggsProcess(process, iRunOnData=True, iData="PromptC2", iHLTFilter="MET", iMCSignal=False, iFile='/store/data/Run2012C/MET/AOD/PromptReco-v2/000/203/002/04BCEC26-AA02-E211-A81D-003048CF99BA.root', iMaxEvent=100):
    
    ###--------------------------------------------------------------
    ### Load PAT, because it insists on defining the process for you
    #from PhysicsTools.PatAlgos.patTemplate_cfg import *
    ###--------------------------------------------------------------


    ###--------------------------------------------------------------
    ### Input
    process.maxEvents.input   = iMaxEvent
    process.source.fileNames  = [iFile]
    ###--------------------------------------------------------------


    ###--------------------------------------------------------------
    ### GlobalTag
    if iRunOnData == True:
        if (iData.find("Jul13")==0):
            process.GlobalTag.globaltag = "FT_53_V6C_AN3::All"
        elif (iData.find("Aug06")==0):
            process.GlobalTag.globaltag = "FT_53_V6C_AN3::All"
        elif (iData.find("Aug24")==0):
            process.GlobalTag.globaltag = "FT53_V10A_AN3::All"
        elif (iData.find("PromptC2")==0):
            process.GlobalTag.globaltag = "GR_P_V42_AN3::All"
        elif (iData.find("PromptD")==0):
            process.GlobalTag.globaltag = "GR_P_V42_AN3::All"
        elif (iData.find("Dec11")==0): #Run201191
            process.GlobalTag.globaltag = "FT_P_V42C_AN3::All"
        else:
            process.GlobalTag.globaltag = "GR_P_V42_AN3::All"
    else:
        process.GlobalTag.globaltag = "START53_V7G::All"
    ###--------------------------------------------------------------

    
    ###--------------------------------------------------------------
    ### Logger
    process.load("FWCore.MessageService.MessageLogger_cfi")
    process.load("FWCore.MessageLogger.MessageLogger_cfi")
    process.MessageLogger.cerr.FwkReport = cms.untracked.PSet(
        reportEvery = cms.untracked.int32(2000),
        limit = cms.untracked.int32(10000000)
        )
    ###--------------------------------------------------------------


    ###--------------------------------------------------------------
    ### HLT Trigger(s)
    # If it's MC signal, no trigger will be applied
    if iRunOnData == False and iMCSignal == True:
        iHLTFilter = "NoTrig"

    # Load hltHighLevel
    process.load('HLTrigger.HLTfilters.hltHighLevel_cfi')
    process.hltHighLevel.TriggerResultsTag = cms.InputTag("TriggerResults","","HLT")
    process.hltHighLevel.throw = cms.bool(False)  # Tolerate if triggers not available
    process.hltHighLevel.andOr = cms.bool(True)   # True = OR, False = AND
    if (iHLTFilter.find("MET")==0):
        process.hltHighLevel.HLTPaths = cms.vstring(
            "HLT_DiPFJet40_PFMETnoMu65_MJJ600VBF_LeadingJets_v*",
            "HLT_DiPFJet40_PFMETnoMu65_MJJ800VBF_AllJets_v*"
            )
    elif (iHLTFilter.find("SingleMu")==0):
        process.hltHighLevel.HLTPaths = cms.vstring("HLT_IsoMu24_eta2p1_v*","HLT_Mu40_eta2p1_v*")
    elif (iHLTFilter.find("DoubleMu")==0):
        process.hltHighLevel.HLTPaths = cms.vstring("HLT_Mu17_Mu8_v*")
    elif (iHLTFilter.find("SingleElectron")==0):
        process.hltHighLevel.HLTPaths = cms.vstring("HLT_Ele27_WP80_v*")
    elif (iHLTFilter.find("DoubleElectron")==0):
        process.hltHighLevel.HLTPaths = cms.vstring("HLT_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v*")
    elif (iHLTFilter.find("NoTrig")==0):
        process.hltHighLevel.HLTPaths = cms.vstring("*")
    else:
        process.hltHighLevel.HLTPaths = cms.vstring(
            "HLT_DiPFJet40_PFMETnoMu65_MJJ600VBF_LeadingJets_v*",
            "HLT_DiPFJet40_PFMETnoMu65_MJJ800VBF_AllJets_v*"
            )
    ###--------------------------------------------------------------


    ###--------------------------------------------------------------
    print "-----------------------------------------------"
    print "INVISIBLE HIGGS: Ntuple V10"
    print "-----------------------------------------------"
    print "RunOnData = ", iRunOnData
    if iRunOnData == True:
        print "Dataset = ", iData
    else:
        if iMCSignal == True:
            print "Dataset = MC Signal"
        else:
            print "Dataset = MC Background"
    print "GlobalTag = ", process.GlobalTag.globaltag
    print "Trigger = ", process.hltHighLevel.HLTPaths
    print "Sample input file = ", iFile
    print "Max events = ", iMaxEvent
    print "-----------------------------------------------"
    ###--------------------------------------------------------------

    
    ###-------------------------------------------------------------- 
    ### Basic filters
    # Track quality filter
    process.noscraping = cms.EDFilter(
        "FilterOutScraping",
        applyfilter = cms.untracked.bool(True),
        debugOn = cms.untracked.bool(False),
        numtrack = cms.untracked.uint32(10),
        thresh = cms.untracked.double(0.25)
        )

    # Require a good vertex
    process.primaryVertexFilter = cms.EDFilter(
        "VertexSelector",
        src = cms.InputTag("offlinePrimaryVertices"),
        cut = cms.string("!isFake && ndof > 4 && abs(z) <= 24 && position.Rho <= 2"),
        filter = cms.bool(True)
        )
    ###-------------------------------------------------------------- 


    ###--------------------------------------------------------------
    ### MET Filters
    # The iso-based HBHE noise filter
    process.load('CommonTools.RecoAlgos.HBHENoiseFilter_cfi')

    # The CSC beam halo tight filter
    process.load('RecoMET.METAnalyzers.CSCHaloFilter_cfi')
    
    # The HCAL laser filter
    process.load("RecoMET.METFilters.hcalLaserEventFilter_cfi")
    process.load("EventFilter.HcalRawToDigi.hcallasereventfilter2012_cff")
    process.hcallasereventfilter2012.eventFileName = cms.string('HCALLaser2012AllDatasets.txt.gz')
    
    # The ECAL dead cell trigger primitive filter
    process.load('RecoMET.METFilters.EcalDeadCellTriggerPrimitiveFilter_cfi')
    
    # The EE bad SuperCrystal filter
    process.load('RecoMET.METFilters.eeBadScFilter_cfi')
    
    # The ECAL laser correction filter
    process.load('RecoMET.METFilters.ecalLaserCorrFilter_cfi')
    
    # The Good vertices collection needed by the tracking failure filter
    process.goodVertices = cms.EDFilter(
        "VertexSelector",
        filter = cms.bool(False),
        src = cms.InputTag("offlinePrimaryVertices"),
        cut = cms.string("!isFake && ndof > 4 && abs(z) <= 24 && position.rho < 2")
        )

    # The tracking failure filter
    process.load('RecoMET.METFilters.trackingFailureFilter_cfi')

    # The tracking POG filters
    process.load('RecoMET.METFilters.trackingPOGFilters_cff')
    ###--------------------------------------------------------------


    ###--------------------------------------------------------------
    ### customise PAT
    process.load('JetMETCorrections.Configuration.DefaultJEC_cff')

    from PhysicsTools.PatAlgos.tools.coreTools import removeMCMatching,runOnData

    if iRunOnData == True:
        removeMCMatching(process, ['All'])
        runOnData(process)

    # Add the PF MET
    from PhysicsTools.PatAlgos.tools.metTools import addPfMET
    addPfMET(process, 'PF')

    # Switch to PF jets
    from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection
    if iRunOnData == True:
        switchJetCollection(process, 
                            cms.InputTag('ak5PFJets'),   
                            doJTA            = True,            
                            doBTagging       = True,            
                            jetCorrLabel     = ('AK5PF', ['L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual']),
                            doType1MET       = True,            
                            doJetID          = False,
                            jetIdLabel       = "ak5"
                            )
    else:
        switchJetCollection(process, 
                            cms.InputTag('ak5PFJets'),   
                            doJTA            = True,            
                            doBTagging       = True,            
                            jetCorrLabel     = ('AK5PF', ['L1FastJet', 'L2Relative', 'L3Absolute']),
                            doType1MET       = True,            
                            genJetCollection = cms.InputTag("ak5GenJetsNoNu"),
                            doJetID          = False,
                            jetIdLabel       = "ak5"
                            )

    from PhysicsTools.PatAlgos.tools.pfTools import usePFIso
    usePFIso(process)

    process.patMuons.isoDeposits = cms.PSet()
    process.patMuons.isolationValues = cms.PSet()
    process.patElectrons.isolationValues = cms.PSet(
        pfChargedHadrons = cms.InputTag("elPFIsoValueCharged03PFIdPFIso"),
        pfChargedAll = cms.InputTag("elPFIsoValueChargedAll03PFIdPFIso"),
        pfPUChargedHadrons = cms.InputTag("elPFIsoValuePU03PFIdPFIso"),
        pfNeutralHadrons = cms.InputTag("elPFIsoValueNeutral03PFIdPFIso"),
        pfPhotons = cms.InputTag("elPFIsoValueGamma03PFIdPFIso")
        )
    process.patElectrons.isolationValuesNoPFId = cms.PSet(
        pfChargedHadrons = cms.InputTag("elPFIsoValueCharged03NoPFIdPFIso"),
        pfChargedAll = cms.InputTag("elPFIsoValueChargedAll03NoPFIdPFIso"),
        pfPUChargedHadrons = cms.InputTag("elPFIsoValuePU03NoPFIdPFIso"),
        pfNeutralHadrons = cms.InputTag("elPFIsoValueNeutral03NoPFIdPFIso"),
        pfPhotons = cms.InputTag("elPFIsoValueGamma03NoPFIdPFIso")
        )
    process.patDefaultSequence.replace(process.patElectrons,process.eleIsoSequence+process.patElectrons)
    process.cleanPatTaus.preselection = cms.string('tauID("decayModeFinding") > 0.5 & tauID("byLooseCombinedIsolationDeltaBetaCorr") > 0.5')
    ###--------------------------------------------------------------
    

    ###--------------------------------------------------------------
    ### Object (pre) selection
    # Jet selection
    process.selectedPatJets.cut = cms.string("pt>10. && abs(eta)<5.")

    # Remove overlaps ???
    # process.cleanPatJets.finalCut = "!hasOverlaps('electrons') && !hasOverlaps('muons')"

    # Apply loose PF jet ID
    from PhysicsTools.SelectorUtils.pfJetIDSelector_cfi import pfJetIDSelector
    process.goodPatJets = cms.EDFilter("PFJetIDSelectionFunctorFilter",
                                       filterParams = pfJetIDSelector.clone(),
                                       src = cms.InputTag("selectedPatJets"),
                                       filter = cms.bool(True)
                                       )

    process.selectedPatMuons.cut = cms.string("isGlobalMuon && pt>10. && abs(eta)<2.5")
    
    process.selectedPatElectrons.cut = cms.string("pt>10. && abs(eta)<2.5")
    ###--------------------------------------------------------------


    ###--------------------------------------------------------------
    ### Load the PU JetID sequence
    if iRunOnData == True:
    	process.load("CMGTools.External.pujetidsequence_cff")
    	process.puJetMva.jets = cms.InputTag("goodPatJets")
    	process.puJetId.jets = cms.InputTag("goodPatJets")
    else:
        process.load("CMGTools.External.pujetidsequence_cff")
        process.puJetMva.jets		= cms.InputTag("goodPatJets")
        process.puJetId.jets 		= cms.InputTag("goodPatJets")
	process.puJetMvaSmeared		= process.puJetMva.clone()
	process.puJetIdSmeared		= process.puJetId.clone()  
	process.puJetMvaResUp 		= process.puJetMva.clone()
	process.puJetIdResUp 		= process.puJetId.clone()
        process.puJetMvaResDown		= process.puJetMva.clone()
        process.puJetIdResDown  	= process.puJetId.clone()
        process.puJetMvaEnUp   		= process.puJetMva.clone()
        process.puJetIdEnUp    		= process.puJetId.clone()
        process.puJetMvaEnDown 		= process.puJetMva.clone()
        process.puJetIdEnDown  		= process.puJetId.clone()

        process.puJetIdSmeared.jets     = cms.InputTag("smearedGoodPatJetsWithGaussian")
        process.puJetMvaSmeared.jetids  = cms.InputTag("puJetIdSmeared")
        process.puJetMvaSmeared.jets    = cms.InputTag("smearedGoodPatJetsWithGaussian")

	process.puJetIdResUp.jets 	= cms.InputTag("smearedGoodPatJetsResUpWithGaussian")
	process.puJetMvaResUp.jetids 	= cms.InputTag("puJetIdResUp")
	process.puJetMvaResUp.jets 	= cms.InputTag("smearedGoodPatJetsResUpWithGaussian")

        process.puJetIdResDown.jets     = cms.InputTag("smearedGoodPatJetsResDownWithGaussian")
        process.puJetMvaResDown.jetids  = cms.InputTag("puJetIdResDown")
        process.puJetMvaResDown.jets    = cms.InputTag("smearedGoodPatJetsResDownWithGaussian")

        process.puJetIdEnUp.jets        = cms.InputTag("shiftedGoodPatJetsEnUpForCorrMEtWithGaussian")
        process.puJetMvaEnUp.jetids     = cms.InputTag("puJetIdEnUp")
        process.puJetMvaEnUp.jets       = cms.InputTag("shiftedGoodPatJetsEnUpForCorrMEtWithGaussian")

        process.puJetIdEnDown.jets      = cms.InputTag("shiftedGoodPatJetsEnDownForCorrMEtWithGaussian")
        process.puJetMvaEnDown.jetids   = cms.InputTag("puJetIdEnDown")
        process.puJetMvaEnDown.jets     = cms.InputTag("shiftedGoodPatJetsEnDownForCorrMEtWithGaussian")

	# For jet without Gaussian smearing collection
	process.puJetMvaSmearedNoGaussian	= process.puJetMva.clone()
	process.puJetIdSmearedNoGaussian	= process.puJetId.clone()
	process.puJetMvaResUpNoGaussian         = process.puJetMva.clone()
        process.puJetIdResUpNoGaussian          = process.puJetId.clone()
        process.puJetMvaResDownNoGaussian       = process.puJetMva.clone()
        process.puJetIdResDownNoGaussian        = process.puJetId.clone()
        process.puJetMvaEnUpNoGaussian          = process.puJetMva.clone()
        process.puJetIdEnUpNoGaussian           = process.puJetId.clone()
        process.puJetMvaEnDownNoGaussian        = process.puJetMva.clone()
        process.puJetIdEnDownNoGaussian         = process.puJetId.clone()

	process.puJetIdSmearedNoGaussian.jets     = cms.InputTag("smearedGoodPatJetsNoGaussian")
        process.puJetMvaSmearedNoGaussian.jetids  = cms.InputTag("puJetIdSmearedNoGaussian")
        process.puJetMvaSmearedNoGaussian.jets    = cms.InputTag("smearedGoodPatJetsNoGaussian")

        process.puJetIdResUpNoGaussian.jets       = cms.InputTag("smearedGoodPatJetsResUpNoGaussian")
        process.puJetMvaResUpNoGaussian.jetids    = cms.InputTag("puJetIdResUpNoGaussian")
        process.puJetMvaResUpNoGaussian.jets      = cms.InputTag("smearedGoodPatJetsResUpNoGaussian")

        process.puJetIdResDownNoGaussian.jets     = cms.InputTag("smearedGoodPatJetsResDownNoGaussian")
        process.puJetMvaResDownNoGaussian.jetids  = cms.InputTag("puJetIdResDownNoGaussian")
        process.puJetMvaResDownNoGaussian.jets    = cms.InputTag("smearedGoodPatJetsResDownNoGaussian")

        process.puJetIdEnUpNoGaussian.jets        = cms.InputTag("shiftedGoodPatJetsEnUpForCorrMEtNoGaussian")
        process.puJetMvaEnUpNoGaussian.jetids     = cms.InputTag("puJetIdEnUpNoGaussian")
        process.puJetMvaEnUpNoGaussian.jets       = cms.InputTag("shiftedGoodPatJetsEnUpForCorrMEtNoGaussian")

        process.puJetIdEnDownNoGaussian.jets      = cms.InputTag("shiftedGoodPatJetsEnDownForCorrMEtNoGaussian")
        process.puJetMvaEnDownNoGaussian.jetids   = cms.InputTag("puJetIdEnDownNoGaussian")
        process.puJetMvaEnDownNoGaussian.jets     = cms.InputTag("shiftedGoodPatJetsEnDownForCorrMEtNoGaussian")
    ###--------------------------------------------------------------


    ###--------------------------------------------------------------
    ### MET
    # Apply type 0 MET corrections based on PFCandidate
    process.load("JetMETCorrections.Type1MET.pfMETCorrectionType0_cfi")
    process.pfType1CorrectedMet.applyType0Corrections = cms.bool(False)
    process.pfType1CorrectedMet.srcType1Corrections = cms.VInputTag(
        cms.InputTag('pfMETcorrType0'),
        cms.InputTag('pfJetMETcorr', 'type1')
        )

    # Get loose ID/Iso muons and veto ID electrons
    process.load("InvisibleHiggs.Ntuple.PhysicsObjectCandidates_cff")

    # Get PFMET from runMEtUncertainties
    from PhysicsTools.PatUtils.tools.metUncertaintyTools import runMEtUncertainties
    process.load("JetMETCorrections.Type1MET.pfMETsysShiftCorrections_cfi")

    if iRunOnData == True:
        runMEtUncertainties(process,
                            electronCollection = cms.InputTag('selectVetoElectrons'),
                            photonCollection = '',
                            muonCollection = 'selectLooseMuons',
                            tauCollection = '',
                            jetCollection = cms.InputTag('goodPatJets'),
                            jetCorrLabel = 'L2L3Residual',
                            doSmearJets = False,
                            makeType1corrPFMEt = True,
                            makeType1p2corrPFMEt = False,
                            makePFMEtByMVA = False,
                            makeNoPileUpPFMEt = False,
                            doApplyType0corr = True,
                            sysShiftCorrParameter = process.pfMEtSysShiftCorrParameters_2012runAvsNvtx_data,
                            doApplySysShiftCorr = False,
			    addToPatDefaultSequence = False,
			    postfix = ''
                            )
        process.patPFJetMETtype1p2Corr.jetCorrLabel = cms.string('L2L3Residual')
        process.patPFJetMETtype2Corr.jetCorrLabel = cms.string('L2L3Residual')
    else:
        runMEtUncertainties(process,
                            electronCollection = cms.InputTag('selectVetoElectrons'),
                            photonCollection = '',
                            muonCollection = 'selectLooseMuons',
                            tauCollection = '',
                            jetCollection = cms.InputTag('goodPatJets'),
                            jetCorrLabel = 'L3Absolute',
                            doSmearJets = True,
                            makeType1corrPFMEt = True,
                            makeType1p2corrPFMEt = False,
                            makePFMEtByMVA = False,
                            makeNoPileUpPFMEt = False,
                            doApplyType0corr = True,
                            sysShiftCorrParameter = process.pfMEtSysShiftCorrParameters_2012runAvsNvtx_mc,
                            doApplySysShiftCorr = False,
			    addToPatDefaultSequence = False,
			    postfix = 'WithGaussian'
                            )
        runMEtUncertainties(process,
                            electronCollection = cms.InputTag('selectVetoElectrons'),
                            photonCollection = '',
                            muonCollection = 'selectLooseMuons',
                            tauCollection = '',
                            jetCollection = cms.InputTag('goodPatJets'),
                            jetCorrLabel = 'L3Absolute',
                            doSmearJets = True,
                            makeType1corrPFMEt = True,
                            makeType1p2corrPFMEt = False,
                            makePFMEtByMVA = False,
                            makeNoPileUpPFMEt = False,
                            doApplyType0corr = True,
                            sysShiftCorrParameter = process.pfMEtSysShiftCorrParameters_2012runAvsNvtx_mc,
                            doApplySysShiftCorr = False,
                            addToPatDefaultSequence = False,
                            postfix = 'NoGaussian'
                            )
	# Turn off gaussian smearing
    	process.smearedGoodPatJetsNoGaussian.doGaussian = cms.int32(0)
    	process.smearedGoodPatJetsResUpNoGaussian.doGaussian = cms.int32(0)
    	process.smearedGoodPatJetsResDownNoGaussian.doGaussian = cms.int32(0)

    # Fix Type0 correction module
    process.patPFMETtype0Corr.correction.par3 = cms.double(0.909209)
    process.patPFMETtype0Corr.correction.par2 = cms.double(0.0303531)
    process.patPFMETtype0Corr.correction.par1 = cms.double(-0.703151)
    process.patPFMETtype0Corr.correction.par0 = cms.double(0.0)
    ###--------------------------------------------------------------

    # PAT/ntuples one step  
    # Z and W candidates    
    process.load('InvisibleHiggs/Ntuple/WCandidates_cff')
    process.load('InvisibleHiggs/Ntuple/ZCandidates_cff')
    # Ntuple producer       
    process.load('InvisibleHiggs/Ntuple/invHiggsInfo_cfi')
    if iRunOnData == False: 
        # Jet/MET uncertainty
        process.invHiggsInfo.jetTag      = cms.untracked.InputTag("smearedGoodPatJetsWithGaussian")
        process.invHiggsInfo.metTag      = cms.untracked.InputTag("patType1CorrectedPFMetWithGaussian")
        process.invHiggsInfo.puJetMvaTag = cms.untracked.InputTag("puJetMvaSmeared", "fullDiscriminant")
        process.invHiggsInfo.puJetIdTag  = cms.untracked.InputTag("puJetMvaSmeared", "fullId")
                            
        # PU re-weighting   
        process.invHiggsInfo.puMCFile    = cms.untracked.string("PUHistS10.root")
        process.invHiggsInfo.puDataFile  = cms.untracked.string("PUHistRun2012All_forV9.root")
        process.invHiggsInfo.puMCHist    = cms.untracked.string("pileup")
        process.invHiggsInfo.puDataHist  = cms.untracked.string("pileup")
        process.invHiggsInfo.mcPYTHIA    = cms.untracked.bool(True)
        
        process.invHiggsInfo.trigCorrFile   = cms.untracked.string("DataMCWeight_53X_v1.root")

	process.invHiggsInfo.leptCorrFile   = cms.untracked.string("leptonWeights.root")
    # TTree output file     
    process.load("CommonTools.UtilAlgos.TFileService_cfi")
    process.TFileService.fileName = cms.string('invHiggsInfo_MC.root')
    ###--------------------------------------------------------------

    ###--------------------------------------------------------------
    ### Tau
    # removeSpecificPATObjects( process, ['Taus'] )
    # process.patDefaultSequence.remove( process.patTaus )
    process.load("RecoTauTag.Configuration.RecoPFTauTag_cff")
    ###--------------------------------------------------------------


    ###--------------------------------------------------------------
    ### Trigger matching
    # from PhysicsTools.PatAlgos.tools.trigTools import *

    # process.metTriggerMatch = cms.EDProducer(
    #     "PATTriggerMatcherDRLessByR"                    # match by DeltaR only, best match by DeltaR
    #     , src     = cms.InputTag( 'patMETs' )
    #     , matched = cms.InputTag( 'patTrigger' )          # default producer label as defined in PhysicsTools/PatAlgos/python/triggerLayer1/triggerProducer_cfi.py
    #     , matchedCuts = cms.string( 'path( "HLT_MET100_v*" )' )
    #     , maxDPtRel = cms.double( 0.5 )
    #     , maxDeltaR = cms.double( 0.5 )
    #     , resolveAmbiguities    = cms.bool( True )        # only one match per trigger object
    #     , resolveByMatchQuality = cms.bool( True )        # take best match found per reco object: by DeltaR here (s. above)
    # )
    # process.jetTriggerMatch = cms.EDProducer(
    #     "PATTriggerMatcherDRLessByR"                    # match by DeltaR only, best match by DeltaR
    #     , src     = cms.InputTag( 'patJets' )
    #     , matched = cms.InputTag( 'patTrigger' )          # default producer label as defined in PhysicsTools/PatAlgos/python/triggerLayer1/triggerProducer_cfi.py
    #     , matchedCuts = cms.string( 'path( "HLT_Jet30_v*" )' )
    #     , maxDPtRel = cms.double( 0.5 )
    #     , maxDeltaR = cms.double( 0.5 )
    #     , resolveAmbiguities    = cms.bool( True )        # only one match per trigger object
    #     , resolveByMatchQuality = cms.bool( True )        # take best match found per reco object: by DeltaR here (s. above)
    # )
    
    # switchOnTriggerMatchEmbedding( process, [ 'metTriggerMatch', 'jetTriggerMatch' ] )
    ###--------------------------------------------------------------


    ###--------------------------------------------------------------
    ### Paths
    process.p0 = cms.Path( process.HBHENoiseFilter )
    process.p1 = cms.Path( process.CSCTightHaloFilter )
    process.p2 = cms.Path( process.hcalLaserEventFilter )
    process.p3 = cms.Path( process.EcalDeadCellTriggerPrimitiveFilter )
    process.p4 = cms.Path( process.eeBadScFilter )
    process.p5 = cms.Path( process.ecalLaserCorrFilter )
    process.p6 = cms.Path( process.goodVertices * process.trackingFailureFilter )
    process.p7 = cms.Path( process.trkPOGFilters )
    process.p8 = cms.Path( process.hcallLaserEvent2012Filter )

    if iRunOnData == True:
    	process.p = cms.Path(    
        	# Trigger filter
        	process.hltHighLevel *
        
        	# Basic filters
        	process.noscraping *
        	process.primaryVertexFilter *
        	
        	# MET filters (Move to be flags)
        
        	# MET Correction
        	process.type0PFMEtCorrection *
        
        	# Tau
        	process.recoTauClassicHPSSequence *
        
        	# Generate PAT
        	process.pfParticleSelectionSequence *
        	process.patDefaultSequence *
        	process.goodPatJets *
		process.PhysicsObjectSequence *
		process.metUncertaintySequence *
        	process.puJetIdSqeuence *
		process.WSequence *
                process.ZSequence *
                process.invHiggsInfo
		)
    else:
        process.p = cms.Path(
                # Trigger filter
                process.hltHighLevel *

                # Basic filters
                process.noscraping *
                process.primaryVertexFilter *

                # MET filters (Move to be flags)

                # MET Correction
                process.type0PFMEtCorrection *

                # Tau
                process.recoTauClassicHPSSequence *

                # Generate PAT
                process.pfParticleSelectionSequence *
        	process.genParticlesForJetsNoNu *
                process.ak5GenJetsNoNu *
                process.patDefaultSequence *
                process.goodPatJets *
                process.PhysicsObjectSequence *
                process.metUncertaintySequenceWithGaussian *
		process.metUncertaintySequenceNoGaussian *
                process.puJetIdSqeuence *
		process.puJetIdSmeared *
		process.puJetMvaSmeared *
        	process.puJetIdResUp *
		process.puJetMvaResUp *
         	process.puJetIdResDown *
        	process.puJetMvaResDown *
        	process.puJetIdEnUp *
        	process.puJetMvaEnUp *
        	process.puJetIdEnDown *
        	process.puJetMvaEnDown *
                process.puJetIdSmearedNoGaussian *
                process.puJetMvaSmearedNoGaussian *
                process.puJetIdResUpNoGaussian *
                process.puJetMvaResUpNoGaussian *
                process.puJetIdResDownNoGaussian *
                process.puJetMvaResDownNoGaussian *
                process.puJetIdEnUpNoGaussian *
                process.puJetMvaEnUpNoGaussian *
                process.puJetIdEnDownNoGaussian *
                process.puJetMvaEnDownNoGaussian *
		process.WSequence *
        	process.ZSequence *
                process.invHiggsInfo
        	)
    ###--------------------------------------------------------------


    ###--------------------------------------------------------------
    ### Output
    process.out.outputCommands += [
        # trigger results
        'keep edmTriggerResults_*_*_*'
        ,'keep *_hltTriggerSummaryAOD_*_*'
        # L1
        ,'keep *_l1extraParticles_MET_RECO'
        ,'keep *_l1extraParticles_MHT_RECO'
        # good jets
        ,'keep *_goodPatJets_*_*'
        # PU jet ID
        ,'keep *_puJetId*_*_*'
        ,'keep *_puJetMva*_*_*'
        # vertices
        ,'keep *_offlineBeamSpot_*_*'
        ,'keep *_offlinePrimaryVertices*_*_*'
        ,'keep *_goodOfflinePrimaryVertices*_*_*'
        ,'keep double_*_rho_*'
        ]

    if iRunOnData == False:
        process.out.outputCommands += ['keep GenEventInfoProduct_*_*_*'
                                       ,'keep recoGenParticles_*_*_*'
                                       ,'keep GenMETs_*_*_*'
                                       ,'keep *_addPileupInfo_*_*'
                                       ,'keep LHEEventProduct_*_*_*'
				       ,'keep ak5GenJets_*_*_*'
                                       ,'keep ak5GenJetsNoNu_*_*_*'
                                       ]
        
    process.out.fileName = 'patTuple.root'

    del(process.out)
    del(process.outpath)
Esempio n. 28
0
        btagInfos=btagInfos,
        jetTrackAssociation=True,
        outputModules=outputModules,
    )
    if runOnMC:
        getattr(process, 'patJetGenJetMatchPatJetsCA15PFCHSFilteredSubJets' +
                postfix).matched = cms.InputTag('ca15GenJetsNoNuFiltered',
                                                'SubJets')

# Do switchJetCollection(...) at the end
switchJetCollection(
    process,
    jetSource=cms.InputTag('ak5PFJetsCHS'),
    algo=jetAlgo,
    postfix=postfix,
    jetCorrections=('AK5PFchs', inputJetCorrLabel, ''),
    btagDiscriminators=btagDiscriminators,
    btagInfos=btagInfos,
    jetTrackAssociation=True,
    outputModules=outputModules,
)

# ------------------------------------------------------------------------------
# Pileup Jet ID
#   https://twiki.cern.ch/twiki/bin/view/CMS/PileupJetID
# ------------------------------------------------------------------------------
process.load("JetMETCorrections.Configuration.JetCorrectionServices_cff")
# Convert algorithm from AK5PFCHS to AK5PFchs
process.ak5PFCHSL1Offset.algorithm = cms.string('AK5PFchs')
process.ak5PFCHSL1Fastjet.algorithm = cms.string('AK5PFchs')
process.ak5PFCHSL2Relative.algorithm = cms.string('AK5PFchs')
Esempio n. 29
0
    jetCorrections = ('AK10PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
    trackSource = cms.InputTag('unpackedTracksAndVertices'),
    pvSource = cms.InputTag('offlineSlimmedPrimaryVertices'),
    svSource = cms.InputTag('slimmedSecondaryVertices'),
    pfCandidates = cms.InputTag('packedPFCandidates'),
    btagDiscriminators = ['pfCombinedSecondaryVertexBJetTags', 'pfCombinedInclusiveSecondaryVertexV2BJetTags'],
    genJetCollection=cms.InputTag('ak4GenJets'),
    )

switchJetCollection(
    process,
    jetSource = cms.InputTag('ak4PFJets'),
    algo = 'ak4',
    rParam = 0.4,
    jetCorrections = ('AK4PF', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'Type-1'),
    trackSource = cms.InputTag('unpackedTracksAndVertices'),
    pvSource = cms.InputTag('offlineSlimmedPrimaryVertices'),
    svSource = cms.InputTag('slimmedSecondaryVertices'),
    pfCandidates = cms.InputTag('packedPFCandidates'),
    #btagDiscriminators = ['pfCombinedSecondaryVertexBJetTags', 'pfCombinedInclusiveSecondaryVertexV2BJetTags'],   #this breaks the config
    genJetCollection=cms.InputTag('ak4GenJets'),
    )

for module in [process.patJetsAK4PFCHS, process.patJetsAK8PFCHS, process.patJetsAK10PFCHS, process.patJetsAK12PFCHS, process.patJetsAK15PFCHS]:
    module.addJetCharge   = False
    module.addBTagInfo    = True   
    module.getJetMCFlavour = False
    module.addAssociatedTracks = False

for module in [process.patJetPartonMatch, process.patJetPartonMatchAK4PFCHS, process.patJetPartonMatchAK8PFCHS, process.patJetPartonMatchAK10PFCHS, process.patJetPartonMatchAK12PFCHS, process.patJetPartonMatchAK15PFCHS]:
    module.matched='prunedGenParticles'
Esempio n. 30
0
                                   SelectEvents=cms.untracked.PSet(SelectEvents=cms.vstring('p')),
                                   outputCommands = cms.untracked.vstring("keep *")
                                   )
    process.outpath  = cms.EndPath(process.out)
    from PhysicsTools.PatAlgos.tools.coreTools import *
    removeMCMatching(process, ['All'])

########################################
# PAT Jet Energy Corrections - MC vs Data
########################################
# 

from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection
if isMC:
    switchJetCollection( process,
                         jetCollection=cms.InputTag('ak5CaloJets'),
                         jetCorrLabel=('AK5Calo', ['L2Relative','L3Absolute']))
else:
    switchJetCollection( process,
                         jetCollection=cms.InputTag('ak5CaloJets'),
                         jetCorrLabel=('AK5Calo', ['L2Relative','L3Absolute','L2L3Residual']))

########################################
# PAT Trigger matching
########################################
# imported directly from PhysicsTools/PatExamples/test/analyzePatTrigger_onTheFly_cfg.py
#
process.load("HeavyNu.AnalysisModules.hnutrigmatch_cfi")

### ============
### Python tools
Esempio n. 31
0
# comment-out to take new HPS + TaNC combined tau id. algorithm
#tauTools.switchToPFTauHPSpTaNC(process)

# disable preselection on of pat::Taus
# (disabled also in TauAnalysis/RecoTools/python/patPFTauConfig_cfi.py ,
#  but re-enabled after switching tau collection)
process.cleanPatTaus.preselection = cms.string('')
#--------------------------------------------------------------------------------

#--------------------------------------------------------------------------------
# import utility function for managing pat::Jets
import PhysicsTools.PatAlgos.tools.jetTools as jetTools

# uncomment to replace caloJets by pfJets
jetTools.switchJetCollection(process,
                             jetCollection=cms.InputTag("ak5PFJets"),
                             doBTagging=True,
                             outputModule='')
#--------------------------------------------------------------------------------

#--------------------------------------------------------------------------------
# import utility function for managing pat::METs
import TauAnalysis.Configuration.tools.metTools as metTools

# uncomment to add pfMET
# set Boolean swich to true in order to apply type-1 corrections
metTools.addPFMet(process, correct=False)

# uncomment to replace caloMET by pfMET in all di-tau objects
process.load("TauAnalysis.CandidateTools.diTauPairProductionAllKinds_cff")
metTools.replaceMETforDiTaus(process, cms.InputTag('patMETs'),
                             cms.InputTag('patPFMETs'))
execfile("TopAnalysis/Configuration/analysis/semiLeptonic/jetEnergy/analyzeJetEnergyCorrections_aod_template_cfg.py")

from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection
switchJetCollection(process, 
                    cms.InputTag('iterativeCone5CaloJets'),
                    doJTA            = True,            
                    doBTagging       = True,            
                    jetCorrLabel     = ('IC5','Calo'),  
                    doType1MET       = True,            
                    genJetCollection = cms.InputTag("iterativeCone5GenJets"),
                    doJetID          = True,
                    jetIdLabel       = 'ic5'
                    )

myGenJets = "iterativeCone5GenJets"
process.ttSemiLepGenJetPartonMatch.jets = myGenJets

process.analyzeJetEnergyGenMatch_raw .genJets = myGenJets
process.analyzeJetEnergyGenMatch_off .genJets = myGenJets
process.analyzeJetEnergyGenMatch_rel .genJets = myGenJets
process.analyzeJetEnergyGenMatch_abs .genJets = myGenJets
process.analyzeJetEnergyGenMatch_emf .genJets = myGenJets
process.analyzeJetEnergyGenMatch_had .genJets = myGenJets
process.analyzeJetEnergyGenMatch_ue  .genJets = myGenJets
process.analyzeJetEnergyGenMatch_part.genJets = myGenJets

process.analyzeJetEnergyGeom_raw .genJets = myGenJets
process.analyzeJetEnergyGeom_off .genJets = myGenJets
process.analyzeJetEnergyGeom_rel .genJets = myGenJets
process.analyzeJetEnergyGeom_abs .genJets = myGenJets
process.analyzeJetEnergyGeom_emf .genJets = myGenJets
def addTagInfos(process,jetMetCorrections):
    from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection
    switchJetCollection( process,
                     jetCollection=cms.InputTag('ak5CaloJets'),
                     jetCorrLabel=('AK5Calo', jetMetCorrections))
Esempio n. 34
0
def addPat(process, isData, doRECO, doTTEffShrinkingConePFTau):
    sequence = cms.Sequence()

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

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

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

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

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

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

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

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

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

    sequence += process.patDefaultSequence
    return sequence
Esempio n. 35
0
def ReRunJetsMC(process):
  process.load("RecoJets.Configuration.RecoPFJets_cff") 
  import PhysicsTools.PatAlgos.tools.jetTools as jettools
  process.load("PhysicsTools.PatAlgos.patSequences_cff")
  process.load("UWAnalysis.Configuration.tools.patJetPUId_cfi")
  from RecoBTag.SoftLepton.softLepton_cff import *
  from RecoBTag.ImpactParameter.impactParameter_cff import *
  from RecoBTag.SecondaryVertex.secondaryVertex_cff import *
  from RecoBTau.JetTagComputer.combinedMVA_cff import *
  process.pileupJetIdProducer.applyJec = cms.bool(True)

  process.load('RecoVertex/AdaptiveVertexFinder/inclusiveVertexing_cff')
  #process.load('RecoBTag/SecondaryVertex/bToCharmDecayVertexMerger_cfi')

  process.simpleSecondaryVertex = cms.ESProducer("SimpleSecondaryVertexESProducer",
                                                       use3d = cms.bool(True),
                                                       unBoost = cms.bool(False),
                                                       useSignificance = cms.bool(True),
                                                       minTracks = cms.uint32(2)
                                                   )

  # Define options for BTagging - these are release dependent.
  btag_options = {'doBTagging': True}
  btag_options['btagInfo'] = [
    'impactParameterTagInfos',
    'secondaryVertexTagInfos',
    'softMuonTagInfos'
  ]
  btag_options['btagdiscriminators'] = [
    'simpleSecondaryVertexHighEffBJetTags',
    'simpleSecondaryVertexHighPurBJetTags',
    'combinedSecondaryVertexMVABJetTags',
    'combinedSecondaryVertexBJetTags',
    ]
    
  jec = ['L1FastJet', 'L2Relative', 'L3Absolute']
  # For Data jec.extend(['L2L3Residual'])
  
  jettools.switchJetCollection(
        process,
        cms.InputTag('ak5PFJets'),
        doJTA=False,
        jetCorrLabel=('AK5PF', jec),
        #jetCorrLabel = None,
        doType1MET=False,
        doJetID=True,
        genJetCollection=cms.InputTag("ak5GenJets"),
        outputModules=[],
        **btag_options       
  )
  process.patJets.embedPFCandidates = False
  process.patJets.embedCaloTowers = False
  process.patJets.embedGenJetMatch = False
  process.patJets.addAssociatedTracks = False
  process.patJets.embedGenPartonMatch = False
  process.patJets.tagInfoSources = cms.VInputTag(
    cms.InputTag("impactParameterTagInfos"),
    #cms.InputTag("secondaryVertexNegativeTagInfos"),
    cms.InputTag("secondaryVertexTagInfos"))
  process.patJets.discriminatorSources = cms.VInputTag(
    cms.InputTag("combinedSecondaryVertexMVABJetTags"),
    cms.InputTag("combinedSecondaryVertexBJetTags"),
    cms.InputTag("simpleSecondaryVertexHighPurBJetTags"),
    cms.InputTag("simpleSecondaryVertexHighEffBJetTags"))
  process.patJets.trackAssociationSource = cms.InputTag("ak5JetTracksAssociatorAtVertex")
  process.patJets.addBTagInfo = cms.bool(True)
  process.patJets.addDiscriminators = cms.bool(True)
  process.patJets.addTagInfos = cms.bool(True)

  process.ak5JetTracksAssociatorAtVertex = cms.EDProducer("JetTracksAssociatorAtVertex",
                                                          tracks       = cms.InputTag("generalTracks"),
                                                          jets         = cms.InputTag("ak5PFJets"),
                                                          coneSize     = cms.double(0.5)
                                                          )
  
  process.load('UWAnalysis.Configuration.tools.RecoBTag_cff')  
  process.patJetCharge.src = cms.InputTag("ak5JetTracksAssociatorAtVertex")
  process.NewSelectedPatJets = process.selectedPatJets.clone(src = cms.InputTag("patJetId"))
  process.analysisSequence = cms.Sequence(
  					process.analysisSequence*
  					process.ak5PFJets*
  					process.ak5JetTracksAssociatorAtVertex*
  					process.btagging*
  					process.pileupJetIdProducer*
  					process.makePatJets*
  					process.patJetsPUID*
  					process.patJetId*
  					process.NewSelectedPatJets  					
  					)
def configurePatTuple(process, isMC=True, **kwargs):
    # Stuff we always keep
    output_commands = [
        '*_addPileupInfo_*_*',
        'edmMergeableCounter_*_*_*',
        '*_lumiProducer_*_*',
        '*_particleFlow_*_*',
        '*_offlineBeamSpot_*_*',
        '*_trackCandidates_*_*',
        '*_gsfTrackCandidates_*_*',
        #'*_generalTracks_*_*',
        '*_electronGsfTracks_*_*',
        '*_offlinePrimaryVertices*_*_*',
        '*_ak5PFJets_*_*',
        '*_ak5GenJets_*_*',
        '*_hltTriggerSummaryAOD_*_*',
        'edmTriggerResults_TriggerResults_*_%s' % process.name_(),
        '*_MEtoEDMConverter*_*_%s' % process.name_(),
        'LHEEventProduct_*_*_*',
        'GenEventInfoProduct_generator_*_*',
        '*_kt6PFJetsForRhoComputationVoronoi_rho_*',
        '*_kt6PFJetsForIso_rho_*',
    ]
    # Define our patTuple production sequence
    process.tuplize = cms.Sequence()
    # Only keep interesting genParticles
    process.load("FinalStateAnalysis.RecoTools.genParticleTrimmer_cfi")
    process.genParticles = process.prunedGenParticles.clone()
    if isMC:
        #process.tuplize += process.genParticles
        #output_commands.append('*_genParticles_*_%s' % process.name_())
        output_commands.append('*_genParticles_*_*')

    output_commands.append('*_tauGenJetsSelectorAllHadrons_*_*')
    output_commands.append('*_tauGenJets_*_*')
    output_commands.append('*_ak5GenJets_*_*')
    # Select vertices
    process.load("FinalStateAnalysis.RecoTools.vertexSelection_cff")
    output_commands.append('*_selectedPrimaryVertex_*_*')
    output_commands.append('*_selectPrimaryVerticesQuality_*_*')
    process.tuplize += process.selectPrimaryVertices

    # Run the ZZ recipe for rho
    from RecoJets.JetProducers.kt4PFJets_cfi import kt4PFJets \
            as zzCantDoAnythingRight
    process.kt6PFJetsForIso = zzCantDoAnythingRight.clone(
        rParam = cms.double(0.6),
        doAreaFastjet = cms.bool(True),
        doRhoFastjet = cms.bool(True),
        Rho_EtaMax = cms.double(2.5),
        Ghost_EtaMax = cms.double(2.5),
    )
    process.tuplize += process.kt6PFJetsForIso

    # Rerun tau-ID
    process.load('Configuration/StandardSequences/Services_cff')
    process.load('Configuration/StandardSequences/GeometryIdeal_cff')
    process.load('Configuration/StandardSequences/MagneticField_cff')
    process.load('Configuration/StandardSequences/FrontierConditions_GlobalTag_cff')
    process.load("RecoTauTag.Configuration.RecoPFTauTag_cff")

    # Optimization - remove PFTauTagInfo compatibility layer
    process.recoTauClassicHPSSequence.remove(process.pfRecoTauTagInfoProducer)
    assert(process.combinatoricRecoTaus.modifiers[3].name.value() == 'TTIworkaround')
    del process.combinatoricRecoTaus.modifiers[3]

    process.tuplize += process.recoTauClassicHPSSequence
    ## Run rho computation
    #from RecoJets.Configuration.RecoPFJets_cff import kt6PFJets
    #kt6PFJets.Rho_EtaMax = cms.double(2.5)
    #kt6PFJets.doRhoFastjet = True
    #process.kt6PFJets = kt6PFJets
    #process.tuplize += process.kt6PFJets

    # Run pat default sequence
    process.load("PhysicsTools.PatAlgos.patSequences_cff")
    # Embed PF Isolation in electrons & muons
    pfTools.usePFIso(process)
    # Custom veto cones
    process.elPFIsoValuePU04PFIdPFIso.deposits.vetos = cms.vstring()
    process.elPFIsoValueChargedAll04PFIdPFIso.deposits.vetos = cms.vstring(
        'EcalBarrel:ConeVeto(0.01)','EcalEndcaps:ConeVeto(0.015)')

    # Unembed junk
    process.patMuons.embedCaloMETMuonCorrs = False
    process.patMuons.embedTcMETMuonCorrs = False
    process.patMuons.embedTrack = True
    process.patMuons.pvSrc = cms.InputTag("selectedPrimaryVertex")

    # Do extra electron ID
    process.load("FinalStateAnalysis.PatTools.electrons.electronID_cff")
    process.tuplize += process.recoElectronID
    process.patElectrons.electronIDSources = process.electronIDSources
    process.patElectrons.embedTrack = True

    # Run EGamma electron energy calibration
    process.load("EgammaCalibratedGsfElectrons.CalibratedElectronProducers.calibratedGsfElectrons_cfi")
    process.RandomNumberGeneratorService.calibratedGsfElectrons = cms.PSet(
        initialSeed = cms.untracked.uint32(1), # A frickin billion
        engineName = cms.untracked.string('TRandom3')
    )
    process.calibratedGsfElectrons.inputDataset = kwargs['dataset']
    process.calibratedGsfElectrons.isMC = bool(isMC)
    process.calibratedGsfElectrons.isAOD = True
    process.calibratedGsfElectrons.updateEnergyError = cms.bool(True)
    # Run a sanity check on the calibration configuration.
    from FinalStateAnalysis.PatTools.electrons.patElectronEmbedCalibratedGsf_cfi \
            import validate_egamma_calib_config
    validate_egamma_calib_config(process)

    process.tuplize += process.calibratedGsfElectrons
    # Keep the calibratedGsfElectrons - we embed refs to this into the
    # pat::Electrons
    output_commands.append('*_calibratedGsfElectrons_*_*')

    # Now run PAT
    process.tuplize += process.patDefaultSequence

    # Use HPS taus
    tautools.switchToPFTauHPS(process)
    # Disable tau IsoDeposits
    process.patDefaultSequence.remove(process.patPFTauIsolation)
    process.patTaus.isoDeposits = cms.PSet()
    process.patTaus.userIsolation = cms.PSet()

    # Disable gen match embedding - we keep it in the ntuple
    process.patMuons.embedGenMatch = False
    process.patElectrons.embedGenMatch = False
    process.patTaus.embedGenMatch = False
    process.patTaus.embedGenJetMatch = False

    # Use PFJets and turn on JEC
    jec = [ 'L1FastJet', 'L2Relative', 'L3Absolute' ]
    if not isMC:
        jec.extend([ 'L2L3Residual' ])
    # Use AK5 PFJets
    jettools.switchJetCollection(process,
                                 cms.InputTag('ak5PFJets'),
                                 doJTA = False,
                                 doBTagging = True,
                                 jetCorrLabel = ('AK5PF', jec),
                                 #jetCorrLabel = None,
                                 doType1MET = False,
                                 doJetID = True,
                                 genJetCollection = cms.InputTag("ak5GenJets"))
    process.patJets.embedPFCandidates = False
    process.patJets.embedCaloTowers = False
    process.patJets.embedGenJetMatch = False
    process.patJets.addAssociatedTracks = False
    process.patJets.embedGenPartonMatch = False
    process.patJetCorrFactors.useRho = True
    # Let's use the same rho as in the TauID, so we don't need to do it twice.
    process.patJetCorrFactors.rho = cms.InputTag(
        "kt6PFJetsForRhoComputationVoronoi", "rho")

    # Use PFMEt
    mettools.addPfMET(process)
    if not isMC:
        coreTools.runOnData(process)
        process.patMETsPF.addGenMET = False
    output_commands.append('patJets_selectedPatJets_*_*')

    # Customize/embed all our sequences
    process.load("FinalStateAnalysis.PatTools.patJetProduction_cff")
    # We have to keep all jets (for the MVA MET...)
    process.patJetGarbageRemoval.cut = 'pt > 0'

    final_jet_collection = chain_sequence(
        process.customizeJetSequence, "patJets")
    process.customizeJetSequence.insert(0, process.patJets)
    # Make it a "complete" sequence
    process.customizeJetSequence += process.selectedPatJets
    # We can't mess up the selected pat jets because the taus use them.
    process.selectedPatJets.src = final_jet_collection
    process.patDefaultSequence.replace(process.patJets,
                                       process.customizeJetSequence)

    # Produce the electron collections
    process.load("FinalStateAnalysis.PatTools.patElectronProduction_cff")
    final_electron_collection = chain_sequence(
        process.customizeElectronSequence, "selectedPatElectrons")
    process.tuplize += process.customizeElectronSequence
    process.customizeElectronSequence.insert(0, process.selectedPatElectrons)
    process.patDefaultSequence.replace(process.selectedPatElectrons,
                                       process.customizeElectronSequence)
    # We have to do the pat Jets before the pat electrons since we embed them
    process.customizeElectronSequence.insert(0, process.selectedPatJets)
    process.cleanPatElectrons.src = final_electron_collection
    # The "effective area" calculation needs to know if it is data/mc, etc.
    process.patElectronMVAIsoEmbedding.target = kwargs['target']
    process.patElectronEffectiveAreaEmbedder.target = kwargs['target']

    process.load("FinalStateAnalysis.PatTools.patMuonProduction_cff")
    final_muon_collection = chain_sequence(
        process.customizeMuonSequence, "selectedPatMuons")
    process.customizeMuonSequence.insert(0, process.selectedPatMuons)
    process.patDefaultSequence.replace(process.selectedPatMuons,
                                       process.customizeMuonSequence)
    process.cleanPatMuons.src = final_muon_collection
    # The "effective area" calculation needs to know if it is data/mc, etc.
    process.patMuonMVAIdIsoEmbedding.target = kwargs['target']
    process.patMuonEffectiveAreaEmbedder.target = kwargs['target']

    process.load("FinalStateAnalysis.PatTools.patTauProduction_cff")
    final_tau_collection = chain_sequence(
        process.customizeTauSequence, "selectedPatTaus")
    # Inject into the pat sequence
    process.customizeTauSequence.insert(0, process.selectedPatTaus)
    process.patDefaultSequence.replace(process.selectedPatTaus,
                                       process.customizeTauSequence)
    process.cleanPatTaus.src = final_tau_collection
    # Remove muons and electrons
    process.cleanPatTaus.checkOverlaps.muons.requireNoOverlaps = False
    process.cleanPatTaus.checkOverlaps.electrons.requireNoOverlaps = False
    # Don't apply any prselections
    process.cleanPatTaus.preselection = 'abs(eta) < 2.5 & (pt > 18 | userFloat("jetPt") > 18)'

    # Setup MET production
    process.load("FinalStateAnalysis.PatTools.patMETProduction_cff")
    final_met_collection = chain_sequence(
        process.customizeMETSequence, "patMETsPF")
    process.tuplize += process.customizeMETSequence
    # The MET systematics depend on all other systematics
    process.systematicsMET.tauSrc = cms.InputTag("cleanPatTaus")
    process.systematicsMET.muonSrc = cms.InputTag("cleanPatMuons")
    process.systematicsMET.electronSrc = cms.InputTag("cleanPatElectrons")

    # Keep all the data formats needed for the systematics
    output_commands.append('recoLeafCandidates_*_*_%s'
                           % process.name_())

    # Define the default lepton cleaning
    process.cleanPatElectrons.preselection = cms.string('pt > 5')
    process.cleanPatElectrons.checkOverlaps.muons.requireNoOverlaps = False
    # Make sure we don't kill any good taus by calling them electrons
    # Note that we don't actually remove these overlaps.
    process.cleanPatElectrons.checkOverlaps.taus = cms.PSet(
        src = final_tau_collection,
        algorithm = cms.string("byDeltaR"),
        preselection = cms.string(
            "tauID('decayModeFinding') > 0.5 &&"
            "tauID('byLooseCombinedIsolationDeltaBetaCorr') > 0.5 &&"
            "tauID('againstElectronLoose') > 0.5 && "
            "pt > 10"
        ),
        deltaR = cms.double(0.1),
        checkRecoComponents = cms.bool(False),
        pairCut = cms.string(""),
        requireNoOverlaps = cms.bool(False),
    )

    output_commands.append('*_cleanPatTaus_*_*')
    output_commands.append('*_cleanPatElectrons_*_*')
    output_commands.append('*_cleanPatMuons_*_*')
    output_commands.append('*_%s_*_*' % final_met_collection.value())

    #process.load("PhysicsTools.PatAlgos.triggerLayer1.triggerMatcher_cfi")
    #trigtools.switchOnTriggerMatchEmbedding(process)
    trigtools.switchOnTrigger(process)

    # Build the PATFinalStateEventObject
    process.load("FinalStateAnalysis.PatTools.finalStates.patFinalStateEventProducer_cfi")
    process.patFinalStateEventProducer.electronSrc = final_electron_collection
    process.patFinalStateEventProducer.muonSrc = cms.InputTag("cleanPatMuons")
    process.patFinalStateEventProducer.tauSrc = cms.InputTag("cleanPatTaus")
    process.patFinalStateEventProducer.jetSrc = cms.InputTag("selectedPatJets")
    process.patFinalStateEventProducer.metSrc = final_met_collection
    process.tuplize += process.patFinalStateEventProducer
    output_commands.append('*_patFinalStateEventProducer_*_*')
    process.patFinalStateEventProducer.puTag = cms.string(kwargs['puTag'])

    # Now build the PATFinalStateLS object, which holds LumiSection info.
    process.load(
        "FinalStateAnalysis.PatTools.finalStates.patFinalStateLSProducer_cfi")
    process.tuplize += process.finalStateLS
    output_commands.append('*_finalStateLS_*_*')
    if isMC:
        process.finalStateLS.xSec = kwargs['xSec']

    # Apply some loose PT cuts on the objects we use to create the final states
    # so the combinatorics don't blow up
    process.muonsForFinalStates = cms.EDFilter(
        "PATMuonRefSelector",
        src = cms.InputTag("cleanPatMuons"),
        cut = cms.string('pt > 4'),
        filter = cms.bool(False),
    )

    process.electronsForFinalStates = cms.EDFilter(
        "PATElectronRefSelector",
        src = cms.InputTag("cleanPatElectrons"),
        cut = cms.string('abs(eta) < 2.5 & pt > 4'),
        filter = cms.bool(False),
    )

    # Require that the PT of the jet (either corrected jet or tau)
    # to be greater than 17
    process.tausForFinalStates = cms.EDFilter(
        "PATTauRefSelector",
        src = cms.InputTag("cleanPatTaus"),
        cut = cms.string('abs(eta) < 2.5 & pt > 17 & tauID("decayModeFinding")'),
        filter = cms.bool(False),
    )

    process.selectObjectsForFinalStates = cms.Sequence(
        process.muonsForFinalStates
        + process.electronsForFinalStates
        + process.tausForFinalStates
    )

    process.tuplize += process.selectObjectsForFinalStates

    # Now build all of our DiLeptons and TriLepton final states
    lepton_types = [('Elec', cms.InputTag("electronsForFinalStates")),
                    ('Mu', cms.InputTag("muonsForFinalStates")),
                    ('Tau', cms.InputTag("tausForFinalStates"))]
    #lepton_types = [('Elec', cms.InputTag("cleanPatElectrons")),
                    #('Mu', cms.InputTag("cleanPatMuons")),
                    #('Tau', cms.InputTag("cleanPatTaus"))]

    process.buildDiLeptons = cms.Sequence()

    process.load(
        "FinalStateAnalysis.PatTools.finalStates.patFinalStatesEmbedExtraCollections_cfi")

    # Build di-lepton pairs
    for dilepton in _combinatorics(lepton_types, 2):
        # Don't build two jet states
        if (dilepton[0][0], dilepton[1][0]) == ('Tau', 'Tau'):
            continue

        # Define some basic selections for building combinations
        cuts = ['smallestDeltaR() > 0.3'] # basic x-cleaning

        producer = cms.EDProducer(
            "PAT%s%sFinalStateProducer" % (dilepton[0][0], dilepton[1][0]),
            evtSrc = cms.InputTag("patFinalStateEventProducer"),
            leg1Src = dilepton[0][1],
            leg2Src = dilepton[1][1],
            # X-cleaning
            cut = cms.string(' & '.join(cuts))
        )
        producer_name = "finalState%s%s" % (dilepton[0][0], dilepton[1][0])
        setattr(process, producer_name + "Raw", producer)
        process.buildDiLeptons += producer
        # Embed the other collections
        embedder_seq = helpers.cloneProcessingSnippet(process,
            process.patFinalStatesEmbedObjects, producer_name)
        process.buildDiLeptons += embedder_seq
        # Do some trickery so the final module has a nice output name
        final_module_name = chain_sequence(embedder_seq, producer_name + "Raw")
        final_module = getattr(process, final_module_name.value())
        final_module.setLabel(producer_name)
        setattr(process, producer_name, final_module)
        output_commands.append("*_%s_*_*" % producer_name)

    process.tuplize += process.buildDiLeptons
    # Build tri-lepton pairs
    process.buildTriLeptons = cms.Sequence()
    for trilepton in _combinatorics(lepton_types, 3):
        # Don't build three jet states
        if (trilepton[0][0], trilepton[1][0], trilepton[2][0]) == \
           ('Tau', 'Tau', 'Tau'):
            continue

        # Define some basic selections for building combinations
        cuts = ['smallestDeltaR() > 0.3'] # basic x-cleaning

        producer = cms.EDProducer(
            "PAT%s%s%sFinalStateProducer" %
            (trilepton[0][0], trilepton[1][0], trilepton[2][0]),
            evtSrc = cms.InputTag("patFinalStateEventProducer"),
            leg1Src = trilepton[0][1],
            leg2Src = trilepton[1][1],
            leg3Src = trilepton[2][1],
            # X-cleaning
            cut = cms.string(' & '.join(cuts))
        )
        producer_name = "finalState%s%s%s" % (
            trilepton[0][0], trilepton[1][0], trilepton[2][0])
        #setattr(process, producer_name, producer)
        #process.buildTriLeptons += producer
        setattr(process, producer_name + "Raw", producer)
        process.buildTriLeptons += producer
        # Embed the other collections
        embedder_seq = helpers.cloneProcessingSnippet(process,
            process.patFinalStatesEmbedObjects, producer_name)
        process.buildTriLeptons += embedder_seq
        # Do some trickery so the final module has a nice output name
        final_module_name = chain_sequence(embedder_seq, producer_name + "Raw")
        final_module = getattr(process, final_module_name.value())
        final_module.setLabel(producer_name)
        setattr(process, producer_name, final_module)
        output_commands.append("*_%s_*_*" % producer_name)
    process.tuplize += process.buildTriLeptons

    # Build 4 lepton final states
    process.buildQuadLeptons = cms.Sequence()
    for quadlepton in _combinatorics(lepton_types, 4):
        # Don't build states with more than 2 hadronic taus
        if [x[0] for x in quadlepton].count('Tau') > 2:
            continue

        # Define some basic selections for building combinations
        cuts = ['smallestDeltaR() > 0.3'] # basic x-cleaning

        producer = cms.EDProducer(
            "PAT%s%s%s%sFinalStateProducer" %
            (quadlepton[0][0], quadlepton[1][0], quadlepton[2][0],
             quadlepton[3][0]),
            evtSrc = cms.InputTag("patFinalStateEventProducer"),
            leg1Src = quadlepton[0][1],
            leg2Src = quadlepton[1][1],
            leg3Src = quadlepton[2][1],
            leg4Src = quadlepton[3][1],
            # X-cleaning
            cut = cms.string(' & '.join(cuts))
        )
        producer_name = "finalState%s%s%s%s" % (
            quadlepton[0][0], quadlepton[1][0], quadlepton[2][0],
            quadlepton[3][0]
        )
        #setattr(process, producer_name, producer)
        #process.buildTriLeptons += producer
        setattr(process, producer_name + "Raw", producer)
        process.buildQuadLeptons += producer
        # Embed the other collections
        embedder_seq = helpers.cloneProcessingSnippet(process,
            process.patFinalStatesEmbedObjects, producer_name)
        process.buildQuadLeptons += embedder_seq
        # Do some trickery so the final module has a nice output name
        final_module_name = chain_sequence(embedder_seq, producer_name + "Raw")
        final_module = getattr(process, final_module_name.value())
        final_module.setLabel(producer_name)
        setattr(process, producer_name, final_module)
        output_commands.append("*_%s_*_*" % producer_name)
    process.tuplize += process.buildQuadLeptons

    # Tell the framework to shut up!
    process.load("FWCore.MessageLogger.MessageLogger_cfi")
    process.MessageLogger.cerr.FwkReport.reportEvery = 1000

    return process.tuplize, output_commands
## import skeleton process
from PhysicsTools.PatAlgos.patTemplate_cfg import *

## switch to uncheduled mode
process.options.allowUnscheduled = cms.untracked.bool(True)

process.load("PhysicsTools.PatAlgos.producersLayer1.patCandidates_cff")
process.load("PhysicsTools.PatAlgos.selectionLayer1.selectedPatCandidates_cff")
process.load("PhysicsTools.PatUtils.patPFMETCorrections_cff")

from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection

switchJetCollection(
    process,
    jetSource=cms.InputTag("ak4PFJets"),
    jetCorrections=("AK4PF", ["L1FastJet", "L2Relative", "L3Absolute"], ""),
)

# apply type I/type I + II PFMEt corrections to pat::MET object
# and estimate systematic uncertainties on MET
from PhysicsTools.PatUtils.tools.runType1PFMEtUncertainties import runType1PFMEtUncertainties

runType1PFMEtUncertainties(
    process,
    addToPatDefaultSequence=False,
    jetCollection="selectedPatJets",
    electronCollection="selectedPatElectrons",
    muonCollection="selectedPatMuons",
    tauCollection="selectedPatTaus",
)
   runOnData( process )
 # subsequent jet area calculations needed for L1FastJet on RECO jets
 if useCaloJets and useL1FastJet:
   if useRelVals:
     process.ak5CaloJets = ak5CaloJets.clone( doAreaFastjet = True )
     process.ak5JetID    = ak5JetID.clone()
     process.ak5CaloJetSequence = cms.Sequence(
       process.ak5CaloJets
     * process.ak5JetID
     )
     from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection
     switchJetCollection( process
                        , cms.InputTag( jetAlgo.lower() + 'CaloJets' )
                        , doJTA            = True
                        , doBTagging       = True
                        , jetCorrLabel     = ( jecSet, jecLevels )
                        , doType1MET       = False
                        , genJetCollection = cms.InputTag( jetAlgo.lower() + 'GenJets' )
                        , doJetID          = True
                        )
   else:
     print 'WARNING patRefSel_muJets_test_cfg.py:'
     print '        L1FastJet JECs are not available for AK5Calo jets in this data due to missing jet area computation;'
     print '        switching to   L1Offset   !!!'
     jecLevelsCalo.insert( 0, 'L1Offset' )
     jecLevelsCalo.remove( 'L1FastJet' )
     process.patJetCorrFactors.levels = jecLevelsCalo
     #process.patJetCorrFactors.useRho = False # FIXME: does not apply
 if usePFJets:
   if useL1FastJet:
     process.ak5PFJets = ak5PFJets.clone( doAreaFastjet = True )
Esempio n. 39
0
    SelectEvents=cms.untracked.PSet(SelectEvents=cms.vstring('p')),
    # save PAT Layer 1 output; you need a '*' to
    # unpack the list of commands 'patEventContent'
    dropMetaData=cms.untracked.string('DROPPED'),
    outputCommands=cms.untracked.vstring('keep *'))
#####################################################

#--------------------------------------------------------------------------------
# produce PAT-tuple
process.load("PhysicsTools/PatAlgos/patSequences_cff")
# configure pat::Jet production
# (enable L2L3Residual corrections in case running on Data)
jetCorrections = ('L1FastJet', 'L2Relative', 'L3Absolute')
from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection
switchJetCollection(process,
                    jetSource=cms.InputTag('ak4PFJetsCHS'),
                    jetCorrections=('AK4PFchs', jetCorrections, ""),
                    outputModules=[])

#process.patJets.addTagInfos = cms.bool(True)
#process.patJets.addBTagInfo = cms.bool(True)

#--------------------------------------------------------------------------------
process.load(
    "RecoTauTag.Configuration.RecoPFTauTag_cff")  #loading the configuration
# switch to HPS PFTaus (and disable all "cleaning" cuts)
from PhysicsTools.PatAlgos.tools.tauTools import *
switchToPFTauHPS(process)

#process.ak4PFJetsLegacyHPSPiZeros.stripPhiAssociationDistance = cms.double(0.9)

# switch on PAT trigger
def configurePatTuple(process, isMC=True, **kwargs):
    '''
    Core function for PATTuple production
    '''
    #fix argparser output
    isMC = bool(isMC)

    ########################
    ##                    ##
    ##  PATTuple content  ##
    ##                    ##
    ########################
    # Stuff we always keep
    output_commands = [
        '*_addPileupInfo_*_*',
        'edmMergeableCounter_*_*_*',
        '*_lumiProducer_*_*',
        '*_particleFlow_*_*',
        '*_offlineBeamSpot_*_*',
        '*_generalTracks_*_*',
        '*_electronGsfTracks_*_*',
        '*_gsfElectrons_*_*',
        '*_gsfElectronCores_*_*',
        '*_offlinePrimaryVertices*_*_*',
        '*_ak5GenJets_*_*',
        '*_hltTriggerSummaryAOD_*_*',
        'edmTriggerResults_TriggerResults_*_%s' % process.name_(),
        '*_MEtoEDMConverter*_*_%s' % process.name_(),
        'LHEEventProduct_*_*_*',
        'GenEventInfoProduct_generator_*_*',
        '*_kt6PFJetsForRhoComputationVoronoi_rho_*',
        '*_kt6PFJetsForIso_rho_*',
        '*_kt6PFJets_rho_*',
        '*_kt6PFJetsHZGPho_rho_*',
        '*_kt6PFJetsCentralHZGEle_rho_*',
        '*_kt6PFJetsCentralHZGMu_rho_*',
        '*_kt6PFJetsCentralNeutralHZGMu_rho_*',
        '*_kt6PFJetsCentral_rho_*',
        '*_kt6PFJetsCentralNeutral_rho_*',  # for zz muons
        '*_photonCore_*_*',
        '*_boostedFsrPhotons_*_*',
        # for Zmumu -> embedded samples
        # https://twiki.cern.ch/twiki/bin/view/CMS/MuonTauReplacementRecHit
        '*_generalTracksORG_*_EmbeddedRECO',
        '*_electronGsfTracksORG_*_EmbeddedRECO',
        'double_TauSpinnerReco_TauSpinnerWT_EmbeddedSPIN',
        'double_ZmumuEvtSelEffCorrWeightProducer_weight_EmbeddedRECO',
        'double_muonRadiationCorrWeightProducer_weight_EmbeddedRECO',
        'GenFilterInfo_generator_minVisPtFilter_EmbeddedRECO',
    ]
    # Define our patTuple production sequence
    process.tuplize = cms.Sequence()
    # Only keep interesting genParticles
    process.load("FinalStateAnalysis.RecoTools.genParticleTrimmer_cfi")
    process.genParticles = process.prunedGenParticles.clone()
    if isMC:
        #process.tuplize += process.genParticles
        #output_commands.append('*_genParticles_*_%s' % process.name_())
        output_commands.append('*_genParticles_*_*')

    output_commands.append('*_tauGenJetsSelectorAllHadrons_*_*')
    output_commands.append('*_tauGenJets_*_*')
    output_commands.append('*_ak5GenJets_*_*')

    ########################
    ##                    ##
    ##        PAT         ##
    ##                    ##
    ########################

    # Run pat default sequence
    process.load("PhysicsTools.PatAlgos.patSequences_cff")

    # Embed PF Isolation in electrons & muons
    pfTools.usePFIso(process)
    # Setup H2Tau custom iso definitions
    setup_h2tau_iso(process)
    # Setup hZg custom iso definitions
    add_hZg_iso_needs(process)

    # Now run PAT
    process.tuplize += process.patDefaultSequence

    # Add FSR photons for ZZ analysis
    process.load("FinalStateAnalysis.PatTools.fsrPhotons_cff")
    process.tuplize += process.fsrPhotonSequence

    ########################
    ##        GEN         ##
    ########################

    # Disable gen match embedding - we keep it in the ntuple
    process.patMuons.embedGenMatch = False
    process.patElectrons.embedGenMatch = False
    process.patTaus.embedGenMatch = False
    process.patTaus.embedGenJetMatch = False
    process.patPhotons.embedGenMatch = False
    if not isMC:
        coreTools.runOnData(process)

    ########################
    ##       MUONS        ##
    ########################

    # Unembed junk
    process.patMuons.embedCaloMETMuonCorrs = False
    process.patMuons.embedTcMETMuonCorrs = False
    process.patMuons.embedTrack = True
    process.patMuons.pvSrc = cms.InputTag("selectedPrimaryVertex")

    process.load("FinalStateAnalysis.PatTools.patMuonProduction_cff")
    final_muon_collection = chain_sequence(process.customizeMuonSequence,
                                           "selectedPatMuons")
    process.customizeMuonSequence.insert(0, process.selectedPatMuons)
    process.patDefaultSequence.replace(process.selectedPatMuons,
                                       process.customizeMuonSequence)
    process.cleanPatMuons.src = final_muon_collection
    process.patMuonRochesterCorrectionEmbedder.isMC = cms.bool(bool(isMC))

    ########################
    ##        TAUS        ##
    ########################

    # Use HPS taus
    tautools.switchToPFTauHPS(
        process)  #this NEEDS a sequence called patDefaultSequence
    # Disable tau IsoDeposits
    process.patDefaultSequence.remove(process.patPFTauIsolation)
    process.patTaus.isoDeposits = cms.PSet()
    process.patTaus.userIsolation = cms.PSet()

    process.load("FinalStateAnalysis.PatTools.patTauProduction_cff")
    # Require all taus to pass decay mode finding and have high PT
    process.patTauGarbageRemoval.cut = cms.string(
        "pt > 17 && abs(eta) < 2.5 && tauID('decayModeFindingNewDMs')")
    final_tau_collection = chain_sequence(process.customizeTauSequence,
                                          "selectedPatTaus")
    # Inject into the pat sequence
    process.customizeTauSequence.insert(0, process.selectedPatTaus)
    process.patDefaultSequence.replace(process.selectedPatTaus,
                                       process.customizeTauSequence)
    process.cleanPatTaus.src = final_tau_collection
    # Remove muons and electrons
    process.cleanPatTaus.checkOverlaps.muons.requireNoOverlaps = False
    process.cleanPatTaus.checkOverlaps.electrons.requireNoOverlaps = False
    # Cuts already applied by the garbage removal
    process.cleanPatTaus.preselection = ''
    process.cleanPatTaus.finalCut = ''

    ########################
    ##     ELECTRONS      ##
    ########################

    # Use POG recommendations for (these) electron Isos
    process.elPFIsoValueGamma04PFIdPFIso.deposits[0].vetos = cms.vstring(
        'EcalEndcaps:ConeVeto(0.08)')
    process.elPFIsoValueGamma04NoPFIdPFIso.deposits[0].vetos = cms.vstring(
        'EcalEndcaps:ConeVeto(0.08)')
    process.elPFIsoValueCharged04PFIdPFIso.deposits[0].vetos = cms.vstring(
        'EcalEndcaps:ConeVeto(0.015)')
    process.elPFIsoValueCharged04NoPFIdPFIso.deposits[0].vetos = cms.vstring(
        'EcalEndcaps:ConeVeto(0.015)')

    # Do extra electron ID
    process.load("FinalStateAnalysis.PatTools.electrons.electronID_cff")
    if cmssw_major_version() == 4:
        process.patDefaultSequence.replace(
            process.patElectrons,
            process.recoElectronID42X + process.patElectrons)
        process.patElectrons.electronIDSources = process.electronIDSources42X
    else:
        process.patDefaultSequence.replace(
            process.patElectrons,
            process.recoElectronID5YX + process.patElectrons)
        process.patElectrons.electronIDSources = process.electronIDSources5YX

    process.electronMatch.checkCharge = cms.bool(False)
    process.patElectrons.embedTrack = False
    process.patElectrons.embedPFCandidate = False
    process.patElectrons.embedGsfElectronCore = False
    process.patElectrons.embedSuperCluster = True

    # Produce the electron collections
    process.load("FinalStateAnalysis.PatTools.patElectronProduction_cff")

    # Electron Energy Regression and Calibrations
    process.load(
        "EgammaAnalysis.ElectronTools.electronRegressionEnergyProducer_cfi")
    process.load("EgammaAnalysis.ElectronTools.calibratedPatElectrons_cfi")

    #setup the energy regression for the specific dataset
    if kwargs['eleReg']:
        print "-- Applying Electron Regression and Calibration --"

        process.customizeElectronSequence += process.eleRegressionEnergy
        process.customizeElectronSequence += process.calibratedPatElectrons

        process.eleRegressionEnergy.energyRegressionType = cms.uint32(2)
        process.calibratedPatElectrons.correctionsType = cms.int32(2)

        if isMC:
            process.calibratedPatElectrons.inputDataset = cms.string(
                "Summer12_LegacyPaper")
        else:
            process.calibratedPatElectrons.inputDataset = cms.string(
                "22Jan2013ReReco")

        process.calibratedPatElectrons.combinationType = cms.int32(3)
        process.calibratedPatElectrons.lumiRatio = cms.double(1.0)
        process.calibratedPatElectrons.synchronization = cms.bool(True)
        process.calibratedPatElectrons.isMC = cms.bool(isMC == 1)
        process.calibratedPatElectrons.verbose = cms.bool(False)

    final_electron_collection = chain_sequence(
        process.customizeElectronSequence,
        "selectedPatElectrons",
        # Some of the EGamma modules have non-standard src InputTags,
        # specify them here.
        ("src", "inputPatElectronsTag", "inputElectronsTag"))

    #process.tuplize += process.customizeElectronSequence #why do we need this?
    process.customizeElectronSequence.insert(0, process.selectedPatElectrons)
    process.patDefaultSequence.replace(process.selectedPatElectrons,
                                       process.customizeElectronSequence)
    # We have to do the pat Jets before the pat electrons since we embed them
    process.customizeElectronSequence.insert(0, process.selectedPatJets)

    # Define cleanPatElectrons input collection
    process.cleanPatElectrons.src = final_electron_collection

    # Define the default lepton cleaning
    process.cleanPatElectrons.preselection = cms.string('pt > 5')
    process.cleanPatElectrons.checkOverlaps.muons.requireNoOverlaps = False
    # Make sure we don't kill any good taus by calling them electrons
    # Note that we don't actually remove these overlaps.
    process.cleanPatElectrons.checkOverlaps.taus = cms.PSet(
        src=final_tau_collection,
        algorithm=cms.string("byDeltaR"),
        preselection=cms.string(
            "tauID('decayModeFinding') > 0.5 &&"
            "tauID('byLooseCombinedIsolationDeltaBetaCorr') > 0.5 &&"
            "tauID('againstElectronLoose') > 0.5 && "
            "pt > 10"),
        deltaR=cms.double(0.1),
        checkRecoComponents=cms.bool(False),
        pairCut=cms.string(""),
        requireNoOverlaps=cms.bool(False),
    )

    ########################
    ##        JETS        ##
    ########################

    # Use PFJets and turn on JEC
    jec = ['L1FastJet', 'L2Relative', 'L3Absolute']
    # If we are running on data (not MC), or embedded sample,
    # apply the MC-DATA residual correction.
    if not isMC or kwargs['embedded']:
        jec.extend(['L2L3Residual'])

    # tmp
    # define the b-tag squences for offline reconstruction
    process.load("RecoBTag.SecondaryVertex.secondaryVertex_cff")
    process.load("RecoBTau.JetTagComputer.combinedMVA_cff")
    process.load('RecoVertex/AdaptiveVertexFinder/inclusiveVertexing_cff')
    process.load('RecoBTag/SecondaryVertex/bToCharmDecayVertexMerger_cfi')
    #process.load("PhysicsTools.PatAlgos.patSequences_cff")

    # Define options for BTagging - these are release dependent.
    btag_options = {'doBTagging': True}
    if cmssw_major_version() == 5:
        btag_options['btagInfo'] = [
            'impactParameterTagInfos', 'secondaryVertexTagInfos',
            'softMuonTagInfos', 'secondaryVertexNegativeTagInfos',
            'inclusiveSecondaryVertexFinderFilteredTagInfos'
        ]
        btag_options['btagdiscriminators'] = [
            'trackCountingHighEffBJetTags',
            'trackCountingHighPurBJetTags',
            'simpleSecondaryVertexHighEffBJetTags',
            'simpleSecondaryVertexHighPurBJetTags',
            'simpleInclusiveSecondaryVertexHighEffBJetTags',
            'simpleInclusiveSecondaryVertexHighPurBJetTags',
            'combinedSecondaryVertexMVABJetTags',
            'combinedSecondaryVertexBJetTags',
            'jetBProbabilityBJetTags',
            'jetProbabilityBJetTags',
        ]

    #Avoid embedding
    process.patJets.embedPFCandidates = True
    process.patJets.embedCaloTowers = False
    process.patJets.embedGenJetMatch = True
    process.patJets.addAssociatedTracks = True
    process.patJets.embedGenPartonMatch = True

    # Add AK5chs PFJets
    jettools.addJetCollection(process,
                              cms.InputTag('ak5PFchsJets'),
                              algoLabel="AK5",
                              typeLabel="PFchs",
                              doJTA=True,
                              jetCorrLabel=('AK5PFchs', jec),
                              doType1MET=False,
                              doL1Cleaning=False,
                              doL1Counters=False,
                              genJetCollection=cms.InputTag('ak5GenJets'),
                              doJetID=True,
                              **btag_options)

    # Use AK5 PFJets
    jettools.switchJetCollection(
        process,
        cms.InputTag('ak5PFJets'),
        doJTA=True,
        jetCorrLabel=('AK5PF', jec),
        #jetCorrLabel = None,
        doType1MET=False,
        doJetID=True,
        genJetCollection=cms.InputTag("ak5GenJets"),
        **btag_options)

    # Customize/embed all our sequences
    process.load("FinalStateAnalysis.PatTools.patJetProduction_cff")
    helpers.cloneProcessingSnippet(process, process.customizeJetSequence,
                                   'AK5PFchs')
    process.patJetGarbageRemoval.cut = 'pt > 12'
    final_jet_collection = chain_sequence(process.customizeJetSequence,
                                          "patJets")
    process.customizeJetSequence.insert(0, process.patJets)
    # Make it a "complete" sequence
    process.customizeJetSequence += process.selectedPatJets
    #    process.customizeJetSequence += process.btagging
    # We can't mess up the selected pat jets because the taus use them.
    process.selectedPatJets.src = final_jet_collection
    process.patDefaultSequence.replace(process.patJets,
                                       process.customizeJetSequence)

    process.customizeJetSequenceAK5PFchs.remove(process.patJetsPUIDAK5PFchs)
    process.customizeJetSequenceAK5PFchs.remove(
        process.pileupJetIdProducerAK5PFchs)
    process.patJetGarbageRemovalAK5PFchs.cut = 'pt > 20'
    process.patJetCorrFactorsAK5PFchs.payload = cms.string('AK5PFchs')
    final_jetchs_collection = chain_sequence(
        process.customizeJetSequenceAK5PFchs, "patJetsAK5PFchs")
    process.customizeJetSequenceAK5PFchs.insert(0, process.patJetsAK5PFchs)
    # Make it a "complete" sequence
    process.customizeJetSequenceAK5PFchs += process.selectedPatJetsAK5PFchs
    # We can't mess up the selected pat jets because the taus use them.
    process.selectedPatJetsAK5PFchs.src = final_jetchs_collection
    process.selectedPatJetsAK5chsPF = process.selectedPatJetsAK5PFchs.clone(
    )  #that's what we keep
    process.customizeJetSequenceAK5PFchs += process.selectedPatJetsAK5chsPF
    process.patDefaultSequence.replace(process.patJetsAK5PFchs,
                                       process.customizeJetSequenceAK5PFchs)

    output_commands.append('*_selectedPatJets_*_*')
    output_commands.append('*_selectedPatJetsAK5chsPF_*_*')
    output_commands.append('*SecondaryVertexTagInfo*_*_*_*')
    output_commands.append('*TrackIPTagInfo*_*_*_*')
    output_commands.append('*SoftLeptonTagInfo*_*_*_*')
    output_commands.append('*_ak5PFJets_*_*')
    output_commands.append('*_ak5PFchsJets_*_*')

    ########################
    ##        MET         ##
    ########################

    # Use PFMEt
    mettools.addPfMET(process)

    # We cut out a lot of the junky taus and jets - but we need these
    # to correctly apply the MET uncertainties.  So, let's make a
    # non-cleaned version of the jet and tau sequence.
    process.jetsForMetSyst = helpers.cloneProcessingSnippet(
        process, process.customizeJetSequence, 'ForMETSyst')
    process.tausForMetSyst = helpers.cloneProcessingSnippet(
        process, process.customizeTauSequence, 'ForMETSyst')
    # Don't apply any cut for these
    process.patTauGarbageRemovalForMETSyst.cut = ''
    process.patJetGarbageRemovalForMETSyst.cut = ''
    process.tuplize += process.jetsForMetSyst
    process.tuplize += process.tausForMetSyst
    # We have to make our clone of cleanPatTaus separately, since e/mu
    # cleaning is applied - therefore it isn't in the customizeTausSequence.
    process.cleanPatTausForMETSyst = process.cleanPatTaus.clone(
        src=cms.InputTag(process.cleanPatTaus.src.value() + "ForMETSyst"))
    process.cleanPatTausForMETSyst.preselection = ''
    process.cleanPatTausForMETSyst.finalCut = ''
    process.patTausEmbedJetInfoForMETSyst.jetSrc = \
        final_jet_collection.value() + "ForMETSyst"
    process.tuplize += process.cleanPatTausForMETSyst

    # Setup MET production
    process.load("FinalStateAnalysis.PatTools.patMETProduction_cff")
    # The MET systematics depend on all other systematics
    process.systematicsMET.tauSrc = cms.InputTag("cleanPatTausForMETSyst")
    process.systematicsMET.muonSrc = cms.InputTag("cleanPatMuons")
    process.systematicsMET.electronSrc = cms.InputTag("cleanPatElectrons")

    final_met_collection = chain_sequence(process.customizeMETSequence,
                                          "patMETsPF")
    process.tuplize += process.customizeMETSequence
    process.patMETsPF.addGenMET = bool(isMC)
    output_commands.append('*_%s_*_*' % final_met_collection.value())

    # Make a version with the MVA MET reconstruction method
    process.load("FinalStateAnalysis.PatTools.met.mvaMetOnPatTuple_cff")
    process.tuplize += process.pfMEtMVAsequence
    mva_met_sequence = helpers.cloneProcessingSnippet(
        process, process.customizeMETSequence, "MVA")
    final_mvamet_collection = chain_sequence(mva_met_sequence, "patMEtMVA")
    process.tuplize += mva_met_sequence
    output_commands.append('*_%s_*_*' % final_mvamet_collection.value())

    # Keep all the data formats needed for the systematics
    output_commands.append('recoLeafCandidates_*_*_%s' % process.name_())
    # We can drop to jet and tau MET specific products. They were only used for
    # computation of the MET numbers.
    output_commands.append('drop recoLeafCandidates_*ForMETSyst_*_%s' %
                           process.name_())

    ########################
    ##      PHOTONS       ##
    ########################

    #alter the photon matching to accept various fakes
    # and sort matches by d-pt-rel
    if isMC:
        process.photonMatch = cms.EDProducer(
            "MCMatcherByPt",
            src=cms.InputTag("photons"),
            maxDPtRel=cms.double(100.0),
            mcPdgId=cms.vint32(),
            mcStatus=cms.vint32(1),
            resolveByMatchQuality=cms.bool(False),
            maxDeltaR=cms.double(0.3),
            checkCharge=cms.bool(False),
            resolveAmbiguities=cms.bool(True),
            matched=cms.InputTag("genParticles"))

    # Setup pat::Photon Production
    process.load("FinalStateAnalysis.PatTools.patPhotonProduction_cff")
    final_photon_collection = chain_sequence(process.customizePhotonSequence,
                                             "selectedPatPhotons")
    #setup PHOSPHOR for a specific dataset
    if cmssw_major_version() == 4:  # for now 2011 = CMSSW42X
        process.patPhotonPHOSPHOREmbedder.year = cms.uint32(2011)
    else:  # 2012 is 5YX
        process.patPhotonPHOSPHOREmbedder.year = cms.uint32(2012)
    process.patPhotonPHOSPHOREmbedder.isMC = cms.bool(bool(isMC))
    #inject photons into pat sequence
    process.customizePhotonSequence.insert(0, process.selectedPatPhotons)
    process.patDefaultSequence.replace(process.selectedPatPhotons,
                                       process.customizePhotonSequence)
    process.cleanPatPhotons.src = final_photon_collection

    ########################
    ##      TRIGGER       ##
    ########################

    trigtools.switchOnTrigger(process)

    #configure the PAT trigger
    if kwargs['HLTprocess']:
        process.patTrigger.processName = cms.string(kwargs['HLTprocess'])
        process.patTriggerEvent.processName = cms.string(kwargs['HLTprocess'])

    ########################
    ##   --------------   ##
    ########################

    output_commands.append('*_cleanPatTaus_*_*')
    output_commands.append('*_cleanPatElectrons_*_*')
    output_commands.append('*_cleanPatMuons_*_*')
    output_commands.append('*_cleanPatPhotons_*_*')

    ########################
    ##                    ##
    ##        FSA         ##
    ##                    ##
    ########################

    # Now build the PATFinalStateLS object, which holds LumiSection info.
    process.load(
        "FinalStateAnalysis.PatTools.finalStates.patFinalStateLSProducer_cfi")
    process.tuplize += process.finalStateLS
    output_commands.append('*_finalStateLS_*_*')
    if isMC:
        process.finalStateLS.xSec = kwargs['xSec']

    # Tell the framework to shut up!
    process.load("FWCore.MessageLogger.MessageLogger_cfi")
    process.MessageLogger.cerr.FwkReport.reportEvery = 1000

    # Which collections are used to build the final states
    fs_daughter_inputs = {
        'electrons': 'cleanPatElectrons',
        'muons': 'cleanPatMuons',
        'taus': 'cleanPatTaus',
        'photons': 'cleanPatPhotons',
        'jets': 'selectedPatJets',
        'pfmet': final_met_collection,
        'mvamet': final_mvamet_collection,
    }

    # Setup all the PATFinalState objects
    produce_final_states(process,
                         fs_daughter_inputs,
                         output_commands,
                         process.tuplize,
                         kwargs['puTag'],
                         zzMode=kwargs.get('zzMode', False))

    return process.tuplize, output_commands
Esempio n. 41
0
def addInvHiggsProcess(
        process,
        iRunOnData=True,
        iData="ParkedData",
        iHLTFilter="MET",
        iMCSignal=False,
        iFile='/store/data/Run2012C/VBF1Parked/AOD/22Jan2013-v1/20000/40F56410-D979-E211-9843-002618943849.root',
        iMaxEvent=100):

    ###--------------------------------------------------------------
    ### Load PAT, because it insists on defining the process for you
    #from PhysicsTools.PatAlgos.patTemplate_cfg import *
    ###--------------------------------------------------------------

    ###--------------------------------------------------------------
    ### Input
    process.maxEvents.input = iMaxEvent
    process.source.fileNames = [iFile]
    ###--------------------------------------------------------------

    ###--------------------------------------------------------------
    ### GlobalTag
    if iRunOnData == True:
        process.GlobalTag.globaltag = "FT53_V21A_AN6::All"
    else:
        process.GlobalTag.globaltag = "START53_V27::All"
    ###--------------------------------------------------------------

    ###--------------------------------------------------------------
    ### Logger
    process.load("FWCore.MessageService.MessageLogger_cfi")
    process.load("FWCore.MessageLogger.MessageLogger_cfi")
    process.MessageLogger.cerr.FwkReport = cms.untracked.PSet(
        reportEvery=cms.untracked.int32(2000),
        limit=cms.untracked.int32(10000000))
    ###--------------------------------------------------------------

    ###--------------------------------------------------------------
    ### L1 Trigger
    process.load('L1Trigger.Skimmer.l1Filter_cfi')
    process.l1Filter.algorithms = cms.vstring('L1_ETM40')
    ###--------------------------------------------------------------

    ###--------------------------------------------------------------
    ### HLT Trigger(s)
    # If it's MC signal, no trigger will be applied
    if iRunOnData == False and iMCSignal == True:
        iHLTFilter = "NoTrig"

    # Load hltHighLevel
    process.load('HLTrigger.HLTfilters.hltHighLevel_cfi')
    process.hltHighLevel.TriggerResultsTag = cms.InputTag(
        "TriggerResults", "", "HLT")
    process.hltHighLevel.throw = cms.bool(
        False)  # Tolerate if triggers not available
    process.hltHighLevel.andOr = cms.bool(True)  # True = OR, False = AND
    if (iRunOnData == True and iHLTFilter.find("MET") == 0):
        process.hltHighLevel.HLTPaths = cms.vstring(
            #"HLT_DiPFJet40_PFMETnoMu65_MJJ600VBF_LeadingJets_v*",
            #"HLT_DiPFJet40_PFMETnoMu65_MJJ800VBF_AllJets_v*"
            "HLT_DiJet35_MJJ700_AllJets_DEta3p5_VBF_v*",
            "HLT_DiJet30_MJJ700_AllJets_DEta3p5_VBF_v*")
    elif (iHLTFilter.find("SingleMu") == 0):
        process.hltHighLevel.HLTPaths = cms.vstring("HLT_IsoMu24_eta2p1_v*",
                                                    "HLT_Mu40_eta2p1_v*")
    #elif (iHLTFilter.find("DoubleMu")==0):
    #    process.hltHighLevel.HLTPaths = cms.vstring("HLT_Mu17_Mu8_v*")
    #elif (iHLTFilter.find("SingleElectron")==0):
    #    process.hltHighLevel.HLTPaths = cms.vstring("HLT_Ele27_WP80_v*")
    #elif (iHLTFilter.find("DoubleElectron")==0):
    #    process.hltHighLevel.HLTPaths = cms.vstring("HLT_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v*")
    elif (iHLTFilter.find("NoTrig") == 0):
        process.hltHighLevel.HLTPaths = cms.vstring("*")
    else:
        process.hltHighLevel.HLTPaths = cms.vstring(
            #"HLT_DiPFJet40_PFMETnoMu65_MJJ600VBF_LeadingJets_v*",
            #"HLT_DiPFJet40_PFMETnoMu65_MJJ800VBF_AllJets_v*"
            "HLT_DiJet35_MJJ700_AllJets_DEta3p5_VBF_v*",
            "HLT_DiJet30_MJJ700_AllJets_DEta3p5_VBF_v*")

    ### VBF filter for MC Background
    process.vbfFilter = cms.EDFilter("HLTPFJetVBFFilter",
                                     saveTags=cms.bool(True),
                                     triggerType=cms.int32(85),
                                     inputTag=cms.InputTag("ak5PFJets"),
                                     leadingJetOnly=cms.bool(False),
                                     minPtHigh=cms.double(25.0),
                                     minPtLow=cms.double(25.0),
                                     maxEta=cms.double(5.0),
                                     etaOpposite=cms.bool(True),
                                     minDeltaEta=cms.double(3.0),
                                     minInvMass=cms.double(500.0))

    ###--------------------------------------------------------------

    ###--------------------------------------------------------------
    print "-----------------------------------------------"
    print "INVISIBLE HIGGS: Ntuple V12 for Parked Data"
    print "-----------------------------------------------"
    print "RunOnData = ", iRunOnData
    if iRunOnData == True:
        print "Dataset = ", iData
    else:
        if iMCSignal == True:
            print "Dataset = MC Signal or DYNoTrig"
        else:
            print "Dataset = MC Background"
    print "GlobalTag = ", process.GlobalTag.globaltag
    print "Trigger = ", process.hltHighLevel.HLTPaths
    print "Sample input file = ", iFile
    print "Max events = ", iMaxEvent
    print "-----------------------------------------------"
    ###--------------------------------------------------------------

    ###--------------------------------------------------------------
    ### Basic filters
    # Track quality filter
    process.noscraping = cms.EDFilter("FilterOutScraping",
                                      applyfilter=cms.untracked.bool(True),
                                      debugOn=cms.untracked.bool(False),
                                      numtrack=cms.untracked.uint32(10),
                                      thresh=cms.untracked.double(0.25))

    # Require a good vertex
    process.primaryVertexFilter = cms.EDFilter(
        "VertexSelector",
        src=cms.InputTag("offlinePrimaryVertices"),
        cut=cms.string(
            "!isFake && ndof > 4 && abs(z) <= 24 && position.Rho <= 2"),
        filter=cms.bool(True))
    ###--------------------------------------------------------------

    ###--------------------------------------------------------------
    ### MET Filters
    # The iso-based HBHE noise filter
    process.load('CommonTools.RecoAlgos.HBHENoiseFilter_cfi')

    # The CSC beam halo tight filter
    process.load('RecoMET.METAnalyzers.CSCHaloFilter_cfi')

    # The HCAL laser filter
    process.load("RecoMET.METFilters.hcalLaserEventFilter_cfi")
    #process.load("EventFilter.HcalRawToDigi.hcallasereventfilter2012_cff")
    #process.hcallasereventfilter2012.eventFileName = cms.string('HCALLaser2012AllDatasets.txt.gz')
    process.load(
        "EventFilter.HcalRawToDigi.hcallaserFilterFromTriggerResult_cff")

    # The ECAL dead cell trigger primitive filter
    process.load('RecoMET.METFilters.EcalDeadCellTriggerPrimitiveFilter_cfi')

    # The EE bad SuperCrystal filter
    process.load('RecoMET.METFilters.eeBadScFilter_cfi')

    # The ECAL laser correction filter
    process.load('RecoMET.METFilters.ecalLaserCorrFilter_cfi')

    # The Good vertices collection needed by the tracking failure filter
    process.goodVertices = cms.EDFilter(
        "VertexSelector",
        filter=cms.bool(False),
        src=cms.InputTag("offlinePrimaryVertices"),
        cut=cms.string(
            "!isFake && ndof > 4 && abs(z) <= 24 && position.rho < 2"))

    # The tracking failure filter
    process.load('RecoMET.METFilters.trackingFailureFilter_cfi')

    # The tracking POG filters
    process.load('RecoMET.METFilters.trackingPOGFilters_cff')
    ###--------------------------------------------------------------

    ###--------------------------------------------------------------
    ### customise PAT
    process.load('JetMETCorrections.Configuration.DefaultJEC_cff')

    from PhysicsTools.PatAlgos.tools.coreTools import removeMCMatching, runOnData

    if iRunOnData == True:
        removeMCMatching(process, ['All'])
        runOnData(process)

    # Add the PF MET
    from PhysicsTools.PatAlgos.tools.metTools import addPfMET
    addPfMET(process, 'PF')

    # Switch to PF jets
    from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection
    if iRunOnData == True:
        switchJetCollection(process,
                            cms.InputTag('ak5PFJets'),
                            doJTA=True,
                            doBTagging=False,
                            jetCorrLabel=('AK5PF', [
                                'L1FastJet', 'L2Relative', 'L3Absolute',
                                'L2L3Residual'
                            ]),
                            doType1MET=True,
                            genJetCollection=cms.InputTag("ak5GenJets"),
                            doJetID=False,
                            jetIdLabel="ak5")
    else:
        switchJetCollection(
            process,
            cms.InputTag('ak5PFJets'),
            doJTA=True,
            doBTagging=False,
            jetCorrLabel=('AK5PF', ['L1FastJet', 'L2Relative', 'L3Absolute']),
            doType1MET=True,
            genJetCollection=cms.InputTag("ak5GenJets"),
            doJetID=False,
            jetIdLabel="ak5")

    from PhysicsTools.PatAlgos.tools.pfTools import usePFIso
    usePFIso(process)

    process.patMuons.isoDeposits = cms.PSet()
    process.patMuons.isolationValues = cms.PSet()
    process.patElectrons.isolationValues = cms.PSet(
        pfChargedHadrons=cms.InputTag("elPFIsoValueCharged03PFIdPFIso"),
        pfChargedAll=cms.InputTag("elPFIsoValueChargedAll03PFIdPFIso"),
        pfPUChargedHadrons=cms.InputTag("elPFIsoValuePU03PFIdPFIso"),
        pfNeutralHadrons=cms.InputTag("elPFIsoValueNeutral03PFIdPFIso"),
        pfPhotons=cms.InputTag("elPFIsoValueGamma03PFIdPFIso"))
    process.patElectrons.isolationValuesNoPFId = cms.PSet(
        pfChargedHadrons=cms.InputTag("elPFIsoValueCharged03NoPFIdPFIso"),
        pfChargedAll=cms.InputTag("elPFIsoValueChargedAll03NoPFIdPFIso"),
        pfPUChargedHadrons=cms.InputTag("elPFIsoValuePU03NoPFIdPFIso"),
        pfNeutralHadrons=cms.InputTag("elPFIsoValueNeutral03NoPFIdPFIso"),
        pfPhotons=cms.InputTag("elPFIsoValueGamma03NoPFIdPFIso"))
    process.patDefaultSequence.replace(
        process.patElectrons, process.eleIsoSequence + process.patElectrons)
    process.cleanPatTaus.preselection = cms.string(
        'tauID("decayModeFinding") > 0.5 & tauID("byLooseCombinedIsolationDeltaBetaCorr") > 0.5'
    )
    ###--------------------------------------------------------------

    ###--------------------------------------------------------------
    ### Object (pre) selection
    # Jet selection
    process.selectedPatJets.cut = cms.string("pt>10. && abs(eta)<5.")

    # Remove overlaps ???
    # process.cleanPatJets.finalCut = "!hasOverlaps('electrons') && !hasOverlaps('muons')"

    # Apply loose PF jet ID
    from PhysicsTools.SelectorUtils.pfJetIDSelector_cfi import pfJetIDSelector
    process.goodPatJets = cms.EDFilter("PFJetIDSelectionFunctorFilter",
                                       filterParams=pfJetIDSelector.clone(),
                                       src=cms.InputTag("selectedPatJets"),
                                       filter=cms.bool(True))

    process.selectedPatMuons.cut = cms.string(
        "isGlobalMuon && pt>10. && abs(eta)<2.5")

    process.selectedPatElectrons.cut = cms.string("pt>10. && abs(eta)<2.5")
    ###--------------------------------------------------------------

    ###--------------------------------------------------------------
    ### Load the PU JetID sequence
    if iRunOnData == True:
        process.load("CMGTools.External.pujetidsequence_cff")
        process.puJetMva.jets = cms.InputTag("goodPatJets")
        process.puJetId.jets = cms.InputTag("goodPatJets")
    else:
        process.load("CMGTools.External.pujetidsequence_cff")
        process.puJetMva.jets = cms.InputTag("goodPatJets")
        process.puJetId.jets = cms.InputTag("goodPatJets")
        process.puJetMvaSmeared = process.puJetMva.clone()
        process.puJetIdSmeared = process.puJetId.clone()
        process.puJetMvaResUp = process.puJetMva.clone()
        process.puJetIdResUp = process.puJetId.clone()
        process.puJetMvaResDown = process.puJetMva.clone()
        process.puJetIdResDown = process.puJetId.clone()
        process.puJetMvaEnUp = process.puJetMva.clone()
        process.puJetIdEnUp = process.puJetId.clone()
        process.puJetMvaEnDown = process.puJetMva.clone()
        process.puJetIdEnDown = process.puJetId.clone()

        process.puJetIdSmeared.jets = cms.InputTag("smearedGoodPatJets")
        process.puJetMvaSmeared.jetids = cms.InputTag("puJetIdSmeared")
        process.puJetMvaSmeared.jets = cms.InputTag("smearedGoodPatJets")

        process.puJetIdResUp.jets = cms.InputTag("smearedGoodPatJetsResUp")
        process.puJetMvaResUp.jetids = cms.InputTag("puJetIdResUp")
        process.puJetMvaResUp.jets = cms.InputTag("smearedGoodPatJetsResUp")

        process.puJetIdResDown.jets = cms.InputTag("smearedGoodPatJetsResDown")
        process.puJetMvaResDown.jetids = cms.InputTag("puJetIdResDown")
        process.puJetMvaResDown.jets = cms.InputTag(
            "smearedGoodPatJetsResDown")

        process.puJetIdEnUp.jets = cms.InputTag(
            "shiftedGoodPatJetsEnUpForCorrMEt")
        process.puJetMvaEnUp.jetids = cms.InputTag("puJetIdEnUp")
        process.puJetMvaEnUp.jets = cms.InputTag(
            "shiftedGoodPatJetsEnUpForCorrMEt")

        process.puJetIdEnDown.jets = cms.InputTag(
            "shiftedGoodPatJetsEnDownForCorrMEt")
        process.puJetMvaEnDown.jetids = cms.InputTag("puJetIdEnDown")
        process.puJetMvaEnDown.jets = cms.InputTag(
            "shiftedGoodPatJetsEnDownForCorrMEt")
    ###--------------------------------------------------------------

    ###--------------------------------------------------------------
    ### MET
    # Apply type 0 MET corrections based on PFCandidate
    process.load("JetMETCorrections.Type1MET.pfMETCorrectionType0_cfi")
    process.pfType1CorrectedMet.applyType0Corrections = cms.bool(False)
    process.pfType1CorrectedMet.srcType1Corrections = cms.VInputTag(
        cms.InputTag('pfMETcorrType0'), cms.InputTag('pfJetMETcorr', 'type1'))

    # Get loose ID/Iso muons and veto ID electrons
    process.load("InvisibleHiggs.Ntuple.PhysicsObjectCandidates_cff")

    # Get PFMET from runMEtUncertainties
    from PhysicsTools.PatUtils.tools.metUncertaintyTools import runMEtUncertainties
    process.load("JetMETCorrections.Type1MET.pfMETsysShiftCorrections_cfi")

    if iRunOnData == True:
        runMEtUncertainties(
            process,
            electronCollection=cms.InputTag('selectVetoElectrons'),
            photonCollection='',
            muonCollection='selectLooseMuons',
            tauCollection='',
            jetCollection=cms.InputTag('goodPatJets'),
            jetCorrLabel='L2L3Residual',
            doSmearJets=False,
            makeType1corrPFMEt=True,
            makeType1p2corrPFMEt=False,
            makePFMEtByMVA=False,
            makeNoPileUpPFMEt=False,
            doApplyType0corr=True,
            sysShiftCorrParameter=process.
            pfMEtSysShiftCorrParameters_2012runAvsNvtx_data,
            doApplySysShiftCorr=False,
            addToPatDefaultSequence=False,
        )
        process.patPFJetMETtype1p2Corr.jetCorrLabel = cms.string(
            'L2L3Residual')
        process.patPFJetMETtype2Corr.jetCorrLabel = cms.string('L2L3Residual')
    else:
        runMEtUncertainties(
            process,
            electronCollection=cms.InputTag('selectVetoElectrons'),
            photonCollection='',
            muonCollection='selectLooseMuons',
            tauCollection='',
            jetCollection=cms.InputTag('goodPatJets'),
            jetCorrLabel='L3Absolute',
            doSmearJets=True,
            makeType1corrPFMEt=True,
            makeType1p2corrPFMEt=False,
            makePFMEtByMVA=False,
            makeNoPileUpPFMEt=False,
            doApplyType0corr=True,
            sysShiftCorrParameter=process.
            pfMEtSysShiftCorrParameters_2012runAvsNvtx_mc,
            doApplySysShiftCorr=False,
            addToPatDefaultSequence=False,
        )

    # Fix Type0 correction module
    #process.patPFMETtype0Corr.correction.par3 = cms.double(0.909209)
    #process.patPFMETtype0Corr.correction.par2 = cms.double(0.0303531)
    #process.patPFMETtype0Corr.correction.par1 = cms.double(-0.703151)
    #process.patPFMETtype0Corr.correction.par0 = cms.double(0.0)
    # Need this line for CMSSW_5_3_11
    process.producePatPFMETCorrections.replace(
        process.patPFJetMETtype2Corr, process.patPFJetMETtype2Corr +
        process.type0PFMEtCorrectionPFCandToVertexAssociation +
        process.patPFMETtype0Corr)
    #process.producePatPFMETCorrections.replace(process.patPFJetMETtype2Corr,process.patPFJetMETtype2Corr + process.patPFMETtype0Corr)
    ###--------------------------------------------------------------

    # PAT/ntuples one step
    # Z and W candidates
    process.load('InvisibleHiggs/Ntuple/WCandidates_cff')
    process.load('InvisibleHiggs/Ntuple/ZCandidates_cff')
    # Ntuple producer
    process.load('InvisibleHiggs/Ntuple/invHiggsInfo_cfi')
    if iRunOnData == False:
        # Jet/MET uncertainty
        process.invHiggsInfo.jetTag = cms.untracked.InputTag(
            "smearedGoodPatJets")
        process.invHiggsInfo.metTag = cms.untracked.InputTag(
            "patType1CorrectedPFMet")
        process.invHiggsInfo.puJetMvaTag = cms.untracked.InputTag(
            "puJetMvaSmeared", "full53xDiscriminant")
        process.invHiggsInfo.puJetIdTag = cms.untracked.InputTag(
            "puJetMvaSmeared", "full53xId")

        # PU re-weighting
        process.invHiggsInfo.puMCFile = cms.untracked.string("PUHistS10.root")
        process.invHiggsInfo.puDataFile = cms.untracked.string(
            "PUHistRun2012All_forParked.root")
        process.invHiggsInfo.puMCHist = cms.untracked.string("pileup")
        process.invHiggsInfo.puDataHist = cms.untracked.string("pileup")
        process.invHiggsInfo.mcPYTHIA = cms.untracked.bool(True)

        process.invHiggsInfo.trigCorrFile = cms.untracked.string(
            "DataMCWeight_53X_v1.root")
    # TTree output file
    process.load("CommonTools.UtilAlgos.TFileService_cfi")
    process.TFileService.fileName = cms.string('invHiggsInfo.root')
    ###--------------------------------------------------------------

    ###--------------------------------------------------------------
    ### Tau
    # removeSpecificPATObjects( process, ['Taus'] )
    # process.patDefaultSequence.remove( process.patTaus )
    process.load("RecoTauTag.Configuration.RecoPFTauTag_cff")
    ###--------------------------------------------------------------

    ###--------------------------------------------------------------
    ### Trigger matching
    # from PhysicsTools.PatAlgos.tools.trigTools import *

    # process.metTriggerMatch = cms.EDProducer(
    #     "PATTriggerMatcherDRLessByR"                    # match by DeltaR only, best match by DeltaR
    #     , src     = cms.InputTag( 'patMETs' )
    #     , matched = cms.InputTag( 'patTrigger' )          # default producer label as defined in PhysicsTools/PatAlgos/python/triggerLayer1/triggerProducer_cfi.py
    #     , matchedCuts = cms.string( 'path( "HLT_MET100_v*" )' )
    #     , maxDPtRel = cms.double( 0.5 )
    #     , maxDeltaR = cms.double( 0.5 )
    #     , resolveAmbiguities    = cms.bool( True )        # only one match per trigger object
    #     , resolveByMatchQuality = cms.bool( True )        # take best match found per reco object: by DeltaR here (s. above)
    # )
    # process.jetTriggerMatch = cms.EDProducer(
    #     "PATTriggerMatcherDRLessByR"                    # match by DeltaR only, best match by DeltaR
    #     , src     = cms.InputTag( 'patJets' )
    #     , matched = cms.InputTag( 'patTrigger' )          # default producer label as defined in PhysicsTools/PatAlgos/python/triggerLayer1/triggerProducer_cfi.py
    #     , matchedCuts = cms.string( 'path( "HLT_Jet30_v*" )' )
    #     , maxDPtRel = cms.double( 0.5 )
    #     , maxDeltaR = cms.double( 0.5 )
    #     , resolveAmbiguities    = cms.bool( True )        # only one match per trigger object
    #     , resolveByMatchQuality = cms.bool( True )        # take best match found per reco object: by DeltaR here (s. above)
    # )

    # switchOnTriggerMatchEmbedding( process, [ 'metTriggerMatch', 'jetTriggerMatch' ] )
    ###--------------------------------------------------------------

    ###--------------------------------------------------------------
    ### Paths
    process.p0 = cms.Path(process.HBHENoiseFilter)
    process.p1 = cms.Path(process.CSCTightHaloFilter)
    process.p2 = cms.Path(process.hcalLaserEventFilter)
    process.p3 = cms.Path(process.EcalDeadCellTriggerPrimitiveFilter)
    process.p4 = cms.Path(process.eeBadScFilter)
    process.p5 = cms.Path(process.ecalLaserCorrFilter)
    process.p6 = cms.Path(process.goodVertices * process.trackingFailureFilter)
    process.p7 = cms.Path(process.trkPOGFilters)
    if iRunOnData == True:
        #process.p8 = cms.Path( process.hcallLaserEvent2012Filter )
        process.p8 = cms.Path(process.hcalfilter)
    else:
        process.p8 = cms.Path(process.primaryVertexFilter)

    if iRunOnData == True:
        process.p = cms.Path(
            # Trigger filter
            process.l1Filter * process.hltHighLevel *

            # Basic filters
            process.noscraping * process.primaryVertexFilter *

            # MET filters (Move to be flagged)

            # MET Correction
            process.type0PFMEtCorrection *

            # Tau
            process.recoTauClassicHPSSequence *

            # Generate PAT
            process.pfParticleSelectionSequence * process.patDefaultSequence *
            process.goodPatJets * process.PhysicsObjectSequence *
            process.metUncertaintySequence * process.puJetIdSqeuence *
            process.WSequence * process.ZSequence * process.invHiggsInfo)
    elif (iMCSignal == True):
        process.p = cms.Path(
            # Trigger filter
            #process.hltHighLevel *

            # Basic filters
            process.noscraping * process.primaryVertexFilter *

            # MET filters (Move to be flags)

            # MET Correction
            process.type0PFMEtCorrection *

            # Tau
            process.recoTauClassicHPSSequence *

            # Generate PAT
            process.pfParticleSelectionSequence * process.patDefaultSequence *
            process.goodPatJets * process.PhysicsObjectSequence *
            process.metUncertaintySequence * process.puJetIdSqeuence *
            process.puJetIdSmeared * process.puJetMvaSmeared *
            process.puJetIdResUp * process.puJetMvaResUp *
            process.puJetIdResDown * process.puJetMvaResDown *
            process.puJetIdEnUp * process.puJetMvaEnUp *
            process.puJetIdEnDown * process.puJetMvaEnDown *
            process.WSequence * process.ZSequence * process.invHiggsInfo)
    else:
        process.p = cms.Path(
            # Trigger filter
            #process.hltHighLevel *
            process.vbfFilter *

            # Basic filters
            process.noscraping * process.primaryVertexFilter *

            # MET filters (Move to be flags)

            # MET Correction
            process.type0PFMEtCorrection *

            # Tau
            process.recoTauClassicHPSSequence *

            # Generate PAT
            process.pfParticleSelectionSequence * process.patDefaultSequence *
            process.goodPatJets * process.PhysicsObjectSequence *
            process.metUncertaintySequence * process.puJetIdSqeuence *
            process.puJetIdSmeared * process.puJetMvaSmeared *
            process.puJetIdResUp * process.puJetMvaResUp *
            process.puJetIdResDown * process.puJetMvaResDown *
            process.puJetIdEnUp * process.puJetMvaEnUp *
            process.puJetIdEnDown * process.puJetMvaEnDown *
            process.WSequence * process.ZSequence * process.invHiggsInfo)
    ###--------------------------------------------------------------

    ###--------------------------------------------------------------
    ### Output
    process.out.outputCommands += [
        # trigger results
        'keep edmTriggerResults_*_*_*',
        'keep *_hltTriggerSummaryAOD_*_*'
        # L1
        ,
        'keep *_l1extraParticles_MET_RECO',
        'keep *_l1extraParticles_MHT_RECO'
        # good jets
        ,
        'keep *_goodPatJets_*_*'
        # PU jet ID
        ,
        'keep *_puJetId*_*_*',
        'keep *_puJetMva*_*_*'
        # vertices
        ,
        'keep *_offlineBeamSpot_*_*',
        'keep *_offlinePrimaryVertices*_*_*',
        'keep *_goodOfflinePrimaryVertices*_*_*',
        'keep double_*_rho_*'
    ]

    if iRunOnData == False:
        process.out.outputCommands += [
            'keep GenEventInfoProduct_*_*_*', 'keep recoGenParticles_*_*_*',
            'keep GenMETs_*_*_*', 'keep *_addPileupInfo_*_*',
            'keep LHEEventProduct_*_*_*'
        ]

    process.out.fileName = 'patTuple.root'

    del (process.out)
    del (process.outpath)
Esempio n. 42
0
if runStandardPAT:
    if not runOnMC:
        runOnData(process)
    # subsequent jet area calculations needed for L1FastJet on RECO jets
    if useCaloJets and useL1FastJet:
        if useRelVals:
            process.ak5CaloJets = ak5CaloJets.clone(doAreaFastjet=True)
            process.ak5JetID = ak5JetID.clone()
            process.ak5CaloJetSequence = cms.Sequence(process.ak5CaloJets *
                                                      process.ak5JetID)
            from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection
            switchJetCollection(process,
                                cms.InputTag(jetAlgo.lower() + 'CaloJets'),
                                doJTA=True,
                                doBTagging=True,
                                jetCorrLabel=(jecSet, jecLevels),
                                doType1MET=False,
                                genJetCollection=cms.InputTag(jetAlgo.lower() +
                                                              'GenJets'),
                                doJetID=True)
        else:
            print 'WARNING patRefSel_muJets_test_cfg.py:'
            print '        L1FastJet JECs are not available for AK5Calo jets in this data due to missing jet area computation;'
            print '        switching to   L1Offset   !!!'
            jecLevelsCalo.insert(0, 'L1Offset')
            jecLevelsCalo.remove('L1FastJet')
            process.patJetCorrFactors.levels = jecLevelsCalo
            #process.patJetCorrFactors.useRho = False # FIXME: does not apply
    if usePFJets:
        if useL1FastJet:
            process.ak5PFJets = ak5PFJets.clone(doAreaFastjet=True)
## import skeleton process
from PhysicsTools.PatAlgos.patTemplate_cfg import *

process.load("PhysicsTools.PatAlgos.producersLayer1.patCandidates_cff")
patAlgosToolsTask.add(process.patCandidatesTask)
#Temporary customize to the unit tests that fail due to old input samples
process.patTaus.skipMissingTauID = True

process.load("PhysicsTools.PatAlgos.selectionLayer1.selectedPatCandidates_cff")
patAlgosToolsTask.add(process.selectedPatCandidatesTask)

process.load("PhysicsTools.PatUtils.patPFMETCorrections_cff")

from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection
switchJetCollection(process,
                    jetSource = cms.InputTag('ak4PFJets'),
                    jetCorrections = ('AK4PF', ['L1FastJet', 'L2Relative', 'L3Absolute'], '')
                    )

# apply type I PFMEt corrections to pat::MET object
# and estimate systematic uncertainties on MET
from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMETCorrectionsAndUncertainties

runMETCorrectionsAndUncertainties(process, metType="PF",
                                  correctionLevel=["T1"],
                                  computeUncertainties=True,
                                  produceIntermediateCorrections=False,
                                  addToPatDefaultSequence=False,
                                  jetCollectionUnskimmed="patJets",
                                  jetSelection="pt>15 && abs(eta)<9.9",
                                  postfix="",
                                  )
Esempio n. 44
0
    process,
    labelName = 'AK15PFCHS',
    jetSource = cms.InputTag('ak15PFJetsCHS'),
    algo = 'ak15',
    rParam = 1.5,
    jetCorrections = ('AK10PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
    trackSource = cms.InputTag('unpackedTracksAndVertices'),
    pvSource = cms.InputTag('unpackedTracksAndVertices'),
    btagDiscriminators = ['combinedSecondaryVertexBJetTags'],
    )

switchJetCollection(
    process,
    jetSource = cms.InputTag('ak4PFJets'),
    algo = 'ak4',
    rParam = 0.4,
    jetCorrections = ('AK4PF', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'Type-1'),
    trackSource = cms.InputTag('unpackedTracksAndVertices'),
    pvSource = cms.InputTag('unpackedTracksAndVertices'),
    #btagDiscriminators = ['combinedSecondaryVertexBJetTags'],   #this breaks the config
    )

for module in [process.patJetsAK4PFCHS, process.patJetsAK8PFCHS, process.patJetsAK10PFCHS, process.patJetsAK12PFCHS, process.patJetsAK15PFCHS]:
    module.addJetCharge   = False
    module.addBTagInfo    = True   
    module.getJetMCFlavour = False
    module.addAssociatedTracks = False

for module in [process.patJetPartonMatch, process.patJetPartonMatchAK4PFCHS, process.patJetPartonMatchAK8PFCHS, process.patJetPartonMatchAK10PFCHS, process.patJetPartonMatchAK12PFCHS, process.patJetPartonMatchAK15PFCHS]:
    module.matched='prunedGenParticles'

for module in [process.patJetCorrFactors, process.patJetCorrFactorsAK4PFCHS, process.patJetCorrFactorsAK8PFCHS, process.patJetCorrFactorsAK10PFCHS, process.patJetCorrFactorsAK12PFCHS, process.patJetCorrFactorsAK15PFCHS]:
def addTagInfos(process, jetMetCorrections):
    from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection
    switchJetCollection(process,
                        jetCollection=cms.InputTag('ak5CaloJets'),
                        jetCorrLabel=('AK5Calo', jetMetCorrections))
def configurePatTuple(process, isMC=True, **kwargs):
    '''
    Core function for PATTuple production
    '''
    #fix argparser output
    isMC = bool(isMC)

    ########################
    ##                    ##
    ##  PATTuple content  ##
    ##                    ##
    ########################
    # Stuff we always keep
    output_commands = [
        '*_addPileupInfo_*_*',
        'edmMergeableCounter_*_*_*',
        '*_lumiProducer_*_*',
        '*_particleFlow_*_*',
        '*_offlineBeamSpot_*_*',
        '*_generalTracks_*_*',
        '*_electronGsfTracks_*_*',
        '*_gsfElectrons_*_*',
        '*_gsfElectronCores_*_*',
        '*_offlinePrimaryVertices*_*_*',
        '*_ak5GenJets_*_*',
        '*_hltTriggerSummaryAOD_*_*',
        'edmTriggerResults_TriggerResults_*_%s' % process.name_(),
        '*_MEtoEDMConverter*_*_%s' % process.name_(),
        'LHEEventProduct_*_*_*',
        'GenEventInfoProduct_generator_*_*',
        '*_kt6PFJetsForRhoComputationVoronoi_rho_*',
        '*_kt6PFJetsForIso_rho_*',
        '*_kt6PFJets_rho_*',
        '*_kt6PFJetsHZGPho_rho_*',
        '*_kt6PFJetsCentralHZGEle_rho_*',
        '*_kt6PFJetsCentralHZGMu_rho_*',
        '*_kt6PFJetsCentralNeutralHZGMu_rho_*',
        '*_kt6PFJetsCentral_rho_*',
        '*_kt6PFJetsCentralNeutral_rho_*',  # for zz muons
        '*_photonCore_*_*',
        '*_boostedFsrPhotons_*_*',
        # for Zmumu -> embedded samples
        # https://twiki.cern.ch/twiki/bin/view/CMS/MuonTauReplacementRecHit
        '*_generalTracksORG_*_EmbeddedRECO',
        '*_electronGsfTracksORG_*_EmbeddedRECO',
        'double_TauSpinnerReco_TauSpinnerWT_EmbeddedSPIN',
        'double_ZmumuEvtSelEffCorrWeightProducer_weight_EmbeddedRECO',
        'double_muonRadiationCorrWeightProducer_weight_EmbeddedRECO',
        'GenFilterInfo_generator_minVisPtFilter_EmbeddedRECO',
    ]
    # Define our patTuple production sequence
    process.tuplize = cms.Sequence()
    # Only keep interesting genParticles
    process.load("FinalStateAnalysis.RecoTools.genParticleTrimmer_cfi")
    process.genParticles = process.prunedGenParticles.clone()
    if isMC:
        #process.tuplize += process.genParticles
        #output_commands.append('*_genParticles_*_%s' % process.name_())
        output_commands.append('*_genParticles_*_*')

    output_commands.append('*_tauGenJetsSelectorAllHadrons_*_*')
    output_commands.append('*_tauGenJets_*_*')
    output_commands.append('*_ak5GenJets_*_*')

    ########################
    ##                    ##
    ##        PAT         ##
    ##                    ##
    ########################

    # Run pat default sequence
    process.load("PhysicsTools.PatAlgos.patSequences_cff")

    # Embed PF Isolation in electrons & muons
    pfTools.usePFIso(process)
    # Setup H2Tau custom iso definitions
    setup_h2tau_iso(process)
    # Setup hZg custom iso definitions
    add_hZg_iso_needs(process)

    # Now run PAT
    process.tuplize += process.patDefaultSequence

    # Add FSR photons for ZZ analysis
    process.load("FinalStateAnalysis.PatTools.fsrPhotons_cff")
    process.tuplize += process.fsrPhotonSequence

    ########################
    ##        GEN         ##
    ########################

    # Disable gen match embedding - we keep it in the ntuple
    process.patMuons.embedGenMatch = False
    process.patElectrons.embedGenMatch = False
    process.patTaus.embedGenMatch = False
    process.patTaus.embedGenJetMatch = False
    process.patPhotons.embedGenMatch = False
    if not isMC:
        coreTools.runOnData(process)

    ########################
    ##       MUONS        ##
    ########################

    # Unembed junk
    process.patMuons.embedCaloMETMuonCorrs = False
    process.patMuons.embedTcMETMuonCorrs = False
    process.patMuons.embedTrack = True
    process.patMuons.pvSrc = cms.InputTag("selectedPrimaryVertex")

    process.load("FinalStateAnalysis.PatTools.patMuonProduction_cff")
    final_muon_collection = chain_sequence(
        process.customizeMuonSequence, "selectedPatMuons")
    process.customizeMuonSequence.insert(0, process.selectedPatMuons)
    process.patDefaultSequence.replace(process.selectedPatMuons,
                                       process.customizeMuonSequence)
    process.cleanPatMuons.src = final_muon_collection
    process.patMuonRochesterCorrectionEmbedder.isMC = cms.bool(bool(isMC))

    ########################
    ##        TAUS        ##
    ########################

    # Use HPS taus
    tautools.switchToPFTauHPS(process) #this NEEDS a sequence called patDefaultSequence
    # Disable tau IsoDeposits
    process.patDefaultSequence.remove(process.patPFTauIsolation)
    process.patTaus.isoDeposits = cms.PSet()
    process.patTaus.userIsolation = cms.PSet()

    process.load("FinalStateAnalysis.PatTools.patTauProduction_cff")
    # Require all taus to pass decay mode finding and have high PT
    process.patTauGarbageRemoval.cut = cms.string(
        "pt > 17 && abs(eta) < 2.5 && tauID('decayModeFindingNewDMs')")
    final_tau_collection = chain_sequence(
        process.customizeTauSequence, "selectedPatTaus")
    # Inject into the pat sequence
    process.customizeTauSequence.insert(0, process.selectedPatTaus)
    process.patDefaultSequence.replace(process.selectedPatTaus,
                                       process.customizeTauSequence)
    process.cleanPatTaus.src = final_tau_collection
    # Remove muons and electrons
    process.cleanPatTaus.checkOverlaps.muons.requireNoOverlaps = False
    process.cleanPatTaus.checkOverlaps.electrons.requireNoOverlaps = False
    # Cuts already applied by the garbage removal
    process.cleanPatTaus.preselection = ''
    process.cleanPatTaus.finalCut = ''

    ########################
    ##     ELECTRONS      ##
    ########################

    # Use POG recommendations for (these) electron Isos
    process.elPFIsoValueGamma04PFIdPFIso.deposits[0].vetos = cms.vstring(
        'EcalEndcaps:ConeVeto(0.08)')
    process.elPFIsoValueGamma04NoPFIdPFIso.deposits[0].vetos = cms.vstring(
        'EcalEndcaps:ConeVeto(0.08)')
    process.elPFIsoValueCharged04PFIdPFIso.deposits[0].vetos = cms.vstring(
        'EcalEndcaps:ConeVeto(0.015)')
    process.elPFIsoValueCharged04NoPFIdPFIso.deposits[0].vetos = cms.vstring(
        'EcalEndcaps:ConeVeto(0.015)')

    # Do extra electron ID
    process.load("FinalStateAnalysis.PatTools.electrons.electronID_cff")
    if cmssw_major_version() == 4:
        process.patDefaultSequence.replace(process.patElectrons,
                                           process.recoElectronID42X +
                                           process.patElectrons)
        process.patElectrons.electronIDSources = process.electronIDSources42X
    else:
        process.patDefaultSequence.replace(process.patElectrons,
                                           process.recoElectronID5YX +
                                           process.patElectrons)
        process.patElectrons.electronIDSources = process.electronIDSources5YX

    process.electronMatch.checkCharge = cms.bool(False)
    process.patElectrons.embedTrack = False
    process.patElectrons.embedPFCandidate = False
    process.patElectrons.embedGsfElectronCore = False
    process.patElectrons.embedSuperCluster = True

    # Produce the electron collections
    process.load("FinalStateAnalysis.PatTools.patElectronProduction_cff")

    # Electron Energy Regression and Calibrations
    process.load(
        "EgammaAnalysis.ElectronTools.electronRegressionEnergyProducer_cfi")
    process.load("EgammaAnalysis.ElectronTools.calibratedPatElectrons_cfi")

    #setup the energy regression for the specific dataset
    if kwargs['eleReg']:
        print "-- Applying Electron Regression and Calibration --"

        process.customizeElectronSequence += process.eleRegressionEnergy
        process.customizeElectronSequence += process.calibratedPatElectrons

        process.eleRegressionEnergy.energyRegressionType = cms.uint32(2)
        process.calibratedPatElectrons.correctionsType = cms.int32(2)

        if isMC:
            process.calibratedPatElectrons.inputDataset = cms.string(
                "Summer12_LegacyPaper")
        else:
            process.calibratedPatElectrons.inputDataset = cms.string(
                "22Jan2013ReReco")

        process.calibratedPatElectrons.combinationType = cms.int32(3)
        process.calibratedPatElectrons.lumiRatio = cms.double(1.0)
        process.calibratedPatElectrons.synchronization = cms.bool(True)
        process.calibratedPatElectrons.isMC = cms.bool(isMC == 1)
        process.calibratedPatElectrons.verbose = cms.bool(False)

    final_electron_collection = chain_sequence(
        process.customizeElectronSequence, "selectedPatElectrons",
        # Some of the EGamma modules have non-standard src InputTags,
        # specify them here.
        ("src", "inputPatElectronsTag", "inputElectronsTag")
    )

    #process.tuplize += process.customizeElectronSequence #why do we need this?
    process.customizeElectronSequence.insert(0, process.selectedPatElectrons)
    process.patDefaultSequence.replace(process.selectedPatElectrons,
                                       process.customizeElectronSequence)
    # We have to do the pat Jets before the pat electrons since we embed them
    process.customizeElectronSequence.insert(0, process.selectedPatJets)

    # Define cleanPatElectrons input collection
    process.cleanPatElectrons.src = final_electron_collection

    # Define the default lepton cleaning
    process.cleanPatElectrons.preselection = cms.string(
        'pt > 5')
    process.cleanPatElectrons.checkOverlaps.muons.requireNoOverlaps = False
    # Make sure we don't kill any good taus by calling them electrons
    # Note that we don't actually remove these overlaps.
    process.cleanPatElectrons.checkOverlaps.taus = cms.PSet(
        src=final_tau_collection,
        algorithm=cms.string("byDeltaR"),
        preselection=cms.string(
            "tauID('decayModeFinding') > 0.5 &&"
            "tauID('byLooseCombinedIsolationDeltaBetaCorr') > 0.5 &&"
            "tauID('againstElectronLoose') > 0.5 && "
            "pt > 10"
        ),
        deltaR=cms.double(0.1),
        checkRecoComponents=cms.bool(False),
        pairCut=cms.string(""),
        requireNoOverlaps=cms.bool(False),
    )

    ########################
    ##        JETS        ##
    ########################

    # Use PFJets and turn on JEC
    jec = ['L1FastJet', 'L2Relative', 'L3Absolute']
    # If we are running on data (not MC), or embedded sample,
    # apply the MC-DATA residual correction.
    if not isMC or kwargs['embedded']:
        jec.extend(['L2L3Residual'])

    # tmp
    # define the b-tag squences for offline reconstruction
    process.load("RecoBTag.SecondaryVertex.secondaryVertex_cff")
    process.load("RecoBTau.JetTagComputer.combinedMVA_cff")
    process.load('RecoVertex/AdaptiveVertexFinder/inclusiveVertexing_cff')
    process.load('RecoBTag/SecondaryVertex/bToCharmDecayVertexMerger_cfi')
    #process.load("PhysicsTools.PatAlgos.patSequences_cff")

    # Define options for BTagging - these are release dependent.
    btag_options = {'doBTagging': True}
    if cmssw_major_version() == 5:
        btag_options['btagInfo'] = [
            'impactParameterTagInfos',
            'secondaryVertexTagInfos',
            'softMuonTagInfos',
            'secondaryVertexNegativeTagInfos',
            'inclusiveSecondaryVertexFinderFilteredTagInfos'
        ]
        btag_options['btagdiscriminators'] = [
            'trackCountingHighEffBJetTags',
            'trackCountingHighPurBJetTags',    
            'simpleSecondaryVertexHighEffBJetTags',
            'simpleSecondaryVertexHighPurBJetTags',
            'simpleInclusiveSecondaryVertexHighEffBJetTags',
            'simpleInclusiveSecondaryVertexHighPurBJetTags',        
            'combinedSecondaryVertexMVABJetTags',
            'combinedSecondaryVertexBJetTags',
            'jetBProbabilityBJetTags', 
            'jetProbabilityBJetTags',   
        ]

    #Avoid embedding
    process.patJets.embedPFCandidates = True
    process.patJets.embedCaloTowers = False
    process.patJets.embedGenJetMatch = True
    process.patJets.addAssociatedTracks = True
    process.patJets.embedGenPartonMatch = True

    # Add AK5chs PFJets
    jettools.addJetCollection(
        process,
        cms.InputTag('ak5PFchsJets'),
        algoLabel = "AK5",
        typeLabel = "PFchs",
        doJTA              = True,
        jetCorrLabel       = ('AK5PFchs', jec),
        doType1MET         = False,
        doL1Cleaning       = False,
        doL1Counters       = False,
        genJetCollection   = cms.InputTag('ak5GenJets'),
        doJetID            = True,
        **btag_options
    )

    # Use AK5 PFJets
    jettools.switchJetCollection(
        process,
        cms.InputTag('ak5PFJets'),
        doJTA=True,
        jetCorrLabel=('AK5PF', jec),
        #jetCorrLabel = None,
        doType1MET=False,
        doJetID=True,
        genJetCollection=cms.InputTag("ak5GenJets"),
        **btag_options
    )

    # Customize/embed all our sequences
    process.load("FinalStateAnalysis.PatTools.patJetProduction_cff")
    helpers.cloneProcessingSnippet( process, process.customizeJetSequence, 'AK5PFchs' )
    process.patJetGarbageRemoval.cut = 'pt > 12'
    final_jet_collection = chain_sequence(
        process.customizeJetSequence, "patJets")
    process.customizeJetSequence.insert(0, process.patJets)
    # Make it a "complete" sequence
    process.customizeJetSequence += process.selectedPatJets
#    process.customizeJetSequence += process.btagging
    # We can't mess up the selected pat jets because the taus use them.
    process.selectedPatJets.src = final_jet_collection
    process.patDefaultSequence.replace(process.patJets,
                                       process.customizeJetSequence)

    process.customizeJetSequenceAK5PFchs.remove( process.patJetsPUIDAK5PFchs )
    process.customizeJetSequenceAK5PFchs.remove( process.pileupJetIdProducerAK5PFchs )
    process.patJetGarbageRemovalAK5PFchs.cut = 'pt > 20'
    process.patJetCorrFactorsAK5PFchs.payload = cms.string('AK5PFchs') 
    final_jetchs_collection = chain_sequence(
        process.customizeJetSequenceAK5PFchs, "patJetsAK5PFchs")
    process.customizeJetSequenceAK5PFchs.insert(0, process.patJetsAK5PFchs)
    # Make it a "complete" sequence
    process.customizeJetSequenceAK5PFchs += process.selectedPatJetsAK5PFchs
    # We can't mess up the selected pat jets because the taus use them.
    process.selectedPatJetsAK5PFchs.src = final_jetchs_collection
    process.selectedPatJetsAK5chsPF  = process.selectedPatJetsAK5PFchs.clone() #that's what we keep
    process.customizeJetSequenceAK5PFchs += process.selectedPatJetsAK5chsPF
    process.patDefaultSequence.replace(process.patJetsAK5PFchs,
                                       process.customizeJetSequenceAK5PFchs)

    output_commands.append('*_selectedPatJets_*_*')
    output_commands.append('*_selectedPatJetsAK5chsPF_*_*')
    output_commands.append('*SecondaryVertexTagInfo*_*_*_*')
    output_commands.append('*TrackIPTagInfo*_*_*_*')
    output_commands.append('*SoftLeptonTagInfo*_*_*_*')
    output_commands.append('*_ak5PFJets_*_*')
    output_commands.append('*_ak5PFchsJets_*_*')

    ########################
    ##        MET         ##
    ########################

    # Use PFMEt
    mettools.addPfMET(process)

    # We cut out a lot of the junky taus and jets - but we need these
    # to correctly apply the MET uncertainties.  So, let's make a
    # non-cleaned version of the jet and tau sequence.
    process.jetsForMetSyst = helpers.cloneProcessingSnippet(
        process, process.customizeJetSequence, 'ForMETSyst')
    process.tausForMetSyst = helpers.cloneProcessingSnippet(
        process, process.customizeTauSequence, 'ForMETSyst')
    # Don't apply any cut for these
    process.patTauGarbageRemovalForMETSyst.cut = ''
    process.patJetGarbageRemovalForMETSyst.cut = ''
    process.tuplize += process.jetsForMetSyst
    process.tuplize += process.tausForMetSyst
    # We have to make our clone of cleanPatTaus separately, since e/mu
    # cleaning is applied - therefore it isn't in the customizeTausSequence.
    process.cleanPatTausForMETSyst = process.cleanPatTaus.clone(
        src=cms.InputTag(process.cleanPatTaus.src.value() + "ForMETSyst"))
    process.cleanPatTausForMETSyst.preselection = ''
    process.cleanPatTausForMETSyst.finalCut = ''
    process.patTausEmbedJetInfoForMETSyst.jetSrc = \
        final_jet_collection.value() + "ForMETSyst"
    process.tuplize += process.cleanPatTausForMETSyst

    # Setup MET production
    process.load("FinalStateAnalysis.PatTools.patMETProduction_cff")
    # The MET systematics depend on all other systematics
    process.systematicsMET.tauSrc = cms.InputTag("cleanPatTausForMETSyst")
    process.systematicsMET.muonSrc = cms.InputTag("cleanPatMuons")
    process.systematicsMET.electronSrc = cms.InputTag("cleanPatElectrons")

    final_met_collection = chain_sequence(
        process.customizeMETSequence, "patMETsPF")
    process.tuplize += process.customizeMETSequence
    process.patMETsPF.addGenMET = bool(isMC)
    output_commands.append('*_%s_*_*' % final_met_collection.value())

    # Make a version with the MVA MET reconstruction method
    process.load("FinalStateAnalysis.PatTools.met.mvaMetOnPatTuple_cff")
    process.tuplize += process.pfMEtMVAsequence
    mva_met_sequence = helpers.cloneProcessingSnippet(
        process, process.customizeMETSequence, "MVA")
    final_mvamet_collection = chain_sequence(
        mva_met_sequence, "patMEtMVA")
    process.tuplize += mva_met_sequence
    output_commands.append('*_%s_*_*' % final_mvamet_collection.value())

    # Keep all the data formats needed for the systematics
    output_commands.append('recoLeafCandidates_*_*_%s'
                           % process.name_())
    # We can drop to jet and tau MET specific products. They were only used for
    # computation of the MET numbers.
    output_commands.append('drop recoLeafCandidates_*ForMETSyst_*_%s'
                           % process.name_())

    ########################
    ##      PHOTONS       ##
    ########################

    #alter the photon matching to accept various fakes
    # and sort matches by d-pt-rel
    if isMC:
        process.photonMatch = cms.EDProducer(
            "MCMatcherByPt",
            src=cms.InputTag("photons"),
            maxDPtRel=cms.double(100.0),
            mcPdgId=cms.vint32(),
            mcStatus=cms.vint32(1),
            resolveByMatchQuality=cms.bool(False),
            maxDeltaR=cms.double(0.3),
            checkCharge=cms.bool(False),
            resolveAmbiguities=cms.bool(True),
            matched=cms.InputTag("genParticles")
        )

    # Setup pat::Photon Production
    process.load("FinalStateAnalysis.PatTools.patPhotonProduction_cff")
    final_photon_collection = chain_sequence(process.customizePhotonSequence,
                                             "selectedPatPhotons")
    #setup PHOSPHOR for a specific dataset
    if cmssw_major_version() == 4:  # for now 2011 = CMSSW42X
        process.patPhotonPHOSPHOREmbedder.year = cms.uint32(2011)
    else:  # 2012 is 5YX
        process.patPhotonPHOSPHOREmbedder.year = cms.uint32(2012)
    process.patPhotonPHOSPHOREmbedder.isMC = cms.bool(bool(isMC))
    #inject photons into pat sequence
    process.customizePhotonSequence.insert(0, process.selectedPatPhotons)
    process.patDefaultSequence.replace(process.selectedPatPhotons,
                                       process.customizePhotonSequence)
    process.cleanPatPhotons.src = final_photon_collection

    ########################
    ##      TRIGGER       ##
    ########################

    trigtools.switchOnTrigger(process)

    #configure the PAT trigger
    if kwargs['HLTprocess']:
        process.patTrigger.processName = cms.string(kwargs['HLTprocess'])
        process.patTriggerEvent.processName = cms.string(kwargs['HLTprocess'])

    ########################
    ##   --------------   ##
    ########################

    output_commands.append('*_cleanPatTaus_*_*')
    output_commands.append('*_cleanPatElectrons_*_*')
    output_commands.append('*_cleanPatMuons_*_*')
    output_commands.append('*_cleanPatPhotons_*_*')

    ########################
    ##                    ##
    ##        FSA         ##
    ##                    ##
    ########################

    # Now build the PATFinalStateLS object, which holds LumiSection info.
    process.load(
        "FinalStateAnalysis.PatTools.finalStates.patFinalStateLSProducer_cfi")
    process.tuplize += process.finalStateLS
    output_commands.append('*_finalStateLS_*_*')
    if isMC:
        process.finalStateLS.xSec = kwargs['xSec']

    # Tell the framework to shut up!
    process.load("FWCore.MessageLogger.MessageLogger_cfi")
    process.MessageLogger.cerr.FwkReport.reportEvery = 1000

    # Which collections are used to build the final states
    fs_daughter_inputs = {
        'electrons':  'cleanPatElectrons',
        'muons':  'cleanPatMuons',
        'taus':  'cleanPatTaus',
        'photons':  'cleanPatPhotons',
        'jets':  'selectedPatJets',
        'pfmet':  final_met_collection,
        'mvamet':  final_mvamet_collection,
    }

    # Setup all the PATFinalState objects
    produce_final_states(process, fs_daughter_inputs, output_commands,
                         process.tuplize, kwargs['puTag'],
                         zzMode=kwargs.get('zzMode', False))

    return process.tuplize, output_commands
Esempio n. 47
0
    jetCorrections=('AK5PFchs',
                    cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']),
                    'None'),  # FIXME: Use proper JECs, as soon as available
    btagDiscriminators=['combinedSecondaryVertexBJetTags'],
)
process.out.outputCommands.append('drop *_selectedPatJets%s_caloTowers_*' %
                                  (labelCA8PFCHSPruned))

# uncomment the following lines to switch to ak4CaloJets in your PAT output
switchJetCollection(
    process,
    jetSource=cms.InputTag('ak4CaloJets'),
    jetCorrections=('AK5Calo',
                    cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']),
                    'Type-1'),  # FIXME: Use proper JECs, as soon as available
    btagDiscriminators=[
        'jetBProbabilityBJetTags', 'jetProbabilityBJetTags',
        'trackCountingHighPurBJetTags', 'trackCountingHighEffBJetTags',
        'simpleSecondaryVertexHighEffBJetTags',
        'simpleSecondaryVertexHighPurBJetTags',
        'combinedSecondaryVertexBJetTags'
    ],
)
## JetID works only with RECO input for the CaloTowers (s. below for 'process.source.fileNames')
#process.patJets.addJetID=True
#process.load("RecoJets.JetProducers.ak4JetID_cfi")
#process.patJets.jetIDMap="ak4JetID"
process.patJets.useLegacyJetMCFlavour = True  # Need to use legacy flavour since the new flavour requires jet constituents which are dropped for CaloJets from AOD
process.out.outputCommands.append('keep *_selectedPatJets_caloTowers_*')
process.out.outputCommands.append('drop *_selectedPatJets_pfCandidates_*')

#print process.out.outputCommands
                                        # 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. ,
                                        )

################## PAT ELECTRONS ####################



###### PAT JETS ########
import PhysicsTools.PatAlgos.tools.jetTools as jetTools
jetTools.switchJetCollection(process, 
                    cms.InputTag('ak5PFJets'),   
                    doJTA            = True,            
                    doBTagging       = True,            
# MC:               jetCorrLabel     = ('AK5PF', ['L1FastJet', 'L2Relative', 'L3Absolute']),  
# data:                   
							jetCorrLabel     = ('AK5PF', ['L1FastJet', 'L2Relative', 'L3Absolute','L2L3Residual']), 
                    doType1MET       = False,            
 #                   genJetCollection = cms.InputTag("ak5GenJets"),
                    doJetID      = False, #True in MC
                    jetIdLabel   = "ak5",
                    outputModules = [],
)
###### PAT JETS ########


process.bsVertexAnalysis = cms.EDAnalyzer("BsToJpsiPhiAnalysis",
                                          isMCstudy = cms.bool(False),
                                          genParticlesLabel  = cms.InputTag(""),  
                                          TrackLabel_K = cms.InputTag("kTracks"),
                                          TrackLabel_pi = cms.InputTag("piTracks"),
                                          TriggerTag = cms.InputTag("TriggerResults::HLT"),
Esempio n. 49
0
     ],
   )
getattr(process, 'patJetsAK5Calo' + postfixAK5Calo).addJetID=True
getattr(process, 'patJetsAK5Calo' + postfixAK5Calo).jetIDMap="ak5JetID"
process.out.outputCommands.append( 'drop *_selectedPatJetsAK5Calo%s_pfCandidates_*'%(postfixAK5Calo) )
#process.patJetsAK5Calo.addJetID=True
#process.patJetsAK5Calo.jetIDMap="ak5JetID"

## uncomment the following lines to add ak5PFJets to your PAT output
switchJetCollection(
   process,
   jetSource = cms.InputTag('ak5PFJets'),
   jetCorrections = ('AK5PF', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'Type-2'),
   btagDiscriminators = [
       'jetBProbabilityBJetTags'
     , 'jetProbabilityBJetTags'
     , 'trackCountingHighPurBJetTags'
     , 'trackCountingHighEffBJetTags'
     , 'simpleSecondaryVertexHighEffBJetTags'
     , 'simpleSecondaryVertexHighPurBJetTags'
     , 'combinedSecondaryVertexBJetTags'
     ],
   )

## let it run
#process.p = cms.Path(
#    process.patDefaultSequence
#)

##process.Tracer = cms.Service("Tracer")
#process.p = cms.Path(
    #process.selectedPatCandidates
Esempio n. 50
0
                                      'L3Absolute']), 'None'))

addJetCollection(process,
                 labelName='AK8PFCHS',
                 jetSource=cms.InputTag('ak8PFJetsCHS'),
                 algo='ak8',
                 rParam=0.8,
                 jetCorrections=('AK8PFchs',
                                 cms.vstring(
                                     ['L1FastJet', 'L2Relative',
                                      'L3Absolute']), 'None'))

switchJetCollection(
    process,
    jetSource=cms.InputTag('ak4PFJets'),
    rParam=0.4,
    jetCorrections=('AK4PF',
                    cms.vstring(['L1FastJet', 'L2Relative',
                                 'L3Absolute']), 'Type-1'),
)

#process.patJetGenJetMatchCA8PFCHS.matched = cms.InputTag("ca8GenJetsNoNu")

patJetsAK4 = process.patJetsAK4PFCHS
patJetsCA8 = process.patJetsCA8PFCHS
patJetsAK8 = process.patJetsAK8PFCHS

process.out.outputCommands += [
    'keep *_ak4PFJetsCHS_*_*', 'keep *_patJetsAK4PFCHS_*_*',
    'keep *_ca8PFJetsCHS_*_*', 'keep *_patJetsCA8PFCHS_*_*',
    'keep *_ak8PFJetsCHS_*_*', 'keep *_patJetsAK8PFCHS_*_*'
]
Esempio n. 51
0
    					  )	    

    process.patJetsAk8PuppiJets.userData.userFloats.src += ['ak8PFJetsPuppiSoftDropMass','ak8PFJetsPuppiSoftDropMassCorrected']
    #process.patJetsAk8PuppiJets.userData.userFloats.src += ['ak8PFJetsPuppiPrunedMass','ak8PFJetsPuppiPrunedMassCorrected']
    process.patJetsAk8PuppiJets.userData.userFloats.src += ['NjettinessAK8Puppi:tau1','NjettinessAK8Puppi:tau2','NjettinessAK8Puppi:tau3']
    process.patJetsAk8PuppiJets.addTagInfos = True

# ###### Recluster MET ##########
if config["DOMETRECLUSTERING"]:

  from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection
		  
  if config["RUNONMC"]:
     switchJetCollection(process,
                         jetSource = cms.InputTag('ak4PFJetsCHS'),
		         jetCorrections = ('AK4PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], ''),
		         genParticles = cms.InputTag('prunedGenParticles'),
		         pvSource = cms.InputTag('offlineSlimmedPrimaryVertices')
     )
  else:
     switchJetCollection(process,
                         jetSource = cms.InputTag('ak4PFJetsCHS'),
		         jetCorrections = ('AK4PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute','L2L3Residual'], ''),
		         genParticles = cms.InputTag('prunedGenParticles'),
		         pvSource = cms.InputTag('offlineSlimmedPrimaryVertices')
     )
		  		
  process.patJets.addGenJetMatch = cms.bool(False) 
  process.patJets.addGenPartonMatch = cms.bool(False) 
  process.patJets.addPartonJetMatch = cms.bool(False) 
  
  from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
Esempio n. 52
0
    # PUT THE DISCRIMINATORS HERE
    #
]

## Switch the default PAT jet collection to the above-defined ak4PFJetsCHS
#
# REPLACE THE FIXME!
#
FIXME = 'FIXME'  #this is just here to avoid python to raise an exception
switchJetCollection(process,
                    jetSource=FIXME,
                    pvSource=FIXME,
                    pfCandidates=FIXME,
                    svSource=FIXME,
                    muSource=FIXME,
                    elSource=FIXME,
                    btagDiscriminators=bTagDiscriminators,
                    jetCorrections=('AK4PFchs',
                                    ['L1FastJet', 'L2Relative',
                                     'L3Absolute'], 'None'),
                    genJetCollection=FIXME,
                    genParticles=FIXME)
getattr(process, 'selectedPatJets').cut = cms.string(
    'pt > 10')  # to match the selection for slimmedJets in MiniAOD

# What is this needed for?

# In[ ]:

from PhysicsTools.PatAlgos.tools.pfTools import adaptPVs
## Adapt primary vertex collection