コード例 #1
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)
コード例 #2
0
#-- SusyPat Specifics ---------------------------------
if not is7X: # CMSSW 53X
    if useSusyPat:
        # Create default susyPattuple
        from PhysicsTools.Configuration.SUSY_pattuple_cff import addDefaultSUSYPAT
        addDefaultSUSYPAT(process,options.isMC,options.hltName,options.jetMetCorrections,options.mcVersion,options.jetTypes,options.doValidation,options.doExtensiveMatching,options.doSusyTopProjection)
        
        # Embed matched trigger objects inside pat objects (used by TagAndProbe)
        from PhysicsTools.PatAlgos.tools.trigTools import switchOnTriggerMatchEmbedding
        switchOnTriggerMatchEmbedding( process, triggerMatchers = [ 'eleTriggerMatcher', 'muonTriggerMatcher' ], hltProcess = options.hltName, sequence =  "susyPatDefaultSequence")
    else: # or use patDefaultSequence
        # Use pf Isolation
        # https://twiki.cern.ch/twiki/bin/viewauth/CMS/EgammaPFBasedIsolation#PAT_configuration
        # Needed also for Rho corrected pfIsolation for Electrons
        from PhysicsTools.PatAlgos.tools.pfTools import usePFIso
        usePFIso( process )
        
        # Add Jet Collections
        from PhysicsTools.Configuration.SUSY_pattuple_cff import addSUSYJetCollection
        for jetName in options.jetTypes:
            addSUSYJetCollection(process,options.jetMetCorrections,jetName,options.mcVersion)
        
else: # SusyPat is not available for 7X yet
    
    # pf Isolation is in CMSSW7X by default, but the producers were renamed
    # eg. elPFIsoValueCharged03PFIdPFIso -> elPFIsoValueCharged03PFId (no PFIso at the end)
    
    #-- Remove MC dependencies ----------------------------
    if not options.isMC:
        from PhysicsTools.PatAlgos.tools.coreTools import *
        runOnData(process)
コード例 #3
0
def createProcess(runOnMC, runCHS, correctMETWithT1, processCaloJets, processCA8Jets, globalTag):

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

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

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


  from PhysicsTools.SelectorUtils.pvSelector_cfi import pvSelector

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

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

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

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

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

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

    p = postfix

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

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

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

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

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

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

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

    # 2012 Photon ID

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

    return getattr(process, "patPF2PATSequence" + p)

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

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

  #runCHS = False

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

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

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

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

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

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

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

  if processCA8Jets:

    from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection

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

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

  
  if processCaloJets:

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

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



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

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

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

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

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

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

  process.analysisSequence = cms.Sequence()

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

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

    # nuovo


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


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

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

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

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

  # Filtering

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

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

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

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

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

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

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

      process.goodOfflinePrimaryVertices +

      # Physics
      process.analysisSequence +

      process.nEventsFiltered
      )

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

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

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

      # Trigger
      #'keep *_TriggerResults_*_HLT',

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

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

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

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

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

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

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

  return process
