def define_METs(process, runOnData=False):
    """Define reconstructed MET.
    
    Configure recalculation of corrected MET and its systematic
    uncertainties.  Only type-1 corrections are applied.  Due to
    limitations of MET tools, uncertainties are calculated even when
    running over data, while this is not needed.  Moreover, they include
    uncertainties corresponding to variations in energies of leptons,
    taus, and photons, although these variations are not considered in
    targeted analyses.
    
    Arguments:
        process: The process to which relevant MET producers are added.
        runOnData: Flag to distinguish processing of data and
            simulation.
    
    Return value:
        None.
    
    Among other things, add to the process producer slimmedMETs, which
    overrides the namesake collection from MiniAOD.  User must use this
    new collection.
    """
    
    # Recalculate MET corrections [1]
    # [1] https://twiki.cern.ch/twiki/bin/view/CMS/MissingETUncertaintyPrescription?rev=57#Instructions_for_8_0_X_X_20_for
    from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import \
        runMetCorAndUncFromMiniAOD
    runMetCorAndUncFromMiniAOD(
        process,
        isData=runOnData,
        # electronColl='', muonColl='', photonColl='', tauColl='',
        postfix=''
    )
Beispiel #2
0
def nanoAOD_recalibrateMETs(process,isData):
    runMetCorAndUncFromMiniAOD(process,isData=isData)
    process.nanoSequenceCommon.insert(process.nanoSequenceCommon.index(jetSequence),cms.Sequence(process.fullPatMetSequence))
#    makePuppiesFromMiniAOD(process,True) # call this before in the global customizer otherwise it would reset photon IDs in VID
#    runMetCorAndUncFromMiniAOD(process,isData=isData,metType="Puppi",postfix="Puppi",jetFlavor="AK4PFPuppi")
#    process.puppiNoLep.useExistingWeights = False
#    process.puppi.useExistingWeights = False
#    process.nanoSequenceCommon.insert(process.nanoSequenceCommon.index(jetSequence),cms.Sequence(process.puppiMETSequence+process.fullPatMetSequencePuppi))
    return process
    def makeAnalysisStep(self, stepName, **inputs):
        step = super(RecomputeMetUncertainties, self).makeAnalysisStep(stepName, **inputs)

        if stepName == 'preliminary':
            # Recompute MET uncertainties with new JEC
            from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
            runMetCorAndUncFromMiniAOD(self.process,
                isData=not self.isMC,
            )
            
            step.addModule('fullPatMetSequence', self.process.fullPatMetSequence,
                'met_fromUncertaintyTool', met_fromUncertaintyTool = ':Ntuple')
        return step
def setup_MET(process, cms, options, postfix="PFlow"):
    from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
    print '=' * 60
    print "Re-running MET on MiniAOD"
    print '=' * 60
    runOnData = options.isData

    # Running post Jet_Setup so GT should already be overwritten if needed?
    # recalculate MET with JEC
    runMetCorAndUncFromMiniAOD(
        process,
        isData=runOnData,
        electronColl = cms.InputTag('calibratedPatElectrons'),
    )
def setup_MET(process, cms, options, postfix="PFlow"):
    from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
    print '=' * 60
    print "Re-running MET on MiniAOD"
    print '=' * 60
    usePrivateSQlite = options.useJECFromFile
    runOnData = options.isData
    '''
    application of residual corrections. Have to be set to True once the 13 TeV
    residual corrections are available. False to be kept meanwhile. Can be kept
    to False
    '''
    applyResiduals = options.applyResiduals

    if usePrivateSQlite:
        from CondCore.DBCommon.CondDBSetup_cfi import *
        import os
        era = "Fall15_25nsV2_"
        if runOnData:
            era += 'DATA'
        else:
            era += 'MC'
        dBFile = os.path.expandvars(
            era + ".db")
           # "$CMSSW_BASE/src/BristolAnalysis/NTupleTools/data/JEC/" + era + ".db")
        process.jec = cms.ESSource( "PoolDBESSource",CondDBSetup,
                                    connect = cms.string( "sqlite_file:"+dBFile ),
                                    toGet =  cms.VPSet(
                                        cms.PSet(
                                            record = cms.string("JetCorrectionsRecord"),
                                            tag = cms.string("JetCorrectorParametersCollection_"+era+"_AK4PF"),
                                            label= cms.untracked.string("AK4PF")
                                            ),
                                        cms.PSet(
                                            record = cms.string("JetCorrectionsRecord"),
                                            tag = cms.string("JetCorrectorParametersCollection_"+era+"_AK4PFchs"),
                                            label= cms.untracked.string("AK4PFchs")
                                            ),
                                        )
                                    )
        process.es_prefer_jec = cms.ESPrefer("PoolDBESSource",'jec')

    # recalculate MET with JEC
    runMetCorAndUncFromMiniAOD(
        process,
        isData=runOnData,
        electronColl = cms.InputTag('calibratedPatElectrons'),
    )
Beispiel #6
0
def configurePFMetForMiniAOD(process, data=False):

	# do produce pfMet and No-HF pfMet, both raw and T1 corrected
	from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
	jecUncertaintyFile="PhysicsTools/PatUtils/data/Summer15_50nsV4_DATA_UncertaintySources_AK4PFchs.txt"

	runMetCorAndUncFromMiniAOD(process, isData=data, jecUncFile=jecUncertaintyFile )
	process.noHFCands = cms.EDFilter("CandPtrSelector", src=cms.InputTag("packedPFCandidates"), cut=cms.string("abs(pdgId)!=1 && abs(pdgId)!=2 && abs(eta)<3.0") )
	runMetCorAndUncFromMiniAOD(process, isData=data, pfCandColl=cms.InputTag("noHFCands"), jecUncFile=jecUncertaintyFile,  postfix="NoHF" )

	process.patPFMet.computeMETSignificance = cms.bool(True)
	process.patPFMet.srcLeptons = cms.VInputTag("slimmedTaus", "slimmedElectrons", "slimmedMuons")
	process.patPFMetNoHF.computeMETSignificance = cms.bool(True)
	process.patPFMetNoHF.srcLeptons = cms.VInputTag("slimmedTaus", "slimmedElectrons", "slimmedMuons")
	process.pfMet.calculateSignificance = cms.bool(True)
	process.pfMetNoHF.calculateSignificance = cms.bool(True)
	from RecoMET.METProducers.METSignificanceParams_cfi import METSignificanceParams
	process.pfMet.parameters = METSignificanceParams
	process.pfMet.srcMet = cms.InputTag("pfMet")
	process.pfMet.srcJets = cms.InputTag("slimmedJets")
	process.pfMet.srcLeptons = cms.VInputTag("slimmedTaus", "slimmedElectrons", "slimmedMuons")
	process.pfMetNoHF.parameters = METSignificanceParams
	process.pfMetNoHF.srcMet = cms.InputTag("pfMetNoHF")
	process.pfMetNoHF.srcJets = cms.InputTag("slimmedJets")
	process.pfMetNoHF.srcLeptons = cms.VInputTag("slimmedTaus", "slimmedElectrons", "slimmedMuons")
	process.pfMetNoHF.srcCandidates = cms.InputTag("noHFCands")

	# temporary fix from Missing ET mailing list
	process.patMETs.addGenMET  = cms.bool(False)
	process.patJets.addGenJetMatch = cms.bool(False)
	process.patJets.addGenPartonMatch = cms.bool(False)
	process.patJets.addPartonJetMatch = cms.bool(False)


	process.makePFMET = cms.Sequence()

	if not data:
		process.makePFMET = cms.Sequence( process.genMetExtractor )

	process.makePFMET *= cms.Sequence( 
		                process.ak4PFJets *
		                process.pfMet *
		                process.patJetCorrFactors *
		                process.patJets *
		                process.patPFMetT1T2Corr 
		)
Beispiel #7
0
def runMETs(process,isMC):
    #================================ Get the most recent JEC ==================================================================#
    # Setup the private SQLite -- Ripped from PhysicsTools/PatAlgos/test/corMETFromMiniAOD.py
    era = "Spring16_25nsV6"
    if isMC : 
        era += "_MC"
    else :
        era += "_DATA"
        
    dBFile = os.path.expandvars(era+".db")
    
    print dBFile
    if usePrivateSQlite:
        process.jec = cms.ESSource("PoolDBESSource",
                                   CondDBSetup,
                                   connect = cms.string("sqlite_file:"+dBFile),
                                   toGet =  cms.VPSet(
                cms.PSet(
                    record = cms.string("JetCorrectionsRecord"),
                    tag = cms.string("JetCorrectorParametersCollection_"+era+"_AK4PF"),
                    label= cms.untracked.string("AK4PF")
                    ),
                cms.PSet(
                        record = cms.string("JetCorrectionsRecord"),
                        tag = cms.string("JetCorrectorParametersCollection_"+era+"_AK4PFchs"),
                        label= cms.untracked.string("AK4PFchs")
                        ),
                )
                                   )
        process.es_prefer_jec = cms.ESPrefer("PoolDBESSource",'jec')
#===========================================================================================================================#
        
        
        runMetCorAndUncFromMiniAOD(process, metType="PF",
                                   jetCollUnskimmed="slimmedJets",
                                   electronColl="slimmedElectrons",
                                   photonColl="slimmedPhotons",
                                   muonColl="slimmedMuons",
                                   tauColl="slimmedTaus",
                                   reclusterJets = False,
                            	   fixEE2017 = True,
                                   pfCandColl = "packedPFCandidates",
				   # will produce new MET collection: slimmedMETsModifiedMET
                                   postfix="ModifiedMET",
                                   isData=(not isMC),
                                   )
Beispiel #8
0
def nanoAOD_recalibrateMETs(process,isData):
    runMetCorAndUncFromMiniAOD(process,isData=isData)
    process.nanoSequenceCommon.insert(process.nanoSequenceCommon.index(process.jetSequence),cms.Sequence(process.fullPatMetSequence))
    process.basicJetsForMetForT1METNano = process.basicJetsForMet.clone(
        src = process.updatedJetsWithUserData.src,
        skipEM = False,
        type1JetPtThreshold = 0.0,
        calcMuonSubtrRawPtAsValueMap = cms.bool(True),
    )
    process.jetSequence.insert(process.jetSequence.index(process.updatedJetsWithUserData),cms.Sequence(process.basicJetsForMetForT1METNano))
    process.updatedJetsWithUserData.userFloats.muonSubtrRawPt = cms.InputTag("basicJetsForMetForT1METNano:MuonSubtrRawPt")
    process.corrT1METJetTable.src = process.finalJets.src
    process.corrT1METJetTable.cut = "pt<15 && abs(eta)<9.9"
    for table in process.jetTable, process.corrT1METJetTable:
        table.variables.muonSubtrFactor = Var("1-userFloat('muonSubtrRawPt')/(pt()*jecFactor('Uncorrected'))",float,doc="1-(muon-subtracted raw pt)/(raw pt)",precision=6)
    process.metTables += process.corrT1METJetTable
#    makePuppiesFromMiniAOD(process,True) # call this before in the global customizer otherwise it would reset photon IDs in VID
#    runMetCorAndUncFromMiniAOD(process,isData=isData,metType="Puppi",postfix="Puppi",jetFlavor="AK4PFPuppi")
#    process.puppiNoLep.useExistingWeights = False
#    process.puppi.useExistingWeights = False
#    process.nanoSequenceCommon.insert(process.nanoSequenceCommon.index(jetSequence),cms.Sequence(process.puppiMETSequence+process.fullPatMetSequencePuppi))
    return process
Beispiel #9
0
def nanoAOD_runMETfixEE2017(process,isData):
    runMetCorAndUncFromMiniAOD(process,isData=isData,
                               fixEE2017 = True,
                               fixEE2017Params = {'userawPt': True, 'ptThreshold':50.0, 'minEtaThreshold':2.65, 'maxEtaThreshold': 3.139},
                               postfix = "FixEE2017")
    process.nanoSequenceCommon.insert(2,process.fullPatMetSequenceFixEE2017)
Beispiel #10
0
process.kappaTuple.PileupDensity.rename = cms.vstring(
    "fixedGridRhoFastjetAll => pileupDensity")

#################
# Configure MET #
#################

# official Prescription for calculating corrections and uncertainties on Missing Transverse Energy (MET):
# https://twiki.cern.ch/twiki/bin/view/CMS/MissingETUncertaintyPrescription#Instructions_for_8_0_X_X_26_patc

from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD

