Beispiel #1
0
def applySubstructure( process, postfix="" ) :

    task = getPatAlgosToolsTask(process)

    from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection


    from PhysicsTools.PatAlgos.producersLayer1.jetProducer_cfi import _patJets as patJetsDefault


    # Configure the RECO jets
    from RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJetsPuppi
    from RecoJets.JetProducers.ak8PFJets_cfi import ak8PFJetsPuppi, ak8PFJetsPuppiSoftDrop, ak8PFJetsPuppiConstituents, ak8PFJetsCHSConstituents
    from RecoJets.JetProducers.ak8GenJets_cfi import ak8GenJets, ak8GenJetsSoftDrop, ak8GenJetsConstituents
    addToProcessAndTask('ak4PFJetsPuppi'+postfix,ak4PFJetsPuppi.clone(), process, task)
    addToProcessAndTask('ak8PFJetsPuppi'+postfix,ak8PFJetsPuppi.clone(), process, task)
    addToProcessAndTask('ak8PFJetsPuppiConstituents', ak8PFJetsPuppiConstituents.clone(cut = cms.string('pt > 170.0 && abs(rapidity()) < 2.4') ), process, task )
    addToProcessAndTask('ak8PFJetsCHSConstituents', ak8PFJetsCHSConstituents.clone(), process, task )
    addToProcessAndTask('ak8PFJetsPuppiSoftDrop'+postfix, ak8PFJetsPuppiSoftDrop.clone( src = cms.InputTag('ak8PFJetsPuppiConstituents', 'constituents') ), process, task)
    addToProcessAndTask('ak8GenJetsNoNuConstituents'+postfix, ak8GenJetsConstituents.clone(src='ak8GenJetsNoNu'), process, task )
    addToProcessAndTask('ak8GenJetsNoNuSoftDrop'+postfix,ak8GenJetsSoftDrop.clone(src=cms.InputTag('ak8GenJetsNoNuConstituents'+postfix, 'constituents')),process,task)
    addToProcessAndTask('slimmedGenJetsAK8SoftDropSubJets'+postfix,
                            cms.EDProducer("PATGenJetSlimmer",
                                               src = cms.InputTag("ak8GenJetsNoNuSoftDrop"+postfix, "SubJets"),
                                               packedGenParticles = cms.InputTag("packedGenParticles"),
                                               cut = cms.string(""),
                                               cutLoose = cms.string(""),
                                               nLoose = cms.uint32(0),
                                               clearDaughters = cms.bool(False), #False means rekeying
                                               dropSpecific = cms.bool(True),  # Save space
                                               ), process, task )
    
    
    #add AK8 CHS
    addJetCollection(process, postfix=postfix, labelName = 'AK8',
                     jetSource = cms.InputTag('ak8PFJetsCHS'+postfix),
                     algo= 'AK', rParam = 0.8,
                     btagDiscriminators = ['None'],
                     jetCorrections = ('AK8PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
                     genJetCollection = cms.InputTag('slimmedGenJetsAK8')
                     )
    getattr(process,"patJetsAK8"+postfix).userData.userFloats.src = [] # start with empty list of user floats
    getattr(process,"selectedPatJetsAK8").cut = cms.string("pt > 170")


    ## add AK8 groomed masses with CHS
    from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSPruned, ak8PFJetsCHSSoftDrop
    addToProcessAndTask('ak8PFJetsCHSPruned'+postfix, ak8PFJetsCHSPruned.clone(), process, task)
    addToProcessAndTask('ak8PFJetsCHSSoftDrop'+postfix, ak8PFJetsCHSSoftDrop.clone(), process, task)
    from RecoJets.JetProducers.ak8PFJetsCHS_groomingValueMaps_cfi import ak8PFJetsCHSPrunedMass, ak8PFJetsCHSTrimmedMass, ak8PFJetsCHSFilteredMass, ak8PFJetsCHSSoftDropMass
    addToProcessAndTask('ak8PFJetsCHSPrunedMass'+postfix, ak8PFJetsCHSPrunedMass.clone(), process, task)
    addToProcessAndTask('ak8PFJetsCHSTrimmedMass'+postfix, ak8PFJetsCHSTrimmedMass.clone(), process, task)
    addToProcessAndTask('ak8PFJetsCHSFilteredMass'+postfix, ak8PFJetsCHSFilteredMass.clone(), process, task)
    addToProcessAndTask('ak8PFJetsCHSSoftDropMass'+postfix, ak8PFJetsCHSSoftDropMass.clone(), process, task)

    getattr(process,"patJetsAK8").userData.userFloats.src += ['ak8PFJetsCHSPrunedMass'+postfix,'ak8PFJetsCHSSoftDropMass'+postfix]  
    getattr(process,"patJetsAK8").addTagInfos = cms.bool(False)

    # add Njetiness for CHS
    process.load('RecoJets.JetProducers.nJettinessAdder_cfi')
    task.add(process.Njettiness)
    addToProcessAndTask('NjettinessAK8'+postfix, process.Njettiness.clone(), process, task)
    getattr(process,"NjettinessAK8").src = cms.InputTag("ak8PFJetsCHS"+postfix)
    getattr(process,"NjettinessAK8").cone = cms.double(0.8)
    getattr(process,"patJetsAK8").userData.userFloats.src += ['NjettinessAK8'+postfix+':tau1','NjettinessAK8'+postfix+':tau2','NjettinessAK8'+postfix+':tau3','NjettinessAK8'+postfix+':tau4']

    # add Njetiness from CHS
    addToProcessAndTask('NjettinessAK8Subjets'+postfix, process.Njettiness.clone(), process, task)
    getattr(process,"NjettinessAK8Subjets"+postfix).src = cms.InputTag("ak8PFJetsPuppiSoftDrop"+postfix, "SubJets")
    getattr(process,"NjettinessAK8Subjets").cone = cms.double(0.8)
        
    ## PATify CHS soft drop fat jets
    addJetCollection(
        process,
        postfix=postfix,
        labelName = 'AK8PFCHSSoftDrop',
        jetSource = cms.InputTag('ak8PFJetsCHSSoftDrop'+postfix),
        btagDiscriminators = ['None'],
        jetCorrections = ('AK8PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),
        getJetMCFlavour = False # jet flavor disabled
    )





    #add RECO AK8 from PUPPI and RECO AK8 PUPPI with soft drop... will be needed by ungroomed AK8 jets later
    ## PATify puppi soft drop fat jets
    addJetCollection(
        process,
        postfix=postfix,
        labelName = 'AK8PFPuppiSoftDrop' + postfix,
        jetSource = cms.InputTag('ak8PFJetsPuppiSoftDrop'+postfix),
        btagDiscriminators = ['None'],
        genJetCollection = cms.InputTag('slimmedGenJetsAK8'), 
        jetCorrections = ('AK8PFPuppi', ['L2Relative', 'L3Absolute'], 'None'),
        getJetMCFlavour = False # jet flavor disabled
    )
    ## PATify soft drop subjets
    addJetCollection(
        process,
        postfix=postfix,
        labelName = 'AK8PFPuppiSoftDropSubjets',
        jetSource = cms.InputTag('ak8PFJetsPuppiSoftDrop'+postfix,'SubJets'),
        algo = 'ak',  # needed for subjet flavor clustering
        rParam = 0.8, # needed for subjet flavor clustering
        btagDiscriminators = ['pfDeepCSVJetTags:probb', 'pfDeepCSVJetTags:probbb', 'pfCombinedInclusiveSecondaryVertexV2BJetTags','pfCombinedMVAV2BJetTags'],
        jetCorrections = ('AK4PFPuppi', ['L2Relative', 'L3Absolute'], 'None'),
        explicitJTA = True,  # needed for subjet b tagging
        svClustering = True, # needed for subjet b tagging
        genJetCollection = cms.InputTag('slimmedGenJetsAK8SoftDropSubJets'), 
        fatJets=cms.InputTag('ak8PFJetsPuppi'),             # needed for subjet flavor clustering
        groomedFatJets=cms.InputTag('ak8PFJetsPuppiSoftDrop') # needed for subjet flavor clustering
    )


    # add groomed ECFs and N-subjettiness to soft dropped pat::Jets for fat jets and subjets
    process.load('RecoJets.JetProducers.ECF_cff')
    addToProcessAndTask('nb1AK8PuppiSoftDrop'+postfix, process.ecfNbeta1.clone(src = cms.InputTag("ak8PFJetsPuppiSoftDrop"+postfix), cuts = cms.vstring('', '', 'pt > 250')), process, task)
    addToProcessAndTask('nb2AK8PuppiSoftDrop'+postfix, process.ecfNbeta2.clone(src = cms.InputTag("ak8PFJetsPuppiSoftDrop"+postfix), cuts = cms.vstring('', '', 'pt > 250')), process, task)

    #too slow now ==> disable
    from Configuration.Eras.Modifier_pp_on_AA_2018_cff import pp_on_AA_2018
    from Configuration.Eras.Modifier_pp_on_XeXe_2017_cff import pp_on_XeXe_2017
    from Configuration.Eras.Modifier_phase2_common_cff import phase2_common
    for e in [pp_on_XeXe_2017, pp_on_AA_2018, phase2_common]:
        e.toModify(getattr(process,'nb1AK8PuppiSoftDrop'+postfix), cuts = ['pt > 999999', 'pt > 999999', 'pt > 999999'] )
        e.toModify(getattr(process,'nb2AK8PuppiSoftDrop'+postfix), cuts = ['pt > 999999', 'pt > 999999', 'pt > 999999'] )


    getattr(process,"patJetsAK8PFPuppiSoftDrop").userData.userFloats.src += ['nb1AK8PuppiSoftDrop'+postfix+':ecfN2','nb1AK8PuppiSoftDrop'+postfix+':ecfN3']
    getattr(process,"patJetsAK8PFPuppiSoftDrop").userData.userFloats.src += ['nb2AK8PuppiSoftDrop'+postfix+':ecfN2','nb2AK8PuppiSoftDrop'+postfix+':ecfN3']
    addToProcessAndTask('nb1AK8PuppiSoftDropSubjets'+postfix, process.ecfNbeta1.clone(src = cms.InputTag("ak8PFJetsPuppiSoftDrop"+postfix, "SubJets")), process, task)
    addToProcessAndTask('nb2AK8PuppiSoftDropSubjets'+postfix, process.ecfNbeta2.clone(src = cms.InputTag("ak8PFJetsPuppiSoftDrop"+postfix, "SubJets")), process, task)
    getattr(process,"patJetsAK8PFPuppiSoftDropSubjets"+postfix).userData.userFloats.src += ['nb1AK8PuppiSoftDropSubjets'+postfix+':ecfN2','nb1AK8PuppiSoftDropSubjets'+postfix+':ecfN3']
    getattr(process,"patJetsAK8PFPuppiSoftDropSubjets"+postfix).userData.userFloats.src += ['nb2AK8PuppiSoftDropSubjets'+postfix+':ecfN2','nb2AK8PuppiSoftDropSubjets'+postfix+':ecfN3']
    getattr(process,"patJetsAK8PFPuppiSoftDropSubjets"+postfix).userData.userFloats.src += ['NjettinessAK8Subjets'+postfix+':tau1','NjettinessAK8Subjets'+postfix+':tau2','NjettinessAK8Subjets'+postfix+':tau3','NjettinessAK8Subjets'+postfix+':tau4']

    for e in [pp_on_XeXe_2017, pp_on_AA_2018, phase2_common]:
        e.toModify(getattr(process,'nb1AK8PuppiSoftDropSubjets'+postfix), cuts = ['pt > 999999', 'pt > 999999', 'pt > 999999'] )
        e.toModify(getattr(process,'nb2AK8PuppiSoftDropSubjets'+postfix), cuts = ['pt > 999999', 'pt > 999999', 'pt > 999999'] )

    # rekey the groomed ECF value maps to the ungroomed reco jets, which will then be picked
    # up by PAT in the user floats. 
    addToProcessAndTask("ak8PFJetsPuppiSoftDropValueMap"+postfix, 
                        cms.EDProducer("RecoJetToPatJetDeltaRValueMapProducer",
                                       src = cms.InputTag("ak8PFJetsPuppi"+postfix),
                                       matched = cms.InputTag("patJetsAK8PFPuppiSoftDrop"+postfix),
                                       distMax = cms.double(0.8),
                                       values = cms.vstring([
                    'userFloat("nb1AK8PuppiSoftDrop'+postfix+':ecfN2")',
                    'userFloat("nb1AK8PuppiSoftDrop'+postfix+':ecfN3")',
                    'userFloat("nb2AK8PuppiSoftDrop'+postfix+':ecfN2")',
                    'userFloat("nb2AK8PuppiSoftDrop'+postfix+':ecfN3")',
                    ]),
                                       valueLabels = cms.vstring( [
                    'nb1AK8PuppiSoftDropN2',
                    'nb1AK8PuppiSoftDropN3',
                    'nb2AK8PuppiSoftDropN2',
                    'nb2AK8PuppiSoftDropN3',
                    ]) ),
                    process, task)

        
    # Patify AK8 PF PUPPI
    addJetCollection(process, postfix=postfix, labelName = 'AK8Puppi',
                     jetSource = cms.InputTag('ak8PFJetsPuppi'+postfix),
                     algo= 'AK', rParam = 0.8,
                     jetCorrections = ('AK8PFPuppi', cms.vstring(['L2Relative', 'L3Absolute']), 'None'),
                     btagDiscriminators = ([
                         'pfCombinedSecondaryVertexV2BJetTags',
                         'pfCombinedInclusiveSecondaryVertexV2BJetTags',
                         'pfCombinedMVAV2BJetTags',
                         'pfDeepCSVJetTags:probb',
                         'pfDeepCSVJetTags:probc',
                         'pfDeepCSVJetTags:probudsg',
                         'pfDeepCSVJetTags:probbb',
                         'pfBoostedDoubleSecondaryVertexAK8BJetTags']),
                     genJetCollection = cms.InputTag('slimmedGenJetsAK8')
                     )
    getattr(process,"patJetsAK8Puppi"+postfix).userData.userFloats.src = [] # start with empty list of user floats
    getattr(process,"selectedPatJetsAK8Puppi"+postfix).cut = cms.string("pt > 100")
    getattr(process,"selectedPatJetsAK8Puppi"+postfix).cutLoose = cms.string("pt > 30")
    getattr(process,"selectedPatJetsAK8Puppi"+postfix).nLoose = cms.uint32(3)

    from RecoJets.JetAssociationProducers.j2tParametersVX_cfi import j2tParametersVX
    addToProcessAndTask('ak8PFJetsPuppiTracksAssociatorAtVertex'+postfix, cms.EDProducer("JetTracksAssociatorAtVertex",
                                      j2tParametersVX.clone( coneSize = cms.double(0.8) ),
                                      jets = cms.InputTag("ak8PFJetsPuppi") ),
                        process, task)
    addToProcessAndTask('patJetAK8PuppiCharge'+postfix, cms.EDProducer("JetChargeProducer",
                                     src = cms.InputTag("ak8PFJetsPuppiTracksAssociatorAtVertex"),
                                     var = cms.string('Pt'),
                                     exp = cms.double(1.0) ), 
                        process, task)

    ## now add AK8 groomed masses and ECF
    from RecoJets.JetProducers.ak8PFJetsPuppi_groomingValueMaps_cfi import ak8PFJetsPuppiSoftDropMass
    addToProcessAndTask('ak8PFJetsPuppiSoftDropMass'+postfix, ak8PFJetsPuppiSoftDropMass.clone(), process, task)
    getattr(process,"patJetsAK8Puppi"+postfix).userData.userFloats.src += ['ak8PFJetsPuppiSoftDropMass'+postfix]
    getattr(process,"patJetsAK8Puppi"+postfix).addTagInfos = cms.bool(False)
    getattr(process,"patJetsAK8Puppi"+postfix).userData.userFloats.src += [
        cms.InputTag('ak8PFJetsPuppiSoftDropValueMap'+postfix,'nb1AK8PuppiSoftDropN2'),
        cms.InputTag('ak8PFJetsPuppiSoftDropValueMap'+postfix,'nb1AK8PuppiSoftDropN3'),
        cms.InputTag('ak8PFJetsPuppiSoftDropValueMap'+postfix,'nb2AK8PuppiSoftDropN2'),
        cms.InputTag('ak8PFJetsPuppiSoftDropValueMap'+postfix,'nb2AK8PuppiSoftDropN3'),
        ]


    # add PUPPI Njetiness
    addToProcessAndTask('NjettinessAK8Puppi'+postfix, process.Njettiness.clone(), process, task)
    getattr(process,"NjettinessAK8Puppi"+postfix).src = cms.InputTag("ak8PFJetsPuppi"+postfix)
    getattr(process,"NjettinessAK8Puppi").cone = cms.double(0.8)
    getattr(process,"patJetsAK8Puppi").userData.userFloats.src += ['NjettinessAK8Puppi'+postfix+':tau1','NjettinessAK8Puppi'+postfix+':tau2','NjettinessAK8Puppi'+postfix+':tau3','NjettinessAK8Puppi'+postfix+':tau4']

    # Now combine the CHS and PUPPI information into the PUPPI jets via delta R value maps
    addToProcessAndTask("ak8PFJetsCHSValueMap"+postfix, cms.EDProducer("RecoJetToPatJetDeltaRValueMapProducer",
                                            src = cms.InputTag("ak8PFJetsPuppi"+postfix),
                                            matched = cms.InputTag("patJetsAK8"+postfix),
                                            distMax = cms.double(0.8),
                                            values = cms.vstring([
                                                'userFloat("ak8PFJetsCHSPrunedMass"'+postfix+')',
                                                'userFloat("ak8PFJetsCHSSoftDropMass"'+postfix+')',
                                                'userFloat("NjettinessAK8'+postfix+':tau1")',
                                                'userFloat("NjettinessAK8'+postfix+':tau2")',
                                                'userFloat("NjettinessAK8'+postfix+':tau3")',
                                                'userFloat("NjettinessAK8'+postfix+':tau4")',
                                                'pt','eta','phi','mass', 'jetArea', 'jecFactor(0)'
                                            ]),
                                            valueLabels = cms.vstring( [
                                                'ak8PFJetsCHSPrunedMass',
                                                'ak8PFJetsCHSSoftDropMass',
                                                'NjettinessAK8CHSTau1',
                                                'NjettinessAK8CHSTau2',
                                                'NjettinessAK8CHSTau3',
                                                'NjettinessAK8CHSTau4',
                                                'pt','eta','phi','mass', 'jetArea', 'rawFactor'
                                            ]) ),
                        process, task)


    # Now set up the user floats
    getattr(process,"patJetsAK8Puppi"+postfix).userData.userFloats.src += [
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'ak8PFJetsCHSPrunedMass'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'ak8PFJetsCHSSoftDropMass'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'NjettinessAK8CHSTau1'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'NjettinessAK8CHSTau2'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'NjettinessAK8CHSTau3'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'NjettinessAK8CHSTau4'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'pt'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'eta'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'phi'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'mass'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'jetArea'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'rawFactor'),
                                                   ]

    

    
    addToProcessAndTask("slimmedJetsAK8PFPuppiSoftDropSubjets"+postfix,
                        cms.EDProducer("PATJetSlimmer",
                             src = cms.InputTag("selectedPatJetsAK8PFPuppiSoftDropSubjets"),
                             packedPFCandidates = cms.InputTag("packedPFCandidates"),
                             dropJetVars = cms.string("1"),
                             dropDaughters = cms.string("0"),
                             rekeyDaughters = cms.string("1"),
                             dropTrackRefs = cms.string("1"),
                             dropSpecific = cms.string("1"),
                             dropTagInfos = cms.string("1"),
                             modifyJets = cms.bool(True),
                             mixedDaughters = cms.bool(False),
                             modifierConfig = cms.PSet( modifications = cms.VPSet() )
                                       ),
                        process, task)

    
    ## Establish references between PATified fat jets and subjets using the BoostedJetMerger
    addToProcessAndTask("slimmedJetsAK8PFPuppiSoftDropPacked"+postfix,
                        cms.EDProducer("BoostedJetMerger",
                               jetSrc=cms.InputTag("selectedPatJetsAK8PFPuppiSoftDrop"),
                               subjetSrc=cms.InputTag("slimmedJetsAK8PFPuppiSoftDropSubjets")
                                       ),
                        process, task )

    
    addToProcessAndTask("packedPatJetsAK8"+postfix, cms.EDProducer("JetSubstructurePacker",
                                           jetSrc = cms.InputTag("selectedPatJetsAK8Puppi"+postfix),
                                           distMax = cms.double(0.8),
                                           algoTags = cms.VInputTag(
                                               cms.InputTag("slimmedJetsAK8PFPuppiSoftDropPacked"+postfix)
                                           ),
                                           algoLabels = cms.vstring(
                                               'SoftDropPuppi'
                                           ),
                                          fixDaughters = cms.bool(True),
                                          packedPFCandidates = cms.InputTag("packedPFCandidates"+postfix),
                                                                   ),
                        process, task)

    # switch off daughter re-keying since it's done in the JetSubstructurePacker (and can't be done afterwards)
    process.slimmedJetsAK8.rekeyDaughters = "0"
    # Reconfigure the slimmedAK8 jet information to keep 
    process.slimmedJetsAK8.dropDaughters = cms.string("pt < 170")
    process.slimmedJetsAK8.dropSpecific = cms.string("pt < 170")
    process.slimmedJetsAK8.dropTagInfos = cms.string("pt < 170")
Beispiel #2
0
def applySubstructure(process):

    from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection

    from PhysicsTools.PatAlgos.producersLayer1.jetProducer_cfi import _patJets as patJetsDefault

    #add AK8
    addJetCollection(
        process,
        labelName='AK8',
        jetSource=cms.InputTag('ak8PFJetsCHS'),
        algo='AK',
        rParam=0.8,
        jetCorrections=('AK8PFchs',
                        cms.vstring(['L1FastJet', 'L2Relative',
                                     'L3Absolute']), 'None'),
        btagDiscriminators=(
            [x.getModuleLabel() for x in patJetsDefault.discriminatorSources] +
            ['pfBoostedDoubleSecondaryVertexAK8BJetTags']),
        genJetCollection=cms.InputTag('slimmedGenJetsAK8'))
    process.patJetsAK8.userData.userFloats.src = [
    ]  # start with empty list of user floats
    process.selectedPatJetsAK8.cut = cms.string("pt > 170")

    process.load('RecoJets.JetProducers.ak8PFJetsPuppi_cfi')
    process.ak8PFJetsPuppi.doAreaFastjet = True  # even for standard ak8PFJets this is overwritten in RecoJets/Configuration/python/RecoPFJets_cff

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

    ## AK8 groomed masses
    from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSPruned, ak8PFJetsCHSSoftDrop, ak8PFJetsPuppiSoftDrop
    process.ak8PFJetsCHSPruned = ak8PFJetsCHSPruned.clone()
    process.ak8PFJetsCHSSoftDrop = ak8PFJetsCHSSoftDrop.clone()
    process.ak8PFJetsPuppiSoftDrop = ak8PFJetsPuppiSoftDrop.clone()
    process.load("RecoJets.JetProducers.ak8PFJetsCHS_groomingValueMaps_cfi")
    process.patJetsAK8.userData.userFloats.src += [
        'ak8PFJetsCHSPrunedMass', 'ak8PFJetsCHSSoftDropMass'
    ]
    process.patJetsAK8.addTagInfos = cms.bool(False)

    # add Njetiness
    process.load('RecoJets.JetProducers.nJettinessAdder_cfi')
    process.NjettinessAK8 = process.Njettiness.clone()
    process.NjettinessAK8.src = cms.InputTag("ak8PFJetsCHS")
    process.NjettinessAK8.cone = cms.double(0.8)
    process.patJetsAK8.userData.userFloats.src += [
        'NjettinessAK8:tau1', 'NjettinessAK8:tau2', 'NjettinessAK8:tau3'
    ]

    #add AK8 from PUPPI

    process.load('RecoJets.JetProducers.ak8PFJetsPuppi_cfi')
    process.ak8PFJetsPuppi.doAreaFastjet = True  # even for standard ak8PFJets this is overwritten in RecoJets/Configuration/python/RecoPFJets_cff

    addJetCollection(
        process,
        labelName='AK8Puppi',
        jetSource=cms.InputTag('ak8PFJetsPuppi'),
        algo='AK',
        rParam=0.8,
        jetCorrections=('AK8PFPuppi',
                        cms.vstring(['L1FastJet', 'L2Relative',
                                     'L3Absolute']), 'None'),
        genJetCollection=cms.InputTag('slimmedGenJetsAK8'))
    process.patJetsAK8Puppi.userData.userFloats.src = [
    ]  # start with empty list of user floats
    process.selectedPatJetsAK8Puppi.cut = cms.string("pt > 170")

    from RecoJets.JetAssociationProducers.j2tParametersVX_cfi import j2tParametersVX
    process.ak8PFJetsPuppiTracksAssociatorAtVertex = cms.EDProducer(
        "JetTracksAssociatorAtVertex",
        j2tParametersVX,
        jets=cms.InputTag("ak8PFJetsPuppi"))
    process.patJetAK8PuppiCharge = cms.EDProducer(
        "JetChargeProducer",
        src=cms.InputTag("ak8PFJetsPuppiTracksAssociatorAtVertex"),
        var=cms.string('Pt'),
        exp=cms.double(1.0))

    ## AK8 groomed masses
    from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsPuppiSoftDrop
    process.ak8PFJetsPuppiSoftDrop = ak8PFJetsPuppiSoftDrop.clone()
    process.load("RecoJets.JetProducers.ak8PFJetsPuppi_groomingValueMaps_cfi")
    process.patJetsAK8Puppi.userData.userFloats.src += [
        'ak8PFJetsPuppiSoftDropMass'
    ]
    process.patJetsAK8Puppi.addTagInfos = cms.bool(False)

    # add Njetiness
    process.NjettinessAK8Puppi = process.Njettiness.clone()
    process.NjettinessAK8Puppi.src = cms.InputTag("ak8PFJetsPuppi")
    process.NjettinessAK8Puppi.cone = cms.double(0.8)
    process.patJetsAK8Puppi.userData.userFloats.src += [
        'NjettinessAK8Puppi:tau1', 'NjettinessAK8Puppi:tau2',
        'NjettinessAK8Puppi:tau3'
    ]

    process.ak8PFJetsPuppiValueMap = cms.EDProducer(
        "RecoJetToPatJetDeltaRValueMapProducer",
        src=cms.InputTag("ak8PFJetsCHS"),
        matched=cms.InputTag("patJetsAK8Puppi"),
        distMax=cms.double(0.8),
        values=cms.vstring([
            'userFloat("NjettinessAK8Puppi:tau1")',
            'userFloat("NjettinessAK8Puppi:tau2")',
            'userFloat("NjettinessAK8Puppi:tau3")', 'pt', 'eta', 'phi', 'mass'
        ]),
        valueLabels=cms.vstring([
            'NjettinessAK8PuppiTau1', 'NjettinessAK8PuppiTau2',
            'NjettinessAK8PuppiTau3', 'pt', 'eta', 'phi', 'mass'
        ]))
    #process.patJetsAK8.userData.userFloats.src += ['NjettinessAK8:tau1','NjettinessAK8:tau2','NjettinessAK8:tau3']

    process.patJetsAK8.userData.userFloats.src += [
        cms.InputTag('ak8PFJetsPuppiValueMap', 'NjettinessAK8PuppiTau1'),
        cms.InputTag('ak8PFJetsPuppiValueMap', 'NjettinessAK8PuppiTau2'),
        cms.InputTag('ak8PFJetsPuppiValueMap', 'NjettinessAK8PuppiTau3'),
        cms.InputTag('ak8PFJetsPuppiValueMap', 'pt'),
        cms.InputTag('ak8PFJetsPuppiValueMap', 'eta'),
        cms.InputTag('ak8PFJetsPuppiValueMap', 'phi'),
        cms.InputTag('ak8PFJetsPuppiValueMap', 'mass'),
    ]

    ## PATify pruned fat jets
    addJetCollection(
        process,
        labelName='AK8PFCHSSoftDrop',
        jetSource=cms.InputTag('ak8PFJetsCHSSoftDrop'),
        btagDiscriminators=['None'],
        jetCorrections=('AK8PFchs', ['L1FastJet', 'L2Relative',
                                     'L3Absolute'], 'None'),
        getJetMCFlavour=False  # jet flavor disabled
    )

    ## PATify soft drop subjets
    addJetCollection(
        process,
        labelName='AK8PFCHSSoftDropSubjets',
        jetSource=cms.InputTag('ak8PFJetsCHSSoftDrop', 'SubJets'),
        algo='ak',  # needed for subjet flavor clustering
        rParam=0.8,  # needed for subjet flavor clustering
        btagDiscriminators=[
            'pfCombinedSecondaryVertexV2BJetTags',
            'pfCombinedInclusiveSecondaryVertexV2BJetTags'
        ],
        jetCorrections=('AK4PFchs', ['L1FastJet', 'L2Relative',
                                     'L3Absolute'], 'None'),
        explicitJTA=True,  # needed for subjet b tagging
        svClustering=True,  # needed for subjet b tagging
        genJetCollection=cms.InputTag('slimmedGenJets'),
        fatJets=cms.InputTag(
            'ak8PFJetsCHS'),  # needed for subjet flavor clustering
        groomedFatJets=cms.InputTag(
            'ak8PFJetsCHSSoftDrop')  # needed for subjet flavor clustering
    )
    process.selectedPatJetsAK8PFCHSSoftDrop.cut = cms.string("pt > 170")

    process.slimmedJetsAK8PFCHSSoftDropSubjets = cms.EDProducer(
        "PATJetSlimmer",
        src=cms.InputTag("selectedPatJetsAK8PFCHSSoftDropSubjets"),
        packedPFCandidates=cms.InputTag("packedPFCandidates"),
        dropJetVars=cms.string("1"),
        dropDaughters=cms.string("0"),
        rekeyDaughters=cms.string("1"),
        dropTrackRefs=cms.string("1"),
        dropSpecific=cms.string("1"),
        dropTagInfos=cms.string("1"),
        modifyJets=cms.bool(True),
        modifierConfig=cms.PSet(modifications=cms.VPSet()))

    ## Establish references between PATified fat jets and subjets using the BoostedJetMerger
    process.slimmedJetsAK8PFCHSSoftDropPacked = cms.EDProducer(
        "BoostedJetMerger",
        jetSrc=cms.InputTag("selectedPatJetsAK8PFCHSSoftDrop"),
        subjetSrc=cms.InputTag("slimmedJetsAK8PFCHSSoftDropSubjets"))

    ## PATify pruned fat jets
    addJetCollection(
        process,
        labelName='AK8PFPuppiSoftDrop',
        jetSource=cms.InputTag('ak8PFJetsPuppiSoftDrop'),
        btagDiscriminators=['None'],
        jetCorrections=('AK8PFPuppi',
                        ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),
        getJetMCFlavour=False  # jet flavor disabled
    )

    ## PATify soft drop subjets
    addJetCollection(
        process,
        labelName='AK8PFPuppiSoftDropSubjets',
        jetSource=cms.InputTag('ak8PFJetsPuppiSoftDrop', 'SubJets'),
        algo='ak',  # needed for subjet flavor clustering
        rParam=0.8,  # needed for subjet flavor clustering
        btagDiscriminators=[
            'pfCombinedSecondaryVertexV2BJetTags',
            'pfCombinedInclusiveSecondaryVertexV2BJetTags'
        ],
        jetCorrections=('AK4PFPuppi',
                        ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),
        explicitJTA=True,  # needed for subjet b tagging
        svClustering=True,  # needed for subjet b tagging
        genJetCollection=cms.InputTag('slimmedGenJets'),
        fatJets=cms.InputTag(
            'ak8PFJetsPuppi'),  # needed for subjet flavor clustering
        groomedFatJets=cms.InputTag(
            'ak8PFJetsPuppiSoftDrop')  # needed for subjet flavor clustering
    )
    process.selectedPatJetsAK8PFPuppiSoftDrop.cut = cms.string("pt > 170")

    process.slimmedJetsAK8PFPuppiSoftDropSubjets = cms.EDProducer(
        "PATJetSlimmer",
        src=cms.InputTag("selectedPatJetsAK8PFPuppiSoftDropSubjets"),
        packedPFCandidates=cms.InputTag("packedPFCandidates"),
        dropJetVars=cms.string("1"),
        dropDaughters=cms.string("0"),
        rekeyDaughters=cms.string("1"),
        dropTrackRefs=cms.string("1"),
        dropSpecific=cms.string("1"),
        dropTagInfos=cms.string("1"),
        modifyJets=cms.bool(True),
        modifierConfig=cms.PSet(modifications=cms.VPSet()))

    ## Establish references between PATified fat jets and subjets using the BoostedJetMerger
    process.slimmedJetsAK8PFPuppiSoftDropPacked = cms.EDProducer(
        "BoostedJetMerger",
        jetSrc=cms.InputTag("selectedPatJetsAK8PFPuppiSoftDrop"),
        subjetSrc=cms.InputTag("slimmedJetsAK8PFPuppiSoftDropSubjets"))

    process.packedPatJetsAK8 = cms.EDProducer(
        "JetSubstructurePacker",
        jetSrc=cms.InputTag("selectedPatJetsAK8"),
        distMax=cms.double(0.8),
        algoTags=cms.VInputTag(
            # NOTE: For an optimal storage of the AK8 jet daughters, the first subjet collection listed here should be
            #       derived from AK8 jets, i.e., subjets should contain either all or a subset of AK8 constituents.
            #       The PUPPI collection has its own pointers to its own PUPPI constituents.
            cms.InputTag("slimmedJetsAK8PFCHSSoftDropPacked"),
            cms.InputTag("slimmedJetsAK8PFPuppiSoftDropPacked")),
        algoLabels=cms.vstring('SoftDrop', 'SoftDropPuppi'),
        fixDaughters=cms.bool(True),
        packedPFCandidates=cms.InputTag("packedPFCandidates"),
    )

    # switch off daughter re-keying since it's done in the JetSubstructurePacker (and can't be done afterwards)
    process.slimmedJetsAK8.rekeyDaughters = "0"
Beispiel #3
0
def applySubstructure(process, postfix=""):

    task = getPatAlgosToolsTask(process)

    from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection

    from PhysicsTools.PatAlgos.producersLayer1.jetProducer_cfi import _patJets as patJetsDefault

    #add AK8
    addJetCollection(
        process,
        postfix=postfix,
        labelName='AK8',
        jetSource=cms.InputTag('ak8PFJetsCHS' + postfix),
        algo='AK',
        rParam=0.8,
        jetCorrections=('AK8PFchs',
                        cms.vstring(['L1FastJet', 'L2Relative',
                                     'L3Absolute']), 'None'),
        genJetCollection=cms.InputTag('slimmedGenJetsAK8'))
    getattr(process, "patJetsAK8" + postfix).userData.userFloats.src = [
    ]  # start with empty list of user floats
    getattr(process, "selectedPatJetsAK8").cut = cms.string("pt > 170")

    ## AK8 groomed masses
    from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSPruned, ak8PFJetsCHSSoftDrop
    addToProcessAndTask('ak8PFJetsCHSPruned' + postfix,
                        ak8PFJetsCHSPruned.clone(), process, task)
    addToProcessAndTask('ak8PFJetsCHSSoftDrop' + postfix,
                        ak8PFJetsCHSSoftDrop.clone(), process, task)
    from RecoJets.JetProducers.ak8PFJetsCHS_groomingValueMaps_cfi import ak8PFJetsCHSPrunedMass, ak8PFJetsCHSTrimmedMass, ak8PFJetsCHSFilteredMass, ak8PFJetsCHSSoftDropMass
    addToProcessAndTask('ak8PFJetsCHSPrunedMass' + postfix,
                        ak8PFJetsCHSPrunedMass.clone(), process, task)
    addToProcessAndTask('ak8PFJetsCHSTrimmedMass' + postfix,
                        ak8PFJetsCHSTrimmedMass.clone(), process, task)
    addToProcessAndTask('ak8PFJetsCHSFilteredMass' + postfix,
                        ak8PFJetsCHSFilteredMass.clone(), process, task)
    addToProcessAndTask('ak8PFJetsCHSSoftDropMass' + postfix,
                        ak8PFJetsCHSSoftDropMass.clone(), process, task)

    getattr(process, "patJetsAK8").userData.userFloats.src += [
        'ak8PFJetsCHSPrunedMass' + postfix,
        'ak8PFJetsCHSSoftDropMass' + postfix
    ]
    getattr(process, "patJetsAK8").addTagInfos = cms.bool(False)

    # add Njetiness
    process.load('RecoJets.JetProducers.nJettinessAdder_cfi')
    task.add(process.Njettiness)
    addToProcessAndTask('NjettinessAK8' + postfix, process.Njettiness.clone(),
                        process, task)

    getattr(process,
            "NjettinessAK8").src = cms.InputTag("ak8PFJetsCHS" + postfix)
    getattr(process, "NjettinessAK8").cone = cms.double(0.8)
    getattr(process, "patJetsAK8").userData.userFloats.src += [
        'NjettinessAK8' + postfix + ':tau1',
        'NjettinessAK8' + postfix + ':tau2',
        'NjettinessAK8' + postfix + ':tau3'
    ]

    #add AK8 from PUPPI
    from RecoJets.JetProducers.ak8PFJetsPuppi_cfi import ak4PFJetsPuppi, ak8PFJetsPuppi
    addToProcessAndTask('ak4PFJetsPuppi' + postfix, ak4PFJetsPuppi.clone(),
                        process, task)
    addToProcessAndTask('ak8PFJetsPuppi' + postfix, ak8PFJetsPuppi.clone(),
                        process, task)
    from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsPuppiSoftDrop
    addToProcessAndTask('ak8PFJetsPuppiSoftDrop' + postfix,
                        ak8PFJetsPuppiSoftDrop.clone(), process, task)
    getattr(
        process, "ak8PFJetsPuppi"
    ).doAreaFastjet = True  # even for standard ak8PFJets this is overwritten in RecoJets/Configuration/python/RecoPFJets_cff

    addJetCollection(
        process,
        postfix=postfix,
        labelName='AK8Puppi',
        jetSource=cms.InputTag('ak8PFJetsPuppi' + postfix),
        algo='AK',
        rParam=0.8,
        jetCorrections=('AK8PFPuppi', cms.vstring(['L2Relative',
                                                   'L3Absolute']), 'None'),
        btagDiscriminators=(
            [x.getModuleLabel() for x in patJetsDefault.discriminatorSources] +
            ['pfBoostedDoubleSecondaryVertexAK8BJetTags']),
        genJetCollection=cms.InputTag('slimmedGenJetsAK8'))
    getattr(process, "patJetsAK8Puppi" + postfix).userData.userFloats.src = [
    ]  # start with empty list of user floats
    getattr(process,
            "selectedPatJetsAK8Puppi" + postfix).cut = cms.string("pt > 170")

    from RecoJets.JetAssociationProducers.j2tParametersVX_cfi import j2tParametersVX
    addToProcessAndTask(
        'ak8PFJetsPuppiTracksAssociatorAtVertex' + postfix,
        cms.EDProducer("JetTracksAssociatorAtVertex",
                       j2tParametersVX.clone(coneSize=cms.double(0.8)),
                       jets=cms.InputTag("ak8PFJetsPuppi")), process, task)
    addToProcessAndTask(
        'patJetAK8PuppiCharge' + postfix,
        cms.EDProducer(
            "JetChargeProducer",
            src=cms.InputTag("ak8PFJetsPuppiTracksAssociatorAtVertex"),
            var=cms.string('Pt'),
            exp=cms.double(1.0)), process, task)

    ## AK8 groomed masses
    from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsPuppiSoftDrop
    addToProcessAndTask('ak8PFJetsPuppiSoftDrop' + postfix,
                        ak8PFJetsPuppiSoftDrop.clone(), process, task)
    from RecoJets.JetProducers.ak8PFJetsPuppi_groomingValueMaps_cfi import ak8PFJetsPuppiSoftDropMass
    addToProcessAndTask('ak8PFJetsPuppiSoftDropMass' + postfix,
                        ak8PFJetsPuppiSoftDropMass.clone(), process, task)
    getattr(process, "patJetsAK8Puppi" + postfix).userData.userFloats.src += [
        'ak8PFJetsPuppiSoftDropMass' + postfix
    ]
    getattr(process, "patJetsAK8Puppi" + postfix).addTagInfos = cms.bool(False)

    # add Njetiness
    addToProcessAndTask('NjettinessAK8Puppi' + postfix,
                        process.Njettiness.clone(), process, task)
    getattr(process, "NjettinessAK8Puppi" +
            postfix).src = cms.InputTag("ak8PFJetsPuppi" + postfix)
    getattr(process, "NjettinessAK8Puppi").cone = cms.double(0.8)
    getattr(process, "patJetsAK8Puppi").userData.userFloats.src += [
        'NjettinessAK8Puppi' + postfix + ':tau1',
        'NjettinessAK8Puppi' + postfix + ':tau2',
        'NjettinessAK8Puppi' + postfix + ':tau3'
    ]

    addToProcessAndTask(
        "ak8PFJetsCHSValueMap" + postfix,
        cms.EDProducer(
            "RecoJetToPatJetDeltaRValueMapProducer",
            src=cms.InputTag("ak8PFJetsPuppi" + postfix),
            matched=cms.InputTag("patJetsAK8" + postfix),
            distMax=cms.double(0.8),
            values=cms.vstring([
                'userFloat("ak8PFJetsCHSPrunedMass"' + postfix + ')',
                'userFloat("ak8PFJetsCHSSoftDropMass"' + postfix + ')',
                'userFloat("NjettinessAK8' + postfix + ':tau1")',
                'userFloat("NjettinessAK8' + postfix + ':tau2")',
                'userFloat("NjettinessAK8' + postfix + ':tau3")', 'pt', 'eta',
                'phi', 'mass'
            ]),
            valueLabels=cms.vstring([
                'ak8PFJetsCHSPrunedMass', 'ak8PFJetsCHSSoftDropMass',
                'NjettinessAK8CHSTau1', 'NjettinessAK8CHSTau2',
                'NjettinessAK8CHSTau3', 'pt', 'eta', 'phi', 'mass'
            ])), process, task)

    getattr(process, "patJetsAK8Puppi" + postfix).userData.userFloats.src += [
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix,
                     'ak8PFJetsCHSPrunedMass'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix,
                     'ak8PFJetsCHSSoftDropMass'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix, 'NjettinessAK8CHSTau1'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix, 'NjettinessAK8CHSTau2'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix, 'NjettinessAK8CHSTau3'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix, 'pt'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix, 'eta'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix, 'phi'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix, 'mass'),
    ]

    # add Njetiness
    process.load('RecoJets.JetProducers.nJettinessAdder_cfi')
    task.add(process.Njettiness)
    addToProcessAndTask('NjettinessAK8Subjets' + postfix,
                        process.Njettiness.clone(), process, task)
    getattr(process, "NjettinessAK8Subjets" + postfix).src = cms.InputTag(
        "ak8PFJetsPuppiSoftDrop" + postfix, "SubJets")
    getattr(process, "NjettinessAK8Subjets").cone = cms.double(0.8)

    ## PATify CHS soft drop fat jets
    addJetCollection(
        process,
        postfix=postfix,
        labelName='AK8PFCHSSoftDrop',
        jetSource=cms.InputTag('ak8PFJetsCHSSoftDrop' + postfix),
        btagDiscriminators=['None'],
        jetCorrections=('AK8PFchs', ['L1FastJet', 'L2Relative',
                                     'L3Absolute'], 'None'),
        getJetMCFlavour=False  # jet flavor disabled
    )

    ## PATify puppi soft drop fat jets
    addJetCollection(
        process,
        postfix=postfix,
        labelName='AK8PFPuppiSoftDrop',
        jetSource=cms.InputTag('ak8PFJetsPuppiSoftDrop' + postfix),
        btagDiscriminators=['None'],
        jetCorrections=('AK8PFPuppi', ['L2Relative', 'L3Absolute'], 'None'),
        getJetMCFlavour=False  # jet flavor disabled
    )

    ## PATify soft drop subjets
    addJetCollection(
        process,
        postfix=postfix,
        labelName='AK8PFPuppiSoftDropSubjets',
        jetSource=cms.InputTag('ak8PFJetsPuppiSoftDrop' + postfix, 'SubJets'),
        algo='ak',  # needed for subjet flavor clustering
        rParam=0.8,  # needed for subjet flavor clustering
        btagDiscriminators=[
            'pfCombinedSecondaryVertexV2BJetTags',
            'pfCombinedInclusiveSecondaryVertexV2BJetTags',
            'pfCombinedMVAV2BJetTags'
        ],
        jetCorrections=('AK4PFPuppi', ['L2Relative', 'L3Absolute'], 'None'),
        explicitJTA=True,  # needed for subjet b tagging
        svClustering=True,  # needed for subjet b tagging
        genJetCollection=cms.InputTag('slimmedGenJets'),
        fatJets=cms.InputTag(
            'ak8PFJetsPuppi'),  # needed for subjet flavor clustering
        groomedFatJets=cms.InputTag(
            'ak8PFJetsPuppiSoftDrop')  # needed for subjet flavor clustering
    )
    getattr(process, "selectedPatJetsAK8PFPuppiSoftDrop" +
            postfix).cut = cms.string("pt > 170")
    getattr(process, "patJetsAK8PFPuppiSoftDropSubjets" +
            postfix).userData.userFloats.src += [
                'NjettinessAK8Subjets' + postfix + ':tau1',
                'NjettinessAK8Subjets' + postfix + ':tau2',
                'NjettinessAK8Subjets' + postfix + ':tau3'
            ]

    addToProcessAndTask(
        "slimmedJetsAK8PFPuppiSoftDropSubjets" + postfix,
        cms.EDProducer(
            "PATJetSlimmer",
            src=cms.InputTag("selectedPatJetsAK8PFPuppiSoftDropSubjets"),
            packedPFCandidates=cms.InputTag("packedPFCandidates"),
            dropJetVars=cms.string("1"),
            dropDaughters=cms.string("0"),
            rekeyDaughters=cms.string("1"),
            dropTrackRefs=cms.string("1"),
            dropSpecific=cms.string("1"),
            dropTagInfos=cms.string("1"),
            modifyJets=cms.bool(True),
            mixedDaughters=cms.bool(False),
            modifierConfig=cms.PSet(modifications=cms.VPSet())), process, task)

    ## Establish references between PATified fat jets and subjets using the BoostedJetMerger
    addToProcessAndTask(
        "slimmedJetsAK8PFPuppiSoftDropPacked" + postfix,
        cms.EDProducer(
            "BoostedJetMerger",
            jetSrc=cms.InputTag("selectedPatJetsAK8PFPuppiSoftDrop"),
            subjetSrc=cms.InputTag("slimmedJetsAK8PFPuppiSoftDropSubjets")),
        process, task)

    addToProcessAndTask(
        "packedPatJetsAK8" + postfix,
        cms.EDProducer(
            "JetSubstructurePacker",
            jetSrc=cms.InputTag("selectedPatJetsAK8Puppi" + postfix),
            distMax=cms.double(0.8),
            algoTags=cms.VInputTag(
                cms.InputTag("slimmedJetsAK8PFPuppiSoftDropPacked" + postfix)),
            algoLabels=cms.vstring('SoftDropPuppi'),
            fixDaughters=cms.bool(True),
            packedPFCandidates=cms.InputTag("packedPFCandidates" + postfix),
        ), process, task)

    # switch off daughter re-keying since it's done in the JetSubstructurePacker (and can't be done afterwards)
    process.slimmedJetsAK8.rekeyDaughters = "0"
process.load('RecoJets.JetProducers.qjetsadder_cfi')
patAlgosToolsTask.add(process.QJetsAdder)
process.QJetsAdderAK8 = process.QJetsAdder.clone()
patAlgosToolsTask.add(process.QJetsAdderAK8)
process.QJetsAdderAK8.src = cms.InputTag("slimmedJetsAK8")
process.QJetsAdderAK8.jetRad = cms.double(0.8)
process.QJetsAdderAK8.jetAlgo = cms.string('AK')

patJetsAK8.userData.userFloats.src += ['QJetsAdderAK8:QjetsVolatility']
process.out.outputCommands += ['keep *_QJetsAdderAK8_*_*']
                                   
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#Grooming valueMaps

from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSPruned, ak8PFJetsCHSSoftDrop, ak8PFJetsCHSTrimmed, ak8PFJetsCHSFiltered
process.ak8PFJetsCHSPruned = ak8PFJetsCHSPruned.clone()
patAlgosToolsTask.add(process.ak8PFJetsCHSPruned)
process.ak8PFJetsCHSSoftDrop = ak8PFJetsCHSSoftDrop.clone()
patAlgosToolsTask.add(process.ak8PFJetsCHSSoftDrop)
process.ak8PFJetsCHSTrimmed = ak8PFJetsCHSTrimmed.clone()
patAlgosToolsTask.add(process.ak8PFJetsCHSTrimmed)
process.ak8PFJetsCHSFiltered = ak8PFJetsCHSFiltered.clone()
patAlgosToolsTask.add(process.ak8PFJetsCHSFiltered)
process.ak8PFJetsCHSPruned.src = cms.InputTag("packedPFCandidates")
process.ak8PFJetsCHSSoftDrop.src = cms.InputTag("packedPFCandidates")
process.ak8PFJetsCHSTrimmed.src = cms.InputTag("packedPFCandidates")
process.ak8PFJetsCHSFiltered.src = cms.InputTag("packedPFCandidates")
from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSPrunedMass, ak8PFJetsCHSSoftDropMass, ak8PFJetsCHSTrimmedMass, ak8PFJetsCHSFilteredMass
process.ak8PFJetsCHSPrunedMass = ak8PFJetsCHSPrunedMass.clone()
patAlgosToolsTask.add(process.ak8PFJetsCHSPrunedMass)
process.ak8PFJetsCHSSoftDropMass = ak8PFJetsCHSSoftDropMass.clone()
def applySubstructure( process, postfix="" ) :

    task = getPatAlgosToolsTask(process)

    from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection


    from PhysicsTools.PatAlgos.producersLayer1.jetProducer_cfi import _patJets as patJetsDefault

    #add AK8
    addJetCollection(process, postfix=postfix, labelName = 'AK8',
                     jetSource = cms.InputTag('ak8PFJetsCHS'+postfix),
                     algo= 'AK', rParam = 0.8,
                     jetCorrections = ('AK8PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
                     genJetCollection = cms.InputTag('slimmedGenJetsAK8')
                     )
    getattr(process,"patJetsAK8"+postfix).userData.userFloats.src = [] # start with empty list of user floats
    getattr(process,"selectedPatJetsAK8").cut = cms.string("pt > 170")


    ## AK8 groomed masses
    from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSPruned, ak8PFJetsCHSSoftDrop
    addToProcessAndTask('ak8PFJetsCHSPruned'+postfix, ak8PFJetsCHSPruned.clone(), process, task)
    addToProcessAndTask('ak8PFJetsCHSSoftDrop'+postfix, ak8PFJetsCHSSoftDrop.clone(), process, task)
    from RecoJets.JetProducers.ak8PFJetsCHS_groomingValueMaps_cfi import ak8PFJetsCHSPrunedMass, ak8PFJetsCHSTrimmedMass, ak8PFJetsCHSFilteredMass, ak8PFJetsCHSSoftDropMass
    addToProcessAndTask('ak8PFJetsCHSPrunedMass'+postfix, ak8PFJetsCHSPrunedMass.clone(), process, task)
    addToProcessAndTask('ak8PFJetsCHSTrimmedMass'+postfix, ak8PFJetsCHSTrimmedMass.clone(), process, task)
    addToProcessAndTask('ak8PFJetsCHSFilteredMass'+postfix, ak8PFJetsCHSFilteredMass.clone(), process, task)
    addToProcessAndTask('ak8PFJetsCHSSoftDropMass'+postfix, ak8PFJetsCHSSoftDropMass.clone(), process, task)

    getattr(process,"patJetsAK8").userData.userFloats.src += ['ak8PFJetsCHSPrunedMass'+postfix,'ak8PFJetsCHSSoftDropMass'+postfix]  
    getattr(process,"patJetsAK8").addTagInfos = cms.bool(False)



    # add Njetiness
    process.load('RecoJets.JetProducers.nJettinessAdder_cfi')
    task.add(process.Njettiness)
    addToProcessAndTask('NjettinessAK8'+postfix, process.Njettiness.clone(), process, task)


    getattr(process,"NjettinessAK8").src = cms.InputTag("ak8PFJetsCHS"+postfix)
    getattr(process,"NjettinessAK8").cone = cms.double(0.8)
    getattr(process,"patJetsAK8").userData.userFloats.src += ['NjettinessAK8'+postfix+':tau1','NjettinessAK8'+postfix+':tau2','NjettinessAK8'+postfix+':tau3']




    #add AK8 from PUPPI                                                                                                                                 
    from RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJetsPuppi
    from RecoJets.JetProducers.ak8PFJets_cfi import ak8PFJetsPuppi
    addToProcessAndTask('ak4PFJetsPuppi'+postfix,ak4PFJetsPuppi.clone(), process, task)
    addToProcessAndTask('ak8PFJetsPuppi'+postfix,ak8PFJetsPuppi.clone(), process, task)
    from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsPuppiSoftDrop
    addToProcessAndTask('ak8PFJetsPuppiSoftDrop'+postfix, ak8PFJetsPuppiSoftDrop.clone(), process, task)
    getattr(process,"ak8PFJetsPuppi").doAreaFastjet = True # even for standard ak8PFJets this is overwritten in RecoJets/Configuration/python/RecoPFJets_cff


    #add AK8 from PUPPI
    from RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJetsPuppi
    from RecoJets.JetProducers.ak8PFJets_cfi import ak8PFJetsPuppi, ak8PFJetsPuppiSoftDrop, ak8PFJetsPuppiConstituents, ak8PFJetsCHSConstituents
    
    #from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsPuppi, ak8PFJetsPuppiSoftDrop, ak8PFJetsPuppiConstituents, ak8PFJetsCHSConstituents
    addToProcessAndTask('ak4PFJetsPuppi'+postfix,ak4PFJetsPuppi.clone(), process, task)
    addToProcessAndTask('ak8PFJetsPuppiConstituents', ak8PFJetsPuppiConstituents.clone(), process, task )
    addToProcessAndTask('ak8PFJetsCHSConstituents', ak8PFJetsCHSConstituents.clone(), process, task )
    addToProcessAndTask('ak8PFJetsPuppi'+postfix,ak8PFJetsPuppi.clone(), process, task)
    addToProcessAndTask('ak8PFJetsPuppiSoftDrop'+postfix, ak8PFJetsPuppiSoftDrop.clone(), process, task)
    getattr(process,"ak8PFJetsPuppi").doAreaFastjet = True # even for standard ak8PFJets this is overwritten in RecoJets/Configuration/python/RecoPFJets_cff

        
    addJetCollection(process, postfix=postfix, labelName = 'AK8Puppi',
                     jetSource = cms.InputTag('ak8PFJetsPuppi'+postfix),
                     algo= 'AK', rParam = 0.8,
                     jetCorrections = ('AK8PFPuppi', cms.vstring(['L2Relative', 'L3Absolute']), 'None'),
                     btagDiscriminators = ([x.value() for x in patJetsDefault.discriminatorSources] + ['pfBoostedDoubleSecondaryVertexAK8BJetTags']),
                     genJetCollection = cms.InputTag('slimmedGenJetsAK8')
                     )
    getattr(process,"patJetsAK8Puppi"+postfix).userData.userFloats.src = [] # start with empty list of user floats
    getattr(process,"selectedPatJetsAK8Puppi"+postfix).cut = cms.string("pt > 170")


    from RecoJets.JetAssociationProducers.j2tParametersVX_cfi import j2tParametersVX
    addToProcessAndTask('ak8PFJetsPuppiTracksAssociatorAtVertex'+postfix, cms.EDProducer("JetTracksAssociatorAtVertex",
                                      j2tParametersVX.clone( coneSize = cms.double(0.8) ),
                                      jets = cms.InputTag("ak8PFJetsPuppi") ),
                        process, task)
    addToProcessAndTask('patJetAK8PuppiCharge'+postfix, cms.EDProducer("JetChargeProducer",
                                     src = cms.InputTag("ak8PFJetsPuppiTracksAssociatorAtVertex"),
                                     var = cms.string('Pt'),
                                     exp = cms.double(1.0) ), 
                        process, task)

    ## AK8 groomed masses
    from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsPuppiSoftDrop
    addToProcessAndTask('ak8PFJetsPuppiSoftDrop'+postfix, ak8PFJetsPuppiSoftDrop.clone(), process, task)
    from RecoJets.JetProducers.ak8PFJetsPuppi_groomingValueMaps_cfi import ak8PFJetsPuppiSoftDropMass
    addToProcessAndTask('ak8PFJetsPuppiSoftDropMass'+postfix, ak8PFJetsPuppiSoftDropMass.clone(), process, task)
    getattr(process,"patJetsAK8Puppi"+postfix).userData.userFloats.src += ['ak8PFJetsPuppiSoftDropMass'+postfix]
    getattr(process,"patJetsAK8Puppi"+postfix).addTagInfos = cms.bool(False)



    # add Njetiness
    addToProcessAndTask('NjettinessAK8Puppi'+postfix, process.Njettiness.clone(), process, task)
    getattr(process,"NjettinessAK8Puppi"+postfix).src = cms.InputTag("ak8PFJetsPuppi"+postfix)
    getattr(process,"NjettinessAK8Puppi").cone = cms.double(0.8)
    getattr(process,"patJetsAK8Puppi").userData.userFloats.src += ['NjettinessAK8Puppi'+postfix+':tau1','NjettinessAK8Puppi'+postfix+':tau2','NjettinessAK8Puppi'+postfix+':tau3']




    addToProcessAndTask("ak8PFJetsCHSValueMap"+postfix, cms.EDProducer("RecoJetToPatJetDeltaRValueMapProducer",
                                            src = cms.InputTag("ak8PFJetsPuppi"+postfix),
                                            matched = cms.InputTag("patJetsAK8"+postfix),
                                            distMax = cms.double(0.8),
                                            values = cms.vstring([
                                                'userFloat("ak8PFJetsCHSPrunedMass"'+postfix+')',
                                                'userFloat("ak8PFJetsCHSSoftDropMass"'+postfix+')',
                                                'userFloat("NjettinessAK8'+postfix+':tau1")',
                                                'userFloat("NjettinessAK8'+postfix+':tau2")',
                                                'userFloat("NjettinessAK8'+postfix+':tau3")',
                                                'pt','eta','phi','mass'
                                            ]),
                                            valueLabels = cms.vstring( [
                                                'ak8PFJetsCHSPrunedMass',
                                                'ak8PFJetsCHSSoftDropMass',
                                                'NjettinessAK8CHSTau1',
                                                'NjettinessAK8CHSTau2',
                                                'NjettinessAK8CHSTau3',
                                                'pt','eta','phi','mass'
                                            ]) ),
                        process, task)

    getattr(process,"patJetsAK8Puppi"+postfix).userData.userFloats.src += [
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'ak8PFJetsCHSPrunedMass'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'ak8PFJetsCHSSoftDropMass'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'NjettinessAK8CHSTau1'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'NjettinessAK8CHSTau2'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'NjettinessAK8CHSTau3'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'pt'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'eta'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'phi'),
                                                   cms.InputTag('ak8PFJetsCHSValueMap'+postfix,'mass'),
                                                   ]

    # add Njetiness
    process.load('RecoJets.JetProducers.nJettinessAdder_cfi')
    task.add(process.Njettiness)
    addToProcessAndTask('NjettinessAK8Subjets'+postfix, process.Njettiness.clone(), process, task)
    getattr(process,"NjettinessAK8Subjets"+postfix).src = cms.InputTag("ak8PFJetsPuppiSoftDrop"+postfix, "SubJets")
    getattr(process,"NjettinessAK8Subjets").cone = cms.double(0.8)
    

    
    ## PATify CHS soft drop fat jets
    addJetCollection(
        process,
        postfix=postfix,
        labelName = 'AK8PFCHSSoftDrop',
        jetSource = cms.InputTag('ak8PFJetsCHSSoftDrop'+postfix),
        btagDiscriminators = ['None'],
        jetCorrections = ('AK8PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),
        getJetMCFlavour = False # jet flavor disabled
    )


    ## PATify puppi soft drop fat jets
    addJetCollection(
        process,
        postfix=postfix,
        labelName = 'AK8PFPuppiSoftDrop',
        jetSource = cms.InputTag('ak8PFJetsPuppiSoftDrop'+postfix),
        btagDiscriminators = ['None'],
        jetCorrections = ('AK8PFPuppi', ['L2Relative', 'L3Absolute'], 'None'),
        getJetMCFlavour = False # jet flavor disabled
    )
    
    ## PATify soft drop subjets
    addJetCollection(
        process,
        postfix=postfix,
        labelName = 'AK8PFPuppiSoftDropSubjets',
        jetSource = cms.InputTag('ak8PFJetsPuppiSoftDrop'+postfix,'SubJets'),
        algo = 'ak',  # needed for subjet flavor clustering
        rParam = 0.8, # needed for subjet flavor clustering
        btagDiscriminators = ['pfDeepCSVJetTags:probb', 'pfDeepCSVJetTags:probbb', 'pfCombinedInclusiveSecondaryVertexV2BJetTags','pfCombinedMVAV2BJetTags'],
        jetCorrections = ('AK4PFPuppi', ['L2Relative', 'L3Absolute'], 'None'),
        explicitJTA = True,  # needed for subjet b tagging
        svClustering = True, # needed for subjet b tagging
        genJetCollection = cms.InputTag('slimmedGenJets'), 
        fatJets=cms.InputTag('ak8PFJetsPuppi'),             # needed for subjet flavor clustering
        groomedFatJets=cms.InputTag('ak8PFJetsPuppiSoftDrop') # needed for subjet flavor clustering
    )
    getattr(process,"selectedPatJetsAK8PFPuppiSoftDrop"+postfix).cut = cms.string("pt > 170")
    getattr(process,"patJetsAK8PFPuppiSoftDropSubjets"+postfix).userData.userFloats.src += ['NjettinessAK8Subjets'+postfix+':tau1','NjettinessAK8Subjets'+postfix+':tau2','NjettinessAK8Subjets'+postfix+':tau3']
    
    addToProcessAndTask("slimmedJetsAK8PFPuppiSoftDropSubjets"+postfix,
                        cms.EDProducer("PATJetSlimmer",
                             src = cms.InputTag("selectedPatJetsAK8PFPuppiSoftDropSubjets"),
                             packedPFCandidates = cms.InputTag("packedPFCandidates"),
                             dropJetVars = cms.string("1"),
                             dropDaughters = cms.string("0"),
                             rekeyDaughters = cms.string("1"),
                             dropTrackRefs = cms.string("1"),
                             dropSpecific = cms.string("1"),
                             dropTagInfos = cms.string("1"),
                             modifyJets = cms.bool(True),
                             mixedDaughters = cms.bool(False),
                             modifierConfig = cms.PSet( modifications = cms.VPSet() )
                                       ),
                        process, task)

    
    ## Establish references between PATified fat jets and subjets using the BoostedJetMerger
    addToProcessAndTask("slimmedJetsAK8PFPuppiSoftDropPacked"+postfix,
                        cms.EDProducer("BoostedJetMerger",
                               jetSrc=cms.InputTag("selectedPatJetsAK8PFPuppiSoftDrop"),
                               subjetSrc=cms.InputTag("slimmedJetsAK8PFPuppiSoftDropSubjets")
                                       ),
                        process, task )

    
    addToProcessAndTask("packedPatJetsAK8"+postfix, cms.EDProducer("JetSubstructurePacker",
                                           jetSrc = cms.InputTag("selectedPatJetsAK8Puppi"+postfix),
                                           distMax = cms.double(0.8),
                                           algoTags = cms.VInputTag(
                                               cms.InputTag("slimmedJetsAK8PFPuppiSoftDropPacked"+postfix)
                                           ),
                                           algoLabels = cms.vstring(
                                               'SoftDropPuppi'
                                           ),
                                          fixDaughters = cms.bool(True),
                                          packedPFCandidates = cms.InputTag("packedPFCandidates"+postfix),
                                                                   ),
                        process, task)

    # switch off daughter re-keying since it's done in the JetSubstructurePacker (and can't be done afterwards)
    process.slimmedJetsAK8.rekeyDaughters = "0"
Beispiel #6
0
def applySubstructure(process):

    from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection

    # add CMS top tagger
    from RecoJets.JetProducers.caTopTaggers_cff import caTopTagInfos
    process.caTopTagInfos = caTopTagInfos.clone()
    process.caTopTagInfosPAT = cms.EDProducer(
        "RecoJetDeltaRTagInfoValueMapProducer",
        src=cms.InputTag("ak8PFJetsCHS"),
        matched=cms.InputTag("cmsTopTagPFJetsCHS"),
        matchedTagInfos=cms.InputTag("caTopTagInfos"),
        distMax=cms.double(0.8))

    from PhysicsTools.PatAlgos.producersLayer1.jetProducer_cfi import _patJets as patJetsDefault

    #add AK8
    addJetCollection(
        process,
        labelName='AK8',
        jetSource=cms.InputTag('ak8PFJetsCHS'),
        algo='AK',
        rParam=0.8,
        jetCorrections=('AK8PFchs',
                        cms.vstring(['L1FastJet', 'L2Relative',
                                     'L3Absolute']), 'None'),
        btagDiscriminators=(
            [x.getModuleLabel() for x in patJetsDefault.discriminatorSources] +
            ['pfBoostedDoubleSecondaryVertexAK8BJetTags']),
        genJetCollection=cms.InputTag('slimmedGenJetsAK8'))
    process.patJetsAK8.userData.userFloats.src = [
    ]  # start with empty list of user floats
    process.selectedPatJetsAK8.cut = cms.string("pt > 170")

    ## AK8 groomed masses
    from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSPruned, ak8PFJetsCHSSoftDrop, ak8PFJetsCHSFiltered, ak8PFJetsCHSTrimmed
    process.ak8PFJetsCHSPruned = ak8PFJetsCHSPruned.clone()
    process.ak8PFJetsCHSSoftDrop = ak8PFJetsCHSSoftDrop.clone()
    process.ak8PFJetsCHSTrimmed = ak8PFJetsCHSTrimmed.clone()
    process.ak8PFJetsCHSFiltered = ak8PFJetsCHSFiltered.clone()
    process.load("RecoJets.JetProducers.ak8PFJetsCHS_groomingValueMaps_cfi")
    process.patJetsAK8.userData.userFloats.src += [
        'ak8PFJetsCHSPrunedMass', 'ak8PFJetsCHSSoftDropMass',
        'ak8PFJetsCHSTrimmedMass', 'ak8PFJetsCHSFilteredMass'
    ]

    # Add AK8 top tagging variables
    process.patJetsAK8.tagInfoSources = cms.VInputTag(
        cms.InputTag("caTopTagInfosPAT"))
    process.patJetsAK8.addTagInfos = cms.bool(True)

    # add Njetiness
    process.load('RecoJets.JetProducers.nJettinessAdder_cfi')
    process.NjettinessAK8 = process.Njettiness.clone()
    process.NjettinessAK8.src = cms.InputTag("ak8PFJetsCHS")
    process.NjettinessAK8.cone = cms.double(0.8)
    process.patJetsAK8.userData.userFloats.src += [
        'NjettinessAK8:tau1', 'NjettinessAK8:tau2', 'NjettinessAK8:tau3'
    ]

    ## PATify pruned fat jets
    addJetCollection(
        process,
        labelName='AK8PFCHSSoftDrop',
        jetSource=cms.InputTag('ak8PFJetsCHSSoftDrop'),
        btagDiscriminators=['None'],
        jetCorrections=('AK8PFchs', ['L1FastJet', 'L2Relative',
                                     'L3Absolute'], 'None'),
        getJetMCFlavour=False  # jet flavor disabled
    )

    ## PATify soft drop subjets
    addJetCollection(
        process,
        labelName='AK8PFCHSSoftDropSubjets',
        jetSource=cms.InputTag('ak8PFJetsCHSSoftDrop', 'SubJets'),
        algo='ak',  # needed for subjet flavor clustering
        rParam=0.8,  # needed for subjet flavor clustering
        btagDiscriminators=[
            'pfCombinedSecondaryVertexV2BJetTags',
            'pfCombinedInclusiveSecondaryVertexV2BJetTags'
        ],
        jetCorrections=('AK4PFchs', ['L1FastJet', 'L2Relative',
                                     'L3Absolute'], 'None'),
        explicitJTA=True,  # needed for subjet b tagging
        svClustering=True,  # needed for subjet b tagging
        genJetCollection=cms.InputTag('slimmedGenJets'),
        fatJets=cms.InputTag(
            'ak8PFJetsCHS'),  # needed for subjet flavor clustering
        groomedFatJets=cms.InputTag(
            'ak8PFJetsCHSSoftDrop')  # needed for subjet flavor clustering
    )
    process.selectedPatJetsAK8PFCHSSoftDrop.cut = cms.string("pt > 170")

    process.slimmedJetsAK8PFCHSSoftDropSubjets = cms.EDProducer(
        "PATJetSlimmer",
        src=cms.InputTag("selectedPatJetsAK8PFCHSSoftDropSubjets"),
        packedPFCandidates=cms.InputTag("packedPFCandidates"),
        dropJetVars=cms.string("1"),
        dropDaughters=cms.string("0"),
        rekeyDaughters=cms.string("1"),
        dropTrackRefs=cms.string("1"),
        dropSpecific=cms.string("1"),
        dropTagInfos=cms.string("1"),
        modifyJets=cms.bool(True),
        modifierConfig=cms.PSet(modifications=cms.VPSet()))

    ## Establish references between PATified fat jets and subjets using the BoostedJetMerger
    process.slimmedJetsAK8PFCHSSoftDropPacked = cms.EDProducer(
        "BoostedJetMerger",
        jetSrc=cms.InputTag("selectedPatJetsAK8PFCHSSoftDrop"),
        subjetSrc=cms.InputTag("slimmedJetsAK8PFCHSSoftDropSubjets"))

    addJetCollection(
        process,
        labelName='CMSTopTagCHS',
        jetSource=cms.InputTag('cmsTopTagPFJetsCHS'),
        jetCorrections=('AK8PFchs',
                        cms.vstring(['L1FastJet', 'L2Relative',
                                     'L3Absolute']), 'None'),
        btagDiscriminators=['None'],
        genJetCollection=cms.InputTag('slimmedGenJetsAK8'),
        getJetMCFlavour=False  #
    )
    process.selectedPatJetsCMSTopTagCHS.cut = cms.string("pt > 200")

    addJetCollection(
        process,
        labelName='CMSTopTagCHSSubjets',
        jetSource=cms.InputTag('cmsTopTagPFJetsCHS', 'caTopSubJets'),
        algo='AK',  # needed for subjet flavor clustering
        rParam=0.8,  # needed for subjet flavor clustering        
        btagDiscriminators=[
            'pfCombinedSecondaryVertexV2BJetTags',
            'pfCombinedInclusiveSecondaryVertexV2BJetTags'
        ],
        jetCorrections=('AK4PFchs', ['L1FastJet', 'L2Relative',
                                     'L3Absolute'], 'None'),
        genJetCollection=cms.InputTag(
            'slimmedGenJets'
        ),  # Using ak4GenJets for matching which is not entirely appropriate
        explicitJTA=True,  # needed for subjet b tagging
        svClustering=True,  # needed for subjet b tagging
        fatJets=cms.InputTag(
            'ak8PFJetsCHS'),  # needed for subjet flavor clustering
        groomedFatJets=cms.InputTag(
            'cmsTopTagPFJetsCHS')  # needed for subjet flavor clustering
    )

    process.slimmedJetsCMSTopTagCHSSubjets = cms.EDProducer(
        "PATJetSlimmer",
        src=cms.InputTag("selectedPatJetsCMSTopTagCHSSubjets"),
        packedPFCandidates=cms.InputTag("packedPFCandidates"),
        dropJetVars=cms.string("1"),
        dropDaughters=cms.string("0"),
        rekeyDaughters=cms.string("1"),
        dropTrackRefs=cms.string("1"),
        dropSpecific=cms.string("1"),
        dropTagInfos=cms.string("1"),
        modifyJets=cms.bool(True),
        modifierConfig=cms.PSet(modifications=cms.VPSet()))

    ## Establish references between PATified fat jets and subjets using the BoostedJetMerger
    process.slimmedJetsCMSTopTagCHSPacked = cms.EDProducer(
        "BoostedJetMerger",
        jetSrc=cms.InputTag("selectedPatJetsCMSTopTagCHS"),
        subjetSrc=cms.InputTag("slimmedJetsCMSTopTagCHSSubjets"))

    process.packedPatJetsAK8 = cms.EDProducer(
        "JetSubstructurePacker",
        jetSrc=cms.InputTag("selectedPatJetsAK8"),
        distMax=cms.double(0.8),
        algoTags=cms.VInputTag(
            # NOTE: For an optimal storage of the AK8 jet daughters, the first subjet collection listed here should be
            #       derived from AK8 jets, i.e., subjets should contain either all or a subset of AK8 constituents.
            #       The CMSTopTag subjets are derived from CA8 jets later matched to AK8 jets and could in principle
            #       contain extra constituents not clustered inside AK8 jets.
            cms.InputTag("slimmedJetsAK8PFCHSSoftDropPacked"),
            cms.InputTag("slimmedJetsCMSTopTagCHSPacked")),
        algoLabels=cms.vstring('SoftDrop', 'CMSTopTag'),
        fixDaughters=cms.bool(True),
        packedPFCandidates=cms.InputTag("packedPFCandidates"),
    )

    # switch off daughter re-keying since it's done in the JetSubstructurePacker (and can't be done afterwards)
    process.slimmedJetsAK8.rekeyDaughters = "0"
def applySubstructure( process ) :

    from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection


    from PhysicsTools.PatAlgos.producersLayer1.jetProducer_cfi import _patJets as patJetsDefault

    #add AK8
    addJetCollection(process, labelName = 'AK8',
                     jetSource = cms.InputTag('ak8PFJetsCHS'),
                     algo= 'AK', rParam = 0.8,
                     jetCorrections = ('AK8PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
                     btagDiscriminators = ([x.getModuleLabel() for x in patJetsDefault.discriminatorSources] + ['pfBoostedDoubleSecondaryVertexAK8BJetTags']),
                     genJetCollection = cms.InputTag('slimmedGenJetsAK8')
                     )
    process.patJetsAK8.userData.userFloats.src = [] # start with empty list of user floats
    process.selectedPatJetsAK8.cut = cms.string("pt > 170")


    process.load('RecoJets.JetProducers.ak8PFJetsPuppi_cfi')
    process.ak8PFJetsPuppi.doAreaFastjet = True # even for standard ak8PFJets this is overwritten in RecoJets/Configuration/python/RecoPFJets_cff

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

    ## AK8 groomed masses
    from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSPruned, ak8PFJetsCHSSoftDrop, ak8PFJetsPuppiSoftDrop 
    process.ak8PFJetsCHSPruned   = ak8PFJetsCHSPruned.clone()
    process.ak8PFJetsCHSSoftDrop = ak8PFJetsCHSSoftDrop.clone()
    process.ak8PFJetsPuppiSoftDrop = ak8PFJetsPuppiSoftDrop.clone()
    process.load("RecoJets.JetProducers.ak8PFJetsCHS_groomingValueMaps_cfi")
    process.patJetsAK8.userData.userFloats.src += ['ak8PFJetsCHSPrunedMass','ak8PFJetsCHSSoftDropMass'] 
    process.patJetsAK8.addTagInfos = cms.bool(False)



    # add Njetiness
    process.load('RecoJets.JetProducers.nJettinessAdder_cfi')
    process.NjettinessAK8 = process.Njettiness.clone()
    process.NjettinessAK8.src = cms.InputTag("ak8PFJetsCHS")
    process.NjettinessAK8.cone = cms.double(0.8)
    process.patJetsAK8.userData.userFloats.src += ['NjettinessAK8:tau1','NjettinessAK8:tau2','NjettinessAK8:tau3']




    #add AK8 from PUPPI

    process.load('RecoJets.JetProducers.ak8PFJetsPuppi_cfi')
    process.ak8PFJetsPuppi.doAreaFastjet = True # even for standard ak8PFJets this is overwritten in RecoJets/Configuration/python/RecoPFJets_cff

        
    addJetCollection(process, labelName = 'AK8Puppi',
                     jetSource = cms.InputTag('ak8PFJetsPuppi'),
                     algo= 'AK', rParam = 0.8,
                     jetCorrections = ('AK8PFPuppi', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
                     genJetCollection = cms.InputTag('slimmedGenJetsAK8')
                     )
    process.patJetsAK8Puppi.userData.userFloats.src = [] # start with empty list of user floats
    process.selectedPatJetsAK8Puppi.cut = cms.string("pt > 170")


    from RecoJets.JetAssociationProducers.j2tParametersVX_cfi import j2tParametersVX
    process.ak8PFJetsPuppiTracksAssociatorAtVertex = cms.EDProducer("JetTracksAssociatorAtVertex",
        j2tParametersVX,
        jets = cms.InputTag("ak8PFJetsPuppi")
    )
    process.patJetAK8PuppiCharge = cms.EDProducer("JetChargeProducer",
        src = cms.InputTag("ak8PFJetsPuppiTracksAssociatorAtVertex"),
        var = cms.string('Pt'),
        exp = cms.double(1.0)
    )

    ## AK8 groomed masses
    from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsPuppiSoftDrop
    process.ak8PFJetsPuppiSoftDrop = ak8PFJetsPuppiSoftDrop.clone()
    process.load("RecoJets.JetProducers.ak8PFJetsPuppi_groomingValueMaps_cfi")
    process.patJetsAK8Puppi.userData.userFloats.src += ['ak8PFJetsPuppiSoftDropMass']
    process.patJetsAK8Puppi.addTagInfos = cms.bool(False)



    # add Njetiness
    process.NjettinessAK8Puppi = process.Njettiness.clone()
    process.NjettinessAK8Puppi.src = cms.InputTag("ak8PFJetsPuppi")
    process.NjettinessAK8Puppi.cone = cms.double(0.8)
    process.patJetsAK8Puppi.userData.userFloats.src += ['NjettinessAK8Puppi:tau1','NjettinessAK8Puppi:tau2','NjettinessAK8Puppi:tau3']




    process.ak8PFJetsPuppiValueMap = cms.EDProducer("RecoJetToPatJetDeltaRValueMapProducer",
                                            src = cms.InputTag("ak8PFJetsCHS"),
                                            matched = cms.InputTag("patJetsAK8Puppi"),                                         
                                            distMax = cms.double(0.8),
                                            values = cms.vstring([
                                                'userFloat("NjettinessAK8Puppi:tau1")',
                                                'userFloat("NjettinessAK8Puppi:tau2")',
                                                'userFloat("NjettinessAK8Puppi:tau3")',
                                                'pt','eta','phi','mass'
                                            ]),
                                            valueLabels = cms.vstring( [
                                                'NjettinessAK8PuppiTau1',
                                                'NjettinessAK8PuppiTau2',
                                                'NjettinessAK8PuppiTau3',
                                                'pt','eta','phi','mass'
                                            ])
                        )
    #process.patJetsAK8.userData.userFloats.src += ['NjettinessAK8:tau1','NjettinessAK8:tau2','NjettinessAK8:tau3']

    process.patJetsAK8.userData.userFloats.src += [cms.InputTag('ak8PFJetsPuppiValueMap','NjettinessAK8PuppiTau1'),
                                                   cms.InputTag('ak8PFJetsPuppiValueMap','NjettinessAK8PuppiTau2'),
                                                   cms.InputTag('ak8PFJetsPuppiValueMap','NjettinessAK8PuppiTau3'),
                                                   cms.InputTag('ak8PFJetsPuppiValueMap','pt'),
                                                   cms.InputTag('ak8PFJetsPuppiValueMap','eta'),
                                                   cms.InputTag('ak8PFJetsPuppiValueMap','phi'),
                                                   cms.InputTag('ak8PFJetsPuppiValueMap','mass'),
                                                   ]

    
    ## PATify pruned fat jets
    addJetCollection(
        process,
        labelName = 'AK8PFCHSSoftDrop',
        jetSource = cms.InputTag('ak8PFJetsCHSSoftDrop'),
        btagDiscriminators = ['None'],
        jetCorrections = ('AK8PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),
        getJetMCFlavour = False # jet flavor disabled
    )
    
    ## PATify soft drop subjets
    addJetCollection(
        process,
        labelName = 'AK8PFCHSSoftDropSubjets',
        jetSource = cms.InputTag('ak8PFJetsCHSSoftDrop','SubJets'),
        algo = 'ak',  # needed for subjet flavor clustering
        rParam = 0.8, # needed for subjet flavor clustering
        btagDiscriminators = ['pfCombinedSecondaryVertexV2BJetTags', 'pfCombinedInclusiveSecondaryVertexV2BJetTags'],
        jetCorrections = ('AK4PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),
        explicitJTA = True,  # needed for subjet b tagging
        svClustering = True, # needed for subjet b tagging
        genJetCollection = cms.InputTag('slimmedGenJets'), 
        fatJets=cms.InputTag('ak8PFJetsCHS'),             # needed for subjet flavor clustering
        groomedFatJets=cms.InputTag('ak8PFJetsCHSSoftDrop') # needed for subjet flavor clustering
    )
    process.selectedPatJetsAK8PFCHSSoftDrop.cut = cms.string("pt > 170")
    
    process.slimmedJetsAK8PFCHSSoftDropSubjets = cms.EDProducer("PATJetSlimmer",
        src = cms.InputTag("selectedPatJetsAK8PFCHSSoftDropSubjets"),
        packedPFCandidates = cms.InputTag("packedPFCandidates"),
        dropJetVars = cms.string("1"),
        dropDaughters = cms.string("0"),
        rekeyDaughters = cms.string("1"),
        dropTrackRefs = cms.string("1"),
        dropSpecific = cms.string("1"),
        dropTagInfos = cms.string("1"),
        modifyJets = cms.bool(True),
        modifierConfig = cms.PSet( modifications = cms.VPSet() )
    )

    
    ## Establish references between PATified fat jets and subjets using the BoostedJetMerger
    process.slimmedJetsAK8PFCHSSoftDropPacked = cms.EDProducer("BoostedJetMerger",
        jetSrc=cms.InputTag("selectedPatJetsAK8PFCHSSoftDrop"),
        subjetSrc=cms.InputTag("slimmedJetsAK8PFCHSSoftDropSubjets")
    )

    
    

    ## PATify pruned fat jets
    addJetCollection(
        process,
        labelName = 'AK8PFPuppiSoftDrop',
        jetSource = cms.InputTag('ak8PFJetsPuppiSoftDrop'),
        btagDiscriminators = ['None'],
        jetCorrections = ('AK8PFPuppi', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),
        getJetMCFlavour = False # jet flavor disabled
    )
    
    ## PATify soft drop subjets
    addJetCollection(
        process,
        labelName = 'AK8PFPuppiSoftDropSubjets',
        jetSource = cms.InputTag('ak8PFJetsPuppiSoftDrop','SubJets'),
        algo = 'ak',  # needed for subjet flavor clustering
        rParam = 0.8, # needed for subjet flavor clustering
        btagDiscriminators = ['pfCombinedSecondaryVertexV2BJetTags', 'pfCombinedInclusiveSecondaryVertexV2BJetTags'],
        jetCorrections = ('AK4PFPuppi', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),
        explicitJTA = True,  # needed for subjet b tagging
        svClustering = True, # needed for subjet b tagging
        genJetCollection = cms.InputTag('slimmedGenJets'), 
        fatJets=cms.InputTag('ak8PFJetsPuppi'),             # needed for subjet flavor clustering
        groomedFatJets=cms.InputTag('ak8PFJetsPuppiSoftDrop') # needed for subjet flavor clustering
    )
    process.selectedPatJetsAK8PFPuppiSoftDrop.cut = cms.string("pt > 170")
    
    process.slimmedJetsAK8PFPuppiSoftDropSubjets = cms.EDProducer("PATJetSlimmer",
        src = cms.InputTag("selectedPatJetsAK8PFPuppiSoftDropSubjets"),
        packedPFCandidates = cms.InputTag("packedPFCandidates"),
        dropJetVars = cms.string("1"),
        dropDaughters = cms.string("0"),
        rekeyDaughters = cms.string("1"),
        dropTrackRefs = cms.string("1"),
        dropSpecific = cms.string("1"),
        dropTagInfos = cms.string("1"),
        modifyJets = cms.bool(True),
        modifierConfig = cms.PSet( modifications = cms.VPSet() )
    )

    
    ## Establish references between PATified fat jets and subjets using the BoostedJetMerger
    process.slimmedJetsAK8PFPuppiSoftDropPacked = cms.EDProducer("BoostedJetMerger",
        jetSrc=cms.InputTag("selectedPatJetsAK8PFPuppiSoftDrop"),
        subjetSrc=cms.InputTag("slimmedJetsAK8PFPuppiSoftDropSubjets")
    )

    
    process.packedPatJetsAK8 = cms.EDProducer("JetSubstructurePacker",
            jetSrc = cms.InputTag("selectedPatJetsAK8"),
            distMax = cms.double(0.8),
            algoTags = cms.VInputTag(
                # NOTE: For an optimal storage of the AK8 jet daughters, the first subjet collection listed here should be
                #       derived from AK8 jets, i.e., subjets should contain either all or a subset of AK8 constituents.
                #       The PUPPI collection has its own pointers to its own PUPPI constituents. 
                cms.InputTag("slimmedJetsAK8PFCHSSoftDropPacked"),
                cms.InputTag("slimmedJetsAK8PFPuppiSoftDropPacked")
            ),
            algoLabels = cms.vstring(
                'SoftDrop',
                'SoftDropPuppi'
                ),
            fixDaughters = cms.bool(True),
            packedPFCandidates = cms.InputTag("packedPFCandidates"),
    )

    # switch off daughter re-keying since it's done in the JetSubstructurePacker (and can't be done afterwards)
    process.slimmedJetsAK8.rekeyDaughters = "0"
Beispiel #8
0
def jetToolbox( proc, jetType, jetSequence, outputFile, 
		newPFCollection=False, nameNewPFCollection = '',	
		PUMethod='CHS',                    #### Options: Puppi, CS, SK, Plain
		miniAOD=True,
		runOnMC=True,
		JETCorrPayload='', JETCorrLevels = [ 'None' ], GetJetMCFlavour=True,
		Cut = '', 
		bTagDiscriminators = None, 
		subJETCorrPayload='', subJETCorrLevels = [ 'None' ], GetSubjetMCFlavour=False,
		CutSubjet = '', 
		addPruning=False, zCut=0.1, rCut=0.5, addPrunedSubjets=False,
		addSoftDrop=False, betaCut=0.0,  zCutSD=0.1, addSoftDropSubjets=False,
		addTrimming=False, rFiltTrim=0.2, ptFrac=0.03,
		addFiltering=False, rfilt=0.3, nfilt=3,
		addCMSTopTagger=False,
		addMassDrop=False,
		addHEPTopTagger=False,
		addNsub=False, maxTau=4,
		addPUJetID=False,
		addQJets=False,
		addQGTagger=False, QGjetsLabel='chs',
		addEnergyCorrFunc=False, ecfBeta = 1.0, maxECF=3,
		):

	runOnData = not runOnMC
	if runOnData:
		GetJetMCFlavour = False
		GetSubjetMCFlavour = False
	
	###############################################################################
	#######  Verifying some inputs and defining variables
	###############################################################################
	print '|---- jetToolbox: Initialyzing collection...'
	if newPFCollection: print '|---- jetToolBox: Using '+ nameNewPFCollection +' as PFCandidates collection'
	supportedJetAlgos = { 'ak': 'AntiKt', 'ca' : 'CambridgeAachen', 'kt' : 'Kt' }
	recommendedJetAlgos = [ 'ak4', 'ak8', 'ca4', 'ca8', 'ca10' ]
	payloadList = [ 'None',
			'AK1PFchs', 'AK2PFchs', 'AK3PFchs', 'AK4PFchs', 'AK5PFchs', 'AK6PFchs', 'AK7PFchs', 'AK8PFchs', 'AK9PFchs', 'AK10PFchs',
			'AK1PFPUPPI', 'AK2PFPUPPI', 'AK3PFPUPPI', 'AK4PFPUPPI', 'AK5PFPUPPI', 'AK6PFPUPPI', 'AK7PFPUPPI', 'AK8PFPUPPI', 'AK9PFPUPPI', 'AK10PFPUPPI',  
			'AK1PFSK', 'AK2PFSK', 'AK3PFSK', 'AK4PFSK', 'AK5PFSK', 'AK6PFSK', 'AK7PFSK', 'AK8PFSK', 'AK9PFSK', 'AK10PFSK',  
			'AK1PF', 'AK2PF', 'AK3PF', 'AK4PF', 'AK5PF', 'AK6PF', 'AK7PF', 'AK8PF', 'AK9PF', 'AK10PF' ]
	JECLevels = [ 'L1Offset', 'L1FastJet', 'L1JPTOffset', 'L2Relative', 'L3Absolute', 'L5Falvour', 'L7Parton' ]
	if runOnData:
		JECLevels += ['L2L3Residual']
	jetAlgo = ''
	algorithm = ''
	size = ''
	for type, tmpAlgo in supportedJetAlgos.iteritems(): 
		if type in jetType.lower():
			jetAlgo = type
			algorithm = tmpAlgo
			size = jetType.replace( type, '' )

	jetSize = 0.
	if int(size) in range(0, 20): jetSize = int(size)/10.
	else: print '|---- jetToolBox: jetSize has not a valid value. Insert a number between 1 and 20 after algorithm, like: AK8'
	### Trick for uppercase/lowercase algo name
	jetALGO = jetAlgo.upper()+size
	jetalgo = jetAlgo.lower()+size
	if jetalgo not in recommendedJetAlgos: print '|---- jetToolBox: CMS recommends the following jet algoritms: '+' '.join(recommendedJetAlgos)+'. You are using', jetalgo,'.'


	#################################################################################
	####### Toolbox start 
	#################################################################################

	elemToKeep = []
	jetSeq = cms.Sequence()
	genParticlesLabel = ''
	pvLabel = ''
	tvLabel = ''
	toolsUsed = []

	#### For MiniAOD
	if miniAOD:

		print '|---- jetToolBox: JETTOOLBOX RUNNING ON MiniAOD FOR '+jetALGO+' JETS USING '+PUMethod

		genParticlesLabel = 'prunedGenParticles'
		pvLabel = 'offlineSlimmedPrimaryVertices'
		svLabel = 'slimmedSecondaryVertices'
		tvLabel = 'unpackedTracksAndVertices'
		pfCand = nameNewPFCollection if newPFCollection else 'packedPFCandidates'

		if runOnMC:
			## Filter out neutrinos from packed GenParticles
			setattr( proc, 'packedGenParticlesForJetsNoNu', 
					cms.EDFilter("CandPtrSelector", 
						src = cms.InputTag("packedGenParticles"), 
						cut = cms.string("abs(pdgId) != 12 && abs(pdgId) != 14 && abs(pdgId) != 16")
						))
			jetSeq += getattr(proc, 'packedGenParticlesForJetsNoNu' )

			setattr( proc, jetalgo+'GenJetsNoNu', 
					ak4GenJets.clone( src = 'packedGenParticlesForJetsNoNu', 
						rParam = jetSize, 
						jetAlgorithm = algorithm ) ) 
			jetSeq += getattr(proc, jetalgo+'GenJetsNoNu' )

		#for Inclusive Vertex Finder
		proc.load('PhysicsTools.PatAlgos.slimming.unpackedTracksAndVertices_cfi')

	#### For AOD
	else:
		print '|---- jetToolBox: JETTOOLBOX RUNNING ON AOD FOR '+jetALGO+' JETS USING '+PUMethod

		genParticlesLabel = 'genParticles'
		pvLabel = 'offlinePrimaryVertices'
		tvLabel = 'generalTracks'
		pfCand =  nameNewPFCollection if newPFCollection else 'particleFlow'
		svLabel = 'inclusiveCandidateSecondaryVertices'

		if runOnMC:
			proc.load('RecoJets.Configuration.GenJetParticles_cff')
			setattr( proc, jetalgo+'GenJetsNoNu', ak4GenJets.clone( src = 'genParticlesForJetsNoNu', rParam = jetSize, jetAlgorithm = algorithm ) ) 
			jetSeq += getattr(proc, jetalgo+'GenJetsNoNu' )
		
		

	## b-tag discriminators
	if bTagDiscriminators is None:
		bTagDiscriminators = [
				'pfTrackCountingHighEffBJetTags',
				'pfTrackCountingHighPurBJetTags',
				'pfJetProbabilityBJetTags',
				'pfJetBProbabilityBJetTags',
				'pfSimpleSecondaryVertexHighEffBJetTags',
				'pfSimpleSecondaryVertexHighPurBJetTags',
				'pfCombinedSecondaryVertexV2BJetTags',
				'pfCombinedInclusiveSecondaryVertexV2BJetTags'
	    	]

	### Jet Corrections
	if not set(JETCorrLevels).issubset(set(JECLevels)): 
		if ( 'CHS' in PUMethod ) or  ( 'Plain' in PUMethod ): JETCorrLevels = ['L1FastJet','L2Relative', 'L3Absolute']
		else: JETCorrLevels = [ 'L2Relative', 'L3Absolute']
		if runOnData: JETCorrLevels.append('L2L3Residual')
	if not set(subJETCorrLevels).issubset(set(JECLevels)): 
		if ( 'CHS' in PUMethod ) or  ( 'Plain' in PUMethod ): subJETCorrLevels = ['L1FastJet','L2Relative', 'L3Absolute']
		else: subJETCorrLevels = [ 'L2Relative', 'L3Absolute']
		if runOnData: subJETCorrLevels.append('L2L3Residual')

	####  Creating PATjets
	tmpPfCandName = pfCand.lower()
	if 'Puppi' in PUMethod:
		if ('puppi' in tmpPfCandName): 
			srcForPFJets = pfCand
			print '|---- jetToolBox: Not running puppi algorithm because keyword puppi was specified in nameNewPFCollection, but applying puppi corrections.' 
		else: 
			proc.load('CommonTools.PileupAlgos.Puppi_cff')
			puppi.candName = cms.InputTag( pfCand ) 
			if miniAOD: puppi.vertexName = cms.InputTag('offlineSlimmedPrimaryVertices')
			jetSeq += getattr(proc, 'puppi' )
			srcForPFJets = 'puppi'
		from RecoJets.JetProducers.ak4PFJetsPuppi_cfi import ak4PFJetsPuppi
		setattr( proc, jetalgo+'PFJetsPuppi', 
				ak4PFJetsPuppi.clone( src = cms.InputTag( srcForPFJets ),
					doAreaFastjet = True, 
					rParam = jetSize, 
					jetAlgorithm = algorithm ) )  
		jetSeq += getattr(proc, jetalgo+'PFJetsPuppi' )
		if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PFPuppi'
		if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PFPuppi'

	elif 'CS' in PUMethod:

		from RecoJets.JetProducers.ak4PFJetsCS_cfi import ak4PFJetsCS
		setattr( proc, jetalgo+'PFJetsCS', 
				ak4PFJetsCS.clone( doAreaFastjet = True, 
					csRParam = cms.double(jetSize),
					jetAlgorithm = algorithm ) ) 
		if miniAOD: getattr( proc, jetalgo+'PFJetsCS').src = pfCand
		#setattr( proc, jetalgo+'PFJetsCSConstituents', ak8PFJetsCSConstituents.clone( src = cms.InputTag(jetalgo+'PFJetsCS') ) )
		jetSeq += getattr(proc, jetalgo+'PFJetsCS' )

		#setattr( proc, jetalgo+'PFJetsCSConstituents', ak8PFJetsCSConstituents.clone( src = cms.InputTag(jetalgo+'PFJetsCS') ) )
		jetSeq += getattr(proc, jetalgo+'PFJetsCS' )
		if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PFCS'
		if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PFCS'

	elif 'SK' in PUMethod:

		if ('sk' in tmpPfCandName): 
			srcForPFJets = pfCand
			print '|---- jetToolBox: Not running softkiller algorithm because keyword SK was specified in nameNewPFCollection, but applying SK corrections.' 
		else:
			proc.load('CommonTools.PileupAlgos.softKiller_cfi')
			getattr( proc, 'softKiller' ).PFCandidates = cms.InputTag( pfCand ) 
			jetSeq += getattr(proc, 'softKiller' )
			srcForPFJets = 'softKiller'
		from RecoJets.JetProducers.ak4PFJetsSK_cfi import ak4PFJetsSK
		setattr( proc, jetalgo+'PFJetsSK', 
				ak4PFJetsSK.clone(  src = cms.InputTag( srcForPFJets ),
					rParam = jetSize, 
					jetAlgorithm = algorithm ) ) 
		jetSeq += getattr(proc, jetalgo+'PFJetsSK' )
		if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PFSK'
		if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PFSK'
	
	elif 'CHS' in PUMethod: 
		
		if miniAOD:
			if ('chs' in tmpPfCandName): 
				srcForPFJets = pfCand
				print '|---- jetToolBox: Not running CHS algorithm because keyword CHS was specified in nameNewPFCollection, but applying CHS corrections.' 
			else: 
				setattr( proc, 'chs', cms.EDFilter('CandPtrSelector', src = cms.InputTag( pfCand ), cut = cms.string('fromPV')) )
				jetSeq += getattr(proc, 'chs')
				srcForPFJets = 'chs'
		else:
			if ( pfCand == 'particleFlow' ):
				from RecoParticleFlow.PFProducer.particleFlowTmpPtrs_cfi import particleFlowTmpPtrs
				setattr( proc, 'newParticleFlowTmpPtrs', particleFlowTmpPtrs.clone( src = pfCand ) )
				jetSeq += getattr(proc, 'newParticleFlowTmpPtrs')
				from CommonTools.ParticleFlow.pfNoPileUpJME_cff import pfPileUpJME, pfNoPileUpJME
				proc.load('CommonTools.ParticleFlow.goodOfflinePrimaryVertices_cfi')
				setattr( proc, 'newPfPileUpJME', pfPileUpJME.clone( PFCandidates= 'newParticleFlowTmpPtrs' ) )
				jetSeq += getattr(proc, 'newPfPileUpJME')
				setattr( proc, 'newPfNoPileUpJME', pfNoPileUpJME.clone( topCollection='newPfPileUpJME', bottomCollection= 'newParticleFlowTmpPtrs' ) )
				jetSeq += getattr(proc, 'newPfNoPileUpJME')
				srcForPFJets = 'newPfNoPileUpJME'
			else: 
				proc.load('CommonTools.ParticleFlow.pfNoPileUpJME_cff')
				srcForPFJets = 'pfNoPileUpJME'
			

		setattr( proc, jetalgo+'PFJetsCHS', 
				ak4PFJetsCHS.clone( src = cms.InputTag( srcForPFJets ), 
					doAreaFastjet = True, 
					rParam = jetSize, 
					jetAlgorithm = algorithm ) ) 
		jetSeq += getattr(proc, jetalgo+'PFJetsCHS' )
		if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PFchs'
		if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PFchs'

	else: 
		PUMethod = ''
		setattr( proc, jetalgo+'PFJets', 
				ak4PFJets.clone( 
					doAreaFastjet = True, 
					rParam = jetSize, 
					jetAlgorithm = algorithm ) ) 
		if miniAOD: getattr( proc, jetalgo+'PFJets').src = pfCand
		jetSeq += getattr(proc, jetalgo+'PFJets' )
		if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PF'
		if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PF'

	if 'None' in JETCorrPayload: JEC = None
	else: JEC = ( JETCorrPayload.replace('CS','chs').replace('SK','chs') , JETCorrLevels, 'None' )   ### temporary
	#else: JEC = ( JETCorrPayload., JETCorrLevels, 'None' ) 
	print '|---- jetToolBox: Applying this corrections: '+str(JEC)

	if addPrunedSubjets or addSoftDropSubjets or addCMSTopTagger:
		if 'None' in subJETCorrPayload: subJEC = None
		else: subJEC = ( subJETCorrPayload.replace('CS','chs').replace('SK','chs') , subJETCorrLevels, 'None' )   ### temporary


	if ( 'CHS' in PUMethod ) and miniAOD: setattr( proc, jetalgo+'PFJets'+PUMethod+'Constituents', cms.EDFilter("MiniAODJetConstituentSelector", src = cms.InputTag( jetalgo+'PFJets'+PUMethod ), cut = cms.string( Cut ) ))
	else: setattr( proc, jetalgo+'PFJets'+PUMethod+'Constituents', cms.EDFilter("PFJetConstituentSelector", src = cms.InputTag( jetalgo+'PFJets'+PUMethod ), cut = cms.string( Cut ) ))
	jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'Constituents' )

	addJetCollection(
			proc,
			labelName = jetALGO+'PF'+PUMethod,
			jetSource = cms.InputTag( jetalgo+'PFJets'+PUMethod),
			algo = jetalgo,
			rParam = jetSize,
			jetCorrections = JEC if JEC is not None else None, 
			pfCandidates = cms.InputTag( pfCand ),  
			svSource = cms.InputTag( svLabel ),  
			genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNu'),
			pvSource = cms.InputTag( pvLabel ), 
			btagDiscriminators = bTagDiscriminators,
			getJetMCFlavour = GetJetMCFlavour,
			genParticles = cms.InputTag(genParticlesLabel),
			outputModules = ['outputFile']
			) 


	if 'CS' in PUMethod: getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod ).getJetMCFlavour = False  # CS jets cannot be re-clustered from their constituents
	
	#### Groomers
	if addSoftDrop or addSoftDropSubjets: 

		setattr( proc, jetalgo+'PFJets'+PUMethod+'SoftDrop', 
			ak8PFJetsCHSSoftDrop.clone( 
				src = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Constituents', 'constituents' ),
				rParam = jetSize, 
				jetAlgorithm = algorithm, 
				useExplicitGhosts=True,
				R0= cms.double(jetSize),
				#zcut=zCutSD, 
				beta=betaCut,
				writeCompound = cms.bool(True),
				jetCollInstanceName=cms.string('SubJets') ) )
		setattr( proc, jetalgo+'PFJets'+PUMethod+'SoftDropMass', 
			ak8PFJetsCHSSoftDropMass.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
				matched = cms.InputTag( jetalgo+'PFJets'+PUMethod+'SoftDrop'), 
				distMax = cms.double( jetSize ) ) )

		elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'SoftDropMass_*_*'] 
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'SoftDrop' )
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'SoftDropMass' )
		getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'SoftDropMass']
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'SoftDropMass' )

		if addSoftDropSubjets:

			if runOnMC:
				setattr( proc, jetalgo+'GenJetsNoNuSoftDrop',
						ak4GenJets.clone(
							SubJetParameters,
							useSoftDrop = cms.bool(True),
							rParam = jetSize, 
							jetAlgorithm = algorithm, 
							useExplicitGhosts=cms.bool(True),
							#zcut=cms.double(zCutSD), 
							R0= cms.double(jetSize),
							beta=cms.double(betaCut),
							writeCompound = cms.bool(True),
							jetCollInstanceName=cms.string('SubJets')
							))
				if miniAOD: getattr( proc, jetalgo+'GenJetsNoNuSoftDrop' ).src = 'packedGenParticlesForJetsNoNu'
				jetSeq += getattr(proc, jetalgo+'GenJetsNoNuSoftDrop' )

			addJetCollection(
					proc,
					labelName = jetALGO+'PF'+PUMethod+'SoftDrop',
					jetSource = cms.InputTag( jetalgo+'PFJets'+PUMethod+'SoftDrop'),
					algo = jetalgo,
					rParam = jetSize,
					jetCorrections = JEC if JEC is not None else None, 
					pvSource = cms.InputTag( pvLabel ),
					btagDiscriminators = ['None'],
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNu'),
					getJetMCFlavour = False, # jet flavor should always be disabled for groomed jets
					genParticles = cms.InputTag(genParticlesLabel),
					outputModules = ['outputFile']
					) 

			setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDrop', selectedPatJets.clone( src = 'patJets'+jetALGO+'PF'+PUMethod+'SoftDrop', cut = Cut ) )

			addJetCollection(
					proc,
					labelName = jetALGO+'PF'+PUMethod+'SoftDropSubjets',
					jetSource = cms.InputTag( jetalgo+'PFJets'+PUMethod+'SoftDrop', 'SubJets'),
					algo = jetalgo,  # needed for subjet b tagging
					rParam = jetSize,  # needed for subjet b tagging
					jetCorrections = subJEC if subJEC is not None else None, 
					pfCandidates = cms.InputTag( pfCand ), 
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ),  
					btagDiscriminators = bTagDiscriminators,
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNuSoftDrop','SubJets'),
					getJetMCFlavour = GetSubjetMCFlavour,
					genParticles = cms.InputTag(genParticlesLabel),
					explicitJTA = True,  # needed for subjet b tagging
					svClustering = True, # needed for subjet b tagging
					fatJets=cms.InputTag(jetalgo+'PFJets'+PUMethod),             # needed for subjet flavor clustering
					groomedFatJets=cms.InputTag(jetalgo+'PFJets'+PUMethod+'SoftDrop'), # needed for subjet flavor clustering
					outputModules = ['outputFile']
					) 

			setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropSubjets', selectedPatJets.clone( src = 'patJets'+jetALGO+'PF'+PUMethod+'SoftDropSubjets', cut = Cut ))

			## Establish references between PATified fat jets and subjets using the BoostedJetMerger
			setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropPacked', 
					cms.EDProducer("BoostedJetMerger",
						jetSrc=cms.InputTag('selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDrop'),
						subjetSrc=cms.InputTag('selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropSubjets')
						))
			jetSeq += getattr(proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropPacked' )
			elemToKeep += [ 'keep *_selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropPacked_*_*' ]
			toolsUsed.append( 'selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropPacked' )
			toolsUsed.append( 'selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropSubjets' )

	if addPruning or addPrunedSubjets: 

		setattr( proc, jetalgo+'PFJets'+PUMethod+'Pruned', 
			ak8PFJetsCHSPruned.clone( 
				src = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Constituents', 'constituents' ),
				rParam = jetSize, 
				jetAlgorithm = algorithm, 
				zcut=zCut, 
				rcut_factor=rCut,
				writeCompound = cms.bool(True),
				doAreaFastjet = cms.bool(True),
				jetCollInstanceName=cms.string('SubJets') ) )
		setattr( proc, jetalgo+'PFJets'+PUMethod+'PrunedMass', 
			ak8PFJetsCHSPrunedMass.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
				matched = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Pruned'), 
				distMax = cms.double( jetSize ) ) )

		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'Pruned' )
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'PrunedMass' )
		getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'PrunedMass']
		elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'PrunedMass_*_*'] 
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'PrunedMass' )

		if addPrunedSubjets:
			if runOnMC:
				setattr( proc, jetalgo+'GenJetsNoNuPruned',
						ak4GenJets.clone(
							SubJetParameters,
							rParam = jetSize,
							usePruning = cms.bool(True),
							writeCompound = cms.bool(True),
							jetCollInstanceName=cms.string('SubJets')
							))
				if miniAOD: getattr( proc, jetalgo+'GenJetsNoNuPruned' ).src = 'packedGenParticlesForJetsNoNu'
				jetSeq += getattr(proc, jetalgo+'GenJetsNoNuPruned' )

			addJetCollection(
					proc,
					labelName = jetALGO+'PF'+PUMethod+'Pruned',
					jetSource = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Pruned'),
					algo = jetalgo,
					rParam = jetSize,
					jetCorrections = JEC if JEC is not None else None, 
					pvSource = cms.InputTag( pvLabel ),
					btagDiscriminators = ['None'],
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNu'),
					getJetMCFlavour = False, # jet flavor should always be disabled for groomed jets
					genParticles = cms.InputTag(genParticlesLabel),
					outputModules = ['outputFile']
					) 

			setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'Pruned', selectedPatJets.clone( src = 'patJets'+jetALGO+'PF'+PUMethod+'Pruned', cut = Cut ) )

			addJetCollection(
					proc,
					labelName = jetALGO+'PF'+PUMethod+'PrunedSubjets',
					jetSource = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Pruned', 'SubJets'),
					algo = jetalgo,  # needed for subjet b tagging
					rParam = jetSize,  # needed for subjet b tagging
					jetCorrections = subJEC if subJEC is not None else None, 
					pfCandidates = cms.InputTag( pfCand ),  
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ), 
					getJetMCFlavour = GetSubjetMCFlavour,
					genParticles = cms.InputTag(genParticlesLabel),
					btagDiscriminators = bTagDiscriminators,
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNuPruned','SubJets'),
					explicitJTA = True,  # needed for subjet b tagging
					svClustering = True, # needed for subjet b tagging
					fatJets=cms.InputTag(jetalgo+'PFJets'+PUMethod),             # needed for subjet flavor clustering
					groomedFatJets=cms.InputTag(jetalgo+'PFJets'+PUMethod+'Pruned'), # needed for subjet flavor clustering
					outputModules = ['outputFile']
					) 

			setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedSubjets', selectedPatJets.clone( src = 'patJets'+jetALGO+'PF'+PUMethod+'PrunedSubjets', cut = Cut ) )

			## Establish references between PATified fat jets and subjets using the BoostedJetMerger
			setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedPacked', 
					cms.EDProducer("BoostedJetMerger",
						jetSrc=cms.InputTag('selectedPatJets'+jetALGO+'PF'+PUMethod+'Pruned'),
						subjetSrc=cms.InputTag('selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedSubjets')
						))
			jetSeq += getattr(proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedPacked' )
			elemToKeep += [ 'keep *_selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedPacked_*_*' ]
			toolsUsed.append( 'selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedPacked' )
			toolsUsed.append( 'selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedSubjets' )


	if addTrimming:

		setattr( proc, jetalgo+'PFJets'+PUMethod+'Trimmed', 
				ak8PFJetsCHSTrimmed.clone( 
					rParam = jetSize, 
					src = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Constituents', 'constituents'),
					jetAlgorithm = algorithm,
					rFilt= rFiltTrim,
					trimPtFracMin= ptFrac) ) 
		setattr( proc, jetalgo+'PFJets'+PUMethod+'TrimmedMass', 
				ak8PFJetsCHSTrimmedMass.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
					matched = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Trimmed'), 
					distMax = cms.double( jetSize ) ) )

		elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'TrimmedMass_*_*'] 
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'Trimmed' )
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'TrimmedMass' )
		getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'TrimmedMass']
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'TrimmedMass' )

	if addFiltering:

		setattr( proc, jetalgo+'PFJets'+PUMethod+'Filtered', 
				ak8PFJetsCHSFiltered.clone( 
					src = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Constituents', 'constituents' ),
					rParam = jetSize, 
					jetAlgorithm = algorithm,
					rFilt= rfilt,
					nFilt= nfilt ) ) 
		setattr( proc, jetalgo+'PFJets'+PUMethod+'FilteredMass', 
				ak8PFJetsCHSFilteredMass.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
					matched = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Filtered'), 
					distMax = cms.double( jetSize ) ) )
		elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'FilteredMass_*_*'] 
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'Filtered' )
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'FilteredMass' )
		getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'FilteredMass']
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'FilteredMass' )

	if addCMSTopTagger :

		if 'CA' in jetALGO : 

			setattr( proc, 'cmsTopTagPFJets'+PUMethod,  
					cms.EDProducer("CATopJetProducer",
						PFJetParameters.clone( 
							src = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Constituents', 'constituents' ),
							doAreaFastjet = cms.bool(True),
							doRhoFastjet = cms.bool(False),
							jetPtMin = cms.double(100.0)
							),
						AnomalousCellParameters,
						CATopJetParameters.clone( jetCollInstanceName = cms.string("SubJets"),
							verbose = cms.bool(False),
							algorithm = cms.int32(1), # 0 = KT, 1 = CA, 2 = anti-KT
							tagAlgo = cms.int32(0), #0=legacy top
							useAdjacency = cms.int32(2), # modified adjacency
							centralEtaCut = cms.double(2.5), # eta for defining "central" jets
							sumEtBins = cms.vdouble(0,1600,2600), # sumEt bins over which cuts vary. vector={bin 0 lower bound, bin 1 lower bound, ...}
							rBins = cms.vdouble(0.8,0.8,0.8), # Jet distance paramter R. R values depend on sumEt bins.
							ptFracBins = cms.vdouble(0.05,0.05,0.05), # minimum fraction of central jet pt for subjets (deltap)
							deltarBins = cms.vdouble(0.19,0.19,0.19), # Applicable only if useAdjacency=1. deltar adjacency values for each sumEtBin
							nCellBins = cms.vdouble(1.9,1.9,1.9),
							),
						jetAlgorithm = cms.string("CambridgeAachen"),
						rParam = cms.double(jetSize),
						writeCompound = cms.bool(True)
						)
					)
			
			setattr( proc, "CATopTagInfos", 
					cms.EDProducer("CATopJetTagger",
						src = cms.InputTag('cmsTopTagPFJets'+PUMethod),
						TopMass = cms.double(171),
						TopMassMin = cms.double(0.),
						TopMassMax = cms.double(250.),
						WMass = cms.double(80.4),
						WMassMin = cms.double(0.0),
						WMassMax = cms.double(200.0),
						MinMassMin = cms.double(0.0),
						MinMassMax = cms.double(200.0),
						verbose = cms.bool(False)
						)
					)
			addJetCollection(
					proc,
					labelName = 'CMSTopTag'+PUMethod,
					jetSource = cms.InputTag('cmsTopTagPFJets'+PUMethod),
					jetCorrections = JEC if JEC is not None else None, 
					pfCandidates = cms.InputTag( pfCand ),  
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ), 
					btagDiscriminators = bTagDiscriminators,
					genJetCollection = cms.InputTag(jetalgo+'GenJetsNoNu'),
					getJetMCFlavour = False, # jet flavor should always be disabled for groomed jets
					genParticles = cms.InputTag(genParticlesLabel)
					)
			getattr(proc,'patJetsCMSTopTag'+PUMethod).addTagInfos = True
			getattr(proc,'patJetsCMSTopTag'+PUMethod).tagInfoSources = cms.VInputTag( cms.InputTag('CATopTagInfos'))
			setattr( proc, 'selectedPatJetsCMSTopTag'+PUMethod, selectedPatJets.clone( src = 'patJetsCMSTopTag'+PUMethod, cut = Cut ) )

			addJetCollection(
					proc,
					labelName = 'CMSTopTag'+PUMethod+'Subjets',
					jetSource = cms.InputTag('cmsTopTagPFJets'+PUMethod, 'SubJets'),
					algo = jetalgo,  # needed for subjet b tagging
					rParam = jetSize,  # needed for subjet b tagging
					jetCorrections = subJEC if subJEC is not None else None, 
					pfCandidates = cms.InputTag( pfCand ),  
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ), 
					btagDiscriminators = bTagDiscriminators,
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNu'),
					getJetMCFlavour = GetSubjetMCFlavour,
					explicitJTA = True,  # needed for subjet b tagging
					svClustering = True, # needed for subjet b tagging
					fatJets=cms.InputTag(jetalgo+'PFJets'+PUMethod),             # needed for subjet flavor clustering
					groomedFatJets=cms.InputTag('patJetsCMSTopTag'+PUMethod), # needed for subjet flavor clustering
					genParticles = cms.InputTag(genParticlesLabel)
					)

			setattr( proc, 'selectedPatJetsCMSTopTag'+PUMethod+'Subjets', selectedPatJets.clone( src = 'patJetsCMSTopTag'+PUMethod+'Subjets', cut = Cut ) )

			setattr( proc, 'patJetsCMSTopTag'+PUMethod+'Packed', 
					cms.EDProducer("BoostedJetMerger",
						jetSrc=cms.InputTag('patJetsCMSTopTag'+PUMethod ),
						subjetSrc=cms.InputTag('patJetsCMSTopTag'+PUMethod+'Subjets')
						))
			jetSeq += getattr(proc, 'patJetsCMSTopTag'+PUMethod+'Packed' )
			elemToKeep += [ 'keep *_patJetsCMSTopTag'+PUMethod+'Packed_*_*' ]
			toolsUsed.append( 'patJetsCMSTopTag'+PUMethod+'Packed' )

		else: print '|---- jetToolBox: CMS recommends CambridgeAachen for CMS Top Tagger, you are using '+algorithm+'. JetToolbox will not run CMS Top Tagger.'

	if addMassDrop :

		if 'CA' in jetALGO : 
			setattr( proc, jetalgo+'PFJets'+PUMethod+'MassDropFiltered', 
					ca15PFJetsCHSMassDropFiltered.clone( 
						rParam = jetSize,
						src = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Constituents', 'constituents' ),
						) )
			setattr( proc, jetalgo+'PFJets'+PUMethod+'MassDropFilteredMass', ak8PFJetsCHSPrunedMass.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
				matched = cms.InputTag(jetalgo+'PFJets'+PUMethod+'MassDropFiltered'), distMax = cms.double( jetSize ) ) )
			elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'MassDropFilteredMass_*_*' ]
			getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'MassDropFilteredMass' ]
			jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'MassDropFiltered' )
			jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'MassDropFilteredMass' )
		else: print '|---- jetToolBox: CMS recommends CambridgeAachen for Mass Drop, you are using '+algorithm+'. JetToolbox will not run Mass Drop.'
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'MassDropFilteredMass' )

	if addHEPTopTagger: 
		if ( jetSize >= 1. ) and ( 'CA' in jetALGO ): 

			setattr( proc, 'hepTopTagPFJets'+PUMethod, hepTopTagPFJetsCHS.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Constituents', 'constituents' ) ) )
			setattr( proc, 'hepTopTagPFJets'+PUMethod+'Mass'+jetALGO, ak8PFJetsCHSPrunedMass.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
				matched = cms.InputTag("hepTopTagPFJets"+PUMethod), distMax = cms.double( jetSize ) ) )
			elemToKeep += [ 'keep *_hepTopTagPFJets'+PUMethod+'Mass'+jetALGO+'_*_*' ]
			getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ 'hepTopTagPFJets'+PUMethod+'Mass'+jetALGO ]
			jetSeq += getattr(proc, 'hepTopTagPFJets'+PUMethod )
			jetSeq += getattr(proc, 'hepTopTagPFJets'+PUMethod+'Mass'+jetALGO )
			toolsUsed.append( 'hepTopTagPFJets'+PUMethod+'Mass'+jetALGO )
		else: print '|---- jetToolBox: CMS recommends CambridgeAachen for HEPTopTagger, you are using '+algorithm+', and a jet cone size bigger than 1. JetToolbox will not run HEP TopTagger.'

	####### Nsubjettiness
	if addNsub:
		from RecoJets.JetProducers.nJettinessAdder_cfi import Njettiness

		rangeTau = range(1,maxTau+1)
		setattr( proc, 'Njettiness'+jetALGO+PUMethod, 
				Njettiness.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
					Njets=cms.vuint32(rangeTau),         # compute 1-, 2-, 3-, 4- subjettiness
					# variables for measure definition : 
					measureDefinition = cms.uint32( 0 ), # CMS default is normalized measure
					beta = cms.double(1.0),              # CMS default is 1
					R0 = cms.double( jetSize ),              # CMS default is jet cone size
					Rcutoff = cms.double( -999.0),       # not used by default
					# variables for axes definition :
					axesDefinition = cms.uint32( 6 ),    # CMS default is 1-pass KT axes
					nPass = cms.int32(-999),             # not used by default
					akAxesR0 = cms.double(-999.0) ) )        # not used by default

		elemToKeep += [ 'keep *_Njettiness'+jetALGO+PUMethod+'_*_*' ]
		for tau in rangeTau: getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += ['Njettiness'+jetALGO+PUMethod+':tau'+str(tau) ] 
		jetSeq += getattr(proc, 'Njettiness'+jetALGO+PUMethod )
		toolsUsed.append( 'Njettiness'+jetALGO+PUMethod )

	###### QJetsAdder
	'''
	if addQJets:
		### there must be a better way to do this random number introduction
		setattr( proc, 'RandomNumberGeneratorService', cms.Service("RandomNumberGeneratorService", 
							QJetsAdderCA8 = cms.PSet(initialSeed = cms.untracked.uint32(7)),
							QJetsAdderAK8 = cms.PSet(initialSeed = cms.untracked.uint32(31)),
							QJetsAdderCA15 = cms.PSet(initialSeed = cms.untracked.uint32(76)), ) )

		from RecoJets.JetProducers.qjetsadder_cfi import QJetsAdder
		setattr( proc, 'QJetsAdder'+jetALGO, 
				QJetsAdder.clone( src = cms.InputTag(jetalgo+'PFJets'+PUMethod), 
					jetRad = cms.double( jetSize ), 
					jetAlgo = cms.string( jetALGO[0:2] )))
		elemToKeep += [ 'keep *_QJetsAdder'+jetALGO+'_*_*' ]
		getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += ['QJetsAdder'+jetALGO+':QjetsVolatility']  
		jetSeq += getattr(proc, 'QJetsAdder'+jetALGO )
		toolsUsed.append( 'QJetsAdder'+jetALGO )
	'''

	###### QGTagger
	if addQGTagger:
		if ( 'ak4' in jetalgo ) and ( PUMethod not in ['Puppi','CS','SK'] ) :
			from RecoJets.JetProducers.QGTagger_cfi import QGTagger
			proc.load('RecoJets.JetProducers.QGTagger_cfi') 	## In 74X you need to run some stuff before.
			setattr( proc, 'QGTagger'+jetALGO+'PF'+PUMethod, 
					QGTagger.clone(
						srcJets = cms.InputTag(jetalgo+'PFJets'+PUMethod),    # Could be reco::PFJetCollection or pat::JetCollection (both AOD and miniAOD)
						jetsLabel = cms.string('QGL_AK4PF'+QGjetsLabel)        # Other options (might need to add an ESSource for it): see https://twiki.cern.ch/twiki/bin/viewauth/CMS/QGDataBaseVersion
						)
					)
			elemToKeep += [ 'keep *_QGTagger'+jetALGO+'PF'+PUMethod+'_*_*' ]
			getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += ['QGTagger'+jetALGO+'PF'+PUMethod+':qgLikelihood']  
			jetSeq += getattr(proc, 'QGTagger'+jetALGO+'PF'+PUMethod )

                        toolsUsed.append( 'QGTagger'+jetALGO+'PF'+PUMethod )
		else:
			print '|---- jetToolBox: QGTagger is optimized for ak4 jets with CHS. NOT running QGTagger'

			
	####### Pileup JetID
        if addPUJetID:
                if ( 'ak4' in jetalgo ) and ( 'CHS' in PUMethod ):
                        from RecoJets.JetProducers.pileupjetidproducer_cfi import pileupJetIdCalculator,pileupJetIdEvaluator

			setattr( proc, jetALGO+'PF'+PUMethod+'pileupJetIdCalculator',
					pileupJetIdCalculator.clone(
						jets = cms.InputTag(jetalgo+'PFJets'+PUMethod),
						rho = cms.InputTag("fixedGridRhoFastjetAll"),
						vertexes = cms.InputTag(pvLabel),
						applyJec = cms.bool(True),
						inputIsCorrected = cms.bool(False)
						))

			setattr( proc, jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator',
					pileupJetIdEvaluator.clone(
						jetids = cms.InputTag(jetALGO+'PF'+PUMethod+'pileupJetIdCalculator'),
						jets = cms.InputTag(jetalgo+'PFJets'+PUMethod),
						rho = cms.InputTag("fixedGridRhoFastjetAll"),
						vertexes = cms.InputTag(pvLabel)
						)
					)

                        getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator:fullDiscriminant']
                        getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userInts.src += [jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator:cutbasedId',jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator:fullId']
                        elemToKeep += ['keep *_'+jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator_*_*']
                        toolsUsed.append( jetALGO+'PF'+PUMethod+'pileupJetIdEvaluator' )
		else:
                        print '|---- jetToolBox: PUJetID is optimized for ak4 PFjets with CHS. NOT running PUJetID.'

	###### Energy Correlation Functions
	if addEnergyCorrFunc:
		from RecoJets.JetProducers.ECF_cfi import ECF 
		rangeECF = range(1,maxECF+1)
		setattr( proc, jetalgo+'PFJets'+PUMethod+'ECF', ECF.clone(
				src = cms.InputTag(jetalgo+'PFJets'+PUMethod),
				Njets = cms.vuint32( rangeECF ),
				beta = cms.double( ecfBeta ) 
				))

		elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'ECF_*_*'] 
		for ecf in rangeECF: getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'ECF:ecf'+str(ecf) ]
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'ECF' )
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'ECF' )
	
	if hasattr(proc, 'patJetPartons'): proc.patJetPartons.particles = genParticlesLabel


	setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod, selectedPatJets.clone( src = 'patJets'+jetALGO+'PF'+PUMethod, cut = Cut ) )
	elemToKeep += [ 'keep *_selectedPatJets'+jetALGO+'PF'+PUMethod+'_*_*' ]
	elemToKeep += [ 'drop *_selectedPatJets'+jetALGO+'PF'+PUMethod+'_calo*_*' ]
	elemToKeep += [ 'drop *_selectedPatJets'+jetALGO+'PF'+PUMethod+'_tagInfos_*' ]


	if len(toolsUsed) > 0 : print '|---- jetToolBox: Running '+', '.join(toolsUsed)+'.'
	print '|---- jetToolBox: Creating selectedPatJets'+jetALGO+'PF'+PUMethod+' collection.'

	### "return"
	setattr(proc, jetSequence, jetSeq)
	if hasattr(proc, outputFile): getattr(proc, outputFile).outputCommands += elemToKeep
	else: setattr( proc, outputFile, 
			cms.OutputModule('PoolOutputModule', 
				fileName = cms.untracked.string('jettoolbox.root'), 
				outputCommands = cms.untracked.vstring( elemToKeep ) ) )

	if runOnData:
		from PhysicsTools.PatAlgos.tools.coreTools import removeMCMatching
		removeMCMatching(proc, names=['Jets'], outputModules=[outputFile])
Beispiel #9
0
def jetToolbox( proc, jetType, jetSequence, outputFile, 
		PUMethod='CHS',                    #### Options: Puppi, CS, SK, Plain
		JETCorrPayload='None', JETCorrLevels = [ 'None' ],
		subJETCorrPayload='None', subJETCorrLevels = [ 'None' ],
		miniAOD=True,
		Cut = '', 
		addPruning=False, zCut=0.1, rCut=0.5, addPrunedSubjets=False,
		addSoftDrop=False, betaCut=0.0,  zCutSD=0.1, addSoftDropSubjets=False,
		addTrimming=False, rFiltTrim=0.2, ptFrac=0.03,
		addFiltering=False, rfilt=0.3, nfilt=3,
		addCMSTopTagger=False,
		addMassDrop=False,
		addHEPTopTagger=False,
		addNsub=False, maxTau=4, 
		addQJets=False 
		):
	
	###############################################################################
	#######  Verifying some inputs and defining variables
	###############################################################################
	print '|---- jetToolbox: Initialyzing...'
	supportedJetAlgos = { 'ak': 'AntiKt', 'ca' : 'CambridgeAachen', 'kt' : 'Kt' }
	recommendedJetAlgos = [ 'ak4', 'ak8', 'ca4', 'ca8', 'ca10' ]
	payloadList = [ 'AK1PFchs', 'AK2PFchs', 'AK3PFchs', 'AK4PFchs', 'AK5PFchs', 'AK6PFchs', 'AK7PFchs', 'AK8PFchs', 'AK9PFchs', 'AK10PFchs' ]
	JECLevels = [ 'L1Offset', 'L1FastJet', 'L1JPTOffset', 'L2Relative', 'L3Absolute', 'L5Falvour', 'L7Parton' ]
	jetAlgo = ''
	algorithm = ''
	size = ''
	for type, tmpAlgo in supportedJetAlgos.iteritems(): 
		if type in jetType.lower():
			jetAlgo = type
			algorithm = tmpAlgo
			size = jetType.replace( type, '' )

	jetSize = 0.
	if int(size) in range(0, 20): jetSize = int(size)/10.
	else: print '|---- jetToolBox: jetSize has not a valid value. Insert a number between 1 and 20 after algorithm, like: AK8'
	### Trick for uppercase/lowercase algo name
	jetALGO = jetAlgo.upper()+size
	jetalgo = jetAlgo.lower()+size
	if jetalgo not in recommendedJetAlgos: print '|---- jetToolBox: CMS recommends the following jet algoritms: '+' '.join(recommendedJetAlgos)+'. You are using', jetalgo,'.'

	if JETCorrPayload not in payloadList:
		if( int(size) > 10 ): 
			size = '10' 
			print '|---- jetToolbox: For jets bigger than 1.0, the jet corrections are AK10PFchs.'
		if not 'None' in JETCorrPayload: print '|---- jetToolBox: Payload given for Jet corrections ('+JETCorrPayload+') is not correct. Using a default AK'+size+'PFchs instead.'
		JETCorrPayload = 'AK'+size+'PFchs'
	else: print '|---- jetToolBox: Using '+JETCorrPayload+' payload for jet corrections.'

	if not set(JETCorrLevels).issubset(set(JECLevels)) :
		if not 'None' in JETCorrLevels: print '|---- jetToolbox: JEC levels given ( '+' '.join(JETCorrLevels)+' ) are incorrect. Using the default levels: L1FastJet, L2Relative, L3Absolute.'
		JETCorrLevels = ['L1FastJet', 'L2Relative', 'L3Absolute']
	
	print '|---- jetToolBox: Applying these jet corrections: ( '+JETCorrPayload+', '+' '.join(JETCorrLevels)+' )'
	JEC = ( JETCorrPayload, JETCorrLevels , 'None')

	if addPrunedSubjets or addSoftDropSubjets or addCMSTopTagger:
		if subJETCorrPayload not in payloadList: 
			if not 'None' in subJETCorrPayload: print '|---- jetToolBox: Payload given for subjet corrections ('+JETCorrPayload+') is not correct. Using default AK4PFchs instead.'
			subJETCorrPayload = 'AK4PFchs'
		if not set(subJETCorrLevels).issubset(set(JECLevels)) or not subJETCorrLevels:
			if not 'None' in subJETCorrLevels: print '|---- jetToolbox: Subjet JEC levels given ( '+' '.join(subJETCorrLevels)+' ) are incorrect. Using the default levels: L1FastJet, L2Relative, L3Absolute.'
			subJETCorrLevels = ['L1FastJet', 'L2Relative', 'L3Absolute']
		print '|---- jetToolBox: Applying these subjet corrections: ( '+subJETCorrPayload+', '+' '.join(subJETCorrLevels)+' )'
		subJEC = ( subJETCorrPayload, subJETCorrLevels , 'None')


	#################################################################################
	####### Toolbox start 
	#################################################################################

	elemToKeep = []
	jetSeq = cms.Sequence()
	genParticlesLabel = ''
	pvLabel = ''
	tvLabel = ''
	toolsUsed = []

	#### For MiniAOD
	if miniAOD:

		print '|---- jetToolBox: JETTOOLBOX RUNNING ON MiniAOD FOR '+jetALGO+' JETS USING '+PUMethod

		genParticlesLabel = 'prunedGenParticles'
		pvLabel = 'offlineSlimmedPrimaryVertices'
		svLabel = 'slimmedSecondaryVertices'
		tvLabel = 'unpackedTracksAndVertices'
		pfCand = 'packedPFCandidates'

		setattr( proc, 'chs', cms.EDFilter('CandPtrSelector', src = cms.InputTag('packedPFCandidates'), cut = cms.string('fromPV')) )
		jetSeq += getattr(proc, 'chs')


		## Filter out neutrinos from packed GenParticles
		setattr( proc, 'packedGenParticlesForJetsNoNu', 
				cms.EDFilter("CandPtrSelector", 
					src = cms.InputTag("packedGenParticles"), 
					cut = cms.string("abs(pdgId) != 12 && abs(pdgId) != 14 && abs(pdgId) != 16")
					))
		jetSeq += getattr(proc, 'packedGenParticlesForJetsNoNu' )
		    
		setattr( proc, jetalgo+'GenJetsNoNu', 
				ak4GenJets.clone( src = 'packedGenParticlesForJetsNoNu', 
					rParam = jetSize, 
					jetAlgorithm = algorithm ) ) 
		jetSeq += getattr(proc, jetalgo+'GenJetsNoNu' )
		#fixedGridRhoFastjetAll.pfCandidatesTag = 'packedPFCandidates'

		#for Inclusive Vertex Finder
		proc.load('PhysicsTools.PatAlgos.slimming.unpackedTracksAndVertices_cfi')

	#### For AOD
	else:
		print '|---- jetToolBox: JETTOOLBOX RUNNING ON AOD FOR '+jetALGO+' JETS USING '+PUMethod

		genParticlesLabel = 'genParticles'
		pvLabel = 'offlinePrimaryVertices'
		tvLabel = 'generalTracks'
		pfCand = 'particleFlow'
		svLabel = 'inclusiveSecondaryVertices'

		proc.load('RecoJets.Configuration.GenJetParticles_cff')
		proc.load('CommonTools.ParticleFlow.pfNoPileUpJME_cff')
		setattr( proc, jetalgo+'GenJetsNoNu', ak4GenJets.clone( src = 'genParticlesForJetsNoNu', rParam = jetSize, jetAlgorithm = algorithm ) ) 
		jetSeq += getattr(proc, jetalgo+'GenJetsNoNu' )
		
		

	## b-tag discriminators
	bTagDiscriminators = [
			'pfTrackCountingHighEffBJetTags',
			'pfTrackCountingHighPurBJetTags',
			'pfJetProbabilityBJetTags',
			'pfJetBProbabilityBJetTags',
			'pfSimpleSecondaryVertexHighEffBJetTags',
			'pfSimpleSecondaryVertexHighPurBJetTags',
			'pfCombinedSecondaryVertexBJetTags',
			'pfCombinedInclusiveSecondaryVertexV2BJetTags'
	    ]

	####  Creating PATjets
	if 'Puppi' in PUMethod:

		proc.load('CommonTools.PileupAlgos.Puppi_cff')
		from RecoJets.JetProducers.ak4PFJetsPuppi_cfi import ak4PFJetsPuppi
		setattr( proc, jetalgo+'PFJetsPuppi', 
				ak4PFJetsPuppi.clone( doAreaFastjet = True, 
					rParam = jetSize, 
					jetAlgorithm = algorithm ) )  
		if miniAOD:
			puppi.candName = cms.InputTag('packedPFCandidates')
			puppi.vertexName = cms.InputTag('offlineSlimmedPrimaryVertices')
		jetSeq += getattr(proc, 'puppi' )
		jetSeq += getattr(proc, jetalgo+'PFJetsPuppi' )

	elif 'CS' in PUMethod:

		from RecoJets.JetProducers.ak4PFJetsCS_cfi import ak4PFJetsCS
		setattr( proc, jetalgo+'PFJetsCS', 
				ak4PFJetsCS.clone( doAreaFastjet = True, 
					csRParam = cms.double(jetSize),
					jetAlgorithm = algorithm ) ) 
		if miniAOD: getattr( proc, jetalgo+'PFJetsCS').src = 'chs'
		jetSeq += getattr(proc, jetalgo+'PFJetsCS' )

		#setattr( proc, jetalgo+'PFJetsCSConstituents', ak8PFJetsCSConstituents.clone( src = cms.InputTag(jetalgo+'PFJetsCS') ) )
		jetSeq += getattr(proc, jetalgo+'PFJetsCS' )

	elif 'SK' in PUMethod:

		proc.load('CommonTools.PileupAlgos.softKiller_cfi')
		from RecoJets.JetProducers.ak4PFJetsSK_cfi import ak4PFJetsSK
		setattr( proc, jetalgo+'PFJetsSK', 
				ak4PFJetsSK.clone( rParam = jetSize, 
					jetAlgorithm = algorithm ) ) 
		if miniAOD: getattr( proc, 'softKiller' ).PFCandidates = cms.InputTag('packedPFCandidates')
		jetSeq += getattr(proc, 'softKiller' )
		jetSeq += getattr(proc, jetalgo+'PFJetsSK' )
	
	elif 'CHS' in PUMethod: 
		setattr( proc, jetalgo+'PFJetsCHS', 
				ak4PFJetsCHS.clone( 
					doAreaFastjet = True, 
					rParam = jetSize, 
					jetAlgorithm = algorithm ) ) 
		if miniAOD: getattr( proc, jetalgo+'PFJetsCHS').src = 'chs'
		jetSeq += getattr(proc, jetalgo+'PFJetsCHS' )
	else: 
		PUMethod = ''
		setattr( proc, jetalgo+'PFJets', 
				ak4PFJets.clone( 
					doAreaFastjet = True, 
					rParam = jetSize, 
					jetAlgorithm = algorithm ) ) 
		if miniAOD: getattr( proc, jetalgo+'PFJets').src = 'packedPFCandidates'
		jetSeq += getattr(proc, jetalgo+'PFJets' )

	#if miniAOD: setattr( proc, jetalgo+'PFJets'+PUMethod+'Constituents', cms.EDFilter("MiniAODJetConstituentSelector", src = cms.InputTag( jetalgo+'PFJets'+PUMethod ), cut = cms.string( 'pt > 100.0 ' ) ))
	#else: setattr( proc, jetalgo+'PFJets'+PUMethod+'Constituents', cms.EDFilter("PFJetConstituentSelector", src = cms.InputTag( jetalgo+'PFJets'+PUMethod ), cut = cms.string( Cut ) ))
	#jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'Constituents' )

	addJetCollection(
			proc,
			labelName = jetALGO+'PF'+PUMethod,
			jetSource = cms.InputTag( jetalgo+'PFJets'+PUMethod),
			algo = jetalgo,
			rParam = jetSize,
			jetCorrections = JEC, #( 'AK'+size+'PFchs', cms.vstring( ['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
			pfCandidates = cms.InputTag( pfCand ),  #'packedPFCandidates'),
			svSource = cms.InputTag( svLabel ),   #'slimmedSecondaryVertices'),
			genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNu'),
			pvSource = cms.InputTag( pvLabel ), #'offlineSlimmedPrimaryVertices'),
			btagDiscriminators = bTagDiscriminators,
			outputModules = ['outputFile']
			) 

	getattr( proc, 'patJetCorrFactors'+jetALGO+'PF'+PUMethod ).primaryVertices = pvLabel  #'offlineSlimmedPrimaryVertices' 
	getattr( proc, 'jetTracksAssociatorAtVertex'+jetALGO+'PF'+PUMethod ).tracks = tvLabel  # 'unpackedTracksAndVertices'

	if 'CS' in PUMethod: getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod ).getJetMCFlavour = False  
	else: getattr(proc,'patJetPartons').particles = cms.InputTag( genParticlesLabel ) #'prunedGenParticles')
	getattr(proc,'patJetPartonMatch'+jetALGO+'PF'+PUMethod).matched = cms.InputTag( genParticlesLabel ) #'prunedGenParticles')
	if miniAOD:
		if hasattr(proc,'pfInclusiveSecondaryVertexFinderTagInfos'+jetALGO+'PF'+PUMethod):
			    getattr(proc,'pfInclusiveSecondaryVertexFinderTagInfos'+jetALGO+'PF'+PUMethod).extSVCollection = cms.InputTag( svLabel ) #'slimmedSecondaryVertices')
		getattr(proc,'patJets'+jetALGO+'PF'+PUMethod).addAssociatedTracks = cms.bool(False) # needs to be disabled since there is no track collection present in MiniAOD
		getattr(proc,'patJets'+jetALGO+'PF'+PUMethod).addJetCharge = cms.bool(False)        # needs to be disabled since there is no track collection present in MiniAOD
	

	if addSoftDrop or addSoftDropSubjets: 

		setattr( proc, jetalgo+'PFJets'+PUMethod+'SoftDrop', 
			ak8PFJetsCHSSoftDrop.clone( 
				rParam = jetSize, 
				jetAlgorithm = algorithm, 
				useExplicitGhosts=True,
				zcut=zCutSD, 
				beta=betaCut,
				writeCompound = cms.bool(True),
				jetCollInstanceName=cms.string('SubJets') ) )
		if miniAOD: getattr( proc, jetalgo+'PFJets'+PUMethod+'SoftDrop').src = 'chs'
		setattr( proc, jetalgo+'PFJets'+PUMethod+'SoftDropLinks', 
			ak8PFJetsCHSSoftDropLinks.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
				matched = cms.InputTag( jetalgo+'PFJets'+PUMethod+'SoftDrop'), 
				distMax = cms.double( jetSize ) ) )

		elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'SoftDropLinks_*_*'] 
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'SoftDrop' )
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'SoftDropLinks' )
		getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'SoftDropLinks']
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'SoftDropLinks' )

		if addSoftDropSubjets:

			setattr( proc, jetalgo+'GenJetsNoNuSoftDrop',
					ak4GenJets.clone(
						SubJetParameters,
						useSoftDrop = cms.bool(True),
						rParam = jetSize, 
						jetAlgorithm = algorithm, 
						useExplicitGhosts=cms.bool(True),
						#zcut=cms.double(zCutSD), 
						beta=cms.double(betaCut),
						writeCompound = cms.bool(True),
						jetCollInstanceName=cms.string('SubJets')
						))
			if miniAOD: getattr( proc, jetalgo+'GenJetsNoNuSoftDrop' ).src = 'packedGenParticlesForJetsNoNu'
			jetSeq += getattr(proc, jetalgo+'GenJetsNoNuSoftDrop' )

			addJetCollection(
					proc,
					labelName = jetALGO+'PF'+PUMethod+'SoftDrop',
					jetSource = cms.InputTag( jetalgo+'PFJets'+PUMethod+'SoftDrop'),
					algo = jetalgo,
					rParam = jetSize,
					jetCorrections = JEC,
					btagDiscriminators = ['None'],
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNu'),
					getJetMCFlavour = False,
					outputModules = ['outputFile']
					) 
			getattr( proc, 'patJetCorrFactors'+jetALGO+'PF'+PUMethod+'SoftDrop' ).primaryVertices = pvLabel  #'offlineSlimmedPrimaryVertices' 
			getattr(proc,'patJetPartonMatch'+jetALGO+'PF'+PUMethod+'SoftDrop').matched = cms.InputTag( genParticlesLabel ) #'prunedGenParticles')
			setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDrop', selectedPatJets.clone( src = 'patJets'+jetALGO+'PF'+PUMethod+'SoftDrop', cut = Cut ) )

			addJetCollection(
					proc,
					labelName = jetALGO+'PF'+PUMethod+'SoftDropSubjets',
					jetSource = cms.InputTag( jetalgo+'PFJets'+PUMethod+'SoftDrop', 'SubJets'),
					algo = jetalgo,  # needed for subjet b tagging
					rParam = jetSize,  # needed for subjet b tagging
					jetCorrections = subJEC, 
					pfCandidates = cms.InputTag( pfCand ), 
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ),  
					btagDiscriminators = bTagDiscriminators,
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNuSoftDrop','SubJets'),
					getJetMCFlavour = False,
					explicitJTA = True,  # needed for subjet b tagging
					svClustering = True, # needed for subjet b tagging
					fatJets=cms.InputTag(jetalgo+'PFJets'+PUMethod),             # needed for subjet flavor clustering
					groomedFatJets=cms.InputTag(jetalgo+'PFJets'+PUMethod+'SoftDrop'), # needed for subjet flavor clustering
					outputModules = ['outputFile']
					) 

			if miniAOD:
				getattr( proc,'patJets'+jetALGO+'PF'+PUMethod+'SoftDropSubjets').addAssociatedTracks = cms.bool(False) 
				getattr( proc,'patJets'+jetALGO+'PF'+PUMethod+'SoftDropSubjets').addJetCharge = cms.bool(False) 
				if hasattr(proc,'pfInclusiveSecondaryVertexFinderTagInfos'+jetALGO+'PF'+PUMethod+'SoftDropSubjets'):
					    getattr(proc,'pfInclusiveSecondaryVertexFinderTagInfos'+jetALGO+'PF'+PUMethod+'SoftDropSubjets').extSVCollection = cms.InputTag( svLabel ) 
			getattr(proc,'patJetCorrFactors'+jetALGO+'PF'+PUMethod+'SoftDropSubjets' ).primaryVertices = pvLabel 
			getattr(proc,'patJetPartonMatch'+jetALGO+'PF'+PUMethod+'SoftDropSubjets').matched = cms.InputTag( genParticlesLabel ) 
			setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropSubjets', selectedPatJets.clone( src = 'patJets'+jetALGO+'PF'+PUMethod+'SoftDropSubjets', cut = Cut ))

			## Establish references between PATified fat jets and subjets using the BoostedJetMerger
			setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropPacked', 
					cms.EDProducer("BoostedJetMerger",
						jetSrc=cms.InputTag('selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDrop'),
						subjetSrc=cms.InputTag('selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropSubjets')
						))
			jetSeq += getattr(proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropPacked' )
			elemToKeep += [ 'keep *_selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropPacked_*_*' ]
			toolsUsed.append( 'selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropPacked' )
			toolsUsed.append( 'selectedPatJets'+jetALGO+'PF'+PUMethod+'SoftDropSubjets' )

	if addPruning or addPrunedSubjets: 

		setattr( proc, jetalgo+'PFJets'+PUMethod+'Pruned', 
			ak8PFJetsCHSPruned.clone( 
				rParam = jetSize, 
				jetAlgorithm = algorithm, 
				zcut=zCut, 
				rcut_factor=rCut,
				writeCompound = cms.bool(True),
				doAreaFastjet = cms.bool(True),
				jetCollInstanceName=cms.string('SubJets') ) )
		if miniAOD: getattr( proc, jetalgo+'PFJets'+PUMethod+'Pruned').src = 'chs'
		setattr( proc, jetalgo+'PFJets'+PUMethod+'PrunedLinks', 
			ak8PFJetsCHSPrunedLinks.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
				matched = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Pruned'), 
				distMax = cms.double( jetSize ) ) )

		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'Pruned' )
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'PrunedLinks' )
		getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'PrunedLinks']
		elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'PrunedLinks_*_*'] 
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'PrunedLinks' )

		if addPrunedSubjets:
			setattr( proc, jetalgo+'GenJetsNoNuPruned',
					ak4GenJets.clone(
						SubJetParameters,
						rParam = jetSize,
						usePruning = cms.bool(True),
						writeCompound = cms.bool(True),
						jetCollInstanceName=cms.string('SubJets')
						))
			if miniAOD: getattr( proc, jetalgo+'GenJetsNoNuPruned' ).src = 'packedGenParticlesForJetsNoNu'
			jetSeq += getattr(proc, jetalgo+'GenJetsNoNuPruned' )

			addJetCollection(
					proc,
					labelName = jetALGO+'PF'+PUMethod+'Pruned',
					jetSource = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Pruned'),
					algo = jetalgo,
					rParam = jetSize,
					jetCorrections = JEC,
					btagDiscriminators = ['None'],
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNu'),
					getJetMCFlavour = False,
					outputModules = ['outputFile']
					) 
			getattr( proc, 'patJetCorrFactors'+jetALGO+'PF'+PUMethod+'Pruned' ).primaryVertices = pvLabel  
			getattr(proc,'patJetPartonMatch'+jetALGO+'PF'+PUMethod+'Pruned').matched = cms.InputTag( genParticlesLabel ) 
			setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'Pruned', selectedPatJets.clone( src = 'patJets'+jetALGO+'PF'+PUMethod+'Pruned', cut = Cut ) )

			addJetCollection(
					proc,
					labelName = jetALGO+'PF'+PUMethod+'PrunedSubjets',
					jetSource = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Pruned', 'SubJets'),
					algo = jetalgo,  # needed for subjet b tagging
					rParam = jetSize,  # needed for subjet b tagging
					jetCorrections = subJEC,
					pfCandidates = cms.InputTag( pfCand ),  
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ), 
					btagDiscriminators = bTagDiscriminators,
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNuPruned','SubJets'),
					getJetMCFlavour = False,
					explicitJTA = True,  # needed for subjet b tagging
					svClustering = True, # needed for subjet b tagging
					fatJets=cms.InputTag(jetalgo+'PFJets'+PUMethod),             # needed for subjet flavor clustering
					groomedFatJets=cms.InputTag(jetalgo+'PFJets'+PUMethod+'Pruned'), # needed for subjet flavor clustering
					outputModules = ['outputFile']
					) 

			getattr(proc,'patJetPartonMatch'+jetALGO+'PF'+PUMethod+'PrunedSubjets').matched = cms.InputTag( genParticlesLabel ) 
			getattr(proc,'patJetCorrFactors'+jetALGO+'PF'+PUMethod+'PrunedSubjets' ).primaryVertices = pvLabel  
			if miniAOD:
				if hasattr(proc,'pfInclusiveSecondaryVertexFinderTagInfos'+jetALGO+'PF'+PUMethod+'PrunedSubjets'):
					getattr(proc,'pfInclusiveSecondaryVertexFinderTagInfos'+jetALGO+'PF'+PUMethod+'PrunedSubjets').extSVCollection = cms.InputTag( svLabel ) 
				getattr( proc,'patJets'+jetALGO+'PF'+PUMethod+'PrunedSubjets').addAssociatedTracks = cms.bool(False)
				getattr( proc,'patJets'+jetALGO+'PF'+PUMethod+'PrunedSubjets').addJetCharge = cms.bool(False) 
			setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedSubjets', selectedPatJets.clone( src = 'patJets'+jetALGO+'PF'+PUMethod+'PrunedSubjets', cut = Cut ) )

			## Establish references between PATified fat jets and subjets using the BoostedJetMerger
			setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedPacked', 
					cms.EDProducer("BoostedJetMerger",
						jetSrc=cms.InputTag('selectedPatJets'+jetALGO+'PF'+PUMethod+'Pruned'),
						subjetSrc=cms.InputTag('selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedSubjets')
						))
			jetSeq += getattr(proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedPacked' )
			elemToKeep += [ 'keep *_selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedPacked_*_*' ]
			toolsUsed.append( 'selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedPacked' )
			toolsUsed.append( 'selectedPatJets'+jetALGO+'PF'+PUMethod+'PrunedSubjets' )


	if addTrimming:

		setattr( proc, jetalgo+'PFJets'+PUMethod+'Trimmed', 
				ak8PFJetsCHSTrimmed.clone( #src = 'chs',
					rParam = jetSize, 
					jetAlgorithm = algorithm,
					rFilt= rFiltTrim,
					trimPtFracMin= ptFrac) ) 
		if miniAOD: getattr( proc, jetalgo+'PFJets'+PUMethod+'Trimmed').src = 'chs'
		setattr( proc, jetalgo+'PFJets'+PUMethod+'TrimmedLinks', 
				ak8PFJetsCHSTrimmedLinks.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
					matched = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Trimmed'), 
					distMax = cms.double( jetSize ) ) )

		elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'TrimmedLinks_*_*'] 
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'Trimmed' )
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'TrimmedLinks' )
		getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'TrimmedLinks']
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'TrimmedLinks' )

	if addFiltering:

		setattr( proc, jetalgo+'PFJets'+PUMethod+'Filtered', 
				ak8PFJetsCHSFiltered.clone( #src = 'chs', 
					rParam = jetSize, 
					jetAlgorithm = algorithm,
					rFilt= rfilt,
					nFilt= nfilt ) ) 
		if miniAOD: getattr( proc, jetalgo+'PFJets'+PUMethod+'Filtered').src = 'chs'
		setattr( proc, jetalgo+'PFJets'+PUMethod+'FilteredLinks', 
				ak8PFJetsCHSFilteredLinks.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
					matched = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Filtered'), 
					distMax = cms.double( jetSize ) ) )
		elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'FilteredLinks_*_*'] 
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'Filtered' )
		jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'FilteredLinks' )
		getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'FilteredLinks']
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'FilteredLinks' )

	if addCMSTopTagger :

		if 'CA' in jetALGO : 

			setattr( proc, 'cmsTopTagPFJets'+PUMethod,  
					cms.EDProducer("CATopJetProducer",
						PFJetParameters.clone( #src = cms.InputTag("chs"), #ak8PFJetsCHSConstituents", "constituents"),
							doAreaFastjet = cms.bool(True),
							doRhoFastjet = cms.bool(False),
							jetPtMin = cms.double(100.0)
							),
						AnomalousCellParameters,
						CATopJetParameters.clone( jetCollInstanceName = cms.string("SubJets"),
							verbose = cms.bool(False),
							algorithm = cms.int32(1), # 0 = KT, 1 = CA, 2 = anti-KT
							tagAlgo = cms.int32(0), #0=legacy top
							useAdjacency = cms.int32(2), # modified adjacency
							centralEtaCut = cms.double(2.5), # eta for defining "central" jets
							sumEtBins = cms.vdouble(0,1600,2600), # sumEt bins over which cuts vary. vector={bin 0 lower bound, bin 1 lower bound, ...}
							rBins = cms.vdouble(0.8,0.8,0.8), # Jet distance paramter R. R values depend on sumEt bins.
							ptFracBins = cms.vdouble(0.05,0.05,0.05), # minimum fraction of central jet pt for subjets (deltap)
							deltarBins = cms.vdouble(0.19,0.19,0.19), # Applicable only if useAdjacency=1. deltar adjacency values for each sumEtBin
							nCellBins = cms.vdouble(1.9,1.9,1.9),
							),
						jetAlgorithm = cms.string("CambridgeAachen"),
						rParam = cms.double(jetSize),
						writeCompound = cms.bool(True)
						)
					)
			if miniAOD: getattr( proc, 'cmsTopTagPFJets'+PUMethod ).src = 'chs'
			
			setattr( proc, "CATopTagInfos", 
					cms.EDProducer("CATopJetTagger",
						src = cms.InputTag('cmsTopTagPFJets'+PUMethod),
						TopMass = cms.double(171),
						TopMassMin = cms.double(0.),
						TopMassMax = cms.double(250.),
						WMass = cms.double(80.4),
						WMassMin = cms.double(0.0),
						WMassMax = cms.double(200.0),
						MinMassMin = cms.double(0.0),
						MinMassMax = cms.double(200.0),
						verbose = cms.bool(False)
						)
					)
			addJetCollection(
					proc,
					labelName = 'CMSTopTag'+PUMethod,
					jetSource = cms.InputTag('cmsTopTagPFJets'+PUMethod),
					jetCorrections = JEC,
					pfCandidates = cms.InputTag( pfCand ),  
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ), 
					btagDiscriminators = bTagDiscriminators,
					genJetCollection = cms.InputTag(jetalgo+'GenJetsNoNu'),
					getJetMCFlavour = False
					)
			getattr(proc,'patJetPartonMatchCMSTopTag'+PUMethod).matched = cms.InputTag( genParticlesLabel ) 
			if hasattr(proc,'pfInclusiveSecondaryVertexFinderTagInfosCMSTopTag'+PUMethod):
				getattr(proc,'pfInclusiveSecondaryVertexFinderTagInfosCMSTopTag'+PUMethod).extSVCollection = cms.InputTag( svLabel ) 
			getattr(proc,'patJetsCMSTopTag'+PUMethod).addTagInfos = True
			getattr(proc,'patJetsCMSTopTag'+PUMethod).tagInfoSources = cms.VInputTag( cms.InputTag('CATopTagInfos'))
			getattr(proc,'patJetCorrFactorsCMSTopTag'+PUMethod ).primaryVertices = pvLabel  
			getattr(proc,'patJetsCMSTopTag'+PUMethod).addAssociatedTracks = cms.bool(False)
			getattr(proc,'patJetsCMSTopTag'+PUMethod).addJetCharge = cms.bool(False)      
			setattr( proc, 'selectedPatJetsCMSTopTag'+PUMethod, selectedPatJets.clone( src = 'patJetsCMSTopTag'+PUMethod, cut = Cut ) )

			addJetCollection(
					proc,
					labelName = 'CMSTopTag'+PUMethod+'Subjets',
					jetSource = cms.InputTag('cmsTopTagPFJets'+PUMethod, 'SubJets'),
					algo = jetalgo,  # needed for subjet b tagging
					rParam = jetSize,  # needed for subjet b tagging
					jetCorrections = subJEC,
					pfCandidates = cms.InputTag( pfCand ),  
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ), 
					btagDiscriminators = bTagDiscriminators,
					genJetCollection = cms.InputTag( jetalgo+'GenJetsNoNu'),
					#getJetMCFlavour = False,
					explicitJTA = True,  # needed for subjet b tagging
					svClustering = True, # needed for subjet b tagging
					fatJets=cms.InputTag(jetalgo+'PFJets'+PUMethod),             # needed for subjet flavor clustering
					groomedFatJets=cms.InputTag('patJetsCMSTopTag'+PUMethod), # needed for subjet flavor clustering
					)

			getattr(proc,'patJetPartonMatchCMSTopTag'+PUMethod+'Subjets').matched = cms.InputTag( genParticlesLabel ) #'prunedGenParticles')
			if hasattr(proc,'pfInclusiveSecondaryVertexFinderTagInfosCMSTopTag'+PUMethod+'Subjets'):
				getattr(proc,'pfInclusiveSecondaryVertexFinderTagInfosCMSTopTag'+PUMethod+'Subjets').extSVCollection = cms.InputTag(svLabel) 
			getattr(proc,'patJetCorrFactorsCMSTopTag'+PUMethod+'Subjets' ).primaryVertices = pvLabel  
			getattr(proc,'patJetsCMSTopTag'+PUMethod+'Subjets').addAssociatedTracks = cms.bool(False)
			getattr(proc,'patJetsCMSTopTag'+PUMethod+'Subjets').addJetCharge = cms.bool(False)      
			setattr( proc, 'selectedPatJetsCMSTopTag'+PUMethod+'Subjets', selectedPatJets.clone( src = 'patJetsCMSTopTag'+PUMethod+'Subjets', cut = Cut ) )

			setattr( proc, 'patJetsCMSTopTag'+PUMethod+'Packed', 
					cms.EDProducer("BoostedJetMerger",
						jetSrc=cms.InputTag('patJetsCMSTopTag'+PUMethod ),
						subjetSrc=cms.InputTag('patJetsCMSTopTag'+PUMethod+'Subjets')
						))
			jetSeq += getattr(proc, 'patJetsCMSTopTag'+PUMethod+'Packed' )
			elemToKeep += [ 'keep *_patJetsCMSTopTag'+PUMethod+'Packed_*_*' ]
			toolsUsed.append( 'patJetsCMSTopTag'+PUMethod+'Packed' )

		else: print '|----- CMS recommends CambridgeAachen for CMS Top Tagger, you are using '+algorithm+'. JetToolbox will not run CMS Top Tagger.'

	if addMassDrop :

		if 'CA' in jetALGO : 
			setattr( proc, jetalgo+'PFJets'+PUMethod+'MassDropFiltered', ca15PFJetsCHSMassDropFiltered.clone( rParam = jetSize ) )
			if miniAOD: getattr( proc, jetalgo+'PFJets'+PUMethod+'MassDropFiltered').src = 'chs'
			setattr( proc, jetalgo+'PFJets'+PUMethod+'MassDropFilteredLinks', ak8PFJetsCHSPrunedLinks.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
				matched = cms.InputTag(jetalgo+'PFJets'+PUMethod+'MassDropFiltered'), distMax = cms.double( jetSize ) ) )
			elemToKeep += [ 'keep *_'+jetalgo+'PFJets'+PUMethod+'MassDropFilteredLinks_*_*' ]
			getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ jetalgo+'PFJets'+PUMethod+'MassDropFilteredLinks' ]
			jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'MassDropFiltered' )
			jetSeq += getattr(proc, jetalgo+'PFJets'+PUMethod+'MassDropFilteredLinks' )
		else: print '|----- CMS recommends CambridgeAachen for Mass Drop, you are using '+algorithm+'. JetToolbox will not run Mass Drop.'
		toolsUsed.append( jetalgo+'PFJets'+PUMethod+'MassDropFilteredLinks' )

	if addHEPTopTagger: 
		if ( jetSize >= 1. ) and ( 'CA' in jetALGO ): 

			if miniAOD: setattr( proc, 'hepTopTagPFJets'+PUMethod, hepTopTagPFJetsCHS.clone( src = 'chs' ) )
			else: 
				setattr( proc, jetalgo+'PFJets'+PUMethod+'Constituents', ak8PFJetsCHSConstituents.clone( src = jetalgo+'PFJets'+PUMethod ) )
				setattr( proc, 'hepTopTagPFJets'+PUMethod, hepTopTagPFJetsCHS.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod+'Constituents', 'constituents' ) ) )
			setattr( proc, 'hepTopTagPFJets'+PUMethod+'Links'+jetALGO, ak8PFJetsCHSPrunedLinks.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
				matched = cms.InputTag("hepTopTagPFJets"+PUMethod), distMax = cms.double( jetSize ) ) )
			elemToKeep += [ 'keep *_hepTopTagPFJets'+PUMethod+'Links'+jetALGO+'_*_*' ]
			getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += [ 'hepTopTagPFJets'+PUMethod+'Links'+jetALGO ]
			jetSeq += getattr(proc, 'hepTopTagPFJets'+PUMethod )
			jetSeq += getattr(proc, 'hepTopTagPFJets'+PUMethod+'Links'+jetALGO )
			toolsUsed.append( 'hepTopTagPFJets'+PUMethod+'Links'+jetALGO )
		else: print '|----- CMS recommends CambridgeAachen for HEPTopTagger, you are using '+algorithm+', and a jet cone size bigger than 1. JetToolbox will not run HEP TopTagger.'

	####### Nsubjettiness
	if addNsub:
		from RecoJets.JetProducers.nJettinessAdder_cfi import Njettiness

		rangeTau = range(1,maxTau+1)
		setattr( proc, 'Njettiness'+jetALGO+PUMethod, 
				Njettiness.clone( src = cms.InputTag( jetalgo+'PFJets'+PUMethod), 
					Njets=cms.vuint32(rangeTau),         # compute 1-, 2-, 3-, 4- subjettiness
					# variables for measure definition : 
					measureDefinition = cms.uint32( 0 ), # CMS default is normalized measure
					beta = cms.double(1.0),              # CMS default is 1
					R0 = cms.double( jetSize ),              # CMS default is jet cone size
					Rcutoff = cms.double( -999.0),       # not used by default
					# variables for axes definition :
					axesDefinition = cms.uint32( 6 ),    # CMS default is 1-pass KT axes
					nPass = cms.int32(-999),             # not used by default
					akAxesR0 = cms.double(-999.0) ) )        # not used by default

		elemToKeep += [ 'keep *_Njettiness'+jetALGO+PUMethod+'_*_*' ]
		for tau in rangeTau: getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += ['Njettiness'+jetALGO+PUMethod+':tau'+str(tau) ] 
		jetSeq += getattr(proc, 'Njettiness'+jetALGO+PUMethod )
		toolsUsed.append( 'Njettiness'+jetALGO+PUMethod )

	###### QJetsAdder
	if addQJets:
		#This is the old way before 731
		### there must be a better way to do this random number introduction
		setattr( proc, 'RandomNumberGeneratorService', cms.Service("RandomNumberGeneratorService", 
							QJetsAdderCA8 = cms.PSet(initialSeed = cms.untracked.uint32(7)),
							QJetsAdderAK8 = cms.PSet(initialSeed = cms.untracked.uint32(31)),
							QJetsAdderCA15 = cms.PSet(initialSeed = cms.untracked.uint32(76)), ) )

		from RecoJets.JetProducers.qjetsadder_cfi import QJetsAdder
		setattr( proc, 'QJetsAdder'+jetALGO, 
				QJetsAdder.clone( src = cms.InputTag(jetalgo+'PFJets'+PUMethod), 
					jetRad = cms.double( jetSize ), 
					jetAlgo = cms.string( jetALGO[0:2] )))
		elemToKeep += [ 'keep *_QJetsAdder'+jetALGO+'_*_*' ]
		getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += ['QJetsAdder'+jetALGO+':QjetsVolatility']  
		jetSeq += getattr(proc, 'QJetsAdder'+jetALGO )
		toolsUsed.append( 'QJetsAdder'+jetALGO )
		'''
		### This is for 731 or higher
		if 'ak4' in jetalgo:
			proc.load('RecoJets.JetProducers.QGTagger_cfi')
			proc.QGTagger.srcJets = cms.InputTag(jetalgo+'PFJets'+PUMethod)    # Could be reco::PFJetCollection or pat::JetCollection (both AOD and miniAOD)
			proc.QGTagger.jetsLabel = cms.string('QGL_AK4PFchs')        # Other options (might need to add an ESSource for it): see https://twiki.cern.ch/twiki/bin/viewauth/CMS/QGDataBaseVersion
			elemToKeep += [ 'keep *_QGTagger_*_*' ]
			getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += ['QJetsAdder'+jetALGO+':qgLikelihood']  
			jetSeq += getattr(proc, 'QGTagger' )
		else:
			'QGTagger is optimized for ak4 jets.'
		'''

	setattr( proc, 'selectedPatJets'+jetALGO+'PF'+PUMethod, selectedPatJets.clone( src = 'patJets'+jetALGO+'PF'+PUMethod, cut = Cut ) )
	elemToKeep += [ 'keep *_selectedPatJets'+jetALGO+'PF'+PUMethod+'_*_*' ]
	elemToKeep += [ 'drop *_selectedPatJets'+jetALGO+'PF'+PUMethod+'_calo*_*' ]
	elemToKeep += [ 'drop *_selectedPatJets'+jetALGO+'PF'+PUMethod+'_tagInfos_*' ]

	print '|---- jetToolBox: Running '+', '.join(toolsUsed)+'.'

	### "return"
	setattr(proc, jetSequence, jetSeq)
	if hasattr(proc, outputFile): getattr(proc, outputFile).outputCommands += elemToKeep
	else: setattr( proc, outputFile, 
			cms.OutputModule('PoolOutputModule', 
				fileName = cms.untracked.string('jettoolbox.root'), 
				outputCommands = cms.untracked.vstring( elemToKeep ) ) )
Beispiel #10
0
process.load('RecoJets.JetProducers.qjetsadder_cfi')
patAlgosToolsTask.add(process.QJetsAdder)
process.QJetsAdderAK8 = process.QJetsAdder.clone()
patAlgosToolsTask.add(process.QJetsAdderAK8)
process.QJetsAdderAK8.src = cms.InputTag("slimmedJetsAK8")
process.QJetsAdderAK8.jetRad = cms.double(0.8)
process.QJetsAdderAK8.jetAlgo = cms.string('AK')

patJetsAK8.userData.userFloats.src += ['QJetsAdderAK8:QjetsVolatility']
process.out.outputCommands += ['keep *_QJetsAdderAK8_*_*']

#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#Grooming valueMaps

from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSPruned, ak8PFJetsCHSSoftDrop, ak8PFJetsCHSTrimmed, ak8PFJetsCHSFiltered
process.ak8PFJetsCHSPruned = ak8PFJetsCHSPruned.clone()
patAlgosToolsTask.add(process.ak8PFJetsCHSPruned)
process.ak8PFJetsCHSSoftDrop = ak8PFJetsCHSSoftDrop.clone()
patAlgosToolsTask.add(process.ak8PFJetsCHSSoftDrop)
process.ak8PFJetsCHSTrimmed = ak8PFJetsCHSTrimmed.clone()
patAlgosToolsTask.add(process.ak8PFJetsCHSTrimmed)
process.ak8PFJetsCHSFiltered = ak8PFJetsCHSFiltered.clone()
patAlgosToolsTask.add(process.ak8PFJetsCHSFiltered)
process.ak8PFJetsCHSPruned.src = cms.InputTag("packedPFCandidates")
process.ak8PFJetsCHSSoftDrop.src = cms.InputTag("packedPFCandidates")
process.ak8PFJetsCHSTrimmed.src = cms.InputTag("packedPFCandidates")
process.ak8PFJetsCHSFiltered.src = cms.InputTag("packedPFCandidates")
from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSPrunedMass, ak8PFJetsCHSSoftDropMass, ak8PFJetsCHSTrimmedMass, ak8PFJetsCHSFilteredMass
process.ak8PFJetsCHSPrunedMass = ak8PFJetsCHSPrunedMass.clone()
patAlgosToolsTask.add(process.ak8PFJetsCHSPrunedMass)
process.ak8PFJetsCHSSoftDropMass = ak8PFJetsCHSSoftDropMass.clone()
def makeTreeTreeFromMiniAOD(process,
outFileName,
NJetsMin=2,
HTMin=350.,
MHTMin=0.,
reportEveryEvt=10,
testFileName="",
Global_Tag="",
METFiltersProcess="",
MC=False,
debug = False,
QCD=False,
LostLepton=False,
numProcessedEvt=1000,
doAK8Reclustering=False,
doJECCorrection=False,
doPuppi=False,
leptonFilter=True,
genJetsAK8Reclustering=True,
customizeHBHENoiseForEarlyData=False,
customizeHBHENoiseForRun2015D=True,
jsonFileName="",
reDoPruningAndSoftdrop=False,
isCrab=False):

    process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff")
    if (MC):
        customizeHBHENoiseForRun2015D=False

    process.GlobalTag.globaltag = Global_Tag

    ## Added Geometry cfi files ###
    ## Not in current EXO-WW configuration ##
    process.load("Geometry.CMSCommonData.cmsIdealGeometryXML_cfi");
    process.load("Geometry.CaloEventSetup.CaloGeometry_cfi");
    process.load("Geometry.CaloEventSetup.CaloTopology_cfi");

    ## --- Log output ------------------------------------------------------
    process.load("FWCore.MessageService.MessageLogger_cfi")
    process.MessageLogger.cerr = cms.untracked.PSet(
        placeholder = cms.untracked.bool(True)
        )
    process.MessageLogger.cout = cms.untracked.PSet(
        INFO = cms.untracked.PSet(reportEvery = cms.untracked.int32(reportEveryEvt))
        )
    process.options = cms.untracked.PSet(
        wantSummary = cms.untracked.bool(True)
        ) 


    ## --- Files to process ------------------------------------------------
    process.maxEvents = cms.untracked.PSet(
        input = cms.untracked.int32(numProcessedEvt)
        )
    process.source = cms.Source("PoolSource",

        fileNames = cms.untracked.vstring(testFileName)
        )

 ## ----------------------------------------------------------------------------------------------
## 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 SemiLeptonicWVA.Utils.triggerproducer_cfi import triggerProducer
    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 = cms.vstring( # list of trigger names
            'HLT_Ele22_eta2p1_WPTight_Gsf_v',
            'HLT_IsoMu20_v',
            'HLT_IsoTkMu20_v',
	    'HLT_Ele27_WP85_Gsf_v'
            )
        )

    ## --- Output file -----------------------------------------------------
    process.TFileService = cms.Service(
        "TFileService",
        fileName = cms.string(outFileName+".root")
        )

    ############### JSON Filter            
    import FWCore.PythonUtilities.LumiList as LumiList
    import sys

    if not MC:
        if(len(jsonFileName)>0):
            import FWCore.PythonUtilities.LumiList as LumiList
            process.source.lumisToProcess = LumiList.LumiList(filename = jsonFileName).getVLuminosityBlockRange()
        else:
            print "ERROR!! running on data with no json file applied!"
            sys.exit()

####### some gen infos
    from SemiLeptonicWVA.Utils.geneventinfo_cfi import geneventinfo
    process.GenEventInfo = geneventinfo.clone()
    
###Lepton Filter
    process.filterSeq = cms.Sequence ()

    process.load('SemiLeptonicWVA.Utils.leptonfilter_cfi')

    process.leptonFilter.electronsInputTag = cms.InputTag("slimmedElectrons")
    process.leptonFilter.muonsInputTag = cms.InputTag("slimmedMuons")
    process.leptonFilter.eleFilterPtCut = cms.double(20.0)
    process.leptonFilter.muFilterPtCut = cms.double(20.0)
    
    if (leptonFilter):
        process.filterSeq = cms.Sequence (process.leptonFilter)
    
       ## --- Setup of TreeMaker ----------------------------------------------
    FilterNames = cms.VInputTag()
    FilterNames.append(cms.InputTag("HBHENoiseFilterRA2","HBHENoiseFilterResult","PAT"))
    FilterNames.append(cms.InputTag("beamHaloFilter"))
    FilterNames.append(cms.InputTag("eeNoiseFilter"))
    FilterNames.append(cms.InputTag("trackingFailureFilter"))
    FilterNames.append(cms.InputTag("inconsistentMuons"))
    FilterNames.append(cms.InputTag("greedyMuons"))
    FilterNames.append(cms.InputTag("ra2EcalTPFilter"))
    FilterNames.append(cms.InputTag("ra2EcalBEFilter"))
    FilterNames.append(cms.InputTag("hcalLaserEventFilter"))
    FilterNames.append(cms.InputTag("ecalLaserCorrFilter"))
    FilterNames.append(cms.InputTag("eeBadScFilter"))
    FilterNames.append(cms.InputTag("PBNRFilter"))
    FilterNames.append(cms.InputTag("HCALLaserEvtFilterList2012"))
    FilterNames.append(cms.InputTag("manystripclus53X"))
    FilterNames.append(cms.InputTag("toomanystripclus53X"))
    FilterNames.append(cms.InputTag("logErrorTooManyClusters"))
    FilterNames.append(cms.InputTag("RA2HONoiseFilter"))

    
    ## --- Setup WeightProducer -------------------------------------------
    from SemiLeptonicWVA.WeightProducer.getWeightProducer_cff import getWeightProducer
    process.WeightProducer = getWeightProducer(testFileName)
    process.WeightProducer.Lumi                       = cms.double(5000)
    process.WeightProducer.PU                         = cms.int32(0) # PU S10 3 for S10 2 for S7
    process.WeightProducer.FileNamePUDataDistribution = cms.string("NONE")
    print process.WeightProducer.PU

    from RecoBTag.Configuration.RecoBTag_cff import *
    from RecoJets.JetAssociationProducers.j2tParametersVX_cfi import *
    process.slimmedJetsPFJetTracksAssociatorAtVertex = cms.EDProducer("JetTracksAssociatorAtVertex",
      j2tParametersVX,
      jets = cms.InputTag("iterativeCone5PFJets")
    )
    process.slimmedJetsPFJetTracksAssociatorAtVertex.jets = "slimmedJets"
    process.slimmedJetsPFJetTracksAssociatorAtVertex.tracks = "generalTracks"
    
    process.slimmedJetsPFImpactParameterTagInfos = impactParameterTagInfos.clone()
    process.slimmedJetsPFImpactParameterTagInfos.jetTracks = "slimmedJetsPFJetTracksAssociatorAtVertex"
    process.slimmedJetsPFSecondaryVertexTagInfos = secondaryVertexTagInfos.clone()
    process.slimmedJetsPFSecondaryVertexTagInfos.trackIPTagInfos = "slimmedJetsPFImpactParameterTagInfos"
    
    process.slimmedJetsPFJetBtaggingSV = cms.Sequence(
    	process.slimmedJetsPFImpactParameterTagInfos *
    process.slimmedJetsPFSecondaryVertexTagInfos 
    )
    process.slimmedJetsPFJetsBtag = cms.Sequence(
    process.slimmedJetsPFJetTracksAssociatorAtVertex *
    process.slimmedJetsPFJetBtaggingSV
    )
    
    ## isotrack producer
    from SemiLeptonicWVA.Utils.trackIsolationMaker_cfi import trackIsolationFilter
    from SemiLeptonicWVA.Utils.trackIsolationMaker_cfi import trackIsolationCounter
    ## default
    process.IsolatedTracks = trackIsolationFilter.clone(
      doTrkIsoVeto= False,
      vertexInputTag = cms.InputTag("offlineSlimmedPrimaryVertices"),
      pfCandidatesTag = cms.InputTag("packedPFCandidates"),
      dR_ConeSize         = cms.double(0.3),
      dz_CutValue         = cms.double(0.05),
      minPt_PFCandidate   = cms.double(15.0),
      isoCut              = cms.double(0.1),
      )
    process.CountIsoTracks = trackIsolationCounter.clone(
      src = cms.InputTag("IsolatedTracks"),
      minNumber = 1,
      )

    process.substructureSequence = cms.Sequence()
    process.softdrop_onMiniAOD = cms.Sequence()
    process.pruning_onMiniAOD = cms.Sequence()
    process.redoPatJets = cms.Sequence()
    process.puppi_onMiniAOD = cms.Sequence()
    process.redoPuppiJets = cms.Sequence()

    if (doAK8Reclustering):
        from RecoJets.Configuration.RecoPFJets_cff import ak4PFJetsCHS, ak8PFJetsCHS, ak8PFJetsCHSPruned, ak8PFJetsCHSSoftDrop, ak8PFJetsCHSPrunedMass, ak8PFJetsCHSSoftDropMass

        process.chs = cms.EDFilter("CandPtrSelector",
                               src = cms.InputTag('packedPFCandidates'),
                               cut = cms.string('fromPV')
                               )

        process.NjettinessAK8 = cms.EDProducer("NjettinessAdder",
                            src=cms.InputTag("ak8PFJetsCHS"),
                            Njets=cms.vuint32(1,2,3,4),          # compute 1-, 2-, 3-, 4- subjettiness
                            # variables for measure definition : 
                            measureDefinition = cms.uint32( 0 ), # CMS default is normalized measure
                            beta = cms.double(1.0),              # CMS default is 1
                            R0 = cms.double( 0.8 ),              # CMS default is jet cone size
                            Rcutoff = cms.double( -999.0),       # not used by default
                            # variables for axes definition :
                            axesDefinition = cms.uint32( 6 ),    # CMS default is 1-pass KT axes
                            nPass = cms.int32(-999),             # not used by default
                            akAxesR0 = cms.double(-999.0)        # not used by default
                            )

        process.ak4PFJetsCHS = ak4PFJetsCHS.clone(src = 'chs')
        process.ak8PFJetsCHS = ak8PFJetsCHS.clone( src = 'chs', jetPtMin = 100.0 )

        process.ak8PFJetsCHSPruned = ak8PFJetsCHSPruned.clone( src = 'chs', jetPtMin = 100.0 )
        process.ak8PFJetsCHSPrunedMass = ak8PFJetsCHSPrunedMass.clone()
        process.ak8PFJetsCHSSoftDrop = ak8PFJetsCHSSoftDrop.clone( src = 'chs', jetPtMin = 100.0 )
        process.ak8PFJetsCHSSoftDropMass = ak8PFJetsCHSSoftDropMass.clone()

        process.substructureSequence+=process.chs
        process.substructureSequence+=process.ak8PFJetsCHS
        process.substructureSequence+=process.NjettinessAK8

        process.softdrop_onMiniAOD += process.ak8PFJetsCHSSoftDrop + process.ak8PFJetsCHSSoftDropMass
        process.pruning_onMiniAOD += process.ak8PFJetsCHSPruned + process.ak8PFJetsCHSPrunedMass

        ####### Redo pat jets sequence ##########
        from ExoDiBosonResonances.EDBRJets.redoPatJets_cff import patJetCorrFactorsAK8, patJetsAK8, selectedPatJetsAK8

        # Redo pat jets from ak8PFJetsCHS

        process.patJetCorrFactorsAK8 = patJetCorrFactorsAK8.clone( src = 'ak8PFJetsCHS' )
        process.patJetsAK8 = patJetsAK8.clone( jetSource = 'ak8PFJetsCHS' )
        process.patJetsAK8.userData.userFloats.src = [ cms.InputTag("ak8PFJetsCHSPrunedMass"), cms.InputTag("ak8PFJetsCHSSoftDropMass"), cms.InputTag("NjettinessAK8:tau1"), cms.InputTag("NjettinessAK8:tau2"), cms.InputTag("NjettinessAK8:tau3")]
        process.patJetsAK8.jetCorrFactorsSource = cms.VInputTag( cms.InputTag("patJetCorrFactorsAK8") )
        process.selectedPatJetsAK8 = selectedPatJetsAK8.clone( cut = cms.string('pt > 20') )

        process.redoPatJets+=process.patJetCorrFactorsAK8
        process.redoPatJets+=process.patJetsAK8
        process.redoPatJets+=process.selectedPatJetsAK8

        if (reDoPruningAndSoftdrop):
            process.patJetCorrFactorsAK8Pruned = patJetCorrFactorsAK8.clone( src = 'ak8PFJetsCHSPruned' )
            process.patJetsAK8Pruned = patJetsAK8.clone( jetSource = 'ak8PFJetsCHSPruned' )
            process.patJetsAK8Pruned.userData.userFloats.src = [ "" ]
            process.patJetsAK8Pruned.jetCorrFactorsSource = cms.VInputTag( cms.InputTag("patJetCorrFactorsAK8Pruned") )
            process.selectedPatJetsAK8Pruned = selectedPatJetsAK8.clone( 
                src = cms.InputTag('patJetsAK8Pruned'),
                cut = cms.string('pt > 20') 
                )

            process.redoPatJets+=process.patJetCorrFactorsAK8Pruned
            process.redoPatJets+=process.patJetsAK8Pruned
            process.redoPatJets+=process.selectedPatJetsAK8Pruned

            process.patJetCorrFactorsAK8Softdrop = patJetCorrFactorsAK8.clone( src = 'ak8PFJetsCHSSoftDrop' )
            process.patJetsAK8Softdrop = patJetsAK8.clone( jetSource = 'ak8PFJetsCHSSoftDrop' )
            process.patJetsAK8Softdrop.userData.userFloats.src = [ "" ]
            process.patJetsAK8Softdrop.jetCorrFactorsSource = cms.VInputTag( cms.InputTag("patJetCorrFactorsAK8Softdrop") )
            process.selectedPatJetsAK8Softdrop = selectedPatJetsAK8.clone(
                src = cms.InputTag('patJetsAK8Softdrop'),
                cut = cms.string('pt > 20') 
                )

            process.redoPatJets+=process.patJetCorrFactorsAK8Softdrop
            process.redoPatJets+=process.patJetsAK8Softdrop
            process.redoPatJets+=process.selectedPatJetsAK8Softdrop

    if (doPuppi):

        from CommonTools.PileupAlgos.Puppi_cff import puppi
        from RecoJets.JetProducers.ak4PFJetsPuppi_cfi import ak4PFJetsPuppi

        process.ak8PFJetsPuppi = ak4PFJetsPuppi.clone( rParam = 0.8 )
        process.puppi = puppi.clone( candName = cms.InputTag('packedPFCandidates'),
                             vertexName = cms.InputTag('offlineSlimmedPrimaryVertices'))

        process.puppi_onMiniAOD = cms.Sequence(process.puppi + process.ak8PFJetsPuppi)

        from RecoJets.Configuration.RecoPFJets_cff import ak4PFJetsCHS, ak8PFJetsCHS, ak8PFJetsCHSPruned, ak8PFJetsCHSSoftDrop, ak8PFJetsCHSPrunedMass, ak8PFJetsCHSSoftDropMass

        process.NjettinessAK8 = cms.EDProducer("NjettinessAdder",
                            src=cms.InputTag("ak8PFJetsPuppi"),
                            Njets=cms.vuint32(1,2,3,4),          # compute 1-, 2-, 3-, 4- subjettiness
                            # variables for measure definition : 
                            measureDefinition = cms.uint32( 0 ), # CMS default is normalized measure
                            beta = cms.double(1.0),              # CMS default is 1
                            R0 = cms.double( 0.8 ),              # CMS default is jet cone size
                            Rcutoff = cms.double( -999.0),       # not used by default
                            # variables for axes definition :
                            axesDefinition = cms.uint32( 6 ),    # CMS default is 1-pass KT axes
                            nPass = cms.int32(-999),             # not used by default
                            akAxesR0 = cms.double(-999.0)        # not used by default
                            )

        process.ak4PFJetsPuppi = ak4PFJetsPuppi.clone(src = 'puppi')
        process.ak8PFJetsPuppi = process.ak8PFJetsPuppi.clone( src = 'puppi', jetPtMin = 100.0 )

        process.ak8PFJetsCHSPruned = ak8PFJetsCHSPruned.clone( src = 'puppi', jetPtMin = 100.0 )
        process.ak8PFJetsCHSPrunedMass = ak8PFJetsCHSPrunedMass.clone(    
            matched = cms.InputTag("ak8PFJetsCHSPruned"),
            src = cms.InputTag("ak8PFJetsPuppi")
            )
        process.ak8PFJetsCHSSoftDrop = ak8PFJetsCHSSoftDrop.clone( src = 'puppi', jetPtMin = 100.0 )
        process.ak8PFJetsCHSSoftDropMass = ak8PFJetsCHSSoftDropMass.clone(
            matched = cms.InputTag("ak8PFJetsCHSSoftDrop"),
            src = cms.InputTag("ak8PFJetsPuppi")
            )

        process.substructureSequence+=process.puppi
        process.substructureSequence+=process.ak8PFJetsPuppi
        process.substructureSequence+=process.NjettinessAK8

        process.softdrop_onMiniAOD += process.ak8PFJetsCHSSoftDrop + process.ak8PFJetsCHSSoftDropMass
        process.pruning_onMiniAOD += process.ak8PFJetsCHSPruned + process.ak8PFJetsCHSPrunedMass

        ####### Redo pat jets sequence ##########
        from ExoDiBosonResonances.EDBRJets.redoPatJets_cff import patJetCorrFactorsAK8, patJetsAK8, selectedPatJetsAK8

        # Redo pat jets from puppi AK8

        process.puppiJetCorrFactorsAK8 = patJetCorrFactorsAK8.clone( src = 'ak8PFJetsPuppi',
                                                                     levels = cms.vstring('L2Relative',
                                                                                          'L3Absolute')
                                                                     )
        process.puppiJetsAK8 = patJetsAK8.clone( jetSource = 'ak8PFJetsPuppi' )
        process.puppiJetsAK8.userData.userFloats.src = [ cms.InputTag("ak8PFJetsCHSPrunedMass"), cms.InputTag("ak8PFJetsCHSSoftDropMass"), cms.InputTag("NjettinessAK8:tau1"), cms.InputTag("NjettinessAK8:tau2"), cms.InputTag("NjettinessAK8:tau3")]
        process.puppiJetsAK8.jetCorrFactorsSource = cms.VInputTag( cms.InputTag("puppiJetCorrFactorsAK8") )
        process.selectedPuppiJetsAK8 = selectedPatJetsAK8.clone( src = 'puppiJetsAK8', cut = cms.string('pt > 20') )

        process.redoPuppiJets+=process.puppiJetCorrFactorsAK8
        process.redoPuppiJets+=process.puppiJetsAK8
        process.redoPuppiJets+=process.selectedPuppiJetsAK8

#######AK8 GEN JETS################

    process.substructureSequenceGen = cms.Sequence()
    process.softdropGen_onMiniAOD = cms.Sequence()
    process.pruningGen_onMiniAOD = cms.Sequence()
    process.redoGenJets = cms.Sequence()
#    process.puppi_onMiniAOD = cms.Sequence()

    if (genJetsAK8Reclustering and MC):    
        from RecoJets.JetProducers.ak4GenJets_cfi import ak4GenJets
        
        process.ak8GenJets = ak4GenJets.clone(src = cms.InputTag('packedGenParticles'),
                                          rParam = cms.double(0.8)
                                          )

        from RecoJets.Configuration.RecoPFJets_cff import ak4PFJetsCHS, ak8PFJetsCHS, ak8PFJetsCHSPruned, ak8PFJetsCHSSoftDrop, ak8PFJetsCHSPrunedMass, ak8PFJetsCHSSoftDropMass

        process.NjettinessGenAK8 = cms.EDProducer("NjettinessAdder",
                            src=cms.InputTag("ak8GenJets"),
                            Njets=cms.vuint32(1,2,3,4),          # compute 1-, 2-, 3-, 4- subjettiness
                            # variables for measure definition : 
                            measureDefinition = cms.uint32( 0 ), # CMS default is normalized measure
                            beta = cms.double(1.0),              # CMS default is 1
                            R0 = cms.double( 0.8 ),              # CMS default is jet cone size
                            Rcutoff = cms.double( -999.0),       # not used by default
                            # variables for axes definition :
                            axesDefinition = cms.uint32( 6 ),    # CMS default is 1-pass KT axes
                            nPass = cms.int32(-999),             # not used by default
                            akAxesR0 = cms.double(-999.0)        # not used by default
                            )

        process.genParticlesForJets = cms.EDProducer("InputGenJetsParticleSelector",
                                             src = cms.InputTag("packedGenParticles"),
                                             ignoreParticleIDs = cms.vuint32(
                1000022,
                1000012, 1000014, 1000016,
                2000012, 2000014, 2000016,
                1000039, 5100039,
                4000012, 4000014, 4000016,
                9900012, 9900014, 9900016,
                39),
                                             partonicFinalState = cms.bool(False),
                                             excludeResonances = cms.bool(False),
                                             excludeFromResonancePids = cms.vuint32(12, 13, 14, 16),
                                             tausAsJets = cms.bool(False)
                                             )

        from RecoJets.JetProducers.SubJetParameters_cfi import SubJetParameters

        process.ak8GenJetsPruned = ak4GenJets.clone(
            SubJetParameters,
            rParam = cms.double(0.8),
            src = cms.InputTag("genParticlesForJets"),
            usePruning = cms.bool(True),
            writeCompound = cms.bool(True),
            jetCollInstanceName=cms.string("SubJets")
            )

#        process.ak8GenJetsPruned = ak8PFJetsCHSPruned.clone( src = 'packedGenParticles', jetPtMin = 100.0 )
        process.ak8GenJetsPrunedMass = ak8PFJetsCHSPrunedMass.clone(    
            matched = cms.InputTag("ak8GenJetsPruned"),
            src = cms.InputTag("ak8GenJets")
            )

        process.ak8GenJetsSoftDrop = ak4GenJets.clone(
            SubJetParameters,
            rParam = cms.double(0.8),
            src = cms.InputTag("genParticlesForJets"),
            useSoftDrop = cms.bool(True),
            R0 = cms.double(0.8),
            beta = cms.double(0.0),
            writeCompound = cms.bool(True),
            jetCollInstanceName=cms.string("SubJets")
            )

        process.ak8GenJetsSoftDropMass = ak8PFJetsCHSSoftDropMass.clone(
            matched = cms.InputTag("ak8GenJetsSoftDrop"),
            src = cms.InputTag("ak8GenJets")
            )

        process.substructureSequenceGen+=process.genParticlesForJets
        process.substructureSequenceGen+=process.ak8GenJets
        process.substructureSequenceGen+=process.NjettinessGenAK8

        process.softdropGen_onMiniAOD += process.ak8GenJetsSoftDrop + process.ak8GenJetsSoftDropMass
        process.pruningGen_onMiniAOD += process.ak8GenJetsPruned + process.ak8GenJetsPrunedMass

        ####### Redo pat jets sequence ##########
        from ExoDiBosonResonances.EDBRJets.redoPatJets_cff import patJetCorrFactorsAK8, patJetsAK8, selectedPatJetsAK8

        # Redo pat jets from gen AK8

        process.genJetsAK8 = patJetsAK8.clone( jetSource = 'ak8GenJets' )
        process.genJetsAK8.userData.userFloats.src = [ cms.InputTag("ak8GenJetsPrunedMass"), cms.InputTag("ak8GenJetsSoftDropMass"), cms.InputTag("NjettinessGenAK8:tau1"), cms.InputTag("NjettinessGenAK8:tau2"), cms.InputTag("NjettinessGenAK8:tau3")]
        process.genJetsAK8.addJetCorrFactors = cms.bool(False)
        process.genJetsAK8.jetCorrFactorsSource = cms.VInputTag( cms.InputTag("") )
        process.selectedGenJetsAK8 = selectedPatJetsAK8.clone( src = 'genJetsAK8', cut = cms.string('pt > 20') )

        process.redoGenJets+=process.genJetsAK8
        process.redoGenJets+=process.selectedGenJetsAK8


######### A4PF-nonCHS jets ###########

    from RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJets

    process.ak4PFJets = ak4PFJets.clone(src = "packedPFCandidates")

    from SemiLeptonicWVA.Utils.ak4pfjets_cfi import patJetCorrFactorsAK4, patJetsAK4

    process.patJetCorrFactorsAK4 = patJetCorrFactorsAK4.clone( src = 'ak4PFJets' )
    process.patJetsAK4 = patJetsAK4.clone( jetSource = 'ak4PFJets' )


    #
    # Set up electron ID (VID framework)
    #
    from PhysicsTools.SelectorUtils.tools.vid_id_tools import *
    # turn on VID producer, indicate data format to be
    # DataFormat.AOD or DataFormat.MiniAOD, as appropriate
    dataFormat=DataFormat.MiniAOD
    switchOnVIDElectronIdProducer(process,dataFormat)

    process.egmGsfElectronIDSequence = cms.Sequence(process.egmGsfElectronIDs)

    # define which IDs we want to produce
    my_id_modules = ['RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_Spring15_25ns_V1_cff',
                     'RecoEgamma.ElectronIdentification.Identification.heepElectronID_HEEPV60_cff']
    #add them to the VID producer
    for idmod in my_id_modules:
        setupAllVIDIdsInModule(process,idmod,setupVIDElectronSelection)

    # Producers
    from SemiLeptonicWVA.Utils.electron_cfi import electron
    process.Electrons = electron.clone(
        VertexTag = cms.InputTag("offlineSlimmedPrimaryVertices"),
        EleTag = cms.InputTag("slimmedElectrons"),
        MinPt = cms.double(-1),
        RhoTag = cms.InputTag("fixedGridRhoFastjetAll"),
        eleVetoIdMap = cms.InputTag("egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-veto"),
        eleLooseIdMap = cms.InputTag("egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-loose"),
        eleMediumIdMap = cms.InputTag("egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-medium"),
        eleTightIdMap = cms.InputTag("egmGsfElectronIDs:cutBasedElectronID-Spring15-25ns-V1-standalone-tight"),
        eleHEEPIdMap = cms.InputTag("egmGsfElectronIDs:heepElectronID-HEEPV60")
    )

    # Add in Photons:
    switchOnVIDPhotonIdProducer(process, dataFormat)
    my_id_modules = ['RecoEgamma.PhotonIdentification.Identification.cutBasedPhotonID_Spring15_25ns_V1_cff']
    for idmod in my_id_modules:
        setupAllVIDIdsInModule(process,idmod,setupVIDPhotonSelection)
    from SemiLeptonicWVA.Utils.photon_cfi import photon
    process.Photons = photon.clone(
        PhoTag = cms.InputTag("slimmedPhotons"),
        phoLooseIdMap = cms.InputTag("egmPhotonIDs:cutBasedPhotonID-Spring15-25ns-V1-standalone-loose"),
        phoMediumIdMap = cms.InputTag("egmPhotonIDs:cutBasedPhotonID-Spring15-25ns-V1-standalone-medium"),
        phoTightIdMap = cms.InputTag("egmPhotonIDs:cutBasedPhotonID-Spring15-25ns-V1-standalone-tight"),
        phoTightIdFullInfoMap = cms.InputTag("egmPhotonIDs:cutBasedPhotonID-Spring15-25ns-V1-standalone-tight")
    )

    from SemiLeptonicWVA.Utils.muon_cfi import muon
    process.Muons = muon.clone(
        VertexTag = cms.InputTag("offlineSlimmedPrimaryVertices"),
        MuTag = cms.InputTag("slimmedMuons"),
        MinPt = cms.double(-1),
        RhoTag = cms.InputTag("fixedGridRhoFastjetAll")
    )
    from SemiLeptonicWVA.Utils.subJetSelection_cfi import SubJetSelection
    process.HTJets = SubJetSelection.clone(
    JetTag  = cms.InputTag('slimmedJets'),
    MinPt								  = cms.double(50),
    MaxEta								  = cms.double(2.5),
    )
    from SemiLeptonicWVA.Utils.htdouble_cfi import htdouble
    process.HT = htdouble.clone(
    JetTag  = cms.InputTag('HTJets'),
    )
    from SemiLeptonicWVA.Utils.njetint_cfi import njetint
    process.NJets = njetint.clone(
    JetTag  = cms.InputTag('HTJets'),
    )
    from SemiLeptonicWVA.Utils.btagint_cfi import btagint
    process.BTags = btagint.clone(
    JetTag  = cms.InputTag('HTJets'),
    BTagInputTag	        = cms.string('combinedInclusiveSecondaryVertexV2BJetTags'),
    BTagCutValue					= cms.double(0.679)
    )
    from SemiLeptonicWVA.Utils.subJetSelection_cfi import SubJetSelection
    process.MHTJets = SubJetSelection.clone(
    JetTag  = cms.InputTag('slimmedJets'),
    MinPt								  = cms.double(30),
    MaxEta								  = cms.double(5.0),
    )
    process.MHTJetsAK8 = SubJetSelection.clone(
    JetTag  = cms.InputTag('slimmedJetsAK8'),
    MinPt								  = cms.double(30),
    MaxEta								  = cms.double(5.0),
    )
    from SemiLeptonicWVA.Utils.jetproperties_cfi import jetproperties
    process.MHTJetsProperties = jetproperties.clone(
    JetTag  = cms.InputTag('MHTJets'),
    doJEC  = cms.bool(doJECCorrection),
    L1File = cms.string("Summer15_25nsV7_DATA_L1FastJet_AK4PFchs.txt"),
    L2File = cms.string("Summer15_25nsV7_DATA_L2Relative_AK4PFchs.txt"),
    L3File = cms.string("Summer15_25nsV7_DATA_L3Absolute_AK4PFchs.txt"),
    L2L3File = cms.string("Summer15_25nsV7_DATA_L2L3Residual_AK4PFchs.txt"),
    )
    from SemiLeptonicWVA.Utils.jetpropertiesAK8_cfi import jetpropertiesAK8
    process.MHTJetsPropertiesAK8 = jetpropertiesAK8.clone(
    JetTag  = cms.InputTag('MHTJetsAK8'),
    puppiJetTag = cms.InputTag('selectedPuppiJetsAK8'),
    doJEC  = cms.bool(doJECCorrection),
    doReclusteringForPrunedAndSoftdrop = cms.bool(reDoPruningAndSoftdrop),
    L1File = cms.string("Summer15_25nsV7_DATA_L1FastJet_AK8PFchs.txt"),
    L2File = cms.string("Summer15_25nsV7_DATA_L2Relative_AK8PFchs.txt"),
    L3File = cms.string("Summer15_25nsV7_DATA_L3Absolute_AK8PFchs.txt"),
    L2L3File = cms.string("Summer15_25nsV7_DATA_L2L3Residual_AK8PFchs.txt"),
    )
    if (reDoPruningAndSoftdrop):
        process.MHTJetsPropertiesAK8.prunedJetTag  = cms.InputTag('selectedPatJetsAK8Pruned')
        process.MHTJetsPropertiesAK8.softdropJetTag  = cms.InputTag('selectedPatJetsAK8Softdrop')
    else:
        process.MHTJetsPropertiesAK8.prunedJetTag  = cms.InputTag('slimmedJetsAK8')
        process.MHTJetsPropertiesAK8.softdropJetTag  = cms.InputTag('slimmedJetsAK8')

    if (MC):
        process.MHTJetsProperties.L1File = cms.string("Summer15_25nsV7_MC_L1FastJet_AK4PFchs.txt")
        process.MHTJetsProperties.L2File = cms.string("Summer15_25nsV7_MC_L2Relative_AK4PFchs.txt")
        process.MHTJetsProperties.L3File = cms.string("Summer15_25nsV7_MC_L3Absolute_AK4PFchs.txt")
        process.MHTJetsProperties.L2L3File = cms.string("NONE")
        process.MHTJetsPropertiesAK8.L1File = cms.string("Summer15_25nsV7_MC_L1FastJet_AK8PFchs.txt")
        process.MHTJetsPropertiesAK8.L2File = cms.string("Summer15_25nsV7_MC_L2Relative_AK8PFchs.txt")
        process.MHTJetsPropertiesAK8.L3File = cms.string("Summer15_25nsV7_MC_L3Absolute_AK8PFchs.txt")
        process.MHTJetsPropertiesAK8.L2L3File = cms.string("NONE")

    from SemiLeptonicWVA.Utils.jetproperties_cfi import jetproperties
    process.JetsProperties = jetproperties.clone(
    JetTag  = cms.InputTag('slimmedJets'),
    MinPt = cms.double(-1),
    doJEC  = cms.bool(doJECCorrection),
    L1File = cms.string("Summer15_25nsV7_DATA_L1FastJet_AK4PFchs.txt"),
    L2File = cms.string("Summer15_25nsV7_DATA_L2Relative_AK4PFchs.txt"),
    L3File = cms.string("Summer15_25nsV7_DATA_L3Absolute_AK4PFchs.txt"),
    L2L3File = cms.string("Summer15_25nsV7_DATA_L2L3Residual_AK4PFchs.txt"),
    )
    from SemiLeptonicWVA.Utils.jetpropertiesAK8_cfi import jetpropertiesAK8
    process.JetsPropertiesAK8 = jetpropertiesAK8.clone(
    JetTag  = cms.InputTag('slimmedJetsAK8'),
    MinPt = cms.double(-1),
    doJEC  = cms.bool(doJECCorrection),
    doReclusteringForPrunedAndSoftdrop = cms.bool(reDoPruningAndSoftdrop),
    L1File = cms.string("Summer15_25nsV7_DATA_L1FastJet_AK8PFchs.txt"),
    L2File = cms.string("Summer15_25nsV7_DATA_L2Relative_AK8PFchs.txt"),
    L3File = cms.string("Summer15_25nsV7_DATA_L3Absolute_AK8PFchs.txt"),
    L2L3File = cms.string("Summer15_25nsV7_DATA_L2L3Residual_AK8PFchs.txt"),
    )
    if (reDoPruningAndSoftdrop):
        process.JetsPropertiesAK8.prunedJetTag  = cms.InputTag('selectedPatJetsAK8Pruned')
        process.JetsPropertiesAK8.softdropJetTag  = cms.InputTag('selectedPatJetsAK8Softdrop')
    else:
        process.JetsPropertiesAK8.prunedJetTag  = cms.InputTag('slimmedJetsAK8')
        process.JetsPropertiesAK8.softdropJetTag  = cms.InputTag('slimmedJetsAK8')
    if (MC):
        process.JetsProperties.L1File = cms.string("Summer15_25nsV7_MC_L1FastJet_AK4PFchs.txt")
        process.JetsProperties.L2File = cms.string("Summer15_25nsV7_MC_L2Relative_AK4PFchs.txt")
        process.JetsProperties.L3File = cms.string("Summer15_25nsV7_MC_L3Absolute_AK4PFchs.txt")
        process.JetsProperties.L2L3File = cms.string("NONE")
        process.JetsPropertiesAK8.L1File = cms.string("Summer15_25nsV7_MC_L1FastJet_AK8PFchs.txt")
        process.JetsPropertiesAK8.L2File = cms.string("Summer15_25nsV7_MC_L2Relative_AK8PFchs.txt")
        process.JetsPropertiesAK8.L3File = cms.string("Summer15_25nsV7_MC_L3Absolute_AK8PFchs.txt")
        process.JetsPropertiesAK8.L2L3File = cms.string("NONE")

    if doAK8Reclustering:
        process.JetsPropertiesAK8.JetTag = cms.InputTag('selectedPatJetsAK8')
    if doPuppi:
        process.JetsPropertiesAK8.JetTag = cms.InputTag('selectedPuppiJetsAK8')
    from SemiLeptonicWVA.Utils.mhtdouble_cfi import mhtdouble
    process.MHT = mhtdouble.clone(
    JetTag  = cms.InputTag('MHTJets'),
    )
    from SemiLeptonicWVA.Utils.deltaphidouble_cfi import deltaphidouble
    process.DeltaPhi = deltaphidouble.clone(
    DeltaPhiJets  = cms.InputTag('HTJets'),
    MHTJets  = cms.InputTag("MHTJets"),
    )
    from SemiLeptonicWVA.Utils.metdouble_cfi import metdouble
    process.MET = metdouble.clone(
    METTag  = cms.InputTag("slimmedMETs"),
    JetTag  = cms.InputTag('slimmedJets'),
    doJEC  = cms.bool(doJECCorrection),
    L1File = cms.string("Summer15_25nsV7_DATA_L1FastJet_AK4PFchs.txt"),
    L2File = cms.string("Summer15_25nsV7_DATA_L2Relative_AK4PFchs.txt"),
    L3File = cms.string("Summer15_25nsV7_DATA_L3Absolute_AK4PFchs.txt"),
    L2L3File = cms.string("Summer15_25nsV7_DATA_L2L3Residual_AK4PFchs.txt"),
    MuTag = cms.InputTag("slimmedMuons"),
    RhoTag = cms.InputTag("fixedGridRhoFastjetAll"),
    corrMet = cms.bool(doJECCorrection),
    )

    if (MC):
        process.MET.L1File = cms.string("Summer15_25nsV7_MC_L1FastJet_AK4PFchs.txt")
        process.MET.L2File = cms.string("Summer15_25nsV7_MC_L2Relative_AK4PFchs.txt")
        process.MET.L3File = cms.string("Summer15_25nsV7_MC_L3Absolute_AK4PFchs.txt")
        process.MET.L2L3File = cms.string("NONE")

    from SemiLeptonicWVA.Utils.primaryverticies_cfi import primaryverticies
    process.NVtx = primaryverticies.clone(
    VertexCollection  = cms.InputTag('offlineSlimmedPrimaryVertices'),
    )
    from SemiLeptonicWVA.Utils.genLeptonRecoCand_cfi import genLeptonRecoCand
    process.GenLeptons = genLeptonRecoCand.clone(
    PrunedGenParticleTag  = cms.InputTag("prunedGenParticles"),
    )
    from SemiLeptonicWVA.Utils.genJet_cfi import genJet
    process.GenJets = genJet.clone(
                            GenJetCollTag  = cms.InputTag("slimmedGenJets"),
                            )
    from SemiLeptonicWVA.Utils.genJetAK8_cfi import genJetAK8
    process.GenJetsAK8 = genJetAK8.clone(
                            GenJetCollTag  = cms.InputTag("selectedGenJetsAK8"),
                            )
    if not MC:
        process.GenLeptons = cms.Sequence()
        process.GenJets = cms.Sequence()
        process.GenJetsAK8 = cms.Sequence()



    ##### MET filters #####

    #### -----> MET Filter Flags from MiniAOD/TWiki <----- ####
    import HLTrigger.HLTfilters.triggerResultsFilter_cfi as hlt
    process.metBits_miniAOD = hlt.triggerResultsFilter.clone()
    # default is to use the latest process (but can set different process through Commandline Args)
    process.metBits_miniAOD.hltResults = cms.InputTag('TriggerResults::%s'%METFiltersProcess) 
    process.metBits_miniAOD.l1tResults = cms.InputTag('')
    #currently configured for CSCTightHaloFilter + GoodVertices
    met_bits = ['(Flag_CSCTightHaloFilter)','(Flag_goodVertices)','(Flag_eeBadScFilter)']
    bitsexpr = ' AND '.join(met_bits)
    process.metBits_miniAOD.triggerConditions = cms.vstring(bitsexpr)

    #### -----> HBHE noise filter <----- ####
    process.load('CommonTools.RecoAlgos.HBHENoiseFilterResultProducer_cfi')
    process.HBHENoiseFilterResultProducer.minZeros = cms.int32(99999)
    process.HBHENoiseFilterResultProducer.IgnoreTS4TS5ifJetInLowBVRegion=cms.bool(False) 
    process.HBHENoiseFilterResultProducer.defaultDecision = cms.string("HBHENoiseFilterResultRun2Loose")
    
    ########## save flags for filters
    from SemiLeptonicWVA.Utils.filterproducer_cfi import filterProducer
    process.FilterProducer = filterProducer.clone(
                                 noiseFilterTag = cms.InputTag("TriggerResults"),
                                 HBHENoiseFilter_Selector_ = cms.string("Flag_HBHENoiseFilter"),
                                 HBHENoiseIsoFilter_Selector_ = cms.string("Flag_HBHENoiseIsoFilter"),
                                 CSCHaloNoiseFilter_Selector_ = cms.string("Flag_CSCTightHaloFilter"),
                                 GoodVtxNoiseFilter_Selector_ = cms.string("Flag_goodVertices"),
                                 EEBadScNoiseFilter_Selector_ = cms.string("Flag_eeBadScFilter"),
                                 HBHENoiseFilterLoose = cms.InputTag("HBHENoiseFilterResultProducer", "HBHENoiseFilterResultRun2Loose"),
                                 HBHENoiseFilterTight = cms.InputTag("HBHENoiseFilterResultProducer", "HBHENoiseFilterResultRun2Tight"),
                                 HBHENoiseIsoFilter = cms.InputTag("HBHENoiseFilterResultProducer", "HBHEIsoNoiseFilterResult")
                                 )


    RecoCandVector = cms.vstring()
    RecoCandVector.extend(['IsolatedTracks']) # basic muons electrons and isoalted tracks
    RecoCandVector.extend(['GenLeptons:Boson(GenBoson)|GenLeptons:BosonPDGId(I_GenBosonPDGId)','GenLeptons:Muon(GenMu)|GenLeptons:MuonTauDecay(I_GenMuFromTau)' ,'GenLeptons:Electron(GenElec)|GenLeptons:ElectronTauDecay(I_GenElecFromTau)','GenLeptons:Tau(GenTau)|GenLeptons:TauHadronic(I_GenTauHad)','GenLeptons:Neutrino(GenNu)'] ) # gen information on leptons
    RecoCandVector.extend(['GenJets:GenJet(GenJets)'] ) # gen information on jets
    RecoCandVector.extend(['GenJetsAK8:GenJetAK8(GenJetsAK8)|GenJetsAK8:GenAK8prunedMass(F_prunedMass)|GenJetsAK8:GenAK8softdropMass(F_softdropMass)|GenJetsAK8:GenAK8tau1(F_tau1)|GenJetsAK8:GenAK8tau2(F_tau2)|GenJetsAK8:GenAK8tau3(F_tau3)'] ) # gen information on AK8 jets
    RecoCandVector.extend(['JetsProperties(Jets)|JetsProperties:bDiscriminatorCSV(F_bDiscriminatorCSV)|JetsProperties:bDiscriminatorICSV(F_bDiscriminatorICSV)|JetsProperties:chargedEmEnergyFraction(F_chargedEmEnergyFraction)|JetsProperties:chargedHadronEnergyFraction(F_chargedHadronEnergyFraction)|JetsProperties:chargedHadronMultiplicity(I_chargedHadronMultiplicity)|JetsProperties:electronMultiplicity(I_electronMultiplicity)|JetsProperties:jetArea(F_jetArea)|JetsProperties:muonEnergyFraction(F_muonEnergyFraction)|JetsProperties:muonMultiplicity(I_muonMultiplicity)|JetsProperties:neutralEmEnergyFraction(F_neutralEmEnergyFraction)|JetsProperties:neutralHadronMultiplicity(I_neutralHadronMultiplicity)|JetsProperties:photonEnergyFraction(F_photonEnergyFraction)|JetsProperties:photonMultiplicity(I_photonMultiplicity)|JetsProperties:isLooseJetId(b_isLooseJetId)|JetsProperties:isTightJetId(b_isTightJetId)|JetsProperties:isTightLepVetoJetId(b_isTightLepVetoJetId)|JetsProperties:PtCorr(F_PtCorr)|JetsProperties:EtaCorr(F_EtaCorr)|JetsProperties:PhiCorr(F_PhiCorr)|JetsProperties:ECorr(F_ECorr)'] ) # jet information on various variables
    RecoCandVector.extend(['JetsPropertiesAK8(AK8Jets)|JetsPropertiesAK8:AK8bDiscriminatorCSV(F_bDiscriminatorCSV)|JetsPropertiesAK8:AK8bDiscriminatorICSV(F_bDiscriminatorICSV)|JetsPropertiesAK8:AK8chargedEmEnergyFraction(F_chargedEmEnergyFraction)|JetsPropertiesAK8:AK8chargedHadronEnergyFraction(F_chargedHadronEnergyFraction)|JetsPropertiesAK8:AK8chargedHadronMultiplicity(I_chargedHadronMultiplicity)|JetsPropertiesAK8:AK8electronMultiplicity(I_electronMultiplicity)|JetsPropertiesAK8:AK8jetArea(F_jetArea)|JetsPropertiesAK8:AK8muonEnergyFraction(F_muonEnergyFraction)|JetsPropertiesAK8:AK8muonMultiplicity(I_muonMultiplicity)|JetsPropertiesAK8:AK8neutralEmEnergyFraction(F_neutralEmEnergyFraction)|JetsPropertiesAK8:AK8neutralHadronMultiplicity(I_neutralHadronMultiplicity)|JetsPropertiesAK8:AK8photonEnergyFraction(F_photonEnergyFraction)|JetsPropertiesAK8:AK8photonMultiplicity(I_photonMultiplicity)|JetsPropertiesAK8:AK8prunedMass(F_prunedMass)|JetsPropertiesAK8:AK8softDropMass(F_softDropMass)|JetsPropertiesAK8:AK8trimmedMass(F_trimmedMass)|JetsPropertiesAK8:AK8filteredMass(F_filteredMass)|JetsPropertiesAK8:AK8tau1(F_tau1)|JetsPropertiesAK8:AK8tau2(F_tau2)|JetsPropertiesAK8:AK8tau3(F_tau3)|JetsPropertiesAK8:AK8isLooseJetId(b_AK8isLooseJetId)|JetsPropertiesAK8:AK8isTightJetId(b_AK8isTightJetId)|JetsPropertiesAK8:AK8isTightLepVetoJetId(b_AK8isTightLepVetoJetId)|JetsPropertiesAK8:PtCorr(F_PtCorr)|JetsPropertiesAK8:EtaCorr(F_EtaCorr)|JetsPropertiesAK8:PhiCorr(F_PhiCorr)|JetsPropertiesAK8:ECorr(F_ECorr)'] ) # AK8 jet information on various variables
# 
    RecoCandVector.extend(['Electrons(Electrons)|Electrons:charge(I_charge)|Electrons:isHEEP(b_isHEEP)|Electrons:type(I_type)|Electrons:mass(F_mass)|Electrons:pfDeltaCorrRelIso(F_pfDeltaCorrRelIso)|Electrons:pfRhoCorrRelIso04(F_pfRhoCorrRelIso04)|Electrons:pfRhoCorrRelIso03(F_pfRhoCorrRelIso03)|Electrons:pfRelIso(F_pfRelIso)|Electrons:photonIso(F_photonIso)|Electrons:neutralHadIso(F_neutralHadIso)|Electrons:chargedHadIso(F_chargedHadIso)|Electrons:trackIso(F_trackIso)|Electrons:isLoose(b_isLoose)|Electrons:isMedium(b_isMedium)|Electrons:isTight(b_isTight)|Electrons:SCEnergy(F_SCEnergy)|Electrons:deltaEtaSCTracker(F_deltaEtaSCTracker)|Electrons:deltaPhiSCTracker(F_deltaPhiSCTracker)|Electrons:sigmaIetaIeta(F_sigmaIetaIeta)|Electrons:sigmaIphiIphi(F_sigmaIphiIphi)'] ) # electron information on various variables
    RecoCandVector.extend(['Muons(Muons)|Muons:charge(I_charge)|Muons:isHighPt(b_isHighPt)|Muons:type(I_type)|Muons:mass(F_mass)|Muons:pfDeltaCorrRelIso(F_pfDeltaCorrRelIso)|Muons:pfRelIso(F_pfRelIso)|Muons:photonIso(F_photonIso)|Muons:neutralHadIso(F_neutralHadIso)|Muons:chargedHadIso(F_chargedHadIso)|Muons:trackIso(F_trackIso)|Muons:isLoose(b_isLoose)|Muons:isMedium(b_isMedium)|Muons:isTight(b_isTight)|Muons:isPFMuon(b_isPFMuon)'] ) # muon information on various variables
    RecoCandVector.extend(['Photons(Photons)|Photons:isLoose(b_isLoose)|Photons:isMedium(b_isMedium)|Photons:isTight(b_isTight)|Photons:minPt(F_minPt)|Photons:phoSCEtaMultiRange(F_phoSCEtaMultiRange)|Photons:phoSingleTowerHadOverEm(F_phoSingleTowerHadOverEm)|Photons:phoFull5x5SigmaIEtaIEta(F_phoFull5x5SigmaIEtaIEta)|Photons:phoAnyPFIsoWithEA(F_phoAnyPFIsoWithEA)|Photons:phoAnyPFIsoWithEAAndExpoScaling(F_phoAnyPFIsoWithEAAndExpoScaling)|Photons:phoAnyPFIsoWithEA1(F_phoAnyPFIsoWithEA1)|Photons:hasPixelSeed(b_hasPixelSeed)|Photons:passElectronVeto(b_passElectronVeto)|Photons:photonIso(F_photonIso)|Photons:neutralHadIso(F_neutralHadIso)|Photons:chargedHadIso(F_chargedHadIso)|Photons:puChargedHadIso(F_puChargedHadIso)|Photons:sigmaIetaIeta(F_sigmaIetaIeta)'] ) # photon information on various variables

    from SemiLeptonicWVA.TreeMaker.treeMaker import TreeMaker
    process.TreeMaker2 = TreeMaker.clone(
    	TreeName          = cms.string("PreSelection"),
    	VarsRecoCand = RecoCandVector,
    	VarsDouble  	  = cms.vstring('WeightProducer:weight(Weight)','MHT','MET:Pt(METPt)','MET:Phi(METPhi)','MET:PtRaw(METPtRaw)','MET:PhiRaw(METPhiRaw)','MET:CaloMetPt(CaloMetPt)','MET:CaloMetPhi(CaloMetPhi)','HT','DeltaPhi:DeltaPhi1(DeltaPhi1)','DeltaPhi:DeltaPhi2(DeltaPhi2)','DeltaPhi:DeltaPhi3(DeltaPhi3)','GenEventInfo:genEventWeight(genEventWeight)','GenEventInfo:PUWeight(PUWeight)','GenEventInfo:originalWeight(originalWeight)'),
    	VarsInt = cms.vstring('NJets','BTags','NVtx','GenEventInfo:npT(npT)','FilterProducer:passFilterHBHE(passFilterHBHE)','FilterProducer:passFilterHBHEIso(passFilterHBHEIso)','FilterProducer:passFilterCSCHalo(passFilterCSCHalo)','FilterProducer:passFilterGoodVtx(passFilterGoodVtx)','FilterProducer:passFilterEEBadSC(passFilterEEBadSC)','FilterProducer:passFilterHBHELooseRerun(passFilterHBHELooseRerun)','FilterProducer:passFilterHBHETightRerun(passFilterHBHETightRerun)','FilterProducer:passFilterHBHEIsoRerun(passFilterHBHEIsoRerun)'),
        debug = debug,
    	)

    process.TreeMaker2.VarsDouble.extend(['MET:PtDefault(METPtDefault)','MET:PhiDefault(METPhiDefault)','MET:PtType1(METPtType1)','MET:PhiType1(METPhiType1)','MET:PtType1XYSmear(METPtType1XYSmear)','MET:PhiType1XYSmear(METPhiType1XYSmear)','MET:PtType1Smear(METPtType1Smear)','MET:PhiType1Smear(METPhiType1Smear)','MET:PtType1XY(METPtType1XY)','MET:PhiType1XY(METPhiType1XY)'])
    process.TreeMaker2.VectorBool.extend(['TriggerProducer:TriggerPass'])
    process.TreeMaker2.VectorInt.extend(['TriggerProducer:TriggerPrescales'])
    process.TreeMaker2.VectorDouble.extend(['GenEventInfo:AQGCweights'])
    process.TreeMaker2.VectorString.extend(['TriggerProducer:TriggerNames'])

    ## --- Final paths ----------------------------------------------------
    process.out = cms.OutputModule("PoolOutputModule",
                                   fileName = cms.untracked.string("output.root"),
                                   )
        
    process.dump = cms.EDAnalyzer("EventContentAnalyzer")
    process.WriteTree = cms.Path(
      process.TriggerProducer*
      ### MET Filter Bits
      process.HBHENoiseFilterResultProducer*
      process.FilterProducer* #this now contains all the met filters
      ### rest of ntupling starts after here
      process.filterSeq *
      process.GenEventInfo *
      process.Muons *
      process.egmGsfElectronIDSequence*
      process.Electrons *
      process.egmPhotonIDSequence *
      process.Photons *
      process.WeightProducer *
      process.IsolatedTracks *
      process.substructureSequenceGen *
      process.softdropGen_onMiniAOD *
      process.pruningGen_onMiniAOD *
      process.redoGenJets*
      process.GenJetsAK8 *
      process.puppi_onMiniAOD *
      process.substructureSequence *
      process.softdrop_onMiniAOD *
      process.pruning_onMiniAOD *
      process.redoPatJets*
      process.redoPuppiJets*
      process.HTJets *
      process.HT *
      process.NJets *
      process.BTags *
      process.MHTJets *
      process.MHTJetsProperties *
      process.JetsProperties *
      process.MHTJetsAK8 *
      process.MHTJetsPropertiesAK8 *
      process.JetsPropertiesAK8 *
      process.MHT *
      process.MET *
      process.DeltaPhi *
      process.NVtx *
      process.GenLeptons *
      process.GenJets *
      process.TreeMaker2

        )
Beispiel #12
0
process.NjettinessAK8 = cms.EDProducer("NjettinessAdder",
                   src = cms.InputTag("ak8PFJetsCHS"),
                   Njets = cms.vuint32(1, 2, 3, 4),
                   # variables for measure definition : 
                   measureDefinition = cms.uint32( 0 ), # CMS default is normalized measure
                   beta = cms.double(1.0),          # CMS default is 1
                   R0 = cms.double( 0.8 ),          # CMS default is jet cone size
                   Rcutoff = cms.double( -999.0),       # not used by default
                   # variables for axes definition :
                   axesDefinition = cms.uint32( 6 ),    # CMS default is 1-pass KT axes
                   nPass = cms.int32(-999),         # not used by default
                   akAxesR0 = cms.double(-999.0)        # not used by default
                   )
process.ak4PFJetsCHS = ak4PFJetsCHS.clone(src = 'chs')
process.ak8PFJetsCHS = ak8PFJetsCHS.clone( src = 'chs', jetPtMin = 100.0 )
process.ak8PFJetsCHSPruned = ak8PFJetsCHSPruned.clone( src = 'chs', jetPtMin = 100.0  )
process.ak8PFJetsCHSPrunedMass = ak8PFJetsCHSPrunedMass.clone()
process.ak8PFJetsCHSSoftDrop = ak8PFJetsCHSSoftDrop.clone( src = 'chs', jetPtMin = 100.0  )
process.ak8PFJetsCHSSoftDropMass = ak8PFJetsCHSSoftDropMass.clone()

process.substructureSequence = cms.Sequence()
if doAK8reclustering:
   process.substructureSequence+=process.chs
   process.substructureSequence+=process.ak8PFJetsCHS
   process.substructureSequence+=process.NjettinessAK8
if doAK8prunedReclustering:
   process.substructureSequence+=process.ak8PFJetsCHSPruned
   process.substructureSequence+=process.ak8PFJetsCHSPrunedMass
if doAK8softdropReclustering:
   process.substructureSequence+=process.ak8PFJetsCHSSoftDrop
   process.substructureSequence+=process.ak8PFJetsCHSSoftDropMass
def miniAOD_customizeCommon(process):
    process.patMuons.isoDeposits = cms.PSet()
    process.patElectrons.isoDeposits = cms.PSet()
    process.patTaus.isoDeposits = cms.PSet()
    process.patPhotons.isoDeposits = cms.PSet()
    #
    process.patMuons.embedTrack         = True  # used for IDs
    process.patMuons.embedCombinedMuon  = True  # used for IDs
    process.patMuons.embedMuonBestTrack = True  # used for IDs
    process.patMuons.embedStandAloneMuon = True # maybe?
    process.patMuons.embedPickyMuon = False   # no, use best track
    process.patMuons.embedTpfmsMuon = False   # no, use best track
    process.patMuons.embedDytMuon   = False   # no, use best track
    #
    # disable embedding of electron and photon associated objects already stored by the ReducedEGProducer
    process.patElectrons.embedGsfElectronCore = False  ## process.patElectrons.embed in AOD externally stored gsf electron core
    process.patElectrons.embedSuperCluster    = False  ## process.patElectrons.embed in AOD externally stored supercluster
    process.patElectrons.embedPflowSuperCluster         = False  ## process.patElectrons.embed in AOD externally stored supercluster
    process.patElectrons.embedSeedCluster               = False  ## process.patElectrons.embed in AOD externally stored the electron's seedcluster 
    process.patElectrons.embedBasicClusters             = False  ## process.patElectrons.embed in AOD externally stored the electron's basic clusters 
    process.patElectrons.embedPreshowerClusters         = False  ## process.patElectrons.embed in AOD externally stored the electron's preshower clusters 
    process.patElectrons.embedPflowBasicClusters        = False  ## process.patElectrons.embed in AOD externally stored the electron's pflow basic clusters 
    process.patElectrons.embedPflowPreshowerClusters    = False  ## process.patElectrons.embed in AOD externally stored the electron's pflow preshower clusters 
    process.patElectrons.embedRecHits         = False  ## process.patElectrons.embed in AOD externally stored the RecHits - can be called from the PATElectronProducer 
    process.patElectrons.electronSource = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.patElectrons.electronIDSources = cms.PSet(
            # configure many IDs as InputTag <someName> = <someTag> you
            # can comment out those you don't want to save some disk space
            eidRobustLoose      = cms.InputTag("reducedEgamma","eidRobustLoose"),
            eidRobustTight      = cms.InputTag("reducedEgamma","eidRobustTight"),
            eidLoose            = cms.InputTag("reducedEgamma","eidLoose"),
            eidTight            = cms.InputTag("reducedEgamma","eidTight"),
            eidRobustHighEnergy = cms.InputTag("reducedEgamma","eidRobustHighEnergy"),
        )
    process.elPFIsoDepositCharged.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositChargedAll.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositNeutral.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositGamma.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositPU.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    #
    process.patPhotons.embedSuperCluster = False ## whether to process.patPhotons.embed in AOD externally stored supercluster
    process.patPhotons.embedSeedCluster               = False  ## process.patPhotons.embed in AOD externally stored the photon's seedcluster 
    process.patPhotons.embedBasicClusters             = False  ## process.patPhotons.embed in AOD externally stored the photon's basic clusters 
    process.patPhotons.embedPreshowerClusters         = False  ## process.patPhotons.embed in AOD externally stored the photon's preshower clusters 
    process.patPhotons.embedRecHits         = False  ## process.patPhotons.embed in AOD externally stored the RecHits - can be called from the PATPhotonProducer 
    process.patPhotons.photonSource = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.patPhotons.photonIDSources = cms.PSet(
                PhotonCutBasedIDLoose = cms.InputTag('reducedEgamma',
                                                      'PhotonCutBasedIDLoose'),
                PhotonCutBasedIDTight = cms.InputTag('reducedEgamma',
                                                      'PhotonCutBasedIDTight')
              )

    process.phPFIsoDepositCharged.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositChargedAll.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositNeutral.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositGamma.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositPU.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    #
    process.selectedPatJets.cut = cms.string("pt > 10")
    process.selectedPatMuons.cut = cms.string("pt > 5 || isPFMuon || (pt > 3 && (isGlobalMuon || isStandAloneMuon || numberOfMatches > 0 || muonID('RPCMuLoose')))") 
    process.selectedPatElectrons.cut = cms.string("") 
    process.selectedPatTaus.cut = cms.string("pt > 18. && tauID('decayModeFinding')> 0.5")
    process.selectedPatPhotons.cut = cms.string("")
    #
    from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection
    #switch to AK4 for CSA14/70X release (should be default in 71X)
    switchJetCollection(process, jetSource = cms.InputTag('ak4PFJetsCHS'),  
    jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), ''),
    btagDiscriminators = ['jetBProbabilityBJetTags', 'jetProbabilityBJetTags', 'trackCountingHighPurBJetTags', 'trackCountingHighEffBJetTags', 'simpleSecondaryVertexHighEffBJetTags',
                         'simpleSecondaryVertexHighPurBJetTags', 'combinedSecondaryVertexBJetTags' , 'combinedInclusiveSecondaryVertexBJetTags' ],
    )
    #add CA8   
    from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection
    addJetCollection(process, labelName = 'AK8', jetSource = cms.InputTag('ak8PFJetsCHS'),algo= 'AK', rParam = 0.8, jetCorrections = ('AK7PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None') )
    process.patJetsAK8.userData.userFloats.src = [] # start with empty list of user floats
    process.selectedPatJetsAK8.cut = cms.string("pt > 100")
    process.patJetGenJetMatchAK8.matched =  'slimmedGenJets'
    ## AK8 groomed masses
    from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSPruned, ak8PFJetsCHSFiltered, ak8PFJetsCHSTrimmed 
    process.ak8PFJetsCHSPruned   = ak8PFJetsCHSPruned.clone()
    process.ak8PFJetsCHSTrimmed  = ak8PFJetsCHSTrimmed.clone()
    process.ak8PFJetsCHSFiltered = ak8PFJetsCHSFiltered.clone()
    process.load("RecoJets.JetProducers.ak8PFJetsCHS_groomingValueMaps_cfi")
    process.patJetsAK8.userData.userFloats.src += ['ak8PFJetsCHSPrunedLinks','ak8PFJetsCHSTrimmedLinks','ak8PFJetsCHSFilteredLinks']
    ### CA8 groomed masses (for the matched jet): doesn't seem to work, it produces tons of warnings "Matched jets separated by dR greater than distMax=0.8"
    # from RecoJets.Configuration.RecoPFJets_cff import ca8PFJetsCHSFiltered, ca8PFJetsCHSTrimmed # ca8PFJetsCHSPruned is already in AOD
    # process.ca8PFJetsCHSTrimmed  = ca8PFJetsCHSTrimmed.clone()
    # process.ca8PFJetsCHSFiltered = ca8PFJetsCHSFiltered.clone()
    # process.load("RecoJets.JetProducers.ca8PFJetsCHS_groomingValueMaps_cfi")
    # process.ca8PFJetsCHSPrunedLinks.src   = cms.InputTag("ak8PFJetsCHS")
    # process.ca8PFJetsCHSTrimmedLinks.src  = cms.InputTag("ak8PFJetsCHS")
    # process.ca8PFJetsCHSFilteredLinks.src = cms.InputTag("ak8PFJetsCHS")
    # process.patJetsAK8.userData.userFloats.src += ['ca8PFJetsCHSPrunedLinks','ca8PFJetsCHSTrimmedLinks','ca8PFJetsCHSFilteredLinks']
    ## cmsTopTagger (note: it is already run in RECO, we just add the value)
    process.cmsTopTagPFJetsCHSLinksAK8 = process.ak8PFJetsCHSPrunedLinks.clone()
    process.cmsTopTagPFJetsCHSLinksAK8.src = cms.InputTag("ak8PFJetsCHS")
    process.cmsTopTagPFJetsCHSLinksAK8.matched = cms.InputTag("cmsTopTagPFJetsCHS")
    process.patJetsAK8.userData.userFloats.src += ['cmsTopTagPFJetsCHSLinksAK8']

    #
    from PhysicsTools.PatAlgos.tools.trigTools import switchOnTriggerStandAlone
    switchOnTriggerStandAlone( process, outputModule = '' )
    process.patTrigger.packTriggerPathNames = cms.bool(True)
    #
    # apply type I/type I + II PFMEt corrections to pat::MET object
    # and estimate systematic uncertainties on MET
    from PhysicsTools.PatUtils.tools.metUncertaintyTools import runMEtUncertainties
    addJetCollection(process, postfix   = "ForMetUnc", labelName = 'AK5PF', jetSource = cms.InputTag('ak5PFJets'), jetCorrections = ('AK5PF', ['L1FastJet', 'L2Relative', 'L3Absolute'], ''))
    runMEtUncertainties(process,jetCollection="selectedPatJetsAK5PFForMetUnc", outputModule=None)

    #keep this after all addJetCollections otherwise it will attempt computing them also for stuf with no taginfos
    #Some useful BTAG vars
    process.patJets.userData.userFunctions = cms.vstring(
    '?(tagInfoSecondaryVertex().nVertices()>0)?(tagInfoSecondaryVertex().secondaryVertex(0).p4.M):(0)',
    '?(tagInfoSecondaryVertex().nVertices()>0)?(tagInfoSecondaryVertex().secondaryVertex(0).nTracks):(0)',
    '?(tagInfoSecondaryVertex().nVertices()>0)?(tagInfoSecondaryVertex().flightDistance(0).value):(0)',
    '?(tagInfoSecondaryVertex().nVertices()>0)?(tagInfoSecondaryVertex().flightDistance(0).significance):(0)',
    )
    process.patJets.userData.userFunctionLabels = cms.vstring('vtxMass','vtxNtracks','vtx3DVal','vtx3DSig')
    process.patJets.tagInfoSources = cms.VInputTag(cms.InputTag("secondaryVertexTagInfos"))
    process.patJets.addTagInfos = cms.bool(True)
    #
    ## PU JetID
    process.load("PhysicsTools.PatAlgos.slimming.pileupJetId_cfi")
    process.patJets.userData.userFloats.src = [ cms.InputTag("pileupJetId:fullDiscriminant"), ]
Beispiel #14
0
def jetToolbox(
    proc,
    jetType,
    jetSequence,
    outputFile,
    PUMethod="CHS",  #### Options: Puppi, CS, SK, Plain
    miniAOD=True,
    JETCorrPayload="None",
    JETCorrLevels=["None"],
    GetJetMCFlavour=True,
    Cut="",
    subJETCorrPayload="None",
    subJETCorrLevels=["None"],
    GetSubjetMCFlavour=False,
    CutSubjet="",
    addPruning=False,
    zCut=0.1,
    rCut=0.5,
    addPrunedSubjets=False,
    addSoftDrop=False,
    betaCut=0.0,
    zCutSD=0.1,
    addSoftDropSubjets=False,
    addTrimming=False,
    rFiltTrim=0.2,
    ptFrac=0.03,
    addFiltering=False,
    rfilt=0.3,
    nfilt=3,
    addCMSTopTagger=False,
    addMassDrop=False,
    addHEPTopTagger=False,
    addNsub=False,
    maxTau=4,
    addPUJetID=False,
    addQJets=False,
):

    ###############################################################################
    #######  Verifying some inputs and defining variables
    ###############################################################################
    print "|---- jetToolbox: Initialyzing collection..."
    supportedJetAlgos = {"ak": "AntiKt", "ca": "CambridgeAachen", "kt": "Kt"}
    recommendedJetAlgos = ["ak4", "ak8", "ca4", "ca8", "ca10"]
    payloadList = [
        "AK1PFchs",
        "AK2PFchs",
        "AK3PFchs",
        "AK4PFchs",
        "AK5PFchs",
        "AK6PFchs",
        "AK7PFchs",
        "AK8PFchs",
        "AK9PFchs",
        "AK10PFchs",
        "AK1PFPUPPI",
        "AK2PFPUPPI",
        "AK3PFPUPPI",
        "AK4PFPUPPI",
        "AK5PFPUPPI",
        "AK6PFPUPPI",
        "AK7PFPUPPI",
        "AK8PFPUPPI",
        "AK9PFPUPPI",
        "AK10PFPUPPI",
        "AK1PFSK",
        "AK2PFSK",
        "AK3PFSK",
        "AK4PFSK",
        "AK5PFSK",
        "AK6PFSK",
        "AK7PFSK",
        "AK8PFSK",
        "AK9PFSK",
        "AK10PFSK",
        "AK1PF",
        "AK2PF",
        "AK3PF",
        "AK4PF",
        "AK5PF",
        "AK6PF",
        "AK7PF",
        "AK8PF",
        "AK9PF",
        "AK10PF",
    ]
    JECLevels = ["L1Offset", "L1FastJet", "L1JPTOffset", "L2Relative", "L3Absolute", "L5Falvour", "L7Parton"]
    jetAlgo = ""
    algorithm = ""
    size = ""
    for type, tmpAlgo in supportedJetAlgos.iteritems():
        if type in jetType.lower():
            jetAlgo = type
            algorithm = tmpAlgo
            size = jetType.replace(type, "")

    jetSize = 0.0
    if int(size) in range(0, 20):
        jetSize = int(size) / 10.0
    else:
        print "|---- jetToolBox: jetSize has not a valid value. Insert a number between 1 and 20 after algorithm, like: AK8"
    ### Trick for uppercase/lowercase algo name
    jetALGO = jetAlgo.upper() + size
    jetalgo = jetAlgo.lower() + size
    if jetalgo not in recommendedJetAlgos:
        print "|---- jetToolBox: CMS recommends the following jet algoritms: " + " ".join(
            recommendedJetAlgos
        ) + ". You are using", jetalgo, "."

    #################################################################################
    ####### Toolbox start
    #################################################################################

    elemToKeep = []
    jetSeq = cms.Sequence()
    genParticlesLabel = ""
    pvLabel = ""
    tvLabel = ""
    toolsUsed = []

    #### For MiniAOD
    if miniAOD:

        print "|---- jetToolBox: JETTOOLBOX RUNNING ON MiniAOD FOR " + jetALGO + " JETS USING " + PUMethod

        genParticlesLabel = "prunedGenParticles"
        pvLabel = "offlineSlimmedPrimaryVertices"
        svLabel = "slimmedSecondaryVertices"
        tvLabel = "unpackedTracksAndVertices"
        pfCand = "packedPFCandidates"

        setattr(
            proc,
            "chs",
            cms.EDFilter("CandPtrSelector", src=cms.InputTag("packedPFCandidates"), cut=cms.string("fromPV")),
        )
        jetSeq += getattr(proc, "chs")

        ## Filter out neutrinos from packed GenParticles
        setattr(
            proc,
            "packedGenParticlesForJetsNoNu",
            cms.EDFilter(
                "CandPtrSelector",
                src=cms.InputTag("packedGenParticles"),
                cut=cms.string("abs(pdgId) != 12 && abs(pdgId) != 14 && abs(pdgId) != 16"),
            ),
        )
        jetSeq += getattr(proc, "packedGenParticlesForJetsNoNu")

        setattr(
            proc,
            jetalgo + "GenJetsNoNu",
            ak4GenJets.clone(src="packedGenParticlesForJetsNoNu", rParam=jetSize, jetAlgorithm=algorithm),
        )
        jetSeq += getattr(proc, jetalgo + "GenJetsNoNu")

        # for Inclusive Vertex Finder
        proc.load("PhysicsTools.PatAlgos.slimming.unpackedTracksAndVertices_cfi")

        #### For AOD
    else:
        print "|---- jetToolBox: JETTOOLBOX RUNNING ON AOD FOR " + jetALGO + " JETS USING " + PUMethod

        genParticlesLabel = "genParticles"
        pvLabel = "offlinePrimaryVertices"
        tvLabel = "generalTracks"
        pfCand = "particleFlow"
        svLabel = "inclusiveSecondaryVertices"

        proc.load("RecoJets.Configuration.GenJetParticles_cff")
        proc.load("CommonTools.ParticleFlow.pfNoPileUpJME_cff")
        setattr(
            proc,
            jetalgo + "GenJetsNoNu",
            ak4GenJets.clone(src="genParticlesForJetsNoNu", rParam=jetSize, jetAlgorithm=algorithm),
        )
        jetSeq += getattr(proc, jetalgo + "GenJetsNoNu")

        ## b-tag discriminators
    bTagDiscriminators = [
        "pfTrackCountingHighEffBJetTags",
        "pfTrackCountingHighPurBJetTags",
        "pfJetProbabilityBJetTags",
        "pfJetBProbabilityBJetTags",
        "pfSimpleSecondaryVertexHighEffBJetTags",
        "pfSimpleSecondaryVertexHighPurBJetTags",
        "pfCombinedSecondaryVertexV2BJetTags",
        "pfCombinedSecondaryVertexBJetTags",
        #'pfcombinedInclusiveSecondaryVertexV2BJetTags',
        #'pfCombinedSecondaryVertexSoftLeptonBJetTags',
        #'pfCombinedMVABJetTags'
    ]

    ####  Creating PATjets
    if "Puppi" in PUMethod:

        proc.load("CommonTools.PileupAlgos.Puppi_cff")
        from RecoJets.JetProducers.ak4PFJetsPuppi_cfi import ak4PFJetsPuppi

        setattr(
            proc,
            jetalgo + "PFJetsPuppi",
            ak4PFJetsPuppi.clone(doAreaFastjet=True, rParam=jetSize, jetAlgorithm=algorithm),
        )
        if miniAOD:
            puppi.candName = cms.InputTag("packedPFCandidates")
            puppi.vertexName = cms.InputTag("offlineSlimmedPrimaryVertices")
        jetSeq += getattr(proc, "puppi")
        jetSeq += getattr(proc, jetalgo + "PFJetsPuppi")

    elif "CS" in PUMethod:

        from RecoJets.JetProducers.ak4PFJetsCS_cfi import ak4PFJetsCS

        setattr(
            proc,
            jetalgo + "PFJetsCS",
            ak4PFJetsCS.clone(doAreaFastjet=True, csRParam=cms.double(jetSize), jetAlgorithm=algorithm),
        )
        # if miniAOD: getattr( proc, jetalgo+'PFJetsCS').src = 'chs'
        if miniAOD:
            getattr(proc, jetalgo + "PFJetsCS").src = "packedPFCandidates"
        # setattr( proc, jetalgo+'PFJetsCSConstituents', ak8PFJetsCSConstituents.clone( src = cms.InputTag(jetalgo+'PFJetsCS') ) )
        jetSeq += getattr(proc, jetalgo + "PFJetsCS")

        # setattr( proc, jetalgo+'PFJetsCSConstituents', ak8PFJetsCSConstituents.clone( src = cms.InputTag(jetalgo+'PFJetsCS') ) )
        jetSeq += getattr(proc, jetalgo + "PFJetsCS")

    elif "SK" in PUMethod:

        proc.load("CommonTools.PileupAlgos.softKiller_cfi")
        from RecoJets.JetProducers.ak4PFJetsSK_cfi import ak4PFJetsSK

        setattr(proc, jetalgo + "PFJetsSK", ak4PFJetsSK.clone(rParam=jetSize, jetAlgorithm=algorithm))
        if miniAOD:
            getattr(proc, "softKiller").PFCandidates = cms.InputTag("packedPFCandidates")
        jetSeq += getattr(proc, "softKiller")
        jetSeq += getattr(proc, jetalgo + "PFJetsSK")

    elif "CHS" in PUMethod:
        setattr(
            proc, jetalgo + "PFJetsCHS", ak4PFJetsCHS.clone(doAreaFastjet=True, rParam=jetSize, jetAlgorithm=algorithm)
        )
        if miniAOD:
            getattr(proc, jetalgo + "PFJetsCHS").src = "chs"
        jetSeq += getattr(proc, jetalgo + "PFJetsCHS")

    else:
        PUMethod = ""
        setattr(proc, jetalgo + "PFJets", ak4PFJets.clone(doAreaFastjet=True, rParam=jetSize, jetAlgorithm=algorithm))
        if miniAOD:
            getattr(proc, jetalgo + "PFJets").src = "packedPFCandidates"
        jetSeq += getattr(proc, jetalgo + "PFJets")

    if miniAOD:
        setattr(
            proc,
            jetalgo + "PFJets" + PUMethod + "Constituents",
            cms.EDFilter(
                "MiniAODJetConstituentSelector", src=cms.InputTag(jetalgo + "PFJets" + PUMethod), cut=cms.string(Cut)
            ),
        )
    else:
        setattr(
            proc,
            jetalgo + "PFJets" + PUMethod + "Constituents",
            cms.EDFilter(
                "PFJetConstituentSelector", src=cms.InputTag(jetalgo + "PFJets" + PUMethod), cut=cms.string(Cut)
            ),
        )
    jetSeq += getattr(proc, jetalgo + "PFJets" + PUMethod + "Constituents")

    ### Jet Corrections
    if JETCorrPayload not in payloadList:
        if not set(JETCorrLevels).issubset(set(JECLevels)):
            if "CHS" in PUMethod:
                JEC = ("AK" + size + "PFchs", ["L1FastJet", "L2Relative", "L3Absolute"], "None")
            elif "Plain" in PUMethod:
                JEC = ("AK" + size + "PF", ["L1FastJet", "L2Relative", "L3Absolute"], "None")
            else:
                JEC = None
            if "None" in JETCorrPayload:
                print "|---- jetToolBox: No JEC provided, jetToolbox is using the recommended corrections for this PU method: " + str(
                    JEC
                )
            else:
                print '|---- jetToolBox: JEC payload provided ("' + JETCorrPayload + '") is wrong, jetToolbox is using the recommended corrections for this PU method: ' + str(
                    JEC
                )
        else:
            if "CHS" in PUMethod:
                JEC = ("AK" + size + "PFchs", JETCorrLevels, "None")
            elif "Plain" in PUMethod:
                JEC = ("AK" + size + "PF", JETCorrLevels, "None")
            else:
                JEC = None
            if "None" in JETCorrPayload:
                print "|---- jetToolBox: No JEC payload provided, jetToolbox is using the recommended payload. Using JEC: " + str(
                    JEC
                )
            else:
                print '|---- jetToolBox: JEC payload provided ("' + JETCorrPayload + '") is wrong, jetToolbox is using the recommended corrections for this PU method: ' + str(
                    JEC
                )
    else:
        if not set(JETCorrLevels).issubset(set(JECLevels)):
            if ("CHS" in PUMethod) or ("Plain" in PUMethod):
                JEC = (JETCorrPayload, ["L1FastJet", "L2Relative", "L3Absolute"], "None")
            else:
                JEC = None
            print "|---- jetToolBox: JEC levels are not provided or wrong, jetToolbox is using the recommended levels for this PU method: " + str(
                JEC
            )
        else:
            JEC = (JETCorrPayload, JETCorrLevels, "None")
            print "|---- jetToolBox: JEC payload and levels provided by user. Using JEC: " + str(JEC)

    if addPrunedSubjets or addSoftDropSubjets or addCMSTopTagger:
        if subJETCorrPayload not in payloadList:
            if not set(subJETCorrLevels).issubset(set(JECLevels)):
                if "CHS" in PUMethod:
                    subJEC = ("AK4PFchs", ["L1FastJet", "L2Relative", "L3Absolute"], "None")
                elif "Plain" in PUMethod:
                    subJEC = ("AK4PF", ["L1FastJet", "L2Relative", "L3Absolute"], "None")
                else:
                    subJEC = None
                if "None" in subJETCorrPayload:
                    print "|---- jetToolBox: No subJEC provided, jetToolbox is using the recommended corrections for this PU method: " + str(
                        subJEC
                    )
                else:
                    print '|---- jetToolBox: subJEC payload provided ("' + subJETCorrPayload + '") is wrong, jetToolbox is using the recommended corrections for this PU method: ' + str(
                        subJEC
                    )
            else:
                if "CHS" in PUMethod:
                    subJEC = ("AK4PFchs", subJETCorrLevels, "None")
                elif "Plain" in PUMethod:
                    subJEC = ("AK4PF", subJETCorrLevels, "None")
                else:
                    subJEC = None
                if "None" in subJETCorrPayload:
                    print "|---- jetToolBox: No subJEC payload provided, jetToolbox is using the recommended payload. Using subJEC: " + str(
                        subJEC
                    )
                else:
                    print '|---- jetToolBox: subJEC payload provided ("' + subJETCorrPayload + '") is wrong, jetToolbox is using the recommended corrections for this PU method: ' + str(
                        subJEC
                    )
        else:
            if not set(subJETCorrLevels).issubset(set(JECLevels)):
                if ("CHS" in PUMethod) or ("Plain" in PUMethod):
                    subJEC = (subJETCorrPayload, ["L1FastJet", "L2Relative", "L3Absolute"], "None")
                else:
                    subJEC = None
                print "|---- jetToolBox: subJEC levels are not provided or wrong, jetToolbox is using the recommended levels for this PU method: " + str(
                    subJEC
                )
            else:
                subJEC = (subJETCorrPayload, subJETCorrLevels, "None")
                print "|---- jetToolBox: subJEC payload and levels provided by user. Using subJEC: " + str(subJEC)

    addJetCollection(
        proc,
        labelName=jetALGO + "PF" + PUMethod,
        jetSource=cms.InputTag(jetalgo + "PFJets" + PUMethod),
        algo=jetalgo,
        rParam=jetSize,
        jetCorrections=JEC if JEC is not None else None,
        pfCandidates=cms.InputTag(pfCand),  #'packedPFCandidates'),
        svSource=cms.InputTag(svLabel),  #'slimmedSecondaryVertices'),
        genJetCollection=cms.InputTag(jetalgo + "GenJetsNoNu"),
        pvSource=cms.InputTag(pvLabel),  #'offlineSlimmedPrimaryVertices'),
        btagDiscriminators=bTagDiscriminators,
        getJetMCFlavour=GetJetMCFlavour,
        outputModules=["outputFile"],
    )

    if JEC is not None:
        getattr(
            proc, "patJetCorrFactors" + jetALGO + "PF" + PUMethod
        ).primaryVertices = pvLabel  #'offlineSlimmedPrimaryVertices'

    if "CS" in PUMethod:
        getattr(proc, "patJets" + jetALGO + "PF" + PUMethod).getJetMCFlavour = False
    else:
        getattr(proc, "patJetPartons").particles = cms.InputTag(genParticlesLabel)  #'prunedGenParticles')
    getattr(proc, "patJetPartonMatch" + jetALGO + "PF" + PUMethod).matched = cms.InputTag(
        genParticlesLabel
    )  #'prunedGenParticles')
    if miniAOD:
        if hasattr(proc, "pfInclusiveSecondaryVertexFinderTagInfos" + jetALGO + "PF" + PUMethod):
            getattr(
                proc, "pfInclusiveSecondaryVertexFinderTagInfos" + jetALGO + "PF" + PUMethod
            ).extSVCollection = cms.InputTag(
                svLabel
            )  #'slimmedSecondaryVertices')
        getattr(proc, "patJets" + jetALGO + "PF" + PUMethod).addAssociatedTracks = cms.bool(
            False
        )  # needs to be disabled since there is no track collection present in MiniAOD
        getattr(proc, "patJets" + jetALGO + "PF" + PUMethod).addJetCharge = cms.bool(
            False
        )  # needs to be disabled since there is no track collection present in MiniAOD

        #### Grommers
    if addSoftDrop or addSoftDropSubjets:

        setattr(
            proc,
            jetalgo + "PFJets" + PUMethod + "SoftDrop",
            ak8PFJetsCHSSoftDrop.clone(
                src=cms.InputTag(jetalgo + "PFJets" + PUMethod + "Constituents"),
                rParam=jetSize,
                jetAlgorithm=algorithm,
                useExplicitGhosts=True,
                R0=cms.double(jetSize),
                # zcut=zCutSD,
                beta=betaCut,
                writeCompound=cms.bool(True),
                jetCollInstanceName=cms.string("SubJets"),
            ),
        )
        setattr(
            proc,
            jetalgo + "PFJets" + PUMethod + "SoftDropMass",
            ak8PFJetsCHSSoftDropMass.clone(
                src=cms.InputTag(jetalgo + "PFJets" + PUMethod),
                matched=cms.InputTag(jetalgo + "PFJets" + PUMethod + "SoftDrop"),
                distMax=cms.double(jetSize),
            ),
        )

        elemToKeep += ["keep *_" + jetalgo + "PFJets" + PUMethod + "SoftDropMass_*_*"]
        jetSeq += getattr(proc, jetalgo + "PFJets" + PUMethod + "SoftDrop")
        jetSeq += getattr(proc, jetalgo + "PFJets" + PUMethod + "SoftDropMass")
        getattr(proc, "patJets" + jetALGO + "PF" + PUMethod).userData.userFloats.src += [
            jetalgo + "PFJets" + PUMethod + "SoftDropMass"
        ]
        toolsUsed.append(jetalgo + "PFJets" + PUMethod + "SoftDropMass")

        if addSoftDropSubjets:

            setattr(
                proc,
                jetalgo + "GenJetsNoNuSoftDrop",
                ak4GenJets.clone(
                    SubJetParameters,
                    useSoftDrop=cms.bool(True),
                    rParam=jetSize,
                    jetAlgorithm=algorithm,
                    useExplicitGhosts=cms.bool(True),
                    # zcut=cms.double(zCutSD),
                    R0=cms.double(jetSize),
                    beta=cms.double(betaCut),
                    writeCompound=cms.bool(True),
                    jetCollInstanceName=cms.string("SubJets"),
                ),
            )
            if miniAOD:
                getattr(proc, jetalgo + "GenJetsNoNuSoftDrop").src = "packedGenParticlesForJetsNoNu"
            jetSeq += getattr(proc, jetalgo + "GenJetsNoNuSoftDrop")

            addJetCollection(
                proc,
                labelName=jetALGO + "PF" + PUMethod + "SoftDrop",
                jetSource=cms.InputTag(jetalgo + "PFJets" + PUMethod + "SoftDrop"),
                algo=jetalgo,
                rParam=jetSize,
                jetCorrections=JEC if JEC is not None else None,
                btagDiscriminators=["None"],
                genJetCollection=cms.InputTag(jetalgo + "GenJetsNoNu"),
                getJetMCFlavour=GetJetMCFlavour,
                outputModules=["outputFile"],
            )

            if JEC is not None:
                getattr(proc, "patJetCorrFactors" + jetALGO + "PF" + PUMethod + "SoftDrop").primaryVertices = pvLabel
            getattr(proc, "patJetPartonMatch" + jetALGO + "PF" + PUMethod + "SoftDrop").matched = cms.InputTag(
                genParticlesLabel
            )  #'prunedGenParticles')
            setattr(
                proc,
                "selectedPatJets" + jetALGO + "PF" + PUMethod + "SoftDrop",
                selectedPatJets.clone(src="patJets" + jetALGO + "PF" + PUMethod + "SoftDrop", cut=Cut),
            )

            addJetCollection(
                proc,
                labelName=jetALGO + "PF" + PUMethod + "SoftDropSubjets",
                jetSource=cms.InputTag(jetalgo + "PFJets" + PUMethod + "SoftDrop", "SubJets"),
                algo=jetalgo,  # needed for subjet b tagging
                rParam=jetSize,  # needed for subjet b tagging
                jetCorrections=subJEC if subJEC is not None else None,
                pfCandidates=cms.InputTag(pfCand),
                pvSource=cms.InputTag(pvLabel),
                svSource=cms.InputTag(svLabel),
                btagDiscriminators=bTagDiscriminators,
                genJetCollection=cms.InputTag(jetalgo + "GenJetsNoNuSoftDrop", "SubJets"),
                getJetMCFlavour=GetSubjetMCFlavour,
                explicitJTA=True,  # needed for subjet b tagging
                svClustering=True,  # needed for subjet b tagging
                fatJets=cms.InputTag(jetalgo + "PFJets" + PUMethod),  # needed for subjet flavor clustering
                groomedFatJets=cms.InputTag(
                    jetalgo + "PFJets" + PUMethod + "SoftDrop"
                ),  # needed for subjet flavor clustering
                outputModules=["outputFile"],
            )

            if miniAOD:
                getattr(proc, "patJets" + jetALGO + "PF" + PUMethod + "SoftDropSubjets").addAssociatedTracks = cms.bool(
                    False
                )
                getattr(proc, "patJets" + jetALGO + "PF" + PUMethod + "SoftDropSubjets").addJetCharge = cms.bool(False)
                if hasattr(
                    proc, "pfInclusiveSecondaryVertexFinderTagInfos" + jetALGO + "PF" + PUMethod + "SoftDropSubjets"
                ):
                    getattr(
                        proc, "pfInclusiveSecondaryVertexFinderTagInfos" + jetALGO + "PF" + PUMethod + "SoftDropSubjets"
                    ).extSVCollection = cms.InputTag(svLabel)
            if subJEC is not None:
                getattr(
                    proc, "patJetCorrFactors" + jetALGO + "PF" + PUMethod + "SoftDropSubjets"
                ).primaryVertices = pvLabel
            getattr(proc, "patJetPartonMatch" + jetALGO + "PF" + PUMethod + "SoftDropSubjets").matched = cms.InputTag(
                genParticlesLabel
            )
            setattr(
                proc,
                "selectedPatJets" + jetALGO + "PF" + PUMethod + "SoftDropSubjets",
                selectedPatJets.clone(src="patJets" + jetALGO + "PF" + PUMethod + "SoftDropSubjets", cut=Cut),
            )

            ## Establish references between PATified fat jets and subjets using the BoostedJetMerger
            setattr(
                proc,
                "selectedPatJets" + jetALGO + "PF" + PUMethod + "SoftDropPacked",
                cms.EDProducer(
                    "BoostedJetMerger",
                    jetSrc=cms.InputTag("selectedPatJets" + jetALGO + "PF" + PUMethod + "SoftDrop"),
                    subjetSrc=cms.InputTag("selectedPatJets" + jetALGO + "PF" + PUMethod + "SoftDropSubjets"),
                ),
            )
            jetSeq += getattr(proc, "selectedPatJets" + jetALGO + "PF" + PUMethod + "SoftDropPacked")
            elemToKeep += ["keep *_selectedPatJets" + jetALGO + "PF" + PUMethod + "SoftDropPacked_*_*"]
            toolsUsed.append("selectedPatJets" + jetALGO + "PF" + PUMethod + "SoftDropPacked")
            toolsUsed.append("selectedPatJets" + jetALGO + "PF" + PUMethod + "SoftDropSubjets")

    if addPruning or addPrunedSubjets:

        setattr(
            proc,
            jetalgo + "PFJets" + PUMethod + "Pruned",
            ak8PFJetsCHSPruned.clone(
                src=cms.InputTag(jetalgo + "PFJets" + PUMethod + "Constituents"),
                rParam=jetSize,
                jetAlgorithm=algorithm,
                zcut=zCut,
                rcut_factor=rCut,
                writeCompound=cms.bool(True),
                doAreaFastjet=cms.bool(True),
                jetCollInstanceName=cms.string("SubJets"),
            ),
        )
        setattr(
            proc,
            jetalgo + "PFJets" + PUMethod + "PrunedMass",
            ak8PFJetsCHSPrunedMass.clone(
                src=cms.InputTag(jetalgo + "PFJets" + PUMethod),
                matched=cms.InputTag(jetalgo + "PFJets" + PUMethod + "Pruned"),
                distMax=cms.double(jetSize),
            ),
        )

        jetSeq += getattr(proc, jetalgo + "PFJets" + PUMethod + "Pruned")
        jetSeq += getattr(proc, jetalgo + "PFJets" + PUMethod + "PrunedMass")
        getattr(proc, "patJets" + jetALGO + "PF" + PUMethod).userData.userFloats.src += [
            jetalgo + "PFJets" + PUMethod + "PrunedMass"
        ]
        elemToKeep += ["keep *_" + jetalgo + "PFJets" + PUMethod + "PrunedMass_*_*"]
        toolsUsed.append(jetalgo + "PFJets" + PUMethod + "PrunedMass")

        if addPrunedSubjets:
            setattr(
                proc,
                jetalgo + "GenJetsNoNuPruned",
                ak4GenJets.clone(
                    SubJetParameters,
                    rParam=jetSize,
                    usePruning=cms.bool(True),
                    writeCompound=cms.bool(True),
                    jetCollInstanceName=cms.string("SubJets"),
                ),
            )
            if miniAOD:
                getattr(proc, jetalgo + "GenJetsNoNuPruned").src = "packedGenParticlesForJetsNoNu"
            jetSeq += getattr(proc, jetalgo + "GenJetsNoNuPruned")

            addJetCollection(
                proc,
                labelName=jetALGO + "PF" + PUMethod + "Pruned",
                jetSource=cms.InputTag(jetalgo + "PFJets" + PUMethod + "Pruned"),
                algo=jetalgo,
                rParam=jetSize,
                jetCorrections=JEC if JEC is not None else None,
                btagDiscriminators=["None"],
                genJetCollection=cms.InputTag(jetalgo + "GenJetsNoNu"),
                getJetMCFlavour=GetJetMCFlavour,
                outputModules=["outputFile"],
            )
            if JEC is not None:
                getattr(proc, "patJetCorrFactors" + jetALGO + "PF" + PUMethod + "Pruned").primaryVertices = pvLabel
            getattr(proc, "patJetPartonMatch" + jetALGO + "PF" + PUMethod + "Pruned").matched = cms.InputTag(
                genParticlesLabel
            )
            setattr(
                proc,
                "selectedPatJets" + jetALGO + "PF" + PUMethod + "Pruned",
                selectedPatJets.clone(src="patJets" + jetALGO + "PF" + PUMethod + "Pruned", cut=Cut),
            )

            addJetCollection(
                proc,
                labelName=jetALGO + "PF" + PUMethod + "PrunedSubjets",
                jetSource=cms.InputTag(jetalgo + "PFJets" + PUMethod + "Pruned", "SubJets"),
                algo=jetalgo,  # needed for subjet b tagging
                rParam=jetSize,  # needed for subjet b tagging
                jetCorrections=subJEC if subJEC is not None else None,
                pfCandidates=cms.InputTag(pfCand),
                pvSource=cms.InputTag(pvLabel),
                svSource=cms.InputTag(svLabel),
                getJetMCFlavour=GetSubjetMCFlavour,
                btagDiscriminators=bTagDiscriminators,
                genJetCollection=cms.InputTag(jetalgo + "GenJetsNoNuPruned", "SubJets"),
                explicitJTA=True,  # needed for subjet b tagging
                svClustering=True,  # needed for subjet b tagging
                fatJets=cms.InputTag(jetalgo + "PFJets" + PUMethod),  # needed for subjet flavor clustering
                groomedFatJets=cms.InputTag(
                    jetalgo + "PFJets" + PUMethod + "Pruned"
                ),  # needed for subjet flavor clustering
                outputModules=["outputFile"],
            )

            getattr(proc, "patJetPartonMatch" + jetALGO + "PF" + PUMethod + "PrunedSubjets").matched = cms.InputTag(
                genParticlesLabel
            )
            if subJEC is not None:
                getattr(
                    proc, "patJetCorrFactors" + jetALGO + "PF" + PUMethod + "PrunedSubjets"
                ).primaryVertices = pvLabel
            if miniAOD:
                if hasattr(
                    proc, "pfInclusiveSecondaryVertexFinderTagInfos" + jetALGO + "PF" + PUMethod + "PrunedSubjets"
                ):
                    getattr(
                        proc, "pfInclusiveSecondaryVertexFinderTagInfos" + jetALGO + "PF" + PUMethod + "PrunedSubjets"
                    ).extSVCollection = cms.InputTag(svLabel)
                getattr(proc, "patJets" + jetALGO + "PF" + PUMethod + "PrunedSubjets").addAssociatedTracks = cms.bool(
                    False
                )
                getattr(proc, "patJets" + jetALGO + "PF" + PUMethod + "PrunedSubjets").addJetCharge = cms.bool(False)
            setattr(
                proc,
                "selectedPatJets" + jetALGO + "PF" + PUMethod + "PrunedSubjets",
                selectedPatJets.clone(src="patJets" + jetALGO + "PF" + PUMethod + "PrunedSubjets", cut=Cut),
            )

            ## Establish references between PATified fat jets and subjets using the BoostedJetMerger
            setattr(
                proc,
                "selectedPatJets" + jetALGO + "PF" + PUMethod + "PrunedPacked",
                cms.EDProducer(
                    "BoostedJetMerger",
                    jetSrc=cms.InputTag("selectedPatJets" + jetALGO + "PF" + PUMethod + "Pruned"),
                    subjetSrc=cms.InputTag("selectedPatJets" + jetALGO + "PF" + PUMethod + "PrunedSubjets"),
                ),
            )
            jetSeq += getattr(proc, "selectedPatJets" + jetALGO + "PF" + PUMethod + "PrunedPacked")
            elemToKeep += ["keep *_selectedPatJets" + jetALGO + "PF" + PUMethod + "PrunedPacked_*_*"]
            toolsUsed.append("selectedPatJets" + jetALGO + "PF" + PUMethod + "PrunedPacked")
            toolsUsed.append("selectedPatJets" + jetALGO + "PF" + PUMethod + "PrunedSubjets")

    if addTrimming:

        setattr(
            proc,
            jetalgo + "PFJets" + PUMethod + "Trimmed",
            ak8PFJetsCHSTrimmed.clone(
                rParam=jetSize,
                src=cms.InputTag(jetalgo + "PFJets" + PUMethod + "Constituents"),
                jetAlgorithm=algorithm,
                rFilt=rFiltTrim,
                trimPtFracMin=ptFrac,
            ),
        )
        setattr(
            proc,
            jetalgo + "PFJets" + PUMethod + "TrimmedMass",
            ak8PFJetsCHSTrimmedMass.clone(
                src=cms.InputTag(jetalgo + "PFJets" + PUMethod),
                matched=cms.InputTag(jetalgo + "PFJets" + PUMethod + "Trimmed"),
                distMax=cms.double(jetSize),
            ),
        )

        elemToKeep += ["keep *_" + jetalgo + "PFJets" + PUMethod + "TrimmedMass_*_*"]
        jetSeq += getattr(proc, jetalgo + "PFJets" + PUMethod + "Trimmed")
        jetSeq += getattr(proc, jetalgo + "PFJets" + PUMethod + "TrimmedMass")
        getattr(proc, "patJets" + jetALGO + "PF" + PUMethod).userData.userFloats.src += [
            jetalgo + "PFJets" + PUMethod + "TrimmedMass"
        ]
        toolsUsed.append(jetalgo + "PFJets" + PUMethod + "TrimmedMass")

    if addFiltering:

        setattr(
            proc,
            jetalgo + "PFJets" + PUMethod + "Filtered",
            ak8PFJetsCHSFiltered.clone(
                src=cms.InputTag(jetalgo + "PFJets" + PUMethod + "Constituents"),
                rParam=jetSize,
                jetAlgorithm=algorithm,
                rFilt=rfilt,
                nFilt=nfilt,
            ),
        )
        setattr(
            proc,
            jetalgo + "PFJets" + PUMethod + "FilteredMass",
            ak8PFJetsCHSFilteredMass.clone(
                src=cms.InputTag(jetalgo + "PFJets" + PUMethod),
                matched=cms.InputTag(jetalgo + "PFJets" + PUMethod + "Filtered"),
                distMax=cms.double(jetSize),
            ),
        )
        elemToKeep += ["keep *_" + jetalgo + "PFJets" + PUMethod + "FilteredMass_*_*"]
        jetSeq += getattr(proc, jetalgo + "PFJets" + PUMethod + "Filtered")
        jetSeq += getattr(proc, jetalgo + "PFJets" + PUMethod + "FilteredMass")
        getattr(proc, "patJets" + jetALGO + "PF" + PUMethod).userData.userFloats.src += [
            jetalgo + "PFJets" + PUMethod + "FilteredMass"
        ]
        toolsUsed.append(jetalgo + "PFJets" + PUMethod + "FilteredMass")

    if addCMSTopTagger:

        if "CA" in jetALGO:

            setattr(
                proc,
                "cmsTopTagPFJets" + PUMethod,
                cms.EDProducer(
                    "CATopJetProducer",
                    PFJetParameters.clone(
                        src=cms.InputTag(jetalgo + "PFJets" + PUMethod + "Constituents"),
                        doAreaFastjet=cms.bool(True),
                        doRhoFastjet=cms.bool(False),
                        jetPtMin=cms.double(100.0),
                    ),
                    AnomalousCellParameters,
                    CATopJetParameters.clone(
                        jetCollInstanceName=cms.string("SubJets"),
                        verbose=cms.bool(False),
                        algorithm=cms.int32(1),  # 0 = KT, 1 = CA, 2 = anti-KT
                        tagAlgo=cms.int32(0),  # 0=legacy top
                        useAdjacency=cms.int32(2),  # modified adjacency
                        centralEtaCut=cms.double(2.5),  # eta for defining "central" jets
                        sumEtBins=cms.vdouble(
                            0, 1600, 2600
                        ),  # sumEt bins over which cuts vary. vector={bin 0 lower bound, bin 1 lower bound, ...}
                        rBins=cms.vdouble(0.8, 0.8, 0.8),  # Jet distance paramter R. R values depend on sumEt bins.
                        ptFracBins=cms.vdouble(
                            0.05, 0.05, 0.05
                        ),  # minimum fraction of central jet pt for subjets (deltap)
                        deltarBins=cms.vdouble(
                            0.19, 0.19, 0.19
                        ),  # Applicable only if useAdjacency=1. deltar adjacency values for each sumEtBin
                        nCellBins=cms.vdouble(1.9, 1.9, 1.9),
                    ),
                    jetAlgorithm=cms.string("CambridgeAachen"),
                    rParam=cms.double(jetSize),
                    writeCompound=cms.bool(True),
                ),
            )

            setattr(
                proc,
                "CATopTagInfos",
                cms.EDProducer(
                    "CATopJetTagger",
                    src=cms.InputTag("cmsTopTagPFJets" + PUMethod),
                    TopMass=cms.double(171),
                    TopMassMin=cms.double(0.0),
                    TopMassMax=cms.double(250.0),
                    WMass=cms.double(80.4),
                    WMassMin=cms.double(0.0),
                    WMassMax=cms.double(200.0),
                    MinMassMin=cms.double(0.0),
                    MinMassMax=cms.double(200.0),
                    verbose=cms.bool(False),
                ),
            )
            addJetCollection(
                proc,
                labelName="CMSTopTag" + PUMethod,
                jetSource=cms.InputTag("cmsTopTagPFJets" + PUMethod),
                jetCorrections=JEC if JEC is not None else None,
                pfCandidates=cms.InputTag(pfCand),
                pvSource=cms.InputTag(pvLabel),
                svSource=cms.InputTag(svLabel),
                btagDiscriminators=bTagDiscriminators,
                genJetCollection=cms.InputTag(jetalgo + "GenJetsNoNu"),
                getJetMCFlavour=GetJetMCFlavour,
            )
            getattr(proc, "patJetPartonMatchCMSTopTag" + PUMethod).matched = cms.InputTag(genParticlesLabel)
            if hasattr(proc, "pfInclusiveSecondaryVertexFinderTagInfosCMSTopTag" + PUMethod):
                getattr(
                    proc, "pfInclusiveSecondaryVertexFinderTagInfosCMSTopTag" + PUMethod
                ).extSVCollection = cms.InputTag(svLabel)
            getattr(proc, "patJetsCMSTopTag" + PUMethod).addTagInfos = True
            getattr(proc, "patJetsCMSTopTag" + PUMethod).tagInfoSources = cms.VInputTag(cms.InputTag("CATopTagInfos"))
            if JEC is not None:
                getattr(proc, "patJetCorrFactorsCMSTopTag" + PUMethod).primaryVertices = pvLabel
            getattr(proc, "patJetsCMSTopTag" + PUMethod).addAssociatedTracks = cms.bool(False)
            getattr(proc, "patJetsCMSTopTag" + PUMethod).addJetCharge = cms.bool(False)
            setattr(
                proc,
                "selectedPatJetsCMSTopTag" + PUMethod,
                selectedPatJets.clone(src="patJetsCMSTopTag" + PUMethod, cut=Cut),
            )

            addJetCollection(
                proc,
                labelName="CMSTopTag" + PUMethod + "Subjets",
                jetSource=cms.InputTag("cmsTopTagPFJets" + PUMethod, "SubJets"),
                algo=jetalgo,  # needed for subjet b tagging
                rParam=jetSize,  # needed for subjet b tagging
                jetCorrections=subJEC if subJEC is not None else None,
                pfCandidates=cms.InputTag(pfCand),
                pvSource=cms.InputTag(pvLabel),
                svSource=cms.InputTag(svLabel),
                btagDiscriminators=bTagDiscriminators,
                genJetCollection=cms.InputTag(jetalgo + "GenJetsNoNu"),
                getJetMCFlavour=GetSubjetMCFlavour,
                explicitJTA=True,  # needed for subjet b tagging
                svClustering=True,  # needed for subjet b tagging
                fatJets=cms.InputTag(jetalgo + "PFJets" + PUMethod),  # needed for subjet flavor clustering
                groomedFatJets=cms.InputTag("patJetsCMSTopTag" + PUMethod),  # needed for subjet flavor clustering
            )

            getattr(proc, "patJetPartonMatchCMSTopTag" + PUMethod + "Subjets").matched = cms.InputTag(
                genParticlesLabel
            )  #'prunedGenParticles')
            if hasattr(proc, "pfInclusiveSecondaryVertexFinderTagInfosCMSTopTag" + PUMethod + "Subjets"):
                getattr(
                    proc, "pfInclusiveSecondaryVertexFinderTagInfosCMSTopTag" + PUMethod + "Subjets"
                ).extSVCollection = cms.InputTag(svLabel)
            if subJEC is not None:
                getattr(proc, "patJetCorrFactorsCMSTopTag" + PUMethod + "Subjets").primaryVertices = pvLabel
            getattr(proc, "patJetsCMSTopTag" + PUMethod + "Subjets").addAssociatedTracks = cms.bool(False)
            getattr(proc, "patJetsCMSTopTag" + PUMethod + "Subjets").addJetCharge = cms.bool(False)
            setattr(
                proc,
                "selectedPatJetsCMSTopTag" + PUMethod + "Subjets",
                selectedPatJets.clone(src="patJetsCMSTopTag" + PUMethod + "Subjets", cut=Cut),
            )

            setattr(
                proc,
                "patJetsCMSTopTag" + PUMethod + "Packed",
                cms.EDProducer(
                    "BoostedJetMerger",
                    jetSrc=cms.InputTag("patJetsCMSTopTag" + PUMethod),
                    subjetSrc=cms.InputTag("patJetsCMSTopTag" + PUMethod + "Subjets"),
                ),
            )
            jetSeq += getattr(proc, "patJetsCMSTopTag" + PUMethod + "Packed")
            elemToKeep += ["keep *_patJetsCMSTopTag" + PUMethod + "Packed_*_*"]
            toolsUsed.append("patJetsCMSTopTag" + PUMethod + "Packed")

        else:
            print "|---- jetToolBox: CMS recommends CambridgeAachen for CMS Top Tagger, you are using " + algorithm + ". JetToolbox will not run CMS Top Tagger."

    if addMassDrop:

        if "CA" in jetALGO:
            setattr(
                proc,
                jetalgo + "PFJets" + PUMethod + "MassDropFiltered",
                ca15PFJetsCHSMassDropFiltered.clone(
                    rParam=jetSize, src=cms.InputTag(jetalgo + "PFJets" + PUMethod + "Constituents")
                ),
            )
            setattr(
                proc,
                jetalgo + "PFJets" + PUMethod + "MassDropFilteredMass",
                ak8PFJetsCHSPrunedMass.clone(
                    src=cms.InputTag(jetalgo + "PFJets" + PUMethod),
                    matched=cms.InputTag(jetalgo + "PFJets" + PUMethod + "MassDropFiltered"),
                    distMax=cms.double(jetSize),
                ),
            )
            elemToKeep += ["keep *_" + jetalgo + "PFJets" + PUMethod + "MassDropFilteredMass_*_*"]
            getattr(proc, "patJets" + jetALGO + "PF" + PUMethod).userData.userFloats.src += [
                jetalgo + "PFJets" + PUMethod + "MassDropFilteredMass"
            ]
            jetSeq += getattr(proc, jetalgo + "PFJets" + PUMethod + "MassDropFiltered")
            jetSeq += getattr(proc, jetalgo + "PFJets" + PUMethod + "MassDropFilteredMass")
        else:
            print "|---- jetToolBox: CMS recommends CambridgeAachen for Mass Drop, you are using " + algorithm + ". JetToolbox will not run Mass Drop."
        toolsUsed.append(jetalgo + "PFJets" + PUMethod + "MassDropFilteredMass")

    if addHEPTopTagger:
        if (jetSize >= 1.0) and ("CA" in jetALGO):

            setattr(
                proc,
                "hepTopTagPFJets" + PUMethod,
                hepTopTagPFJetsCHS.clone(src=cms.InputTag(jetalgo + "PFJets" + PUMethod + "Constituents")),
            )
            setattr(
                proc,
                "hepTopTagPFJets" + PUMethod + "Mass" + jetALGO,
                ak8PFJetsCHSPrunedMass.clone(
                    src=cms.InputTag(jetalgo + "PFJets" + PUMethod),
                    matched=cms.InputTag("hepTopTagPFJets" + PUMethod),
                    distMax=cms.double(jetSize),
                ),
            )
            elemToKeep += ["keep *_hepTopTagPFJets" + PUMethod + "Mass" + jetALGO + "_*_*"]
            getattr(proc, "patJets" + jetALGO + "PF" + PUMethod).userData.userFloats.src += [
                "hepTopTagPFJets" + PUMethod + "Mass" + jetALGO
            ]
            jetSeq += getattr(proc, "hepTopTagPFJets" + PUMethod)
            jetSeq += getattr(proc, "hepTopTagPFJets" + PUMethod + "Mass" + jetALGO)
            toolsUsed.append("hepTopTagPFJets" + PUMethod + "Mass" + jetALGO)
        else:
            print "|---- jetToolBox: CMS recommends CambridgeAachen for HEPTopTagger, you are using " + algorithm + ", and a jet cone size bigger than 1. JetToolbox will not run HEP TopTagger."

        ####### Nsubjettiness
    if addNsub:
        from RecoJets.JetProducers.nJettinessAdder_cfi import Njettiness

        rangeTau = range(1, maxTau + 1)
        setattr(
            proc,
            "Njettiness" + jetALGO + PUMethod,
            Njettiness.clone(
                src=cms.InputTag(jetalgo + "PFJets" + PUMethod),
                Njets=cms.vuint32(rangeTau),  # compute 1-, 2-, 3-, 4- subjettiness
                # variables for measure definition :
                measureDefinition=cms.uint32(0),  # CMS default is normalized measure
                beta=cms.double(1.0),  # CMS default is 1
                R0=cms.double(jetSize),  # CMS default is jet cone size
                Rcutoff=cms.double(-999.0),  # not used by default
                # variables for axes definition :
                axesDefinition=cms.uint32(6),  # CMS default is 1-pass KT axes
                nPass=cms.int32(-999),  # not used by default
                akAxesR0=cms.double(-999.0),
            ),
        )  # not used by default

        elemToKeep += ["keep *_Njettiness" + jetALGO + PUMethod + "_*_*"]
        for tau in rangeTau:
            getattr(proc, "patJets" + jetALGO + "PF" + PUMethod).userData.userFloats.src += [
                "Njettiness" + jetALGO + PUMethod + ":tau" + str(tau)
            ]
        jetSeq += getattr(proc, "Njettiness" + jetALGO + PUMethod)
        toolsUsed.append("Njettiness" + jetALGO + PUMethod)

        ###### QJetsAdder
    if addQJets:
        """
		#This is the old way before 731
		### there must be a better way to do this random number introduction
		setattr( proc, 'RandomNumberGeneratorService', cms.Service("RandomNumberGeneratorService", 
							QJetsAdderCA8 = cms.PSet(initialSeed = cms.untracked.uint32(7)),
							QJetsAdderAK8 = cms.PSet(initialSeed = cms.untracked.uint32(31)),
							QJetsAdderCA15 = cms.PSet(initialSeed = cms.untracked.uint32(76)), ) )

		from RecoJets.JetProducers.qjetsadder_cfi import QJetsAdder
		setattr( proc, 'QJetsAdder'+jetALGO, 
				QJetsAdder.clone( src = cms.InputTag(jetalgo+'PFJets'+PUMethod), 
					jetRad = cms.double( jetSize ), 
					jetAlgo = cms.string( jetALGO[0:2] )))
		elemToKeep += [ 'keep *_QJetsAdder'+jetALGO+'_*_*' ]
		getattr( proc, 'patJets'+jetALGO+'PF'+PUMethod).userData.userFloats.src += ['QJetsAdder'+jetALGO+':QjetsVolatility']  
		jetSeq += getattr(proc, 'QJetsAdder'+jetALGO )
		toolsUsed.append( 'QJetsAdder'+jetALGO )
		"""
        ### This is for 731 or higher
        if "ak4" in jetalgo:
            proc.load("RecoJets.JetProducers.QGTagger_cfi")
            proc.QGTagger.srcJets = cms.InputTag(
                jetalgo + "PFJets" + PUMethod
            )  # Could be reco::PFJetCollection or pat::JetCollection (both AOD and miniAOD)
            proc.QGTagger.jetsLabel = cms.string(
                "QGL_AK4PFchs"
            )  # Other options (might need to add an ESSource for it): see https://twiki.cern.ch/twiki/bin/viewauth/CMS/QGDataBaseVersion
            elemToKeep += ["keep *_QGTagger_*_*"]
            getattr(proc, "patJets" + jetALGO + "PF" + PUMethod).userData.userFloats.src += ["QGTagger:qgLikelihood"]
            jetSeq += getattr(proc, "QGTagger")
        else:
            print "|---- jetToolBox: QGTagger is optimized for ak4 jets."

            ####### Pileup JetID
    if addPUJetID:
        if ("ak4" in jetalgo) and ("CHS" in PUMethod):
            from RecoJets.JetProducers.pileupjetidproducer_cfi import pileupJetIdCalculator, pileupJetIdEvaluator

            setattr(
                proc,
                jetALGO + "PF" + PUMethod + "pileupJetIdCalculator",
                pileupJetIdCalculator.clone(
                    jets=cms.InputTag(jetalgo + "PFJets" + PUMethod),
                    rho=cms.InputTag("fixedGridRhoFastjetAll"),
                    vertexes=cms.InputTag(pvLabel),
                ),
            )

            setattr(
                proc,
                jetALGO + "PF" + PUMethod + "pileupJetIdEvaluator",
                pileupJetIdEvaluator.clone(
                    jetids=cms.InputTag(jetALGO + "PF" + PUMethod + "pileupJetIdCalculator"),
                    jets=cms.InputTag(jetalgo + "PFJets" + PUMethod),
                    rho=cms.InputTag("fixedGridRhoFastjetAll"),
                    vertexes=cms.InputTag(pvLabel),
                ),
            )

            getattr(proc, "patJets" + jetALGO + "PF" + PUMethod).userData.userFloats.src += [
                jetALGO + "PF" + PUMethod + "pileupJetIdEvaluator:fullDiscriminant"
            ]
            getattr(proc, "patJets" + jetALGO + "PF" + PUMethod).userData.userInts.src += [
                jetALGO + "PF" + PUMethod + "pileupJetIdEvaluator:cutbasedId",
                jetALGO + "PF" + PUMethod + "pileupJetIdEvaluator:fullId",
            ]
            elemToKeep += ["keep *_" + jetALGO + "PF" + PUMethod + "pileupJetIdEvaluator_*_*"]
            toolsUsed.append(jetALGO + "PF" + PUMethod + "pileupJetIdEvaluator")
        else:
            print "|---- jetToolBox: PUJetID is optimized for ak4 PFjets with CHS."

    if hasattr(proc, "patJetPartons"):
        proc.patJetPartons.particles = genParticlesLabel

    setattr(
        proc,
        "selectedPatJets" + jetALGO + "PF" + PUMethod,
        selectedPatJets.clone(src="patJets" + jetALGO + "PF" + PUMethod, cut=Cut),
    )
    elemToKeep += ["keep *_selectedPatJets" + jetALGO + "PF" + PUMethod + "_*_*"]
    elemToKeep += ["drop *_selectedPatJets" + jetALGO + "PF" + PUMethod + "_calo*_*"]
    elemToKeep += ["drop *_selectedPatJets" + jetALGO + "PF" + PUMethod + "_tagInfos_*"]

    print "|---- jetToolBox: Running " + ", ".join(toolsUsed) + "."
    print "|---- jetToolBox: Creating selectedPatJets" + jetALGO + "PF" + PUMethod + " collection."

    ### "return"
    setattr(proc, jetSequence, jetSeq)
    if hasattr(proc, outputFile):
        getattr(proc, outputFile).outputCommands += elemToKeep
    else:
        setattr(
            proc,
            outputFile,
            cms.OutputModule(
                "PoolOutputModule",
                fileName=cms.untracked.string("jettoolbox.root"),
                outputCommands=cms.untracked.vstring(elemToKeep),
            ),
        )
Beispiel #15
0
def miniAOD_customizeCommon(process):
    process.patMuons.isoDeposits = cms.PSet()
    process.patElectrons.isoDeposits = cms.PSet()
    process.patTaus.isoDeposits = cms.PSet()
    process.patPhotons.isoDeposits = cms.PSet()
    #
    process.patMuons.embedTrack = True  # used for IDs
    process.patMuons.embedCombinedMuon = True  # used for IDs
    process.patMuons.embedMuonBestTrack = True  # used for IDs
    process.patMuons.embedStandAloneMuon = True  # maybe?
    process.patMuons.embedPickyMuon = False  # no, use best track
    process.patMuons.embedTpfmsMuon = False  # no, use best track
    process.patMuons.embedDytMuon = False  # no, use best track
    #
    # disable embedding of electron and photon associated objects already stored by the ReducedEGProducer
    process.patElectrons.embedGsfElectronCore = False  ## process.patElectrons.embed in AOD externally stored gsf electron core
    process.patElectrons.embedSuperCluster = False  ## process.patElectrons.embed in AOD externally stored supercluster
    process.patElectrons.embedPflowSuperCluster = False  ## process.patElectrons.embed in AOD externally stored supercluster
    process.patElectrons.embedSeedCluster = False  ## process.patElectrons.embed in AOD externally stored the electron's seedcluster
    process.patElectrons.embedBasicClusters = False  ## process.patElectrons.embed in AOD externally stored the electron's basic clusters
    process.patElectrons.embedPreshowerClusters = False  ## process.patElectrons.embed in AOD externally stored the electron's preshower clusters
    process.patElectrons.embedPflowBasicClusters = False  ## process.patElectrons.embed in AOD externally stored the electron's pflow basic clusters
    process.patElectrons.embedPflowPreshowerClusters = False  ## process.patElectrons.embed in AOD externally stored the electron's pflow preshower clusters
    process.patElectrons.embedRecHits = False  ## process.patElectrons.embed in AOD externally stored the RecHits - can be called from the PATElectronProducer
    process.patElectrons.electronSource = cms.InputTag(
        "reducedEgamma", "reducedGedGsfElectrons")
    process.patElectrons.electronIDSources = cms.PSet(
        # configure many IDs as InputTag <someName> = <someTag> you
        # can comment out those you don't want to save some disk space
        eidRobustLoose=cms.InputTag("reducedEgamma", "eidRobustLoose"),
        eidRobustTight=cms.InputTag("reducedEgamma", "eidRobustTight"),
        eidLoose=cms.InputTag("reducedEgamma", "eidLoose"),
        eidTight=cms.InputTag("reducedEgamma", "eidTight"),
        eidRobustHighEnergy=cms.InputTag("reducedEgamma",
                                         "eidRobustHighEnergy"),
    )
    process.elPFIsoDepositChargedPAT.src = cms.InputTag(
        "reducedEgamma", "reducedGedGsfElectrons")
    process.elPFIsoDepositChargedAllPAT.src = cms.InputTag(
        "reducedEgamma", "reducedGedGsfElectrons")
    process.elPFIsoDepositNeutralPAT.src = cms.InputTag(
        "reducedEgamma", "reducedGedGsfElectrons")
    process.elPFIsoDepositGammaPAT.src = cms.InputTag(
        "reducedEgamma", "reducedGedGsfElectrons")
    process.elPFIsoDepositPUPAT.src = cms.InputTag("reducedEgamma",
                                                   "reducedGedGsfElectrons")
    #
    process.patPhotons.embedSuperCluster = False  ## whether to process.patPhotons.embed in AOD externally stored supercluster
    process.patPhotons.embedSeedCluster = False  ## process.patPhotons.embed in AOD externally stored the photon's seedcluster
    process.patPhotons.embedBasicClusters = False  ## process.patPhotons.embed in AOD externally stored the photon's basic clusters
    process.patPhotons.embedPreshowerClusters = False  ## process.patPhotons.embed in AOD externally stored the photon's preshower clusters
    process.patPhotons.embedRecHits = False  ## process.patPhotons.embed in AOD externally stored the RecHits - can be called from the PATPhotonProducer
    process.patPhotons.photonSource = cms.InputTag("reducedEgamma",
                                                   "reducedGedPhotons")
    process.patPhotons.photonIDSources = cms.PSet(
        PhotonCutBasedIDLoose=cms.InputTag('reducedEgamma',
                                           'PhotonCutBasedIDLoose'),
        PhotonCutBasedIDTight=cms.InputTag('reducedEgamma',
                                           'PhotonCutBasedIDTight'))

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

    # add CMS top tagger
    from RecoJets.JetProducers.caTopTaggers_cff import caTopTagInfos
    process.caTopTagInfos = caTopTagInfos.clone()
    process.caTopTagInfosPAT = cms.EDProducer(
        "RecoJetDeltaRTagInfoValueMapProducer",
        src=cms.InputTag("ak8PFJetsCHS"),
        matched=cms.InputTag("cmsTopTagPFJetsCHS"),
        matchedTagInfos=cms.InputTag("caTopTagInfos"),
        distMax=cms.double(0.8))

    #add AK8
    from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection
    addJetCollection(
        process,
        labelName='AK8',
        jetSource=cms.InputTag('ak8PFJetsCHS'),
        algo='AK',
        rParam=0.8,
        jetCorrections=('AK8PFchs',
                        cms.vstring(['L1FastJet', 'L2Relative',
                                     'L3Absolute']), 'None'),
        btagInfos=['caTopTagInfosPAT'])
    process.patJetsAK8.userData.userFloats.src = [
    ]  # start with empty list of user floats
    process.selectedPatJetsAK8.cut = cms.string("pt > 100")
    process.patJetGenJetMatchAK8.matched = 'slimmedGenJets'
    ## AK8 groomed masses
    from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSPruned, ak8PFJetsCHSSoftDrop, ak8PFJetsCHSFiltered, ak8PFJetsCHSTrimmed
    process.ak8PFJetsCHSPruned = ak8PFJetsCHSPruned.clone()
    process.ak8PFJetsCHSSoftDrop = ak8PFJetsCHSSoftDrop.clone()
    process.ak8PFJetsCHSTrimmed = ak8PFJetsCHSTrimmed.clone()
    process.ak8PFJetsCHSFiltered = ak8PFJetsCHSFiltered.clone()
    process.load("RecoJets.JetProducers.ak8PFJetsCHS_groomingValueMaps_cfi")
    process.patJetsAK8.userData.userFloats.src += [
        'ak8PFJetsCHSPrunedMass', 'ak8PFJetsCHSSoftDropMass',
        'ak8PFJetsCHSTrimmedMass', 'ak8PFJetsCHSFilteredMass'
    ]

    # Add AK8 top tagging variables
    process.patJetsAK8.tagInfoSources = cms.VInputTag(
        cms.InputTag("caTopTagInfosPAT"))
    process.patJetsAK8.addTagInfos = cms.bool(True)

    # add Njetiness
    process.load('RecoJets.JetProducers.nJettinessAdder_cfi')
    process.NjettinessAK8 = process.Njettiness.clone()
    process.NjettinessAK8.src = cms.InputTag("ak8PFJetsCHS")
    process.NjettinessAK8.cone = cms.double(0.8)
    process.patJetsAK8.userData.userFloats.src += [
        'NjettinessAK8:tau1', 'NjettinessAK8:tau2', 'NjettinessAK8:tau3'
    ]

    #
    from PhysicsTools.PatAlgos.tools.trigTools import switchOnTriggerStandAlone
    switchOnTriggerStandAlone(process, outputModule='')
    process.patTrigger.packTriggerPathNames = cms.bool(True)
    #
    # apply type I/type I + II PFMEt corrections to pat::MET object
    # and estimate systematic uncertainties on MET
    # FIXME: this and the typeI MET should become AK4 once we have the proper JEC?
    from PhysicsTools.PatUtils.tools.runType1PFMEtUncertainties import runType1PFMEtUncertainties
    addJetCollection(process,
                     postfix="ForMetUnc",
                     labelName='AK4PF',
                     jetSource=cms.InputTag('ak4PFJets'),
                     jetCorrections=('AK4PF',
                                     ['L1FastJet', 'L2Relative',
                                      'L3Absolute'], ''))
    process.patJetsAK4PFForMetUnc.getJetMCFlavour = False
    runType1PFMEtUncertainties(process,
                               addToPatDefaultSequence=False,
                               jetCollection="selectedPatJetsAK4PFForMetUnc",
                               electronCollection="selectedPatElectrons",
                               muonCollection="selectedPatMuons",
                               tauCollection="selectedPatTaus",
                               makeType1p2corrPFMEt=True,
                               outputModule=None)

    #keep this after all addJetCollections otherwise it will attempt computing them also for stuf with no taginfos
    #Some useful BTAG vars
    process.patJets.userData.userFunctions = cms.vstring(
        '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").secondaryVertex(0).p4.M):(0)',
        '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").secondaryVertex(0).numberOfSourceCandidatePtrs):(0)',
        '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").flightDistance(0).value):(0)',
        '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").flightDistance(0).significance):(0)',
        '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").secondaryVertex(0).p4.x):(0)',
        '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").secondaryVertex(0).p4.y):(0)',
        '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").secondaryVertex(0).p4.z):(0)',
        '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").secondaryVertex(0).vertex.x):(0)',
        '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").secondaryVertex(0).vertex.y):(0)',
        '?(tagInfoCandSecondaryVertex("pfSecondaryVertex").nVertices()>0)?(tagInfoCandSecondaryVertex("pfSecondaryVertex").secondaryVertex(0).vertex.z):(0)',
    )
    process.patJets.userData.userFunctionLabels = cms.vstring(
        'vtxMass', 'vtxNtracks', 'vtx3DVal', 'vtx3DSig', 'vtxPx', 'vtxPy',
        'vtxPz', 'vtxPosX', 'vtxPosY', 'vtxPosZ')
    process.patJets.tagInfoSources = cms.VInputTag(
        cms.InputTag("pfSecondaryVertexTagInfos"))
    process.patJets.addTagInfos = cms.bool(True)
    #
    ## PU JetID
    process.load("PhysicsTools.PatAlgos.slimming.pileupJetId_cfi")
    process.patJets.userData.userFloats.src = [
        cms.InputTag("pileupJetId:fullDiscriminant"),
    ]

    #VID Electron IDs
    electron_ids = [
        'RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_CSA14_50ns_V1_cff',
        'RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_CSA14_PU20bx25_V0_cff',
        'RecoEgamma.ElectronIdentification.Identification.heepElectronID_HEEPV50_CSA14_25ns_cff',
        'RecoEgamma.ElectronIdentification.Identification.heepElectronID_HEEPV50_CSA14_startup_cff'
    ]
    switchOnVIDElectronIdProducer(process)
    process.egmGsfElectronIDs.physicsObjectSrc = \
        cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.electronIDValueMapProducer.src = \
        cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.electronIDValueMapProducer.ebReducedRecHitCollection = \
        cms.InputTag("reducedEgamma","reducedEBRecHits")
    process.electronIDValueMapProducer.eeReducedRecHitCollection = \
        cms.InputTag("reducedEgamma","reducedEERecHits")
    process.electronIDValueMapProducer.esReducedRecHitCollection = \
        cms.InputTag("reducedEgamma","reducedESRecHits")
    for idmod in electron_ids:
        setupAllVIDIdsInModule(process, idmod, setupVIDElectronSelection)
Beispiel #16
0
def jetToolbox( proc, jetType, jetSequence, outputFile,
		updateCollection='', updateCollectionSubjets='',
		newPFCollection=False, nameNewPFCollection = '',	
		PUMethod='CHS', 
		miniAOD=True,
		runOnMC=True,
		JETCorrPayload='', JETCorrLevels = [ 'None' ], GetJetMCFlavour=True,
		Cut = '', 
		postFix='',
		# blank means default list of discriminators, None means none
		bTagDiscriminators = '',
		bTagInfos = None, 
		subjetBTagDiscriminators = '',
		subjetBTagInfos = None, 
		subJETCorrPayload='', subJETCorrLevels = [ 'None' ], GetSubjetMCFlavour=True,
		CutSubjet = '', 
		addPruning=False, zCut=0.1, rCut=0.5, addPrunedSubjets=False,
		addSoftDrop=False, betaCut=0.0,  zCutSD=0.1, addSoftDropSubjets=False,
		addTrimming=False, rFiltTrim=0.2, ptFrac=0.03,
		addFiltering=False, rfilt=0.3, nfilt=3,
		addCMSTopTagger=False,
		addMassDrop=False,
		addHEPTopTagger=False,
		addNsub=False, maxTau=4,
		addNsubSubjets=False, subjetMaxTau=4,
		addPUJetID=False,
		addQGTagger=False, QGjetsLabel='chs',
		addEnergyCorrFunc=False, 
		addEnergyCorrFuncSubjets=False,
		# set this to false to disable creation of jettoolbox.root
		# then you need to associate the jetTask to a Path or EndPath manually in your config
		associateTask=True,
		# 0 = no printouts, 1 = warnings only, 2 = warnings & info, 3 = warnings, info, debug
		verbosity=2,
		):

	runOnData = not runOnMC
	if runOnData:
		GetJetMCFlavour = False
		GetSubjetMCFlavour = False
	
	###############################################################################
	#######  Verifying some inputs and defining variables
	###############################################################################
	if verbosity>=1: print('|---- jetToolbox: Initializing collection... (with postfix '+postFix+')')
	if newPFCollection and verbosity>=2: print('|---- jetToolBox: Using '+ nameNewPFCollection +' as PFCandidates collection')
	supportedJetAlgos = { 'ak': 'AntiKt', 'ca' : 'CambridgeAachen', 'kt' : 'Kt' }
	recommendedJetAlgos = [ 'ak4', 'ak8', 'ca4', 'ca8', 'ca10', 'ca15' ]
	payloadList = [ 'None',
			'AK1PFchs', 'AK2PFchs', 'AK3PFchs', 'AK4PFchs', 'AK5PFchs', 'AK6PFchs', 'AK7PFchs', 'AK8PFchs', 'AK9PFchs', 'AK10PFchs',
			'AK1PFPuppi', 'AK2PFPuppi', 'AK3PFPuppi', 'AK4PFPuppi', 'AK5PFPuppi', 'AK6PFPuppi', 'AK7PFPuppi', 'AK8PFPuppi', 'AK9PFPuppi', 'AK10PFPuppi',  
			'AK1PFSK', 'AK2PFSK', 'AK3PFSK', 'AK4PFSK', 'AK5PFSK', 'AK6PFSK', 'AK7PFSK', 'AK8PFSK', 'AK9PFSK', 'AK10PFSK',  
			'AK1PF', 'AK2PF', 'AK3PF', 'AK4PF', 'AK5PF', 'AK6PF', 'AK7PF', 'AK8PF', 'AK9PF', 'AK10PF' ]
	JECLevels = [ 'L1Offset', 'L1FastJet', 'L1JPTOffset', 'L2Relative', 'L3Absolute', 'L5Falvour', 'L7Parton' ]
	if runOnData:
		JECLevels += ['L2L3Residual']
	jetAlgo = ''
	algorithm = ''
	size = ''
	for TYPE, tmpAlgo in supportedJetAlgos.iteritems(): 
		if TYPE in jetType.lower():
			jetAlgo = TYPE
			algorithm = tmpAlgo
			size = jetType.replace( TYPE, '' )

	jetSize = 0.
	if int(size) in range(0, 20): jetSize = int(size)/10.
	else: raise ValueError('|---- jetToolBox: jetSize has not a valid value. Insert a number between 1 and 20 after algorithm, like: AK8')
	### Trick for uppercase/lowercase algo name
	jetALGO = jetAlgo.upper()+size
	jetalgo = jetAlgo.lower()+size
	if jetalgo not in recommendedJetAlgos and verbosity>=1: print('|---- jetToolBox: CMS recommends the following jet algorithms: '+' '.join(recommendedJetAlgos)+'. You are using '+jetalgo+' .')


	#################################################################################
	####### Toolbox start 
	#################################################################################

	elemToKeep = []
	jetSeq = cms.Sequence()
	genParticlesLabel = ''
	pvLabel = ''
	tvLabel = ''
	toolsUsed = []
	mod = OrderedDict()

	### List of Jet Corrections
	if not set(JETCorrLevels).issubset(set(JECLevels)): 
		if ( 'CHS' in PUMethod ) or  ( 'Plain' in PUMethod ): JETCorrLevels = ['L1FastJet','L2Relative', 'L3Absolute']
		else: JETCorrLevels = [ 'L2Relative', 'L3Absolute']
		if runOnData: JETCorrLevels.append('L2L3Residual')
	if not set(subJETCorrLevels).issubset(set(JECLevels)): 
		if ( 'CHS' in PUMethod ) or  ( 'Plain' in PUMethod ): subJETCorrLevels = ['L1FastJet','L2Relative', 'L3Absolute']
		else: subJETCorrLevels = [ 'L2Relative', 'L3Absolute']
		if runOnData: subJETCorrLevels.append('L2L3Residual')


	## b-tag discriminators
	defaultBTagDiscriminators = [
			'pfTrackCountingHighEffBJetTags',
			'pfTrackCountingHighPurBJetTags',
			'pfJetProbabilityBJetTags',
			'pfJetBProbabilityBJetTags',
			'pfSimpleSecondaryVertexHighEffBJetTags',
			'pfSimpleSecondaryVertexHighPurBJetTags',
			'pfCombinedSecondaryVertexV2BJetTags',
			'pfCombinedInclusiveSecondaryVertexV2BJetTags',
			'pfCombinedMVAV2BJetTags'
	]
	if bTagDiscriminators is '': bTagDiscriminators = defaultBTagDiscriminators
	if subjetBTagDiscriminators is '': subjetBTagDiscriminators = defaultBTagDiscriminators

	if updateCollection and 'Puppi' in updateCollection: PUMethod='Puppi'
	mod["PATJetsLabel"] = jetALGO+'PF'+PUMethod
	mod["PATJetsLabelPost"] = mod["PATJetsLabel"]+postFix
	# some substructure quantities don't include the 'PF' in the name
	mod["SubstructureLabel"] = jetALGO+PUMethod+postFix
	if not updateCollection: 

		mod["GenJetsNoNu"] = jetalgo+'GenJetsNoNu'
		#### For MiniAOD
		if miniAOD:

			if verbosity>=2: print('|---- jetToolBox: JETTOOLBOX RUNNING ON MiniAOD FOR '+jetALGO+' JETS USING '+PUMethod)

			genParticlesLabel = 'prunedGenParticles'
			pvLabel = 'offlineSlimmedPrimaryVertices'
			svLabel = 'slimmedSecondaryVertices'
			tvLabel = 'unpackedTracksAndVertices'
			muLabel = 'slimmedMuons'
			elLabel = 'slimmedElectrons'
			pfCand = nameNewPFCollection if newPFCollection else 'packedPFCandidates'

			if runOnMC:
				## Filter out neutrinos from packed GenParticles
				mod["GenParticlesNoNu"] = 'packedGenParticlesForJetsNoNu'
				_addProcessAndTask(proc, mod["GenParticlesNoNu"],
						cms.EDFilter("CandPtrSelector", 
							src = cms.InputTag("packedGenParticles"), 
							cut = cms.string("abs(pdgId) != 12 && abs(pdgId) != 14 && abs(pdgId) != 16")
							))
				jetSeq += getattr(proc, mod["GenParticlesNoNu"])

				_addProcessAndTask(proc, mod["GenJetsNoNu"],
						ak4GenJets.clone( src = mod["GenParticlesNoNu"],
							rParam = jetSize, 
							jetAlgorithm = algorithm ) ) 
				jetSeq += getattr(proc, mod["GenJetsNoNu"])

			#for Inclusive Vertex Finder
			proc.load('PhysicsTools.PatAlgos.slimming.unpackedTracksAndVertices_cfi')

		#### For AOD
		else:
			if verbosity>=2: print('|---- jetToolBox: JETTOOLBOX RUNNING ON AOD FOR '+jetALGO+' JETS USING '+PUMethod)

			genParticlesLabel = 'genParticles'
			pvLabel = 'offlinePrimaryVertices'
			tvLabel = 'generalTracks'
			muLabel = 'muons'
			elLabel = 'gedGsfElectrons'
			pfCand =  nameNewPFCollection if newPFCollection else 'particleFlow'
			svLabel = 'inclusiveCandidateSecondaryVertices'

			if runOnMC:
				proc.load('RecoJets.Configuration.GenJetParticles_cff')
				_addProcessAndTask(proc, mod["GenJetsNoNu"], ak4GenJets.clone(src='genParticlesForJetsNoNu', rParam=jetSize, jetAlgorithm=algorithm))
				jetSeq += getattr(proc, mod["GenJetsNoNu"])
			

		####  Creating PATjets
		tmpPfCandName = pfCand.lower()
		mod["PFJets"] = ""
		if 'Puppi' in PUMethod:
			if ('puppi' in tmpPfCandName): 
				srcForPFJets = pfCand
				if verbosity>=1: print('|---- jetToolBox: Not running puppi algorithm because keyword puppi was specified in nameNewPFCollection, but applying puppi corrections.')
			else: 
				proc.load('CommonTools.PileupAlgos.Puppi_cff')
				puppi.candName = cms.InputTag( pfCand ) 
				if miniAOD:
				  puppi.vertexName = cms.InputTag('offlineSlimmedPrimaryVertices')
				  puppi.clonePackedCands = cms.bool(True)
				  puppi.useExistingWeights = cms.bool(True)
				_addProcessAndTask(proc, 'puppi', getattr(proc, 'puppi'))
				jetSeq += getattr(proc, 'puppi' )
				srcForPFJets = 'puppi'

			from RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJetsPuppi
			mod["PFJets"] = jetalgo+'PFJetsPuppi'+postFix
			_addProcessAndTask(proc, mod["PFJets"],
					ak4PFJetsPuppi.clone( src = cms.InputTag( srcForPFJets ),
						doAreaFastjet = True, 
						rParam = jetSize, 
						jetAlgorithm = algorithm ) )  
			jetSeq += getattr(proc, mod["PFJets"])

			if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PFPuppi'
			if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PFPuppi'

		elif 'SK' in PUMethod:

			if ('sk' in tmpPfCandName): 
				srcForPFJets = pfCand
				if verbosity>=1: print('|---- jetToolBox: Not running softkiller algorithm because keyword SK was specified in nameNewPFCollection, but applying SK corrections.')
			else:
				proc.load('CommonTools.PileupAlgos.softKiller_cfi')
				getattr( proc, 'softKiller' ).PFCandidates = cms.InputTag( pfCand )
				_addProcessAndTask(proc, 'softKiller', getattr(proc, 'softKiller'))
				jetSeq += getattr(proc, 'softKiller' )
				srcForPFJets = 'softKiller'

			from RecoJets.JetProducers.ak4PFJetsSK_cfi import ak4PFJetsSK
			mod["PFJets"] = jetalgo+'PFJetsSK'+postFix
			_addProcessAndTask(proc, mod["PFJets"],
					ak4PFJetsSK.clone(  src = cms.InputTag( srcForPFJets ),
						rParam = jetSize, 
						jetAlgorithm = algorithm ) ) 
			jetSeq += getattr(proc, mod["PFJets"])

			if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PFSK'
			if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PFSK'
		
		elif 'CS' in PUMethod: 

			from RecoJets.JetProducers.ak4PFJetsCHSCS_cfi import ak4PFJetsCHSCS
			mod["PFJets"] = jetalgo+'PFJetsCS'+postFix
			_addProcessAndTask(proc, mod["PFJets"],
					ak4PFJetsCHSCS.clone( doAreaFastjet = True, 
						src = cms.InputTag( pfCand ), #srcForPFJets ),
						csRParam = cms.double(jetSize),
						jetAlgorithm = algorithm ) ) 
			if miniAOD: getattr( proc, mod["PFJets"]).src = pfCand
			jetSeq += getattr(proc, mod["PFJets"])

			if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PFCS'
			if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PFCS'

		elif 'CHS' in PUMethod: 
			
			if miniAOD:
				if ('chs' in tmpPfCandName): 
					srcForPFJets = pfCand
					if verbosity>=1: print('|---- jetToolBox: Not running CHS algorithm because keyword CHS was specified in nameNewPFCollection, but applying CHS corrections.')
				else: 
					_addProcessAndTask(proc, 'chs', cms.EDFilter('CandPtrSelector', src=cms.InputTag(pfCand), cut=cms.string('fromPV')))
					jetSeq += getattr(proc, 'chs')
					srcForPFJets = 'chs'
			else:
				if ( pfCand == 'particleFlow' ):
					from RecoParticleFlow.PFProducer.particleFlowTmpPtrs_cfi import particleFlowTmpPtrs
					_addProcessAndTask(proc, 'newParticleFlowTmpPtrs', particleFlowTmpPtrs.clone(src=pfCand))
					jetSeq += getattr(proc, 'newParticleFlowTmpPtrs')
					from CommonTools.ParticleFlow.pfNoPileUpJME_cff import pfPileUpJME, pfNoPileUpJME
					proc.load('CommonTools.ParticleFlow.goodOfflinePrimaryVertices_cfi')
					_addProcessAndTask(proc, 'newPfPileUpJME', pfPileUpJME.clone(PFCandidates='newParticleFlowTmpPtrs'))
					jetSeq += getattr(proc, 'newPfPileUpJME')
					_addProcessAndTask(proc, 'newPfNoPileUpJME', pfNoPileUpJME.clone(topCollection='newPfPileUpJME', bottomCollection='newParticleFlowTmpPtrs'))
					jetSeq += getattr(proc, 'newPfNoPileUpJME')
					srcForPFJets = 'newPfNoPileUpJME'
				else: 
					proc.load('CommonTools.ParticleFlow.pfNoPileUpJME_cff')
					srcForPFJets = 'pfNoPileUpJME'
				
			mod["PFJets"] = jetalgo+'PFJetsCHS'+postFix
			_addProcessAndTask(proc, mod["PFJets"],
					ak4PFJetsCHS.clone( src = cms.InputTag( srcForPFJets ), 
						doAreaFastjet = True, 
						rParam = jetSize, 
						jetAlgorithm = algorithm ) ) 
			jetSeq += getattr(proc, mod["PFJets"])

			if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PFchs'
			if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PFchs'

		else: 
			PUMethod = ''
			mod["PFJets"] = jetalgo+'PFJets'+postFix
			_addProcessAndTask(proc, mod["PFJets"],
					ak4PFJets.clone( 
						doAreaFastjet = True, 
						rParam = jetSize, 
						jetAlgorithm = algorithm ) ) 
			if miniAOD: getattr( proc, mod["PFJets"]).src = pfCand
			jetSeq += getattr(proc, mod["PFJets"])
			if JETCorrPayload not in payloadList: JETCorrPayload = 'AK'+size+'PF'
			if subJETCorrPayload not in payloadList: subJETCorrPayload = 'AK4PF'


		if 'None' in JETCorrPayload: JEC = None
		else: JEC = ( JETCorrPayload.replace('CS','chs').replace('SK','chs') , JETCorrLevels, 'None' )   ### temporary
		#else: JEC = ( JETCorrPayload., JETCorrLevels, 'None' ) 
		if verbosity>=2: print('|---- jetToolBox: Applying these corrections: '+str(JEC))

		if addPrunedSubjets or addSoftDropSubjets or addCMSTopTagger:
			if 'None' in subJETCorrPayload: subJEC = None
			else: subJEC = ( subJETCorrPayload.replace('CS','chs').replace('SK','chs') , subJETCorrLevels, 'None' )   ### temporary


		mod["PFJetsConstituents"] = mod["PFJets"]+'Constituents'
		mod["PFJetsConstituentsColon"] = mod["PFJets"]+'Constituents:constituents'
		mod["PFJetsConstituentsColonOrUpdate"] = mod["PFJetsConstituentsColon"] if not updateCollection else updateCollection
		if (PUMethod in [ 'CHS', 'CS', 'Puppi' ]) and miniAOD: _addProcessAndTask(proc, mod["PFJetsConstituents"], cms.EDProducer("MiniAODJetConstituentSelector", src=cms.InputTag(mod["PFJets"]), cut=cms.string(Cut)))
		else: _addProcessAndTask(proc, mod["PFJetsConstituents"], cms.EDProducer("PFJetConstituentSelector", src=cms.InputTag(mod["PFJets"]), cut=cms.string(Cut)))
		jetSeq += getattr(proc, mod["PFJetsConstituents"])

		addJetCollection(
				proc,
				labelName = mod["PATJetsLabel"],
				jetSource = cms.InputTag(mod["PFJets"]),
				postfix = postFix, 
				algo = jetalgo,
				rParam = jetSize,
				jetCorrections = JEC if JEC is not None else None, 
				pfCandidates = cms.InputTag( pfCand ),  
				svSource = cms.InputTag( svLabel ),  
				genJetCollection = cms.InputTag(mod["GenJetsNoNu"]),
				pvSource = cms.InputTag( pvLabel ), 
				muSource = cms.InputTag( muLabel ),
				elSource = cms.InputTag( elLabel ),
				btagDiscriminators = bTagDiscriminators,
				btagInfos = bTagInfos,
				getJetMCFlavour = GetJetMCFlavour,
				genParticles = cms.InputTag(genParticlesLabel),
				outputModules = ['outputFile']
				)
		patJets = 'patJets'
		patSubJets = ''
		selPatJets = 'selectedPatJets'
		mod["PATJets"] = patJets+mod["PATJetsLabelPost"]
		mod["selPATJets"] = selPatJets+mod["PATJetsLabelPost"]
		getattr(proc, mod["PATJets"]).addTagInfos = cms.bool(True)

		if 'CS' in PUMethod: getattr( proc, mod["PATJets"] ).getJetMCFlavour = False  # CS jets cannot be re-clustered from their constituents
	else:
		if verbosity>=2: print('|---- jetToolBox: JETTOOLBOX IS UPDATING '+updateCollection+' collection')
		genParticlesLabel = 'prunedGenParticles'
		pvLabel = 'offlineSlimmedPrimaryVertices'
		svLabel = 'slimmedSecondaryVertices'
		tvLabel = 'unpackedTracksAndVertices'
		muLabel = 'slimmedMuons'
		elLabel = 'slimmedElectrons'

		if not JETCorrPayload: 
			raise ValueError('|---- jetToolBox: updateCollection option requires to add JETCorrPayload.')

		JEC = ( JETCorrPayload, JETCorrLevels, 'None' )   ### temporary
		if verbosity>=2: print('|---- jetToolBox: Applying these corrections: '+str(JEC))
		updateJetCollection(
				proc,
				postfix = postFix,
				jetSource = cms.InputTag( updateCollection ),
				labelName = mod["PATJetsLabel"],
				jetCorrections = JEC, 
				btagDiscriminators = bTagDiscriminators,
				)
		mod["PATJetsCorrFactors"] = 'patJetCorrFactors'+mod["PATJetsLabelPost"]
		getattr( proc, mod["PATJetsCorrFactors"] ).payload = JETCorrPayload
		getattr( proc, mod["PATJetsCorrFactors"] ).levels = JETCorrLevels
		patJets = 'updatedPatJets'
		patSubJets = ''
		selPatJets = 'selectedPatJets'
		mod["PATJets"] = patJets+mod["PATJetsLabelPost"]
		mod["selPATJets"] = selPatJets+mod["PATJetsLabelPost"]

		if updateCollectionSubjets:
			if verbosity>=2: print('|---- jetToolBox: JETTOOLBOX IS UPDATING '+updateCollectionSubjets+' collection for subjets/groomers.')
			if 'SoftDrop' in updateCollectionSubjets: updateSubjetLabel = 'SoftDrop'
			else: updateSubjetLabel = 'Pruned'
			mod["PATSubjetsLabel"] = jetALGO+'PF'+PUMethod+postFix+updateSubjetLabel+'Packed'
			updateJetCollection(
					proc,
					jetSource = cms.InputTag( updateCollectionSubjets ),
					labelName = mod["PATSubjetsLabel"],
					jetCorrections = JEC, 
					explicitJTA = True,
					fatJets = cms.InputTag( updateCollection ),
					rParam = jetSize, 
					algo = jetALGO,
					btagDiscriminators = subjetBTagDiscriminators,
					)
			mod["PATSubjetsCorrFactors"] = 'patJetCorrFactors'+mod["PATSubjetsLabel"]
			getattr( proc, mod["PATSubjetsCorrFactors"] ).payload = subJETCorrPayload
			getattr( proc, mod["PATSubjetsCorrFactors"] ).levels = subJETCorrLevels
			patSubJets = 'updatedPatJets'+mod["PATSubjetsLabel"]

		if addPrunedSubjets or addSoftDropSubjets or addCMSTopTagger or addMassDrop or addHEPTopTagger or addPruning or addSoftDrop: 
			if verbosity>=1: print('|---- jetToolBox: You are trying to add a groomer variable into a clustered jet collection. THIS IS NOT RECOMMENDED, it is recommended to recluster jets instead using a plain jetToolbox configuration. Please use this feature at your own risk.')

	mod["PFJetsOrUpdate"] = mod["PFJets"] if not updateCollection else updateCollection

	if bTagDiscriminators and verbosity>=2: print('|---- jetToolBox: Adding these btag discriminators: '+str(bTagDiscriminators)+' in the jet collection.')
	if ( (addPrunedSubjets or addSoftDropSubjets) or (updateCollection and updateCollectionSubjets) ) and subjetBTagDiscriminators and verbosity>=2:
		print('|---- jetToolBox: Adding these btag discriminators: '+str(subjetBTagDiscriminators)+' in the subjet collection.')

	#### Groomers
	if addSoftDrop or addSoftDropSubjets: 

		mod["PFJetsSoftDrop"] = mod["PFJets"]+'SoftDrop'
		mod["SoftDropMass"] = mod["PFJets"]+'SoftDropMass'
		_addProcessAndTask(proc, mod["PFJetsSoftDrop"],
			ak8PFJetsCHSSoftDrop.clone( 
				src = cms.InputTag( mod["PFJetsConstituentsColonOrUpdate"] ),
				rParam = jetSize, 
				jetAlgorithm = algorithm, 
				useExplicitGhosts=True,
				R0= cms.double(jetSize),
				zcut=zCutSD, 
				beta=betaCut,
				doAreaFastjet = cms.bool(True),
				writeCompound = cms.bool(True),
				jetCollInstanceName=cms.string('SubJets') ) )
		_addProcessAndTask(proc, mod["SoftDropMass"],
			ak8PFJetsCHSSoftDropMass.clone( src = cms.InputTag( mod["PFJetsOrUpdate"] ), 
				matched = cms.InputTag( mod["PFJetsSoftDrop"] ),
				distMax = cms.double( jetSize ) ) )

		elemToKeep += [ 'keep *_'+mod["SoftDropMass"]+'_*_*'] 
		jetSeq += getattr(proc, mod["PFJetsSoftDrop"] )
		jetSeq += getattr(proc, mod["SoftDropMass"] )
		getattr( proc, mod["PATJets"]).userData.userFloats.src += [ mod["SoftDropMass"] ]
		toolsUsed.append( mod["SoftDropMass"] )

		if addSoftDropSubjets:

			mod["GenJetsNoNuSoftDrop"] = mod["GenJetsNoNu"]+'SoftDrop'
			if runOnMC:
				_addProcessAndTask(proc, mod["GenJetsNoNuSoftDrop"],
						ak4GenJets.clone(
							SubJetParameters,
							useSoftDrop = cms.bool(True),
							rParam = jetSize, 
							jetAlgorithm = algorithm, 
							useExplicitGhosts=cms.bool(True),
							#zcut=cms.double(zCutSD), 
							R0= cms.double(jetSize),
							beta=cms.double(betaCut),
							writeCompound = cms.bool(True),
							jetCollInstanceName=cms.string('SubJets')
							))
				if miniAOD: getattr( proc, mod["GenJetsNoNuSoftDrop"] ).src = mod["GenParticlesNoNu"]
				jetSeq += getattr(proc, mod["GenJetsNoNuSoftDrop"] )

			mod["PATJetsSoftDropLabel"] = mod["PATJetsLabelPost"]+'SoftDrop'
			addJetCollection(
					proc,
					labelName = mod["PATJetsSoftDropLabel"],
					jetSource = cms.InputTag( mod["PFJetsSoftDrop"]),
					algo = jetalgo,
					rParam = jetSize,
					jetCorrections = JEC if JEC is not None else None, 
					pvSource = cms.InputTag( pvLabel ),
					btagDiscriminators = ['None'],
					genJetCollection = cms.InputTag( mod["GenJetsNoNu"]),
					getJetMCFlavour = False, # jet flavor should always be disabled for groomed jets
					genParticles = cms.InputTag(genParticlesLabel),
					outputModules = ['outputFile']
					)
			mod["PATJetsSoftDrop"] = patJets+mod["PATJetsSoftDropLabel"]
			mod["selPATJetsSoftDrop"] = selPatJets+mod["PATJetsSoftDropLabel"]

			_addProcessAndTask(proc, mod["selPATJetsSoftDrop"], selectedPatJets.clone(src=mod["PATJetsSoftDrop"], cut=Cut))

			mod["PATSubjetsSoftDropLabel"] = mod["PATJetsSoftDropLabel"]+'Subjets'
			addJetCollection(
					proc,
					labelName = mod["PATSubjetsSoftDropLabel"],
					jetSource = cms.InputTag( mod["PFJetsSoftDrop"], 'SubJets'),
					algo = jetalgo,  # needed for subjet b tagging
					rParam = jetSize,  # needed for subjet b tagging
					jetCorrections = subJEC if subJEC is not None else None, 
					pfCandidates = cms.InputTag( pfCand ), 
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ),  
					muSource = cms.InputTag( muLabel ),
					elSource = cms.InputTag( elLabel ),
					btagDiscriminators = subjetBTagDiscriminators,
					btagInfos = bTagInfos,
					genJetCollection = cms.InputTag( mod["GenJetsNoNuSoftDrop"],'SubJets'),
					getJetMCFlavour = GetSubjetMCFlavour,
					genParticles = cms.InputTag(genParticlesLabel),
					explicitJTA = True,  # needed for subjet b tagging
					svClustering = True, # needed for subjet b tagging
					fatJets=cms.InputTag(mod["PFJets"]),             # needed for subjet flavor clustering
					groomedFatJets=cms.InputTag(mod["PFJetsSoftDrop"]), # needed for subjet flavor clustering
					outputModules = ['outputFile']
					) 
			mod["PATSubjetsSoftDrop"] = patJets+mod["PATSubjetsSoftDropLabel"]
			mod["selPATSubjetsSoftDrop"] = selPatJets+mod["PATSubjetsSoftDropLabel"]

			_addProcessAndTask(proc, mod["selPATSubjetsSoftDrop"], selectedPatJets.clone(src=mod["PATSubjetsSoftDrop"], cut=CutSubjet))

			# Establish references between PATified fat jets and subjets using the BoostedJetMerger
			mod["selPATJetsSoftDropPacked"] = mod["selPATJetsSoftDrop"]+'Packed'
			_addProcessAndTask(proc, mod["selPATJetsSoftDropPacked"],
					cms.EDProducer("BoostedJetMerger",
						jetSrc=cms.InputTag(mod["selPATJetsSoftDrop"]),
						subjetSrc=cms.InputTag(mod["selPATSubjetsSoftDrop"])
						))
			jetSeq += getattr(proc, mod["selPATJetsSoftDropPacked"] )
			elemToKeep += [ 'keep *_'+mod["selPATJetsSoftDropPacked"]+'_SubJets_*' ]
			toolsUsed.append( mod["selPATJetsSoftDropPacked"]+':SubJets' )

			## Pack fat jets with subjets
			mod["packedPATJetsSoftDrop"] = 'packedPatJets'+mod["PATJetsSoftDropLabel"]
			_addProcessAndTask(proc, mod["packedPATJetsSoftDrop"],
				 cms.EDProducer("JetSubstructurePacker",
						jetSrc=cms.InputTag(mod["selPATJets"]),
						distMax = cms.double( jetSize ),
						fixDaughters = cms.bool(False),
						algoTags = cms.VInputTag(
						cms.InputTag(mod["selPATJetsSoftDropPacked"])
						), 
						algoLabels =cms.vstring('SoftDrop')
						)
				 )
			jetSeq += getattr(proc, mod["packedPATJetsSoftDrop"])
			elemToKeep += [ 'keep *_'+mod["packedPATJetsSoftDrop"]+'_*_*' ]
			if verbosity>=2: print('|---- jetToolBox: Creating '+mod["packedPATJetsSoftDrop"]+' collection with SoftDrop subjets.')



	if addPruning or addPrunedSubjets: 

		mod["PFJetsPruned"] = mod["PFJets"]+'Pruned'
		mod["PrunedMass"] =  mod["PFJets"]+'PrunedMass'
		_addProcessAndTask(proc, mod["PFJetsPruned"],
			ak8PFJetsCHSPruned.clone( 
				src = cms.InputTag( mod["PFJetsConstituentsColonOrUpdate"] ),
				rParam = jetSize, 
				jetAlgorithm = algorithm, 
				zcut=zCut, 
				rcut_factor=rCut,
				writeCompound = cms.bool(True),
				doAreaFastjet = cms.bool(True),
				jetCollInstanceName=cms.string('SubJets') ) )
		_addProcessAndTask(proc, mod["PrunedMass"],
			ak8PFJetsCHSPrunedMass.clone( 
				src = cms.InputTag( mod["PFJetsOrUpdate"] ), 
				matched = cms.InputTag( mod["PFJetsPruned"]), 
				distMax = cms.double( jetSize ) ) )

		jetSeq += getattr(proc, mod["PFJetsPruned"])
		jetSeq += getattr(proc, mod["PrunedMass"])
		getattr( proc, mod["PATJets"]).userData.userFloats.src += [ mod["PrunedMass"] ]
		elemToKeep += [ 'keep *_'+mod["PrunedMass"]+'_*_*'] 
		toolsUsed.append( mod["PrunedMass"] )

		if addPrunedSubjets:
			if runOnMC:
				mod["GenJetsNoNuPruned"] = mod["GenJetsNoNu"]+'Pruned'
				_addProcessAndTask(proc, mod["GenJetsNoNuPruned"],
						ak4GenJets.clone(
							SubJetParameters,
							rParam = jetSize,
							usePruning = cms.bool(True),
							writeCompound = cms.bool(True),
							jetCollInstanceName=cms.string('SubJets')
							))
				if miniAOD: getattr( proc, mod["GenJetsNoNuPruned"] ).src = mod["GenParticlesNoNu"]
				jetSeq += getattr(proc, mod["GenJetsNoNuPruned"])

			mod["PATJetsPrunedLabel"] = mod["PATJetsLabelPost"]+'Pruned'
			addJetCollection(
					proc,
					labelName = mod["PATJetsPrunedLabel"],
					jetSource = cms.InputTag( mod["PFJetsPruned"]),
					algo = jetalgo,
					rParam = jetSize,
					jetCorrections = JEC if JEC is not None else None, 
					pvSource = cms.InputTag( pvLabel ),
					btagDiscriminators = ['None'],
					genJetCollection = cms.InputTag( mod["GenJetsNoNu"]),
					getJetMCFlavour = False, # jet flavor should always be disabled for groomed jets
					genParticles = cms.InputTag(genParticlesLabel),
					outputModules = ['outputFile']
					)
			mod["PATJetsPruned"] = patJets+mod["PATJetsPrunedLabel"]
			mod["selPATJetsPruned"] = selPatJets+mod["PATJetsPrunedLabel"]

			_addProcessAndTask(proc, mod["selPATJetsPruned"], selectedPatJets.clone(src=mod["PATJetsPruned"], cut=Cut))

			mod["PATSubjetsPrunedLabel"] = mod["PATJetsPrunedLabel"]+'Subjets'
			addJetCollection(
					proc,
					labelName = mod["PATSubjetsPrunedLabel"],
					jetSource = cms.InputTag( mod["PFJetsPruned"], 'SubJets'),
					algo = jetalgo,  # needed for subjet b tagging
					rParam = jetSize,  # needed for subjet b tagging
					jetCorrections = subJEC if subJEC is not None else None, 
					pfCandidates = cms.InputTag( pfCand ),  
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ), 
					muSource = cms.InputTag( muLabel ),
					elSource = cms.InputTag( elLabel ),
					getJetMCFlavour = GetSubjetMCFlavour,
					genParticles = cms.InputTag(genParticlesLabel),
					btagDiscriminators = subjetBTagDiscriminators,
					btagInfos = bTagInfos,
					genJetCollection = cms.InputTag( mod["GenJetsNoNuPruned"],'SubJets'),
					explicitJTA = True,  # needed for subjet b tagging
					svClustering = True, # needed for subjet b tagging
					fatJets=cms.InputTag(mod["PFJets"]),             # needed for subjet flavor clustering
					groomedFatJets=cms.InputTag(mod["PFJetsPruned"]), # needed for subjet flavor clustering
					outputModules = ['outputFile']
					) 
			mod["PATSubjetsPruned"] = patJets+mod["PATSubjetsPrunedLabel"]
			mod["selPATSubjetsPruned"] = selPatJets+mod["PATSubjetsPrunedLabel"]

			_addProcessAndTask(proc, mod["selPATSubjetsPruned"], selectedPatJets.clone(src=mod["PATSubjetsPruned"], cut=CutSubjet))

			## Establish references between PATified fat jets and subjets using the BoostedJetMerger
			mod["selPATJetsPrunedPacked"] = mod["selPATJetsPruned"]+'Packed'
			_addProcessAndTask(proc, mod["selPATJetsPrunedPacked"],
					cms.EDProducer("BoostedJetMerger",
						jetSrc=cms.InputTag(mod["selPATJetsPruned"]),
						subjetSrc=cms.InputTag(mod["selPATSubjetsPruned"]),
						))
			jetSeq += getattr(proc, mod["selPATJetsPrunedPacked"])
			elemToKeep += [ 'keep *_'+mod["selPATJetsPrunedPacked"]+'_SubJets_*' ]
			toolsUsed.append( mod["selPATJetsPrunedPacked"]+':SubJets' )

			## Pack fat jets with subjets
			mod["packedPATJetsPruned"] = 'packedPatJets'+mod["PATSubjetsPrunedLabel"]
			_addProcessAndTask(proc, mod["packedPATJetsPruned"],
				 cms.EDProducer("JetSubstructurePacker",
						jetSrc=cms.InputTag(mod["selPATJets"]),
						distMax = cms.double( jetSize ),
						fixDaughters = cms.bool(False),
						algoTags = cms.VInputTag(
						cms.InputTag(mod["selPATJetsPrunedPacked"])
						), 
						algoLabels =cms.vstring('Pruned')
						)
				 )
			jetSeq += getattr(proc, mod["packedPATJetsPruned"])
			elemToKeep += [ 'keep *_'+mod["packedPATJetsPruned"]+'_*_*' ]
			if verbosity>=2: print('|---- jetToolBox: Creating '+mod["packedPATJetsPruned"]+' collection with Pruned subjets.')


	if addTrimming:

		mod["PFJetsTrimmed"] = mod["PFJets"]+'Trimmed'
		mod["TrimmedMass"] = mod["PFJets"]+'TrimmedMass'
		_addProcessAndTask(proc, mod["PFJetsTrimmed"],
				ak8PFJetsCHSTrimmed.clone( 
					rParam = jetSize, 
					src = cms.InputTag( mod["PFJetsConstituentsColonOrUpdate"] ),
					jetAlgorithm = algorithm,
					rFilt= rFiltTrim,
					trimPtFracMin= ptFrac) ) 
		_addProcessAndTask(proc, mod["TrimmedMass"],
				ak8PFJetsCHSTrimmedMass.clone( 
					src = cms.InputTag( mod["PFJetsOrUpdate"] ), 
					matched = cms.InputTag( mod["PFJetsTrimmed"]), 
					distMax = cms.double( jetSize ) ) )

		elemToKeep += [ 'keep *_'+mod["TrimmedMass"]+'_*_*'] 
		jetSeq += getattr(proc, mod["PFJetsTrimmed"])
		jetSeq += getattr(proc, mod["TrimmedMass"])
		getattr( proc, mod["PATJets"]).userData.userFloats.src += [mod["TrimmedMass"]]
		toolsUsed.append( mod["TrimmedMass"] )

	if addFiltering:

		mod["PFJetsFiltered"] = mod["PFJets"]+'Filtered'
		mod["FilteredMass"] = mod["PFJets"]+'FilteredMass'
		_addProcessAndTask(proc, mod["PFJetsFiltered"],
				ak8PFJetsCHSFiltered.clone( 
					src = cms.InputTag( mod["PFJetsConstituentsColonOrUpdate"] ),
					rParam = jetSize, 
					jetAlgorithm = algorithm,
					rFilt= rfilt,
					nFilt= nfilt ) ) 
		_addProcessAndTask(proc, mod["FilteredMass"],
				ak8PFJetsCHSFilteredMass.clone( 
					src = cms.InputTag( mod["PFJetsOrUpdate"] ), 
					matched = cms.InputTag( mod["PFJetsFiltered"]), 
					distMax = cms.double( jetSize ) ) )
		elemToKeep += [ 'keep *_'+mod["FilteredMass"]+'_*_*'] 
		jetSeq += getattr(proc, mod["PFJetsFiltered"])
		jetSeq += getattr(proc, mod["FilteredMass"])
		getattr( proc, patJets+jetALGO+'PF'+PUMethod+postFix).userData.userFloats.src += [mod["FilteredMass"]]
		toolsUsed.append( mod["FilteredMass"] )

	if addCMSTopTagger :

		if 'CA' in jetALGO : 

			mod["PFJetsCMSTopTag"] = mod["PFJets"].replace(jetalgo,"cmsTopTag")
			_addProcessAndTask(proc, mod["PFJetsCMSTopTag"],
					cms.EDProducer("CATopJetProducer",
						PFJetParameters.clone( 
							src = cms.InputTag( mod["PFJetsConstituentsColonOrUpdate"] ),
							doAreaFastjet = cms.bool(True),
							doRhoFastjet = cms.bool(False),
							jetPtMin = cms.double(100.0)
							),
						AnomalousCellParameters,
						CATopJetParameters.clone( jetCollInstanceName = cms.string("SubJets"),
							verbose = cms.bool(False),
							algorithm = cms.int32(1), # 0 = KT, 1 = CA, 2 = anti-KT
							tagAlgo = cms.int32(0), #0=legacy top
							useAdjacency = cms.int32(2), # modified adjacency
							centralEtaCut = cms.double(2.5), # eta for defining "central" jets
							sumEtBins = cms.vdouble(0,1600,2600), # sumEt bins over which cuts vary. vector={bin 0 lower bound, bin 1 lower bound, ...}
							rBins = cms.vdouble(0.8,0.8,0.8), # Jet distance paramter R. R values depend on sumEt bins.
							ptFracBins = cms.vdouble(0.05,0.05,0.05), # minimum fraction of central jet pt for subjets (deltap)
							deltarBins = cms.vdouble(0.19,0.19,0.19), # Applicable only if useAdjacency=1. deltar adjacency values for each sumEtBin
							nCellBins = cms.vdouble(1.9,1.9,1.9),
							),
						jetAlgorithm = cms.string("CambridgeAachen"),
						rParam = cms.double(jetSize),
						writeCompound = cms.bool(True)
						)
					)
			
			mod["CATopTagInfos"] = "CATopTagInfos"+postFix
			_addProcessAndTask(proc, mod["CATopTagInfos"],
					cms.EDProducer("CATopJetTagger",
						src = cms.InputTag(mod["PFJetsCMSTopTag"]),
						TopMass = cms.double(171),
						TopMassMin = cms.double(0.),
						TopMassMax = cms.double(250.),
						WMass = cms.double(80.4),
						WMassMin = cms.double(0.0),
						WMassMax = cms.double(200.0),
						MinMassMin = cms.double(0.0),
						MinMassMax = cms.double(200.0),
						verbose = cms.bool(False)
						)
					)
			mod["PATJetsCMSTopTagLabel"] = 'CMSTopTag'+PUMethod+postFix
			addJetCollection(
					proc,
					labelName = mod["PATJetsCMSTopTagLabel"],
					jetSource = cms.InputTag(mod["PFJetsCMSTopTag"]),
					jetCorrections = JEC if JEC is not None else None, 
					pfCandidates = cms.InputTag( pfCand ),  
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ), 
					muSource = cms.InputTag( muLabel ),
					elSource = cms.InputTag( elLabel ),
					btagDiscriminators = bTagDiscriminators,
					btagInfos = bTagInfos,
					genJetCollection = cms.InputTag(mod["GenJetsNoNu"]),
					getJetMCFlavour = False, # jet flavor should always be disabled for groomed jets
					genParticles = cms.InputTag(genParticlesLabel)
					)
			mod["PATJetsCMSTopTag"] = patJets+mod["PATJetsCMSTopTagLabel"]
			mod["selPATJetsCMSTopTag"] = selPatJets+mod["PATJetsCMSTopTagLabel"]
			getattr(proc,mod["PATJetsCMSTopTag"]).addTagInfos = True
			getattr(proc,mod["PATJetsCMSTopTag"]).tagInfoSources = cms.VInputTag( cms.InputTag(mod["CATopTagInfos"]))
			_addProcessAndTask(proc, mod["selPATJetsCMSTopTag"], selectedPatJets.clone(src=mod["PATJetsCMSTopTag"], cut=Cut))

			mod["PATSubjetsCMSTopTagLabel"] = mod["PATJetsCMSTopTagLabel"]+'Subjets'
			addJetCollection(
					proc,
					labelName = mod["PATSubjetsCMSTopTagLabel"],
					jetSource = cms.InputTag(mod["PFJetsCMSTopTag"], 'SubJets'),
					algo = jetalgo,  # needed for subjet b tagging
					rParam = jetSize,  # needed for subjet b tagging
					jetCorrections = subJEC if subJEC is not None else None, 
					pfCandidates = cms.InputTag( pfCand ),  
					pvSource = cms.InputTag( pvLabel), 
					svSource = cms.InputTag( svLabel ), 
					muSource = cms.InputTag( muLabel ),
					elSource = cms.InputTag( elLabel ),
					btagDiscriminators = bTagDiscriminators,
					btagInfos = bTagInfos,
					genJetCollection = cms.InputTag( mod["GenJetsNoNu"]),
					getJetMCFlavour = GetSubjetMCFlavour,
					explicitJTA = True,  # needed for subjet b tagging
					svClustering = True, # needed for subjet b tagging
					fatJets=cms.InputTag(mod["PFJets"]),             # needed for subjet flavor clustering
					groomedFatJets=cms.InputTag(mod["PATJetsCMSTopTag"]), # needed for subjet flavor clustering
					genParticles = cms.InputTag(genParticlesLabel)
					)
			mod["PATSubjetsCMSTopTag"] = patJets+mod["PATSubjetsCMSTopTagLabel"]
			mod["selPATSubjetsCMSTopTag"] = selPatJets+mod["PATSubjetsCMSTopTagLabel"]

			_addProcessAndTask(proc, mod["selPATSubjetsCMSTopTag"], selectedPatJets.clone(src=mod["PATSubjetsCMSTopTag"], cut=Cut))

			mod["PATJetsCMSTopTagPacked"] = mod["PATJetsCMSTopTag"]+'Packed'
			_addProcessAndTask(proc, mod["PATJetsCMSTopTagPacked"],
					cms.EDProducer("BoostedJetMerger",
						jetSrc=cms.InputTag(mod["PATJetsCMSTopTag"]),
						subjetSrc=cms.InputTag(mod["PATSubjetsCMSTopTag"])
						))
			jetSeq += getattr(proc, mod["PATJetsCMSTopTagPacked"])
			elemToKeep += [ 'keep *_'+mod["PATJetsCMSTopTagPacked"]+'_*_*' ]
			toolsUsed.append( mod["PATJetsCMSTopTagPacked"] )

		else:
			raise ValueError('|---- jetToolBox: CMS recommends CambridgeAachen for CMS Top Tagger, you are using '+algorithm+'. JetToolbox will not run CMS Top Tagger.')

	if addMassDrop :

		if 'CA' in jetALGO :
			mod["PFJetsMassDrop"] = mod["PFJets"]+'MassDropFiltered'
			mod["MassDropFilteredMass"] = mod["PFJetsMassDrop"]+'Mass'
			_addProcessAndTask(proc, mod["PFJetsMassDrop"],
					ca15PFJetsCHSMassDropFiltered.clone( 
						rParam = jetSize,
						src = cms.InputTag( mod["PFJetsConstituentsColonOrUpdate"] ),
						) )
			_addProcessAndTask(proc, mod["MassDropFilteredMass"], ak8PFJetsCHSPrunedMass.clone(src=cms.InputTag(mod["PFJets"]),
				matched = cms.InputTag(mod["PFJetsMassDrop"]), distMax = cms.double( jetSize ) ) )
			elemToKeep += [ 'keep *_'+mod["MassDropFilteredMass"]+'_*_*' ]
			getattr( proc, mod["PATJets"]).userData.userFloats.src += [ mod["MassDropFilteredMass"] ]
			jetSeq += getattr(proc, mod["PFJetsMassDrop"])
			jetSeq += getattr(proc, mod["MassDropFilteredMass"])
			toolsUsed.append( mod["MassDropFilteredMass"] )
		else:
			raise ValueError('|---- jetToolBox: CMS recommends CambridgeAachen for Mass Drop, you are using '+algorithm+'. JetToolbox will not run Mass Drop.')

	if addHEPTopTagger: 
		if ( jetSize >= 1. ) and ( 'CA' in jetALGO ): 

			mod["PFJetsHEPTopTag"] = mod["PFJets"].replace(jetalgo,"hepTopTag")
			mod["PFJetsHEPTopTagMass"] = mod["PFJetsHEPTopTag"]+'Mass'+jetALGO
			_addProcessAndTask(proc, mod["PFJetsHEPTopTag"], hepTopTagPFJetsCHS.clone(src=cms.InputTag(mod["PFJetsConstituentsColonOrUpdate"])))
			_addProcessAndTask(proc, mod["PFJetsHEPTopTagMass"], ak8PFJetsCHSPrunedMass.clone(src=cms.InputTag(mod["PFJets"]),
				matched = cms.InputTag(mod["PFJetsHEPTopTag"]), distMax = cms.double( jetSize ) ) )
			elemToKeep += [ 'keep *_'+mod["PFJetsHEPTopTagMass"]+'_*_*' ]
			getattr( proc, mod["PATJets"]).userData.userFloats.src += [ mod["PFJetsHEPTopTagMass"] ]
			jetSeq += getattr(proc, mod["PFJetsHEPTopTag"])
			jetSeq += getattr(proc, mod["PFJetsHEPTopTagMass"])
			toolsUsed.append( mod["PFJetsHEPTopTagMass"] )
		else:
			raise ValueError('|---- jetToolBox: CMS recommends CambridgeAachen w/ jet cone size > 1.0 for HEPTopTagger, you are using '+algorithm+'. JetToolbox will not run HEP TopTagger.')

	####### Nsubjettiness
	if addNsub:
		from RecoJets.JetProducers.nJettinessAdder_cfi import Njettiness

		rangeTau = range(1,maxTau+1)
		mod["Njettiness"] = 'Njettiness'+mod["SubstructureLabel"]
		_addProcessAndTask(proc, mod["Njettiness"],
				Njettiness.clone( src = cms.InputTag( mod["PFJetsOrUpdate"] ),
					Njets=cms.vuint32(rangeTau),         # compute 1-, 2-, 3-, 4- subjettiness
					# variables for measure definition : 
					measureDefinition = cms.uint32( 0 ), # CMS default is normalized measure
					beta = cms.double(1.0),              # CMS default is 1
					R0 = cms.double( jetSize ),              # CMS default is jet cone size
					Rcutoff = cms.double( 999.0),       # not used by default
					# variables for axes definition :
					axesDefinition = cms.uint32( 6 ),    # CMS default is 1-pass KT axes
					nPass = cms.int32(999),             # not used by default
					akAxesR0 = cms.double(-999.0) ) )        # not used by default

		elemToKeep += [ 'keep *_'+mod["Njettiness"]+'_*_*' ]
		for tau in rangeTau: getattr( proc, mod["PATJets"]).userData.userFloats.src += [mod["Njettiness"]+':tau'+str(tau) ] 
		jetSeq += getattr(proc, mod["Njettiness"])
		toolsUsed.append( mod["Njettiness"] )

	####### Nsubjettiness
	if addNsubSubjets:

		from RecoJets.JetProducers.nJettinessAdder_cfi import Njettiness

		mod["NsubGroomer"] = ''
		mod["NsubSubjets"] = ''
		mod["NsubPATSubjets"] = ''
		if addSoftDropSubjets or updateCollectionSubjets:
			mod["NsubGroomer"] = mod["PFJetsSoftDrop"]
			mod["NsubSubjets"] = mod["PATSubjetsSoftDropLabel"]
			mod["NsubPATSubjets"] = mod["PATSubjetsSoftDrop"]
			if updateCollectionSubjets:
				if verbosity>=2: print('|---- jetToolBox: Using updateCollection option. ASSUMING MINIAOD collection '+ updateCollectionSubjets +' for Nsubjettiness of subjets.')
		elif addPrunedSubjets:
			mod["NsubGroomer"] = mod["PFJetsPruned"]
			mod["NsubSubjets"] = mod["PATSubjetsPrunedLabel"]
			mod["NsubPATSubjets"] = mod["PATSubjetsPruned"]
		else: 
			raise ValueError('|---- jetToolBox: Nsubjettiness of subjets needs a Subjet collection. Or create one using addSoftDropSubjets option, or updateCollection.')

		mod["Nsubjettiness"] = 'Nsubjettiness'+mod["NsubSubjets"]
		rangeTau = range(1,subjetMaxTau+1)
		_addProcessAndTask(proc, mod["Nsubjettiness"],
				Njettiness.clone( src = cms.InputTag( ( mod["NsubGroomer"] if not updateCollectionSubjets else updateCollectionSubjets ), 'SubJets' ), 
					Njets=cms.vuint32(rangeTau),         # compute 1-, 2-, 3-, 4- subjettiness
					# variables for measure definition : 
					measureDefinition = cms.uint32( 0 ), # CMS default is normalized measure
					beta = cms.double(1.0),              # CMS default is 1
					R0 = cms.double( jetSize ),              # CMS default is jet cone size
					Rcutoff = cms.double( 999.0),       # not used by default
					# variables for axes definition :
					axesDefinition = cms.uint32( 6 ),    # CMS default is 1-pass KT axes
					nPass = cms.int32(999),             # not used by default
					akAxesR0 = cms.double(-999.0) ) )        # not used by default

		elemToKeep += [ 'keep *_'+mod["Nsubjettiness"]+'_*_*' ]
		for tau in rangeTau: getattr( proc, ( mod["NsubPATSubjets"] if not updateCollectionSubjets else patSubJets ) ).userData.userFloats.src += [mod["Nsubjettiness"]+':tau'+str(tau) ] 
		jetSeq += getattr(proc, mod["Nsubjettiness"])
		toolsUsed.append( mod["Nsubjettiness"] )

	###### QGTagger
	if addQGTagger:
		if ( 'ak4' in jetalgo ) and ( PUMethod not in ['Puppi','CS','SK'] ) :
			from RecoJets.JetProducers.QGTagger_cfi import QGTagger
			proc.load('RecoJets.JetProducers.QGTagger_cfi') 	## In 74X you need to run some stuff before.
			mod["QGTagger"] = 'QGTagger'+mod["PATJetsLabelPost"]
			_addProcessAndTask(proc, mod["QGTagger"],
					QGTagger.clone(
						srcJets = cms.InputTag( mod["PFJetsOrUpdate"] ),    # Could be reco::PFJetCollection or pat::JetCollection (both AOD and miniAOD)
						jetsLabel = cms.string('QGL_AK4PF'+QGjetsLabel)        # Other options (might need to add an ESSource for it): see https://twiki.cern.ch/twiki/bin/viewauth/CMS/QGDataBaseVersion
						)
					)
			elemToKeep += [ 'keep *_'+mod["QGTagger"]+'_*_*' ]
			getattr( proc, mod["PATJets"]).userData.userFloats.src += [mod["QGTagger"]+':qgLikelihood']
			jetSeq += getattr(proc, mod["QGTagger"])

			toolsUsed.append( mod["QGTagger"] )
		else:
			raise ValueError('|---- jetToolBox: QGTagger is optimized for ak4 jets with CHS. NOT running QGTagger')

			
	####### Pileup JetID
	if addPUJetID:
		if ( 'ak4' in jetalgo ) and ( PUMethod not in ['CS','SK'] ):
			if PUMethod=="Puppi" and verbosity>=1: print('|---- jetToolBox: PUJetID is not yet optimized for ak4 PFjets with PUPPI. USE ONLY FOR TESTING.')
			from RecoJets.JetProducers.pileupjetidproducer_cfi import pileupJetIdCalculator,pileupJetIdEvaluator

			mod["PUJetIDCalc"] = mod["PATJetsLabelPost"]+'pileupJetIdCalculator'
			_addProcessAndTask(proc, mod["PUJetIDCalc"],
					pileupJetIdCalculator.clone(
						jets = cms.InputTag( mod["PFJetsOrUpdate"] ),
						rho = cms.InputTag("fixedGridRhoFastjetAll"),
						vertexes = cms.InputTag(pvLabel),
						applyJec = cms.bool(True),
						inputIsCorrected = cms.bool(False)
						))

			mod["PUJetIDEval"] = mod["PATJetsLabelPost"]+'pileupJetIdEvaluator'
			_addProcessAndTask(proc, mod["PUJetIDEval"],
					pileupJetIdEvaluator.clone(
						jetids = cms.InputTag(mod["PUJetIDCalc"]),
						jets = cms.InputTag( mod["PFJetsOrUpdate"] ),
						rho = cms.InputTag("fixedGridRhoFastjetAll"),
						vertexes = cms.InputTag(pvLabel)
						)
					)

			getattr( proc, mod["PATJets"]).userData.userFloats.src += [mod["PUJetIDEval"]+':fullDiscriminant']
			getattr( proc, mod["PATJets"]).userData.userInts.src += [mod["PUJetIDEval"]+':cutbasedId',mod["PUJetIDEval"]+':fullId']
			elemToKeep += ['keep *_'+mod["PUJetIDEval"]+'_*_*']
			toolsUsed.append( mod["PUJetIDEval"] )
		else:
			raise ValueError('|---- jetToolBox: PUJetID is optimized for ak4 PFjets with CHS. NOT running PUJetID.')

	###### Energy Correlation Functions
	if addEnergyCorrFunc:
		if PUMethod!="Puppi" or (addSoftDrop==False and addSoftDropSubjets==False):
			raise ValueError("|---- jetToolBox: addEnergyCorrFunc only supported for Puppi w/ addSoftDrop or addSoftDropSubjets")
		from RecoJets.JetProducers.ECF_cff import ecfNbeta1, ecfNbeta2
		mod["ECFnb1"] = 'nb1'+mod["SubstructureLabel"]+'SoftDrop'
# 		mod["ECFnb2"] = 'nb2'+mod["SubstructureLabel"]+'SoftDrop'
		_addProcessAndTask(proc, mod["ECFnb1"], ecfNbeta1.clone(src=cms.InputTag(mod["PFJetsSoftDrop"]), cuts=cms.vstring('', '', 'pt > 250')))
# 		_addProcessAndTask(proc, mod["ECFnb2"], ecfNbeta2.clone(src=cms.InputTag(mod["PFJetsSoftDrop"]), cuts=cms.vstring('', '', 'pt > 250')))
		elemToKeep += [ 'keep *_' + mod["ECFnb1"] + '_*_*',
					# 'keep *_'+mod["ECFnb2"]+'_*_*'
					]
		jetSeq += getattr(proc, mod["ECFnb1"])
# 		jetSeq += getattr(proc, mod["ECFnb2"])
# 		toolsUsed.extend([mod["ECFnb1"], mod["ECFnb2"]])
		toolsUsed.extend([mod["ECFnb1"]])

		# set up user floats
		getattr(proc, mod["PATJetsSoftDrop"]).userData.userFloats.src += [
			mod["ECFnb1"]+':ecfN2',
			mod["ECFnb1"]+':ecfN3',
# 			mod["ECFnb2"]+':ecfN2',
# 			mod["ECFnb2"]+':ecfN3',
		]
		# rekey the groomed ECF value maps to the ungroomed reco jets, which will then be picked
		# up by PAT in the user floats. 
		mod["PFJetsSoftDropValueMap"] = mod["PFJetsSoftDrop"]+'ValueMap'
		_addProcessAndTask(proc, mod["PFJetsSoftDropValueMap"],
			cms.EDProducer("RecoJetToPatJetDeltaRValueMapProducer",
				src = cms.InputTag(mod["PFJets"]),
				matched = cms.InputTag(mod["PATJetsSoftDrop"]),
				distMax = cms.double(jetSize),
				values = cms.vstring([
					'userFloat("'+mod["ECFnb1"]+':ecfN2'+'")',
					'userFloat("'+mod["ECFnb1"]+':ecfN3'+'")',
# 					'userFloat("'+mod["ECFnb2"]+':ecfN2'+'")',
# 					'userFloat("'+mod["ECFnb2"]+':ecfN3'+'")',
				]),
				valueLabels = cms.vstring( [
					mod["ECFnb1"]+'N2',
					mod["ECFnb1"]+'N3',
# 					mod["ECFnb2"]+'N2',
# 					mod["ECFnb2"]+'N3',
				]),
			)
		)
		getattr(proc, mod["PATJets"]).userData.userFloats.src += [
			mod["PFJetsSoftDropValueMap"]+':'+mod["ECFnb1"]+'N2',
			mod["PFJetsSoftDropValueMap"]+':'+mod["ECFnb1"]+'N3',
# 			mod["PFJetsSoftDropValueMap"]+':'+mod["ECFnb2"]+'N2',
# 			mod["PFJetsSoftDropValueMap"]+':'+mod["ECFnb2"]+'N3',
		]

	if addEnergyCorrFuncSubjets:
		if PUMethod!="Puppi" or addSoftDropSubjets==False:
			raise ValueError("|---- jetToolBox: addEnergyCorrFuncSubjets only supported for Puppi w/ addSoftDropSubjets")
		from RecoJets.JetProducers.ECF_cff import ecfNbeta1, ecfNbeta2
		mod["ECFnb1Subjets"] = 'nb1'+mod["SubstructureLabel"]+'SoftDropSubjets'
		mod["ECFnb2Subjets"] = 'nb2'+mod["SubstructureLabel"]+'SoftDropSubjets'
		_addProcessAndTask(proc, mod["ECFnb1Subjets"], ecfNbeta1.clone(src=cms.InputTag(mod["PFJetsSoftDrop"], 'SubJets')))
		_addProcessAndTask(proc, mod["ECFnb2Subjets"], ecfNbeta2.clone(src=cms.InputTag(mod["PFJetsSoftDrop"], 'SubJets')))
		elemToKeep += [ 'keep *_'+mod["ECFnb1Subjets"]+'_*_*', 'keep *_'+mod["ECFnb2Subjets"]+'_*_*']
		jetSeq += getattr(proc, mod["ECFnb1Subjets"])
		jetSeq += getattr(proc, mod["ECFnb2Subjets"])
		toolsUsed.extend([mod["ECFnb1Subjets"],mod["ECFnb2Subjets"]])

		# set up user floats
		getattr(proc, mod["PATSubjetsSoftDrop"]).userData.userFloats.src += [
			mod["ECFnb1Subjets"]+':ecfN2',
			mod["ECFnb1Subjets"]+':ecfN3',
			mod["ECFnb2Subjets"]+':ecfN2',
			mod["ECFnb2Subjets"]+':ecfN3',
		]

	if hasattr(proc, 'patJetPartons'): proc.patJetPartons.particles = genParticlesLabel

	_addProcessAndTask(proc, mod["selPATJets"], selectedPatJets.clone(src=mod["PATJets"], cut=Cut))
	elemToKeep += [ 'keep *_'+mod["selPATJets"]+'_*_*' ]
	elemToKeep += [ 'drop *_'+mod["selPATJets"]+'_calo*_*' ]
	elemToKeep += [ 'drop *_'+mod["selPATJets"]+'_tagInfos_*' ]

	if updateCollectionSubjets:
		mod["PATSubjets"] = patJets+mod["PATSubjetsLabel"]
		mod["selPATSubjets"] = selPatJets+mod["PATSubjetsLabel"]
		_addProcessAndTask(proc, mod["selPATSubjets"], selectedPatJets.clone(src=mod["PATSubjets"], cut=Cut))
		elemToKeep += [ 'keep *_'+mod["selPATSubjets"]+'__*' ]


	if len(toolsUsed) > 0 and verbosity>=2: print('|---- jetToolBox: Running '+', '.join(toolsUsed)+'.')
	if verbosity>=2: print('|---- jetToolBox: Creating '+mod["selPATJets"]+' collection.')
	if updateCollectionSubjets and verbosity>=2: print('|---- jetToolBox: Creating '+mod["selPATSubjets"]+' collection.')

	### "return"
	setattr(proc, jetSequence, jetSeq)
	if outputFile!='':
		if hasattr(proc, outputFile): getattr(proc, outputFile).outputCommands += elemToKeep
		else: setattr( proc, outputFile, 
				cms.OutputModule('PoolOutputModule', 
					fileName = cms.untracked.string('jettoolbox.root'), 
					outputCommands = cms.untracked.vstring( elemToKeep ) ) )

	if associateTask:
		from PhysicsTools.PatAlgos.tools.helpers import getPatAlgosToolsTask
		task = getPatAlgosToolsTask(proc)
		if hasattr(proc, 'endpath'):
			getattr(proc, 'endpath').associate(task)
		else:
			setattr(proc, 'endpath', cms.EndPath(task))
		if outputFile != '': 
			getattr(proc, 'endpath').insert(-1, getattr(proc, outputFile))

	#### removing mc matching for data
	if runOnData:
		from PhysicsTools.PatAlgos.tools.coreTools import removeMCMatching
		removeMCMatching(proc, names=['Jets'], outputModules=[outputFile])

	if verbosity>=3:
		print('|---- jetToolBox: List of modules created (and other internal names):')
		for m in mod:
			print('      '+m+' = '+mod[m])
Beispiel #17
0
process.jetTracksAssociatorAtVertexSlimmedJetsAK8BTagged.coneSize = 0.8 

process.load('PhysicsTools.PatAlgos.slimming.unpackedTracksAndVertices_cfi')
process.combinedSecondaryVertex.trackMultiplicityMin = 1 #silly sv, uses un filtered tracks.. i.e. any pt

### Add Nsubjettiness
from RecoJets.JetProducers.nJettinessAdder_cfi import Njettiness
process.Njettiness = Njettiness.clone(
    src = cms.InputTag("ak8PFJetsCHS"),
    cone = cms.double(0.8)
    )

process.patJetsAK8PFCHS.userData.userFloats.src += ['Njettiness:tau1','Njettiness:tau2','Njettiness:tau3']

from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSPruned, ak8PFJetsCHSFiltered, ak8PFJetsCHSTrimmed 
process.ak8PFJetsCHSPruned   = ak8PFJetsCHSPruned.clone(src = cms.InputTag("pfCHS"))
process.ak8PFJetsCHSTrimmed  = ak8PFJetsCHSTrimmed.clone(src = cms.InputTag("pfCHS"))
process.ak8PFJetsCHSFiltered = ak8PFJetsCHSFiltered.clone(src = cms.InputTag("pfCHS"))

from RecoJets.JetProducers.ak8PFJetsCHS_groomingValueMaps_cfi import *
process.ak8PFJetsCHSPrunedMass = cms.EDProducer("RecoJetDeltaRValueMapProducer",
                                         src = cms.InputTag("ak8PFJetsCHS"),
                                         matched = cms.InputTag("ak8PFJetsCHSPruned"),
                                         distMax = cms.double(0.8),
                                         value = cms.string('mass')
                        )
process.ak8PFJetsCHSTrimmedMass = process.ak8PFJetsCHSPrunedMass.clone(matched = cms.InputTag("ak8PFJetsCHSTrimmed"))
process.ak8PFJetsCHSFilteredMass = process.ak8PFJetsCHSPrunedMass.clone(matched = cms.InputTag("ak8PFJetsCHSFiltered"))

process.patJetsAK8PFCHS.userData.userFloats.src += ['ak8PFJetsCHSPrunedMass', 'ak8PFJetsCHSTrimmedMass', 'ak8PFJetsCHSFilteredMass']
def applySubstructure( process ) :

    from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection

    # add CMS top tagger
    from RecoJets.JetProducers.caTopTaggers_cff import caTopTagInfos
    process.caTopTagInfos = caTopTagInfos.clone()
    process.caTopTagInfosPAT = cms.EDProducer("RecoJetDeltaRTagInfoValueMapProducer",
                                    src = cms.InputTag("ak8PFJetsCHS"),
                                    matched = cms.InputTag("cmsTopTagPFJetsCHS"),
                                    matchedTagInfos = cms.InputTag("caTopTagInfos"),
                                    distMax = cms.double(0.8)
    )

    from PhysicsTools.PatAlgos.producersLayer1.jetProducer_cfi import patJets as patJetsDefault

    #add AK8
    addJetCollection(process, labelName = 'AK8',
                     jetSource = cms.InputTag('ak8PFJetsCHS'),
                     algo= 'AK', rParam = 0.8,
                     jetCorrections = ('AK8PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
                     btagDiscriminators = ([x.getModuleLabel() for x in patJetsDefault.discriminatorSources] + ['pfBoostedDoubleSecondaryVertexAK8BJetTags']),
                     genJetCollection = cms.InputTag('slimmedGenJetsAK8')
                     )
    process.patJetsAK8.userData.userFloats.src = [] # start with empty list of user floats
    process.selectedPatJetsAK8.cut = cms.string("pt > 170")



    ## AK8 groomed masses
    from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSPruned, ak8PFJetsCHSSoftDrop, ak8PFJetsCHSFiltered, ak8PFJetsCHSTrimmed 
    process.ak8PFJetsCHSPruned   = ak8PFJetsCHSPruned.clone()
    process.ak8PFJetsCHSSoftDrop = ak8PFJetsCHSSoftDrop.clone()
    process.ak8PFJetsCHSTrimmed  = ak8PFJetsCHSTrimmed.clone()
    process.ak8PFJetsCHSFiltered = ak8PFJetsCHSFiltered.clone()
    process.load("RecoJets.JetProducers.ak8PFJetsCHS_groomingValueMaps_cfi")
    process.patJetsAK8.userData.userFloats.src += ['ak8PFJetsCHSPrunedMass','ak8PFJetsCHSSoftDropMass','ak8PFJetsCHSTrimmedMass','ak8PFJetsCHSFilteredMass']

    # Add AK8 top tagging variables
    process.patJetsAK8.tagInfoSources = cms.VInputTag(cms.InputTag("caTopTagInfosPAT"))
    process.patJetsAK8.addTagInfos = cms.bool(True)



    # add Njetiness
    process.load('RecoJets.JetProducers.nJettinessAdder_cfi')
    process.NjettinessAK8 = process.Njettiness.clone()
    process.NjettinessAK8.src = cms.InputTag("ak8PFJetsCHS")
    process.NjettinessAK8.cone = cms.double(0.8)
    process.patJetsAK8.userData.userFloats.src += ['NjettinessAK8:tau1','NjettinessAK8:tau2','NjettinessAK8:tau3']


    ## PATify pruned fat jets
    addJetCollection(
        process,
        labelName = 'AK8PFCHSSoftDrop',
        jetSource = cms.InputTag('ak8PFJetsCHSSoftDrop'),
        btagDiscriminators = ['None'],
        jetCorrections = ('AK8PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),
        getJetMCFlavour = False # jet flavor disabled
    )
    
    ## PATify soft drop subjets
    addJetCollection(
        process,
        labelName = 'AK8PFCHSSoftDropSubjets',
        jetSource = cms.InputTag('ak8PFJetsCHSSoftDrop','SubJets'),
        algo = 'ak',  # needed for subjet flavor clustering
        rParam = 0.8, # needed for subjet flavor clustering
        btagDiscriminators = ['pfCombinedSecondaryVertexV2BJetTags', 'pfCombinedInclusiveSecondaryVertexV2BJetTags'],
        jetCorrections = ('AK4PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),
        explicitJTA = True,  # needed for subjet b tagging
        svClustering = True, # needed for subjet b tagging
        genJetCollection = cms.InputTag('slimmedGenJets'), 
        fatJets=cms.InputTag('ak8PFJetsCHS'),             # needed for subjet flavor clustering
        groomedFatJets=cms.InputTag('ak8PFJetsCHSSoftDrop') # needed for subjet flavor clustering
    )
    process.selectedPatJetsAK8PFCHSSoftDrop.cut = cms.string("pt > 170")
    
    process.slimmedJetsAK8PFCHSSoftDropSubjets = cms.EDProducer("PATJetSlimmer",
        src = cms.InputTag("selectedPatJetsAK8PFCHSSoftDropSubjets"),
        packedPFCandidates = cms.InputTag("packedPFCandidates"),
        dropJetVars = cms.string("1"),
        dropDaughters = cms.string("0"),
        rekeyDaughters = cms.string("1"),
        dropTrackRefs = cms.string("1"),
        dropSpecific = cms.string("1"),
        dropTagInfos = cms.string("1"),
        modifyJets = cms.bool(True),
        modifierConfig = cms.PSet( modifications = cms.VPSet() )
    )

    
    ## Establish references between PATified fat jets and subjets using the BoostedJetMerger
    process.slimmedJetsAK8PFCHSSoftDropPacked = cms.EDProducer("BoostedJetMerger",
        jetSrc=cms.InputTag("selectedPatJetsAK8PFCHSSoftDrop"),
        subjetSrc=cms.InputTag("slimmedJetsAK8PFCHSSoftDropSubjets")
    )
    
    addJetCollection(
        process,
        labelName = 'CMSTopTagCHS',
        jetSource = cms.InputTag('cmsTopTagPFJetsCHS'),
        jetCorrections = ('AK8PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
        btagDiscriminators = ['None'],
        genJetCollection = cms.InputTag('slimmedGenJetsAK8'), 
        getJetMCFlavour = False #
        )
    process.selectedPatJetsCMSTopTagCHS.cut = cms.string("pt > 200")

    addJetCollection(
        process,
        labelName = 'CMSTopTagCHSSubjets',
        jetSource = cms.InputTag('cmsTopTagPFJetsCHS','caTopSubJets'),
        algo = 'AK',  # needed for subjet flavor clustering
        rParam = 0.8, # needed for subjet flavor clustering        
        btagDiscriminators = ['pfCombinedSecondaryVertexV2BJetTags', 'pfCombinedInclusiveSecondaryVertexV2BJetTags'],
        jetCorrections = ('AK4PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),
        genJetCollection = cms.InputTag('slimmedGenJets'), # Using ak4GenJets for matching which is not entirely appropriate
        explicitJTA = True,  # needed for subjet b tagging
        svClustering = True, # needed for subjet b tagging
        fatJets=cms.InputTag('ak8PFJetsCHS'),             # needed for subjet flavor clustering
        groomedFatJets=cms.InputTag('cmsTopTagPFJetsCHS') # needed for subjet flavor clustering

        )

    process.slimmedJetsCMSTopTagCHSSubjets = cms.EDProducer("PATJetSlimmer",
        src = cms.InputTag("selectedPatJetsCMSTopTagCHSSubjets"),
        packedPFCandidates = cms.InputTag("packedPFCandidates"),
        dropJetVars = cms.string("1"),
        dropDaughters = cms.string("0"),
        rekeyDaughters = cms.string("1"),
        dropTrackRefs = cms.string("1"),
        dropSpecific = cms.string("1"),
        dropTagInfos = cms.string("1"),
        modifyJets = cms.bool(True),
        modifierConfig = cms.PSet( modifications = cms.VPSet() )
    )
    
    ## Establish references between PATified fat jets and subjets using the BoostedJetMerger
    process.slimmedJetsCMSTopTagCHSPacked = cms.EDProducer("BoostedJetMerger",
        jetSrc=cms.InputTag("selectedPatJetsCMSTopTagCHS"),
        subjetSrc=cms.InputTag("slimmedJetsCMSTopTagCHSSubjets")
    )


    process.packedPatJetsAK8 = cms.EDProducer("JetSubstructurePacker",
            jetSrc = cms.InputTag("selectedPatJetsAK8"),
            distMax = cms.double(0.8),
            algoTags = cms.VInputTag(
                # NOTE: For an optimal storage of the AK8 jet daughters, the first subjet collection listed here should be
                #       derived from AK8 jets, i.e., subjets should contain either all or a subset of AK8 constituents.
                #       The CMSTopTag subjets are derived from CA8 jets later matched to AK8 jets and could in principle
                #       contain extra constituents not clustered inside AK8 jets.
                cms.InputTag("slimmedJetsAK8PFCHSSoftDropPacked"),
                cms.InputTag("slimmedJetsCMSTopTagCHSPacked")
            ),
            algoLabels = cms.vstring(
                'SoftDrop',
                'CMSTopTag'
                ),
            fixDaughters = cms.bool(True),
            packedPFCandidates = cms.InputTag("packedPFCandidates"),
    )

    # switch off daughter re-keying since it's done in the JetSubstructurePacker (and can't be done afterwards)
    process.slimmedJetsAK8.rekeyDaughters = "0"
def miniAOD_customizeCommon(process):
    process.patMuons.isoDeposits = cms.PSet()
    process.patElectrons.isoDeposits = cms.PSet()
    process.patTaus.isoDeposits = cms.PSet()
    process.patPhotons.isoDeposits = cms.PSet()
    #
    process.patMuons.embedTrack         = True  # used for IDs
    process.patMuons.embedCombinedMuon  = True  # used for IDs
    process.patMuons.embedMuonBestTrack = True  # used for IDs
    process.patMuons.embedStandAloneMuon = True # maybe?
    process.patMuons.embedPickyMuon = False   # no, use best track
    process.patMuons.embedTpfmsMuon = False   # no, use best track
    process.patMuons.embedDytMuon   = False   # no, use best track
    #
    # disable embedding of electron and photon associated objects already stored by the ReducedEGProducer
    process.patElectrons.embedGsfElectronCore = False  ## process.patElectrons.embed in AOD externally stored gsf electron core
    process.patElectrons.embedSuperCluster    = False  ## process.patElectrons.embed in AOD externally stored supercluster
    process.patElectrons.embedPflowSuperCluster         = False  ## process.patElectrons.embed in AOD externally stored supercluster
    process.patElectrons.embedSeedCluster               = False  ## process.patElectrons.embed in AOD externally stored the electron's seedcluster 
    process.patElectrons.embedBasicClusters             = False  ## process.patElectrons.embed in AOD externally stored the electron's basic clusters 
    process.patElectrons.embedPreshowerClusters         = False  ## process.patElectrons.embed in AOD externally stored the electron's preshower clusters 
    process.patElectrons.embedPflowBasicClusters        = False  ## process.patElectrons.embed in AOD externally stored the electron's pflow basic clusters 
    process.patElectrons.embedPflowPreshowerClusters    = False  ## process.patElectrons.embed in AOD externally stored the electron's pflow preshower clusters 
    process.patElectrons.embedRecHits         = False  ## process.patElectrons.embed in AOD externally stored the RecHits - can be called from the PATElectronProducer 
    process.patElectrons.electronSource = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.patElectrons.electronIDSources = cms.PSet(
            # configure many IDs as InputTag <someName> = <someTag> you
            # can comment out those you don't want to save some disk space
            eidRobustLoose      = cms.InputTag("reducedEgamma","eidRobustLoose"),
            eidRobustTight      = cms.InputTag("reducedEgamma","eidRobustTight"),
            eidLoose            = cms.InputTag("reducedEgamma","eidLoose"),
            eidTight            = cms.InputTag("reducedEgamma","eidTight"),
            eidRobustHighEnergy = cms.InputTag("reducedEgamma","eidRobustHighEnergy"),
        )
    process.elPFIsoDepositCharged.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositChargedAll.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositNeutral.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositGamma.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositPU.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    #
    process.patPhotons.embedSuperCluster = False ## whether to process.patPhotons.embed in AOD externally stored supercluster
    process.patPhotons.embedSeedCluster               = False  ## process.patPhotons.embed in AOD externally stored the photon's seedcluster 
    process.patPhotons.embedBasicClusters             = False  ## process.patPhotons.embed in AOD externally stored the photon's basic clusters 
    process.patPhotons.embedPreshowerClusters         = False  ## process.patPhotons.embed in AOD externally stored the photon's preshower clusters 
    process.patPhotons.embedRecHits         = False  ## process.patPhotons.embed in AOD externally stored the RecHits - can be called from the PATPhotonProducer 
    process.patPhotons.photonSource = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.patPhotons.photonIDSources = cms.PSet(
                PhotonCutBasedIDLoose = cms.InputTag('reducedEgamma',
                                                      'PhotonCutBasedIDLoose'),
                PhotonCutBasedIDTight = cms.InputTag('reducedEgamma',
                                                      'PhotonCutBasedIDTight')
              )

    process.phPFIsoDepositCharged.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositChargedAll.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositNeutral.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositGamma.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositPU.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    #
    process.selectedPatJets.cut = cms.string("pt > 10")
    process.selectedPatMuons.cut = cms.string("pt > 5 || isPFMuon || (pt > 3 && (isGlobalMuon || isStandAloneMuon || numberOfMatches > 0 || muonID('RPCMuLoose')))") 
    process.selectedPatElectrons.cut = cms.string("") 
    process.selectedPatTaus.cut = cms.string("pt > 18. && tauID('decayModeFinding')> 0.5")
    process.selectedPatPhotons.cut = cms.string("")

    # add CMS top tagger
    from RecoJets.JetProducers.caTopTaggers_cff import caTopTagInfos as toptag
    process.cmsttRaw = toptag.clone()
    process.caTopTagInfos = cms.EDProducer("RecoJetDeltaRTagInfoValueMapProducer",
                                    src = cms.InputTag("ak8PFJetsCHS"),
                                    matched = cms.InputTag("cmsTopTagPFJetsCHS"),
                                    matchedTagInfos = cms.InputTag("cmsttRaw"),
                                    distMax = cms.double(0.8)
                        )
    
    #add AK8
    from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection
    addJetCollection(process, labelName = 'AK8',                     
                     jetSource = cms.InputTag('ak8PFJetsCHS'),
                     algo= 'AK', rParam = 0.8,
                     jetCorrections = ('AK8PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None'),
                     btagInfos = ['caTopTagInfos']
                     )
    process.patJetsAK8.userData.userFloats.src = [] # start with empty list of user floats
    process.selectedPatJetsAK8.cut = cms.string("pt > 100")
    process.patJetGenJetMatchAK8.matched =  'slimmedGenJets'
    ## AK8 groomed masses
    from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSPruned, ak8PFJetsCHSFiltered, ak8PFJetsCHSTrimmed 
    process.ak8PFJetsCHSPruned   = ak8PFJetsCHSPruned.clone()
    process.ak8PFJetsCHSTrimmed  = ak8PFJetsCHSTrimmed.clone()
    process.ak8PFJetsCHSFiltered = ak8PFJetsCHSFiltered.clone()
    process.load("RecoJets.JetProducers.ak8PFJetsCHS_groomingValueMaps_cfi")
    process.patJetsAK8.userData.userFloats.src += ['ak8PFJetsCHSPrunedLinks','ak8PFJetsCHSTrimmedLinks','ak8PFJetsCHSFilteredLinks']

    # Add AK8 top tagging variables
    process.patJetsAK8.tagInfoSources = cms.VInputTag(cms.InputTag("caTopTagInfos"))
    process.patJetsAK8.addTagInfos = cms.bool(True) 



    # add Njetiness
    process.load('RecoJets.JetProducers.nJettinessAdder_cfi')
    process.NjettinessAK8 = process.Njettiness.clone()
    process.NjettinessAK8.src = cms.InputTag("ak8PFJetsCHS")
    process.NjettinessAK8.cone = cms.double(0.8)
    process.patJetsAK8.userData.userFloats.src += ['NjettinessAK8:tau1','NjettinessAK8:tau2','NjettinessAK8:tau3']

            
    
    #
    from PhysicsTools.PatAlgos.tools.trigTools import switchOnTriggerStandAlone
    switchOnTriggerStandAlone( process, outputModule = '' )
    process.patTrigger.packTriggerPathNames = cms.bool(True)
    #
    # apply type I/type I + II PFMEt corrections to pat::MET object
    # and estimate systematic uncertainties on MET
    # FIXME: this and the typeI MET should become AK4 once we have the proper JEC?
    from PhysicsTools.PatUtils.tools.runType1PFMEtUncertainties import runType1PFMEtUncertainties
    addJetCollection(process, postfix   = "ForMetUnc", labelName = 'AK4PF', jetSource = cms.InputTag('ak4PFJets'), jetCorrections = ('AK4PF', ['L1FastJet', 'L2Relative', 'L3Absolute'], ''))
    process.patJetsAK4PFForMetUnc.getJetMCFlavour = False
    runType1PFMEtUncertainties(process,
                               addToPatDefaultSequence=False,
                               jetCollection="selectedPatJetsAK4PFForMetUnc",
                               electronCollection="selectedPatElectrons",
                               muonCollection="selectedPatMuons",
                               tauCollection="selectedPatTaus",
                               makeType1p2corrPFMEt=True,
                               outputModule=None)
 

    #keep this after all addJetCollections otherwise it will attempt computing them also for stuf with no taginfos
    #Some useful BTAG vars
    process.patJets.userData.userFunctions = cms.vstring(
    '?(tagInfoSecondaryVertex().nVertices()>0)?(tagInfoSecondaryVertex().secondaryVertex(0).p4.M):(0)',
    '?(tagInfoSecondaryVertex().nVertices()>0)?(tagInfoSecondaryVertex().secondaryVertex(0).nTracks):(0)',
    '?(tagInfoSecondaryVertex().nVertices()>0)?(tagInfoSecondaryVertex().flightDistance(0).value):(0)',
    '?(tagInfoSecondaryVertex().nVertices()>0)?(tagInfoSecondaryVertex().flightDistance(0).significance):(0)',
    '?(tagInfoSecondaryVertex().nVertices()>0)?(tagInfoSecondaryVertex().secondaryVertex(0).p4.x):(0)',
    '?(tagInfoSecondaryVertex().nVertices()>0)?(tagInfoSecondaryVertex().secondaryVertex(0).p4.y):(0)',
    '?(tagInfoSecondaryVertex().nVertices()>0)?(tagInfoSecondaryVertex().secondaryVertex(0).p4.z):(0)',
    '?(tagInfoSecondaryVertex().nVertices()>0)?(tagInfoSecondaryVertex().secondaryVertex(0).position.x):(0)',
    '?(tagInfoSecondaryVertex().nVertices()>0)?(tagInfoSecondaryVertex().secondaryVertex(0).position.y):(0)',
    '?(tagInfoSecondaryVertex().nVertices()>0)?(tagInfoSecondaryVertex().secondaryVertex(0).position.z):(0)',
    )
    process.patJets.userData.userFunctionLabels = cms.vstring('vtxMass','vtxNtracks','vtx3DVal','vtx3DSig','vtxPx','vtxPy','vtxPz','vtxPosX','vtxPosY','vtxPosZ')
    process.patJets.tagInfoSources = cms.VInputTag(cms.InputTag("secondaryVertexTagInfos"))
    process.patJets.addTagInfos = cms.bool(True)
    #
    ## PU JetID
    process.load("PhysicsTools.PatAlgos.slimming.pileupJetId_cfi")
    process.patJets.userData.userFloats.src = [ cms.InputTag("pileupJetId:fullDiscriminant"), ]

    #VID Electron IDs
    electron_ids = ['RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_CSA14_50ns_V1_cff',
                    'RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_CSA14_PU20bx25_V0_cff',
                    'RecoEgamma.ElectronIdentification.Identification.heepElectronID_HEEPV50_CSA14_25ns_cff',
                    'RecoEgamma.ElectronIdentification.Identification.heepElectronID_HEEPV50_CSA14_startup_cff']
    switchOnVIDElectronIdProducer(process)
    process.egmGsfElectronIDs.physicsObjectSrc = \
        cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.electronIDValueMapProducer.src = \
        cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.electronIDValueMapProducer.ebReducedRecHitCollection = \
        cms.InputTag("reducedEgamma","reducedEBRecHits")
    process.electronIDValueMapProducer.eeReducedRecHitCollection = \
        cms.InputTag("reducedEgamma","reducedEERecHits") 
    process.electronIDValueMapProducer.esReducedRecHitCollection = \
        cms.InputTag("reducedEgamma","reducedESRecHits")
    for idmod in electron_ids:
        setupAllVIDIdsInModule(process,idmod,setupVIDElectronSelection)
Beispiel #20
0
def applySubstructure(process, postfix=""):

    task = getPatAlgosToolsTask(process)

    from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection

    from PhysicsTools.PatAlgos.producersLayer1.jetProducer_cfi import _patJets as patJetsDefault

    # Configure the RECO jets
    from RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJetsPuppi
    from RecoJets.JetProducers.ak8PFJets_cfi import ak8PFJetsPuppi, ak8PFJetsPuppiSoftDrop, ak8PFJetsPuppiConstituents, ak8PFJetsCHSConstituents
    from RecoJets.JetProducers.ak8GenJets_cfi import ak8GenJets, ak8GenJetsSoftDrop, ak8GenJetsConstituents
    addToProcessAndTask('ak4PFJetsPuppi' + postfix, ak4PFJetsPuppi.clone(),
                        process, task)
    addToProcessAndTask('ak8PFJetsPuppi' + postfix, ak8PFJetsPuppi.clone(),
                        process, task)
    addToProcessAndTask(
        'ak8PFJetsPuppiConstituents',
        ak8PFJetsPuppiConstituents.clone(
            cut=cms.string('pt > 170.0 && abs(rapidity()) < 2.4')), process,
        task)
    addToProcessAndTask('ak8PFJetsCHSConstituents',
                        ak8PFJetsCHSConstituents.clone(), process, task)
    addToProcessAndTask(
        'ak8PFJetsPuppiSoftDrop' + postfix,
        ak8PFJetsPuppiSoftDrop.clone(
            src=cms.InputTag('ak8PFJetsPuppiConstituents', 'constituents')),
        process, task)
    addToProcessAndTask('ak8GenJetsNoNuConstituents' + postfix,
                        ak8GenJetsConstituents.clone(src='ak8GenJetsNoNu'),
                        process, task)
    addToProcessAndTask(
        'ak8GenJetsNoNuSoftDrop' + postfix,
        ak8GenJetsSoftDrop.clone(
            src=cms.InputTag('ak8GenJetsNoNuConstituents' +
                             postfix, 'constituents')), process, task)
    addToProcessAndTask(
        'slimmedGenJetsAK8SoftDropSubJets' + postfix,
        cms.EDProducer(
            "PATGenJetSlimmer",
            src=cms.InputTag("ak8GenJetsNoNuSoftDrop" + postfix, "SubJets"),
            packedGenParticles=cms.InputTag("packedGenParticles"),
            cut=cms.string(""),
            cutLoose=cms.string(""),
            nLoose=cms.uint32(0),
            clearDaughters=cms.bool(False),  #False means rekeying
            dropSpecific=cms.bool(True),  # Save space
        ),
        process,
        task)

    #add AK8 CHS
    addJetCollection(
        process,
        postfix=postfix,
        labelName='AK8',
        jetSource=cms.InputTag('ak8PFJetsCHS' + postfix),
        algo='AK',
        rParam=0.8,
        btagDiscriminators=['None'],
        jetCorrections=('AK8PFchs',
                        cms.vstring(['L1FastJet', 'L2Relative',
                                     'L3Absolute']), 'None'),
        genJetCollection=cms.InputTag('slimmedGenJetsAK8'))
    getattr(process, "patJetsAK8" + postfix).userData.userFloats.src = [
    ]  # start with empty list of user floats
    getattr(process, "selectedPatJetsAK8").cut = cms.string("pt > 170")

    ## add AK8 groomed masses with CHS
    from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSPruned, ak8PFJetsCHSSoftDrop
    addToProcessAndTask('ak8PFJetsCHSPruned' + postfix,
                        ak8PFJetsCHSPruned.clone(), process, task)
    addToProcessAndTask('ak8PFJetsCHSSoftDrop' + postfix,
                        ak8PFJetsCHSSoftDrop.clone(), process, task)
    from RecoJets.JetProducers.ak8PFJetsCHS_groomingValueMaps_cfi import ak8PFJetsCHSPrunedMass, ak8PFJetsCHSTrimmedMass, ak8PFJetsCHSFilteredMass, ak8PFJetsCHSSoftDropMass
    addToProcessAndTask('ak8PFJetsCHSPrunedMass' + postfix,
                        ak8PFJetsCHSPrunedMass.clone(), process, task)
    addToProcessAndTask('ak8PFJetsCHSTrimmedMass' + postfix,
                        ak8PFJetsCHSTrimmedMass.clone(), process, task)
    addToProcessAndTask('ak8PFJetsCHSFilteredMass' + postfix,
                        ak8PFJetsCHSFilteredMass.clone(), process, task)
    addToProcessAndTask('ak8PFJetsCHSSoftDropMass' + postfix,
                        ak8PFJetsCHSSoftDropMass.clone(), process, task)

    getattr(process, "patJetsAK8").userData.userFloats.src += [
        'ak8PFJetsCHSPrunedMass' + postfix,
        'ak8PFJetsCHSSoftDropMass' + postfix
    ]
    getattr(process, "patJetsAK8").addTagInfos = cms.bool(False)

    # add Njetiness for CHS
    process.load('RecoJets.JetProducers.nJettinessAdder_cfi')
    task.add(process.Njettiness)
    addToProcessAndTask('NjettinessAK8' + postfix, process.Njettiness.clone(),
                        process, task)
    getattr(process,
            "NjettinessAK8").src = cms.InputTag("ak8PFJetsCHS" + postfix)
    getattr(process, "NjettinessAK8").cone = cms.double(0.8)
    getattr(process, "patJetsAK8").userData.userFloats.src += [
        'NjettinessAK8' + postfix + ':tau1',
        'NjettinessAK8' + postfix + ':tau2',
        'NjettinessAK8' + postfix + ':tau3',
        'NjettinessAK8' + postfix + ':tau4'
    ]

    # add Njetiness from CHS
    addToProcessAndTask('NjettinessAK8Subjets' + postfix,
                        process.Njettiness.clone(), process, task)
    getattr(process, "NjettinessAK8Subjets" + postfix).src = cms.InputTag(
        "ak8PFJetsPuppiSoftDrop" + postfix, "SubJets")
    getattr(process, "NjettinessAK8Subjets").cone = cms.double(0.8)

    ## PATify CHS soft drop fat jets
    addJetCollection(
        process,
        postfix=postfix,
        labelName='AK8PFCHSSoftDrop',
        jetSource=cms.InputTag('ak8PFJetsCHSSoftDrop' + postfix),
        btagDiscriminators=['None'],
        jetCorrections=('AK8PFchs', ['L1FastJet', 'L2Relative',
                                     'L3Absolute'], 'None'),
        getJetMCFlavour=False  # jet flavor disabled
    )

    #add RECO AK8 from PUPPI and RECO AK8 PUPPI with soft drop... will be needed by ungroomed AK8 jets later
    ## PATify puppi soft drop fat jets
    addJetCollection(
        process,
        postfix=postfix,
        labelName='AK8PFPuppiSoftDrop' + postfix,
        jetSource=cms.InputTag('ak8PFJetsPuppiSoftDrop' + postfix),
        btagDiscriminators=['None'],
        genJetCollection=cms.InputTag('slimmedGenJetsAK8'),
        jetCorrections=('AK8PFPuppi', ['L2Relative', 'L3Absolute'], 'None'),
        getJetMCFlavour=False  # jet flavor disabled
    )
    ## PATify soft drop subjets
    addJetCollection(
        process,
        postfix=postfix,
        labelName='AK8PFPuppiSoftDropSubjets',
        jetSource=cms.InputTag('ak8PFJetsPuppiSoftDrop' + postfix, 'SubJets'),
        algo='ak',  # needed for subjet flavor clustering
        rParam=0.8,  # needed for subjet flavor clustering
        btagDiscriminators=[
            'pfDeepCSVJetTags:probb', 'pfDeepCSVJetTags:probbb',
            'pfCombinedInclusiveSecondaryVertexV2BJetTags',
            'pfCombinedMVAV2BJetTags'
        ],
        jetCorrections=('AK4PFPuppi', ['L2Relative', 'L3Absolute'], 'None'),
        explicitJTA=True,  # needed for subjet b tagging
        svClustering=True,  # needed for subjet b tagging
        genJetCollection=cms.InputTag('slimmedGenJetsAK8SoftDropSubJets'),
        fatJets=cms.InputTag(
            'ak8PFJetsPuppi'),  # needed for subjet flavor clustering
        groomedFatJets=cms.InputTag(
            'ak8PFJetsPuppiSoftDrop')  # needed for subjet flavor clustering
    )

    # add groomed ECFs and N-subjettiness to soft dropped pat::Jets for fat jets and subjets
    process.load('RecoJets.JetProducers.ECF_cff')
    addToProcessAndTask(
        'nb1AK8PuppiSoftDrop' + postfix,
        process.ecfNbeta1.clone(
            src=cms.InputTag("ak8PFJetsPuppiSoftDrop" + postfix),
            cuts=cms.vstring('', '', 'pt > 250')), process, task)
    addToProcessAndTask(
        'nb2AK8PuppiSoftDrop' + postfix,
        process.ecfNbeta2.clone(
            src=cms.InputTag("ak8PFJetsPuppiSoftDrop" + postfix),
            cuts=cms.vstring('', '', 'pt > 250')), process, task)

    #too slow now ==> disable
    from Configuration.Eras.Modifier_pp_on_AA_2018_cff import pp_on_AA_2018
    from Configuration.Eras.Modifier_pp_on_XeXe_2017_cff import pp_on_XeXe_2017
    from Configuration.Eras.Modifier_phase2_common_cff import phase2_common
    for e in [pp_on_XeXe_2017, pp_on_AA_2018, phase2_common]:
        e.toModify(getattr(process, 'nb1AK8PuppiSoftDrop' + postfix),
                   cuts=['pt > 999999', 'pt > 999999', 'pt > 999999'])
        e.toModify(getattr(process, 'nb2AK8PuppiSoftDrop' + postfix),
                   cuts=['pt > 999999', 'pt > 999999', 'pt > 999999'])

    getattr(process, "patJetsAK8PFPuppiSoftDrop").userData.userFloats.src += [
        'nb1AK8PuppiSoftDrop' + postfix + ':ecfN2',
        'nb1AK8PuppiSoftDrop' + postfix + ':ecfN3'
    ]
    getattr(process, "patJetsAK8PFPuppiSoftDrop").userData.userFloats.src += [
        'nb2AK8PuppiSoftDrop' + postfix + ':ecfN2',
        'nb2AK8PuppiSoftDrop' + postfix + ':ecfN3'
    ]
    addToProcessAndTask(
        'nb1AK8PuppiSoftDropSubjets' + postfix,
        process.ecfNbeta1.clone(
            src=cms.InputTag("ak8PFJetsPuppiSoftDrop" + postfix, "SubJets")),
        process, task)
    addToProcessAndTask(
        'nb2AK8PuppiSoftDropSubjets' + postfix,
        process.ecfNbeta2.clone(
            src=cms.InputTag("ak8PFJetsPuppiSoftDrop" + postfix, "SubJets")),
        process, task)
    getattr(process, "patJetsAK8PFPuppiSoftDropSubjets" +
            postfix).userData.userFloats.src += [
                'nb1AK8PuppiSoftDropSubjets' + postfix + ':ecfN2',
                'nb1AK8PuppiSoftDropSubjets' + postfix + ':ecfN3'
            ]
    getattr(process, "patJetsAK8PFPuppiSoftDropSubjets" +
            postfix).userData.userFloats.src += [
                'nb2AK8PuppiSoftDropSubjets' + postfix + ':ecfN2',
                'nb2AK8PuppiSoftDropSubjets' + postfix + ':ecfN3'
            ]
    getattr(process, "patJetsAK8PFPuppiSoftDropSubjets" +
            postfix).userData.userFloats.src += [
                'NjettinessAK8Subjets' + postfix + ':tau1',
                'NjettinessAK8Subjets' + postfix + ':tau2',
                'NjettinessAK8Subjets' + postfix + ':tau3',
                'NjettinessAK8Subjets' + postfix + ':tau4'
            ]

    for e in [pp_on_XeXe_2017, pp_on_AA_2018, phase2_common]:
        e.toModify(getattr(process, 'nb1AK8PuppiSoftDropSubjets' + postfix),
                   cuts=['pt > 999999', 'pt > 999999', 'pt > 999999'])
        e.toModify(getattr(process, 'nb2AK8PuppiSoftDropSubjets' + postfix),
                   cuts=['pt > 999999', 'pt > 999999', 'pt > 999999'])

    # rekey the groomed ECF value maps to the ungroomed reco jets, which will then be picked
    # up by PAT in the user floats.
    addToProcessAndTask(
        "ak8PFJetsPuppiSoftDropValueMap" + postfix,
        cms.EDProducer(
            "RecoJetToPatJetDeltaRValueMapProducer",
            src=cms.InputTag("ak8PFJetsPuppi" + postfix),
            matched=cms.InputTag("patJetsAK8PFPuppiSoftDrop" + postfix),
            distMax=cms.double(0.8),
            values=cms.vstring([
                'userFloat("nb1AK8PuppiSoftDrop' + postfix + ':ecfN2")',
                'userFloat("nb1AK8PuppiSoftDrop' + postfix + ':ecfN3")',
                'userFloat("nb2AK8PuppiSoftDrop' + postfix + ':ecfN2")',
                'userFloat("nb2AK8PuppiSoftDrop' + postfix + ':ecfN3")',
            ]),
            valueLabels=cms.vstring([
                'nb1AK8PuppiSoftDropN2',
                'nb1AK8PuppiSoftDropN3',
                'nb2AK8PuppiSoftDropN2',
                'nb2AK8PuppiSoftDropN3',
            ])), process, task)

    # Patify AK8 PF PUPPI
    addJetCollection(process,
                     postfix=postfix,
                     labelName='AK8Puppi',
                     jetSource=cms.InputTag('ak8PFJetsPuppi' + postfix),
                     algo='AK',
                     rParam=0.8,
                     jetCorrections=('AK8PFPuppi',
                                     cms.vstring(['L2Relative',
                                                  'L3Absolute']), 'None'),
                     btagDiscriminators=([
                         'pfCombinedSecondaryVertexV2BJetTags',
                         'pfCombinedInclusiveSecondaryVertexV2BJetTags',
                         'pfCombinedMVAV2BJetTags', 'pfDeepCSVJetTags:probb',
                         'pfDeepCSVJetTags:probc', 'pfDeepCSVJetTags:probudsg',
                         'pfDeepCSVJetTags:probbb',
                         'pfBoostedDoubleSecondaryVertexAK8BJetTags'
                     ]),
                     genJetCollection=cms.InputTag('slimmedGenJetsAK8'))
    getattr(process, "patJetsAK8Puppi" + postfix).userData.userFloats.src = [
    ]  # start with empty list of user floats
    getattr(process,
            "selectedPatJetsAK8Puppi" + postfix).cut = cms.string("pt > 100")
    getattr(process, "selectedPatJetsAK8Puppi" +
            postfix).cutLoose = cms.string("pt > 30")
    getattr(process,
            "selectedPatJetsAK8Puppi" + postfix).nLoose = cms.uint32(3)

    from RecoJets.JetAssociationProducers.j2tParametersVX_cfi import j2tParametersVX
    addToProcessAndTask(
        'ak8PFJetsPuppiTracksAssociatorAtVertex' + postfix,
        cms.EDProducer("JetTracksAssociatorAtVertex",
                       j2tParametersVX.clone(coneSize=cms.double(0.8)),
                       jets=cms.InputTag("ak8PFJetsPuppi")), process, task)
    addToProcessAndTask(
        'patJetAK8PuppiCharge' + postfix,
        cms.EDProducer(
            "JetChargeProducer",
            src=cms.InputTag("ak8PFJetsPuppiTracksAssociatorAtVertex"),
            var=cms.string('Pt'),
            exp=cms.double(1.0)), process, task)

    ## now add AK8 groomed masses and ECF
    from RecoJets.JetProducers.ak8PFJetsPuppi_groomingValueMaps_cfi import ak8PFJetsPuppiSoftDropMass
    addToProcessAndTask('ak8PFJetsPuppiSoftDropMass' + postfix,
                        ak8PFJetsPuppiSoftDropMass.clone(), process, task)
    getattr(process, "patJetsAK8Puppi" + postfix).userData.userFloats.src += [
        'ak8PFJetsPuppiSoftDropMass' + postfix
    ]
    getattr(process, "patJetsAK8Puppi" + postfix).addTagInfos = cms.bool(False)
    getattr(process, "patJetsAK8Puppi" + postfix).userData.userFloats.src += [
        cms.InputTag('ak8PFJetsPuppiSoftDropValueMap' + postfix,
                     'nb1AK8PuppiSoftDropN2'),
        cms.InputTag('ak8PFJetsPuppiSoftDropValueMap' + postfix,
                     'nb1AK8PuppiSoftDropN3'),
        cms.InputTag('ak8PFJetsPuppiSoftDropValueMap' + postfix,
                     'nb2AK8PuppiSoftDropN2'),
        cms.InputTag('ak8PFJetsPuppiSoftDropValueMap' + postfix,
                     'nb2AK8PuppiSoftDropN3'),
    ]

    # add PUPPI Njetiness
    addToProcessAndTask('NjettinessAK8Puppi' + postfix,
                        process.Njettiness.clone(), process, task)
    getattr(process, "NjettinessAK8Puppi" +
            postfix).src = cms.InputTag("ak8PFJetsPuppi" + postfix)
    getattr(process, "NjettinessAK8Puppi").cone = cms.double(0.8)
    getattr(process, "patJetsAK8Puppi").userData.userFloats.src += [
        'NjettinessAK8Puppi' + postfix + ':tau1',
        'NjettinessAK8Puppi' + postfix + ':tau2',
        'NjettinessAK8Puppi' + postfix + ':tau3',
        'NjettinessAK8Puppi' + postfix + ':tau4'
    ]

    # Now combine the CHS and PUPPI information into the PUPPI jets via delta R value maps
    addToProcessAndTask(
        "ak8PFJetsCHSValueMap" + postfix,
        cms.EDProducer(
            "RecoJetToPatJetDeltaRValueMapProducer",
            src=cms.InputTag("ak8PFJetsPuppi" + postfix),
            matched=cms.InputTag("patJetsAK8" + postfix),
            distMax=cms.double(0.8),
            values=cms.vstring([
                'userFloat("ak8PFJetsCHSPrunedMass"' + postfix + ')',
                'userFloat("ak8PFJetsCHSSoftDropMass"' + postfix + ')',
                'userFloat("NjettinessAK8' + postfix + ':tau1")',
                'userFloat("NjettinessAK8' + postfix + ':tau2")',
                'userFloat("NjettinessAK8' + postfix + ':tau3")',
                'userFloat("NjettinessAK8' + postfix + ':tau4")', 'pt', 'eta',
                'phi', 'mass', 'jetArea', 'jecFactor(0)'
            ]),
            valueLabels=cms.vstring([
                'ak8PFJetsCHSPrunedMass', 'ak8PFJetsCHSSoftDropMass',
                'NjettinessAK8CHSTau1', 'NjettinessAK8CHSTau2',
                'NjettinessAK8CHSTau3', 'NjettinessAK8CHSTau4', 'pt', 'eta',
                'phi', 'mass', 'jetArea', 'rawFactor'
            ])), process, task)

    # Now set up the user floats
    getattr(process, "patJetsAK8Puppi" + postfix).userData.userFloats.src += [
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix,
                     'ak8PFJetsCHSPrunedMass'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix,
                     'ak8PFJetsCHSSoftDropMass'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix, 'NjettinessAK8CHSTau1'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix, 'NjettinessAK8CHSTau2'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix, 'NjettinessAK8CHSTau3'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix, 'NjettinessAK8CHSTau4'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix, 'pt'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix, 'eta'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix, 'phi'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix, 'mass'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix, 'jetArea'),
        cms.InputTag('ak8PFJetsCHSValueMap' + postfix, 'rawFactor'),
    ]

    addToProcessAndTask(
        "slimmedJetsAK8PFPuppiSoftDropSubjets" + postfix,
        cms.EDProducer(
            "PATJetSlimmer",
            src=cms.InputTag("selectedPatJetsAK8PFPuppiSoftDropSubjets"),
            packedPFCandidates=cms.InputTag("packedPFCandidates"),
            dropJetVars=cms.string("1"),
            dropDaughters=cms.string("0"),
            rekeyDaughters=cms.string("1"),
            dropTrackRefs=cms.string("1"),
            dropSpecific=cms.string("1"),
            dropTagInfos=cms.string("1"),
            modifyJets=cms.bool(True),
            mixedDaughters=cms.bool(False),
            modifierConfig=cms.PSet(modifications=cms.VPSet())), process, task)

    ## Establish references between PATified fat jets and subjets using the BoostedJetMerger
    addToProcessAndTask(
        "slimmedJetsAK8PFPuppiSoftDropPacked" + postfix,
        cms.EDProducer(
            "BoostedJetMerger",
            jetSrc=cms.InputTag("selectedPatJetsAK8PFPuppiSoftDrop"),
            subjetSrc=cms.InputTag("slimmedJetsAK8PFPuppiSoftDropSubjets")),
        process, task)

    addToProcessAndTask(
        "packedPatJetsAK8" + postfix,
        cms.EDProducer(
            "JetSubstructurePacker",
            jetSrc=cms.InputTag("selectedPatJetsAK8Puppi" + postfix),
            distMax=cms.double(0.8),
            algoTags=cms.VInputTag(
                cms.InputTag("slimmedJetsAK8PFPuppiSoftDropPacked" + postfix)),
            algoLabels=cms.vstring('SoftDropPuppi'),
            fixDaughters=cms.bool(True),
            packedPFCandidates=cms.InputTag("packedPFCandidates" + postfix),
        ), process, task)

    # switch off daughter re-keying since it's done in the JetSubstructurePacker (and can't be done afterwards)
    process.slimmedJetsAK8.rekeyDaughters = "0"
    # Reconfigure the slimmedAK8 jet information to keep
    process.slimmedJetsAK8.dropDaughters = cms.string("pt < 170")
    process.slimmedJetsAK8.dropSpecific = cms.string("pt < 170")
    process.slimmedJetsAK8.dropTagInfos = cms.string("pt < 170")
Beispiel #21
0
)
# ---------------------------------------------------------

####### Redo Jet clustering sequence ##########

from RecoJets.Configuration.RecoPFJets_cff import ak4PFJetsCHS, ak8PFJetsCHS, ak8PFJetsCHSPruned, ak8PFJetsCHSSoftDrop, ak8PFJetsCHSPrunedMass, ak8PFJetsCHSSoftDropMass# , ak8PFJetsCSTrimmed, ak8PFJetsCSFiltered, ak8PFJetsCHSFilteredMass, ak8PFJetsCHSTrimmedMass

from CommonTools.PileupAlgos.Puppi_cff import puppi

process.puppi = puppi.clone()
process.puppi.useExistingWeights = True
process.puppi.candName = cms.InputTag('packedPFCandidates')
process.puppi.vertexName = cms.InputTag('offlineSlimmedPrimaryVertices')

process.ak8PFJetsCHS = ak8PFJetsCHS.clone( src = 'puppi', jetPtMin = 100.0 )
process.ak8PFJetsCHSPruned = ak8PFJetsCHSPruned.clone( src = 'puppi', jetPtMin = 100.0 )
process.ak8PFJetsCHSPrunedMass = ak8PFJetsCHSPrunedMass.clone()
process.ak8PFJetsCHSSoftDrop = ak8PFJetsCHSSoftDrop.clone( src = 'puppi', jetPtMin = 100.0 )
process.ak8PFJetsCHSSoftDropMass = ak8PFJetsCHSSoftDropMass.clone()


process.NjettinessAK8 = cms.EDProducer("NjettinessAdder",
                   src = cms.InputTag("ak8PFJetsCHS"),
                   Njets = cms.vuint32(1, 2, 3, 4),
                   # variables for measure definition : 
                   measureDefinition = cms.uint32( 0 ), # CMS default is normalized measure
                   beta = cms.double(1.0),          # CMS default is 1
                   R0 = cms.double( 0.8 ),          # CMS default is jet cone size
                   Rcutoff = cms.double( 999.0),       # not used by default
                   # variables for axes definition :
                   axesDefinition = cms.uint32( 6 ),    # CMS default is 1-pass KT axes
Beispiel #22
0
def miniAOD_customizeCommon(process):
    process.patMuons.isoDeposits = cms.PSet()
    process.patElectrons.isoDeposits = cms.PSet()
    process.patTaus.isoDeposits = cms.PSet()
    process.patPhotons.isoDeposits = cms.PSet()
    #
    process.patMuons.embedTrack         = True  # used for IDs
    process.patMuons.embedCombinedMuon  = True  # used for IDs
    process.patMuons.embedMuonBestTrack = True  # used for IDs
    process.patMuons.embedStandAloneMuon = True # maybe?
    process.patMuons.embedPickyMuon = False   # no, use best track
    process.patMuons.embedTpfmsMuon = False   # no, use best track
    process.patMuons.embedDytMuon   = False   # no, use best track
    #
    # disable embedding of electron and photon associated objects already stored by the ReducedEGProducer
    process.patElectrons.embedGsfElectronCore = False  ## process.patElectrons.embed in AOD externally stored gsf electron core
    process.patElectrons.embedSuperCluster    = False  ## process.patElectrons.embed in AOD externally stored supercluster
    process.patElectrons.embedPflowSuperCluster         = False  ## process.patElectrons.embed in AOD externally stored supercluster
    process.patElectrons.embedSeedCluster               = False  ## process.patElectrons.embed in AOD externally stored the electron's seedcluster 
    process.patElectrons.embedBasicClusters             = False  ## process.patElectrons.embed in AOD externally stored the electron's basic clusters 
    process.patElectrons.embedPreshowerClusters         = False  ## process.patElectrons.embed in AOD externally stored the electron's preshower clusters 
    process.patElectrons.embedPflowBasicClusters        = False  ## process.patElectrons.embed in AOD externally stored the electron's pflow basic clusters 
    process.patElectrons.embedPflowPreshowerClusters    = False  ## process.patElectrons.embed in AOD externally stored the electron's pflow preshower clusters 
    process.patElectrons.embedRecHits         = False  ## process.patElectrons.embed in AOD externally stored the RecHits - can be called from the PATElectronProducer 
    process.patElectrons.electronSource = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.patElectrons.electronIDSources = cms.PSet(
            # configure many IDs as InputTag <someName> = <someTag> you
            # can comment out those you don't want to save some disk space
            eidRobustLoose      = cms.InputTag("reducedEgamma","eidRobustLoose"),
            eidRobustTight      = cms.InputTag("reducedEgamma","eidRobustTight"),
            eidLoose            = cms.InputTag("reducedEgamma","eidLoose"),
            eidTight            = cms.InputTag("reducedEgamma","eidTight"),
            eidRobustHighEnergy = cms.InputTag("reducedEgamma","eidRobustHighEnergy"),
        )
    process.elPFIsoDepositCharged.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositChargedAll.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositNeutral.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositGamma.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    process.elPFIsoDepositPU.src = cms.InputTag("reducedEgamma","reducedGedGsfElectrons")
    #
    process.patPhotons.embedSuperCluster = False ## whether to process.patPhotons.embed in AOD externally stored supercluster
    process.patPhotons.embedSeedCluster               = False  ## process.patPhotons.embed in AOD externally stored the photon's seedcluster 
    process.patPhotons.embedBasicClusters             = False  ## process.patPhotons.embed in AOD externally stored the photon's basic clusters 
    process.patPhotons.embedPreshowerClusters         = False  ## process.patPhotons.embed in AOD externally stored the photon's preshower clusters 
    process.patPhotons.embedRecHits         = False  ## process.patPhotons.embed in AOD externally stored the RecHits - can be called from the PATPhotonProducer 
    process.patPhotons.photonSource = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.patPhotons.photonIDSources = cms.PSet(
                PhotonCutBasedIDLoose = cms.InputTag('reducedEgamma',
                                                      'PhotonCutBasedIDLoose'),
                PhotonCutBasedIDTight = cms.InputTag('reducedEgamma',
                                                      'PhotonCutBasedIDTight')
              )

    process.phPFIsoDepositCharged.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositChargedAll.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositNeutral.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositGamma.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    process.phPFIsoDepositPU.src = cms.InputTag("reducedEgamma","reducedGedPhotons")
    #
    process.selectedPatJets.cut = cms.string("pt > 10")
    process.selectedPatMuons.cut = cms.string("pt > 5 || isPFMuon || (pt > 3 && (isGlobalMuon || isStandAloneMuon || numberOfMatches > 0 || muonID('RPCMuLoose')))") 
    process.selectedPatElectrons.cut = cms.string("") 
    process.selectedPatTaus.cut = cms.string("pt > 18. && tauID('decayModeFinding')> 0.5")
    process.selectedPatPhotons.cut = cms.string("")
    #
    from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection
    #switch to AK4 (though it should soon be unnecessary as ak4 should become the 71X default)
    #FIXME: still using AK5PFchs for jet energy corrections, while waiting for a new globalTag
    switchJetCollection(process, jetSource = cms.InputTag('ak4PFJetsCHS'),  
    jetCorrections = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), ''),
    btagDiscriminators = ['jetBProbabilityBJetTags', 'jetProbabilityBJetTags', 'trackCountingHighPurBJetTags', 'trackCountingHighEffBJetTags', 'simpleSecondaryVertexHighEffBJetTags',
                         'simpleSecondaryVertexHighPurBJetTags', 'combinedSecondaryVertexBJetTags' , 'combinedInclusiveSecondaryVertexBJetTags' ],
    )
    #add CA8   
    from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection
    addJetCollection(process, labelName = 'AK8', jetSource = cms.InputTag('ak8PFJetsCHS'),algo= 'AK', rParam = 0.8, jetCorrections = ('AK7PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None') )
    process.patJetsAK8.userData.userFloats.src = [] # start with empty list of user floats
    process.selectedPatJetsAK8.cut = cms.string("pt > 100")
    process.patJetGenJetMatchAK8.matched =  'slimmedGenJets'
    ## AK8 groomed masses
    from RecoJets.Configuration.RecoPFJets_cff import ak8PFJetsCHSPruned, ak8PFJetsCHSFiltered, ak8PFJetsCHSTrimmed 
    process.ak8PFJetsCHSPruned   = ak8PFJetsCHSPruned.clone()
    process.ak8PFJetsCHSTrimmed  = ak8PFJetsCHSTrimmed.clone()
    process.ak8PFJetsCHSFiltered = ak8PFJetsCHSFiltered.clone()
    process.load("RecoJets.JetProducers.ak8PFJetsCHS_groomingValueMaps_cfi")
    process.patJetsAK8.userData.userFloats.src += ['ak8PFJetsCHSPrunedLinks','ak8PFJetsCHSTrimmedLinks','ak8PFJetsCHSFilteredLinks']
    ### CA8 groomed masses (for the matched jet): doesn't seem to work, it produces tons of warnings "Matched jets separated by dR greater than distMax=0.8"
    # from RecoJets.Configuration.RecoPFJets_cff import ca8PFJetsCHSFiltered, ca8PFJetsCHSTrimmed # ca8PFJetsCHSPruned is already in AOD
    # process.ca8PFJetsCHSTrimmed  = ca8PFJetsCHSTrimmed.clone()
    # process.ca8PFJetsCHSFiltered = ca8PFJetsCHSFiltered.clone()
    # process.load("RecoJets.JetProducers.ca8PFJetsCHS_groomingValueMaps_cfi")
    # process.ca8PFJetsCHSPrunedLinks.src   = cms.InputTag("ak8PFJetsCHS")
    # process.ca8PFJetsCHSTrimmedLinks.src  = cms.InputTag("ak8PFJetsCHS")
    # process.ca8PFJetsCHSFilteredLinks.src = cms.InputTag("ak8PFJetsCHS")
    # process.patJetsAK8.userData.userFloats.src += ['ca8PFJetsCHSPrunedLinks','ca8PFJetsCHSTrimmedLinks','ca8PFJetsCHSFilteredLinks']
    ## cmsTopTagger (note: it is already run in RECO, we just add the value)
    process.cmsTopTagPFJetsCHSLinksAK8 = process.ak8PFJetsCHSPrunedLinks.clone()
    process.cmsTopTagPFJetsCHSLinksAK8.src = cms.InputTag("ak8PFJetsCHS")
    process.cmsTopTagPFJetsCHSLinksAK8.matched = cms.InputTag("cmsTopTagPFJetsCHS")
    process.patJetsAK8.userData.userFloats.src += ['cmsTopTagPFJetsCHSLinksAK8']

    #
    from PhysicsTools.PatAlgos.tools.trigTools import switchOnTriggerStandAlone
    switchOnTriggerStandAlone( process, outputModule = '' )
    process.patTrigger.packTriggerPathNames = cms.bool(True)
    #
    # apply type I/type I + II PFMEt corrections to pat::MET object
    # and estimate systematic uncertainties on MET
    # FIXME: this and the typeI MET should become AK4 once we have the proper JEC?
    from PhysicsTools.PatUtils.tools.runType1PFMEtUncertainties import runType1PFMEtUncertainties
    addJetCollection(process, postfix   = "ForMetUnc", labelName = 'AK4PF', jetSource = cms.InputTag('ak4PFJets'), jetCorrections = ('AK4PF', ['L1FastJet', 'L2Relative', 'L3Absolute'], ''))
    process.patJetsAK4PFForMetUnc.getJetMCFlavour = False
    runType1PFMEtUncertainties(process,
                               addToPatDefaultSequence=False,
                               jetCollection="selectedPatJetsAK4PFForMetUnc",
                               electronCollection="selectedPatElectrons",
                               muonCollection="selectedPatMuons",
                               tauCollection="selectedPatTaus",
                               makeType1p2corrPFMEt=True,
                               outputModule=None)
 

    #keep this after all addJetCollections otherwise it will attempt computing them also for stuf with no taginfos
    #Some useful BTAG vars
    process.patJets.userData.userFunctions = cms.vstring(
    '?(tagInfoSecondaryVertex().nVertices()>0)?(tagInfoSecondaryVertex().secondaryVertex(0).p4.M):(0)',
    '?(tagInfoSecondaryVertex().nVertices()>0)?(tagInfoSecondaryVertex().secondaryVertex(0).nTracks):(0)',
    '?(tagInfoSecondaryVertex().nVertices()>0)?(tagInfoSecondaryVertex().flightDistance(0).value):(0)',
    '?(tagInfoSecondaryVertex().nVertices()>0)?(tagInfoSecondaryVertex().flightDistance(0).significance):(0)',
    )
    process.patJets.userData.userFunctionLabels = cms.vstring('vtxMass','vtxNtracks','vtx3DVal','vtx3DSig')
    process.patJets.tagInfoSources = cms.VInputTag(cms.InputTag("secondaryVertexTagInfos"))
    process.patJets.addTagInfos = cms.bool(True)
    #
    ## PU JetID
    process.load("PhysicsTools.PatAlgos.slimming.pileupJetId_cfi")
    process.patJets.userData.userFloats.src = [ cms.InputTag("pileupJetId:fullDiscriminant"), ]