Exemple #1
0
def nanoAOD_addDeepInfoAK8(process,addDeepBTag,addDeepBoostedJet,jecPayload):
    _btagDiscriminators=[]
    if addDeepBTag:
        print("Updating process to run DeepCSV btag to AK8 jets")
        _btagDiscriminators += ['pfDeepCSVJetTags:probb','pfDeepCSVJetTags:probbb']
    if addDeepBoostedJet:
        print("Updating process to run DeepBoostedJet on datasets before 103X")
        from RecoBTag.MXNet.pfDeepBoostedJet_cff import _pfDeepBoostedJetTagsAll as pfDeepBoostedJetTagsAll
        _btagDiscriminators += pfDeepBoostedJetTagsAll
    if len(_btagDiscriminators)==0: return process
    print("Will recalculate the following discriminators on AK8 jets: "+", ".join(_btagDiscriminators))
    updateJetCollection(
       process,
       jetSource = cms.InputTag('slimmedJetsAK8'),
       pvSource = cms.InputTag('offlineSlimmedPrimaryVertices'),
       svSource = cms.InputTag('slimmedSecondaryVertices'),
       rParam = 0.8,
       jetCorrections = (jecPayload.value(), cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual']), 'None'),
       btagDiscriminators = _btagDiscriminators,
       postfix='AK8WithDeepInfo',
       printWarning = False
       )
    process.looseJetIdAK8.src = "selectedUpdatedPatJetsAK8WithDeepInfo"
    process.tightJetIdAK8.src = "selectedUpdatedPatJetsAK8WithDeepInfo"
    process.tightJetIdLepVetoAK8.src = "selectedUpdatedPatJetsAK8WithDeepInfo"
    process.slimmedJetsAK8WithUserData.src = "selectedUpdatedPatJetsAK8WithDeepInfo"
    return process
def reproduceJEC(process):
    '''
    For instructions and more details see:
    https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookJetEnergyCorrections#CorrPatJets
    https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookMiniAOD2016#Jets
    https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookJetAnalysis
    '''
    print "=== Customisation: reproducing jet collections with latest JEC"
    from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
    updateJetCollection(
        process,
        # jetSource = cms.InputTag('slimmedJets'),
        jetSource = cms.InputTag('cleanedPatJets'),
        labelName = 'UpdatedJEC',
        jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None')  # Do not forget 'L2L3Residual' on data!
    )
    # PUPPI jets
    updateJetCollection(
        process,
        jetSource = cms.InputTag('slimmedJetsPuppi'),
        labelName = 'UpdatedJECPuppi',
        jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None')  # Do not
    )
    
    # Add to customisations sequence
    process.CustomisationsSequence += process.patJetCorrFactorsUpdatedJEC
    process.CustomisationsSequence += process.updatedPatJetsUpdatedJEC
    process.CustomisationsSequence += process.patJetCorrFactorsUpdatedJECPuppi
    process.CustomisationsSequence += process.updatedPatJetsUpdatedJECPuppi
Exemple #3
0
def nanoAOD_addDeepInfo(process,addDeepBTag,addDeepFlavour):
    _btagDiscriminators=[]
    if addDeepBTag:
        print("Updating process to run DeepCSV btag")
        _btagDiscriminators += ['pfDeepCSVJetTags:probb','pfDeepCSVJetTags:probbb','pfDeepCSVJetTags:probc']
    if addDeepFlavour:
        print("Updating process to run DeepFlavour btag")
        _btagDiscriminators += ['pfDeepFlavourJetTags:probb','pfDeepFlavourJetTags:probbb','pfDeepFlavourJetTags:problepb']
    if len(_btagDiscriminators)==0: return process
    print("Will recalculate the following discriminators: "+", ".join(_btagDiscriminators))
    updateJetCollection(
               process,
               jetSource = cms.InputTag('slimmedJets'),
               jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute','L2L3Residual']), 'None'),
               btagDiscriminators = _btagDiscriminators,
               postfix = 'WithDeepInfo',
           )
    process.load("Configuration.StandardSequences.MagneticField_cff")
    process.looseJetId.src="selectedUpdatedPatJetsWithDeepInfo"
    process.tightJetId.src="selectedUpdatedPatJetsWithDeepInfo"
    process.tightJetIdLepVeto.src="selectedUpdatedPatJetsWithDeepInfo"
    process.bJetVars.src="selectedUpdatedPatJetsWithDeepInfo"
    process.slimmedJetsWithUserData.src="selectedUpdatedPatJetsWithDeepInfo"
    process.qgtagger80x.srcJets="selectedUpdatedPatJetsWithDeepInfo"
    if addDeepFlavour:
        process.pfDeepFlavourJetTagsWithDeepInfo.graph_path = 'RecoBTag/Combined/data/DeepFlavourV03_10X_training/constant_graph.pb'
        process.pfDeepFlavourJetTagsWithDeepInfo.lp_names = ["cpf_input_batchnorm/keras_learning_phase"]
    return process
def reproduceJEC(process):
    print "=== Customisation: reproducing jet collections with latest JEC"
    from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
    updateJetCollection(
        process,
#        jetSource = cms.InputTag('slimmedJets'),
        jetSource = cms.InputTag('cleanedPatJets'),
        labelName = 'UpdatedJEC',
        jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None')  # Do not forget 'L2L3Residual' on data!
    )
#    from PhysicsTools.PatAlgos.producersLayer1.jetUpdater_cff import patJetCorrFactorsUpdated
#    # PF AK4CHS jets
#    if not hasattr(process, "JECpayloadAK4PFchs"):
#        raise Exception("Error: Could not access process.JECpayloadAK4PFchs! Please load Jet_cfi.py before calling customizations")
#    process.patJetCorrFactorsReapplyJECAK4CHS = patJetCorrFactorsUpdated.clone(
#      src = cms.InputTag("slimmedJets"),
#      levels = ['L1FastJet', 'L2Relative', 'L3Absolute'],
#      payload = process.JECpayloadAK4PFchs.payload,  # Set in Jet_cfi.py
#    ) 
#    from PhysicsTools.PatAlgos.producersLayer1.jetUpdater_cff import patJetsUpdated
#    process.patJetsReapplyJECAK4CHS = patJetsUpdated.clone(
#      jetSource = cms.InputTag("slimmedJets"),
#      jetCorrFactorsSource = cms.VInputTag(cms.InputTag("patJetCorrFactorsReapplyJECAK4CHS"))
#    )
#    # PUPPI jets
#    updateJetCollection(
#        process,
#        jetSource = cms.InputTag('slimmedJetsPuppi'),
#        labelName = 'UpdatedJECPuppi',
#        jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None')  # Do not$
#    )
#    if not hasattr(process, "JECpayloadAK4PFPuppi"):
#        raise Exception("Error: Could not access process.JECpayloadAK4PFPuppi! Please load Jet_cfi.py before calling customizations")
#    process.patJetCorrFactorsReapplyJECPuppi = patJetCorrFactorsUpdated.clone(
#      src = cms.InputTag("slimmedJetsPuppi"),
#      levels = ['L1FastJet', 'L2Relative', 'L3Absolute'],
#      payload = process.JECpayloadAK4PFPuppi.payload,  # Set in Jet_cfi.py
#    )
#    from PhysicsTools.PatAlgos.producersLayer1.jetUpdater_cff import patJetsUpdated
#    process.patJetsReapplyJECPuppi = patJetsUpdated.clone(
#      jetSource = cms.InputTag("slimmedJetsPuppi"), 
#      jetCorrFactorsSource = cms.VInputTag(cms.InputTag("patJetCorrFactorsReapplyJECPuppi"))
#    )
    #process.reapplyJEC = cms.Sequence(process.patJetCorrFactorsReapplyJECAK4CHS +
    #                                  process.patJetsReapplyJECAK4CHS +
    #                                  process.patJetCorrFactorsReapplyJECPuppi +
    #                                  process.patJetsReapplyJECPuppi)
#    process.CustomisationsSequence += process.patJetCorrFactorsReapplyJECAK4CHS
#    process.CustomisationsSequence += process.patJetsReapplyJECAK4CHS
#    process.CustomisationsSequence += process.patJetCorrFactorsReapplyJECPuppi
#    process.CustomisationsSequence += process.patJetsReapplyJECPuppi
    process.CustomisationsSequence += process.patJetCorrFactorsUpdatedJEC
    process.CustomisationsSequence += process.updatedPatJetsUpdatedJEC
def produceAK8JEC(process, isData):
    from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
    
    JEC = ['L1FastJet','L2Relative','L3Absolute']
    if isData:
        JEC += ['L2L3Residual']
        
    updateJetCollection(
        process,
        labelName = 'AK8PFCHS',
        jetSource = cms.InputTag("slimmedJetsAK8"),
        rParam = 0.8,
        jetCorrections = ('AK8PFchs', cms.vstring(JEC), 'None') 
    )
    
    process.AK8CustomisationsSequence += process.patJetCorrFactorsAK8PFCHS
    process.AK8CustomisationsSequence += process.updatedPatJetsAK8PFCHS
    return
Exemple #6
0
def nanoAOD_addDeepBTagFor80X(process):
    print("Updating process to run DeepCSV btag on legacy 80X datasets")
    updateJetCollection(
               process,
               jetSource = cms.InputTag('slimmedJets'),
               jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute','L2L3Residual']), 'None'),
               btagDiscriminators = ['pfDeepCSVJetTags:probb','pfDeepCSVJetTags:probbb','pfDeepCSVJetTags:probc'], ## to add discriminators
               btagPrefix = ''
           )
    process.load("Configuration.StandardSequences.MagneticField_cff")
    process.looseJetId.src="selectedUpdatedPatJets"
    process.tightJetId.src="selectedUpdatedPatJets"
    process.tightJetIdLepVeto.src="selectedUpdatedPatJets"
    process.bJetVars.src="selectedUpdatedPatJets"
    process.slimmedJetsWithUserData.src="selectedUpdatedPatJets"
    process.qgtagger80x.srcJets="selectedUpdatedPatJets"
    patAlgosToolsTask = getPatAlgosToolsTask(process)
    patAlgosToolsTask .add(process.updatedPatJets)
    patAlgosToolsTask .add(process.patJetCorrFactors)
    process.additionalendpath = cms.EndPath(patAlgosToolsTask)
    return process
Exemple #7
0
def nanoAOD_addDeepFlavourTagFor94X2016(process):
    print("Updating process to run DeepCSV btag on 94X re-miniAOD of legacy 80X datasets")
    updateJetCollection(
               process,
               jetSource = cms.InputTag('slimmedJets'),
               jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute','L2L3Residual']), 'None'),
               btagDiscriminators = ['pfDeepFlavourJetTags:probb','pfDeepFlavourJetTags:probbb','pfDeepFlavourJetTags:problepb'], ## to add discriminators
               btagPrefix = ''
           )
    process.load("Configuration.StandardSequences.MagneticField_cff")
    process.looseJetId.src="selectedUpdatedPatJets"
    process.tightJetId.src="selectedUpdatedPatJets"
    process.tightJetIdLepVeto.src="selectedUpdatedPatJets"
    process.bJetVars.src="selectedUpdatedPatJets"
    process.slimmedJetsWithUserData.src="selectedUpdatedPatJets"
    process.qgtagger80x.srcJets="selectedUpdatedPatJets"
    process.pfDeepFlavourJetTags.graph_path = 'RecoBTag/Combined/data/DeepFlavourV03_10X_training/constant_graph.pb'
    process.pfDeepFlavourJetTags.lp_names = ["cpf_input_batchnorm/keras_learning_phase"]
    patAlgosToolsTask = getPatAlgosToolsTask(process)
    patAlgosToolsTask .add(process.updatedPatJets)
    patAlgosToolsTask .add(process.patJetCorrFactors)
    process.additionalendpath = cms.EndPath(patAlgosToolsTask)
    return process
def makeTreeFromMiniAOD(
process,
outfile,
reportfreq=10,
dataset="",
globaltag="",
numevents=1000,
geninfo=False,
tagname="RECO",
jsonfile="",
jecfile="",
residual=False,
jerfile="",
pufile="",
doPDFs=False,
fastsim=False,
signal=False,
scenario=""
):

    ## ----------------------------------------------------------------------------------------------
    ## ----------------------------------------------------------------------------------------------
    ## Preamble
    ## ----------------------------------------------------------------------------------------------
    ## ----------------------------------------------------------------------------------------------
    
    process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff")
    process.GlobalTag.globaltag = globaltag

    # log output
    process.load("FWCore.MessageService.MessageLogger_cfi")
    process.MessageLogger.cerr.FwkReport.reportEvery = reportfreq
    process.options = cms.untracked.PSet(
        allowUnscheduled = cms.untracked.bool(True),
#        wantSummary = cms.untracked.bool(True) # off by default
    )

    # files to process
    import FWCore.PythonUtilities.LumiList as LumiList
    process.maxEvents = cms.untracked.PSet(
        input = cms.untracked.int32(numevents)
    )
    process.source = cms.Source("PoolSource",
        fileNames = cms.untracked.vstring(dataset)
    )
    if len(jsonfile)>0: process.source.lumisToProcess = LumiList.LumiList(filename = jsonfile).getVLuminosityBlockRange()

    # output file
    process.TFileService = cms.Service("TFileService",
        fileName = cms.string(outfile+".root")
    )
    # branches for treemaker
    VectorRecoCand       = cms.vstring() 
    VarsDouble           = cms.vstring()
    VarsInt              = cms.vstring()
    VarsBool             = cms.vstring()
    VectorTLorentzVector = cms.vstring()
    VectorDouble         = cms.vstring()
    VectorString         = cms.vstring()
    VectorInt            = cms.vstring()
    VectorBool           = cms.vstring()

    # configure treemaker
    from LeptoQuarkTreeMaker.LeptoQuarkTreeMaker.treeMaker import TreeMaker
    process.LQTreeMaker2 = TreeMaker.clone(
        TreeName             = cms.string("SimpleTree"),
        VectorRecoCand       = VectorRecoCand, 
        VarsDouble           = VarsDouble,
        VarsInt              = VarsInt,
        VarsBool             = VarsBool,
        VectorTLorentzVector = VectorTLorentzVector,
        VectorDouble         = VectorDouble,
        VectorInt            = VectorInt,
        VectorString         = VectorString,
        VectorBool           = VectorBool,
    )

    ## ----------------------------------------------------------------------------------------------
    ## ----------------------------------------------------------------------------------------------
    ## Standard producers
    ## ----------------------------------------------------------------------------------------------
    ## ----------------------------------------------------------------------------------------------

    ## ----------------------------------------------------------------------------------------------
    ## SUSY scan info

    
    ## ----------------------------------------------------------------------------------------------
    ## WeightProducer
    ## ----------------------------------------------------------------------------------------------
    if geninfo:
        from LeptoQuarkTreeMaker.WeightProducer.getWeightProducer_cff import getWeightProducer
        process.WeightProducer = getWeightProducer(process.source.fileNames[0],fastsim and signal)
        process.WeightProducer.Lumi                       = cms.double(1) #default: 1 pb-1 (unit value)
        process.WeightProducer.FileNamePUDataDistribution = cms.string(pufile)
        VarsDouble.extend(['WeightProducer:weight(Weight)','WeightProducer:xsec(CrossSection)','WeightProducer:nevents(NumEvents)',
                           'WeightProducer:TrueNumInteractions','WeightProducer:PUweight(puWeight)','WeightProducer:PUSysUp(puSysUp)','WeightProducer:PUSysDown(puSysDown)'])
        VarsInt.extend(['WeightProducer:NumInteractions'])

    ## ----------------------------------------------------------------------------------------------
    ## PDF weights for PDF systematics
    ## ----------------------------------------------------------------------------------------------
    if geninfo and doPDFs:
        process.PDFWeights = cms.EDProducer('PDFWeightProducer')
        VectorDouble.extend(['PDFWeights:PDFweights','PDFWeights:ScaleWeights','PDFWeights:genWeight'])
        VectorInt.extend(['PDFWeights:PDFids'])

    ## ----------------------------------------------------------------------------------------------
    ## GenHT for stitching together MC samples
    ## ----------------------------------------------------------------------------------------------
    if geninfo:
        process.MadHT = cms.EDProducer('GenHTProducer')
        # called madHT, i.e. MadGraph, to distinguish from GenHT from GenJets
        VarsDouble.extend(['MadHT:genHT(madHT)'])
    
    ## ----------------------------------------------------------------------------------------------
    ## PrimaryVertices
    ## ----------------------------------------------------------------------------------------------
    process.goodVertices = cms.EDFilter("VertexSelector",
        src = cms.InputTag("offlineSlimmedPrimaryVertices"),
        cut = cms.string("!isFake && ndof > 4 && abs(z) < 24 && position.Rho < 2"),
        filter = cms.bool(False)
    )
    from LeptoQuarkTreeMaker.Utils.primaryvertices_cfi import primaryvertices
    process.NVtx = primaryvertices.clone(
        VertexCollection  = cms.InputTag('goodVertices'),
    )
    VarsInt.extend(['NVtx'])
    # also store total number of vertices without quality checks
    process.nAllVertices = primaryvertices.clone(
        VertexCollection  = cms.InputTag('offlineSlimmedPrimaryVertices'),
    )
    VarsInt.extend(['nAllVertices'])

    ## ----------------------------------------------------------------------------------------------
    ## GenParticles
    ## ----------------------------------------------------------------------------------------------
    ## JECs
    ## ----------------------------------------------------------------------------------------------

    process.load("CondCore.DBCommon.CondDBCommon_cfi")
    from CondCore.DBCommon.CondDBSetup_cfi import CondDBSetup
    
    # default miniAOD tags
    JetTag = cms.InputTag('slimmedJets')
    JetAK8Tag = cms.InputTag('slimmedJetsAK8')
    METTag = cms.InputTag('slimmedMETs')
    if scenario=="2016ReMiniAOD03Feb": METTag = cms.InputTag('slimmedMETsMuEGClean') 
    # get the JECs (disabled by default)
    # this requires the user to download the .db file from this twiki
    # https://twiki.cern.ch/twiki/bin/viewauth/CMS/JECDataMC
    if len(jecfile)>0:
        #get name of JECs without any directories
        JECera = jecfile.split('/')[-1]
        JECPatch = cms.string('sqlite_file:'+jecfile+'.db')
        if os.getenv('GC_CONF'): 
            JECPatch = cms.string('sqlite_file:../src/'+jecfile+'.db')

        process.jec = cms.ESSource("PoolDBESSource",CondDBSetup,
            connect = JECPatch,
            toGet   = cms.VPSet(
                cms.PSet(
                    record = cms.string("JetCorrectionsRecord"),
                    tag    = cms.string("JetCorrectorParametersCollection_"+JECera+"_AK4PFchs"),
                    label  = cms.untracked.string("AK4PFchs")
                ),
                cms.PSet(
                    record = cms.string("JetCorrectionsRecord"),
                    tag    = cms.string("JetCorrectorParametersCollection_"+JECera+"_AK4PF"),
                    label  = cms.untracked.string("AK4PF")
                ),
                cms.PSet(
                    record = cms.string("JetCorrectionsRecord"),
                    tag    = cms.string("JetCorrectorParametersCollection_"+JECera+"_AK8PFchs"),
                    label  = cms.untracked.string("AK8PFchs")
                ),
            )
        )
        process.es_prefer_jec = cms.ESPrefer("PoolDBESSource","jec")
        
        levels  = ['L1FastJet','L2Relative','L3Absolute']
        if residual: levels.append('L2L3Residual')
        
        from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
        
        updateJetCollection(
            process,
            jetSource = cms.InputTag('slimmedJets'),
            postfix = 'UpdatedJEC',
            jetCorrections = ('AK4PFchs', levels, 'None')
        )
        
        JetTag = cms.InputTag('updatedPatJetsUpdatedJEC')
        
        # also update the corrections for AK8 jets
        updateJetCollection(
            process,
            jetSource = cms.InputTag('slimmedJetsAK8'),
            labelName = 'AK8',
            postfix = 'UpdatedJEC',
            jetCorrections = ('AK8PFchs', levels, 'None')
        )
        
        JetAK8Tag = cms.InputTag('updatedPatJetsAK8UpdatedJEC')
        
        # update the MET to account for the new JECs
        from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
        runMetCorAndUncFromMiniAOD(
            process,
            isData=not geninfo, # controls gen met
        )
        process.load('RecoMET.METFilters.badGlobalMuonTaggersMiniAOD_cff')
        process.badGlobalMuonTaggerMAOD.taggingMode = cms.bool(True)
        process.cloneGlobalMuonTaggerMAOD.taggingMode = cms.bool(True)
        from PhysicsTools.PatUtils.tools.muonRecoMitigation import muonRecoMitigation
        muonRecoMitigation(
                          process = process,
                          pfCandCollection = "packedPFCandidates", #input PF Candidate Collection
                          runOnMiniAOD = True, #To determine if you are running on AOD or MiniAOD
                          selection="", #You can use a custom selection for your bad muons. Leave empty if you would like to use the bad muon recipe definition.
                          muonCollection="", #The muon collection name where your custom selection will be applied to. Leave empty if you would like to use the bad muon recipe definition.
                          cleanCollName="cleanMuonsPFCandidates", #output pf candidate collection ame
                          cleaningScheme="computeAllApplyClone", #Options are: "all", "computeAllApplyBad","computeAllApplyClone". Decides which (or both) bad muon collections to be used for MET cleaning coming from the bad muon recipe.
                          postfix="" #Use if you would like to add a post fix to your muon / pf collections
                       )
        runMetCorAndUncFromMiniAOD(process,
                                 isData=not geninfo,
                                 pfCandColl="cleanMuonsPFCandidates",
                                 recoMetFromPFCs=True,
                                 postfix="MuClean"
                           )
        process.mucorMET = cms.Sequence(                     
           process.badGlobalMuonTaggerMAOD *
           process.cloneGlobalMuonTaggerMAOD *
           #process.badMuons * # If you are using cleaning mode "all", uncomment this line
           process.cleanMuonsPFCandidates *
           process.fullPatMetSequenceMuClean
           )

        from PhysicsTools.PatUtils.tools.corMETFromMuonAndEG import corMETFromMuonAndEG
        corMETFromMuonAndEG(process,
                    pfCandCollection="", #not needed                                                                                                                                                                                                                                                                                                                      
                    electronCollection="slimmedElectronsBeforeGSFix",
                    photonCollection="slimmedPhotonsBeforeGSFix",
                    corElectronCollection="slimmedElectrons",
                    corPhotonCollection="slimmedPhotons",
                    allMETEGCorrected=True,
                    muCorrection=False,
                    eGCorrection=True,
                    runOnMiniAOD=True,
                    postfix="MuEGClean"
                    )

        process.slimmedMETsMuEGClean = process.slimmedMETs.clone()
        process.slimmedMETsMuEGClean.src = cms.InputTag("patPFMetT1MuEGClean")
        process.slimmedMETsMuEGClean.rawVariation =  cms.InputTag("patPFMetRawMuEGClean")
        process.slimmedMETsMuEGClean.t1Uncertainties = cms.InputTag("patPFMetT1%sMuEGClean")
        del process.slimmedMETsMuEGClean.caloMET

        METTag = cms.InputTag('slimmedMETs','',process.name_())
    else:
        # pointless run of MET tool because it is barely functional
        from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
        runMetCorAndUncFromMiniAOD(
            process,
            isData=not geninfo, # controls gen met
        )

    # keep jets before any further modifications for hadtau
    JetTagBeforeSmearing = JetTag
    # JEC uncertainty - after JECs are updated
    from LeptoQuarkTreeMaker.Utils.jetuncertainty_cfi import JetUncertaintyProducer
    process.jecUnc = JetUncertaintyProducer.clone(
        JetTag = JetTag,
        jecUncDir = cms.int32(0)
    )
    _infosToAdd = ['jecUnc']
    if geninfo:
        # JER factors - central, up, down
        from LeptoQuarkTreeMaker.Utils.smearedpatjet_cfi import SmearedPATJetProducer
        process.jerFactor = SmearedPATJetProducer.clone(
            src = JetTag,
            variation = cms.int32(0),
            store_factor = cms.bool(True)
        )
        process.jerFactorUp = SmearedPATJetProducer.clone(
            src = JetTag,
            variation = cms.int32(1),
            store_factor = cms.bool(True)
        )
        process.jerFactorDown = SmearedPATJetProducer.clone(
            src = JetTag,
            variation = cms.int32(-1),
            store_factor = cms.bool(True)
        )
        _infosToAdd.extend(['jerFactor','jerFactorUp','jerFactorDown'])
    # add userfloat & update tag
    from LeptoQuarkTreeMaker.LeptoQuarkTreeMaker.addJetInfo import addJetInfo
    process, JetTag = addJetInfo(process, JetTag, _infosToAdd, [])

    ## ----------------------------------------------------------------------------------------------
    ## IsoTracks

    ## ----------------------------------------------------------------------------------------------
    ## MET Filters
    ## ----------------------------------------------------------------------------------------------
    
    # When the miniAOD file is created, the results of several different
    # MET filters are save in a TriggerResults object for the PAT process
    # Look at /PhysicsTools/PatAlgos/python/slimming/metFilterPaths_cff.py
    # for the available filter flags

    # The decision was made to include the filter decision flags
    # as individual branches in the tree
    
    if not fastsim: # MET filters are not run for fastsim samples

        from LeptoQuarkTreeMaker.Utils.filterdecisionproducer_cfi import filterDecisionProducer
        
        process.CSCTightHaloFilter = filterDecisionProducer.clone(
            trigTagArg1 = cms.string('TriggerResults'),
            trigTagArg2 = cms.string(''),
            trigTagArg3 = cms.string(tagname),
            filterName  = cms.string("Flag_CSCTightHalo2015Filter"),
        )
        VarsInt.extend(['CSCTightHaloFilter'])
        
        process.globalTightHalo2016Filter = filterDecisionProducer.clone(
            trigTagArg1 = cms.string('TriggerResults'),
            trigTagArg2 = cms.string(''),
            trigTagArg3 = cms.string(tagname),
            filterName  = cms.string("Flag_globalTightHalo2016Filter"),
        )
        VarsInt.extend(['globalTightHalo2016Filter'])
        
        process.HBHENoiseFilter = filterDecisionProducer.clone(
            trigTagArg1 = cms.string('TriggerResults'),
            trigTagArg2 = cms.string(''),
            trigTagArg3 = cms.string(tagname),
            filterName  = cms.string("Flag_HBHENoiseFilter"),
        )
        VarsInt.extend(['HBHENoiseFilter'])
        
        process.HBHEIsoNoiseFilter = filterDecisionProducer.clone(
            trigTagArg1 = cms.string('TriggerResults'),
            trigTagArg2 = cms.string(''),
            trigTagArg3 = cms.string(tagname),
            filterName  = cms.string("Flag_HBHENoiseIsoFilter"),
        )
        VarsInt.extend(['HBHEIsoNoiseFilter'])
        
        process.EcalDeadCellTriggerPrimitiveFilter = filterDecisionProducer.clone(
            trigTagArg1 = cms.string('TriggerResults'),
            trigTagArg2 = cms.string(''),
            trigTagArg3 = cms.string(tagname),
            filterName  = cms.string("Flag_EcalDeadCellTriggerPrimitiveFilter"),
        )
        VarsInt.extend(['EcalDeadCellTriggerPrimitiveFilter'])
        
        process.eeBadScFilter = filterDecisionProducer.clone(
            trigTagArg1  = cms.string('TriggerResults'),
            trigTagArg2  = cms.string(''),
            trigTagArg3  = cms.string(tagname),
            filterName  =   cms.string("Flag_eeBadScFilter"),
        )
        VarsInt.extend(['eeBadScFilter'])
        
        # some filters need to be rerun
        process.load('RecoMET.METFilters.BadChargedCandidateFilter_cfi')
        process.BadChargedCandidateFilter.muons = cms.InputTag("slimmedMuons")
        process.BadChargedCandidateFilter.PFCandidates = cms.InputTag("packedPFCandidates")
        process.BadChargedCandidateFilter.taggingMode = True
        VarsBool.extend(['BadChargedCandidateFilter'])
        
        process.load('RecoMET.METFilters.BadPFMuonFilter_cfi')
        process.BadPFMuonFilter.muons = cms.InputTag("slimmedMuons")
        process.BadPFMuonFilter.PFCandidates = cms.InputTag("packedPFCandidates")
        process.BadPFMuonFilter.taggingMode = True
        VarsBool.extend(['BadPFMuonFilter'])



    from EgammaAnalysis.ElectronTools.regressionWeights_cfi import regressionWeights
    process = regressionWeights(process) 
    '''
    process.RandomNumberGeneratorService = cms.Service("RandomNumberGeneratorService",
                  calibratedPatElectrons  = cms.PSet( initialSeed = cms.untracked.uint32(8675389),
                                                      engineName = cms.untracked.string('TRandom3'),
                                                      ),
                  calibratedPatPhotons    = cms.PSet( initialSeed = cms.untracked.uint32(8675389),
                                                      engineName = cms.untracked.string('TRandom3'),
                                                      ),
                                                   )
    '''
    process.load('Configuration.StandardSequences.Services_cff')
    process.RandomNumberGeneratorService = cms.Service("RandomNumberGeneratorService",
                                                   calibratedPatElectrons  = cms.PSet( 
                                                     initialSeed = cms.untracked.uint32(81),
                                                     engineName = cms.untracked.string('TRandom3'),
                                                     ),
                                                   calibratedPatPhotons  = cms.PSet( 
                                                     initialSeed = cms.untracked.uint32(81),
                                                     engineName = cms.untracked.string('TRandom3'),
                                                     ),
                                                   )

    process.load('EgammaAnalysis.ElectronTools.regressionApplication_cff')
    process.load('EgammaAnalysis.ElectronTools.calibratedPatElectronsRun2_cfi')
    process.calibratedPatElectrons.isMC =  cms.bool(False)
    process.selectedElectrons = cms.EDFilter(
                                "PATElectronSelector",
        src = cms.InputTag("slimmedElectrons"),
        cut = cms.string("pt > 5 && abs(eta)<2.5")
    )
    process.calibratedPatElectrons.electrons = cms.InputTag('selectedElectrons')
    process.calibratedPatElectrons.isMC =  cms.bool(False)

    #process.EGMRegression =cms.Path(process.regressionApplication)
   # process.EGMSmearerElectrons = cms.Path(process.calibratedPatElectrons)
   # process.EGMSmearerElectrons.isMC = cms.bool(False)

    #process.schedule = cms.Schedule(process.EGMRegression,process.EGMSmearerElectrons,process.analysis)
    '''
    process.load('Configuration.StandardSequences.Services_cff')
    process.RandomNumberGeneratorService = cms.Service("RandomNumberGeneratorService",
                                                   calibratedPatElectrons  = cms.PSet( 
                                                     initialSeed = cms.untracked.uint32(81),
                                                     engineName = cms.untracked.string('TRandom3'),
                                                     ),
                                                   calibratedPatPhotons  = cms.PSet( 
                                                     initialSeed = cms.untracked.uint32(81),
                                                     engineName = cms.untracked.string('TRandom3'),
                                                     ),
                                                   )
    process.load('EgammaAnalysis.ElectronTools.calibratedElectronsRun2_cfi')
    correctionType = "Moriond2017_JEC "
    
    calibratedPatElectrons = cms.EDProducer("CalibratedPatElectronProducerRun2",
                                        
                                        # input collections
                                        electrons = cms.InputTag('slimmedElectrons'),
                                        gbrForestName = cms.string("gedelectron_p4combination_25ns"),
                                        
                                        # data or MC corrections
                                        # if isMC is false, data corrections are applied
                                        isMC = cms.bool(True),
                                        
                                        # set to True to get special "fake" smearing for synchronization. Use JUST in case of synchronization
                                        isSynchronization = cms.bool(True),

                                        correctionFile = cms.string("Moriond2017_JEC ")
                                        )   
    '''
    #process.Baseline += process.calibratedPatElectrons
    from PhysicsTools.SelectorUtils.tools.vid_id_tools import *
    switchOnVIDElectronIdProducer(process, DataFormat.MiniAOD)
    my_id_modules = []
    my_id_modules.append('RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_Spring15_25ns_V1_cff')
    my_id_modules.append('RecoEgamma.ElectronIdentification.Identification.heepElectronID_HEEPV60_cff') 
    my_id_modules.append('RecoEgamma.ElectronIdentification.Identification.heepElectronID_HEEPV70_cff')
    my_id_modules.append('RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Spring15_25ns_nonTrig_V1_cff')
    for idmod in my_id_modules:
        setupAllVIDIdsInModule(process,idmod,setupVIDElectronSelection)

    process.egmGsfElectronIDs.physicsObjectSrc     = cms.InputTag('calibratedPatElectrons')
    process.electronMVAValueMapProducer.srcMiniAOD = cms.InputTag('calibratedPatElectrons')
    process.heepIDVarValueMaps.elesMiniAOD  = cms.InputTag('calibratedPatElectrons')
    process.electronRegressionValueMapProducer.srcMiniAOD = cms.InputTag('calibratedPatElectrons')

    
    
    from LeptoQuarkTreeMaker.Utils.HEEPProducer_cfi import HEEPProducer
    process.HEEPProducer = HEEPProducer.clone(
        eletag = cms.InputTag('calibratedPatElectrons')
    )
    #process.Baseline += process.HEEPProducer
    VectorDouble.extend(['HEEPProducer:trackiso(Electron_trackiso)'])
    #VectorDouble.extend(['HEEPProducer:Eta(Electron_Eta)'])
    VectorDouble.extend(['HEEPProducer:Et(Electron_Et)'])
    VectorDouble.extend(['HEEPProducer:DeltaEtain(Electron_DeltaEtain)'])
    VectorDouble.extend(['HEEPProducer:DeltaPhiin(Electron_DeltaPhiin)'])
    VectorDouble.extend(['HEEPProducer:HbE(Electron_HOverE)'])
    #VectorDouble.extend(['HEEPProducer:SiEtaiEta(Electron_SiEtaiEta)'])
    VectorDouble.extend(['HEEPProducer:Ecaliso(Electron_Ecaliso)'])
    VectorDouble.extend(['HEEPProducer:HD1iso(Electron_HD1iso)'])
    #VectorDouble.extend(['HEEPProducer:HD2iso(Electron_HD2iso)'])
    VectorBool.extend(['HEEPProducer:ecalDriven(Electron_ecalDriven)'])
    #VectorDouble.extend(['HEEPProducer:e25max(Electron_e25max)'])
    #VectorDouble.extend(['HEEPProducer:e55(Electron_e55)'])
    VectorDouble.extend(['HEEPProducer:e25bye55(Electron_e25bye55)'])
    VectorDouble.extend(['HEEPProducer:Fullsce25bye55(Electron_Fullsce25bye55)'])
    VectorDouble.extend(['HEEPProducer:Fulle15bye55(Electron_Fulle15bye55)'])
    VectorDouble.extend(['HEEPProducer:scEnergy(Electron_scEnergy)'])
    VectorDouble.extend(['HEEPProducer:DeltaEtaSeed(Electron_DeltaEtaSeed)'])
    VectorDouble.extend(['HEEPProducer:rho(rho)'])
    VectorInt.extend(['HEEPProducer:Charge(Electron_Charge)'])
    #VectorDouble.extend(['HEEPProducer:ePt(Electron_Pt)'])
    #VectorDouble.extend(['HEEPProducer:e15(Electron_e15)'])
    VectorDouble.extend(['HEEPProducer:ecalEnergy(Electron_ecalEnergy)'])
    VectorDouble.extend(['HEEPProducer:full55SiEtaiEta(Electron_full55SiEtaiEta)'])
    #VectorDouble.extend(['HEEPProducer:sce25max(Electron_sce25max)'])
    #VectorDouble.extend(['HEEPProducer:sce55(Electron_sce55)'])
    VectorDouble.extend(['HEEPProducer:sce25bye55(Electron_sce25bye55)'])
    VectorDouble.extend(['HEEPProducer:e15bye55(Electron_e15bye55)'])
    #VectorDouble.extend(['HEEPProducer:DeltaEtaSeedscandTrack(Electron_DeltaEtaSeedscandTrack)'])
    VectorDouble.extend(['HEEPProducer:Phi(Electron_Phi)'])
    VectorDouble.extend(['HEEPProducer:eEnergy(Electron_Energy)'])
    VectorDouble.extend(['HEEPProducer:dxy(dxy)'])
    VectorInt.extend(['HEEPProducer:losthits(Electron_losthits)'])
    VectorDouble.extend(['HEEPProducer:ePz(Electron_Pz)'])
    #VectorDouble.extend(['HEEPProducer:eTheta(Electron_Theta)'])
    VectorDouble.extend(['HEEPProducer:ePx(Electron_Px)'])
    VectorDouble.extend(['HEEPProducer:ePy(Electron_Py)'])
    #VectorDouble.extend(['HEEPProducer:normalizedChi2(Electron_normalizedChi2)'])
    VectorInt.extend(['HEEPProducer:PDGID(PDGID)'])
    VectorInt.extend(['HEEPProducer:gencharge(gencharge)'])
    VectorDouble.extend(['HEEPProducer:genPt(genPt)'])
    VectorDouble.extend(['HEEPProducer:genEta(genEta)'])
    VectorDouble.extend(['HEEPProducer:genPhi(genPhi)'])
    VectorDouble.extend(['HEEPProducer:genEnergy(genEnergy)'])
    VectorInt.extend(['HEEPProducer:motherPDGID(motherPDGID)'])
    VectorInt.extend(['HEEPProducer:elstatus(elstatus)'])
    VectorDouble.extend(['HEEPProducer:PtHEEP(Electron_PtHEEP)'])
    #VectorDouble.extend(['HEEPProducer:scEtaa(Electron_scEtaa)'])
    VectorDouble.extend(['HEEPProducer:scEta(Electron_scEta)'])
    VectorDouble.extend(['HEEPProducer:heep70TrkIso(Electron_heep70TrkIso)'])
    VectorBool.extend(['HEEPProducer:passEMHD1iso(Electron_passEMHD1iso)'])
    
    
    VectorBool.extend(['HEEPProducer:passShowerShape(Electron_passShowerShape)'])
    VectorBool.extend(['HEEPProducer:passDeltaEta(Electron_passDeltaEta)'])
    VectorBool.extend(['HEEPProducer:passDeltaPhi(Electron_passDeltaPhi)'])
    VectorBool.extend(['HEEPProducer:passEMHD1iso(Electron_passEMHD1iso)'])
    VectorBool.extend(['HEEPProducer:passHoverE(Electron_passHoverE)'])
    VectorBool.extend(['HEEPProducer:passDXY(Electron_passDXY)'])
    VectorBool.extend(['HEEPProducer:passMissingHits(Electron_passMissingHits)'])
    
    VectorBool.extend(['HEEPProducer:passEcaldriven(Electron_passEcaldriven)'])
    VectorBool.extend(['HEEPProducer:passN1TrkIso(Electron_passN1TrkIso)'])
    VectorDouble.extend(['HEEPProducer:worzsystempt(worzsystempt)']) 










    ## Muons
    ## ----------------------------------------------------------------------------------------------

    from LeptoQuarkTreeMaker.Utils.MuonProducer_cfi import MuonProducer
    process.MuonProducer = MuonProducer.clone(
        muontag = cms.InputTag('slimmedMuons')
    )
    #process.Baseline += process.MuonProducer

    #VectorBool.extend(['MuonProducer:MuonisTightMuon(MuonisTightMuon)'])
    #VectorBool.extend(['MuonProducer:MuonisHighPtMuon(MuonisHighPtMuon)'])
    VectorDouble.extend(['MuonProducer:MuonEta(MuonEta)'])
    VectorDouble.extend(['MuonProducer:MuonPhi(MuonPhi)'])
    VectorDouble.extend(['MuonProducer:MuonPt(MuonPt)'])
    VectorDouble.extend(['MuonProducer:MuonEnergy(MuonEnergy)'])
    #VectorDouble.extend(['MuonProducer:MuonPtError(MuonPtError)'])
    #VectorDouble.extend(['MuonProducer:MuonGlobalChi2(MuonGlobalChi2)'])
    #VectorDouble.extend(['MuonProducer:MuonTrkPtError(MuonTrkPtError)'])
    #VectorInt.extend(['MuonProducer:MuonIsPF(MuonIsPF)'])
    VectorInt.extend(['MuonProducer:MuonCharge(MuonCharge)'])
    #VectorInt.extend(['MuonProducer:MuonGlobalTrkValidHits(MuonGlobalTrkValidHits)'])
    #VectorInt.extend(['MuonProducer:MuonTrkPixelHits(MuonTrkPixelHits)'])
    #VectorInt.extend(['MuonProducer:MuonStationMatches(MuonStationMatches)'])
    #VectorDouble.extend(['MuonProducer:MuonPFIsoR04Photon(MuonPFIsoR04Photon)'])
    #VectorDouble.extend(['MuonProducer:MuonPFIsoR04NeutralHadron(MuonPFIsoR04NeutralHadron)'])
    #VectorDouble.extend(['MuonProducer:MuonPFIsoR04PU(MuonPFIsoR04PU)'])
    #VectorDouble.extend(['MuonProducer:MuonTrackerIsoSumPT(MuonTrackerIsoSumPT)'])
    #VectorDouble.extend(['MuonProducer:MuonPFIsoR04ChargedHadron(MuonPFIsoR04ChargedHadron)'])
    VectorInt.extend(['MuonProducer:MuonPassID(MuonPassID)'])
    VectorInt.extend(['MuonProducer:MuonIsGlobal(MuonIsGlobal)'])
    #VectorInt.extend(['MuonProducer:MuonTrackLayersWithMeasurement(MuonTrackLayersWithMeasurement)'])
    #VectorDouble.extend(['MuonProducer:CocktailEta(CocktailPtError)'])
    #VectorDouble.extend(['MuonProducer:CocktailPt(CocktailPt)'])
    #VectorDouble.extend(['MuonProducer:MuonBestTrackVtxDistXY(MuonBestTrackVtxDistXY)'])
    #VectorDouble.extend(['MuonProducer:MuonBestTrackVtxDistZ(MuonBestTrackVtxDistZ)'])

    ## ----------------------------------------------------------------------------------------------
    ## Taus
    ## ----------------------------------------------------------------------------------------------


    from LeptoQuarkTreeMaker.Utils.TauProducer_cfi import TauProducer
    process.TauProducer = TauProducer.clone(
        tautag = cms.InputTag('slimmedTaus')
    )
    #process.Baseline += process.TauProducer
    VectorDouble.extend(['TauProducer:tEta(TauEta)'])
    VectorDouble.extend(['TauProducer:tPhi(TauPhi)'])
    VectorDouble.extend(['TauProducer:tPt(TauPt)'])
    



        
    ## ----------------------------------------------------------------------------------------------
    ## Triggers
    ## ----------------------------------------------------------------------------------------------

    # The trigger results are saved to the tree as a vector
    # Three vectors are saved:
    # 1) names of the triggers
    # 2) trigger results
    # 3) trigger prescales
    # the indexing of these vectors must match
    # If the version number of the input trigger name is omitted,
    # any matching trigger will be included (default behavior)

    from LeptoQuarkTreeMaker.Utils.triggerproducer_cfi import triggerProducer
    from LeptoQuarkTreeMaker.LeptoQuarkTreeMaker.triggerNameList import triggerNameList as _triggerNameList
    process.TriggerProducer = triggerProducer.clone(
        trigTagArg1     = cms.string('TriggerResults'),
        trigTagArg2     = cms.string(''),
        trigTagArg3     = cms.string('HLT'),
        prescaleTagArg1  = cms.string('patTrigger'),
        prescaleTagArg2  = cms.string(''),
        prescaleTagArg3  = cms.string(''),
        triggerNameList = _triggerNameList
    )
    VectorInt.extend(['TriggerProducer:TriggerPass','TriggerProducer:TriggerPrescales'])
    VectorString.extend(['TriggerProducer:TriggerNames'])
    VectorDouble.extend(['TriggerProducer:objectPt'])
    VectorDouble.extend(['TriggerProducer:objecteta'])
    VectorDouble.extend(['TriggerProducer:objectphi'])
    VectorDouble.extend(['TriggerProducer:objectE'])
    VectorDouble.extend(['TriggerProducer:ColumnNum'])


    
    ## ----------------------------------------------------------------------------------------------
    ## JER smearing, various uncertainties
    ## ----------------------------------------------------------------------------------------------
    
    # list of clean tags - ignore jet ID for jets matching these objects
    SkipTag = cms.VInputTag(
    )
    
    # get the JERs (disabled by default)
    # this requires the user to download the .db file from this github
    # https://github.com/cms-jet/JRDatabase
    if len(jerfile)>0:
        #get name of JERs without any directories
        JERera = jerfile.split('/')[-1]
        JERPatch = cms.string('sqlite_file:'+jerfile+'.db')
        if os.getenv('GC_CONF'): 
            JERPatch = cms.string('sqlite_file:../src/'+jerfile+'.db')
    
        process.jer = cms.ESSource("PoolDBESSource",CondDBSetup,
            connect = JERPatch,
            toGet = cms.VPSet(
                cms.PSet(
                    record = cms.string('JetResolutionRcd'),
                    tag    = cms.string('JR_'+JERera+'_PtResolution_AK4PFchs'),
                    label  = cms.untracked.string('AK4PFchs_pt')
                ),
                cms.PSet(
                    record = cms.string('JetResolutionScaleFactorRcd'),
                    tag    = cms.string('JR_'+JERera+'_SF_AK4PFchs'),
                    label  = cms.untracked.string('AK4PFchs')
                ),
            ),
        )

        process.es_prefer_jer = cms.ESPrefer('PoolDBESSource', 'jer')

    # skip all jet smearing and uncertainties for data
    from LeptoQuarkTreeMaker.LeptoQuarkTreeMaker.JetDepot import JetDepot          #........Uncomment it once you start running on MC datasets
    from LeptoQuarkTreeMaker.LeptoQuarkTreeMaker.makeJetVars import makeJetVars

    process = makeJetVars(process,
                          JetTag=JetTag,
                          suff='',
                          skipGoodJets=False,
                          storeProperties=2,
                          geninfo=geninfo,
                          fastsim=fastsim,
                          SkipTag=SkipTag
    )

    
    if geninfo:
        # JEC unc up
        process, JetTagJECup = JetDepot(process,
            JetTag=JetTag,
            jecUncDir=1,
            doSmear=True,
            jerUncDir=0
        )
        process = makeJetVars(process,
                              JetTag=JetTagJECup,
                              suff='JECup',
                              skipGoodJets=False,
                              storeProperties=1,
                              geninfo=geninfo,
                              fastsim=fastsim,
                              SkipTag=SkipTag
        )
        
        # JEC unc down
        process, JetTagJECdown = JetDepot(process,
            JetTag=JetTag,
            jecUncDir=-1,
            doSmear=True,
            jerUncDir=0
        )
        process = makeJetVars(process,
                              JetTag=JetTagJECdown,
                              suff='JECdown',
                              skipGoodJets=False,
                              storeProperties=1,
                              geninfo=geninfo,
                              fastsim=fastsim,
                              SkipTag=SkipTag
        )

        # JER unc up
        process, JetTagJERup = JetDepot(process,
            JetTag=JetTag,
            jecUncDir=0,
            doSmear=True,
            jerUncDir=1
        )
        process = makeJetVars(process,
                              JetTag=JetTagJERup,
                              suff='JERup',
                              skipGoodJets=False,
                              storeProperties=1,
                              geninfo=geninfo,
                              fastsim=fastsim,
                              SkipTag=SkipTag
        )
        
        # JER unc down
        process, JetTagJERdown = JetDepot(process,
            JetTag=JetTag,
            jecUncDir=0,
            doSmear=True,
            jerUncDir=-1
        )
        process = makeJetVars(process,
                              JetTag=JetTagJERdown,
                              suff='JERdown',
                              skipGoodJets=False,
                              storeProperties=1,
                              geninfo=geninfo,
                              fastsim=fastsim,
                              SkipTag=SkipTag
        )

        # finally, do central smearing and replace jet tag
        process, JetTag = JetDepot(process,
            JetTag=JetTag,
            jecUncDir=0,
            doSmear=True,
            jerUncDir=0
        )
        
    ## ----------------------------------------------------------------------------------------------
    ## Jet variables
    ## ----------------------------------------------------------------------------------------------
    '''
    # get updated QG training
    QGPatch = cms.string('sqlite_file:data/QGL_80X.db')
    if os.getenv('GC_CONF'): 
        QGPatch = cms.string('sqlite_file:../src/data/QGL_80X.db')

    process.qgdb = cms.ESSource("PoolDBESSource",CondDBSetup,
        connect = QGPatch,
        toGet   = cms.VPSet(
            cms.PSet(
                record = cms.string('QGLikelihoodRcd'),
                tag    = cms.string('QGLikelihoodObject_80X_AK4PFchs'),
                label  = cms.untracked.string('QGL_AK4PFchs')
            ),
            cms.PSet(
                record = cms.string('QGLikelihoodRcd'),
                tag    = cms.string('QGLikelihoodObject_80X_AK4PFchs_antib'),
                label  = cms.untracked.string('QGL_AK4PFchs_antib')
            ),
        )
    )
    process.es_prefer_qg = cms.ESPrefer("PoolDBESSource","qgdb")
    
    # get QG tagging discriminant
    process.QGTagger = cms.EDProducer('QGTagger',
        srcJets	            = JetTag,
        jetsLabel           = cms.string('QGL_AK4PFchs'),
        srcRho              = cms.InputTag('fixedGridRhoFastjetAll'),		
        srcVertexCollection	= cms.InputTag('offlinePrimaryVerticesWithBS'),
        useQualityCuts	    = cms.bool(False)
    )
    
    # add userfloats & update tag
    process, JetTag = addJetInfo(process, JetTag, ['QGTagger:qgLikelihood','QGTagger:ptD', 'QGTagger:axis2'], ['QGTagger:mult'])
    
    process = makeJetVars(process,
                          JetTag=JetTag,
                          suff='',
                          skipGoodJets=False,
                          storeProperties=2,
                          geninfo=geninfo,
                          fastsim=fastsim,
                          SkipTag=SkipTag
    )
    
    # get double b-tagger (w/ miniAOD customizations)
    process.load("RecoBTag.ImpactParameter.pfImpactParameterAK8TagInfos_cfi")
    process.pfImpactParameterAK8TagInfos.primaryVertex = cms.InputTag("offlineSlimmedPrimaryVertices")
    process.pfImpactParameterAK8TagInfos.candidates = cms.InputTag("packedPFCandidates")
    process.pfImpactParameterAK8TagInfos.jets = JetAK8Tag
    process.load("RecoBTag.SecondaryVertex.pfInclusiveSecondaryVertexFinderAK8TagInfos_cfi")
    process.pfInclusiveSecondaryVertexFinderAK8TagInfos.extSVCollection = cms.InputTag("slimmedSecondaryVertices")
    process.pfInclusiveSecondaryVertexFinderAK8TagInfos.trackIPTagInfos = cms.InputTag("pfImpactParameterAK8TagInfos")
    process.load("RecoBTag.SecondaryVertex.pfBoostedDoubleSVAK8TagInfos_cfi")
    process.load("RecoBTag.SecondaryVertex.candidateBoostedDoubleSecondaryVertexAK8Computer_cfi")
    process.load("RecoBTag.SecondaryVertex.pfBoostedDoubleSecondaryVertexAK8BJetTags_cfi")
    
    # add discriminator and update tag
    process, JetAK8Tag = addJetInfo(process, JetAK8Tag, [], [], cms.VInputTag(cms.InputTag("pfBoostedDoubleSecondaryVertexAK8BJetTags")))
    
    # apply jet ID
    process = makeJetVars(process,
                          JetTag=JetAK8Tag,
                          suff='AK8',
                          skipGoodJets=False,
                          storeProperties=1,
                          geninfo=geninfo,
                          fastsim=fastsim,
                          onlyGoodJets=True
    )
    
    # AK8 jet variables - separate instance of jet properties producer
    from LeptoQuarkTreeMaker.Utils.jetproperties_cfi import jetproperties
    process.JetsPropertiesAK8 = jetproperties.clone(
        JetTag       = JetAK8Tag,
        properties = cms.vstring(
            "prunedMass"           ,
            "NsubjettinessTau1"    ,
            "NsubjettinessTau2"    ,
            "NsubjettinessTau3"    ,
            "bDiscriminatorSubjet1",
            "bDiscriminatorSubjet2",
            "bDiscriminatorCSV"    ,
            "NumBhadrons"          ,
            "NumChadrons"          ,
        )
    )
    #specify userfloats
    process.JetsPropertiesAK8.prunedMass = cms.vstring('ak8PFJetsCHSPrunedMass')
    process.JetsPropertiesAK8.NsubjettinessTau1 = cms.vstring('NjettinessAK8:tau1')
    process.JetsPropertiesAK8.NsubjettinessTau2 = cms.vstring('NjettinessAK8:tau2')
    process.JetsPropertiesAK8.NsubjettinessTau3 = cms.vstring('NjettinessAK8:tau3')
    process.JetsPropertiesAK8.bDiscriminatorSubjet1 = cms.vstring('SoftDrop','pfCombinedInclusiveSecondaryVertexV2BJetTags')
    process.JetsPropertiesAK8.bDiscriminatorSubjet2 = cms.vstring('SoftDrop','pfCombinedInclusiveSecondaryVertexV2BJetTags')
    process.JetsPropertiesAK8.bDiscriminatorCSV = cms.vstring('pfBoostedDoubleSecondaryVertexAK8BJetTags')
    #VectorRecoCand.extend([JetAK8Tag.value()+'(JetsAK8)'])
    VectorDouble.extend(['JetsPropertiesAK8:prunedMass(JetsAK8_prunedMass)',
                         'JetsPropertiesAK8:bDiscriminatorSubjet1(JetsAK8_bDiscriminatorSubjet1CSV)',
                         'JetsPropertiesAK8:bDiscriminatorSubjet2(JetsAK8_bDiscriminatorSubjet2CSV)',
                         'JetsPropertiesAK8:bDiscriminatorCSV(JetsAK8_doubleBDiscriminator)',
                         'JetsPropertiesAK8:NsubjettinessTau1(JetsAK8_NsubjettinessTau1)',
                         'JetsPropertiesAK8:NsubjettinessTau2(JetsAK8_NsubjettinessTau2)',
                         'JetsPropertiesAK8:NsubjettinessTau3(JetsAK8_NsubjettinessTau3)'])
    VectorInt.extend(['JetsPropertiesAK8:NumBhadrons(JetsAK8_NumBhadrons)',
                      'JetsPropertiesAK8:NumChadrons(JetsAK8_NumChadrons)'])

    '''
    ## ----------------------------------------------------------------------------------------------
    ## GenJet variables
    ## ----------------------------------------------------------------------------------------------
    if geninfo:
        # store all genjets
        VectorRecoCand.extend ( [ 'slimmedGenJets(GenJets)' ] )
    
        from LeptoQuarkTreeMaker.Utils.subJetSelection_cfi import SubGenJetSelection
        
        process.GenHTJets = SubGenJetSelection.clone(
            JetTag = cms.InputTag('slimmedGenJets'),
            MinPt  = cms.double(30),
            MaxEta = cms.double(2.4),
        )
        VectorBool.extend(['GenHTJets:SubJetMask(GenJets_HTMask)'])
        
        # make gen HT
        from LeptoQuarkTreeMaker.Utils.htdouble_cfi import htdouble
        process.GenHT = htdouble.clone(
            JetTag = cms.InputTag("GenHTJets"),
        )
        VarsDouble.extend(['GenHT'])
        
        process.GenMHTJets = SubGenJetSelection.clone(
            JetTag = cms.InputTag('slimmedGenJets'),
            MinPt  = cms.double(30),
            MaxEta = cms.double(5.0),
        )
        VectorBool.extend(['GenMHTJets:SubJetMask(GenJets_MHTMask)'])
        
        # make gen MHT
    
    ## ----------------------------------------------------------------------------------------------
    ## Baseline filters
    ## ----------------------------------------------------------------------------------------------
    # sequence for baseline filters
    process.Baseline = cms.Sequence()
        #process.Baseline += process.MHTFilter
    
    ## ----------------------------------------------------------------------------------------------
    ## MET
    ## ----------------------------------------------------------------------------------------------
    from LeptoQuarkTreeMaker.Utils.metdouble_cfi import metdouble
    process.MET = metdouble.clone(
        METTag = METTag,
        GenMETTag = cms.InputTag("slimmedMETs","",tagname), #original collection used deliberately here
        JetTag = cms.InputTag('HTJets'),
        geninfo = cms.untracked.bool(geninfo),
    )
    VarsDouble.extend(['MET:Pt(MET)','MET:Phi(METPhi)','MET:CaloPt(CaloMET)','MET:CaloPhi(CaloMETPhi)','MET:PFCaloPtRatio(PFCaloMETRatio)'])
    if geninfo:
        VarsDouble.extend(['MET:GenPt(GenMET)','MET:GenPhi(GenMETPhi)'])
        VectorDouble.extend(['MET:PtUp(METUp)', 'MET:PtDown(METDown)', 'MET:PhiUp(METPhiUp)', 'MET:PhiDown(METPhiDown)'])

    
    ## ----------------------------------------------------------------------------------------------
    ## ----------------------------------------------------------------------------------------------
    ## Optional producers (background estimations, control regions)
    ## ----------------------------------------------------------------------------------------------
    ## ----------------------------------------------------------------------------------------------

    ## ----------------------------------------------------------------------------------------------
    ## Hadronic Tau Background
    ## ----------------------------------------------------------------------------------------------

    ## ----------------------------------------------------------------------------------------------
    ## Lost Lepton Background
    ## ----------------------------------------------------------------------------------------------
    ## Zinv Background
    ## ----------------------------------------------------------------------------------------------

    ## ----------------------------------------------------------------------------------------------
    ## ----------------------------------------------------------------------------------------------
    ## Final steps
    ## ----------------------------------------------------------------------------------------------
    ## ----------------------------------------------------------------------------------------------

    # create the process path
    process.dump = cms.EDAnalyzer("EventContentAnalyzer")
    process.WriteTree = cms.Path(
        process.Baseline *
        process.LQTreeMaker2
    )
    
    return process
def define_jets(process, reapplyJEC=False, runOnData=False):
    """Define reconstructed jets.
    
    Configure reconstructed jets to be used in an analysis.  In
    particular, reapply JEC if requested.
    
    Arguments:
        process: The process to which relevant jet producers are added.
        reapplyJEC: Flag determining if JEC are to be reapplied or not.
        runOnData: Flag to distinguish processing of data and
            simulation.
    
    Return value:
        Return a tuple with the following elements:
        recorrectedJetsLabel: Label to access collection of jets with
            up-to-date JEC (reapplied or not, depending on the
            configuration) and no kinamatical or quality selection.
        jetQualityCuts: List of string-based quality selections whose
            decisions are to be saved.
    
    Create the following jet collections:
        analysisPatJets: Jets with up-to-date JEC and a loose quality
            selection to be used in an analysis.
    """
    
    # Reapply JEC [1] and evaluate DeepCSV b-taggers [2].  Jet
    # collection is updated regardless of the value of parameter
    # reapplyJEC because of the b-taggers.
    # [1] https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookJetEnergyCorrections?rev=139#CorrPatJets
    # [2] https://twiki.cern.ch/twiki/bin/viewauth/CMS/DeepFlavour?rev=6
    jecLevels = ['L1FastJet', 'L2Relative', 'L3Absolute']
    if runOnData:
        jecLevels.append('L2L3Residual')
    
    from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
    updateJetCollection(
        process, labelName = 'UpdatedJECBTags',
        jetSource = cms.InputTag('slimmedJets'),
        jetCorrections = ('AK4PFchs', cms.vstring(jecLevels), 'None'),
        btagDiscriminators = [
            'deepFlavourJetTags:probbb', 'deepFlavourJetTags:probb',
            'deepFlavourJetTags:probcc', 'deepFlavourJetTags:probc',
            'deepFlavourJetTags:probudsg'
        ]
    )
    
    # When b-tagging is rerun, JEC are first undone, b-taggind is
    # discriminators are evaluated, and then another jet collection is
    # produced.  This is the name that is used for the final collection.
    recorrectedJetsLabel = 'updatedPatJetsTransientCorrectedUpdatedJECBTags'
    
    
    # Define analysis-level jets.  The produced collection will contain
    # all jets that have a chance to pass the given pt threshold thanks
    # to JEC and JER variations.
    process.analysisPatJets = cms.EDFilter('JERCJetSelector',
        src = cms.InputTag(recorrectedJetsLabel),
        jetTypeLabel = cms.string('AK4PFchs'),
        preselection = cms.string('abs(eta) < 5.2'),
        minPt = cms.double(20.),
        includeJERCVariations = cms.bool(not runOnData),
        genJets = cms.InputTag('slimmedGenJets'),
        rho = cms.InputTag('fixedGridRhoFastjetAll')
    )
    
    
    # Additional selection to be evaluated (empty at the moment)
    jetQualityCuts = cms.vstring()
    
    
    return recorrectedJetsLabel, jetQualityCuts
Exemple #10
0
def addParticleNetAK8(process, runParticleNet=False, runParticleNetMD=True):
    if not runParticleNet and not runParticleNetMD:
        return process

    from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
    from RecoBTag.MXNet.pfParticleNet_cff import _pfParticleNetJetTagsProbs as pfParticleNetJetTagsProbs
    from RecoBTag.MXNet.pfParticleNet_cff import _pfMassDecorrelatedParticleNetJetTagsProbs as pfMassDecorrelatedParticleNetJetTagsProbs

    JETCorrLevels = ['L2Relative', 'L3Absolute', 'L2L3Residual']
    bTagDiscriminators = []
    if runParticleNet:
        bTagDiscriminators += pfParticleNetJetTagsProbs
    if runParticleNetMD:
        bTagDiscriminators += pfMassDecorrelatedParticleNetJetTagsProbs

    updateJetCollection(
        process,
        jetSource=cms.InputTag('selectedUpdatedPatJetsAK8WithDeepInfo'),
        rParam=0.8,
        jetCorrections=('AK8PFPuppi', cms.vstring(JETCorrLevels), 'None'),
        btagDiscriminators=bTagDiscriminators,
        postfix='AK8WithParticleNet',
    )
    process.jetCorrFactorsAK8.src = "selectedUpdatedPatJetsAK8WithParticleNet"
    process.updatedJetsAK8.jetSource = "selectedUpdatedPatJetsAK8WithParticleNet"

    from RecoBTag.ONNXRuntime.pfDeepBoostedJetTags_cfi import pfDeepBoostedJetTags as _pfDeepBoostedJetTags
    if runParticleNet:
        process.pfParticleNetJetTagsAK8WithParticleNet = _pfDeepBoostedJetTags.clone(
            src=process.pfParticleNetJetTagsAK8WithParticleNet.src,
            flav_names=process.pfParticleNetJetTagsAK8WithParticleNet.
            flav_names,
            preprocessParams=process.pfParticleNetJetTagsAK8WithParticleNet.
            preprocessParams,
            model_path=
            'PhysicsTools/NanoTuples/data/ParticleNet/ak8/ParticleNet.onnx',
        )
    if runParticleNetMD:
        process.pfMassDecorrelatedParticleNetJetTagsAK8WithParticleNet = _pfDeepBoostedJetTags.clone(
            src=process.pfMassDecorrelatedParticleNetJetTagsAK8WithParticleNet.
            src,
            flav_names=process.
            pfMassDecorrelatedParticleNetJetTagsAK8WithParticleNet.flav_names,
            preprocessParams=process.
            pfMassDecorrelatedParticleNetJetTagsAK8WithParticleNet.
            preprocessParams,
            model_path=
            'PhysicsTools/NanoTuples/data/ParticleNet-MD/ak8/ParticleNetMD.onnx',
        )

    # add nominal taggers
    if runParticleNet:
        for prob in pfParticleNetJetTagsProbs:
            name = 'ParticleNet_' + prob.split(':')[1]
            setattr(
                process.fatJetTable.variables, name,
                Var("bDiscriminator('%s')" % prob,
                    float,
                    doc=prob,
                    precision=-1))

    # add mass-decorelated taggers
    if runParticleNetMD:
        for prob in pfMassDecorrelatedParticleNetJetTagsProbs:
            name = 'ParticleNetMD_' + prob.split(':')[1]
            setattr(
                process.fatJetTable.variables, name,
                Var("bDiscriminator('%s')" % prob,
                    float,
                    doc=prob,
                    precision=-1))

    return process
    elif options.pileup == 200:
        process.ntuple.photonEcorr = cms.FileInPath("PhaseTwoAnalysis/NTupler/data/photonEnergyCorrections_PU200.root")
        process.ntuple.jets = "slimmedJetsPuppi"
        process.ntuple.mets = "slimmedMETsPuppi"

    if options.updateJEC:
        # The updateJetCollection function will uncorred the jets from MiniAOD and then recorrect them using the current
        #  set of JEC in the event setup
        # The new name of the updated jet collection becomes updatedPatJetsUpdatedJECAK4PFPuppi
        from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
        if options.pileup==0:
            if options.rerunBtag:
                updateJetCollection(process,
                                    jetSource = cms.InputTag('slimmedJets'),
                                    postfix = 'UpdatedJECAK4PF',
                                    jetCorrections = ('AK4PF', ['L2Relative','L3Absolute'], 'None'),
                                    pfCandidates       = cms.InputTag('packedPFCandidates'),
                                    btagDiscriminators = ['pfDeepCSVJetTags:probb', 'pfDeepCSVJetTags:probbb'],
                                    )
                process.ntuple.jets = "selectedUpdatedPatJetsUpdatedJECAK4PF"
            else:            
                updateJetCollection(process,
                                    jetSource = cms.InputTag('slimmedJets'),
                                    postfix = 'UpdatedJECAK4PF',
                                    jetCorrections = ('AK4PF', ['L2Relative','L3Absolute'], 'None')
                                    )
                process.ntuple.jets = "updatedPatJetsUpdatedJECAK4PF"
        else:
            if options.rerunBtag:
                updateJetCollection(process,
                                    jetSource = cms.InputTag('slimmedJetsPuppi'),
Exemple #12
0
#                ),
#        ),
#        connect = cms.string(jetDBFile)
#)
#process.es_prefer_jer = cms.ESPrefer('PoolDBESSource', 'jer')
 
# Apply jet energy corrections:
#   https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookJetEnergyCorrections#CorrPatJets
#   https://github.com/cms-sw/cmssw/blob/CMSSW_8_0_X/PhysicsTools/PatAlgos/test/patTuple_updateJets_fromMiniAOD_cfg.py
# This should load them from the global tag
from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection

if varOptions.isMC : 
  updateJetCollection(
    process,
    jetSource = cms.InputTag('slimmedJets'),
    jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
  )
else : 
  updateJetCollection(
    process,
    jetSource = cms.InputTag('slimmedJets'),
    jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual']), 'None'),
  )
process.rootTuplePFJetsAK4CHS.InputTag = cms.InputTag('updatedPatJets')
process.applyCorrections = cms.Path()
process.applyCorrections += process.patJetCorrFactors
process.applyCorrections += process.updatedPatJets

##----------------------------------------------------------------------------------------------------
## MET Re-Corrections and Uncertainties
                     label = cms.untracked.string("AK4PFPuppi"))
            )
                               )
    process.es_prefer_jec = cms.ESPrefer("PoolDBESSource","jec")