# re-correct MET for JEC and get the proper uncertainties
# Note: this only affects the default (i.e. Type1-corrected) MET.
# Since we only write out the raw MET, this line likely has no effect.
runMetCorAndUncFromMiniAOD(process, isData=options.isData)

# -- end of MET recipe

# wire miniAOD METs to collection from the "KAPPA" process
process.kappaTuple.PatMET.metPF = cms.PSet(src=cms.InputTag("slimmedMETs"),
                                           correctionLevel=cms.string('Raw'))
process.kappaTuple.PatMET.metCHS = cms.PSet(
    src=cms.InputTag("slimmedMETs"), correctionLevel=cms.string('RawChs'))
process.kappaTuple.PatMET.metPuppi = cms.PSet(
    src=cms.InputTag("slimmedMETsPuppi"), correctionLevel=cms.string('Raw'))

# -- activate KAPPA producers
process.kappaTuple.active += cms.vstring('PatMET')

##############
Beispiel #11
0
if not useHFCandidates:
    process.noHFCands = cms.EDFilter(
        "CandPtrSelector",
        src=cms.InputTag("packedPFCandidates"),
        cut=cms.string("abs(pdgId)!=1 && abs(pdgId)!=2 && abs(eta)<3.0"))
    patAlgosToolsTask.add(process.noHFCands)

#jets are rebuilt from those candidates by the tools, no need to do anything else
### =================================================================================

from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD

#default configuration for miniAOD reprocessing, change the isData flag to run on data
#for a full met computation, remove the pfCandColl input
runMetCorAndUncFromMiniAOD(
    process,
    isData=runOnData,
)

if not useHFCandidates:
    runMetCorAndUncFromMiniAOD(
        process,
        isData=runOnData,
        pfCandColl=cms.InputTag("noHFCands"),
        reclusterJets=True,  #needed for NoHF
        recoMetFromPFCs=True,  #needed for NoHF
        postfix="NoHF")

if redoPuppi:
    from PhysicsTools.PatAlgos.slimming.puppiForMET_cff import makePuppiesFromMiniAOD
    makePuppiesFromMiniAOD(process)
def reproduceMET(process, isdata):

    from CondCore.DBCommon.CondDBSetup_cfi import *
    import os

    if isdata:
        era = "Spring16_25nsV6_DATA"
    else:
        era = "Spring16_25nsV6_MC"
    jerera = "Spring16_25nsV6"

    ##___________________________External JEC file________________________________||

    process.jec = cms.ESSource(
        "PoolDBESSource",
        CondDBSetup,
        #                               connect = cms.string("sqlite:PhysicsTools/PatUtils/data/"+era+".db"),
        connect=cms.string("sqlite:" + era + "_JEC.db"),
        toGet=cms.VPSet(
            cms.PSet(record=cms.string("JetCorrectionsRecord"),
                     tag=cms.string("JetCorrectorParametersCollection_" + era +
                                    "_AK4PF"),
                     label=cms.untracked.string("AK4PF")),
            cms.PSet(record=cms.string("JetCorrectionsRecord"),
                     tag=cms.string("JetCorrectorParametersCollection_" + era +
                                    "_AK4PFchs"),
                     label=cms.untracked.string("AK4PFchs")),
            cms.PSet(record=cms.string("JetCorrectionsRecord"),
                     tag=cms.string("JetCorrectorParametersCollection_" + era +
                                    "_AK4PFPuppi"),
                     label=cms.untracked.string("AK4PFPuppi")),
        ))
    process.es_prefer_jec = cms.ESPrefer("PoolDBESSource", 'jec')

    ##___________________________External JER file________________________________||

    process.jer = cms.ESSource(
        "PoolDBESSource",
        CondDBSetup,
        #                               connect = cms.string("sqlite:PhysicsTools/PatUtils/data/JER/"+jerera+"_MC.db"),
        connect=cms.string("sqlite:" + jerera + "_MC_JER.db"),
        toGet=cms.VPSet(
            #######
            ### read the PFchs
            cms.PSet(record=cms.string('JetResolutionRcd'),
                     tag=cms.string('JR_' + jerera +
                                    '_MC_PtResolution_AK4PFchs'),
                     label=cms.untracked.string('AK4PFchs_pt')),
            cms.PSet(record=cms.string("JetResolutionRcd"),
                     tag=cms.string('JR_' + jerera +
                                    '_MC_PhiResolution_AK4PFchs'),
                     label=cms.untracked.string("AK4PFchs_phi")),
            cms.PSet(record=cms.string('JetResolutionScaleFactorRcd'),
                     tag=cms.string('JR_' + jerera + '_MC_SF_AK4PFchs'),
                     label=cms.untracked.string('AK4PFchs')),

            #######
            ### read the Puppi JER
            cms.PSet(record=cms.string('JetResolutionRcd'),
                     tag=cms.string('JR_' + jerera +
                                    '_MC_PtResolution_AK4PFPuppi'),
                     label=cms.untracked.string('AK4PFPuppi_pt')),
            cms.PSet(record=cms.string("JetResolutionRcd"),
                     tag=cms.string('JR_' + jerera +
                                    '_MC_PhiResolution_AK4PFPuppi'),
                     label=cms.untracked.string("AK4PFPuppi_phi")),
            cms.PSet(record=cms.string('JetResolutionScaleFactorRcd'),
                     tag=cms.string('JR_' + jerera + '_MC_SF_AK4PFPuppi'),
                     label=cms.untracked.string('AK4PFPuppi')),
        ))

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

    from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD

    #default configuration for miniAOD reprocessing, change the isData flag to run on data
    #for a full met computation, remove the pfCandColl input
    runMetCorAndUncFromMiniAOD(
        process,
        isData=isdata,
    )

    #    process.selectedPatJetsForMetT1T2Corr.src = cms.InputTag("cleanedPatJets")
    #    process.patPFMetT1.src = cms.InputTag("slimmedMETs")
    #
    #    process.CustomisationsSequence += process.patJetCorrFactorsReapplyJEC
    #    process.CustomisationsSequence += process.patJetsReapplyJEC
    #    process.CustomisationsSequence += process.basicJetsForMet
    #    process.CustomisationsSequence += process.jetSelectorForMet
    #    process.CustomisationsSequence += process.cleanedPatJets
    #    process.CustomisationsSequence += process.metrawCalo
    #    process.CustomisationsSequence += process.selectedPatJetsForMetT1T2Corr
    #    process.CustomisationsSequence += process.patPFMetT1T2Corr
    #    process.CustomisationsSequence += process.patPFMetT1

    #    process.CustomisationsSequence += process.patMetCorrectionSequence

    if isdata:
        return