コード例 #4
0
def loadPAT(process,jetMetCorrections,extMatch):
    #-- Changes for electron and photon ID ----------------------------------------
    from PhysicsTools.PatAlgos.tools.pfTools import usePFIso
    usePFIso( process )
    process.patElectrons.isolationValues = cms.PSet(
        pfNeutralHadrons = cms.InputTag("elPFIsoValueNeutral03PFIdPFIso"),
        pfChargedAll = cms.InputTag("elPFIsoValueChargedAll03PFIdPFIso"),
        pfPUChargedHadrons = cms.InputTag("elPFIsoValuePU03PFIdPFIso"),
        pfPhotons = cms.InputTag("elPFIsoValueGamma03PFIdPFIso"),
        pfChargedHadrons = cms.InputTag("elPFIsoValueCharged03PFIdPFIso")
        )
    process.patElectrons.isolationValuesNoPFId = cms.PSet(
        pfNeutralHadrons = cms.InputTag("elPFIsoValueNeutral03NoPFIdPFIso"),
        pfChargedAll = cms.InputTag("elPFIsoValueChargedAll03NoPFIdPFIso"),
        pfPUChargedHadrons = cms.InputTag("elPFIsoValuePU03NoPFIdPFIso"),
        pfPhotons = cms.InputTag("elPFIsoValueGamma03NoPFIdPFIso"),
        pfChargedHadrons = cms.InputTag("elPFIsoValueCharged03NoPFIdPFIso")
        )
    process.patDefaultSequence.replace(process.patElectrons,process.eleIsoSequence+process.patElectrons)
    process.patDefaultSequence.replace(process.patMuons,process.muIsoSequence+process.patMuons)
    
    # Turn off photon-electron cleaning (i.e., flag only)
    process.cleanPatPhotons.checkOverlaps.electrons.requireNoOverlaps = False

    # Embed tracks, since we drop them
    process.patElectrons.embedTrack = True
    process.patMuons.embedTrack   = True

    #include tau decay mode in pat::Taus (elese it will just be uninitialized)
    #decay modes are dropped and have to be redone, this is a bit dangorous since the decay modes insered are *not* the ones used in RECO
    #process.patTaus.addDecayMode = True
    #process.makePatTaus.replace( process.patTaus, process.shrinkingConePFTauDecayModeProducer + process.patTaus )

    #Additional electron ids as defined for VBTF
    process.load("ElectroWeakAnalysis.WENu.simpleEleIdSequence_cff")
    process.patElectrons.electronIDSources = cms.PSet(
    eidTight = cms.InputTag("eidTight"),
    eidLoose = cms.InputTag("eidLoose"),
    eidRobustTight = cms.InputTag("eidRobustTight"),
    eidRobustHighEnergy = cms.InputTag("eidRobustHighEnergy"),
    eidRobustLoose = cms.InputTag("eidRobustLoose"),
    simpleEleId95relIso= cms.InputTag("simpleEleId95relIso"),
    simpleEleId90relIso= cms.InputTag("simpleEleId90relIso"),
    simpleEleId85relIso= cms.InputTag("simpleEleId85relIso"),
    simpleEleId80relIso= cms.InputTag("simpleEleId80relIso"),
    simpleEleId70relIso= cms.InputTag("simpleEleId70relIso"),
    simpleEleId60relIso= cms.InputTag("simpleEleId60relIso"),
    simpleEleId95cIso= cms.InputTag("simpleEleId95cIso"),
    simpleEleId90cIso= cms.InputTag("simpleEleId90cIso"),
    simpleEleId85cIso= cms.InputTag("simpleEleId85cIso"),
    simpleEleId80cIso= cms.InputTag("simpleEleId80cIso"),
    simpleEleId70cIso= cms.InputTag("simpleEleId70cIso"),
    simpleEleId60cIso= cms.InputTag("simpleEleId60cIso"))
    process.patDefaultSequence.replace(process.patElectrons,process.simpleEleIdSequence+process.patElectrons)
    
    #-- Tuning of Monte Carlo matching --------------------------------------------
    # Also match with leptons of opposite charge
    process.electronMatch.checkCharge = False
    process.electronMatch.maxDeltaR   = cms.double(0.2)
    process.electronMatch.maxDPtRel   = cms.double(999999.)
    process.muonMatch.checkCharge     = False
    process.muonMatch.maxDeltaR       = cms.double(0.2)
    process.muonMatch.maxDPtRel       = cms.double(999999.)
    #process.tauMatch.checkCharge      = False
    #process.tauMatch.maxDeltaR        = cms.double(0.3)
    process.patJetPartonMatch.maxDeltaR  = cms.double(0.25)
    process.patJetPartonMatch.maxDPtRel  = cms.double(999999.)
    process.patJetGenJetMatch.maxDeltaR  = cms.double(0.25)
    process.patJetGenJetMatch.maxDPtRel  = cms.double(999999.)
    if extMatch:
        process.electronMatch.mcStatus = cms.vint32(1,5)
        process.electronMatch.matched = "mergedTruth"
        process.muonMatch.mcStatus = cms.vint32(1,5)
        process.muonMatch.matched = "mergedTruth"
        process.patJetPartonMatch.matched = "mergedTruth"
        process.patJetPartons.src = "mergedTruth"
        process.photonMatch.matched = "mergedTruth"
        #process.tauGenJets.GenParticles = "mergedTruth"
        #process.tauMatch.matched = "mergedTruth"


    #-- Taus ----------------------------------------------------------------------
    #some tau discriminators have been switched off during development. They can be switched on again...
    #setattr(process.patTaus.tauIDSources, "trackIsolation", cms.InputTag("shrinkingConePFTauDiscriminationByTrackIsolation"))
    #setattr(process.patTaus.tauIDSources, "ecalIsolation", cms.InputTag("shrinkingConePFTauDiscriminationByECALIsolation"))
    #setattr(process.patTaus.tauIDSources, "byIsolation", cms.InputTag("shrinkingConePFTauDiscriminationByIsolation"))
    #setattr(process.patTaus.tauIDSources, "leadingPionPtCut", cms.InputTag("shrinkingConePFTauDiscriminationByLeadingPionPtCut"))
    #setattr(process.patTaus.tauIDSources, "trackIsolationUsingLeadingPion", cms.InputTag("shrinkingConePFTauDiscriminationByTrackIsolationUsingLeadingPion"))
    #setattr(process.patTaus.tauIDSources, "ecalIsolationUsingLeadingPion", cms.InputTag("shrinkingConePFTauDiscriminationByECALIsolationUsingLeadingPion"))
    #setattr(process.patTaus.tauIDSources, "byIsolationUsingLeadingPion", cms.InputTag("shrinkingConePFTauDiscriminationByIsolationUsingLeadingPion"))
    #setattr(process.patTaus.tauIDSources, "byTaNC", cms.InputTag("shrinkingConePFTauDiscriminationByTaNC"))
    #setattr(process.patTaus.tauIDSources, "byTaNCfrOnePercent", cms.InputTag("shrinkingConePFTauDiscriminationByTaNCfrOnePercent"))
    #setattr(process.patTaus.tauIDSources, "byTaNCfrHalfPercent", cms.InputTag("shrinkingConePFTauDiscriminationByTaNCfrHalfPercent"))
    #setattr(process.patTaus.tauIDSources, "byTaNCfrQuarterPercent", cms.InputTag("shrinkingConePFTauDiscriminationByTaNCfrQuarterPercent"))
    #setattr(process.patTaus.tauIDSources, "byTaNCfrTenthPercent", cms.InputTag("shrinkingConePFTauDiscriminationByTaNCfrTenthPercent"))


    #-- Jet corrections -----------------------------------------------------------
    # L1 FastJet jet corrections
    # kt6PFJets for FastJet corrections are already run and placed before jetCorrection calculation
    # apply FastJet corrections only if demanded
    # TODO: Check if still necessary to switch here
    if ("L1FastJet" in jetMetCorrections):
        process.pfJets.doAreaFastjet = True
        process.pfJetsPF.doAreaFastjet = True