process.myana = cms.EDAnalyzer('BasicPatDistrib')
process.load("PhaseTwoAnalysis.BasicPatDistrib.CfiFile_cfi")
#process.myana.useDeepCSV = True
#process.myana.pileup = 0
#process.myana.mets = cms.InputTag("slimmedMETs"),
if options.updateJEC:
    # The updateJetCollection function will uncorred the jets from MiniAOD and then recorrect them using the current
    #  set of JEC in the event setup
    # The new name of the updated jet collection becomes updatedPatJetsUpdatedJECAK4PFPuppi
    from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
    updateJetCollection(process,
                        jetSource = cms.InputTag('slimmedJetsPuppi'),
                        postfix = 'UpdatedJECAK4PFPuppi',
                        jetCorrections = ('AK4PFPuppi', ['L1FastJet','L2Relative','L3Absolute'], 'None')
                        )
    process.myana.jets = "updatedPatJetsUpdatedJECAK4PFPuppi"

process.TFileService = cms.Service("TFileService",
        fileName = cms.string('histos.root') 
)

if options.updateJEC:
    process.p = cms.Path(process.patJetCorrFactorsUpdatedJECAK4PFPuppi * process.updatedPatJetsUpdatedJECAK4PFPuppi * process.myana)
else:
    process.p = cms.Path(process.myana)
         )
)