#    process.CustomisationsSequence += process.patMetUncertaintySequence #only for MC
#    process.CustomisationsSequence += process.patShiftedModuleSequence #only for MC
    """    
Beispiel #13
0
    labelName='UpdatedJEC',
    jetCorrections=('AK4PFchs',
                    cms.vstring(['L1FastJet', 'L2Relative',
                                 'L3Absolute']), 'None'))

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

#///////////////////////////////////////////////////////////

#Reham to update the MET after updating the JEC

from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD

runMetCorAndUncFromMiniAOD(
    process,
    isData=False,  #(or False),
    postfix="TEST")

#/////////////////////////////////////////////////////

#Reham to add new instructiond for electron energy correction and smearing PLUS electron ID

from RecoEgamma.EgammaTools.EgammaPostRecoTools import setupEgammaPostRecoSeq
setupEgammaPostRecoSeq(
    process,
    runVID=True,
    eleIDModules=[
        'RecoEgamma.ElectronIdentification.Identification.mvaElectronID_Fall17_iso_V2_cff',
        'RecoEgamma.ElectronIdentification.Identification.heepElectronID_HEEPV70_cff'
    ],
    # runVID=True, #saves CPU time by not needlessly re-running VID
Beispiel #14
0
process.load('RecoMET.METFilters.BadChargedCandidateFilter_cfi')
process.BadChargedCandidateFilter.muons = cms.InputTag("slimmedMuons")
process.BadChargedCandidateFilter.PFCandidates = cms.InputTag(
    "packedPFCandidates")
process.BadChargedCandidateFilter.taggingMode = cms.bool(True)

process.metfilterSequence = cms.Sequence(process.BadPFMuonFilter *
                                         process.BadChargedCandidateFilter)

if not options.isData:
    process.PandaNtupler.metfilter = cms.InputTag('TriggerResults', '', 'PAT')

############ RECOMPUTE PUPPI/MET #######################
from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
runMetCorAndUncFromMiniAOD(
    process,  ## PF MET
    isData=isData)

process.PandaNtupler.pfmet = cms.InputTag('slimmedMETs', '', 'PandaNtupler')
process.MonoXFilter.met = cms.InputTag('slimmedMETs', '', 'PandaNtupler')

from PhysicsTools.PatAlgos.slimming.puppiForMET_cff import makePuppiesFromMiniAOD

makePuppiesFromMiniAOD(process, True)
process.puppi.useExistingWeights = False  # I still don't trust miniaod...
process.puppiNoLep.useExistingWeights = False

runMetCorAndUncFromMiniAOD(
    process,  ## Puppi MET
    isData=options.isData,
    metType="Puppi",
Beispiel #15
0
def nanoAOD_recalibrateMETs(process, isData):
    # add DeepMETs
    nanoAOD_DeepMET_switch = cms.PSet(
        nanoAOD_addDeepMET_switch=cms.untracked.bool(
            True),  # decide if DeeMET should be included in Nano
        nanoAOD_produceDeepMET_switch=cms.untracked.bool(
            False),  # decide if DeepMET should be computed on the fly
        ResponseTune_Graph=cms.untracked.string(
            'RecoMET/METPUSubtraction/data/deepmet/deepmet_resp_v1_2018.pb'))
    for modifier in run2_miniAOD_80XLegacy, run2_nanoAOD_94X2016, run2_nanoAOD_94XMiniAODv1, run2_nanoAOD_94XMiniAODv2, run2_nanoAOD_102Xv1, run2_nanoAOD_106Xv1:
        # compute DeepMETs in these eras (before 111X)
        modifier.toModify(
            nanoAOD_DeepMET_switch,
            nanoAOD_produceDeepMET_switch=cms.untracked.bool(True))
    for modifier in run2_miniAOD_80XLegacy, run2_nanoAOD_94X2016:
        modifier.toModify(
            nanoAOD_DeepMET_switch,
            ResponseTune_Graph=cms.untracked.string(
                "RecoMET/METPUSubtraction/data/deepmet/deepmet_resp_v1_2016.pb"
            ))
    if nanoAOD_DeepMET_switch.nanoAOD_addDeepMET_switch:
        process = nanoAOD_addDeepMET(
            process,
            addDeepMETProducer=nanoAOD_DeepMET_switch.
            nanoAOD_produceDeepMET_switch,
            ResponseTune_Graph=nanoAOD_DeepMET_switch.ResponseTune_Graph)

    # if included in Nano, and not computed in the fly, then it should be extracted from minAOD
    extractDeepMETs = nanoAOD_DeepMET_switch.nanoAOD_addDeepMET_switch and not nanoAOD_DeepMET_switch.nanoAOD_produceDeepMET_switch

    runMetCorAndUncFromMiniAOD(process,
                               isData=isData,
                               extractDeepMETs=extractDeepMETs)
    process.nanoSequenceCommon.insert(
        process.nanoSequenceCommon.index(process.jetSequence),
        cms.Sequence(process.fullPatMetSequence))
    process.basicJetsForMetForT1METNano = process.basicJetsForMet.clone(
        src=process.updatedJetsWithUserData.src,
        skipEM=False,
        type1JetPtThreshold=0.0,
        calcMuonSubtrRawPtAsValueMap=cms.bool(True),
    )
    process.jetSequence.insert(
        process.jetSequence.index(process.updatedJetsWithUserData),
        cms.Sequence(process.basicJetsForMetForT1METNano))
    process.updatedJetsWithUserData.userFloats.muonSubtrRawPt = cms.InputTag(
        "basicJetsForMetForT1METNano:MuonSubtrRawPt")
    process.corrT1METJetTable.src = process.finalJets.src
    process.corrT1METJetTable.cut = "pt<15 && abs(eta)<9.9"
    for table in process.jetTable, process.corrT1METJetTable:
        table.variables.muonSubtrFactor = Var(
            "1-userFloat('muonSubtrRawPt')/(pt()*jecFactor('Uncorrected'))",
            float,
            doc="1-(muon-subtracted raw pt)/(raw pt)",
            precision=6)
    process.metTables += process.corrT1METJetTable
    #    makePuppiesFromMiniAOD(process,True) # call this before in the global customizer otherwise it would reset photon IDs in VID
    #    runMetCorAndUncFromMiniAOD(process,isData=isData,metType="Puppi",postfix="Puppi",jetFlavor="AK4PFPuppi")
    #    process.puppiNoLep.useExistingWeights = False
    #    process.puppi.useExistingWeights = False
    #    process.nanoSequenceCommon.insert(process.nanoSequenceCommon.index(jetSequence),cms.Sequence(process.puppiMETSequence+process.fullPatMetSequencePuppi))
    return process
Beispiel #16
0
if isData:
    jecFile = cms.string('%s/src/Analysis/ALPHA/data/%s/%s_Uncertainty_AK4PFchs.txt' % (os.environ['CMSSW_BASE'], JECstring, JECstring))
else:
    jecFile = cms.string('%s/src/Analysis/ALPHA/data/Summer16_23Sep2016V3_MC/Summer16_23Sep2016V3_MC_Uncertainty_AK4PFchs.txt' % os.environ['CMSSW_BASE'])

runMetCorAndUncFromMiniAOD(process,
                           #metType="PF",
                           #correctionLevel=["T1","Smear"],
                           #computeUncertainties=True,
                           #produceIntermediateCorrections=False,
                           #addToPatDefaultSequence=False,
                           isData=isData,
                           #onMiniAOD=True,
                           #reapplyJEC=reapplyJEC,
                           #reclusterJets=reclusterJets,
                           #jetSelection=jetSelection,
                           #recoMetFromPFCs=recoMetFromPFCs,
                           #autoJetCleaning=jetCleaning,
                           #manualJetConfig=manualJetConfig,
                           #jetFlavor=jetFlavor,
                           #jetCorLabelUpToL3=jetCorLabelL3,
                           #jetCorLabelL3Res=jetCorLabelRes,
                           #jecUnFile=jecFile,
                           #CHS=CHS,
                           #postfix=postfix,
                           )

if isData:
    filterString = "RECO"
else:
    filterString = "PAT"
Beispiel #17
0
from RecoEgamma.EgammaTools.EgammaPostRecoTools import setupEgammaPostRecoSeq
setupEgammaPostRecoSeq(process, era='2018-Prompt')
######################################################

################   MET Re-correct   ##################
from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
process.noHFCands = cms.EDFilter(
    "CandPtrSelector",
    src=cms.InputTag("packedPFCandidates"),
    cut=cms.string(
        "abs(pdgId)!=1 && abs(pdgId)!=2 && !(eta> -3.14 && eta <1.4 && phi >-1.57 && phi < 0.87) "
    ))
runMetCorAndUncFromMiniAOD(
    process,
    isData=True,  # false for MC
    pfCandColl=cms.InputTag("noHFCands"),
    recoMetFromPFCs=True,
    reclusterJets=True,
    postfix="NoHF")
######################################################

#################   MET FILTERS   ####################
process.load('RecoMET.METFilters.ecalBadCalibFilter_cfi')
baddetEcallist = cms.vuint32([
    872439604, 872422825, 872420274, 872423218, 872423215, 872416066,
    872435036, 872439336, 872420273, 872436907, 872420147, 872439731,
    872436657, 872420397, 872439732, 872439339, 872439603, 872422436,
    872439861, 872437051, 872437052, 872420649, 872422436, 872421950,
    872437185, 872422564, 872421566, 872421695, 872421955, 872421567,
    872437184, 872421951, 872421694, 872437056, 872437057, 872437313
])
Beispiel #18
0
### Removing the HF from the MET computation as from 7 Aug 2015 recommendations
### ---------------------------------------------------------------------------
if options.useNoHFMET:
    process.noHFCands = cms.EDFilter(
        "CandPtrSelector",
        src=cms.InputTag("packedPFCandidates"),
        cut=cms.string("abs(pdgId)!=1 && abs(pdgId)!=2 && abs(eta)<3.0"))

#jets are rebuilt from those candidates by the tools, no need to do anything else
### =================================================================================

from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD

#For a full met computation, remove the pfCandColl input
runMetCorAndUncFromMiniAOD(
    process,
    isData=("Data" in options.DataProcessing),
)

if options.useNoHFMET:
    runMetCorAndUncFromMiniAOD(process,
                               isData=("Data" in options.DataProcessing),
                               pfCandColl=cms.InputTag("noHFCands"),
                               postfix="NoHF")
    jLabelNoHF = 'patJetsNoHF'

### -------------------------------------------------------------------
### the lines below remove the L2L3 residual corrections when processing data
### -------------------------------------------------------------------

if ("Data" in options.DataProcessing and options.forceResiduals):
    #Take new pat jets as input of the entuples
Beispiel #19
0
########################################

from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection

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


from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
runMetCorAndUncFromMiniAOD(process,
                           isData=runOnData,
                           metType = 'PF',
                           postfix=''
                           )

process.load('Configuration.StandardSequences.Services_cff')
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'),
Beispiel #20
0
    # MET correction
    # https://twiki.cern.ch/twiki/bin/viewauth/CMS/MissingETUncertaintyPrescription
    from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
    params = {
        "isData" : options.isData,
        "jecUncFile" : os.path.basename(options.jesUncFiles[0]),
        "electronColl" : electronCollection.value(),
        "muonColl" : muonCollection.value(),
        "jetCollUnskimmed" : jetCollection.value(),
    }
    if options.campaign == "Run2_pp_13TeV_Legacy17":
        params["fixEE2017"] = True
        params["fixEE2017Params"] = {"userawPt": True, "ptThreshold": 50.0, "minEtaThreshold": 2.65, "maxEtaThreshold": 3.139}

    runMetCorAndUncFromMiniAOD(process, **params)
    seq += process.fullPatMetSequence
    metCollection = cms.InputTag("slimmedMETs", "", process.name_())

    # add DeepJet discriminators
    from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection

    if options.campaign != "Run2_pp_13TeV_Legacy18":
        updateJetCollection(
           process,
           jetSource = jetCollection,
           pvSource = cms.InputTag('offlineSlimmedPrimaryVertices'),
           svSource = cms.InputTag('slimmedSecondaryVertices'),
           # Safe to always add 'L2L3Residual' as MC contains dummy L2L3Residual corrections (always set to 1)
           jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual']), 'None'),
           btagDiscriminators = [
)
process.jecSequence = cms.Sequence(process.patJetCorrFactorsUpdatedJEC *
                                   process.updatedPatJetsUpdatedJEC)

### END JECs ==========================================================================================

### MET ===============================================================================================
# from : https://twiki.cern.ch/twiki/bin/view/CMS/MissingETUncertaintyPrescription#We_have_a_tool_to_help_you_to_ap

# PFMET
from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD

# If you only want to re-correct and get the proper uncertainties
runMetCorAndUncFromMiniAOD(
    process,
    isData=runOnData,
    #fixEE2017 = False,
    #fixEE2017Params = {'userawPt': True, 'PtThreshold':50.0, 'MinEtaThreshold':2.65, 'MaxEtaThreshold': 3.139} ,
    postfix="ModifiedMET")

# PuppiMET
from PhysicsTools.PatAlgos.slimming.puppiForMET_cff import makePuppiesFromMiniAOD
makePuppiesFromMiniAOD(process, True)

# If you only want to re-correct and get the proper uncertainties
runMetCorAndUncFromMiniAOD(
    process,
    isData=runOnData,
    metType="Puppi",
    postfix="Puppi",
    jetFlavor="AK4PFPuppi",
)
Beispiel #22
0
from PhysicsTools.PatAlgos.producersLayer1.jetUpdater_cff import updatedPatJets
process.patJetsReapplyJEC = updatedPatJets.clone(
    jetSource=cms.InputTag("slimmedJets"),
    jetCorrFactorsSource=cms.VInputTag(
        cms.InputTag("patJetCorrFactorsReapplyJEC")))

#PFMET
from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD

# If you only want to re-correct and get the proper uncertainties
runMetCorAndUncFromMiniAOD(process,
                           isData=runOnData,
                           fixEE2017=True,
                           fixEE2017Params={
                               'userawPt': True,
                               'PtThreshold': 50.0,
                               'MinEtaThreshold': 2.65,
                               'MaxEtaThreshold': 3.139
                           },
                           postfix="ModifiedMET")

#PuppiMET
from PhysicsTools.PatAlgos.slimming.puppiForMET_cff import makePuppiesFromMiniAOD
makePuppiesFromMiniAOD(process, True)

# If you only want to re-cluster and get the proper uncertainties
runMetCorAndUncFromMiniAOD(process,
                           isData=runOnData,
                           metType="Puppi",
                           pfCandColl=cms.InputTag("puppiForMET"),
                           recoMetFromPFCs=True,
)
process.path *= (process.packedPFCandidatesCHSNotFromPV)
process.packedPFCandidatesCHS = cms.EDFilter(
    'CandPtrSelector',
    src=cms.InputTag('packedPFCandidates'),
    cut=cms.string('fromPV() > 0')  # only loose selection (0)
)
process.path *= (process.packedPFCandidatesCHS)

# -- start of MET recipe

# the following lines are for default MET for Type1 corrections

# If you only want to re-correct for JEC and get the proper uncertainties for the default MET
runMetCorAndUncFromMiniAOD(process,
                           isData=options.isData,
                           pfCandColl='packedPFCandidatesCHS',
                           recoMetFromPFCs=True)

## If you would like to re-cluster both jets and met and get the proper uncertainties
#runMetCorAndUncFromMiniAOD(process,
#                           isData=options.isData,
#                           pfCandColl=cms.InputTag("packedPFCandidates"),
#                           recoMetFromPFCs=True,
#                           CHS = True, # this is an important step and determines what type of jets to be reclustered
#                           reclusterJets = True
#                           )

# wire CHS MET to new collection from the "KAPPA" process
process.kappaTuple.PatMET.metCHS = cms.PSet(src=cms.InputTag("slimmedMETs"),
                                            uncorrected=cms.bool(True))
if not options.isData:
Beispiel #24
0
from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD

# create collection of PF candidates likely coming from the primary vertex
process.packedPFCandidatesCHS = cms.EDFilter('CandPtrSelector',
    src = cms.InputTag('packedPFCandidates'),
    cut = cms.string('fromPV() > 0')  # only loose selection (0)
)
process.path *= (process.packedPFCandidatesCHS)

# -- start of MET recipe

# the following lines are for default MET for Type1 corrections

# If you only want to re-correct for JEC and get the proper uncertainties for the default MET
runMetCorAndUncFromMiniAOD(process,
                           isData=options.isData,
                           pfCandColl='packedPFCandidatesCHS',  # TODO: use 'packedPFCandidatesCHS'?
                           recoMetFromPFCs=True)

## If you would like to re-cluster both jets and met and get the proper uncertainties
#runMetCorAndUncFromMiniAOD(process,
#                           isData=options.isData,
#                           pfCandColl=cms.InputTag("packedPFCandidates"),
#                           recoMetFromPFCs=True,
#                           CHS = True, # this is an important step and determines what type of jets to be reclustered
#                           reclusterJets = True
#                           )


# -- apply E/Gamma gain switch fix

if options.isData:
Beispiel #25
0
def getBaseConfig(
        nickname,
        testfile=False,  # false if not given, string otherwise
        maxevents=-1,
        outputfilename='kappaTuple.root'):

    from Kappa.Skimming.KSkimming_template_cfg import process
    ## ------------------------------------------------------------------------

    # count number of events before doing anything else
    process.p *= process.nEventsTotal
    process.p *= process.nNegEventsTotal

    muons = "slimmedMuons"
    electrons = "slimmedElectrons"

    # new tau id only available for 8_0_20 (I believe) and above
    if tools.is_above_cmssw_version([8, 0, 20]):
        taus = "NewTauIDsEmbedded"
    else:
        taus = "slimmedTaus"
    isSignal = datasetsHelper.isSignal(nickname)

    # produce selected collections and filter events with not even one Lepton
    if options.preselect and not isSignal:
        from Kappa.Skimming.KSkimming_preselection import do_preselection

        do_preselection(process)
        process.p *= process.goodEventFilter

        process.selectedKappaTaus.cut = cms.string('pt > 15 && abs(eta) < 2.5')
        process.selectedKappaMuons.cut = cms.string('pt > 8 && abs(eta) < 2.6')
        process.selectedKappaElectrons.cut = cms.string(
            'pt > 8 && abs(eta) < 2.7')
        muons = "selectedKappaMuons"
        electrons = "selectedKappaElectrons"
        taus = "selectedKappaTaus"
        process.goodEventFilter.minNumber = cms.uint32(2)

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

    # possibility to write out edmDump. Be careful when using unsceduled mode
    process.load("Kappa.Skimming.edmOut")
    process.ep = cms.EndPath()
    #process.ep *= process.edmOut

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

    # Configure Kappa
    if testfile:
        process.source.fileNames = cms.untracked.vstring("%s" % testfile)
    else:
        process.source = cms.Source('PoolSource',
                                    fileNames=cms.untracked.vstring())
    process.maxEvents.input = maxevents
    process.kappaTuple.verbose = cms.int32(0)
    # uncomment the following option to select only running on certain luminosity blocks. Use only for debugging
    # process.source.lumisToProcess  = cms.untracked.VLuminosityBlockRange("1:500-1:1000")
    # process.source.eventsToProcess  = cms.untracked.VEventRange("299368:56418140-299368:56418140")
    process.kappaTuple.profile = cms.bool(True)

    globaltag = datasetsHelper.getGlobalTag(nickname)
    print "Global Tag:", globaltag
    process.GlobalTag.globaltag = globaltag

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

    # Configure Metadata describing the file
    # Important to be evaluated correctly for the following steps
    # data, isEmbedded, miniaod, process.kappaTuple.TreeInfo.parameters = datasetsHelper.getTreeInfo(nickname, globaltag, kappaTag)
    process.kappaTuple.active = cms.vstring('TreeInfo')

    data = datasetsHelper.isData(nickname)
    isEmbedded = datasetsHelper.isEmbedded(nickname)
    print "nickname:", nickname

    #####miniaod = datasetsHelper.isMiniaod(nickname) not used anymore, since everything is MiniAOD now
    process.kappaTuple.TreeInfo.parameters = datasetsHelper.getTreeInfo(
        nickname)

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

    # General configuration
    if tools.is_above_cmssw_version([7, 4]) and not data and not isEmbedded:
        process.kappaTuple.Info.pileUpInfoSource = cms.InputTag(
            "slimmedAddPileupInfo", "", "PAT")
    if not tools.is_above_cmssw_version([9]):
        if isSignal:
            process.kappaTuple.Info.lheSource = cms.InputTag("source")

    # save primary vertex
    process.kappaTuple.active += cms.vstring(
        'VertexSummary')  # save VertexSummary

    process.kappaTuple.VertexSummary.whitelist = cms.vstring(
        'offlineSlimmedPrimaryVertices')  # save VertexSummary
    process.kappaTuple.VertexSummary.rename = cms.vstring(
        'offlineSlimmedPrimaryVertices => goodOfflinePrimaryVerticesSummary')

    if tools.is_above_cmssw_version([7, 6]):
        process.kappaTuple.VertexSummary.goodOfflinePrimaryVerticesSummary = cms.PSet(
            src=cms.InputTag("offlineSlimmedPrimaryVertices"))

    process.kappaTuple.active += cms.vstring('TriggerObjectStandalone')

    # setup BadPFMuonFilter and BadChargedCandidateFilter
    if tools.is_above_cmssw_version(
        [8]) and not tools.is_above_cmssw_version([9]):
        process.load('RecoMET.METFilters.BadPFMuonFilter_cfi')
        process.BadPFMuonFilter.muons = cms.InputTag("slimmedMuons")
        process.BadPFMuonFilter.PFCandidates = cms.InputTag(
            "packedPFCandidates")
        process.BadPFMuonFilter.taggingMode = cms.bool(True)

        process.load('RecoMET.METFilters.BadChargedCandidateFilter_cfi')
        process.BadChargedCandidateFilter.muons = cms.InputTag("slimmedMuons")
        process.BadChargedCandidateFilter.PFCandidates = cms.InputTag(
            "packedPFCandidates")
        process.BadChargedCandidateFilter.taggingMode = cms.bool(True)

        # in reMiniAOD data these filters are already present; only need to run the dedicated module for MC and older data
        if not "03Feb2017" in str(
                process.kappaTuple.TreeInfo.parameters.scenario):
            process.load('RecoMET.METFilters.badGlobalMuonTaggersMiniAOD_cff')
            #switch on tagging mode:
            process.badGlobalMuonTaggerMAOD.taggingMode = cms.bool(True)
            process.cloneGlobalMuonTaggerMAOD.taggingMode = cms.bool(True)
            process.kappaTuple.TriggerObjectStandalone.metfilterbitslist = cms.vstring(
                "BadChargedCandidateFilter", "BadPFMuonFilter",
                "badGlobalMuonTaggerMAOD", "cloneGlobalMuonTaggerMAOD")
        else:
            process.kappaTuple.TriggerObjectStandalone.metfilterbitslist = cms.vstring(
                "BadChargedCandidateFilter", "BadPFMuonFilter")

    process.kappaTuple.Info.hltSource = cms.InputTag("TriggerResults", "",
                                                     "HLT")
    if isEmbedded:
        process.kappaTuple.TriggerObjectStandalone.bits = cms.InputTag(
            "TriggerResults", "", "SIMembedding")
        process.kappaTuple.TriggerObjectStandalone.metfilterbits = cms.InputTag(
            "TriggerResults", "", "MERGE")
        process.kappaTuple.Info.hltSource = cms.InputTag(
            "TriggerResults", "", "SIMembedding")
    elif data:
        if tools.is_above_cmssw_version([9]):
            process.kappaTuple.Info.hltSource = cms.InputTag(
                "TriggerResults", "", "HLT")
            process.kappaTuple.TriggerObjectStandalone.metfilterbits = cms.InputTag(
                "TriggerResults", "",
                "RECO")  # take last process used in production for data
        elif "03Feb2017" in str(
                process.kappaTuple.TreeInfo.parameters.scenario):
            process.kappaTuple.TriggerObjectStandalone.metfilterbits = cms.InputTag(
                "TriggerResults", "", "PAT")
        else:
            process.kappaTuple.TriggerObjectStandalone.metfilterbits = cms.InputTag(
                "TriggerResults", "", "RECO")
            process.kappaTuple.Info.hltSource = cms.InputTag(
                "TriggerResults", "", "RECO")
    else:
        process.kappaTuple.TriggerObjectStandalone.metfilterbits = cms.InputTag(
            "TriggerResults", "",
            "PAT")  # take last process used in production for mc

    if not isEmbedded and "Spring16" in str(
            process.kappaTuple.TreeInfo.parameters.campaign):
        # adds for each HLT Trigger wich contains "Tau" or "tau" in the name a Filter object named "l1extratauccolltection"
        process.kappaTuple.TriggerObjectStandalone.l1extratauJetSource = cms.untracked.InputTag(
            "l1extraParticles", "IsoTau", "RECO")

    if not tools.is_above_cmssw_version([9]):
        process.kappaTuple.TriggerObjectStandalone.triggerObjects = cms.PSet(
            src=cms.InputTag("selectedPatTrigger"))
        process.kappaTuple.TriggerObjectStandalone.bits = cms.InputTag(
            "TriggerResults", "", "HLT")

    process.kappaTuple.active += cms.vstring('BeamSpot')
    if tools.is_above_cmssw_version([7, 6]):
        process.kappaTuple.BeamSpot.offlineBeamSpot = cms.PSet(
            src=cms.InputTag("offlineBeamSpot"))

    if not isEmbedded and data:
        process.kappaTuple.active += cms.vstring(
            'DataInfo')  # produce Metadata for data,

    if not isEmbedded and not data:
        process.kappaTuple.active += cms.vstring(
            'GenInfo')  # produce Metadata for MC,
        process.kappaTuple.active += cms.vstring(
            'GenParticles')  # save GenParticles,
        process.kappaTuple.active += cms.vstring(
            'GenTaus')  # save GenParticles,
        process.kappaTuple.GenParticles.genParticles.src = cms.InputTag(
            "prunedGenParticles")
        process.kappaTuple.GenTaus.genTaus.src = cms.InputTag(
            "prunedGenParticles")

    # write out for all processes where available
    process.kappaTuple.Info.lheWeightNames = cms.vstring(".*")

    # save Flag
    process.kappaTuple.Info.isEmbedded = cms.bool(isEmbedded)

    if isEmbedded:
        #process.load('RecoBTag/Configuration/RecoBTag_cff')
        #process.load('RecoJets/JetAssociationProducers/ak5JTA_cff')
        #process.ak5PFJetNewTracksAssociatorAtVertex.tracks = "tmfTracks"
        #process.ak5PFCHSNewJetTracksAssociatorAtVertex.tracks = "tmfTracks"
        #process.p *= process.btagging
        # disable overrideHLTCheck for embedded samples, since it triggers an Kappa error
        process.kappaTuple.Info.overrideHLTCheck = cms.untracked.bool(True)
        process.kappaTuple.active += cms.vstring('GenInfo')
        process.kappaTuple.active += cms.vstring(
            'GenParticles')  # save GenParticles,
        process.kappaTuple.GenParticles.genParticles.src = cms.InputTag(
            "prunedGenParticles")
        process.kappaTuple.active += cms.vstring('GenTaus')
        process.kappaTuple.GenTaus.genTaus.src = cms.InputTag(
            "prunedGenParticles")

        #process.kappaTuple.active += cms.vstring('GenTaus') # save GenParticles,
        #process.kappaTuple.GenParticles.genParticles.src = cms.InputTag("genParticles","","EmbeddedRECO")

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

    # Trigger
    from Kappa.Skimming.hlt_run2 import hltBlacklist, hltWhitelist
    process.kappaTuple.Info.hltWhitelist = hltWhitelist
    process.kappaTuple.Info.hltBlacklist = hltBlacklist

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

    # should not be the default, it blows up the skim a lot
    #process.kappaTuple.active += cms.vstring('packedPFCandidates')
    #process.kappaTuple.packedPFCandidates.packedPFCandidates = cms.PSet(src = cms.InputTag("packedPFCandidates"))

    jetCollectionPuppi = "slimmedJetsPuppi"
    if tools.is_above_cmssw_version([9]):
        jetCollection = "slimmedJets"
    elif tools.is_above_cmssw_version([8]):
        from RecoMET.METPUSubtraction.jet_recorrections import recorrectJets
        #from RecoMET.METPUSubtraction.jet_recorrections import loadLocalSqlite
        #loadLocalSqlite(process, sqliteFilename = "Spring16_25nsV6_DATA.db" if data else "Spring16_25nsV6_MC.db",
        #                         tag = 'JetCorrectorParametersCollection_Spring16_25nsV6_DATA_AK4PF' if data else 'JetCorrectorParametersCollection_Spring16_25nsV6_MC_AK4PF')
        recorrectJets(process, isData=data)
        jetCollection = "patJetsReapplyJEC"
    else:
        from RecoMET.METPUSubtraction.localSqlite import recorrectJets
        recorrectJets(process, isData=data)
        jetCollection = "patJetsReapplyJEC"

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

    # Configure Muons
    process.load("Kappa.Skimming.KMuons_miniAOD_cff")
    process.kappaTuple.Muons.muons.src = cms.InputTag(muons)
    process.kappaTuple.Muons.muons.vertexcollection = cms.InputTag(
        "offlineSlimmedPrimaryVertices")
    process.kappaTuple.Muons.use03ConeForPfIso = cms.bool(True)
    process.kappaTuple.Muons.doPfIsolation = cms.bool(False)
    for src in [
            "muPFIsoDepositCharged", "muPFIsoDepositChargedAll",
            "muPFIsoDepositNeutral", "muPFIsoDepositGamma", "muPFIsoDepositPU"
    ]:
        setattr(getattr(process, src), "src", cms.InputTag(muons))

    process.kappaTuple.active += cms.vstring('Muons')
    process.kappaTuple.Muons.noPropagation = cms.bool(True)
    process.p *= (process.makeKappaMuons)

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

    # Configure Electrons
    process.kappaTuple.active += cms.vstring('Electrons')
    process.load("Kappa.Skimming.KElectrons_miniAOD_cff")
    process.kappaTuple.Electrons.electrons.src = cms.InputTag(
        "slimmedElectrons")
    process.kappaTuple.Electrons.electrons.vertexcollection = cms.InputTag(
        "offlineSlimmedPrimaryVertices")
    process.kappaTuple.Electrons.electrons.rhoIsoInputTag = cms.InputTag(
        "slimmedJets", "rho")
    process.kappaTuple.Electrons.electrons.allConversions = cms.InputTag(
        "reducedEgamma", "reducedConversions")
    from Kappa.Skimming.KElectrons_miniAOD_cff import setupElectrons
    process.kappaTuple.Electrons.srcIds = cms.string("standalone")

    if tools.is_above_cmssw_version([9, 4]):
        process.kappaTuple.Electrons.ids = cms.VInputTag(
            "egmGsfElectronIDs:cutBasedElectronID-Fall17-94X-V1-veto",
            "egmGsfElectronIDs:cutBasedElectronID-Fall17-94X-V1-loose",
            "egmGsfElectronIDs:cutBasedElectronID-Fall17-94X-V1-medium",
            "egmGsfElectronIDs:cutBasedElectronID-Fall17-94X-V1-tight",
            "egmGsfElectronIDs:mvaEleID-Fall17-noIso-V1-wp90",
            "egmGsfElectronIDs:mvaEleID-Fall17-noIso-V1-wp80",
            "egmGsfElectronIDs:mvaEleID-Fall17-noIso-V1-wpLoose",
            "egmGsfElectronIDs:mvaEleID-Fall17-iso-V1-wp90",
            "egmGsfElectronIDs:mvaEleID-Fall17-iso-V1-wp80",
            "egmGsfElectronIDs:mvaEleID-Fall17-iso-V1-wpLoose",
            "electronMVAValueMapProducer:ElectronMVAEstimatorRun2Fall17NoIsoV1Values",
            "electronMVAValueMapProducer:ElectronMVAEstimatorRun2Fall17IsoV1Values",
            "egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-veto",
            "egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-loose",
            "egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-medium",
            "egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-tight",
            "electronMVAValueMapProducer:ElectronMVAEstimatorRun2Spring16GeneralPurposeV1Values"
        )
    elif tools.is_above_cmssw_version([8]):
        process.kappaTuple.Electrons.ids = cms.VInputTag(
            "egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-veto",
            "egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-loose",
            "egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-medium",
            "egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-tight",
            "electronMVAValueMapProducer:ElectronMVAEstimatorRun2Spring16GeneralPurposeV1Values"
        )
    else:
        process.kappaTuple.Electrons.ids = cms.VInputTag(
            "egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-veto",
            "egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-loose",
            "egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-medium",
            "egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-tight",
            "electronMVAValueMapProducer:ElectronMVAEstimatorRun2Spring15NonTrig25nsV1Values"
        )

    setupElectrons(process, electrons)
    process.p *= (process.makeKappaElectrons)

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

    # new tau id only available for 8_0_20 (I believe) and above
    if tools.is_above_cmssw_version([8, 0, 20]):
        process.load(
            'RecoTauTag.Configuration.loadRecoTauTagMVAsFromPrepDB_cfi')
        process.load("Kappa.Skimming.KPatTaus_run2_cff")
        process.p *= (process.makeKappaTaus)

        # embed new id's into new tau collection
        embedID = cms.EDProducer(
            "PATTauIDEmbedder",
            src=cms.InputTag('slimmedTaus'),
            tauIDSources=cms.PSet(
                rerunDiscriminationByIsolationMVAOldDMrun2v1raw=cms.InputTag(
                    'rerunDiscriminationByIsolationMVAOldDMrun2v1raw'),
                rerunDiscriminationByIsolationMVAOldDMrun2v1VLoose=cms.
                InputTag('rerunDiscriminationByIsolationMVAOldDMrun2v1VLoose'),
                rerunDiscriminationByIsolationMVAOldDMrun2v1Loose=cms.InputTag(
                    'rerunDiscriminationByIsolationMVAOldDMrun2v1Loose'),
                rerunDiscriminationByIsolationMVAOldDMrun2v1Medium=cms.
                InputTag('rerunDiscriminationByIsolationMVAOldDMrun2v1Medium'),
                rerunDiscriminationByIsolationMVAOldDMrun2v1Tight=cms.InputTag(
                    'rerunDiscriminationByIsolationMVAOldDMrun2v1Tight'),
                rerunDiscriminationByIsolationMVAOldDMrun2v1VTight=cms.
                InputTag('rerunDiscriminationByIsolationMVAOldDMrun2v1VTight'),
                rerunDiscriminationByIsolationMVAOldDMrun2v1VVTight=cms.
                InputTag(
                    'rerunDiscriminationByIsolationMVAOldDMrun2v1VVTight'),
                rerunDiscriminationByIsolationMVANewDMrun2v1raw=cms.InputTag(
                    'rerunDiscriminationByIsolationMVANewDMrun2v1raw'),
                rerunDiscriminationByIsolationMVANewDMrun2v1VLoose=cms.
                InputTag('rerunDiscriminationByIsolationMVANewDMrun2v1VLoose'),
                rerunDiscriminationByIsolationMVANewDMrun2v1Loose=cms.InputTag(
                    'rerunDiscriminationByIsolationMVANewDMrun2v1Loose'),
                rerunDiscriminationByIsolationMVANewDMrun2v1Medium=cms.
                InputTag('rerunDiscriminationByIsolationMVANewDMrun2v1Medium'),
                rerunDiscriminationByIsolationMVANewDMrun2v1Tight=cms.InputTag(
                    'rerunDiscriminationByIsolationMVANewDMrun2v1Tight'),
                rerunDiscriminationByIsolationMVANewDMrun2v1VTight=cms.
                InputTag('rerunDiscriminationByIsolationMVANewDMrun2v1VTight'),
                rerunDiscriminationByIsolationMVANewDMrun2v1VVTight=cms.
                InputTag(
                    'rerunDiscriminationByIsolationMVANewDMrun2v1VVTight')),
        )
        setattr(process, taus, embedID)
        process.p *= getattr(process, taus)

    process.kappaTuple.active += cms.vstring('PatTaus')
    process.kappaTuple.PatTaus.taus.binaryDiscrBlacklist = cms.vstring()
    process.kappaTuple.PatTaus.taus.src = cms.InputTag(taus)
    process.kappaTuple.PatTaus.taus.floatDiscrBlacklist = cms.vstring()
    # just took everything from https://twiki.cern.ch/twiki/bin/viewauth/CMS/TauIDRecommendation13TeV
    process.kappaTuple.PatTaus.taus.preselectOnDiscriminators = cms.vstring()
    process.kappaTuple.PatTaus.taus.binaryDiscrWhitelist = cms.vstring(
        "decayModeFinding",
        "decayModeFindingNewDMs",
        "byLooseCombinedIsolationDeltaBetaCorr3Hits",
        "byMediumCombinedIsolationDeltaBetaCorr3Hits",
        "byTightCombinedIsolationDeltaBetaCorr3Hits",
        "byCombinedIsolationDeltaBetaCorrRaw3Hits",
        "chargedIsoPtSum",
        "neutralIsoPtSum",
        "neutralIsoPtSumWeight",
        "puCorrPtSum",
        "footprintCorrection",
        "photonPtSumOutsideSignalCone",
        "byIsolationMVArun2v1DBoldDMwLTraw",
        "byVLooseIsolationMVArun2v1DBoldDMwLT",
        "byLooseIsolationMVArun2v1DBoldDMwLT",
        "byMediumIsolationMVArun2v1DBoldDMwLT",
        "byTightIsolationMVArun2v1DBoldDMwLT",
        "byVTightIsolationMVArun2v1DBoldDMwLT",
        "byVVTightIsolationMVArun2v1DBoldDMwLT",
        #"byIsolationMVArun2v1DBnewDMwLTraw",
        #"byVLooseIsolationMVArun2v1DBnewDMwLT",
        #"byLooseIsolationMVArun2v1DBnewDMwLT",
        #"byMediumIsolationMVArun2v1DBnewDMwLT",
        #"byTightIsolationMVArun2v1DBnewDMwLT",
        #"byVTightIsolationMVArun2v1DBnewDMwLT",
        #"byVVTightIsolationMVArun2v1DBnewDMwLT",
        "againstMuonLoose3",
        "againstMuonTight3",
        "againstElectronMVA6category",
        "againstElectronMVA6raw",
        "againstElectronVLooseMVA6",
        "againstElectronLooseMVA6",
        "againstElectronMediumMVA6",
        "againstElectronTightMVA6",
        "againstElectronVTightMVA6"  #,
        #"chargedIsoPtSumdR03",
        #"neutralIsoPtSumdR03",
        #"neutralIsoPtSumWeightdR03",
        #"footprintCorrectiondR03",
        #"photonPtSumOutsideSignalConedR03",
        #"byLooseCombinedIsolationDeltaBetaCorr3HitsdR03",
        #"byMediumCombinedIsolationDeltaBetaCorr3HitsdR03",
        #"byTightCombinedIsolationDeltaBetaCorr3HitsdR03",
        #"byIsolationMVArun2v1DBdR03oldDMwLTraw",
        #"byVLooseIsolationMVArun2v1DBdR03oldDMwLT",
        #"byLooseIsolationMVArun2v1DBdR03oldDMwLT",
        #"byMediumIsolationMVArun2v1DBdR03oldDMwLT",
        #"byTightIsolationMVArun2v1DBdR03oldDMwLT",
        #"byVTightIsolationMVArun2v1DBdR03oldDMwLT",
        #"byVVTightIsolationMVArun2v1DBdR03oldDMwLT",
    )
    if tools.is_above_cmssw_version([8, 0, 20]):
        process.kappaTuple.PatTaus.taus.binaryDiscrWhitelist += cms.vstring(
            "rerunDiscriminationByIsolationMVAOldDMrun2v1raw",
            "rerunDiscriminationByIsolationMVAOldDMrun2v1VLoose",
            "rerunDiscriminationByIsolationMVAOldDMrun2v1Loose",
            "rerunDiscriminationByIsolationMVAOldDMrun2v1Medium",
            "rerunDiscriminationByIsolationMVAOldDMrun2v1Tight",
            "rerunDiscriminationByIsolationMVAOldDMrun2v1VTight",
            "rerunDiscriminationByIsolationMVAOldDMrun2v1VVTight",
            "rerunDiscriminationByIsolationMVANewDMrun2v1raw",
            "rerunDiscriminationByIsolationMVANewDMrun2v1VLoose",
            "rerunDiscriminationByIsolationMVANewDMrun2v1Loose",
            "rerunDiscriminationByIsolationMVANewDMrun2v1Medium",
            "rerunDiscriminationByIsolationMVANewDMrun2v1Tight",
            "rerunDiscriminationByIsolationMVANewDMrun2v1VTight",
            "rerunDiscriminationByIsolationMVANewDMrun2v1VVTight")
    ## now also possible to save all MVA isolation inputs for taus # turn of per default

    process.kappaTuple.PatTaus.taus.extrafloatDiscrlist = cms.untracked.vstring(
        "decayDistX", "decayDistY", "decayDistZ", "decayDistM", "nPhoton",
        "ptWeightedDetaStrip", "ptWeightedDphiStrip", "ptWeightedDrSignal",
        "ptWeightedDrIsolation", "leadingTrackChi2", "eRatio")

    process.kappaTuple.PatTaus.taus.floatDiscrWhitelist = process.kappaTuple.PatTaus.taus.binaryDiscrWhitelist
    process.kappaTuple.PatTaus.verbose = cms.int32(1)

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

    ## Configure Jets
    process.kappaTuple.active += cms.vstring('PileupDensity')
    process.kappaTuple.PileupDensity.whitelist = cms.vstring(
        "fixedGridRhoFastjetAll")
    process.kappaTuple.PileupDensity.rename = cms.vstring(
        "fixedGridRhoFastjetAll => pileupDensity")
    if tools.is_above_cmssw_version([7, 6]):
        process.kappaTuple.PileupDensity.pileupDensity = cms.PSet(
            src=cms.InputTag("fixedGridRhoFastjetAll"))
    process.kappaTuple.active += cms.vstring('PatJets')
    if tools.is_above_cmssw_version([7, 6]):
        process.kappaTuple.PatJets.ak4PF = cms.PSet(
            src=cms.InputTag(jetCollection))
        process.kappaTuple.PatJets.puppiJets = cms.PSet(
            src=cms.InputTag(jetCollectionPuppi))

    ## Standard MET and GenMet from pat::MET
    process.kappaTuple.active += cms.vstring('PatMET')
    process.kappaTuple.PatMET.met = cms.PSet(src=cms.InputTag("slimmedMETs"))
    if tools.is_above_cmssw_version([9]):
        pass
    elif tools.is_above_cmssw_version([8, 0, 14]):
        from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
        runMetCorAndUncFromMiniAOD(process, isData=data)
        process.kappaTuple.PatMET.met = cms.PSet(
            src=cms.InputTag("slimmedMETs", "", "KAPPA"))

    #process.kappaTuple.PatMET.pfmetT1 = cms.PSet(src=cms.InputTag("patpfMETT1"))
    process.kappaTuple.PatMET.metPuppi = cms.PSet(
        src=cms.InputTag("slimmedMETsPuppi"))

    if not tools.is_above_cmssw_version([9]):
        ## Write MVA MET to KMETs
        process.kappaTuple.active += cms.vstring('PatMETs')
        # new MVA MET
        from RecoMET.METPUSubtraction.MVAMETConfiguration_cff import runMVAMET
        runMVAMET(process, jetCollectionPF=jetCollection)
        process.kappaTuple.PatMETs.MVAMET = cms.PSet(
            src=cms.InputTag("MVAMET", "MVAMET"))
        process.MVAMET.srcLeptons = cms.VInputTag(
            muons, electrons, taus)  # to produce all possible combinations
        process.MVAMET.requireOS = cms.bool(False)
        if tools.is_above_cmssw_version([8, 0]) and isEmbedded:
            process.MVAMET.srcMETs = cms.VInputTag(
                cms.InputTag("slimmedMETs", "", "MERGE"),
                cms.InputTag("patpfTrackMET"), cms.InputTag("patpfNoPUMET"),
                cms.InputTag("patpfPUCorrectedMET"),
                cms.InputTag("patpfPUMET"),
                cms.InputTag("slimmedMETsPuppi", "", "MERGE"))

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

    ## GenJets
    if not data or isEmbedded:
        process.load('PhysicsTools/JetMCAlgos/TauGenJets_cfi')
        process.load(
            'PhysicsTools/JetMCAlgos/TauGenJetsDecayModeSelectorAllHadrons_cfi'
        )
        process.tauGenJets.GenParticles = cms.InputTag("prunedGenParticles")
        process.p *= (process.tauGenJets +
                      process.tauGenJetsSelectorAllHadrons)
        if isSignal:
            process.kappaTuple.GenJets.whitelist = cms.vstring(
                "tauGenJets", "slimmedGenJets")
        else:
            process.kappaTuple.GenJets.whitelist = cms.vstring("tauGenJets")
        process.kappaTuple.active += cms.vstring('GenJets')
        if tools.is_above_cmssw_version([7, 6]):
            if isSignal:
                process.kappaTuple.GenJets.genJets = cms.PSet(
                    src=cms.InputTag("slimmedGenJets"))
            process.kappaTuple.GenJets.tauGenJets = cms.PSet(
                src=cms.InputTag("tauGenJets"))
            process.kappaTuple.GenJets.tauGenJetsSelectorAllHadrons = cms.PSet(
                src=cms.InputTag("tauGenJetsSelectorAllHadrons"))

    # add repository revisions to TreeInfo
    for repo, rev in tools.get_repository_revisions().iteritems():
        setattr(process.kappaTuple.TreeInfo.parameters, repo, cms.string(rev))

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

    ## Count Events after running all filters
    if not data:
        process.nEventsTotal.isMC = cms.bool(True)
        process.nNegEventsTotal.isMC = cms.bool(True)
        process.nEventsFiltered.isMC = cms.bool(True)
        process.nNegEventsFiltered.isMC = cms.bool(True)

    process.p *= process.nEventsFiltered
    process.p *= process.nNegEventsFiltered
    process.kappaTuple.active += cms.vstring('FilterSummary')

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

    ## if needed adapt output filename
    process.ep *= process.kappaOut
    if outputfilename != '':
        process.kappaTuple.outputFile = cms.string('%s' % outputfilename)

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

    ## Further information saved to Kappa output
    if options.dumpPython:
        f = open("dumpPython.py", "w")
        f.write(process.dumpPython())
        f.close()

    # add python config to TreeInfo
    process.kappaTuple.TreeInfo.parameters.config = cms.string(
        process.dumpPython())

    return process
    fillpfjetInfo_=cms.untracked.bool(True),
    pfjetLabel_=cms.untracked.InputTag("selectedUpdatedPatJetsUpdatedJEC"),
    filltauInfo_=cms.untracked.bool(False),
    tauLabel_=cms.untracked.InputTag("slimmedTaus"),
)

process.TFileService = cms.Service("TFileService",
                                   fileName=cms.string("histo.root"),
                                   closeFileFast=cms.untracked.bool(True))

from RecoEgamma.EgammaTools.EgammaPostRecoTools import setupEgammaPostRecoSeq
setupEgammaPostRecoSeq(process, runVID=False, era='2018-Prompt')

from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
runMetCorAndUncFromMiniAOD(
    process,
    isData=False,
)

from PhysicsTools.PatAlgos.slimming.puppiForMET_cff import makePuppiesFromMiniAOD
makePuppiesFromMiniAOD(process, True)
runMetCorAndUncFromMiniAOD(
    process,
    isData=False,
    metType="Puppi",
    postfix="Puppi",
    jetFlavor="AK4PFPuppi",
)
process.puppi.useExistingWeights = True

#All paths are here
process.p = cms.Path(
            jetCorrections=('AK4PFchs', [
                'L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual'
            ], ''),
            genParticles=cms.InputTag('prunedGenParticles'),
            pvSource=cms.InputTag('offlineSlimmedPrimaryVertices'))

    process.patJets.addGenJetMatch = cms.bool(False)
    process.patJets.addGenPartonMatch = cms.bool(False)
    process.patJets.addPartonJetMatch = cms.bool(False)

    from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD

    #default configuration for miniAOD reprocessing, change the isData flag to run on data
    #for a full met computation, remove the pfCandColl input
    runMetCorAndUncFromMiniAOD(
        process,
        isData=not (config["RUNONMC"]),
    )
    process.patPFMetT1T2Corr.type1JetPtThreshold = cms.double(15.0)
    process.patPFMetT2Corr.type1JetPtThreshold = cms.double(15.0)
    process.slimmedMETs.t01Variation = cms.InputTag("slimmedMETs", "", "RECO")

    if config["RUNONMC"]:
        process.patPFMetT1T2Corr.jetCorrLabelRes = cms.InputTag("L3Absolute")
        process.patPFMetT1T2SmearCorr.jetCorrLabelRes = cms.InputTag(
            "L3Absolute")
        process.patPFMetT2Corr.jetCorrLabelRes = cms.InputTag("L3Absolute")
        process.patPFMetT2SmearCorr.jetCorrLabelRes = cms.InputTag(
            "L3Absolute")
        process.shiftedPatJetEnDown.jetCorrLabelUpToL3Res = cms.InputTag(
            "ak4PFCHSL1FastL2L3Corrector")
        process.shiftedPatJetEnUp.jetCorrLabelUpToL3Res = cms.InputTag(
def reproduceMET(process,isdata):

    from CondCore.DBCommon.CondDBSetup_cfi import *
    import os

    if isdata:
      era="Spring16_25nsV6_DATA"
    else:
      era="Spring16_25nsV6_MC"
    jerera="Spring16_25nsV6"

##___________________________External JEC file________________________________||
 
    process.jec = cms.ESSource("PoolDBESSource",CondDBSetup,
#                               connect = cms.string("sqlite:PhysicsTools/PatUtils/data/"+era+".db"),
                               connect = cms.string("sqlite:"+era+"_JEC.db"),
                               toGet =  cms.VPSet(
            cms.PSet(
                record = cms.string("JetCorrectionsRecord"),
                tag = cms.string("JetCorrectorParametersCollection_"+era+"_AK4PF"),
                label= cms.untracked.string("AK4PF")
                ),
            cms.PSet(
                record = cms.string("JetCorrectionsRecord"),
                tag = cms.string("JetCorrectorParametersCollection_"+era+"_AK4PFchs"),  
                label= cms.untracked.string("AK4PFchs")
                ),
            cms.PSet(record  = cms.string("JetCorrectionsRecord"),
                tag     = cms.string("JetCorrectorParametersCollection_"+era+"_AK4PFPuppi"),
                label   = cms.untracked.string("AK4PFPuppi")
                ),
            )
                               )
    process.es_prefer_jec = cms.ESPrefer("PoolDBESSource",'jec')

##___________________________External JER file________________________________||
    
    process.jer = cms.ESSource("PoolDBESSource",CondDBSetup,
#                               connect = cms.string("sqlite:PhysicsTools/PatUtils/data/JER/"+jerera+"_MC.db"),
                               connect = cms.string("sqlite:"+jerera+"_MC_JER.db"),
                               toGet =  cms.VPSet(
        #######
        ### read the PFchs  

        cms.PSet(
          record = cms.string('JetResolutionRcd'),
          tag    = cms.string('JR_'+jerera+'_MC_PtResolution_AK4PFchs'),
          label  = cms.untracked.string('AK4PFchs_pt')
          ),
        cms.PSet(
          record = cms.string("JetResolutionRcd"),
          tag    = cms.string('JR_'+jerera+'_MC_PhiResolution_AK4PFchs'),
          label  = cms.untracked.string("AK4PFchs_phi")
          ),
        cms.PSet( 
          record = cms.string('JetResolutionScaleFactorRcd'),
          tag    = cms.string('JR_'+jerera+'_MC_SF_AK4PFchs'),
          label  = cms.untracked.string('AK4PFchs')
          ),
                  
        #######
        ### read the Puppi JER
                
        cms.PSet( 
          record = cms.string('JetResolutionRcd'),
          tag    = cms.string('JR_'+jerera+'_MC_PtResolution_AK4PFPuppi'),
          label  = cms.untracked.string('AK4PFPuppi_pt')
          ),
        cms.PSet(
          record = cms.string("JetResolutionRcd"),
          tag = cms.string('JR_'+jerera+'_MC_PhiResolution_AK4PFPuppi'),
          label= cms.untracked.string("AK4PFPuppi_phi")
          ),
        cms.PSet(
          record = cms.string('JetResolutionScaleFactorRcd'),
          tag    = cms.string('JR_'+jerera+'_MC_SF_AK4PFPuppi'),
          label  = cms.untracked.string('AK4PFPuppi')
          ),
          
        ) )
          
    process.es_prefer_jer = cms.ESPrefer("PoolDBESSource",'jer')

    from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
    
    #default configuration for miniAOD reprocessing, change the isData flag to run on data
    #for a full met computation, remove the pfCandColl input
    runMetCorAndUncFromMiniAOD(process,
                           isData=isdata,
                           )

#    process.selectedPatJetsForMetT1T2Corr.src = cms.InputTag("cleanedPatJets")
#    process.patPFMetT1.src = cms.InputTag("slimmedMETs")
#
#    process.CustomisationsSequence += process.patJetCorrFactorsReapplyJEC 
#    process.CustomisationsSequence += process.patJetsReapplyJEC
#    process.CustomisationsSequence += process.basicJetsForMet
#    process.CustomisationsSequence += process.jetSelectorForMet
#    process.CustomisationsSequence += process.cleanedPatJets
#    process.CustomisationsSequence += process.metrawCalo
#    process.CustomisationsSequence += process.selectedPatJetsForMetT1T2Corr   
#    process.CustomisationsSequence += process.patPFMetT1T2Corr
#    process.CustomisationsSequence += process.patPFMetT1

#    process.CustomisationsSequence += process.patMetCorrectionSequence

    if isdata:
        return

#    process.CustomisationsSequence += process.patMetUncertaintySequence #only for MC
#    process.CustomisationsSequence += process.patShiftedModuleSequence #only for MC


    """    