コード例 #5
0
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
コード例 #6
0
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)
コード例 #7
0
def createProcess(runOnMC, runCHS, correctMETWithT1, processCaloJets, globalTag):

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

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

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


  from PhysicsTools.SelectorUtils.pvSelector_cfi import pvSelector

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

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

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

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

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

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

    p = postfix

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

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

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

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

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

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

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

    # 2012 Photon ID

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

    return getattr(process, "patPF2PATSequence" + p)

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

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

  #runCHS = False

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

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

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

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

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

    if runCHS:
      chsP = p + "chs"

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

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

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

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

  if processCaloJets:

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

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

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

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

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

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

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

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

  process.analysisSequence = cms.Sequence()

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

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

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

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

  process.analysisSequence *= process.photonPFIsolation

  # Filtering

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

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

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

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

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

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

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

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

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

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

      process.nEventsFiltered
      )

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

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

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

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

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

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

  return process
コード例 #8
0
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
コード例 #9
0
def loadPAT(process,jetMetCorrections,extMatch):
    #-- Changes for electron and photon ID ----------------------------------------
    from PhysicsTools.PatAlgos.tools.pfTools import usePFIso
    usePFIso( process )
    process.patElectrons.isolationValues = cms.PSet(
        pfNeutralHadrons = cms.InputTag("elPFIsoValueNeutral03PFIdPFIso"),
        pfChargedAll = cms.InputTag("elPFIsoValueChargedAll03PFIdPFIso"),
        pfPUChargedHadrons = cms.InputTag("elPFIsoValuePU03PFIdPFIso"),
        pfPhotons = cms.InputTag("elPFIsoValueGamma03PFIdPFIso"),
        pfChargedHadrons = cms.InputTag("elPFIsoValueCharged03PFIdPFIso")
        )
    process.patElectrons.isolationValuesNoPFId = cms.PSet(
        pfNeutralHadrons = cms.InputTag("elPFIsoValueNeutral03NoPFIdPFIso"),
        pfChargedAll = cms.InputTag("elPFIsoValueChargedAll03NoPFIdPFIso"),
        pfPUChargedHadrons = cms.InputTag("elPFIsoValuePU03NoPFIdPFIso"),
        pfPhotons = cms.InputTag("elPFIsoValueGamma03NoPFIdPFIso"),
        pfChargedHadrons = cms.InputTag("elPFIsoValueCharged03NoPFIdPFIso")
        )
    process.patDefaultSequence.replace(process.patElectrons,process.eleIsoSequence+process.patElectrons)
    process.patDefaultSequence.replace(process.patMuons,process.muIsoSequence+process.patMuons)
    
    # Turn off photon-electron cleaning (i.e., flag only)
    process.cleanPatPhotons.checkOverlaps.electrons.requireNoOverlaps = False

    # Embed tracks, since we drop them
    process.patElectrons.embedTrack = True
    process.patMuons.embedTrack   = True

    #include tau decay mode in pat::Taus (elese it will just be uninitialized)
    #decay modes are dropped and have to be redone, this is a bit dangorous since the decay modes insered are *not* the ones used in RECO
    #process.patTaus.addDecayMode = True
    #process.makePatTaus.replace( process.patTaus, process.shrinkingConePFTauDecayModeProducer + process.patTaus )

    #Additional electron ids as defined for VBTF
    process.load("ElectroWeakAnalysis.WENu.simpleEleIdSequence_cff")
    process.patElectrons.electronIDSources = cms.PSet(
    eidTight = cms.InputTag("eidTight"),
    eidLoose = cms.InputTag("eidLoose"),
    eidRobustTight = cms.InputTag("eidRobustTight"),
    eidRobustHighEnergy = cms.InputTag("eidRobustHighEnergy"),
    eidRobustLoose = cms.InputTag("eidRobustLoose"),
    simpleEleId95relIso= cms.InputTag("simpleEleId95relIso"),
    simpleEleId90relIso= cms.InputTag("simpleEleId90relIso"),
    simpleEleId85relIso= cms.InputTag("simpleEleId85relIso"),
    simpleEleId80relIso= cms.InputTag("simpleEleId80relIso"),
    simpleEleId70relIso= cms.InputTag("simpleEleId70relIso"),
    simpleEleId60relIso= cms.InputTag("simpleEleId60relIso"),
    simpleEleId95cIso= cms.InputTag("simpleEleId95cIso"),
    simpleEleId90cIso= cms.InputTag("simpleEleId90cIso"),
    simpleEleId85cIso= cms.InputTag("simpleEleId85cIso"),
    simpleEleId80cIso= cms.InputTag("simpleEleId80cIso"),
    simpleEleId70cIso= cms.InputTag("simpleEleId70cIso"),
    simpleEleId60cIso= cms.InputTag("simpleEleId60cIso"))
    process.patDefaultSequence.replace(process.patElectrons,process.simpleEleIdSequence+process.patElectrons)
    
    #-- Tuning of Monte Carlo matching --------------------------------------------
    # Also match with leptons of opposite charge
    process.electronMatch.checkCharge = False
    process.electronMatch.maxDeltaR   = cms.double(0.2)
    process.electronMatch.maxDPtRel   = cms.double(999999.)
    process.muonMatch.checkCharge     = False
    process.muonMatch.maxDeltaR       = cms.double(0.2)
    process.muonMatch.maxDPtRel       = cms.double(999999.)
    #process.tauMatch.checkCharge      = False
    #process.tauMatch.maxDeltaR        = cms.double(0.3)
    process.patJetPartonMatch.maxDeltaR  = cms.double(0.25)
    process.patJetPartonMatch.maxDPtRel  = cms.double(999999.)
    process.patJetGenJetMatch.maxDeltaR  = cms.double(0.25)
    process.patJetGenJetMatch.maxDPtRel  = cms.double(999999.)
    if extMatch:
        process.electronMatch.mcStatus = cms.vint32(1,5)
        process.electronMatch.matched = "mergedTruth"
        process.muonMatch.mcStatus = cms.vint32(1,5)
        process.muonMatch.matched = "mergedTruth"
        process.patJetPartonMatch.matched = "mergedTruth"
        process.patJetPartons.src = "mergedTruth"
        process.photonMatch.matched = "mergedTruth"
        #process.tauGenJets.GenParticles = "mergedTruth"
        #process.tauMatch.matched = "mergedTruth"


    #-- Taus ----------------------------------------------------------------------
    #some tau discriminators have been switched off during development. They can be switched on again...
    #setattr(process.patTaus.tauIDSources, "trackIsolation", cms.InputTag("shrinkingConePFTauDiscriminationByTrackIsolation"))
    #setattr(process.patTaus.tauIDSources, "ecalIsolation", cms.InputTag("shrinkingConePFTauDiscriminationByECALIsolation"))
    #setattr(process.patTaus.tauIDSources, "byIsolation", cms.InputTag("shrinkingConePFTauDiscriminationByIsolation"))
    #setattr(process.patTaus.tauIDSources, "leadingPionPtCut", cms.InputTag("shrinkingConePFTauDiscriminationByLeadingPionPtCut"))
    #setattr(process.patTaus.tauIDSources, "trackIsolationUsingLeadingPion", cms.InputTag("shrinkingConePFTauDiscriminationByTrackIsolationUsingLeadingPion"))
    #setattr(process.patTaus.tauIDSources, "ecalIsolationUsingLeadingPion", cms.InputTag("shrinkingConePFTauDiscriminationByECALIsolationUsingLeadingPion"))
    #setattr(process.patTaus.tauIDSources, "byIsolationUsingLeadingPion", cms.InputTag("shrinkingConePFTauDiscriminationByIsolationUsingLeadingPion"))
    #setattr(process.patTaus.tauIDSources, "byTaNC", cms.InputTag("shrinkingConePFTauDiscriminationByTaNC"))
    #setattr(process.patTaus.tauIDSources, "byTaNCfrOnePercent", cms.InputTag("shrinkingConePFTauDiscriminationByTaNCfrOnePercent"))
    #setattr(process.patTaus.tauIDSources, "byTaNCfrHalfPercent", cms.InputTag("shrinkingConePFTauDiscriminationByTaNCfrHalfPercent"))
    #setattr(process.patTaus.tauIDSources, "byTaNCfrQuarterPercent", cms.InputTag("shrinkingConePFTauDiscriminationByTaNCfrQuarterPercent"))
    #setattr(process.patTaus.tauIDSources, "byTaNCfrTenthPercent", cms.InputTag("shrinkingConePFTauDiscriminationByTaNCfrTenthPercent"))


    #-- Jet corrections -----------------------------------------------------------
    # L1 FastJet jet corrections
    # kt6PFJets for FastJet corrections are already run and placed before jetCorrection calculation
    # apply FastJet corrections only if demanded
    # TODO: Check if still necessary to switch here
    if ("L1FastJet" in jetMetCorrections):
        process.pfJets.doAreaFastjet = True
        process.pfJetsPF.doAreaFastjet = True
コード例 #10
0
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
コード例 #11
0
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
コード例 #12
0
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
コード例 #13
0
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