process.load('Configuration.StandardSequences.Services_cff')
process.load("Configuration.Geometry.GeometryRecoDB_cff")
process.load("Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff")

corList = cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute'])
if options.isData:
    corList = cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual'])

# Re-apply JEC to AK4
from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
updateJetCollection(
    process,
    jetSource = cms.InputTag('slimmedJets'),
    labelName = 'UpdatedJEC',
    jetCorrections = ('AK4PFchs', corList, 'None')
)

# Re-apply JEC to AK8
updateJetCollection(
    process,
    jetSource = cms.InputTag('slimmedJets'),
    labelName = 'UpdatedJECAK8',
    jetCorrections = ('AK8PFchs', corList, 'None')
)

jetsNameAK4="selectedUpdatedPatJetsUpdatedJEC"
jetsNameAK8="selectedUpdatedPatJetsUpdatedJECAK8"
#jetsNameAK10="patJetsReapplyJECAK10"
jetsNameAK10="selectedPatJetsAK10PFCHS"
Exemple #15
0
                       runEnergyCorrections=True,
                       applyEPCombBug=False,
                       autoAdjustParams=True,
                       computeHeepTrkPtIso=True)   #era is new to select between 2016 / 2017,  it defaults to 2017)  
#a sequence egammaPostRecoSeq has now been created and should be added to your path, eg process.p=cms.Path(process.egammaPostRecoSeq)

# Update jet collection
from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
updateJetCollection(
   process,
   jetSource = cms.InputTag('slimmedJets'),
   pvSource = cms.InputTag('offlineSlimmedPrimaryVertices'),
   svSource = cms.InputTag('slimmedSecondaryVertices'),
   jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
   btagDiscriminators = [
      'pfDeepFlavourJetTags:probb',
      'pfDeepFlavourJetTags:probbb',
      'pfDeepFlavourJetTags:problepb',
      'pfDeepFlavourJetTags:probc',
      'pfDeepFlavourJetTags:probuds',
      'pfDeepFlavourJetTags:probg'
      ],
   postfix='NewDFTraining'
)

updateJetCollection(
   process,
   jetSource = cms.InputTag('selectedUpdatedPatJetsNewDFTraining'), # slimmedJets
   labelName = 'UpdatedJEC',
   jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual']), 'None')  # Update: Safe to always add 'L2L3Residual' as MC contains dummy L2L3Residual corrections (always set to 1)
)
Exemple #16
0
    'pfDeepCSVJetTags:probudsg',        
    'pfDeepCSVJetTags:probb',           
    'pfDeepCSVJetTags:probc',           
    'pfDeepCSVJetTags:probbb',          
    'pfDeepFlavourJetTags:probb',
    'pfDeepFlavourJetTags:probbb',
    'pfDeepFlavourJetTags:probc',
    'pfDeepFlavourJetTags:probuds',
    'pfDeepFlavourJetTags:problepb',
    'pfDeepFlavourJetTags:probg',
]

from PhysicsTools.PatAlgos.tools.jetTools import *
updateJetCollection(
    process,
    jetSource = cms.InputTag('slimmedJets'),
    jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
    btagDiscriminators = bTagDiscriminators
)

#update training
process.pfDeepFlavourJetTags.graph_path = cms.FileInPath('RecoBTag/Combined/data/DeepFlavourV03_10X_training/constant_graph.pb')
process.pfDeepFlavourJetTags.lp_names = cms.vstring('cpf_input_batchnorm/keras_learning_phase')