process.QGTagger.srcVertexCollection = cms.InputTag("offlinePrimaryVertices")

# compute corrected pruned jet mass
process.corrJets = cms.EDProducer(
    "CorrJetsProducer",
    jets=cms.InputTag("slimmedJetsAK8JEC"),
    vertex=cms.InputTag("offlineSlimmedPrimaryVertices"),
    rho=cms.InputTag("fixedGridRhoFastjetAll"),
    payload=cms.string("AK8PFchs"),
    isData=cms.bool(False),
    year=cms.untracked.int32(2016))

# Recompute MET
from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
runMetCorAndUncFromMiniAOD(
    process,
    isData=True,
)

# STXS
process.load("SimGeneral.HepPDTESSource.pythiapdt_cfi")
process.mergedGenParticles = cms.EDProducer(
    "MergedGenParticleProducer",
    inputPruned=cms.InputTag("prunedGenParticles"),
    inputPacked=cms.InputTag("packedGenParticles"),
)
process.myGenerator = cms.EDProducer(
    "GenParticles2HepMCConverter",
    genParticles=cms.InputTag("mergedGenParticles"),
    genEventInfo=cms.InputTag("generator"),
    signalParticlePdgIds=cms.vint32(25))
process.rivetProducerHTXS = cms.EDProducer(
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
        from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection
        updateJetCollection(process,
                            jetSource=cms.InputTag('slimmedJetsPuppi'),
                            postfix='UpdatedJECAK4PFPuppi',
                            jetCorrections=('AK4PFPuppi', [
                                'L1FastJet', 'L2Relative', 'L3Absolute'
                            ], 'None'))
        process.ntuple.jets = "updatedPatJetsUpdatedJECAK4PFPuppi"

        from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD

        runMetCorAndUncFromMiniAOD(
            process,
            isData=False,
            metType="Puppi",
            postfix="PuppiCorr",
            pfCandColl=cms.InputTag("puppiForMET"),
            recoMetFromPFCs=True,
            jetFlavor="AK4PFPuppi",
        )

        puppiMetSource = cms.InputTag("slimmedMETsPuppiCorr", "",
                                      "MiniAnalysis")

from PhysicsTools.PatAlgos.slimming.puppiForMET_cff import makePuppiesFromMiniAOD

makePuppiesFromMiniAOD(process, True)

process.ntuple.mets = puppiMetSource

process.jetmetsequence = cms.Sequence()
Beispiel #32
0
    from PhysicsTools.PatAlgos.producersLayer1.jetUpdater_cff import patJetsUpdated
    process.patJetsReapplyJEC = patJetsUpdated.clone(
        jetSource = cms.InputTag("slimmedJets"),
        jetCorrFactorsSource = cms.VInputTag(cms.InputTag("patJetCorrFactorsReapplyJEC"))
    )

    ###### Apply new JECs to MET
    ## From https://github.com/cms-met/cmssw/blob/METCorUnc74X/PhysicsTools/PatAlgos/test/corMETFromMiniAOD.py
    process.options = cms.untracked.PSet(
        allowUnscheduled = cms.untracked.bool(True),
        wantSummary = cms.untracked.bool(False)
    )
    from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
    runMetCorAndUncFromMiniAOD(process,
                               isData=isData,
                               pfCandColl=cms.InputTag("packedPFCandidates")
                           )
    if isData:
        process.patPFMetT1T2Corr.jetCorrLabelRes = cms.InputTag("L3Absolute")
        process.patPFMetT1T2SmearCorr.jetCorrLabelRes = cms.InputTag("L3Absolute")
        process.patPFMetT2Corr.jetCorrLabelRes = cms.InputTag("L3Absolute")
        process.patPFMetT2SmearCorr.jetCorrLabelRes = cms.InputTag("L3Absolute")
        process.shiftedPatJetEnDown.jetCorrLabelUpToL3Res = cms.InputTag("ak4PFCHSL1FastL2L3Corrector")
        process.shiftedPatJetEnUp.jetCorrLabelUpToL3Res = cms.InputTag("ak4PFCHSL1FastL2L3Corrector")
    # Redefine process for data to RECO
    process.slimmedMETs.t01Variation = cms.InputTag("slimmedMETs","",processRECO)

    ###### Path
    process.p = cms.Path(process.patJetCorrFactorsReapplyJEC*
                         process.patJetsReapplyJEC*
                         #process.HBHENoiseFilterResultProducer* #produces HBHE baseline bools
Beispiel #33
0
                         era='2017-Nov17ReReco',
                         eleIDModules=myEleID,
                         phoIDModules=myPhoID,
  )
  #a sequence egammaPostRecoSeq has now been created and should be added to your path, eg process.p=cms.Path(process.egammaPostRecoSeq)

  ###########################
  #### MET EE Noise
  ###########################

  from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD

  runMetCorAndUncFromMiniAOD (
          process,
          isData = (not isMC), # false for MC
          fixEE2017 = True,
          fixEE2017Params = {'userawPt': True, 'ptThreshold':50.0, 'minEtaThreshold':2.65, 'maxEtaThreshold': 3.139} ,
          postfix = "ModifiedMET"
  )
  process.recoTree.MET = cms.InputTag("slimmedMETsModifiedMET")

  #################
  ### Reapply JEC
  ### https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookJetEnergyCorrections#CorrPatJets
  #################

  from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection

  #### AK4

  updateJetCollection(
                         jetSource = cms.InputTag('ak4PFJetsCHS'),
		         jetCorrections = ('AK4PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute','L2L3Residual'], ''),
		         genParticles = cms.InputTag('prunedGenParticles'),
		         pvSource = cms.InputTag('offlineSlimmedPrimaryVertices')
     )
		  		
  process.patJets.addGenJetMatch = cms.bool(False) 
  process.patJets.addGenPartonMatch = cms.bool(False) 
  process.patJets.addPartonJetMatch = cms.bool(False) 
  
  from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD

  #default configuration for miniAOD reprocessing, change the isData flag to run on data
  #for a full met computation, remove the pfCandColl input
  runMetCorAndUncFromMiniAOD(process,
                           isData=not(config["RUNONMC"]),
                           )
  process.patPFMetT1T2Corr.type1JetPtThreshold = cms.double(15.0)
  process.patPFMetT2Corr.type1JetPtThreshold = cms.double(15.0)
  process.slimmedMETs.t01Variation = cms.InputTag("slimmedMETs","","RECO")
  
  if config["RUNONMC"]:
    process.patPFMetT1T2Corr.jetCorrLabelRes = cms.InputTag("L3Absolute")
    process.patPFMetT1T2SmearCorr.jetCorrLabelRes = cms.InputTag("L3Absolute")
    process.patPFMetT2Corr.jetCorrLabelRes = cms.InputTag("L3Absolute")
    process.patPFMetT2SmearCorr.jetCorrLabelRes = cms.InputTag("L3Absolute")
    process.shiftedPatJetEnDown.jetCorrLabelUpToL3Res = cms.InputTag("ak4PFCHSL1FastL2L3Corrector")
    process.shiftedPatJetEnUp.jetCorrLabelUpToL3Res = cms.InputTag("ak4PFCHSL1FastL2L3Corrector")
			           