## Initialize analyzer
process.bTaggingExerciseIIAK4Jets = cms.EDAnalyzer(
    'FastBTV',
    jets = cms.InputTag('selectedUpdatedPatJets'), # input jet collection name
    bDiscriminators = cms.PSet(
        CSVv2 = cms.vstring('pfCombinedInclusiveSecondaryVertexV2BJetTags'),
        DeepCSV = cms.vstring(
            'pfDeepCSVJetTags:probb',

# Setup VID for EGM ID
from PhysicsTools.SelectorUtils.tools.vid_id_tools import *
switchOnVIDPhotonIdProducer(process, DataFormat.MiniAOD)
# define which IDs we want to produce
my_id_modules = ['RecoEgamma.PhotonIdentification.Identification.cutBasedPhotonID_Spring15_25ns_V1_cff']
#add them to the VID producer
for idmod in my_id_modules:
    setupAllVIDIdsInModule(process,idmod,setupVIDPhotonSelection)

## update AK4PFchs jet collection in MiniAOD JECs
from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
updateJetCollection(
   process,
   jetSource = cms.InputTag('slimmedJets'),
   labelName = 'UpdatedJEC',
   jetCorrections = ('AK4PFchs', JEC, 'None')  # Do not forget 'L2L3Residual' on data!
)

# main analyzer and inputs
process.diphoton = cms.EDAnalyzer(
    'ExoDiPhotonAnalyzer',
    # photon tag
    photonsMiniAOD = cms.InputTag("slimmedPhotons"),
    minPhotonPt = cms.double(75.),
    # genParticle tag
    genParticlesMiniAOD = cms.InputTag("prunedGenParticles"),
    # vertex tag
    vertices = cms.InputTag("offlineSlimmedPrimaryVertices"),
    # beam spot tag
    beamSpot = cms.InputTag("offlineBeamSpot", "", "RECO"),
Exemple #18
0
		if options.doJetToolbox:
			jetCollection = 'selectedPatJets'+params['algo'].upper()+'PF'+pu_method
		elif options.doMiniAOD and not options.doReclustering:
			#straight from MiniAOD
			jetCollection = "slimmedJets"
			if params['algo'] == 'ak4' and pu_method == "Puppi":
				jetCollection+= "Puppi"
			elif params['algo'] == 'ak8':
				jetCollection+="AK8"

			#If updated the JEC using the patJetUpdater
			if options.useUpdater:
				from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
				updateJetCollection(process,
									jetSource = cms.InputTag(jetCollection),
									postfix = 'UpdatedJEC'+params['jec_payloads'][index],
									jetCorrections = (params['jec_payloads'][index], params['jec_levels'], 'None')
				)
				jetCollection = 'updatedPatJetsUpdatedJEC'+params['jec_payloads'][index]
		elif not options.doMiniAOD and not options.doJetToolbox:
			jetCollection = 'selectedPatJets'+params['algo'].upper()+'PF'+pu_method
			#jetCollection = params['algo']+'PFJets'+pu_method+PUSuffix.upper().replace("L1","L1Fast")

		#################################################
		## Controls the JER and JES used in the analyzer
		#################################################
		from Analysis.JMEDAS.JetDepot import JetDepot

		if not options.UncertaintyOTF:
			if options.JESUncertainty!='none':
				process, jetCollection = JetDepot(process,
def applyDeepBtagging( process, postfix="" ) :

    task = getPatAlgosToolsTask(process)

    from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection

    process.load('PhysicsTools.PatAlgos.slimming.slimmedJets_cfi')

    # update slimmed jets to include DeepFlavour (keep same name)
    # make clone for DeepFlavour-less slimmed jets, so output name is preserved
    addToProcessAndTask('slimmedJetsNoDeepFlavour', process.slimmedJets.clone(), process, task)
    updateJetCollection(
       process,
       jetSource = cms.InputTag('slimmedJetsNoDeepFlavour'),
       # updateJetCollection defaults to MiniAOD inputs but
       # here it is made explicit (as in training or MINIAOD redoing)
       pvSource = cms.InputTag('offlineSlimmedPrimaryVertices'),
       pfCandidates = cms.InputTag('packedPFCandidates'),
       svSource = cms.InputTag('slimmedSecondaryVertices'),
       muSource = cms.InputTag('slimmedMuons'),
       elSource = cms.InputTag('slimmedElectrons'),
       jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
       btagDiscriminators = [
          'pfDeepFlavourJetTags:probb',
          'pfDeepFlavourJetTags:probbb',
          'pfDeepFlavourJetTags:problepb',
          'pfDeepFlavourJetTags:probc',
          'pfDeepFlavourJetTags:probuds',
          'pfDeepFlavourJetTags:probg',
       ],
       postfix = 'SlimmedDeepFlavour'+postfix,
       printWarning = False
    )

    # slimmedJets with DeepFlavour (remove DeepFlavour-less)
    delattr(process, 'slimmedJets')
    addToProcessAndTask('slimmedJets', getattr(process,'selectedUpdatedPatJetsSlimmedDeepFlavour'+postfix).clone(), process, task)
    # delete module not used anymore (slimmedJets substitutes)
    delattr(process, 'selectedUpdatedPatJetsSlimmedDeepFlavour'+postfix)



    # update slimmed jets to include DeepFlavour (keep same name)
    # make clone for DeepDoubleB-less slimmed AK8 jets, so output name is preserved
    addToProcessAndTask('slimmedJetsAK8NoDeepDoubleB', process.slimmedJetsAK8.clone(), process, task)
    updateJetCollection(
       process,
       jetSource = cms.InputTag('slimmedJetsAK8NoDeepDoubleB'),
       # updateJetCollection defaults to MiniAOD inputs but
       # here it is made explicit (as in training or MINIAOD redoing)
       pvSource = cms.InputTag('offlineSlimmedPrimaryVertices'),
       pfCandidates = cms.InputTag('packedPFCandidates'),
       svSource = cms.InputTag('slimmedSecondaryVertices'),
       muSource = cms.InputTag('slimmedMuons'),
       elSource = cms.InputTag('slimmedElectrons'),
       rParam = 0.8,
       jetCorrections = ('AK8PFPuppi', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
       btagDiscriminators = [
          'pfDeepDoubleBJetTags:probQ',
          'pfDeepDoubleBJetTags:probH',
       ],
       postfix = 'SlimmedAK8DeepDoubleB'+postfix,
       printWarning = False
    )

    # slimmedJetsAK8 with DeepDoubleB (remove DeepDoubleB-less)
    delattr(process, 'slimmedJetsAK8')
    addToProcessAndTask('slimmedJetsAK8', getattr(process,'selectedUpdatedPatJetsSlimmedAK8DeepDoubleB'+postfix).clone(), process, task)
    # delete module not used anymore (slimmedJetsAK8 substitutes)
    delattr(process, 'selectedUpdatedPatJetsSlimmedAK8DeepDoubleB'+postfix)
Exemple #20
0
def setupCustomizedAK8(process, runOnMC=False, path=None):
    # recluster Puppi jets
    bTagDiscriminators = [
        'pfCombinedInclusiveSecondaryVertexV2BJetTags',
        'pfBoostedDoubleSecondaryVertexAK8BJetTags',
    ]
    subjetBTagDiscriminators = [
        'pfCombinedInclusiveSecondaryVertexV2BJetTags',
        'pfDeepCSVJetTags:probb',
        'pfDeepCSVJetTags:probbb',
    ]
    JETCorrLevels = ['L2Relative', 'L3Absolute', 'L2L3Residual']

    from PhysicsTools.NanoTuples.jetToolbox_cff import jetToolbox
    jetToolbox(process,
               'ak8',
               'dummySeqAK8',
               'noOutput',
               PUMethod='Puppi',
               JETCorrPayload='AK8PFPuppi',
               JETCorrLevels=JETCorrLevels,
               Cut='pt > 170.0 && abs(rapidity()) < 2.4',
               runOnMC=runOnMC,
               addNsub=True,
               maxTau=3,
               addSoftDrop=True,
               addSoftDropSubjets=True,
               subJETCorrPayload='AK4PFPuppi',
               subJETCorrLevels=JETCorrLevels,
               bTagDiscriminators=bTagDiscriminators,
               subjetBTagDiscriminators=subjetBTagDiscriminators)

    if runOnMC:
        process.ak8GenJetsNoNu.jetPtMin = 100
        process.ak8GenJetsNoNuSoftDrop.jetPtMin = 100

    from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
    from RecoBTag.ONNXRuntime.pfDeepBoostedJet_cff import _pfDeepBoostedJetTagsProbs, _pfMassDecorrelatedDeepBoostedJetTagsProbs
    from RecoBTag.MXNet.pfParticleNet_cff import _pfParticleNetJetTagsProbs, _pfMassDecorrelatedParticleNetJetTagsProbs
    updateJetCollection(
        process,
        jetSource=cms.InputTag('packedPatJetsAK8PFPuppiSoftDrop'),
        rParam=0.8,
        jetCorrections=('AK8PFPuppi', cms.vstring(JETCorrLevels), 'None'),
        btagDiscriminators=bTagDiscriminators + _pfDeepBoostedJetTagsProbs +
        _pfMassDecorrelatedDeepBoostedJetTagsProbs +
        _pfParticleNetJetTagsProbs +
        _pfMassDecorrelatedParticleNetJetTagsProbs,
        postfix='AK8WithPuppiDaughters',
    )

    # src
    srcJets = cms.InputTag('selectedUpdatedPatJetsAK8WithPuppiDaughters')

    # jetID
    process.looseJetIdCustomAK8 = cms.EDProducer(
        "PatJetIDValueMapProducer",
        filterParams=cms.PSet(
            version=cms.string('WINTER16'),
            quality=cms.string('LOOSE'),
        ),
        src=srcJets)

    process.tightJetIdCustomAK8 = cms.EDProducer(
        "PatJetIDValueMapProducer",
        filterParams=cms.PSet(
            version=cms.string('SUMMER18PUPPI'),
            quality=cms.string('TIGHT'),
        ),
        src=srcJets)

    process.tightJetIdLepVetoCustomAK8 = cms.EDProducer(
        "PatJetIDValueMapProducer",
        filterParams=cms.PSet(
            version=cms.string('SUMMER18PUPPI'),
            quality=cms.string('TIGHTLEPVETO'),
        ),
        src=srcJets)

    run2_jme_2016.toModify(process.tightJetIdCustomAK8.filterParams,
                           version="WINTER16")
    run2_jme_2016.toModify(process.tightJetIdLepVetoCustomAK8.filterParams,
                           version="WINTER16")
    run2_jme_2017.toModify(process.tightJetIdCustomAK8.filterParams,
                           version="WINTER17PUPPI")
    run2_jme_2017.toModify(process.tightJetIdLepVetoCustomAK8.filterParams,
                           version="WINTER17PUPPI")

    process.customAK8WithUserData = cms.EDProducer(
        "PATJetUserDataEmbedder",
        src=srcJets,
        userFloats=cms.PSet(),
        userInts=cms.PSet(
            tightId=cms.InputTag("tightJetIdCustomAK8"),
            tightIdLepVeto=cms.InputTag("tightJetIdLepVetoCustomAK8"),
        ),
    )

    run2_jme_2016.toModify(
        process.customAK8WithUserData.userInts,
        looseId=cms.InputTag("looseJetIdCustomAK8"),
        tightIdLepVeto=None,
    )

    process.customAK8Table = cms.EDProducer(
        "SimpleCandidateFlatTableProducer",
        src=cms.InputTag("customAK8WithUserData"),
        name=cms.string("CustomAK8Puppi"),
        cut=cms.string(""),
        doc=cms.string("reclustered ak8 puppi jets"),
        singleton=cms.bool(False),  # the number of entries is variable
        extension=cms.bool(False),  # this is the main table for the jets
        variables=cms.PSet(
            P4Vars,
            jetId=Var(
                "userInt('tightId')*2+4*userInt('tightIdLepVeto')",
                int,
                doc=
                "Jet ID flags bit1 is loose (always false in 2017 since it does not exist), bit2 is tight, bit3 is tightLepVeto"
            ),
            area=Var("jetArea()",
                     float,
                     doc="jet catchment area, for JECs",
                     precision=10),
            rawFactor=Var("1.-jecFactor('Uncorrected')",
                          float,
                          doc="1 - Factor to get back to raw pT",
                          precision=6),
            nPFConstituents=Var("numberOfDaughters()",
                                int,
                                doc="Number of PF candidate constituents"),
            tau1=Var("userFloat('NjettinessAK8Puppi:tau1')",
                     float,
                     doc="Nsubjettiness (1 axis)",
                     precision=10),
            tau2=Var("userFloat('NjettinessAK8Puppi:tau2')",
                     float,
                     doc="Nsubjettiness (2 axis)",
                     precision=10),
            tau3=Var("userFloat('NjettinessAK8Puppi:tau3')",
                     float,
                     doc="Nsubjettiness (3 axis)",
                     precision=10),
            msoftdrop=Var("groomedMass()",
                          float,
                          doc="Corrected soft drop mass with PUPPI",
                          precision=10),
            btagCSVV2=Var(
                "bDiscriminator('pfCombinedInclusiveSecondaryVertexV2BJetTags')",
                float,
                doc=
                " pfCombinedInclusiveSecondaryVertexV2 b-tag discriminator (aka CSVV2)",
                precision=10),
            btagHbb=Var(
                "bDiscriminator('pfBoostedDoubleSecondaryVertexAK8BJetTags')",
                float,
                doc="Higgs to BB tagger discriminator",
                precision=10),
            nBHadrons=Var("jetFlavourInfo().getbHadrons().size()",
                          int,
                          doc="number of b-hadrons"),
            nCHadrons=Var("jetFlavourInfo().getcHadrons().size()",
                          int,
                          doc="number of c-hadrons"),
            subJetIdx1=Var(
                "?nSubjetCollections()>0 && subjets().size()>0?subjets()[0].key():-1",
                int,
                doc="index of first subjet"),
            subJetIdx2=Var(
                "?nSubjetCollections()>0 && subjets().size()>1?subjets()[1].key():-1",
                int,
                doc="index of second subjet"),
        ))
    run2_jme_2016.toModify(
        process.customAK8Table.variables,
        jetId=Var("userInt('tightId')*2+userInt('looseId')",
                  int,
                  doc="Jet ID flags bit1 is loose, bit2 is tight"))
    process.customAK8Table.variables.pt.precision = 10

    # add DeepAK8 scores: nominal
    for prob in _pfDeepBoostedJetTagsProbs:
        name = 'DeepAK8_' + prob.split(':')[1]
        setattr(
            process.customAK8Table.variables, name,
            Var("bDiscriminator('%s')" % prob, float, doc=prob, precision=-1))

    # add DeepAK8 scores: mass decorrelated
    for prob in _pfMassDecorrelatedDeepBoostedJetTagsProbs:
        name = 'DeepAK8MD_' + prob.split(':')[1]
        setattr(
            process.customAK8Table.variables, name,
            Var("bDiscriminator('%s')" % prob, float, doc=prob, precision=-1))

    # add ParticleNet nominal taggers
    for prob in _pfParticleNetJetTagsProbs:
        name = 'ParticleNet_' + prob.split(':')[1]
        setattr(
            process.customAK8Table.variables, name,
            Var("bDiscriminator('%s')" % prob, float, doc=prob, precision=-1))

    # add ParticleNet mass-decorelated taggers
    for prob in _pfMassDecorrelatedParticleNetJetTagsProbs:
        name = 'ParticleNetMD_' + prob.split(':')[1]
        setattr(
            process.customAK8Table.variables, name,
            Var("bDiscriminator('%s')" % prob, float, doc=prob, precision=-1))

    process.customAK8SubJetTable = cms.EDProducer(
        "SimpleCandidateFlatTableProducer",
        src=cms.InputTag("selectedPatJetsAK8PFPuppiSoftDropPacked", "SubJets"),
        cut=cms.string(""),
        name=cms.string("CustomAK8PuppiSubJet"),
        doc=cms.string("reculstered ak8 puppi subjets"),
        singleton=cms.bool(False),  # the number of entries is variable
        extension=cms.bool(False),  # this is the main table for the jets
        variables=cms.PSet(
            P4Vars,
            area=Var("jetArea()",
                     float,
                     doc="jet catchment area, for JECs",
                     precision=10),
            rawFactor=Var("1.-jecFactor('Uncorrected')",
                          float,
                          doc="1 - Factor to get back to raw pT",
                          precision=6),
            btagDeepB=Var(
                "bDiscriminator('pfDeepCSVJetTags:probb')+bDiscriminator('pfDeepCSVJetTags:probbb')",
                float,
                doc="DeepCSV b+bb tag discriminator",
                precision=10),
            btagCSVV2=Var(
                "bDiscriminator('pfCombinedInclusiveSecondaryVertexV2BJetTags')",
                float,
                doc=
                " pfCombinedInclusiveSecondaryVertexV2 b-tag discriminator (aka CSVV2)",
                precision=10),
            nBHadrons=Var("jetFlavourInfo().getbHadrons().size()",
                          int,
                          doc="number of b-hadrons"),
            nCHadrons=Var("jetFlavourInfo().getcHadrons().size()",
                          int,
                          doc="number of c-hadrons"),
        ))
    process.customAK8SubJetTable.variables.pt.precision = 10

    process.customizedAK8Task = cms.Task(process.tightJetIdCustomAK8,
                                         process.tightJetIdLepVetoCustomAK8,
                                         process.customAK8WithUserData,
                                         process.customAK8Table,
                                         process.customAK8SubJetTable)

    if runOnMC:
        process.customGenJetAK8Table = cms.EDProducer(
            "SimpleCandidateFlatTableProducer",
            src=cms.InputTag("ak8GenJetsNoNu"),
            cut=cms.string("pt > 100."),
            name=cms.string("CustomGenJetAK8"),
            doc=cms.string("AK8 GenJets made with visible genparticles"),
            singleton=cms.bool(False),  # the number of entries is variable
            extension=cms.bool(
                False),  # this is the main table for the genjets
            variables=cms.PSet(P4Vars, ))
        process.customGenJetAK8Table.variables.pt.precision = 10

        process.customGenSubJetAK8Table = cms.EDProducer(
            "SimpleCandidateFlatTableProducer",
            src=cms.InputTag("ak8GenJetsNoNuSoftDrop", "SubJets"),
            cut=cms.string(""),
            name=cms.string("CustomGenSubJetAK8"),
            doc=cms.string("AK8 Gen-SubJets made with visible genparticles"),
            singleton=cms.bool(False),  # the number of entries is variable
            extension=cms.bool(
                False),  # this is the main table for the genjets
            variables=cms.PSet(P4Vars, ))
        process.customGenSubJetAK8Table.variables.pt.precision = 10

        process.customizedAK8Task.add(process.customGenJetAK8Table)
        process.customizedAK8Task.add(process.customGenSubJetAK8Table)

    _customizedAK8Task_80X = process.customizedAK8Task.copy()
    _customizedAK8Task_80X.replace(process.tightJetIdLepVetoCustomAK8,
                                   process.looseJetIdCustomAK8)
    run2_jme_2016.toReplaceWith(process.customizedAK8Task,
                                _customizedAK8Task_80X)

    if path is None:
        process.schedule.associate(process.customizedAK8Task)
    else:
        getattr(process, path).associate(process.customizedAK8Task)
                 'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Spring15_25ns_nonTrig_V1_cff',
                 'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Spring15_25ns_Trig_V1_cff',
                 'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Spring16_GeneralPurpose_V1_cff',
                 'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Spring16_HZZ_V1_cff']
for idmod in my_id_modules:
    setupAllVIDIdsInModule(process,idmod,setupVIDElectronSelection)

#process.globalPixelSeeds.OrderedHitsFactoryPSet.maxElement = cms.uint32(100000)
#process.gsfElectrons.MaxElePtForOnlyMVA = cms.double(50.0)

from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
from PhysicsTools.PatAlgos.tools.jetTools import *
deep_discriminators = ["deepFlavourJetTags:probudsg", "deepFlavourJetTags:probb", "deepFlavourJetTags:probc", "deepFlavourJetTags:probbb", "deepFlavourJetTags:probcc" ]
updateJetCollection(
    process,
    jetSource = cms.InputTag('slimmedJets'),
   jetCorrections = ('AK4PFchs', cms.vstring([]), 'None'),
    btagDiscriminators = deep_discriminators
)
updateJetCollection(
    process,
    labelName = 'Puppi',
    jetSource = cms.InputTag('slimmedJetsPuppi'),
   jetCorrections = ('AK4PFchs', cms.vstring([]), 'None'),
    btagDiscriminators = deep_discriminators
)

# Load Ntuple producer cff
process.load("CMS3.NtupleMaker.cms3CoreSequences_cff")
process.load("CMS3.NtupleMaker.cms3GENSequence_cff")
process.load("CMS3.NtupleMaker.cms3PFSequence_cff")
Exemple #22
0
def miniAOD_customizeCommon(process):
    process.patMuons.isoDeposits = cms.PSet()
    process.patElectrons.isoDeposits = cms.PSet()
    process.patTaus.isoDeposits = cms.PSet()
    process.patPhotons.isoDeposits = cms.PSet()
    #
    process.patMuons.embedTrack         = True  # used for IDs
    process.patMuons.embedCombinedMuon  = True  # used for IDs
    process.patMuons.embedMuonBestTrack = True  # used for IDs
    process.patMuons.embedStandAloneMuon = True # maybe?
    process.patMuons.embedPickyMuon = False   # no, use best track
    process.patMuons.embedTpfmsMuon = False   # no, use best track
    process.patMuons.embedDytMuon   = False   # no, use best track
    process.patMuons.addPuppiIsolation = cms.bool(True)
    process.patMuons.puppiIsolationChargedHadrons = cms.InputTag("muonPUPPIIsolation","h+-DR040-ThresholdVeto000-ConeVeto000")
    process.patMuons.puppiIsolationNeutralHadrons = cms.InputTag("muonPUPPIIsolation","h0-DR040-ThresholdVeto000-ConeVeto001")
    process.patMuons.puppiIsolationPhotons        = cms.InputTag("muonPUPPIIsolation","gamma-DR040-ThresholdVeto000-ConeVeto001")
    process.patMuons.puppiNoLeptonsIsolationChargedHadrons = cms.InputTag("muonPUPPINoLeptonsIsolation","h+-DR040-ThresholdVeto000-ConeVeto000")
    process.patMuons.puppiNoLeptonsIsolationNeutralHadrons = cms.InputTag("muonPUPPINoLeptonsIsolation","h0-DR040-ThresholdVeto000-ConeVeto001")
    process.patMuons.puppiNoLeptonsIsolationPhotons        = cms.InputTag("muonPUPPINoLeptonsIsolation","gamma-DR040-ThresholdVeto000-ConeVeto001")

    process.patMuons.computeMiniIso = cms.bool(True)
    process.patMuons.computeMuonMVA = cms.bool(True)
    process.patMuons.computeSoftMuonMVA = cms.bool(True)
    
    #
    # disable embedding of electron and photon associated objects already stored by the ReducedEGProducer
    process.patElectrons.embedGsfElectronCore = False  ## process.patElectrons.embed in AOD externally stored gsf electron core
    process.patElectrons.embedSuperCluster    = False  ## process.patElectrons.embed in AOD externally stored supercluster
    process.patElectrons.embedPflowSuperCluster         = False  ## process.patElectrons.embed in AOD externally stored supercluster
    process.patElectrons.embedSeedCluster               = False  ## process.patElectrons.embed in AOD externally stored the electron's seedcluster
    process.patElectrons.embedBasicClusters             = False  ## process.patElectrons.embed in AOD externally stored the electron's basic clusters
    process.patElectrons.embedPreshowerClusters         = False  ## process.patElectrons.embed in AOD externally stored the electron's preshower clusters
    process.patElectrons.embedPflowBasicClusters        = False  ## process.patElectrons.embed in AOD externally stored the electron's pflow basic clusters
    process.patElectrons.embedPflowPreshowerClusters    = False  ## process.patElectrons.embed in AOD externally stored the electron's pflow preshower clusters
    process.patElectrons.embedRecHits         = False  ## process.patElectrons.embed in AOD externally stored the RecHits - can be called from the PATElectronProducer
    process.patElectrons.electronSource = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.patElectrons.usePfCandidateMultiMap = True
    process.patElectrons.pfCandidateMultiMap    = cms.InputTag("reducedEgamma","reducedGsfElectronPfCandMap")
    process.patElectrons.electronIDSources = cms.PSet()
    from Configuration.Eras.Modifier_run2_miniAOD_80XLegacy_cff import run2_miniAOD_80XLegacy
    run2_miniAOD_80XLegacy.toModify(process.patElectrons,
                                    addPFClusterIso = cms.bool(True),
                                    ecalPFClusterIsoMap = cms.InputTag("reducedEgamma", "eleEcalPFClusIso"),
                                    hcalPFClusterIsoMap = cms.InputTag("reducedEgamma", "eleHcalPFClusIso"))
    from Configuration.Eras.Modifier_run2_miniAOD_94XFall17_cff import run2_miniAOD_94XFall17
    run2_miniAOD_94XFall17.toModify(process.patElectrons,
                                    addPFClusterIso = cms.bool(True),
                                    ecalPFClusterIsoMap = cms.InputTag("reducedEgamma", "eleEcalPFClusIso"),
                                    hcalPFClusterIsoMap = cms.InputTag("reducedEgamma", "eleHcalPFClusIso"))

    #add puppi isolation in miniAOD
    process.patElectrons.addPuppiIsolation = cms.bool(True)
    process.patElectrons.puppiIsolationChargedHadrons = cms.InputTag("egmElectronPUPPIIsolation","h+-DR030-BarVeto000-EndVeto001")
    process.patElectrons.puppiIsolationNeutralHadrons = cms.InputTag("egmElectronPUPPIIsolation","h0-DR030-BarVeto000-EndVeto000")
    process.patElectrons.puppiIsolationPhotons        = cms.InputTag("egmElectronPUPPIIsolation","gamma-DR030-BarVeto000-EndVeto008")
    process.patElectrons.puppiNoLeptonsIsolationChargedHadrons = cms.InputTag("egmElectronPUPPINoLeptonsIsolation","h+-DR030-BarVeto000-EndVeto001")
    process.patElectrons.puppiNoLeptonsIsolationNeutralHadrons = cms.InputTag("egmElectronPUPPINoLeptonsIsolation","h0-DR030-BarVeto000-EndVeto000")
    process.patElectrons.puppiNoLeptonsIsolationPhotons        = cms.InputTag("egmElectronPUPPINoLeptonsIsolation","gamma-DR030-BarVeto000-EndVeto008")

    process.patElectrons.computeMiniIso = cms.bool(True)

    process.elPFIsoDepositChargedPAT.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositChargedAllPAT.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositNeutralPAT.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositGammaPAT.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositPUPAT.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    #
    process.patPhotons.embedSuperCluster = False ## whether to process.patPhotons.embed in AOD externally stored supercluster
    process.patPhotons.embedSeedCluster               = False  ## process.patPhotons.embed in AOD externally stored the photon's seedcluster
    process.patPhotons.embedBasicClusters             = False  ## process.patPhotons.embed in AOD externally stored the photon's basic clusters
    process.patPhotons.embedPreshowerClusters         = False  ## process.patPhotons.embed in AOD externally stored the photon's preshower clusters
    process.patPhotons.embedRecHits         = False  ## process.patPhotons.embed in AOD externally stored the RecHits - can be called from the PATPhotonProducer

    #add puppi isolation in miniAOD
    process.patPhotons.addPuppiIsolation = cms.bool(True)
    process.patPhotons.puppiIsolationChargedHadrons = cms.InputTag("egmPhotonPUPPIIsolation","h+-DR030-")
    process.patPhotons.puppiIsolationNeutralHadrons = cms.InputTag("egmPhotonPUPPIIsolation","h0-DR030-")
    process.patPhotons.puppiIsolationPhotons        = cms.InputTag("egmPhotonPUPPIIsolation","gamma-DR030-")

    from Configuration.Eras.Modifier_run2_miniAOD_80XLegacy_cff import run2_miniAOD_80XLegacy
    run2_miniAOD_80XLegacy.toModify(process.patPhotons,
                                    addPFClusterIso = cms.bool(True),
                                    ecalPFClusterIsoMap = cms.InputTag("reducedEgamma", "phoEcalPFClusIso"),
                                    hcalPFClusterIsoMap = cms.InputTag("reducedEgamma", "phoHcalPFClusIso"))
    from Configuration.Eras.Modifier_run2_miniAOD_94XFall17_cff import run2_miniAOD_94XFall17
    run2_miniAOD_94XFall17.toModify(process.patPhotons,
                                    addPFClusterIso = cms.bool(True),
                                    ecalPFClusterIsoMap = cms.InputTag("reducedEgamma", "phoEcalPFClusIso"),
                                    hcalPFClusterIsoMap = cms.InputTag("reducedEgamma", "phoHcalPFClusIso"))
    #the 80X legacy customsations are done in ootPhotonProducer for OOT photons
    run2_miniAOD_94XFall17.toModify(process.patOOTPhotons,
                                    addPFClusterIso = cms.bool(True),
                                    ecalPFClusterIsoMap = cms.InputTag("reducedEgamma", "ootPhoEcalPFClusIso"),
                                    hcalPFClusterIsoMap = cms.InputTag("reducedEgamma", "ootPhoHcalPFClusIso"))


    process.patPhotons.photonSource = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.patPhotons.electronSource = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    
    process.phPFIsoDepositChargedPAT.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositChargedAllPAT.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositNeutralPAT.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositGammaPAT.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositPUPAT.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    #
    process.patOOTPhotons.photonSource = cms.InputTag("reducedEgamma","reducedOOTPhotons")
    process.patOOTPhotons.electronSource = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    #
    process.selectedPatJets.cut = cms.string("pt > 10")
    process.selectedPatMuons.cut = cms.string("pt > 5 || isPFMuon || (pt > 3 && (isGlobalMuon || isStandAloneMuon || numberOfMatches > 0 || muonID('RPCMuLoose')))")
    
    from Configuration.Eras.Modifier_phase2_muon_cff import phase2_muon
    phase2_muon.toModify(process.selectedPatMuons, cut = "pt > 5 || isPFMuon || (pt > 3 && (isGlobalMuon || isStandAloneMuon || numberOfMatches > 0 || muonID('RPCMuLoose') || muonID('ME0MuonArbitrated') || muonID('GEMMuonArbitrated')) )")
    
    process.selectedPatElectrons.cut = cms.string("")
    process.selectedPatTaus.cut = cms.string("pt > 18. && tauID('decayModeFindingNewDMs')> 0.5")
    process.selectedPatPhotons.cut = cms.string("")

    from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection

    from PhysicsTools.PatAlgos.slimming.applySubstructure_cff import applySubstructure
    applySubstructure( process )

        
    #
    from PhysicsTools.PatAlgos.tools.trigTools import switchOnTriggerStandAlone
    switchOnTriggerStandAlone( process, outputModule = '' )
    process.patTrigger.packTriggerPathNames = cms.bool(True)
    #
    # apply type I + other PFMEt corrections to pat::MET object
    # and estimate systematic uncertainties on MET

    from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncForMiniAODProduction
    runMetCorAndUncForMiniAODProduction(process, metType="PF",
                                        jetCollUnskimmed="patJets")
    
    #caloMET computation
    from PhysicsTools.PatAlgos.tools.metTools import addMETCollection
    addMETCollection(process,
                     labelName = "patCaloMet",
                     metSource = "caloMetM"
                     )

    #noHF pfMET =========

    task = getPatAlgosToolsTask(process)

    process.noHFCands = cms.EDFilter("GenericPFCandidateSelector",
                                     src=cms.InputTag("particleFlow"),
                                     cut=cms.string("abs(pdgId)!=1 && abs(pdgId)!=2 && abs(eta)<3.0")
                                     )
    task.add(process.noHFCands)

    runMetCorAndUncForMiniAODProduction(process,
                                        pfCandColl=cms.InputTag("noHFCands"),
                                        recoMetFromPFCs=True, #needed for HF removal
                                        jetSelection="pt>15 && abs(eta)<3.",
                                        postfix="NoHF"
                                        )

    process.load('PhysicsTools.PatAlgos.slimming.slimmedMETs_cfi')
    task.add(process.slimmedMETs)
    addToProcessAndTask('slimmedMETsNoHF', process.slimmedMETs.clone(), process, task)
    process.slimmedMETsNoHF.src = cms.InputTag("patMETsNoHF")
    process.slimmedMETsNoHF.rawVariation =  cms.InputTag("patPFMetNoHF")
    process.slimmedMETsNoHF.t1Uncertainties = cms.InputTag("patPFMetT1%sNoHF") 
    process.slimmedMETsNoHF.t01Variation = cms.InputTag("patPFMetT0pcT1NoHF")
    process.slimmedMETsNoHF.t1SmearedVarsAndUncs = cms.InputTag("patPFMetT1Smear%sNoHF")
    process.slimmedMETsNoHF.tXYUncForRaw = cms.InputTag("patPFMetTxyNoHF")
    process.slimmedMETsNoHF.tXYUncForT1 = cms.InputTag("patPFMetT1TxyNoHF")
    process.slimmedMETsNoHF.tXYUncForT01 = cms.InputTag("patPFMetT0pcT1TxyNoHF")
    process.slimmedMETsNoHF.tXYUncForT1Smear = cms.InputTag("patPFMetT1SmearTxyNoHF")
    process.slimmedMETsNoHF.tXYUncForT01Smear = cms.InputTag("patPFMetT0pcT1SmearTxyNoHF")
    del process.slimmedMETsNoHF.caloMET
    # ================== NoHF pfMET

    #  ==================  CHSMET 
    process.CHSCands = cms.EDFilter("CandPtrSelector",
                                    src=cms.InputTag("packedPFCandidates"),
                                    cut=cms.string("fromPV(0) > 0")
                                    )
    task.add(process.CHSCands)

    process.pfMetCHS = cms.EDProducer("PFMETProducer",
                                      src = cms.InputTag("CHSCands"),
                                      alias = cms.string('pfMet'),
                                      globalThreshold = cms.double(0.0),
                                      calculateSignificance = cms.bool(False),
                                      )
    task.add(process.pfMetCHS)    

    addMETCollection(process,
                     labelName = "patCHSMet",
                     metSource = "pfMetCHS"
                     )

    process.patCHSMet.computeMETSignificance = cms.bool(False)

    #  ==================  CHSMET 

    #  ==================  TrkMET 
    process.TrkCands = cms.EDFilter("CandPtrSelector",
                                    src=cms.InputTag("packedPFCandidates"),
                                    cut=cms.string("charge()!=0 && pvAssociationQuality()>=4 && vertexRef().key()==0")
                                    )
    task.add(process.TrkCands)

    process.pfMetTrk = cms.EDProducer("PFMETProducer",
                                      src = cms.InputTag("TrkCands"),
                                      alias = cms.string('pfMet'),
                                      globalThreshold = cms.double(0.0),
                                      calculateSignificance = cms.bool(False),
                                      )

    task.add(process.pfMetTrk)

    addMETCollection(process,
                     labelName = "patTrkMet",
                     metSource = "pfMetTrk"
                     )

    process.patTrkMet.computeMETSignificance = cms.bool(False)

    #  ==================  TrkMET 
    

    ## PU JetID
    process.load("RecoJets.JetProducers.PileupJetID_cfi")
    task.add(process.pileUpJetIDTask)

    process.patJets.userData.userFloats.src = [ cms.InputTag("pileupJetId:fullDiscriminant"), ]
    process.patJets.userData.userInts.src = [ cms.InputTag("pileupJetId:fullId"), ]

    ## Quark Gluon Likelihood
    process.load('RecoJets.JetProducers.QGTagger_cfi')
    task.add(process.QGTaggerTask)

    process.patJets.userData.userFloats.src += [ cms.InputTag('QGTagger:qgLikelihood'), ]

    ## DeepCSV meta discriminators (simple arithmethic on output probabilities)
    process.load('RecoBTag.Combined.deepFlavour_cff')
    task.add(process.pfDeepCSVDiscriminatorsJetTags)
    process.patJets.discriminatorSources.extend([
            cms.InputTag('pfDeepCSVDiscriminatorsJetTags:BvsAll' ),
            cms.InputTag('pfDeepCSVDiscriminatorsJetTags:CvsB'   ),
            cms.InputTag('pfDeepCSVDiscriminatorsJetTags:CvsL'   ),
            ])

    ## CaloJets
    process.caloJetMap = cms.EDProducer("RecoJetDeltaRValueMapProducer",
         src = process.patJets.jetSource,
         matched = cms.InputTag("ak4CaloJets"),
         distMax = cms.double(0.4),
         values = cms.vstring('pt','emEnergyFraction'),
	 valueLabels = cms.vstring('pt','emEnergyFraction'),
	 lazyParser = cms.bool(True) )
    task.add(process.caloJetMap)
    process.patJets.userData.userFloats.src += [ cms.InputTag("caloJetMap:pt"), cms.InputTag("caloJetMap:emEnergyFraction") ]

    #Muon object modifications 
    from PhysicsTools.PatAlgos.slimming.muonIsolationsPUPPI_cfi import makeInputForPUPPIIsolationMuon
    makeInputForPUPPIIsolationMuon(process)

    #EGM object modifications 
    from PhysicsTools.PatAlgos.slimming.egmIsolationsPUPPI_cfi import makeInputForPUPPIIsolationEgm
    makeInputForPUPPIIsolationEgm(process)
    from RecoEgamma.EgammaTools.egammaObjectModificationsInMiniAOD_cff import egamma_modifications
    process.slimmedElectrons.modifierConfig.modifications = egamma_modifications
    process.slimmedPhotons.modifierConfig.modifications   = egamma_modifications

    #VID Electron IDs
    process.patElectrons.addElectronID = cms.bool(True)
    electron_ids = ['RecoEgamma.ElectronIdentification.Identification.heepElectronID_HEEPV70_cff',
                    'RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_Fall17_94X_V1_cff',
                    'RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_Fall17_94X_V2_cff',
                    'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Fall17_noIso_V1_cff', 
                    'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Fall17_iso_V1_cff',
                    'RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_Summer16_80X_V1_cff',
                    'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Spring16_GeneralPurpose_V1_cff',
                    'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Spring16_HZZ_V1_cff',
                    ]
    switchOnVIDElectronIdProducer(process,DataFormat.MiniAOD, task)
    process.egmGsfElectronIDs.physicsObjectSrc = \
        cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.electronMVAValueMapProducer.src = \
        cms.InputTag('reducedEgamma','reducedGedGsfElectrons')
    process.electronRegressionValueMapProducer.src = \
        cms.InputTag('reducedEgamma','reducedGedGsfElectrons')
    for idmod in electron_ids:
        setupAllVIDIdsInModule(process,idmod,setupVIDElectronSelection,None,False,task)
        
    #heepIDVarValueMaps only exists if HEEP V6.1 or HEEP 7.0 ID has already been loaded
    if hasattr(process,'heepIDVarValueMaps'):
        process.heepIDVarValueMaps.elesMiniAOD = cms.InputTag('reducedEgamma','reducedGedGsfElectrons')
        #force HEEP to use miniAOD (otherwise it'll detect the AOD)
        process.heepIDVarValueMaps.dataFormat = cms.int32(2)
  
        #add the HEEP trk isol to the slimmed electron, add it to the first FromFloatValMap modifier
        for pset in process.slimmedElectrons.modifierConfig.modifications:
            if pset.hasParameter("modifierName") and pset.modifierName == cms.string('EGExtraInfoModifierFromFloatValueMaps'):
                pset.electron_config.heepTrkPtIso = cms.InputTag("heepIDVarValueMaps","eleTrkPtIso")
                break
               

    #VID Photon IDs
    process.patPhotons.addPhotonID = cms.bool(True)
    photon_ids = ['RecoEgamma.PhotonIdentification.Identification.cutBasedPhotonID_Fall17_94X_V1_TrueVtx_cff',
                  'RecoEgamma.PhotonIdentification.Identification.mvaPhotonID_Fall17_94X_V1_cff', 
                  'RecoEgamma.PhotonIdentification.Identification.mvaPhotonID_Fall17_94X_V1p1_cff', 
                  'RecoEgamma.PhotonIdentification.Identification.cutBasedPhotonID_Spring16_V2p2_cff',
                  'RecoEgamma.PhotonIdentification.Identification.mvaPhotonID_Spring16_nonTrig_V1_cff']
    switchOnVIDPhotonIdProducer(process,DataFormat.AOD, task) 
    process.egmPhotonIsolation.srcToIsolate = \
        cms.InputTag("reducedEgamma","reducedGedPhotons")  
    for iPSet in process.egmPhotonIsolation.isolationConeDefinitions:
        iPSet.particleBasedIsolation = cms.InputTag("reducedEgamma","reducedPhotonPfCandMap")    

    process.egmPhotonIDs.physicsObjectSrc = \
        cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.photonIDValueMapProducer.src = \
        cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.photonRegressionValueMapProducer.src = \
        cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.photonIDValueMapProducer.particleBasedIsolation = \
        cms.InputTag("reducedEgamma","reducedPhotonPfCandMap")
    process.photonMVAValueMapProducer.src = \
        cms.InputTag('reducedEgamma','reducedGedPhotons')
    for idmod in photon_ids:
        setupAllVIDIdsInModule(process,idmod,setupVIDPhotonSelection,None,False,task)
 
    #add the cut base IDs bitmaps of which cuts passed
    from RecoEgamma.EgammaTools.egammaObjectModifications_tools import makeVIDBitsModifier
    egamma_modifications.append(makeVIDBitsModifier(process,"egmGsfElectronIDs","egmPhotonIDs"))

    #-- Adding boosted taus
    from RecoTauTag.Configuration.boostedHPSPFTaus_cfi import addBoostedTaus
    addBoostedTaus(process)
    process.load("RecoTauTag.Configuration.RecoPFTauTag_cff")
    process.load("RecoTauTag.Configuration.HPSPFTaus_cff")
    #-- Adding customization for 94X 2017 legacy reMniAOD
    from Configuration.Eras.Modifier_run2_miniAOD_94XFall17_cff import run2_miniAOD_94XFall17
    _makePatTausTaskWithRetrainedMVATauID = process.makePatTausTask.copy()
    _makePatTausTaskWithRetrainedMVATauID.add(process.hpsPFTauDiscriminationByIsolationMVArun2v1DBoldDMwLTTask)
    run2_miniAOD_94XFall17.toReplaceWith(
        process.makePatTausTask, _makePatTausTaskWithRetrainedMVATauID
        )
    #-- Adding customization for 80X 2016 legacy reMiniAOD
    from Configuration.Eras.Modifier_run2_miniAOD_80XLegacy_cff import run2_miniAOD_80XLegacy
    _makePatTausTaskWithTauReReco = process.makePatTausTask.copy()
    _makePatTausTaskWithTauReReco.add(process.PFTauTask)
    run2_miniAOD_80XLegacy.toReplaceWith(
        process.makePatTausTask, _makePatTausTaskWithTauReReco
        )
    
    # Adding puppi jets
    if not hasattr(process, 'ak4PFJetsPuppi'): #MM: avoid confilct with substructure call
        process.load('RecoJets.JetProducers.ak4PFJetsPuppi_cfi')
        task.add(process.ak4PFJets)
        task.add(process.ak4PFJetsPuppi)
    process.ak4PFJetsPuppi.doAreaFastjet = True # even for standard ak4PFJets this is overwritten in RecoJets/Configuration/python/RecoPFJets_cff
    from RecoJets.JetAssociationProducers.j2tParametersVX_cfi import j2tParametersVX
    process.ak4PFJetsPuppiTracksAssociatorAtVertex = cms.EDProducer("JetTracksAssociatorAtVertex",
        j2tParametersVX,
        jets = cms.InputTag("ak4PFJetsPuppi")
    )
    task.add(process.ak4PFJetsPuppiTracksAssociatorAtVertex)
    process.patJetPuppiCharge = cms.EDProducer("JetChargeProducer",
        src = cms.InputTag("ak4PFJetsPuppiTracksAssociatorAtVertex"),
        var = cms.string('Pt'),
        exp = cms.double(1.0)
    )
    task.add(process.patJetPuppiCharge)

    noDeepFlavourDiscriminators = [x.value() for x in process.patJets.discriminatorSources if not "DeepFlavour" in x.value()]
    addJetCollection(process, postfix   = "", labelName = 'Puppi', jetSource = cms.InputTag('ak4PFJetsPuppi'),
                    jetCorrections = ('AK4PFPuppi', ['L2Relative', 'L3Absolute'], ''),
                    pfCandidates = cms.InputTag("particleFlow"),
                    algo= 'AK', rParam = 0.4, btagDiscriminators = noDeepFlavourDiscriminators
                    )
    
    process.patJetGenJetMatchPuppi.matched = 'slimmedGenJets'
    
    process.patJetsPuppi.jetChargeSource = cms.InputTag("patJetPuppiCharge")

    process.selectedPatJetsPuppi.cut = cms.string("pt > 15")

    from PhysicsTools.PatAlgos.slimming.applyDeepBtagging_cff import applyDeepBtagging
    applyDeepBtagging( process )

    addToProcessAndTask('slimmedJetsPuppiNoMultiplicities', process.slimmedJetsNoDeepFlavour.clone(), process, task)
    process.slimmedJetsPuppiNoMultiplicities.src = cms.InputTag("selectedPatJetsPuppi")
    process.slimmedJetsPuppiNoMultiplicities.packedPFCandidates = cms.InputTag("packedPFCandidates")

    from PhysicsTools.PatAlgos.patPuppiJetSpecificProducer_cfi import patPuppiJetSpecificProducer
    from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
    process.patPuppiJetSpecificProducer = patPuppiJetSpecificProducer.clone(
      src=cms.InputTag("slimmedJetsPuppiNoMultiplicities"),
    )
    task.add(process.patPuppiJetSpecificProducer)
    updateJetCollection(
       process,
       labelName = 'PuppiJetSpecific',
       jetSource = cms.InputTag('slimmedJetsPuppiNoMultiplicities'),
    )
    process.updatedPatJetsPuppiJetSpecific.userData.userFloats.src = ['patPuppiJetSpecificProducer:puppiMultiplicity', 'patPuppiJetSpecificProducer:neutralPuppiMultiplicity', 'patPuppiJetSpecificProducer:neutralHadronPuppiMultiplicity', 'patPuppiJetSpecificProducer:photonPuppiMultiplicity', 'patPuppiJetSpecificProducer:HFHadronPuppiMultiplicity', 'patPuppiJetSpecificProducer:HFEMPuppiMultiplicity' ]
    process.slimmedJetsPuppi = process.selectedUpdatedPatJetsPuppiJetSpecific.clone()
    delattr(process, 'selectedUpdatedPatJetsPuppiJetSpecific')

    task.add(process.slimmedJetsPuppi)
    
    ## puppi met
    from PhysicsTools.PatAlgos.slimming.puppiForMET_cff import makePuppies
    makePuppies( process );

    runMetCorAndUncForMiniAODProduction(process, metType="Puppi",
                                        pfCandColl=cms.InputTag("puppiForMET"),
                                        jetCollUnskimmed="slimmedJetsPuppi",
                                        recoMetFromPFCs=True,
                                        jetFlavor="AK4PFPuppi",
                                        postfix="Puppi"
                                        )
    
    process.load('PhysicsTools.PatAlgos.slimming.slimmedMETs_cfi')
    task.add(process.slimmedMETs)
    addToProcessAndTask('slimmedMETsPuppi', process.slimmedMETs.clone(), process, task)
    process.slimmedMETsPuppi.src = cms.InputTag("patMETsPuppi")
    process.slimmedMETsPuppi.rawVariation =  cms.InputTag("patPFMetPuppi")
    process.slimmedMETsPuppi.t1Uncertainties = cms.InputTag("patPFMetT1%sPuppi")
    process.slimmedMETsPuppi.t01Variation = cms.InputTag("patPFMetT0pcT1Puppi")
    process.slimmedMETsPuppi.t1SmearedVarsAndUncs = cms.InputTag("patPFMetT1Smear%sPuppi")
    process.slimmedMETsPuppi.tXYUncForRaw = cms.InputTag("patPFMetTxyPuppi")
    process.slimmedMETsPuppi.tXYUncForT1 = cms.InputTag("patPFMetT1TxyPuppi")
    process.slimmedMETsPuppi.tXYUncForT01 = cms.InputTag("patPFMetT0pcT1TxyPuppi")
    process.slimmedMETsPuppi.tXYUncForT1Smear = cms.InputTag("patPFMetT1SmearTxyPuppi")
    process.slimmedMETsPuppi.tXYUncForT01Smear = cms.InputTag("patPFMetT0pcT1SmearTxyPuppi")
    del process.slimmedMETsPuppi.caloMET

    # add DetIdAssociatorRecords to EventSetup (for isolatedTracks)
    process.load("TrackingTools.TrackAssociator.DetIdAssociatorESProducer_cff")

    # EGamma objects from HGCal are not yet in GED
    # so add companion collections for Phase-II MiniAOD production
    from Configuration.Eras.Modifier_phase2_hgcal_cff import phase2_hgcal
    process.load("RecoEgamma.EgammaTools.slimmedEgammaFromMultiCl_cff")
    phase2_hgcal.toModify(task, func=lambda t: t.add(process.slimmedEgammaFromMultiClTask))
Exemple #23
0
def miniAOD_customizeCommon(process):
    process.patMuons.isoDeposits = cms.PSet()
    process.patElectrons.isoDeposits = cms.PSet()
    process.patTaus.isoDeposits = cms.PSet()
    process.patPhotons.isoDeposits = cms.PSet()
    #
    process.patMuons.embedTrack         = True  # used for IDs
    process.patMuons.embedCombinedMuon  = True  # used for IDs
    process.patMuons.embedMuonBestTrack = True  # used for IDs
    process.patMuons.embedStandAloneMuon = True # maybe?
    process.patMuons.embedPickyMuon = False   # no, use best track
    process.patMuons.embedTpfmsMuon = False   # no, use best track
    process.patMuons.embedDytMuon   = False   # no, use best track
    #
    # disable embedding of electron and photon associated objects already stored by the ReducedEGProducer
    process.patElectrons.embedGsfElectronCore = False  ## process.patElectrons.embed in AOD externally stored gsf electron core
    process.patElectrons.embedSuperCluster    = False  ## process.patElectrons.embed in AOD externally stored supercluster
    process.patElectrons.embedPflowSuperCluster         = False  ## process.patElectrons.embed in AOD externally stored supercluster
    process.patElectrons.embedSeedCluster               = False  ## process.patElectrons.embed in AOD externally stored the electron's seedcluster
    process.patElectrons.embedBasicClusters             = False  ## process.patElectrons.embed in AOD externally stored the electron's basic clusters
    process.patElectrons.embedPreshowerClusters         = False  ## process.patElectrons.embed in AOD externally stored the electron's preshower clusters
    process.patElectrons.embedPflowBasicClusters        = False  ## process.patElectrons.embed in AOD externally stored the electron's pflow basic clusters
    process.patElectrons.embedPflowPreshowerClusters    = False  ## process.patElectrons.embed in AOD externally stored the electron's pflow preshower clusters
    process.patElectrons.embedRecHits         = False  ## process.patElectrons.embed in AOD externally stored the RecHits - can be called from the PATElectronProducer
    process.patElectrons.electronSource = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.patElectrons.electronIDSources = cms.PSet(
            # configure many IDs as InputTag <someName> = <someTag> you
            # can comment out those you don't want to save some disk space
            eidRobustLoose      = cms.InputTag("reducedEgamma","eidRobustLoose"),
            eidRobustTight      = cms.InputTag("reducedEgamma","eidRobustTight"),
            eidLoose            = cms.InputTag("reducedEgamma","eidLoose"),
            eidTight            = cms.InputTag("reducedEgamma","eidTight"),
            eidRobustHighEnergy = cms.InputTag("reducedEgamma","eidRobustHighEnergy"),
        )
    process.patElectrons.addPFClusterIso = cms.bool(True)
    #add puppi isolation in miniAOD
    process.patElectrons.addPuppiIsolation = cms.bool(True)
    process.patElectrons.puppiIsolationChargedHadrons = cms.InputTag("egmElectronPUPPIIsolation","h+-DR030-BarVeto000-EndVeto001")
    process.patElectrons.puppiIsolationNeutralHadrons = cms.InputTag("egmElectronPUPPIIsolation","h0-DR030-BarVeto000-EndVeto000")
    process.patElectrons.puppiIsolationPhotons        = cms.InputTag("egmElectronPUPPIIsolation","gamma-DR030-BarVeto000-EndVeto008")
    process.patElectrons.puppiNoLeptonsIsolationChargedHadrons = cms.InputTag("egmElectronPUPPINoLeptonsIsolation","h+-DR030-BarVeto000-EndVeto001")
    process.patElectrons.puppiNoLeptonsIsolationNeutralHadrons = cms.InputTag("egmElectronPUPPINoLeptonsIsolation","h0-DR030-BarVeto000-EndVeto000")
    process.patElectrons.puppiNoLeptonsIsolationPhotons        = cms.InputTag("egmElectronPUPPINoLeptonsIsolation","gamma-DR030-BarVeto000-EndVeto008")

    process.patElectrons.ecalPFClusterIsoMap = cms.InputTag("reducedEgamma", "eleEcalPFClusIso")
    process.patElectrons.hcalPFClusterIsoMap = cms.InputTag("reducedEgamma", "eleHcalPFClusIso")

    process.elPFIsoDepositChargedPAT.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositChargedAllPAT.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositNeutralPAT.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositGammaPAT.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositPUPAT.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    #
    process.patPhotons.embedSuperCluster = False ## whether to process.patPhotons.embed in AOD externally stored supercluster
    process.patPhotons.embedSeedCluster               = False  ## process.patPhotons.embed in AOD externally stored the photon's seedcluster
    process.patPhotons.embedBasicClusters             = False  ## process.patPhotons.embed in AOD externally stored the photon's basic clusters
    process.patPhotons.embedPreshowerClusters         = False  ## process.patPhotons.embed in AOD externally stored the photon's preshower clusters
    process.patPhotons.embedRecHits         = False  ## process.patPhotons.embed in AOD externally stored the RecHits - can be called from the PATPhotonProducer
    process.patPhotons.addPFClusterIso = cms.bool(True)

    #add puppi isolation in miniAOD
    process.patPhotons.addPuppiIsolation = cms.bool(True)
    process.patPhotons.puppiIsolationChargedHadrons = cms.InputTag("egmPhotonPUPPIIsolation","h+-DR030-")
    process.patPhotons.puppiIsolationNeutralHadrons = cms.InputTag("egmPhotonPUPPIIsolation","h0-DR030-")
    process.patPhotons.puppiIsolationPhotons        = cms.InputTag("egmPhotonPUPPIIsolation","gamma-DR030-")

    process.patPhotons.ecalPFClusterIsoMap = cms.InputTag("reducedEgamma", "phoEcalPFClusIso")
    process.patPhotons.hcalPFClusterIsoMap = cms.InputTag("reducedEgamma", "phoHcalPFClusIso")
    process.patPhotons.photonSource = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.patPhotons.electronSource = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.patPhotons.photonIDSources = cms.PSet(
                PhotonCutBasedIDLoose = cms.InputTag('reducedEgamma',
                                                      'PhotonCutBasedIDLoose'),
                PhotonCutBasedIDTight = cms.InputTag('reducedEgamma',
                                                      'PhotonCutBasedIDTight')
              )

    process.phPFIsoDepositChargedPAT.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositChargedAllPAT.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositNeutralPAT.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositGammaPAT.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositPUPAT.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    #
    process.selectedPatJets.cut = cms.string("pt > 10")
    process.selectedPatMuons.cut = cms.string("pt > 5 || isPFMuon || (pt > 3 && (isGlobalMuon || isStandAloneMuon || numberOfMatches > 0 || muonID('RPCMuLoose')))")
    process.selectedPatElectrons.cut = cms.string("")
    process.selectedPatTaus.cut = cms.string("pt > 18. && tauID('decayModeFindingNewDMs')> 0.5")
    process.selectedPatPhotons.cut = cms.string("")

    from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection

    from PhysicsTools.PatAlgos.slimming.applySubstructure_cff import applySubstructure
    applySubstructure( process )

        
    #
    from PhysicsTools.PatAlgos.tools.trigTools import switchOnTriggerStandAlone
    switchOnTriggerStandAlone( process, outputModule = '' )
    process.patTrigger.packTriggerPathNames = cms.bool(True)
    #
    # apply type I + other PFMEt corrections to pat::MET object
    # and estimate systematic uncertainties on MET

    from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncForMiniAODProduction
    runMetCorAndUncForMiniAODProduction(process, metType="PF",
                                        jetCollUnskimmed="patJets")
    
    #caloMET computation
    from PhysicsTools.PatAlgos.tools.metTools import addMETCollection
    addMETCollection(process,
                     labelName = "patCaloMet",
                     metSource = "caloMetM"
                     )

    #noHF pfMET =========

    task = getPatAlgosToolsTask(process)

    process.noHFCands = cms.EDFilter("GenericPFCandidateSelector",
                                     src=cms.InputTag("particleFlow"),
                                     cut=cms.string("abs(pdgId)!=1 && abs(pdgId)!=2 && abs(eta)<3.0")
                                     )
    task.add(process.noHFCands)

    runMetCorAndUncForMiniAODProduction(process,
                                        pfCandColl=cms.InputTag("noHFCands"),
                                        recoMetFromPFCs=True, #needed for HF removal
                                        jetSelection="pt>15 && abs(eta)<3.",
                                        postfix="NoHF"
                                        )

    process.load('PhysicsTools.PatAlgos.slimming.slimmedMETs_cfi')
    task.add(process.slimmedMETs)
    addToProcessAndTask('slimmedMETsNoHF', process.slimmedMETs.clone(), process, task)
    process.slimmedMETsNoHF.src = cms.InputTag("patMETsNoHF")
    process.slimmedMETsNoHF.rawVariation =  cms.InputTag("patPFMetNoHF")
    process.slimmedMETsNoHF.t1Uncertainties = cms.InputTag("patPFMetT1%sNoHF") 
    process.slimmedMETsNoHF.t01Variation = cms.InputTag("patPFMetT0pcT1NoHF")
    process.slimmedMETsNoHF.t1SmearedVarsAndUncs = cms.InputTag("patPFMetT1Smear%sNoHF")
    process.slimmedMETsNoHF.tXYUncForRaw = cms.InputTag("patPFMetTxyNoHF")
    process.slimmedMETsNoHF.tXYUncForT1 = cms.InputTag("patPFMetT1TxyNoHF")
    process.slimmedMETsNoHF.tXYUncForT01 = cms.InputTag("patPFMetT0pcT1TxyNoHF")
    process.slimmedMETsNoHF.tXYUncForT1Smear = cms.InputTag("patPFMetT1SmearTxyNoHF")
    process.slimmedMETsNoHF.tXYUncForT01Smear = cms.InputTag("patPFMetT0pcT1SmearTxyNoHF")
    del process.slimmedMETsNoHF.caloMET
    # ================== NoHF pfMET

    #keep this after all addJetCollections otherwise it will attempt computing them also for stuf with no taginfos
    #Some useful BTAG vars
    if not hasattr( process, 'pfImpactParameterTagInfos' ):
        process.load('RecoBTag.ImpactParameter.pfImpactParameterTagInfos_cfi')
        task.add(process.pfImpactParameterTagInfos)
    if not hasattr( process, 'pfSecondaryVertexTagInfos' ):
        process.load('RecoBTag.SecondaryVertex.pfSecondaryVertexTagInfos_cfi')
        task.add(process.pfSecondaryVertexTagInfos)
    process.patJets.userData.userFunctions = cms.vstring(
    '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").secondaryVertex(0).p4.M):(0)',
    '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").secondaryVertex(0).numberOfSourceCandidatePtrs):(0)',
    '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").flightDistance(0).value):(0)',
    '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").flightDistance(0).significance):(0)',
    '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").secondaryVertex(0).p4.x):(0)',
    '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").secondaryVertex(0).p4.y):(0)',
    '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").secondaryVertex(0).p4.z):(0)',
    '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").secondaryVertex(0).vertex.x):(0)',
    '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").secondaryVertex(0).vertex.y):(0)',
    '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").secondaryVertex(0).vertex.z):(0)',
    )
    process.patJets.userData.userFunctionLabels = cms.vstring('vtxMass','vtxNtracks','vtx3DVal','vtx3DSig','vtxPx','vtxPy','vtxPz','vtxPosX','vtxPosY','vtxPosZ')
    process.patJets.tagInfoSources = cms.VInputTag(cms.InputTag("pfSecondaryVertexTagInfos"))
    process.patJets.addTagInfos = cms.bool(True)

    ## Legacy tight b-tag track selection
    ## (this will run below-specified taggers with the tight b-tag track selection enabled
    ## and will add an extra set of b-tag discriminators to 'selectedPatJets'
    ## with the 'tight' prefix added to the usual discriminator names)
    from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
    updateJetCollection(
        process,
        jetSource = cms.InputTag('selectedPatJets'),
        ## updateJetCollection defaults to MiniAOD inputs. Here, this needs to be changed to RECO/AOD inputs
        pvSource = cms.InputTag('offlinePrimaryVertices'),
        pfCandidates = cms.InputTag('particleFlow'),
        svSource = cms.InputTag('inclusiveCandidateSecondaryVertices'),
        muSource = cms.InputTag('muons'),
        elSource = cms.InputTag('gedGsfElectrons'),
        ##
        jetCorrections = ('AK4PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], ''),
        btagDiscriminators = ["pfCombinedSecondaryVertexV2BJetTags", "pfCombinedInclusiveSecondaryVertexV2BJetTags",
                              "pfCombinedCvsLJetTags", "pfCombinedCvsBJetTags"],
        runIVF = True,
        tightBTagNTkHits = True,
        btagPrefix = 'tight',
        postfix = 'BTAG' # added to avoid problems with unrunnable schedule
    )
    #
    ## PU JetID
    process.load("RecoJets.JetProducers.PileupJetID_cfi")
    task.add(process.pileupJetId)
    task.add(process.pileupJetIdCalculator)
    task.add(process.pileupJetIdEvaluator)

    process.patJets.userData.userFloats.src = [ cms.InputTag("pileupJetId:fullDiscriminant"), ]
    process.patJets.userData.userInts.src = [ cms.InputTag("pileupJetId:fullId"), ]

    ## CaloJets
    process.caloJetMap = cms.EDProducer("RecoJetDeltaRValueMapProducer",
         src = process.patJets.jetSource,
         matched = cms.InputTag("ak4CaloJets"),
         distMax = cms.double(0.4),
         values = cms.vstring('pt','emEnergyFraction'),
	 valueLabels = cms.vstring('pt','emEnergyFraction'),
	 lazyParser = cms.bool(True) )
    task.add(process.caloJetMap)
    process.patJets.userData.userFloats.src += [ cms.InputTag("caloJetMap:pt"), cms.InputTag("caloJetMap:emEnergyFraction") ]

    #EGM object modifications 
    from PhysicsTools.PatAlgos.slimming.egmIsolationsPUPPI_cfi import makeInputForPUPPIIsolationEgm
    makeInputForPUPPIIsolationEgm(process)
    from RecoEgamma.EgammaTools.egammaObjectModificationsInMiniAOD_cff import egamma_modifications
    process.slimmedElectrons.modifierConfig.modifications = egamma_modifications
    process.slimmedPhotons.modifierConfig.modifications   = egamma_modifications

    #VID Electron IDs
    electron_ids = ['RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_PHYS14_PU20bx25_V2_cff',
                    'RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_Spring15_25ns_V1_cff',
                    'RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_Spring15_50ns_V2_cff',
                    'RecoEgamma.ElectronIdentification.Identification.heepElectronID_HEEPV60_cff',
                    'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Spring15_25ns_nonTrig_V1_cff',
                    'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Spring15_25ns_Trig_V1_cff',
                    'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Spring15_50ns_Trig_V1_cff']
    switchOnVIDElectronIdProducer(process,DataFormat.MiniAOD, task)
    process.egmGsfElectronIDs.physicsObjectSrc = \
        cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.electronMVAValueMapProducer.src = \
        cms.InputTag('reducedEgamma','reducedGedGsfElectrons')
    process.electronRegressionValueMapProducer.src = \
        cms.InputTag('reducedEgamma','reducedGedGsfElectrons')
    for idmod in electron_ids:
        setupAllVIDIdsInModule(process,idmod,setupVIDElectronSelection,None,False,task)
        
    #heepIDVarValueMaps only exists if HEEP V6.1 or HEEP 7.0 ID has already been loaded
    if hasattr(process,'heepIDVarValueMaps'):
        process.heepIDVarValueMaps.elesMiniAOD = cms.InputTag('reducedEgamma','reducedGedGsfElectrons')
        #force HEEP to use miniAOD (otherwise it'll detect the AOD)
        process.heepIDVarValueMaps.dataFormat = cms.int32(2)
        

    #VID Photon IDs
    photon_ids = ['RecoEgamma.PhotonIdentification.Identification.cutBasedPhotonID_Spring15_25ns_V1_cff',
                  'RecoEgamma.PhotonIdentification.Identification.cutBasedPhotonID_Spring15_50ns_V1_cff',
                  'RecoEgamma.PhotonIdentification.Identification.mvaPhotonID_Spring15_25ns_nonTrig_V2p1_cff',
                  'RecoEgamma.PhotonIdentification.Identification.mvaPhotonID_Spring15_50ns_nonTrig_V2p1_cff']
    switchOnVIDPhotonIdProducer(process,DataFormat.MiniAOD, task)
    process.egmPhotonIDs.physicsObjectSrc = \
        cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.photonIDValueMapProducer.src = \
        cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.photonRegressionValueMapProducer.src = \
        cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.photonIDValueMapProducer.particleBasedIsolation = \
        cms.InputTag("reducedEgamma","reducedPhotonPfCandMap")
    process.photonMVAValueMapProducer.src = \
        cms.InputTag('reducedEgamma','reducedGedPhotons')
    for idmod in photon_ids:
        setupAllVIDIdsInModule(process,idmod,setupVIDPhotonSelection,None,False,task)

    #---------------------------------------------------------------------------
    #Adding  Boosted Subjets taus
    from RecoTauTag.Configuration.boostedHPSPFTaus_cfi import addBoostedTaus
    addBoostedTaus(process)
    #---------------------------------------------------------------------------

    # Adding puppi jets
    process.load('RecoJets.JetProducers.ak4PFJetsPuppi_cfi')
    task.add(process.ak4PFJets)
    task.add(process.ak4PFJetsPuppi)
    process.ak4PFJetsPuppi.doAreaFastjet = True # even for standard ak4PFJets this is overwritten in RecoJets/Configuration/python/RecoPFJets_cff

    from RecoJets.JetAssociationProducers.j2tParametersVX_cfi import j2tParametersVX
    process.ak4PFJetsPuppiTracksAssociatorAtVertex = cms.EDProducer("JetTracksAssociatorAtVertex",
        j2tParametersVX,
        jets = cms.InputTag("ak4PFJetsPuppi")
    )
    task.add(process.ak4PFJetsPuppiTracksAssociatorAtVertex)
    process.patJetPuppiCharge = cms.EDProducer("JetChargeProducer",
        src = cms.InputTag("ak4PFJetsPuppiTracksAssociatorAtVertex"),
        var = cms.string('Pt'),
        exp = cms.double(1.0)
    )
    task.add(process.patJetPuppiCharge)

    addJetCollection(process, postfix   = "", labelName = 'Puppi', jetSource = cms.InputTag('ak4PFJetsPuppi'),
                    jetCorrections = ('AK4PFPuppi', ['L2Relative', 'L3Absolute'], ''),
                    algo= 'AK', rParam = 0.4, btagDiscriminators = map(lambda x: x.value() ,process.patJets.discriminatorSources)
                    )
    
    process.patJetGenJetMatchPuppi.matched = 'slimmedGenJets'
    
    process.patJetsPuppi.jetChargeSource = cms.InputTag("patJetPuppiCharge")

    process.selectedPatJetsPuppi.cut = cms.string("pt > 15")

    process.load('PhysicsTools.PatAlgos.slimming.slimmedJets_cfi')
    task.add(process.slimmedJets)
    task.add(process.slimmedJetsAK8)
    addToProcessAndTask('slimmedJetsPuppi', process.slimmedJets.clone(), process, task)
    process.slimmedJetsPuppi.src = cms.InputTag("selectedPatJetsPuppi")    
    process.slimmedJetsPuppi.packedPFCandidates = cms.InputTag("packedPFCandidates")

    
    ## puppi met
    from PhysicsTools.PatAlgos.slimming.puppiForMET_cff import makePuppies
    makePuppies( process );

    runMetCorAndUncForMiniAODProduction(process, metType="Puppi",
                                        pfCandColl=cms.InputTag("puppiForMET"),
                                        jetCollUnskimmed="slimmedJetsPuppi",
                                        recoMetFromPFCs=True,
                                        jetFlavor="AK4PFPuppi",
                                        postfix="Puppi"
                                        )
    
    process.load('PhysicsTools.PatAlgos.slimming.slimmedMETs_cfi')
    task.add(process.slimmedMETs)
    addToProcessAndTask('slimmedMETsPuppi', process.slimmedMETs.clone(), process, task)
    process.slimmedMETsPuppi.src = cms.InputTag("patMETsPuppi")
    process.slimmedMETsPuppi.rawVariation =  cms.InputTag("patPFMetPuppi")
    process.slimmedMETsPuppi.t1Uncertainties = cms.InputTag("patPFMetT1%sPuppi")
    process.slimmedMETsPuppi.t01Variation = cms.InputTag("patPFMetT0pcT1Puppi")
    process.slimmedMETsPuppi.t1SmearedVarsAndUncs = cms.InputTag("patPFMetT1Smear%sPuppi")
    process.slimmedMETsPuppi.tXYUncForRaw = cms.InputTag("patPFMetTxyPuppi")
    process.slimmedMETsPuppi.tXYUncForT1 = cms.InputTag("patPFMetT1TxyPuppi")
    process.slimmedMETsPuppi.tXYUncForT01 = cms.InputTag("patPFMetT0pcT1TxyPuppi")
    process.slimmedMETsPuppi.tXYUncForT1Smear = cms.InputTag("patPFMetT1SmearTxyPuppi")
    process.slimmedMETsPuppi.tXYUncForT01Smear = cms.InputTag("patPFMetT0pcT1SmearTxyPuppi")
    del process.slimmedMETsPuppi.caloMET
Exemple #24
0
)

process.es_prefer_jer = cms.ESPrefer("PoolDBESSource", "jer")


################ end sqlite connection
#### RECOMPUTE JEC From GT ###
from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection

jecLevels = ["L1FastJet", "L2Relative", "L3Absolute"]
if options.isData:
    jecLevels = ["L1FastJet", "L2Relative", "L3Absolute", "L2L3Residual"]

updateJetCollection(
    process,
    jetSource=process.nero.jets,
    labelName="UpdatedJEC",
    jetCorrections=("AK4PFchs", cms.vstring(jecLevels), "None"),  # Do not forget 'L2L3Residual' on data!
)

updateJetCollection(
    process,
    jetSource=process.nero.chsAK8,
    labelName="UpdatedJECAK8",
    jetCorrections=("AK8PFchs", cms.vstring(jecLevels), "None"),  # Do not forget 'L2L3Residual' on data!
)

print "-> Updating the jets collection to run on to 'updatedPatJetsUpdatedJEC' with the new jec in the GT"
process.nero.jets = cms.InputTag("updatedPatJetsUpdatedJEC")
process.nero.chsAK8 = cms.InputTag("updatedPatJetsUpdatedJECAK8")
process.jecSequence = cms.Sequence(
    process.patJetCorrFactorsUpdatedJEC
def makeTreeFromMiniAOD(
process,
outfile,
reportfreq=10,
dataset="",
globaltag="",
numevents=-1,
lostlepton=False,
geninfo=False,
tagname="RECO",
jsonfile="",
jecfile="",
residual=False,
jerfile="",
pufile="",
doPDFs=False,
fastsim=False,
signal=False,
):

    ## ----------------------------------------------------------------------------------------------
    ## ----------------------------------------------------------------------------------------------
    ## Preamble
    ## ----------------------------------------------------------------------------------------------
    ## ----------------------------------------------------------------------------------------------
    
    process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff")
    process.GlobalTag.globaltag = globaltag

    # log output
    process.load("FWCore.MessageService.MessageLogger_cfi")
    process.MessageLogger.cerr.FwkReport.reportEvery = reportfreq
    process.options = cms.untracked.PSet(
        allowUnscheduled = cms.untracked.bool(True),
#        wantSummary = cms.untracked.bool(True) # off by default
    )

    # files to process
    import FWCore.PythonUtilities.LumiList as LumiList
    process.maxEvents = cms.untracked.PSet(
        input = cms.untracked.int32(numevents)
    )
    process.source = cms.Source("PoolSource",
        fileNames = cms.untracked.vstring(dataset)
    )
    if len(jsonfile)>0: process.source.lumisToProcess = LumiList.LumiList(filename = jsonfile).getVLuminosityBlockRange()

    # output file
    process.TFileService = cms.Service("TFileService",
        fileName = cms.string(outfile+".root")
    )
    # branches for treemaker
    VectorRecoCand       = cms.vstring() 
    VarsDouble           = cms.vstring()
    VarsInt              = cms.vstring()
    VarsBool             = cms.vstring()
    VectorTLorentzVector = cms.vstring()
    VectorDouble         = cms.vstring()
    VectorString         = cms.vstring()
    VectorInt            = cms.vstring()
    VectorBool           = cms.vstring()
    process.Baseline = cms.Sequence()
    # configure treemaker
    from LeptoQuarkTreeMaker.LeptoQuarkTreeMaker.treeMaker import TreeMaker
    process.LQTreeMaker2 = TreeMaker.clone(
        TreeName             = cms.string("SimpleTree"),
        VectorRecoCand       = VectorRecoCand, 
        VarsDouble           = VarsDouble,
        VarsInt              = VarsInt,
        VarsBool             = VarsBool,
        VectorTLorentzVector = VectorTLorentzVector,
        VectorDouble         = VectorDouble,
        VectorInt            = VectorInt,
        VectorString         = VectorString,
        VectorBool           = VectorBool,
    )

    ## ----------------------------------------------------------------------------------------------
    ## ----------------------------------------------------------------------------------------------
    ## Standard producers
    ## ----------------------------------------------------------------------------------------------
    ## ----------------------------------------------------------------------------------------------

    ## ----------------------------------------------------------------------------------------------
    ## SUSY scan info
    ## ----------------------------------------------------------------------------------------------
    ## ----------------------------------------------------------------------------------------------
    ## WeightProducer
    ## ----------------------------------------------------------------------------------------------
    if geninfo:
        from LeptoQuarkTreeMaker.WeightProducer.getWeightProducer_cff import getWeightProducer
        process.WeightProducer = getWeightProducer(process.source.fileNames[0],fastsim and signal)
        process.WeightProducer.Lumi                       = cms.double(1) #default: 1 pb-1 (unit value)
        process.WeightProducer.FileNamePUDataDistribution = cms.string(pufile)
        VarsDouble.extend(['WeightProducer:weight(Weight)','WeightProducer:xsec(CrossSection)','WeightProducer:nevents(NumEvents)',
                           'WeightProducer:TrueNumInteractions','WeightProducer:PUweight(puWeight)','WeightProducer:PUSysUp(puSysUp)','WeightProducer:PUSysDown(puSysDown)'])
        VarsInt.extend(['WeightProducer:NumInteractions'])

    ## ----------------------------------------------------------------------------------------------
    ## PDF weights for PDF systematics
    ## ----------------------------------------------------------------------------------------------
    if geninfo and doPDFs:
        process.PDFWeights = cms.EDProducer('PDFWeightProducer')
        VectorDouble.extend(['PDFWeights:PDFweights','PDFWeights:ScaleWeights'])
        VectorInt.extend(['PDFWeights:PDFids'])

    ## ----------------------------------------------------------------------------------------------
    ## GenHT for stitching together MC samples
    ## ----------------------------------------------------------------------------------------------
    
    ## ----------------------------------------------------------------------------------------------
    ## PrimaryVertices
    ## ----------------------------------------------------------------------------------------------
    process.goodVertices = cms.EDFilter("VertexSelector",
        src = cms.InputTag("offlineSlimmedPrimaryVertices"),
        cut = cms.string("!isFake && ndof > 4 && abs(z) < 24 && position.Rho < 2"),
        filter = cms.bool(False)
    )
    from LeptoQuarkTreeMaker.Utils.primaryvertices_cfi import primaryvertices
    process.NVtx = primaryvertices.clone(
        VertexCollection  = cms.InputTag('goodVertices'),
    )
    VarsInt.extend(['NVtx'])
    # also store total number of vertices without quality checks
    process.nAllVertices = primaryvertices.clone(
        VertexCollection  = cms.InputTag('offlineSlimmedPrimaryVertices'),
    )
    VarsInt.extend(['nAllVertices'])

    ## ----------------------------------------------------------------------------------------------
    ## GenParticles
    ## ----------------------------------------------------------------------------------------------
    ## JECs
    ## ----------------------------------------------------------------------------------------------

    process.load("CondCore.DBCommon.CondDBCommon_cfi")
    from CondCore.DBCommon.CondDBSetup_cfi import CondDBSetup
    
    # default miniAOD tags
    JetTag = cms.InputTag('slimmedJets')
    JetAK8Tag = cms.InputTag('slimmedJetsAK8')
    METTag = cms.InputTag('slimmedMETs')
    
    # get the JECs (disabled by default)
    # this requires the user to download the .db file from this twiki
    # https://twiki.cern.ch/twiki/bin/viewauth/CMS/JECDataMC
    if len(jecfile)>0:
        #get name of JECs without any directories
        JECera = jecfile.split('/')[-1]
        JECPatch = cms.string('sqlite_file:'+jecfile+'.db')
        if os.getenv('GC_CONF'): 
            JECPatch = cms.string('sqlite_file:../src/'+jecfile+'.db')

        process.jec = cms.ESSource("PoolDBESSource",CondDBSetup,
            connect = JECPatch,
            toGet   = cms.VPSet(
                cms.PSet(
                    record = cms.string("JetCorrectionsRecord"),
                    tag    = cms.string("JetCorrectorParametersCollection_"+JECera+"_AK4PFchs"),
                    label  = cms.untracked.string("AK4PFchs")
                ),
                cms.PSet(
                    record = cms.string("JetCorrectionsRecord"),
                    tag    = cms.string("JetCorrectorParametersCollection_"+JECera+"_AK4PF"),
                    label  = cms.untracked.string("AK4PF")
                ),
                cms.PSet(
                    record = cms.string("JetCorrectionsRecord"),
                    tag    = cms.string("JetCorrectorParametersCollection_"+JECera+"_AK8PFchs"),
                    label  = cms.untracked.string("AK8PFchs")
                ),
            )
        )
        process.es_prefer_jec = cms.ESPrefer("PoolDBESSource","jec")
        
        levels  = ['L1FastJet','L2Relative','L3Absolute']
        if residual: levels.append('L2L3Residual')
        
        from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
        
        updateJetCollection(
            process,
            jetSource = cms.InputTag('slimmedJets'),
            postfix = 'UpdatedJEC',
            jetCorrections = ('AK4PFchs', levels, 'None')
        )
        
        JetTag = cms.InputTag('updatedPatJetsUpdatedJEC')
        
        # also update the corrections for AK8 jets
        updateJetCollection(
            process,
            jetSource = cms.InputTag('slimmedJetsAK8'),
            labelName = 'AK8',
            postfix = 'UpdatedJEC',
            jetCorrections = ('AK8PFchs', levels, 'None')
        )
        
        JetAK8Tag = cms.InputTag('updatedPatJetsAK8UpdatedJEC')
        
        # update the MET to account for the new JECs
        from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
        runMetCorAndUncFromMiniAOD(
            process,
            isData=not geninfo, # controls gen met
        )
        METTag = cms.InputTag('slimmedMETs','',process.name_())
    else:
        # pointless run of MET tool because it is barely functional
        from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
        runMetCorAndUncFromMiniAOD(
            process,
            isData=not geninfo, # controls gen met
        )

    # keep jets before any further modifications for hadtau
    JetTagBeforeSmearing = JetTag
    # JEC uncertainty - after JECs are updated
    from LeptoQuarkTreeMaker.Utils.jetuncertainty_cfi import JetUncertaintyProducer
    process.jecUnc = JetUncertaintyProducer.clone(
        JetTag = JetTag,
        jecUncDir = cms.int32(0)
    )
    # JER factors - central, up, dow
    
    from LeptoQuarkTreeMaker.Utils.smearedpatjet_cfi import SmearedPATJetProducer
    process.jerFactor = SmearedPATJetProducer.clone(
        src = JetTag,
        variation = cms.int32(0),
        store_factor = cms.bool(True)
    )
    process.jerFactorUp = SmearedPATJetProducer.clone(
        src = JetTag,
        variation = cms.int32(1),
        store_factor = cms.bool(True)
    )
    process.jerFactorDown = SmearedPATJetProducer.clone(
        src = JetTag,
        variation = cms.int32(-1),
        store_factor = cms.bool(True)
    )
    
    # add userfloat & update tag
    from LeptoQuarkTreeMaker.LeptoQuarkTreeMaker.addJetInfo import addJetInfo
    process, JetTag = addJetInfo(process, JetTag, ['jecUnc','jerFactor','jerFactorUp','jerFactorDown'], [])

    ## ----------------------------------------------------------------------------------------------
    ## IsoTracks
    ## ----------------------------------------------------------------------------------------------
    
    ## ----------------------------------------------------------------------------------------------
    ## Electrons/Muons
    ## ----------------------------------------------------------------------------------------------
    # The decision was made to include the filter decision flags
    # as individual branches in the tree
    
    if not fastsim: # MET filters are not run for fastsim samples

        from LeptoQuarkTreeMaker.Utils.filterdecisionproducer_cfi import filterDecisionProducer
        
        process.CSCTightHaloFilter = filterDecisionProducer.clone(
            trigTagArg1 = cms.string('TriggerResults'),
            trigTagArg2 = cms.string(''),
            trigTagArg3 = cms.string(tagname),
            filterName  = cms.string("Flag_CSCTightHalo2015Filter"),
        )
        VarsInt.extend(['CSCTightHaloFilter'])
        
        process.globalTightHalo2016Filter = filterDecisionProducer.clone(
            trigTagArg1 = cms.string('TriggerResults'),
            trigTagArg2 = cms.string(''),
            trigTagArg3 = cms.string(tagname),
            filterName  = cms.string("Flag_globalTightHalo2016Filter"),
        )
        VarsInt.extend(['globalTightHalo2016Filter'])
        
        process.HBHENoiseFilter = filterDecisionProducer.clone(
            trigTagArg1 = cms.string('TriggerResults'),
            trigTagArg2 = cms.string(''),
            trigTagArg3 = cms.string(tagname),
            filterName  = cms.string("Flag_HBHENoiseFilter"),
        )
        VarsInt.extend(['HBHENoiseFilter'])
        
        process.HBHEIsoNoiseFilter = filterDecisionProducer.clone(
            trigTagArg1 = cms.string('TriggerResults'),
            trigTagArg2 = cms.string(''),
            trigTagArg3 = cms.string(tagname),
            filterName  = cms.string("Flag_HBHENoiseIsoFilter"),
        )
        VarsInt.extend(['HBHEIsoNoiseFilter'])
        
        process.EcalDeadCellTriggerPrimitiveFilter = filterDecisionProducer.clone(
            trigTagArg1 = cms.string('TriggerResults'),
            trigTagArg2 = cms.string(''),
            trigTagArg3 = cms.string(tagname),
            filterName  = cms.string("Flag_EcalDeadCellTriggerPrimitiveFilter"),
        )
        VarsInt.extend(['EcalDeadCellTriggerPrimitiveFilter'])
        
        process.eeBadScFilter = filterDecisionProducer.clone(
            trigTagArg1  = cms.string('TriggerResults'),
            trigTagArg2  = cms.string(''),
            trigTagArg3  = cms.string(tagname),
            filterName  =   cms.string("Flag_eeBadScFilter"),
        )
        VarsInt.extend(['eeBadScFilter'])
        
        # some filters need to be rerun
        process.load('RecoMET.METFilters.BadChargedCandidateFilter_cfi')
        process.BadChargedCandidateFilter.muons = cms.InputTag("slimmedMuons")
        process.BadChargedCandidateFilter.PFCandidates = cms.InputTag("packedPFCandidates")
        process.BadChargedCandidateFilter.taggingMode = True
        VarsBool.extend(['BadChargedCandidateFilter'])
        
        process.load('RecoMET.METFilters.BadPFMuonFilter_cfi')
        process.BadPFMuonFilter.muons = cms.InputTag("slimmedMuons")
        process.BadPFMuonFilter.PFCandidates = cms.InputTag("packedPFCandidates")
        process.BadPFMuonFilter.taggingMode = True
        VarsBool.extend(['BadPFMuonFilter'])
    '''
    process.load('Configuration.StandardSequences.Services_cff')
    process.RandomNumberGeneratorService = cms.Service("RandomNumberGeneratorService",
                                                   calibratedPatElectrons  = cms.PSet( 
                                                     initialSeed = cms.untracked.uint32(81),
                                                     engineName = cms.untracked.string('TRandom3'),
                                                     ),
                                                   calibratedPatPhotons  = cms.PSet( 
                                                     initialSeed = cms.untracked.uint32(81),
                                                     engineName = cms.untracked.string('TRandom3'),
                                                     ),
                                                   )
    process.load('EgammaAnalysis.ElectronTools.calibratedElectronsRun2_cfi')
    correctionType = "80Xapproval"
    
    calibratedPatElectrons = cms.EDProducer("CalibratedPatElectronProducerRun2",
                                        
                                        # input collections
                                        electrons = cms.InputTag('slimmedElectrons'),
                                        gbrForestName = cms.string("gedelectron_p4combination_25ns"),
                                        
                                        # data or MC corrections
                                        # if isMC is false, data corrections are applied
                                        isMC = cms.bool(False),
                                        
                                        # set to True to get special "fake" smearing for synchronization. Use JUST in case of synchronization
                                        isSynchronization = cms.bool(False),

                                        correctionFile = cms.string("80Xapproval")
                                        )   
    process.Baseline += process.calibratedPatElectrons

    
    
    from LeptoQuarkTreeMaker.Utils.HEEPProducer_cfi import HEEPProducer
    process.HEEPProducer = HEEPProducer.clone(
        eletag = cms.InputTag('slimmedElectrons')
    )
    process.Baseline += process.HEEPProducer
    VectorDouble.extend(['HEEPProducer:trackiso(Electron_trackiso)'])
    VectorDouble.extend(['HEEPProducer:Eta(Electron_Eta)'])
    VectorDouble.extend(['HEEPProducer:Et(Electron_Et)'])
    VectorDouble.extend(['HEEPProducer:DeltaEtain(Electron_DeltaEtain)'])
    VectorDouble.extend(['HEEPProducer:DeltaPhiin(Electron_DeltaPhiin)'])
    VectorDouble.extend(['HEEPProducer:HbE(Electron_HOverE)'])
    VectorDouble.extend(['HEEPProducer:SiEtaiEta(Electron_SiEtaiEta)'])
    VectorDouble.extend(['HEEPProducer:Ecaliso(Electron_Ecaliso)'])
    VectorDouble.extend(['HEEPProducer:HD1iso(Electron_HD1iso)'])
    VectorDouble.extend(['HEEPProducer:HD2iso(Electron_HD2iso)'])
    VectorBool.extend(['HEEPProducer:ecalDriven(Electron_ecalDriven)'])
    VectorDouble.extend(['HEEPProducer:e25max(Electron_e25max)'])
    VectorDouble.extend(['HEEPProducer:e55(Electron_e55)'])
    VectorDouble.extend(['HEEPProducer:e25bye55(Electron_e25bye55)'])
    VectorDouble.extend(['HEEPProducer:Fullsce25bye55(Electron_Fullsce25bye55)'])
    VectorDouble.extend(['HEEPProducer:Fulle15bye55(Electron_Fulle15bye55)'])
    VectorDouble.extend(['HEEPProducer:scEnergy(Electron_scEnergy)'])
    VectorDouble.extend(['HEEPProducer:DeltaEtaSeed(Electron_DeltaEtaSeed)'])
    VectorDouble.extend(['HEEPProducer:rho(rho)'])
    VectorInt.extend(['HEEPProducer:Charge(Electron_Charge)'])
    VectorDouble.extend(['HEEPProducer:ePt(Electron_Pt)'])
    VectorDouble.extend(['HEEPProducer:e15(Electron_e15)'])
    VectorDouble.extend(['HEEPProducer:ecalEnergy(Electron_ecalEnergy)'])
    VectorDouble.extend(['HEEPProducer:full55SiEtaiEta(Electron_full55SiEtaiEta)'])
    VectorDouble.extend(['HEEPProducer:sce25max(Electron_sce25max)'])
    VectorDouble.extend(['HEEPProducer:sce55(Electron_sce55)'])
    VectorDouble.extend(['HEEPProducer:sce25bye55(Electron_sce25bye55)'])
    VectorDouble.extend(['HEEPProducer:e15bye55(Electron_e15bye55)'])
    VectorDouble.extend(['HEEPProducer:DeltaEtaSeedscandTrack(Electron_DeltaEtaSeedscandTrack)'])
    VectorDouble.extend(['HEEPProducer:Phi(Electron_Phi)'])
    VectorDouble.extend(['HEEPProducer:eEnergy(Electron_Energy)'])
    VectorDouble.extend(['HEEPProducer:dxy(dxy)'])
    VectorInt.extend(['HEEPProducer:losthits(Electron_losthits)'])
    VectorDouble.extend(['HEEPProducer:ePz(Electron_Pz)'])
    VectorDouble.extend(['HEEPProducer:eTheta(Electron_Theta)'])
    VectorDouble.extend(['HEEPProducer:ePx(Electron_Px)'])
    VectorDouble.extend(['HEEPProducer:ePy(Electron_Py)'])
    VectorDouble.extend(['HEEPProducer:normalizedChi2(Electron_normalizedChi2)'])
    VectorInt.extend(['HEEPProducer:PDGID(PDGID)'])
    VectorInt.extend(['HEEPProducer:gencharge(gencharge)'])
    VectorDouble.extend(['HEEPProducer:genPt(genPt)'])
    VectorDouble.extend(['HEEPProducer:genEta(genEta)'])
    VectorDouble.extend(['HEEPProducer:genPhi(genPhi)'])
    VectorDouble.extend(['HEEPProducer:genEnergy(genEnergy)'])
    VectorInt.extend(['HEEPProducer:motherPDGID(motherPDGID)'])
    VectorInt.extend(['HEEPProducer:elstatus(elstatus)'])
    VectorDouble.extend(['HEEPProducer:PtHEEP(Electron_PtHEEP)'])
    VectorDouble.extend(['HEEPProducer:scEtaa(Electron_scEtaa)'])
    VectorDouble.extend(['HEEPProducer:scEta(Electron_scEta)'])
    



    ## ----------------------------------------------------------------------------------------------
    ## Muons
    ## ----------------------------------------------------------------------------------------------

    from LeptoQuarkTreeMaker.Utils.MuonProducer_cfi import MuonProducer
    process.MuonProducer = MuonProducer.clone(
        muontag = cms.InputTag('slimmedMuons')
    )
    process.Baseline += process.MuonProducer

    VectorBool.extend(['MuonProducer:MuonisTightMuon(MuonisTightMuon)'])
    VectorBool.extend(['MuonProducer:MuonisHighPtMuon(MuonisHighPtMuon)'])
    VectorDouble.extend(['MuonProducer:MuonEta(MuonEta)'])
    VectorDouble.extend(['MuonProducer:MuonPhi(MuonPhi)'])
    VectorDouble.extend(['MuonProducer:MuonPt(MuonPt)'])
    VectorDouble.extend(['MuonProducer:MuonEnergy(MuonEnergy)'])
    VectorDouble.extend(['MuonProducer:MuonPtError(MuonPtError)'])
    VectorDouble.extend(['MuonProducer:MuonGlobalChi2(MuonGlobalChi2)'])
    VectorDouble.extend(['MuonProducer:MuonTrkPtError(MuonTrkPtError)'])
    VectorInt.extend(['MuonProducer:MuonIsPF(MuonIsPF)'])
    VectorInt.extend(['MuonProducer:MuonCharge(MuonCharge)'])
    VectorInt.extend(['MuonProducer:MuonGlobalTrkValidHits(MuonGlobalTrkValidHits)'])
    VectorInt.extend(['MuonProducer:MuonTrkPixelHits(MuonTrkPixelHits)'])
    VectorInt.extend(['MuonProducer:MuonStationMatches(MuonStationMatches)'])
    VectorDouble.extend(['MuonProducer:MuonPFIsoR04Photon(MuonPFIsoR04Photon)'])
    VectorDouble.extend(['MuonProducer:MuonPFIsoR04NeutralHadron(MuonPFIsoR04NeutralHadron)'])
    VectorDouble.extend(['MuonProducer:MuonPFIsoR04PU(MuonPFIsoR04PU)'])
    VectorDouble.extend(['MuonProducer:MuonTrackerIsoSumPT(MuonTrackerIsoSumPT)'])
    VectorDouble.extend(['MuonProducer:MuonPFIsoR04ChargedHadron(MuonPFIsoR04ChargedHadron)'])
    VectorInt.extend(['MuonProducer:MuonPassID(MuonPassID)'])
    VectorInt.extend(['MuonProducer:MuonIsGlobal(MuonIsGlobal)'])
    VectorInt.extend(['MuonProducer:MuonTrackLayersWithMeasurement(MuonTrackLayersWithMeasurement)'])
    VectorDouble.extend(['MuonProducer:CocktailEta(CocktailPtError)'])
    VectorDouble.extend(['MuonProducer:CocktailPt(CocktailPt)'])
    VectorDouble.extend(['MuonProducer:MuonBestTrackVtxDistXY(MuonBestTrackVtxDistXY)'])
    VectorDouble.extend(['MuonProducer:MuonBestTrackVtxDistZ(MuonBestTrackVtxDistZ)'])

    ## ----------------------------------------------------------------------------------------------
    ## Taus
    ## ----------------------------------------------------------------------------------------------


    from LeptoQuarkTreeMaker.Utils.TauProducer_cfi import TauProducer
    process.TauProducer = TauProducer.clone(
        tautag = cms.InputTag('slimmedTaus')
    )
    process.Baseline += process.TauProducer
    VectorDouble.extend(['TauProducer:tEta(TauEta)'])
    VectorDouble.extend(['TauProducer:tPhi(TauPhi)'])
    VectorDouble.extend(['TauProducer:tPt(TauPt)'])

    '''


    
    ## ----------------------------------------------------------------------------------------------
    ## Triggers
    ## ----------------------------------------------------------------------------------------------

    # The trigger results are saved to the tree as a vector
    # Three vectors are saved:
    # 1) names of the triggers
    # 2) trigger results
    # 3) trigger prescales
    # the indexing of these vectors must match
    # If the version number of the input trigger name is omitted,
    # any matching trigger will be included (default behavior)

    from LeptoQuarkTreeMaker.Utils.triggerproducer_cfi import triggerProducer
    from LeptoQuarkTreeMaker.LeptoQuarkTreeMaker.triggerNameList import triggerNameList as _triggerNameList
    process.TriggerProducer = triggerProducer.clone(
        trigTagArg1     = cms.string('TriggerResults'),
        trigTagArg2     = cms.string(''),
        trigTagArg3     = cms.string('HLT'),
        prescaleTagArg1  = cms.string('patTrigger'),
        prescaleTagArg2  = cms.string(''),
        prescaleTagArg3  = cms.string(''),
        triggerNameList = _triggerNameList
    )
    VectorInt.extend(['TriggerProducer:TriggerPass','TriggerProducer:TriggerPrescales'])
    VectorString.extend(['TriggerProducer:TriggerNames'])
    VectorDouble.extend(['TriggerProducer:objectPt'])
    VectorDouble.extend(['TriggerProducer:objecteta'])
    VectorDouble.extend(['TriggerProducer:objectphi'])
    VectorDouble.extend(['TriggerProducer:objectE'])


    '''
    if not geninfo:
        from LeptoQuarkTreeMaker.Utils.prescaleweightproducer_cfi import prescaleweightProducer
        process.PrescaleWeightProducer = prescaleweightProducer.clone()
        VarsDouble.extend(['PrescaleWeightProducer:weight(PrescaleWeightHT)'])
        VarsDouble.extend(['PrescaleWeightProducer:ht(HTOnline)'])
        VarsDouble.extend(['PrescaleWeightProducer:mht(MHTOnline)'])
    '''
    
    ## ----------------------------------------------------------------------------------------------
    ## JER smearing, various uncertainties
    ## ----------------------------------------------------------------------------------------------
    
    # list of clean tags - ignore jet ID for jets matching these objects
    SkipTag = cms.VInputTag(
       # cms.InputTag('LeptonsNew:IdIsoMuon'),
       # cms.InputTag('LeptonsNew:IdIsoElectron'),
       # cms.InputTag('IsolatedElectronTracksVeto'),
       # cms.InputTag('IsolatedMuonTracksVeto'),
       # cms.InputTag('IsolatedPionTracksVeto'),
    )
    
    # get the JERs (disabled by default)
    # this requires the user to download the .db file from this github
    # https://github.com/cms-jet/JRDatabase
    ''' 
    if len(jerfile)>0:
        #get name of JERs without any directories
        JERera = jerfile.split('/')[-1]
        JERPatch = cms.string('sqlite_file:'+jerfile+'.db')
        if os.getenv('GC_CONF'): 
            JERPatch = cms.string('sqlite_file:../src/'+jerfile+'.db')
    
        process.jer = cms.ESSource("PoolDBESSource",CondDBSetup,
            connect = JERPatch,
            toGet = cms.VPSet(
                cms.PSet(
                    record = cms.string('JetResolutionRcd'),
                    tag    = cms.string('JR_'+JERera+'_PtResolution_AK4PFchs'),
                    label  = cms.untracked.string('AK4PFchs_pt')
                ),
                cms.PSet(
                    record = cms.string('JetResolutionScaleFactorRcd'),
                    tag    = cms.string('JR_'+JERera+'_SF_AK4PFchs'),
                    label  = cms.untracked.string('AK4PFchs')
                ),
            ),
        )

        process.es_prefer_jer = cms.ESPrefer('PoolDBESSource', 'jer')
    '''
    # skip all jet smearing and uncertainties for data
#    from LeptoQuarkTreeMaker.LeptoQuarkTreeMaker.JetDepot import JetDepot
    from LeptoQuarkTreeMaker.LeptoQuarkTreeMaker.makeJetVars import makeJetVars
    process = makeJetVars(process,
                          JetTag=JetTag,
                          suff='',
                          skipGoodJets=False,
                          storeProperties=2,
                          geninfo=geninfo,
                          fastsim=fastsim,
                          SkipTag=SkipTag
    )

 
    if geninfo:
        from LeptoQuarkTreeMaker.LeptoQuarkTreeMaker.JetDepot import JetDepot

        # JEC unc up
        process, JetTagJECup = JetDepot(process,
            JetTag=JetTag,
            jecUncDir=1,
            doSmear=True,
            jerUncDir=0
        )
        process = makeJetVars(process,
                              JetTag=JetTagJECup,
                              suff='JECup',
                              skipGoodJets=False,
                              storeProperties=1,
                              geninfo=geninfo,
                              fastsim=fastsim,
                              SkipTag=SkipTag
        )
        
        # JEC unc down
        process, JetTagJECdown = JetDepot(process,
            JetTag=JetTag,
            jecUncDir=-1,
            doSmear=True,
            jerUncDir=0
        )
        process = makeJetVars(process,
                              JetTag=JetTagJECdown,
                              suff='JECdown',
                              skipGoodJets=False,
                              storeProperties=1,
                              geninfo=geninfo,
                              fastsim=fastsim,
                              SkipTag=SkipTag
        )

        # JER unc up
        process, JetTagJERup = JetDepot(process,
            JetTag=JetTag,
            jecUncDir=0,
            doSmear=True,
            jerUncDir=1
        )
        process = makeJetVars(process,
                              JetTag=JetTagJERup,
                              suff='JERup',
                              skipGoodJets=False,
                              storeProperties=1,
                              geninfo=geninfo,
                              fastsim=fastsim,
                              SkipTag=SkipTag
        )
        
        # JER unc down
        process, JetTagJERdown = JetDepot(process,
            JetTag=JetTag,
            jecUncDir=0,
            doSmear=True,
            jerUncDir=-1
        )
        process = makeJetVars(process,
                              JetTag=JetTagJERdown,
                              suff='JERdown',
                              skipGoodJets=False,
                              storeProperties=1,
                              geninfo=geninfo,
                              fastsim=fastsim,
                              SkipTag=SkipTag
        )

        # finally, do central smearing and replace jet tag
        process, JetTag = JetDepot(process,
            JetTag=JetTag,
            jecUncDir=0,
            doSmear=True,
            jerUncDir=0
        )
        
    ## ----------------------------------------------------------------------------------------------
    ## Jet variables
    ## ----------------------------------------------------------------------------------------------
    '''
    # get updated QG training
    QGPatch = cms.string('sqlite_file:data/QGL_80X.db')
    if os.getenv('GC_CONF'): 
        QGPatch = cms.string('sqlite_file:../src/data/QGL_80X.db')

    process.qgdb = cms.ESSource("PoolDBESSource",CondDBSetup,
        connect = QGPatch,
        toGet   = cms.VPSet(
            cms.PSet(
                record = cms.string('QGLikelihoodRcd'),
                tag    = cms.string('QGLikelihoodObject_80X_AK4PFchs'),
                label  = cms.untracked.string('QGL_AK4PFchs')
            ),
            cms.PSet(
                record = cms.string('QGLikelihoodRcd'),
                tag    = cms.string('QGLikelihoodObject_80X_AK4PFchs_antib'),
                label  = cms.untracked.string('QGL_AK4PFchs_antib')
            ),
        )
    )
    process.es_prefer_qg = cms.ESPrefer("PoolDBESSource","qgdb")
    
    # get QG tagging discriminant
    process.QGTagger = cms.EDProducer('QGTagger',
        srcJets	            = JetTag,
        jetsLabel           = cms.string('QGL_AK4PFchs'),
        srcRho              = cms.InputTag('fixedGridRhoFastjetAll'),		
        srcVertexCollection	= cms.InputTag('offlinePrimaryVerticesWithBS'),
        useQualityCuts	    = cms.bool(False)
    )
    
    # add userfloats & update tag
    process, JetTag = addJetInfo(process, JetTag, ['QGTagger:qgLikelihood','QGTagger:ptD', 'QGTagger:axis2'], ['QGTagger:mult'])
    
    process = makeJetVars(process,
                          JetTag=JetTag,
                          suff='',
                          skipGoodJets=False,
                          storeProperties=2,
                          geninfo=geninfo,
                          fastsim=fastsim,
                          SkipTag=SkipTag
    )
    
    # get double b-tagger (w/ miniAOD customizations)
    process.load("RecoBTag.ImpactParameter.pfImpactParameterAK8TagInfos_cfi")
    process.pfImpactParameterAK8TagInfos.primaryVertex = cms.InputTag("offlineSlimmedPrimaryVertices")
    process.pfImpactParameterAK8TagInfos.candidates = cms.InputTag("packedPFCandidates")
    process.pfImpactParameterAK8TagInfos.jets = JetAK8Tag
    process.load("RecoBTag.SecondaryVertex.pfInclusiveSecondaryVertexFinderAK8TagInfos_cfi")
    process.pfInclusiveSecondaryVertexFinderAK8TagInfos.extSVCollection = cms.InputTag("slimmedSecondaryVertices")
    process.pfInclusiveSecondaryVertexFinderAK8TagInfos.trackIPTagInfos = cms.InputTag("pfImpactParameterAK8TagInfos")
    process.load("RecoBTag.SecondaryVertex.pfBoostedDoubleSVAK8TagInfos_cfi")
    process.load("RecoBTag.SecondaryVertex.candidateBoostedDoubleSecondaryVertexAK8Computer_cfi")
    process.load("RecoBTag.SecondaryVertex.pfBoostedDoubleSecondaryVertexAK8BJetTags_cfi")
    
    # add discriminator and update tag
    process, JetAK8Tag = addJetInfo(process, JetAK8Tag, [], [], cms.VInputTag(cms.InputTag("pfBoostedDoubleSecondaryVertexAK8BJetTags")))
    
    # apply jet ID
    process = makeJetVars(process,
                          JetTag=JetAK8Tag,
                          suff='AK8',
                          skipGoodJets=False,
                          storeProperties=1,
                          geninfo=geninfo,
                          fastsim=fastsim,
                          onlyGoodJets=True
    )
    
    # AK8 jet variables - separate instance of jet properties producer
    from LeptoQuarkTreeMaker.Utils.jetproperties_cfi import jetproperties
    process.JetsPropertiesAK8 = jetproperties.clone(
        JetTag       = JetAK8Tag,
        properties = cms.vstring(
            "prunedMass"           ,
            "NsubjettinessTau1"    ,
            "NsubjettinessTau2"    ,
            "NsubjettinessTau3"    ,
            "bDiscriminatorSubjet1",
            "bDiscriminatorSubjet2",
            "bDiscriminatorCSV"    ,
            "NumBhadrons"          ,
            "NumChadrons"          ,
        )
    )
    #specify userfloats
    process.JetsPropertiesAK8.prunedMass = cms.vstring('ak8PFJetsCHSPrunedMass')
    process.JetsPropertiesAK8.NsubjettinessTau1 = cms.vstring('NjettinessAK8:tau1')
    process.JetsPropertiesAK8.NsubjettinessTau2 = cms.vstring('NjettinessAK8:tau2')
    process.JetsPropertiesAK8.NsubjettinessTau3 = cms.vstring('NjettinessAK8:tau3')
    process.JetsPropertiesAK8.bDiscriminatorSubjet1 = cms.vstring('SoftDrop','pfCombinedInclusiveSecondaryVertexV2BJetTags')
    process.JetsPropertiesAK8.bDiscriminatorSubjet2 = cms.vstring('SoftDrop','pfCombinedInclusiveSecondaryVertexV2BJetTags')
    process.JetsPropertiesAK8.bDiscriminatorCSV = cms.vstring('pfBoostedDoubleSecondaryVertexAK8BJetTags')
    #VectorRecoCand.extend([JetAK8Tag.value()+'(JetsAK8)'])
    #VectorDouble.extend(['JetsPropertiesAK8:prunedMass(JetsAK8_prunedMass)',
     #                    'JetsPropertiesAK8:bDiscriminatorSubjet1(JetsAK8_bDiscriminatorSubjet1CSV)',
      #                   'JetsPropertiesAK8:bDiscriminatorSubjet2(JetsAK8_bDiscriminatorSubjet2CSV)',
       #                  'JetsPropertiesAK8:bDiscriminatorCSV(JetsAK8_doubleBDiscriminator)',
        #                 'JetsPropertiesAK8:NsubjettinessTau1(JetsAK8_NsubjettinessTau1)',
         #                'JetsPropertiesAK8:NsubjettinessTau2(JetsAK8_NsubjettinessTau2)',
          #               'JetsPropertiesAK8:NsubjettinessTau3(JetsAK8_NsubjettinessTau3)'])
    #VectorInt.extend(['JetsPropertiesAK8:NumBhadrons(JetsAK8_NumBhadrons)',
           #           'JetsPropertiesAK8:NumChadrons(JetsAK8_NumChadrons)'])
    ''' 
    ## ----------------------------------------------------------------------------------------------
    ## GenJet variables
    ## ----------------------------------------------------------------------------------------------
    if geninfo:
        # store all genjets
        VectorRecoCand.extend ( [ 'slimmedGenJets(GenJets)' ] )
    
        from LeptoQuarkTreeMaker.Utils.subJetSelection_cfi import SubGenJetSelection
        
        process.GenHTJets = SubGenJetSelection.clone(
            JetTag = cms.InputTag('slimmedGenJets'),
            MinPt  = cms.double(30),
            MaxEta = cms.double(2.4),
        )
        #VectorBool.extend(['GenHTJets:SubJetMask(GenJets_HTMask)'])
        
        # make gen HT
        from LeptoQuarkTreeMaker.Utils.htdouble_cfi import htdouble
        process.GenHT = htdouble.clone(
            JetTag = cms.InputTag("GenHTJets"),
        )
        #VarsDouble.extend(['GenHT'])
        
        process.GenMHTJets = SubGenJetSelection.clone(
            JetTag = cms.InputTag('slimmedGenJets'),
            MinPt  = cms.double(30),
            MaxEta = cms.double(5.0),
        )
        #VectorBool.extend(['GenMHTJets:SubJetMask(GenJets_MHTMask)'])
        ''' 
        # make gen MHT
        from LeptoQuarkTreeMaker.Utils.mhtdouble_cfi import mhtdouble
        process.GenMHT = mhtdouble.clone(
            JetTag  = cms.InputTag('GenMHTJets'),
        )
        VarsDouble.extend(['GenMHT:Pt(GenMHT)','GenMHT:Phi(GenMHTPhi)'])
        '''
    ## ----------------------------------------------------------------------------------------------
    ## Baseline filters
    ## ----------------------------------------------------------------------------------------------
    # sequence for baseline filters
    process.Baseline = cms.Sequence()
    '''
    from LeptoQuarkTreeMaker.Utils.doublefilter_cfi import DoubleFilter
    process.HTFilter = DoubleFilter.clone(
        DoubleTag = cms.InputTag('HT'),
        CutValue  = cms.double('500'),
    )
    process.MHTFilter = DoubleFilter.clone(
        DoubleTag = cms.InputTag('MHT:Pt'),
        CutValue  = cms.double('200'),
    )
    if applybaseline:
        process.Baseline += process.HTFilter
        #process.Baseline += process.MHTFilter
    '''
    ## ----------------------------------------------------------------------------------------------
    ## MET
    ## ----------------------------------------------------------------------------------------------
    from LeptoQuarkTreeMaker.Utils.metdouble_cfi import metdouble
    process.MET = metdouble.clone(
        METTag = METTag,
        GenMETTag = cms.InputTag("slimmedMETs","",tagname), #original collection used deliberately here
        JetTag = cms.InputTag('HTJets'),
        geninfo = cms.untracked.bool(geninfo),
    )
    VarsDouble.extend(['MET:Pt(MET)','MET:Phi(METPhi)'])
    if geninfo:
        VarsDouble.extend(['MET:GenPt(GenMET)','MET:GenPhi(GenMETPhi)'])
        VectorDouble.extend(['MET:PtUp(METUp)', 'MET:PtDown(METDown)', 'MET:PhiUp(METPhiUp)', 'MET:PhiDown(METPhiDown)'])
    '''
    from LeptoQuarkTreeMaker.Utils.mt2producer_cfi import mt2Producer
    process.Mt2Producer = mt2Producer.clone(
                JetTag  = cms.InputTag('MHTJets'),
                METTag = METTag
        )
    VarsDouble.extend(['Mt2Producer:mt2(MT2)'])
    '''
    ## ----------------------------------------------------------------------------------------------
    ## ----------------------------------------------------------------------------------------------
    ## Optional producers (background estimations, control regions)
    ## ----------------------------------------------------------------------------------------------
    ## ----------------------------------------------------------------------------------------------

    ## ----------------------------------------------------------------------------------------------
    ## Hadronic Tau Background
    ## ----------------------------------------------------------------------------------------------
    '''
    if hadtau:
        from LeptoQuarkTreeMaker.LeptoQuarkTreeMaker.doHadTauBkg import doHadTauBkg
        dorecluster = False
        if hadtaurecluster==0: dorecluster = False
        elif hadtaurecluster==1: dorecluster = ("TTJets" in process.source.fileNames[0] or "WJets" in process.source.fileNames[0])
        elif hadtaurecluster==2: dorecluster = geninfo
        elif hadtaurecluster==3: dorecluster = True
        process = doHadTauBkg(process,geninfo,residual,JetTagBeforeSmearing,fastsim,dorecluster)

    ## ----------------------------------------------------------------------------------------------
    ## Lost Lepton Background
    ## ----------------------------------------------------------------------------------------------
    if lostlepton:
        from LeptoQuarkTreeMaker.LeptoQuarkTreeMaker.doLostLeptonBkg import doLostLeptonBkg
        process = doLostLeptonBkg(process,geninfo,METTag)

    ## ----------------------------------------------------------------------------------------------
    ## Zinv Background
    ## ----------------------------------------------------------------------------------------------
    if doZinv:
        from LeptoQuarkTreeMaker.LeptoQuarkTreeMaker.doZinvBkg import doZinvBkg
        process = doZinvBkg(process,tagname,geninfo,residual,fastsim)

    ## ----------------------------------------------------------------------------------------------
    ## ----------------------------------------------------------------------------------------------
    ## Final steps
    ## ----------------------------------------------------------------------------------------------
    ## ----------------------------------------------------------------------------------------------
    '''
    # create the process path
    process.dump = cms.EDAnalyzer("EventContentAnalyzer")
    process.WriteTree = cms.Path(
        process.Baseline *
        process.LQTreeMaker2
    )
    
    return process
Exemple #26
0
from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSSoftDropMass
process.oldJetMass = ak8PFJetsCHSSoftDropMass.clone(
  src = cms.InputTag("slimmedJets"),
  matched = cms.InputTag("slimmedJets") )
patAlgosToolsTask.add(process.oldJetMass)

updateJetCollection(
   process,
   jetSource = cms.InputTag('slimmedJets'),
   jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
   btagDiscriminators = [
      'pfCombinedSecondaryVertexV2BJetTags',

      'pfDeepCSVJetTags:probudsg', 
      'pfDeepCSVJetTags:probb', 
      'pfDeepCSVJetTags:probc', 
      'pfDeepCSVJetTags:probbb', 
      'pfDeepCSVJetTags:probcc',
      
      ## 'pfDeepCMVAJetTags:probudsg', 
      ## 'pfDeepCMVAJetTags:probb', 
      ## 'pfDeepCMVAJetTags:probc', 
      ## 'pfDeepCMVAJetTags:probbb', 
      ## 'pfDeepCMVAJetTags:probcc'
      ] ## to add discriminators
)

process.updatedPatJets.userData.userFloats.src += ['oldJetMass']

from PhysicsTools.PatAlgos.patInputFiles_cff import filesRelValTTbarPileUpMINIAODSIM
process.source.fileNames = filesRelValTTbarPileUpMINIAODSIM
#                                         ##
# Setup VID for EGM ID
from PhysicsTools.SelectorUtils.tools.vid_id_tools import *
switchOnVIDPhotonIdProducer(process, DataFormat.MiniAOD)
# define which IDs we want to produce
my_id_modules = ['RecoEgamma.PhotonIdentification.Identification.cutBasedPhotonID_Spring15_25ns_V1_cff']
#add them to the VID producer
for idmod in my_id_modules:
    setupAllVIDIdsInModule(process,idmod,setupVIDPhotonSelection)

## update AK4PFchs jet collection in MiniAOD JECs

from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection

updateJetCollection(
   process,
   jetSource = cms.InputTag('slimmedJets'),
   labelName = 'UpdatedJEC',
   jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None')  # Do not forget 'L2L3Residual' on data!
)

# main analyzer and inputs
process.diphoton = cms.EDAnalyzer(
    'ExoDiPhotonMCFakeRateClosureTestAnalyzer',
    # photon tag
    photonsMiniAOD = cms.InputTag("slimmedPhotons"),
    # genParticle tag
    genParticlesMiniAOD = cms.InputTag("prunedGenParticles"),
    # ak4 jets
    jetsMiniAOD = cms.InputTag("selectedUpdatedPatJetsUpdatedJEC"),
    jetPtThreshold = cms.double(30.),
    jetEtaThreshold = cms.double(2.5),
    # rho tag
Exemple #28
0
        )

process.es_prefer_jer = cms.ESPrefer('PoolDBESSource', 'jer')


################ end sqlite connection
#### RECOMPUTE JEC From GT ###
from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
 
jecLevels= ['L1FastJet',  'L2Relative', 'L3Absolute']
if options.isData:
        jecLevels =['L1FastJet',  'L2Relative', 'L3Absolute', 'L2L3Residual']
 
updateJetCollection(
    process,
    jetSource = process.nero.jets,
    labelName = 'UpdatedJEC',
    jetCorrections = ('AK4PFchs', cms.vstring(jecLevels), 'None')  # Do not forget 'L2L3Residual' on data!
)

updateJetCollection(
    process,
    jetSource = process.nero.chsAK8,
    labelName = 'UpdatedJECAK8',
    jetCorrections = ('AK8PFchs', cms.vstring(jecLevels), 'None')  # Do not forget 'L2L3Residual' on data!
)

print "-> Updating the jets collection to run on to 'updatedPatJetsUpdatedJEC' with the new jec in the GT"
process.nero.jets=cms.InputTag('updatedPatJetsUpdatedJEC')
process.nero.chsAK8=cms.InputTag('updatedPatJetsUpdatedJECAK8')
process.jecSequence = cms.Sequence( process.patJetCorrFactorsUpdatedJEC* process.updatedPatJetsUpdatedJEC* process.patJetCorrFactorsUpdatedJECAK8* process.updatedPatJetsUpdatedJECAK8)
                           postfix="Puppi"
                           )

if is_data_flag:
  process.AK4QGTaggerPuppi.jec           = cms.InputTag("ak4PuppiL1FastL2L3ResidualCorrector")
  process.AK8QGTaggerPuppi.jec           = cms.InputTag("ak8PuppiL1FastL2L3ResidualCorrector")
  process.CA15QGTaggerPuppi.jec          = cms.InputTag("ak8PuppiL1FastL2L3ResidualCorrector")
  process.AK4QGTaggerSubJetsPuppi.jec    = cms.InputTag("ak4PuppiL1FastL2L3ResidualCorrector")
  process.AK8QGTaggerSubJetsPuppi.jec    = cms.InputTag("ak8PuppiL1FastL2L3ResidualCorrector")
  process.CA15QGTaggerSubJetsPuppi.jec   = cms.InputTag("ak8PuppiL1FastL2L3ResidualCorrector")

from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
updateJetCollection(
  process,
  jetSource = cms.InputTag('slimmedJets'),
  jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
  btagDiscriminators = ['pfDeepCMVAJetTags:probb','pfDeepCMVAJetTags:probc','pfDeepCMVAJetTags:probudsg','pfDeepCMVAJetTags:probbb',
                        'pfDeepCSVJetTags:probb' ,'pfDeepCSVJetTags:probc' ,'pfDeepCSVJetTags:probudsg' ,'pfDeepCSVJetTags:probbb']
  )

# ALPACA
#process.load('BaconProd/Ntupler/myAlpacaCorrections_cff')
alpacaMet = ''
alpacaPuppiMet = ''
if do_alpaca: 
  alpacaMet      = ('pfMetAlpacaData'        if is_data_flag else 'pfMetAlpacaMC' )
  alpacaPuppiMet = ('pfMetPuppiAlpacaData'   if is_data_flag else 'pfMetPuppiAlpacaMC' ) 

#--------------------------------------------------------------------------------
# input settings
#================================================================================
     'deepFlavourJetTags:probcc',
 ]

jetCorrectionsAK4 = ('AK4PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None')
jetCorrectionsAK8 = ('AK8PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None')


from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
updateJetCollection(
        process,
        labelName = "DeepFlavour",
        jetSource=cms.InputTag('slimmedJetsAK8PFCHSSoftDropPacked','SubJets'), #slimmedJetsAK8PFPuppiSoftDropPacked', 'SubJets'),  # subjets from AK8
#         jetSource = cms.InputTag('slimmedJets'),  # 'ak4Jets'
        jetCorrections = jetCorrectionsAK4,
        pfCandidates = cms.InputTag('packedPFCandidates'),
        pvSource = cms.InputTag("offlineSlimmedPrimaryVertices"),
        svSource = cms.InputTag('slimmedSecondaryVertices'),
        muSource = cms.InputTag('slimmedMuons'),
        elSource = cms.InputTag('slimmedElectrons'),
        btagInfos = bTagInfos,
        btagDiscriminators = bTagDiscriminators,
        explicitJTA = False
)

if hasattr(process,'updatedPatJetsTransientCorrectedDeepFlavour'):
	process.updatedPatJetsTransientCorrectedDeepFlavour.addTagInfos = cms.bool(True) 
	process.updatedPatJetsTransientCorrectedDeepFlavour.addBTagInfo = cms.bool(True)
else:
	raise ValueError('I could not find updatedPatJetsTransientCorrectedDeepFlavour to embed the tagInfos, please check the cfg')

#  payload = 'AK4PFchs' ) # Make sure to choose the appropriate levels and payload here!
#
#from PhysicsTools.PatAlgos.producersLayer1.jetUpdater_cff import patJetsUpdated
#process.patJetsReapplyJEC = process.patJetsUpdated.clone(
#  jetSource = cms.InputTag("slimmedJets"),
#  jetCorrFactorsSource = cms.VInputTag(cms.InputTag("patJetCorrFactorsReapplyJEC"))
#  )
#process.JEC = cms.Sequence( process.patJetCorrFactorsReapplyJEC + process. patJetsReapplyJEC )

#-----------------For JEC----------------- for 7.6.4 and above
from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection

if runOnData:
    updateJetCollection(
       process,
       jetSource = cms.InputTag('slimmedJets'),
       labelName = 'UpdatedJEC',
       jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute','L2L3Residual']), 'None')  # Do not forget 'L2L3Residual' on data!
    )
else:
    updateJetCollection(
       process,
       jetSource = cms.InputTag('slimmedJets'),
       labelName = 'UpdatedJEC',
       jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None')  # Do not forget 'L2L3Residual' on data!
    )

process.load('FWCore.MessageService.MessageLogger_cfi')

process.TFileService=cms.Service("TFileService",
        fileName=cms.string("ntuple_output.root"),
        closeFileFast = cms.untracked.bool(True)
            label  = cms.untracked.string('AK4PFchs')
            ),
      ## here you add as many jet types as you need
      ## note that the tag name is specific for the particular sqlite file 
      ), 
      connect = jecString
     # uncomment above tag lines and this comment to use MC JEC
)

process.es_prefer_jec = cms.ESPrefer('PoolDBESSource','jec')

from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection

updateJetCollection(
   process,
   jetSource = cms.InputTag('slimmedJets'),
   labelName = 'UpdatedJEC',
   jetCorrections = ('AK4PFchs', cms.vstring('L1FastJet',  'L2Relative', 'L3Absolute'), 'None')
)

process.jecSequence = cms.Sequence(process.patJetCorrFactorsUpdatedJEC * process.updatedPatJetsUpdatedJEC)

jerString = cms.string('sqlite:src/ntuple_maker/ntuple_maker/data/jer/Spring16_25nsV6_MC.db')

process.jer = cms.ESSource("PoolDBESSource",
        CondDBSetup,
        toGet = cms.VPSet(
            # Resolution
            cms.PSet(
                record = cms.string('JetResolutionRcd'),
                tag    = cms.string('JR_Spring16_25nsV6_MC_PtResolution_AK4PFchs'),
                label  = cms.untracked.string('AK4PFchs_pt')
Exemple #33
0
    def makeAnalysisStep(self, stepName, **inputs):
        step = super(JetBaseFlow, self).makeAnalysisStep(stepName, **inputs)

        if stepName == 'preliminary':
            # Pileup veto
            # This puts the IDs in the event stream, not an updated
            # jet collection
            self.process.load("RecoJets.JetProducers.PileupJetID_cfi")
            self.process.pileupJetIdUpdated = self.process.pileupJetId.clone(
                jets = step.getObjTag('j'),
                inputIsCorrected = True,
                applyJec = True,
                vertexes = step.getObjTag('v'),
                )
            step.addModule('pileupJetIdUpdated',
                           self.process.pileupJetIdUpdated,
                           'puID', puID='fullId')

            # Jet energy corrections
            corrections = ['L1FastJet', 'L2Relative', 'L3Absolute',]
            if not self.isMC:
                corrections.append('L2L3Residual')
            updateJetCollection(
                self.process,
                jetSource = step.getObjTag('j'),
                labelName = 'UpdatedJEC',
                jetCorrections = ('AK4PFchs', cms.vstring(corrections), 'None'),
                )

            # Store PU ID in jet collection as a userInt
            self.process.updatedPatJetsUpdatedJEC.userData.userInts.src += [step.getObjTagString('puID')]

            self.process.jecSequence = cms.Sequence(
                self.process.patJetCorrFactorsUpdatedJEC
                * self.process.updatedPatJetsUpdatedJEC
                )
            step.addModule('jecSequence',
                           self.process.jecSequence,
                           'j')

            if self.isMC:
                # shift corrections up and down for systematics
                jesShifts = cms.EDProducer(
                    "PATJetEnergyScaleShifter",
                    src = step.getObjTag('j'),
                    )
                step.addModule('jesShifts', jesShifts, 'j_jesUp', 'j_jesDown',
                               j_jesUp='jesUp', j_jesDown='jesDown')

            jetIDEmbedding = cms.EDProducer(
                "PATJetIDEmbedder",
                src = step.getObjTag('j'),
                )
            step.addModule('jetIDEmbedding', jetIDEmbedding, 'j')

            if self.isMC:
                jetIDEmbedding_jesUp = cms.EDProducer(
                    "PATJetIDEmbedder",
                    src = step.getObjTag('j_jesUp'),
                    )
                step.addModule('jetIDEmbeddingJESUp', jetIDEmbedding_jesUp, 'j_jesUp')
                jetIDEmbedding_jesDown = cms.EDProducer(
                    "PATJetIDEmbedder",
                    src = step.getObjTag('j_jesDown'),
                    )
                step.addModule('jetIDEmbeddingJESDown', jetIDEmbedding_jesDown, 'j_jesDown')


                jetSmearing = cms.EDProducer(
                    "PATJetSmearing",
                    src = step.getObjTag('j'),
                    rhoSrc = cms.InputTag("fixedGridRhoFastjetAll"),
                    systematics = cms.bool(True),
                    )
                step.addModule("jetSmearing", jetSmearing, 'j', 'j_jerUp',
                               'j_jerDown', j_jerUp='jerUp', j_jerDown='jerDown')

                jetSmearing_jesUp = jetSmearing.clone(src = step.getObjTag('j_jesUp'),
                                                      systematics = cms.bool(False))
                step.addModule("jetSmearingJESUp", jetSmearing_jesUp, 'j_jesUp')
                jetSmearing_jesDown = jetSmearing.clone(src = step.getObjTag('j_jesDown'),
                                                      systematics = cms.bool(False))
                step.addModule("jetSmearingJESDown", jetSmearing_jesDown, 'j_jesDown')

                # need to re-sort now that we're calibrated
                jSort_jesUp = cms.EDProducer(
                    "PATJetCollectionSorter",
                    src = step.getObjTag('j_jesUp'),
                    function = cms.string('pt'),
                    )
                step.addModule('jetSortingJESUp', jSort_jesUp, 'j_jesUp')

                jSort_jesDn = cms.EDProducer(
                    "PATJetCollectionSorter",
                    src = step.getObjTag('j_jesDown'),
                    function = cms.string('pt'),
                    )
                step.addModule('jetSortingJESDn', jSort_jesDn, 'j_jesDown')

                jSort_jerUp = cms.EDProducer(
                    "PATJetCollectionSorter",
                    src = step.getObjTag('j_jerUp'),
                    function = cms.string('pt'),
                    )
                step.addModule('jetSortingJERUp', jSort_jerUp, 'j_jerUp')

                jSort_jerDn = cms.EDProducer(
                    "PATJetCollectionSorter",
                    src = step.getObjTag('j_jerDown'),
                    function = cms.string('pt'),
                    )
                step.addModule('jetSortingJERDn', jSort_jerDn, 'j_jerDown')

            # need to re-sort now that we're calibrated
            jSort = cms.EDProducer(
                "PATJetCollectionSorter",
                src = step.getObjTag('j'),
                function = cms.string('pt'),
                )
            step.addModule('jetSorting', jSort, 'j')

        if stepName == 'preselection':
            # For now, we're not using the PU ID, but we'll store it in the
            # ntuples later
            selectionString = ('pt > 30. && abs(eta) < 4.7 && '
                               'userFloat("idLoose") > 0.5')

            # # use medium PU ID
            # # PU IDs are stored as a userInt where the first three digits are
            # # tight, medium, and loose PUID decisions (going right to left)
            # selectionString = ('pt>30. && abs(eta) < 4.7 && '
            #                    'userFloat("idLoose") > 0.5 && '
            #                    'userInt("{}") >= 6').format(step.getObjTagString('puID'))

            step.addBasicSelector('j', selectionString)
            if self.isMC:
                step.addBasicSelector('j_jesUp', selectionString)
                step.addBasicSelector('j_jesDown', selectionString)
                step.addBasicSelector('j_jerUp', selectionString)
                step.addBasicSelector('j_jerDown', selectionString)

        return step
## uncomment the following line to update different jet collections
## and add them to the event content
from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection

## An example where the jet energy correction are updated to the current GlobalTag
## and a userFloat containing the previous mass of the jet and an additional
## b-tag discriminator are added
from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSSoftDropMass
process.oldJetMass = ak8PFJetsCHSSoftDropMass.clone(
  src = cms.InputTag("slimmedJets"),
  matched = cms.InputTag("slimmedJets") )
patAlgosToolsTask.add(process.oldJetMass)

updateJetCollection(
   process,
   jetSource = cms.InputTag('slimmedJets'),
   jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
   btagDiscriminators = ['pfCombinedSecondaryVertexV2BJetTags'] ## to add discriminators
)
process.updatedPatJets.userData.userFloats.src += ['oldJetMass']

## An example where the jet corrections are undone
updateJetCollection(
   process,
   labelName = 'UndoneJEC',
   jetSource = cms.InputTag('slimmedJets'),
   jetCorrections = ('AK4PFchs', cms.vstring([]), 'None')
)
process.updatedPatJetsUndoneJEC.userData.userFloats.src = []

## An example where the jet corrections are reapplied
updateJetCollection(
def reSetJet(process):
    ## Filter out neutrinos from packed GenParticles
    process.packedGenParticlesForJetsNoNu = cms.EDFilter("CandPtrSelector", src = cms.InputTag("packedGenParticles"), cut = cms.string("abs(pdgId) != 12 && abs(pdgId) != 14 && abs(pdgId) != 16"))
    ## Define GenJets
    from RecoJets.JetProducers.ak5GenJets_cfi import ak5GenJets
    process.ak5GenJetsNoNu = ak5GenJets.clone(src = 'packedGenParticlesForJetsNoNu')

    ## Select charged hadron subtracted packed PF candidates
    process.pfCHS = cms.EDFilter("CandPtrSelector", src = cms.InputTag("packedPFCandidates"), cut = cms.string("fromPV"))
    from RecoJets.JetProducers.ak5PFJets_cfi import ak5PFJets
    ## Define PFJetsCHS
    process.ak5PFJetsCHS = ak5PFJets.clone(src = 'pfCHS', doAreaFastjet = True)

    #################################################
    ## Remake PAT jets
    #################################################

    ## b-tag discriminators
    bTagDiscriminators = [
        'pfCombinedInclusiveSecondaryVertexV2BJetTags'
    ]
#################################################################
    slimmedAddPileupInfo = cms.EDProducer(
       'PileupSummaryInfoSlimmer',
        #src = cms.InputTag('addPileupInfo'),
        keepDetailedInfoFor = cms.vint32(0)
    )
#######################################################
    from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection

    ## Add PAT jet collection based on the above-defined ak5PFJetsCHS
    addJetCollection(
        process,
        labelName = 'AK5PFCHS',
        jetSource = cms.InputTag('ak5PFJetsCHS'),
        pvSource = cms.InputTag('offlineSlimmedPrimaryVertices'),
        bsSource = cms.InputTag('offlineBeamSpot'),
        pfCandidates = cms.InputTag('packedPFCandidates'),
        svSource = cms.InputTag('slimmedSecondaryVertices'),
        btagDiscriminators = bTagDiscriminators,
        #jetCorrections = ('AK5PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),  #commented before adding jet corrections
        genJetCollection = cms.InputTag('ak5GenJetsNoNu'),
        genParticles = cms.InputTag('prunedGenParticles'),
        algo = 'AK',
        rParam = 0.5
    )

    getattr(process,'selectedPatJetsAK5PFCHS').cut = cms.string('pt > 20.')

    process.rejet = cms.Path(process.packedGenParticlesForJetsNoNu *
                             process.ak5GenJetsNoNu *
                             process.pfCHS *
                             process.ak5PFJetsCHS *
                             process.patJetCorrFactorsAK5PFCHS *
                             process.patJetPartons *
                             process.patJetFlavourAssociationAK5PFCHS *
                             process.patJetPartonMatchAK5PFCHS *
                             process.patJetGenJetMatchAK5PFCHS *
                             process.pfImpactParameterTagInfosAK5PFCHS *
                             process.pfInclusiveSecondaryVertexFinderTagInfosAK5PFCHS *
                             process.pfCombinedInclusiveSecondaryVertexV2BJetTagsAK5PFCHS *
                             process.patJetsAK5PFCHS *
                             process.selectedPatJetsAK5PFCHS)

    from PhysicsTools.PatAlgos.tools.pfTools import adaptPVs
    ## Adapt primary vertex collection and BeamSpot
    adaptPVs(process, pvCollection=cms.InputTag('offlineSlimmedPrimaryVertices'))
    adaptBSs(process, bsCollection=cms.InputTag('offlineBeamSpot'))
 
    from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
    updateJetCollection(
        process,
        jetSource = cms.InputTag('slimmedJets'),
        labelName = 'UpdatedJEC',
        jetCorrections = ('AK5PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None')  # Do not forget 'L2L3Residual' on data
     )

    process.load('Configuration.StandardSequences.Services_cff') #Added info from now onwards
    process.load("JetMETCorrections.Modules.JetResolutionESProducer_cfi")

    from CondCore.DBCommon.CondDBSetup_cfi import *
    import os
    process.jer = cms.ESSource("PoolDBESSource",
            CondDBSetup,
            toGet = cms.VPSet(
                # Resolution
                cms.PSet(
                    record = cms.string('JetResolutionRcd'),
                    tag    = cms.string('JR_Fall15_25nsV2_MC_PtResolution_AK5PFchs'),
                    label  = cms.untracked.string('AK5PFchs_pt')
                    ),

                # Scale factors
                cms.PSet(
                    record = cms.string('JetResolutionScaleFactorRcd'),
                    tag    = cms.string('JR_Fall15_25nsV2_MC_SF_AK4PFchs'),
                    label  = cms.untracked.string('AK5PFchs')
                    ),
                ),
            connect = cms.string('sqlite:Fall15_25nsV2_MC.db')
            )
    process.es_prefer_jer = cms.ESPrefer('PoolDBESSource', 'jer')