####### Adding HEEP id ##########
Beispiel #35
0
                                 'L3Absolute']), 'None'))
updateJetCollection(
    process,
    jetSource=cms.InputTag('slimmedJetsAK8'),
    labelName='UpdatedJECAK8',
    jetCorrections=('AK8PFchs',
                    cms.vstring(['L1FastJet', 'L2Relative',
                                 'L3Absolute']), 'None'),
    btagDiscriminators=['pfBoostedDoubleSecondaryVertexAK8BJetTags'],
    btagPrefix=
    'newV4'  # optional, in case interested in accessing both the old and new discriminator values
)

# MET correction and uncertainties
from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
runMetCorAndUncFromMiniAOD(process, isData=False)

process.load("ggAnalysis.ggNtuplizer.ggNtuplizer_miniAOD_cfi")
process.load("ggAnalysis.ggNtuplizer.ggPhotonIso_CITK_PUPPI_cff")
process.load("ggAnalysis.ggNtuplizer.ggMETFilters_cff")
process.ggNtuplizer.dumpSoftDrop = cms.bool(True)
process.ggNtuplizer.jecAK8PayloadNames = cms.vstring(jecLevels)
process.ggNtuplizer.runHFElectrons = cms.bool(True)
process.ggNtuplizer.isAOD = cms.bool(False)
process.ggNtuplizer.doGenParticles = cms.bool(True)
process.ggNtuplizer.dumpSubJets = cms.bool(True)
process.ggNtuplizer.dumpJets = cms.bool(True)
process.ggNtuplizer.dumpTaus = cms.bool(False)
process.ggNtuplizer.patTriggerResults = cms.InputTag("TriggerResults", "",
                                                     "PAT")
Beispiel #36
0
if runOnData:
    process.patJetCorrFactorsReapplyJEC.levels.append("L2L3Residual")

from PhysicsTools.PatAlgos.producersLayer1.jetUpdater_cff import updatedPatJets
process.patJetsReapplyJEC = updatedPatJets.clone(
    jetSource = cms.InputTag("slimmedJets"),
    jetCorrFactorsSource = cms.VInputTag(cms.InputTag("patJetCorrFactorsReapplyJEC"))
    )

#PFMET
from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD

# If you only want to re-correct and get the proper uncertainties
runMetCorAndUncFromMiniAOD(process,
                           isData=runOnData,
                           fixEE2017 = True,
                           postfix = "ModifiedMET"
                           )

#PuppiMET
from PhysicsTools.PatAlgos.slimming.puppiForMET_cff import makePuppiesFromMiniAOD
makePuppiesFromMiniAOD( process, True );

# If you only want to re-cluster and get the proper uncertainties
runMetCorAndUncFromMiniAOD(process,
                           isData=runOnData,
                           metType="Puppi",
                           pfCandColl=cms.InputTag("puppiForMET"),
                           recoMetFromPFCs=True,
                           jetFlavor="AK4PFPuppi",
                           postfix="Puppi"
Beispiel #37
0
    #     setattr(process, UnpackerName, UnpackerModule)   #equiv to process.<UnpackerName> = <UnpackerModule>
    #     process.METSequence += UnpackerModule

    #     MVAMETName = "patMETMVA%i" % index
    #     MVAModule = process.MVAMET.clone( srcLeptons = cms.VInputTag (cms.InputTag(UnpackerName) ) )
    #     setattr(process, MVAMETName, MVAModule)
    #     process.METSequence += MVAModule

    #     MVAPairMET.append(cms.InputTag(MVAMETName, "MVAMET"))

else:
    print "Using event pfMET (same MET for all pairs)"

    from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
    runMetCorAndUncFromMiniAOD(
        process,
        isData=(not IsMC),
    )
    # patch to get a standalone MET significance collection
    process.METSignificance = cms.EDProducer("ExtractMETSignificance",
                                             srcMET=cms.InputTag(
                                                 "slimmedMETs", "", "TEST"))
    process.METSequence += process.fullPatMetSequence
    process.METSequence += process.METSignificance

# ## always compute met significance
# process.load("RecoMET.METProducers.METSignificance_cfi")
# process.load("RecoMET.METProducers.METSignificanceParams_cfi")
# process.METSequence += cms.Sequence(process.METSignificance)

## ----------------------------------------------------------------------
## Z-recoil correction
Beispiel #38
0
def nanoAOD_recalibrateMETs(process,isData):
    # add DeepMETs
    nanoAOD_DeepMET_switch = cms.PSet(
        ResponseTune_Graph = cms.untracked.string('RecoMET/METPUSubtraction/data/models/deepmet/deepmet_resp_v1_2018/model.graphdef')
    )
    for modifier in run2_miniAOD_80XLegacy, run2_nanoAOD_94X2016:
        modifier.toModify(nanoAOD_DeepMET_switch, ResponseTune_Graph="RecoMET/METPUSubtraction/data/models/deepmet/deepmet_resp_v1_2016/model.graphdef")

    print("add DeepMET Producers")
    process.load('RecoMET.METPUSubtraction.deepMETProducer_cfi')
    process.deepMETsResolutionTune = process.deepMETProducer.clone()
    process.deepMETsResponseTune = process.deepMETProducer.clone()
    process.deepMETsResponseTune.graph_path = nanoAOD_DeepMET_switch.ResponseTune_Graph.value()

    runMetCorAndUncFromMiniAOD(process,isData=isData)
    process.nanoSequenceCommon.insert(2,cms.Sequence(process.fullPatMetSequence))


    from PhysicsTools.PatAlgos.slimming.puppiForMET_cff import makePuppiesFromMiniAOD
    makePuppiesFromMiniAOD(process,True)
    process.puppiNoLep.useExistingWeights = True
    process.puppi.useExistingWeights = True
    run2_nanoAOD_106Xv1.toModify(process.puppiNoLep, useExistingWeights = False)
    run2_nanoAOD_106Xv1.toModify(process.puppi, useExistingWeights = False)
    print("will make Puppies on top of MINIAOD")

#    makePuppiesFromMiniAOD(process,True) # call this before in the global customizer otherwise it would reset photon IDs in VID
    nanoAOD_PuppiV15_switch = cms.PSet(
            recoMetFromPFCs = cms.untracked.bool(False),
            reclusterJets = cms.untracked.bool(False),
            )
    run2_nanoAOD_106Xv1.toModify(nanoAOD_PuppiV15_switch,recoMetFromPFCs=True,reclusterJets=True)
    if nanoAOD_PuppiV15_switch.reclusterJets:
        from RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJets
        from PhysicsTools.PatAlgos.tools.helpers import getPatAlgosToolsTask, addToProcessAndTask
        task = getPatAlgosToolsTask(process)
        addToProcessAndTask('ak4PuppiJets', ak4PFJets.clone (src = 'puppi', doAreaFastjet = True, jetPtMin = 10.), process, task)
        from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection
        addJetCollection(process,
            labelName = 'Puppi',
            jetSource = cms.InputTag('ak4PuppiJets'),
            algo = 'AK', rParam=0.4,
            genJetCollection=cms.InputTag('slimmedGenJets'),
            jetCorrections = ('AK4PFPuppi', ['L1FastJet', 'L2Relative', 'L3Absolute','L2L3Residual'], 'None'),
            pfCandidates = cms.InputTag('packedPFCandidates'),
            pvSource = cms.InputTag('offlineSlimmedPrimaryVertices'),
            svSource = cms.InputTag('slimmedSecondaryVertices'),
            muSource =cms.InputTag( 'slimmedMuons'),
            elSource = cms.InputTag('slimmedElectrons'),
            genParticles= cms.InputTag('prunedGenParticles'),
            getJetMCFlavour= False
        )

        process.patJetsPuppi.addGenPartonMatch = cms.bool(False)
        process.patJetsPuppi.addGenJetMatch = cms.bool(False)

        print("nanoAOD_PuppiV15_switch.reclusterJets is true")

    runMetCorAndUncFromMiniAOD(process,isData=isData,metType="Puppi",postfix="Puppi",jetFlavor="AK4PFPuppi", recoMetFromPFCs=bool(nanoAOD_PuppiV15_switch.recoMetFromPFCs), reclusterJets=bool(nanoAOD_PuppiV15_switch.reclusterJets))
    process.nanoSequenceCommon.insert(2,cms.Sequence(process.puppiMETSequence+process.fullPatMetSequencePuppi))

    return process
Beispiel #39
0
### Removing the HF from the MET computation as from 7 Aug 2015 recommendations
### ---------------------------------------------------------------------------
if options.useNoHFMET:
  process.noHFCands = cms.EDFilter("CandPtrSelector",
      src=cms.InputTag("packedPFCandidates"),
      cut=cms.string("abs(pdgId)!=1 && abs(pdgId)!=2 && abs(eta)<3.0")
      )

  #jets are rebuilt from those candidates by the tools, no need to do anything else
### =================================================================================

from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD

#For a full met computation, remove the pfCandColl input
runMetCorAndUncFromMiniAOD(process,
    isData=("Data" in options.DataProcessing),
    )

if options.useNoHFMET:
  runMetCorAndUncFromMiniAOD(process,
      isData=("Data" in options.DataProcessing),
      pfCandColl=cms.InputTag("noHFCands"),
      recoMetFromPFCs=True,
      reclusterJets=True, 
      postfix="NoHF"
      )
  jLabelNoHF = 'patJetsNoHF'

### -------------------------------------------------------------------
### the lines below remove the L2L3 residual corrections when processing data
### -------------------------------------------------------------------
Beispiel #40
0
egmCorrectionSequence = cms.Sequence(
    process.selectedElectrons +
    process.smearedElectrons +
    process.smearedPhotons
)

### Vanilla MET
# this is the most basic MET one can find
# even if we override with various types of MET later on, create this so we have a consistent calo MET
# https://twiki.cern.ch/twiki/bin/view/CMS/MissingETUncertaintyPrescription

from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD

runMetCorAndUncFromMiniAOD(
    process,
    isData = options.isData,
) 
metSequence = cms.Sequence(
    process.fullPatMetSequence
)

### PUPPI
from PhysicsTools.PatAlgos.slimming.puppiForMET_cff import makePuppiesFromMiniAOD
## Creates process.puppiMETSequence which includes 'puppi' and 'puppiForMET' (= EDProducer('PuppiPhoton'))
## By default, does not use specific photon ID for PuppiPhoton (which was the case in 80X)
makePuppiesFromMiniAOD(process, createScheduledSequence = True)
## Just renaming
puppiSequence = process.puppiMETSequence

process.puppiNoLep.useExistingWeights = False
process.puppi.useExistingWeights = False
        )

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




process.cleanedMu = cms.EDProducer("PATMuonCleanerBySegments",
   src = cms.InputTag("slimmedMuons"),
   preselection = cms.string("track.isNonnull"),
   passthrough = cms.string("isGlobalMuon && numberOfMatches >= 2"),
   fractionOfSharedSegments = cms.double(0.499))

from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
runMetCorAndUncFromMiniAOD(process,
           isData=False,

           )

process.load('EgammaAnalysis.ElectronTools.regressionApplication_cff')
from EgammaAnalysis.ElectronTools.regressionWeights_cfi import regressionWeights
process = regressionWeights(process)

process.load('EgammaAnalysis.ElectronTools.calibratedElectronsRun2_cfi')

process.demo = cms.EDAnalyzer('ntuple_maker',

  syscalcinfo = cms.untracked.bool (True), #fill the information from syscalc
  mgreweightinfo = cms.untracked.bool (False),
  vertices = cms.InputTag("offlineSlimmedPrimaryVertices"),
#  muons = cms.InputTag("cleanedMu"),
  lheevent = cms.InputTag("externalLHEProducer"),
Beispiel #42
0
egmCorrectionSequence = cms.Sequence(process.regressionElectrons +
                                     process.regressionPhotons +
                                     process.selectedElectrons +
                                     process.smearedElectrons +
                                     process.smearedPhotons)

### Vanilla MET
# this is the most basic MET one can find
# even if we override with various types of MET later on, create this so we have a consistent calo MET
# https://twiki.cern.ch/twiki/bin/view/CMS/MissingETUncertaintyPrescription

from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD

runMetCorAndUncFromMiniAOD(
    process,
    isData=options.isData,
)
metSequence = cms.Sequence(process.fullPatMetSequence)

### PUPPI
# TODO find PUPPI recipes, the following doesn't look right:
# https://twiki.cern.ch/twiki/bin/viewauth/CMS/PUPPI
# From PUPPI MET recipe in
# https://twiki.cern.ch/twiki/bin/view/CMS/MissingETUncertaintyPrescription

# 80X does not contain the latest & greatest PuppiPhoton; need to rerun for all config
from PhysicsTools.PatAlgos.slimming.puppiForMET_cff import makePuppiesFromMiniAOD
# Creates process.puppiMETSequence which includes 'puppi' and 'puppiForMET' (= EDProducer('PuppiPhoton'))
# *UGLY* also runs switchOnVIDPhotonIdProducer and sets up photon id Spring16_V2p2 internally
# which loads photonIDValueMapProducer and egmPhotonIDs
makePuppiesFromMiniAOD(process, createScheduledSequence=True)
Beispiel #43
0
from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
if isData:
    jecFile = cms.string('{0}/src/Analysis/ALPHA/data/{1}_DATA/{1}_DATA_Uncertainty_AK4PFchs.txt'.format(os.environ['CMSSW_BASE'], JECstring))
else:
    jecFile = cms.string('{0}/src/Analysis/ALPHA/data/{1}_MC/{1}_MC_Uncertainty_AK4PFchs.txt'.format(os.environ['CMSSW_BASE'], JECstring))
runMetCorAndUncFromMiniAOD(process,
                            #metType="PF",
                            #correctionLevel=["T1","Smear"],
                            #computeUncertainties=True,
                            #produceIntermediateCorrections=False,
                            #addToPatDefaultSequence=False,
                            isData=isData,
                            #onMiniAOD=True,
                            #reapplyJEC=reapplyJEC,
                            #reclusterJets=reclusterJets,
                            #jetSelection=jetSelection,
                            #recoMetFromPFCs=recoMetFromPFCs,
                            #autoJetCleaning=jetCleaning,
                            #manualJetConfig=manualJetConfig,
                            #jetFlavor=jetFlavor,
                            #jetCorLabelUpToL3=jetCorLabelL3,
                            #jetCorLabelL3Res=jetCorLabelRes,
                            #jecUnFile=jecFile,
                            #CHS=CHS,
                            #postfix=postfix,
                           )

if isData:
    filterString = "RECO"
else:
    filterString = "PAT"
process.egmGsfElectronIDs.physicsObjectSrc = electronCollection
process.electronRegressionValueMapProducer.srcMiniAOD = electronCollection
process.electronMVAValueMapProducer.srcMiniAOD = electronCollection

#
# MET corrections and uncertainties
#

if options.recorrectMET:
    # use the standard tool
    from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
    # do not use a postfix here!
    runMetCorAndUncFromMiniAOD(process,
                               isData=options.realData,
                               electronColl=electronCollection.value(),
                               muonColl=muonCollection.value(),
                               tauColl=tauCollection.value(),
                               photonColl=photonCollection.value(),
                               jetCollUnskimmed=jetCollection.value(),
                               recoMetFromPFCs=True)

    # overwrite output collections
    METCollection = cms.InputTag("slimmedMETs", "", process.name_())

    # also add MET corrections due to e/g corrections, such as the slew rate fix in reMiniAOD
    if options.realData:
        from PhysicsTools.PatUtils.tools.corMETFromMuonAndEG import corMETFromMuonAndEG
        corMETFromMuonAndEG(process,
                            pfCandCollection="",
                            electronCollection="slimmedElectronsBeforeGSFix",
                            photonCollection="slimmedPhotonsBeforeGSFix",
                            corElectronCollection=electronCollection.value(),
Beispiel #45
0
    setupAllVIDIdsInModule(process,idmod,setupVIDPhotonSelection)

process.ggNtuplizer.doNoHFMET=cms.bool(doNoHFMet)
tellMETData = False

if doNoHFMet == True:
    process.noHFCands = cms.EDFilter("CandPtrSelector",
                                     src=cms.InputTag("packedPFCandidates"),
                                     cut=cms.string("abs(pdgId)!=1 && abs(pdgId)!=2 && abs(eta)<3.0")
                                     )
    from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD
    #default configuration for miniAOD reprocessing, change the isData flag to run on data
    #for a full met computation, remove the pfCandColl input
    runMetCorAndUncFromMiniAOD(process,
                               isData=tellMETData,
                               pfCandColl=cms.InputTag("noHFCands"),
                               postfix="NoHF"
                               )
    process.patPFMetT1T2CorrNoHF.jetCorrLabelRes = cms.InputTag("L3Absolute")
    process.patPFMetT1T2SmearCorrNoHF.jetCorrLabelRes = cms.InputTag("L3Absolute")
    process.patPFMetT2CorrNoHF.jetCorrLabelRes = cms.InputTag("L3Absolute")
    process.patPFMetT2SmearCorrNoHF.jetCorrLabelRes = cms.InputTag("L3Absolute")
    process.shiftedPatJetEnDownNoHF.jetCorrLabelUpToL3Res = cms.InputTag("ak4PFCHSL1FastL2L3Corrector")
    process.shiftedPatJetEnUpNoHF.jetCorrLabelUpToL3Res = cms.InputTag("ak4PFCHSL1FastL2L3Corrector")

process.p = cms.Path(
    ###process.egmGsfElectronIDSequence
    # process.mvaTrigV050nsCSA14
    # + process.mvaTrigV025nsCSA14
    # + process.mvaNonTrigV050nsCSA14
    # + process.mvaNonTrigV025nsCSA14
Beispiel #46
0
### ---------------------------------------------------------------------------
if not useHFCandidates:
    process.noHFCands = cms.EDFilter(
        "CandPtrSelector",
        src=cms.InputTag("packedPFCandidates"),
        cut=cms.string("abs(pdgId)!=1 && abs(pdgId)!=2 && abs(eta)<3.0"))

#jets are rebuilt from those candidates by the tools, no need to do anything else
### =================================================================================

from PhysicsTools.PatUtils.tools.runMETCorrectionsAndUncertainties import runMetCorAndUncFromMiniAOD

#default configuration for miniAOD reprocessing, change the isData flag to run on data
#for a full met computation, remove the pfCandColl input
runMetCorAndUncFromMiniAOD(
    process,
    isData=runOnData,
)

if not useHFCandidates:
    runMetCorAndUncFromMiniAOD(process,
                               isData=runOnData,
                               pfCandColl=cms.InputTag("noHFCands"),
                               postfix="NoHF")

### -------------------------------------------------------------------
### the lines below remove the L2L3 residual corrections when processing data
### -------------------------------------------------------------------
if not applyResiduals:
    process.patPFMetT1T2Corr.jetCorrLabelRes = cms.InputTag("L3Absolute")
    process.patPFMetT1T2SmearCorr.jetCorrLabelRes = cms.InputTag("L3Absolute")
    process.patPFMetT2Corr.jetCorrLabelRes = cms.InputTag("L3Absolute")