Beispiel #1
0
    def toolCode(self, process):
        jetCollection=self._parameters['jetCollection'].value
        doJTA=self._parameters['doJTA'].value
        doBTagging=self._parameters['doBTagging'].value
        jetCorrLabel=self._parameters['jetCorrLabel'].value
        doType1MET =self._parameters['doType1MET'].value
        genJetCollection=self._parameters['genJetCollection'].value
        doJetID=self._parameters['doJetID'].value
        jetIdLabel=self._parameters['jetIdLabel'].value


        ## save label of old input jet collection
        oldLabel = process.patJets.jetSource;
    
        ## replace input jet collection for generator matches
        process.patJetPartonMatch.src        = jetCollection
        process.patJetGenJetMatch.src        = jetCollection
        process.patJetGenJetMatch.matched    = genJetCollection
        process.patJetPartonAssociation.jets = jetCollection
        ## replace input jet collection for pat jet production
        process.patJets.jetSource         = jetCollection
    
        ## make VInputTag from strings
        def vit(*args) : return cms.VInputTag( *[ cms.InputTag(x) for x in args ] )

        if (doJTA or doBTagging):
            ## replace jet track association
            process.load("RecoJets.JetAssociationProducers.ak5JTA_cff")
            from RecoJets.JetAssociationProducers.ak5JTA_cff import ak5JetTracksAssociatorAtVertex
            process.jetTracksAssociatorAtVertex = ak5JetTracksAssociatorAtVertex.clone(jets = jetCollection)
            process.makePatJets.replace(process.patJetCharge, process.jetTracksAssociatorAtVertex+process.patJetCharge)
            process.patJetCharge.src = 'jetTracksAssociatorAtVertex'
            process.patJets.trackAssociationSource = 'jetTracksAssociatorAtVertex'
        else:
            ## remove the jet track association from the std
            ## sequence
            process.makePatJets.remove(process.patJetCharge)
            ## switch embedding of track association and jet
            ## charge estimate to 'False'
            process.patJets.addAssociatedTracks = False
            process.patJets.addJetCharge = False

        if (doBTagging):
            ## replace b tagging sequence; add postfix label 'AOD' as crab will
            ## crash when confronted with empy labels
            (btagSeq, btagLabels) = runBTagging(process, jetCollection, 'AOD')
            ## add b tagging sequence before running the allLayer1Jets modules
            process.makePatJets.replace(process.jetTracksAssociatorAtVertex, process.jetTracksAssociatorAtVertex+btagSeq)

            ## replace corresponding tags for pat jet production
            process.patJets.trackAssociationSource = btagLabels['jta']
            process.patJets.tagInfoSources = cms.VInputTag( *[ cms.InputTag(x) for x in btagLabels['tagInfos'] ] )
            process.patJets.discriminatorSources = cms.VInputTag( *[ cms.InputTag(x) for x in btagLabels['jetTags']  ] )
        else:
            ## remove b tagging from the std sequence
            process.makePatJets.remove(process.secondaryVertexNegativeTagInfos)
            process.makePatJets.remove(process.simpleSecondaryVertexNegativeBJetTags)
            ## switch embedding of b tagging for pat
            ## jet production to 'False'
            process.patJets.addBTagInfo = False

        if (doJetID):
            jetIdLabelNew = jetIdLabel + 'JetID'
            process.patJets.jetIDMap = cms.InputTag( jetIdLabelNew )
        else:
            process.patJets.addJetID = cms.bool(False)

            
        if (jetCorrLabel!=None):
            ## replace jet energy corrections; catch
            ## a couple of exceptions first
            if (jetCorrLabel == False ):
                raise ValueError, "In switchJetCollection 'jetCorrLabel' must be set to 'None', not 'False'"
            if (jetCorrLabel == "None"):
                raise ValueError, "In switchJetCollection 'jetCorrLabel' must be set to 'None' (without quotes)"
            ## check for the correct format
            if (type(jetCorrLabel)!=type(('AK5','Calo'))): 
                raise ValueError, "In switchJetCollection 'jetCorrLabel' must be 'None', or of type ('Algo','Type')"

            ## switch JEC parameters to the new jet collection
            process.patJetCorrFactors.jetSource = jetCollection            
            switchJECParameters(process.patJetCorrFactors, jetCorrLabel[0], jetCorrLabel[1], oldAlgo='AK5',oldType='Calo')

            ## switch type1MET corrections off for PFJets
            if( jetCollection.__str__().find('PFJets')>=0 ):
                print '================================================='
                print 'Type1MET corrections are switched off for PFJets.'
                print 'Users are recommened to use pfMET together with'
                print 'PFJets.'
                print '================================================='            
                doType1MET=False

            ## redo the type1MET correction for the new jet collection
            if (doType1MET):
                ## in case there is no jet correction service in the paths add it
                ## as L2L3 if possible, as combined from L2 and L3 otherwise
                if (not hasattr( process, 'L2L3JetCorrector%s%s' % jetCorrLabel )):
                    setattr( process, 
                             'L2L3JetCorrector%s%s' % jetCorrLabel, 
                             cms.ESSource("JetCorrectionServiceChain",
                                          correctors = cms.vstring('L2RelativeJetCorrector%s%s' % jetCorrLabel,
                                                                   'L3AbsoluteJetCorrector%s%s' % jetCorrLabel),
                                          label = cms.string('L2L3JetCorrector%s%s' % jetCorrLabel)
                                          )
                             )
                ## configure the type1MET correction the following muonMET
                ## corrections have the corMetType1Icone5 as input and are
                ## automatically correct  
                process.metJESCorAK5CaloJet.inputUncorJetsLabel = jetCollection.value()
                process.metJESCorAK5CaloJet.corrector = 'L2L3JetCorrector%s%s' % jetCorrLabel
        else:
            ## remove the jetCorrFactors from the std sequence
            process.patJetMETCorrections.remove(process.jetCorrFactors)
            ## switch embedding of jetCorrFactors off
            ## for pat jet production
            process.patJets.addJetCorrFactors = False
Beispiel #2
0
    def toolCode(self, process):
        """
        Tool code implementation
        """
        ## initialize parameters
        labelName = "patJets" + self._parameters["labelName"].value
        postfix = self._parameters["postfix"].value
        jetSource = self._parameters["jetSource"].value
        algo = self._parameters["algo"].value
        jetCorrections = self._parameters["jetCorrections"].value
        btagDiscriminators = list(self._parameters["btagDiscriminators"].value)
        btagInfos = list(self._parameters["btagInfos"].value)
        jetTrackAssociation = self._parameters["jetTrackAssociation"].value
        outputModules = list(self._parameters["outputModules"].value)

        ## a list of all producer modules, which are already known to process
        knownModules = process.producerNames().split()
        ## determine whether btagging information is required or not
        if btagDiscriminators.count("None") > 0:
            btagDiscriminators.remove("None")
        if btagInfos.count("None") > 0:
            btagInfos.remove("None")
        bTagging = len(btagDiscriminators) > 0 or len(btagInfos) > 0
        ## construct postfix label for auxiliary modules; this postfix
        ## label will start with a capitalized first letter following
        ## the CMS nameing conventions and for improved readablility
        _labelName = labelName[:1].upper() + labelName[1:]
        # _labelName=labelName
        ## determine jet algorithm from jetSource; supported algo types
        ## are ak, kt, sc, ic. This loop expects that the algo type is
        ## followed by a single integer corresponding to the opening
        ## angle parameter dR times 10 (examples ak5, kt4, kt6, ...)
        _algo = algo
        # jetSource=cms.InputTag("ak5PFJets")
        for x in ["ak", "kt", "sc", "ic"]:
            if jetSource.getModuleLabel().lower().find(x) > -1:
                _algo = jetSource.getModuleLabel()[
                    jetSource.getModuleLabel().lower().find(x) : jetSource.getModuleLabel().lower().find(x) + 3
                ]
        # print _algo
        ## add new patJets to process (keep instance for later further modifications)
        from PhysicsTools.PatAlgos.producersLayer1.jetProducer_cfi import patJets

        if labelName in knownModules:
            _newPatJets = getattr(process, labelName + postfix)
            _newPatJets.jetSource = jetSource
        else:
            # setattr(process, labelName, patJets.clone(jetSource=jetSource))
            setattr(process, labelName + postfix, patJets.clone(jetSource=jetSource))
            _newPatJets = getattr(process, labelName + postfix)
            knownModules.append(labelName + postfix)
        ## add new selectedPatJets to process
        from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets

        if "selected" + _labelName + postfix in knownModules:
            _newSelectedPatJets = getattr(process, "selected" + _labelName + postfix)
            _newSelectedPatJets.src = labelName + postfix
        else:
            setattr(process, "selected" + _labelName + postfix, selectedPatJets.clone(src=labelName + postfix))
            knownModules.append("selected" + _labelName + postfix)

        ## set postfix label to '' if there is no labelName given. In this case all
        ## modules should keep there names w/o postfixes. This will cover the case
        ## of switchJectCollection
        if self._parameters["labelName"].value == "":
            _labelName = ""

        ## add new patJetPartonMatch to process
        from PhysicsTools.PatAlgos.mcMatchLayer0.jetMatch_cfi import patJetPartonMatch

        if "patJetPartonMatch" + _labelName + postfix in knownModules:
            _newPatJetPartonMatch = getattr(process, "patJetPartonMatch" + _labelName + postfix)
            _newPatJetPartonMatch.src = jetSource
        else:
            setattr(process, "patJetPartonMatch" + _labelName + postfix, patJetPartonMatch.clone(src=jetSource))
            knownModules.append("patJetPartonMatch" + _labelName + postfix)
        ## add new patJetGenJetMatch to process
        from PhysicsTools.PatAlgos.mcMatchLayer0.jetMatch_cfi import patJetGenJetMatch

        if "patJetGenJetMatch" + _labelName + postfix in knownModules:
            _newPatJetGenJetMatch = getattr(process, "patJetGenJetMatch" + _labelName + postfix)
            _newPatJetGenJetMatch.src = jetSource
            _newPatJetGenJetMatch.matched = _algo.lower() + "GenJets" + postfix
        else:
            setattr(
                process,
                "patJetGenJetMatch" + _labelName + postfix,
                patJetGenJetMatch.clone(src=jetSource, matched=_algo + "GenJets"),
            )
            knownModules.append("patJetGenJetMatch" + _labelName + postfix)
        ## add new patJetPartonAssociation to process
        from PhysicsTools.PatAlgos.mcMatchLayer0.jetFlavourId_cff import patJetPartonAssociation

        if "patJetPartonAssociation" + _labelName + postfix in knownModules:
            _newPatJetPartonAssociation = getattr(
                process, "patJetPartonAssociation" + _labelName + postfix, patJetPartonAssociation.clone(jets=jetSource)
            )
            _newPatJetPartonAssociation.jets = jetSource
        else:
            setattr(
                process, "patJetPartonAssociation" + _labelName + postfix, patJetPartonAssociation.clone(jets=jetSource)
            )
            knownModules.append("patJetPartonAssociation" + _labelName + postfix)
        ## add new patJetPartonAssociation to process
        from PhysicsTools.PatAlgos.mcMatchLayer0.jetFlavourId_cff import patJetFlavourAssociation

        if "patJetFlavourAssociation" + _labelName + postfix in knownModules:
            _newPatJetFlavourAssociation = getattr(
                process,
                "patJetFlavourAssociation" + _labelName + postfix,
                patJetFlavourAssociation.clone(srcByReference="patJetPartonAssociation" + _labelName + postfix),
            )
            _newPatJetFlavourAssociation.srcByReference = "patJetPartonAssociation" + _labelName + postfix
        else:
            setattr(
                process,
                "patJetFlavourAssociation" + _labelName + postfix,
                patJetFlavourAssociation.clone(srcByReference="patJetPartonAssociation" + _labelName + postfix),
            )
            knownModules.append("patJetFlavourAssociation" + _labelName + postfix)
        ## modify new patJets collection accordingly
        _newPatJets.genJetMatch.setModuleLabel("patJetGenJetMatch" + _labelName + postfix)
        _newPatJets.genPartonMatch.setModuleLabel("patJetPartonMatch" + _labelName + postfix)
        _newPatJets.JetPartonMapSource.setModuleLabel("patJetFlavourAssociation" + _labelName + postfix)

        ## add jetTrackAssociation for btagging (or jetTracksAssociation only) if required by user
        if jetTrackAssociation or bTagging:
            ## add new jetTracksAssociationAtVertex to process
            from RecoJets.JetAssociationProducers.ak5JTA_cff import ak5JetTracksAssociatorAtVertex

            if "jetTracksAssociationAtVertex" + _labelName + postfix in knownModules:
                _newJetTracksAssociationAtVertex = getattr(
                    process, "jetTracksAssociatorAtVertex" + _labelName + postfix
                )
                _newJetTracksAssociationAtVertex.jets = jetSource
            else:
                setattr(
                    process,
                    "jetTracksAssociatorAtVertex" + _labelName + postfix,
                    ak5JetTracksAssociatorAtVertex.clone(jets=jetSource),
                )
                knownModules.append("jetTracksAssociationAtVertex" + _labelName + postfix)
            ## add new patJetCharge to process
            from PhysicsTools.PatAlgos.recoLayer0.jetTracksCharge_cff import patJetCharge

            if "patJetCharge" + _labelName + postfix in knownModules:
                _newPatJetCharge = getattr(process, "patJetCharge" + _labelName + postfix)
                _newPatJetCharge.src = "jetTracksAssociatorAtVertex" + _labelName + postfix
            else:
                setattr(
                    process,
                    "patJetCharge" + _labelName + postfix,
                    patJetCharge.clone(src="jetTracksAssociatorAtVertex" + _labelName + postfix),
                )
                knownModules.append("patJetCharge" + _labelName + postfix)
            ## modify new patJets collection accordingly
            _newPatJets.addAssociatedTracks = True
            _newPatJets.trackAssociationSource = cms.InputTag("jetTracksAssociatorAtVertex" + _labelName + postfix)
            _newPatJets.addJetCharge = True
            _newPatJets.jetChargeSource = cms.InputTag("patJetCharge" + _labelName + postfix)
        else:
            ## modify new patJets collection accordingly
            _newPatJets.addAssociatedTracks = False
            _newPatJets.trackAssociationSource = ""
            _newPatJets.addJetCharge = False
            _newPatJets.jetChargeSource = ""
        ## run btagging if required by user
        if bTagging:
            ## expand tagInfos to what is explicitely required by user + implicit
            ## requirements that come in from one or the other discriminator
            requiredTagInfos = list(btagInfos)
            for btagDiscr in btagDiscriminators:
                for requiredTagInfo in supportedBtagDiscr[btagDiscr]:
                    tagInfoCovered = False
                    for tagInfo in requiredTagInfos:
                        if requiredTagInfo == tagInfo:
                            tagInfoCovered = True
                            break
                    if not tagInfoCovered:
                        requiredTagInfos.append(requiredTagInfo)
            ## load sequences and setups needed fro btagging
            ## This loads all available btagger, but the ones we need are added to the process by hand lader. Only needed to get the ESProducer. Needs improvement
            # loadWithPostFix(process,"RecoBTag.Configuration.RecoBTag_cff",postfix)
            process.load("RecoBTag.Configuration.RecoBTag_cff")
            # addESProducers(process,'RecoBTag.Configuration.RecoBTag_cff')
            import RecoBTag.Configuration.RecoBTag_cff as btag

            ## prepare setups for simple secondary vertex infos
            setattr(process, "simpleSecondaryVertex2Trk", simpleSecondaryVertex2Trk)
            ## prepare setups for transient tracks
            setattr(process, "TransientTrackBuilderESProducer", TransientTrackBuilderESProducer)
            ## setup all required btagInfos : we give a dedicated treatment for all five different
            ## types of tagINfos here. A common treatment is possible but might require a more
            ## general approach anyway in coordination with the btaggin POG.
            for btagInfo in requiredTagInfos:
                if "impactParameterTagInfos" in btagInfo:
                    setattr(
                        process,
                        btagInfo + _labelName + postfix,
                        btag.impactParameterTagInfos.clone(
                            jetTracks=cms.InputTag("jetTracksAssociatorAtVertex" + _labelName + postfix)
                        ),
                    )
                if "secondaryVertexTagInfos" in btagInfo:
                    setattr(
                        process,
                        btagInfo + _labelName + postfix,
                        btag.secondaryVertexTagInfos.clone(
                            trackIPTagInfos=cms.InputTag("impactParameterTagInfos" + _labelName + postfix)
                        ),
                    )
                if "secondaryVertexNegativeTagInfos" in btagInfo:
                    setattr(
                        process,
                        btagInfo + _labelName + postfix,
                        btag.secondaryVertexNegativeTagInfos.clone(
                            trackIPTagInfos=cms.InputTag("impactParameterTagInfos" + _labelName + postfix)
                        ),
                    )
                if "softElectronTagInfos" in btagInfo:
                    setattr(
                        process,
                        btagInfo + _labelName + postfix,
                        btag.softElectronTagInfos.clone(jets=cms.InputTag(_newJetCollection)),
                    )
                if "softMuonTagInfos" in btagInfo:
                    setattr(
                        process,
                        btagInfo + _labelName + postfix,
                        btag.softMuonTagInfos.clone(jets=cms.InputTag(_newJetCollection)),
                    )
            ## setup all required btagDiscriminators
            for btagDiscr in btagDiscriminators:
                setattr(
                    process,
                    btagDiscr + _labelName + postfix,
                    getattr(btag, btagDiscr).clone(
                        tagInfos=cms.VInputTag(
                            *[cms.InputTag(x + _labelName + postfix) for x in supportedBtagDiscr[btagDiscr]]
                        )
                    ),
                )
            ## replace corresponding tags for pat jet production
            _newPatJets.tagInfoSources = cms.VInputTag(*[cms.InputTag(x + _labelName + postfix) for x in btagInfos])
            _newPatJets.discriminatorSources = cms.VInputTag(
                *[cms.InputTag(x + _labelName + postfix) for x in btagDiscriminators]
            )
        else:
            _newPatJets.addBTagInfo = False
            ## adjust output module; these collections will be empty anyhow, but we do it to stay clean
            for outputModule in outputModules:
                if hasattr(process, outputModule):
                    getattr(process, outputModule).outputCommands.append(
                        "drop *_" + "selected" + _labelName + postfix + "_tagInfos_*"
                    )

        ## add jet correction factors if required by user
        if jetCorrections != None:
            ## check for the correct format
            if type(jetCorrections) != type(
                ("PAYLOAD-LABEL", ["CORRECTION-LEVEL-A", "CORRECTION-LEVEL-B"], "MET-LABEL")
            ):
                raise ValueError, "In addJetCollection: 'jetCorrections' must be 'None' (as a python value w/o quotation marks), or of type ('PAYLOAD-LABEL', ['CORRECTION-LEVEL-A', \
                'CORRECTION-LEVEL-B', ...], 'MET-LABEL'). Note that 'MET-LABEL' can be set to 'None' (as a string in quotation marks) in case you do not want to apply MET(Type1) \
                corrections."
            ## determine type of jet constituents from jetSource; supported
            ## jet constituent types are calo, pf, jpt, for pf also particleflow
            ## is aloowed as part of the jetSource label, which might be used
            ## in CommonTools.ParticleFlow
            _type = "NONE"
            if jetCorrections[0].count("PF") > 0:
                _type = "PF"
            elif jetCorrections[0].count("Calo") > 0:
                _type = "Calo"
            elif jetCorrections[0].count("JPT") > 0:
                _type = "JPT"
            else:
                raise TypeError, "In addJetCollection: Jet energy corrections are only supported for PF, JPT and Calo jets."
            from PhysicsTools.PatAlgos.recoLayer0.jetCorrFactors_cfi import patJetCorrFactors

            if "patJetCorrFactors" + _labelName + postfix in knownModules:
                _newPatJetCorrFactors = getattr(process, "patJetCorrFactors" + _labelName + postfix)
                _newPatJetCorrFactors.src = jetSource
            else:

                setattr(process, "patJetCorrFactors" + _labelName + postfix, patJetCorrFactors.clone(src=jetSource))
                _newPatJetCorrFactors = getattr(process, "patJetCorrFactors" + _labelName + postfix)
            _newPatJetCorrFactors.payload = jetCorrections[0]
            _newPatJetCorrFactors.levels = jetCorrections[1]
            ## check whether L1Offset or L1FastJet is part of levels
            error = False
            for x in jetCorrections[1]:
                if x == "L1Offset":
                    if not error:
                        _newPatJetCorrFactors.useNPV = True
                        _newPatJetCorrFactors.primaryVertices = "offlinePrimaryVertices"
                        ## we set this to True now as a L1 correction type should appear only once
                        ## otherwise levels is miss configured
                        error = True
                    else:
                        raise ValueError, "In addJetCollection: Correction levels for jet energy corrections are miss configured. An L1 correction type should appear not more than \
                        once. Check the list of correction levels you requested to be applied: ", jetCorrections[
                            1
                        ]
                if x == "L1FastJet":
                    if not error:
                        if _type == "JPT":
                            raise TypeError, "In addJetCollection: L1FastJet corrections are only supported for PF and Calo jets."
                        ## configure module
                        _newPatJetCorrFactors.useRho = True
                        _newPatJetCorrFactors.rho = cms.InputTag("kt6" + _type + "Jets", "rho")
                        ## we set this to True now as a L1 correction type should appear only once
                        ## otherwise levels is miss configured
                        error = True
                    else:
                        raise ValueError, "In addJetCollection: Correction levels for jet energy corrections are miss configured. An L1 correction type should appear not more than \
                        once. Check the list of correction levels you requested to be applied: ", jetCorrections[
                            1
                        ]
            _newPatJets.jetCorrFactorsSource = cms.VInputTag(cms.InputTag("patJetCorrFactors" + _labelName + postfix))
            ## configure MET(Type1) corrections
            if jetCorrections[2].lower() != "none" and jetCorrections[2] != "":
                if not jetCorrections[2].lower() == "type-1" and not jetCorrections[2].lower() == "type-2":
                    raise valueError, "In addJetCollection: Wrong choice of MET corrections for new jet collection. Possible choices are None (or empty string), Type-1, Type-2 (i.e.\
                    Type-1 and Type-2 corrections applied). This choice is not case sensitive. Your choice was: ", jetCorrections[
                        2
                    ]
                if _type == "JPT":
                    raise ValueError, 'In addJecCollection: MET(type1) corrections are not supported for JPTJets. Please set the MET-LABEL to "None" (as string in quatiation \
                    marks) and use raw tcMET together with JPTJets.'
                ## set up jet correctors for MET corrections
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFL1Fastjet
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFL1Offset
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFL2Relative
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFL3Absolute
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFResidual

                setattr(
                    process,
                    jetCorrections[0] + "L1FastJet",
                    ak5PFL1Fastjet.clone(
                        algorithm=jetCorrections[0], srcRho=cms.InputTag("kt6" + _type + "Jets", "rho")
                    ),
                )
                setattr(process, jetCorrections[0] + "L1Offset", ak5PFL1Offset.clone(algorithm=jetCorrections[0]))
                setattr(process, jetCorrections[0] + "L2Relative", ak5PFL2Relative.clone(algorithm=jetCorrections[0]))
                setattr(process, jetCorrections[0] + "L3Absolute", ak5PFL3Absolute.clone(algorithm=jetCorrections[0]))
                setattr(process, jetCorrections[0] + "L2L3Residual", ak5PFResidual.clone(algorithm=jetCorrections[0]))
                setattr(
                    process,
                    jetCorrections[0] + "CombinedCorrector",
                    cms.ESProducer("JetCorrectionESChain", correctors=cms.vstring()),
                )
                for x in jetCorrections[1]:
                    if (
                        x != "L1FastJet"
                        and x != "L1Offset"
                        and x != "L2Relative"
                        and x != "L3Absolute"
                        and x != "L2L3Residual"
                    ):
                        raise ValueError, "In addJetCollection: Unsupported JEC for MET(Type1). Currently supported jet correction levels are L1FastJet, L1Offset, L2Relative, \
                        L3Asolute, L2L3Residual. Requested was:", x
                    else:
                        getattr(process, jetCorrections[0] + "CombinedCorrector").correctors.append(
                            jetCorrections[0] + x
                        )

                ## set up MET(Type1) correction modules
                if _type == "Calo":
                    from JetMETCorrections.Type1MET.caloMETCorrections_cff import caloJetMETcorr
                    from JetMETCorrections.Type1MET.caloMETCorrections_cff import caloType1CorrectedMet
                    from JetMETCorrections.Type1MET.caloMETCorrections_cff import caloType1p2CorrectedMet

                    setattr(
                        process,
                        jetCorrections[0] + "JetMETcorr" + postfix,
                        caloJetMETcorr.clone(
                            src=jetSource,
                            srcMET="corMetGlobalMuons",
                            jetCorrections=cms.string(jetCorrections[0] + "CombinedCorrector" + postfix),
                        ),
                    )
                    setattr(
                        process,
                        jetCorrections[0] + "Type1CorMet" + postfix,
                        caloType1CorrectedMet.clone(
                            src="corMetGlobalMuons" + postfix,
                            srcType1Corrections=cms.VInputTag(
                                cms.InputTag(jetCorrections[0] + "JetMETcorr" + postfix, "type1")
                            ),
                        ),
                    )
                    setattr(
                        process,
                        jetCorrections[0] + "Type1p2CorMet" + postfix,
                        caloType1p2CorrectedMet.clone(
                            src="corMetGlobalMuons" + postfix,
                            srcType1Corrections=cms.VInputTag(
                                cms.InputTag(jetCorrections[0] + "JetMETcorr" + postfix, "type1")
                            ),
                            srcUnclEnergySums=cms.VInputTag(
                                cms.InputTag(jetCorrections[0] + "JetMETcorr" + postfix, "type2"),
                                cms.InputTag(jetCorrections[0] + "JetMETcorr" + postfix, "offset"),
                                cms.InputTag("muonCaloMETcorr" + postfix),
                            ),
                        ),
                    )

                elif _type == "PF":
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfCandsNotInJet
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfJetMETcorr
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfCandMETcorr
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfType1CorrectedMet
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfType1p2CorrectedMet

                    setattr(
                        process,
                        jetCorrections[0] + "CandsNotInJet" + postfix,
                        pfCandsNotInJet.clone(topCollection=jetSource),
                    )
                    setattr(
                        process,
                        jetCorrections[0] + "CandMETcorr" + postfix,
                        pfCandMETcorr.clone(src=cms.InputTag(jetCorrections[0] + "CandsNotInJet" + postfix)),
                    )
                    setattr(process, jetCorrections[0] + "JetMETcorr" + postfix, pfJetMETcorr.clone(src=jetSource))
                    setattr(
                        process,
                        jetCorrections[0] + "Type1CorMet" + postfix,
                        pfType1CorrectedMet.clone(
                            srcType1Corrections=cms.VInputTag(
                                cms.InputTag(jetCorrections[0] + "JetMETcorr" + postfix, "type1")
                            )
                        ),
                    )
                    setattr(
                        process,
                        jetCorrections[0] + "Type1p2CorMet" + postfix,
                        pfType1p2CorrectedMet.clone(
                            srcType1Corrections=cms.VInputTag(
                                cms.InputTag(jetCorrections[0] + "JetMETcorr" + postfix, "type1")
                            ),
                            srcUnclEnergySums=cms.VInputTag(
                                cms.InputTag(jetCorrections[0] + "JetMETcorr" + postfix, "type2"),
                                cms.InputTag(jetCorrections[0] + "JetMETcorr" + postfix, "offset"),
                                cms.InputTag(jetCorrections[0] + "CandMETcorr" + postfix),
                            ),
                        ),
                    )

                ## common configuration for Calo and PF
                if "L1FastJet" in jetCorrections[1] or "L1Fastjet" in jetCorrections[1]:
                    getattr(process, jetCorrections[0] + "JetMETcorr" + postfix).offsetCorrLabel = cms.string(
                        jetCorrections[0] + "L1FastJet"
                    )
                elif "L1Offset" in jetCorrections[1]:
                    getattr(process, jetCorrections[0] + "JetMETcorr" + postfix).offsetCorrLabel = cms.string(
                        jetCorrections[0] + "L1Offset"
                    )
                else:
                    getattr(process, jetCorrections[0] + "JetMETcorr" + postfix).offsetCorrLabel = cms.string("")

                from PhysicsTools.PatAlgos.producersLayer1.metProducer_cfi import patMETs

                if jetCorrections[2].lower() == "type-1":
                    setattr(
                        process,
                        "patMETs" + _labelName + postfix,
                        patMETs.clone(
                            metSource=cms.InputTag(jetCorrections[0] + "Type1CorMet" + postfix),
                            addMuonCorrections=False,
                        ),
                    )
                elif jetCorrections[2].lower() == "type-1":
                    setattr(
                        process,
                        "patMETs" + _labelName + postfix,
                        patMETs.clone(
                            metSource=cms.InputTag(jetCorrections[0] + "Type1p2CorMet" + postfix),
                            addMuonCorrections=False,
                        ),
                    )
        else:
            ## switch jetCorrFactors off
            _newPatJets.addJetCorrFactors = False
Beispiel #3
0
    def toolCode(self, process):        
        jetCollection=self._parameters['jetCollection'].value
        algoLabel=self._parameters['algoLabel'].value
        typeLabel=self._parameters['typeLabel'].value
        doJTA=self._parameters['doJTA'].value
        doBTagging=self._parameters['doBTagging'].value
        jetCorrLabel=self._parameters['jetCorrLabel'].value
        doType1MET =self._parameters['doType1MET'].value
        doL1Cleaning=self._parameters['doL1Cleaning'].value
        doL1Counters=self._parameters['doL1Counters'].value
        genJetCollection=self._parameters['genJetCollection'].value
        doJetID=self._parameters['doJetID'].value
        jetIdLabel=self._parameters['jetIdLabel'].value
        standardAlgo=self._parameters['standardAlgo'].value
        standardType=self._parameters['standardType'].value
     
        ## define common label for pre pat jet 
        ## creation steps in makePatJets    
        #label=standardAlgo+standardType

        ## create old module label from standardAlgo
        ## and standardType and return
        def oldLabel(prefix=''):        
            return jetCollectionString(prefix, '', '')

        ## create new module label from old module
        ## label and return
        def newLabel(oldLabel):
            newLabel=oldLabel
            if(oldLabel.find(standardAlgo)>=0 and oldLabel.find(standardType)>=0):
                oldLabel=oldLabel.replace(standardAlgo, algoLabel).replace(standardType, typeLabel)
            else:
                oldLabel=oldLabel+algoLabel+typeLabel
            return oldLabel

        ## clone module and add it to the patDefaultSequence
        def addClone(hook, **replaceStatements):
            ## create a clone of the hook with corresponding
            ## parameter replacements
            newModule = getattr(process, hook).clone(**replaceStatements)
            ## add the module to the sequence
            addModuleToSequence(hook, newModule)

        ## add module to the patDefaultSequence
        def addModuleToSequence(hook, newModule):
            hookModule = getattr(process, hook)
            ## add the new module with standardAlgo &
            ## standardType replaced in module label
            setattr( process, newLabel(hook), newModule)
            ## add new module to default sequence
            ## just behind the hookModule
            process.patDefaultSequence.replace( hookModule, hookModule*newModule )        

        ## add a clone of patJets
        addClone(oldLabel(), jetSource = jetCollection)
        ## add a clone of selectedPatJets    
        addClone(oldLabel('selected'), src=cms.InputTag(newLabel(oldLabel())))
        ## add a clone of cleanPatJets    
        if( doL1Cleaning ):
            addClone(oldLabel('clean'), src=cms.InputTag(newLabel(oldLabel('selected'))))
        ## add a clone of countPatJets    
        if( doL1Counters ):
            if( doL1Cleaning ):
                addClone(oldLabel('count'), src=cms.InputTag(newLabel(oldLabel('clean'))))
            else:
                addClone(oldLabel('count'), src=cms.InputTag(newLabel(oldLabel('selected'))))            

        ## get attributes of new module
        l1Jets = getattr(process, newLabel(oldLabel()))

        ## add a clone of gen jet matching
        addClone('patJetPartonMatch', src = jetCollection)
        addClone('patJetGenJetMatch', src = jetCollection, matched = genJetCollection)

        ## add a clone of parton and flavour associations
        addClone('patJetPartonAssociation', jets = jetCollection)
        addClone('patJetFlavourAssociation', srcByReference = cms.InputTag(newLabel('patJetPartonAssociation')))

        ## fix label for input tag
        def fixInputTag(x): x.setModuleLabel(newLabel(x.moduleLabel))
        ## fix label for vector of input tags
        def fixVInputTag(x): x[0].setModuleLabel(newLabel(x[0].moduleLabel))

        ## provide allLayer1Jet inputs with individual labels
        fixInputTag(l1Jets.genJetMatch)
        fixInputTag(l1Jets.genPartonMatch)
        fixInputTag(l1Jets.JetPartonMapSource)

        ## make VInputTag from strings 
        def vit(*args) : return cms.VInputTag( *[ cms.InputTag(x) for x in args ] )

        if (doJTA or doBTagging):
            ## add clone of jet track association        
            process.load("RecoJets.JetAssociationProducers.ak5JTA_cff")
            from RecoJets.JetAssociationProducers.ak5JTA_cff import ak5JetTracksAssociatorAtVertex
            ## add jet track association module to processes
            jtaLabel = 'jetTracksAssociatorAtVertex'+algoLabel+typeLabel
            setattr( process, jtaLabel, ak5JetTracksAssociatorAtVertex.clone(jets = jetCollection) )
            process.makePatJets.replace(process.patJetCharge, getattr(process,jtaLabel)+process.patJetCharge)
            l1Jets.trackAssociationSource = cms.InputTag(jtaLabel)
            addClone('patJetCharge', src=cms.InputTag(jtaLabel)),
            fixInputTag(l1Jets.jetChargeSource)
        else:
            ## switch embedding of track association and jet
            ## charge estimate to 'False'        
            l1Jets.addAssociatedTracks = False
            l1Jets.addJetCharge = False

        if (doBTagging):
            ## define postfixLabel
            postfixLabel=algoLabel+typeLabel
            ## add b tagging sequence
            (btagSeq, btagLabels) = runBTagging(process, jetCollection, postfixLabel)
            ## add b tagging sequence before running the allLayer1Jets modules
            process.makePatJets.replace(getattr(process,jtaLabel), getattr(process,jtaLabel)+btagSeq)
            ## replace corresponding tags for pat jet production
            l1Jets.trackAssociationSource = cms.InputTag(btagLabels['jta'])
            l1Jets.tagInfoSources = cms.VInputTag( *[ cms.InputTag(x) for x in btagLabels['tagInfos'] ] )
            l1Jets.discriminatorSources = cms.VInputTag( *[ cms.InputTag(x) for x in btagLabels['jetTags']  ] )
        else:
            ## switch general b tagging info switch off
            l1Jets.addBTagInfo = False
        
        if (doJetID):
            l1Jets.addJetID = cms.bool(True)
            jetIdLabelNew = jetIdLabel + 'JetID'
            l1Jets.jetIDMap = cms.InputTag( jetIdLabelNew )
        else :
            l1Jets.addJetID = cms.bool(False)

        if (jetCorrLabel != None):
            ## add clone of jet energy corrections;
            ## catch a couple of exceptions first
            if (jetCorrLabel == False ):
                raise ValueError, "In addJetCollection 'jetCorrLabel' must be set to 'None', not 'False'"
            if (jetCorrLabel == "None"):
                raise ValueError, "In addJetCollection 'jetCorrLabel' must be set to 'None' (without quotes)"
            ## check for the correct format
            if type(jetCorrLabel) != type(('AK5','Calo')): 
                raise ValueError, "In switchJetCollection 'jetCorrLabel' must be 'None', or of type ('Algo','Type')"

            ## add clone of jetCorrFactors
            addClone('patJetCorrFactors', jetSource = jetCollection)
            switchJECParameters( getattr(process,newLabel('patJetCorrFactors')), jetCorrLabel[0], jetCorrLabel[1], oldAlgo='AK5',oldType='Calo' )
            fixVInputTag(l1Jets.jetCorrFactorsSource)
        
            ## switch type1MET corrections off for PFJets
            if( jetCollection.__str__().find('PFJets')>=0 ):
                print '================================================='
                print 'Type1MET corrections are switched off for PFJets.'
                print 'Users are recommened to use pfMET together with'
                print 'PFJets.'
                print '================================================='            
                doType1MET=False

            ## add a clone of the type1MET correction for the new jet collection
            if (doType1MET):
                ## in case there is no jet correction service in the paths add it
                ## as L2L3 if possible, as combined from L2 and L3 otherwise
                if not hasattr( process, 'L2L3JetCorrector%s%s' % jetCorrLabel ):
                    setattr( process, 
                             'L2L3JetCorrector%s%s' % jetCorrLabel, 
                             cms.ESSource("JetCorrectionServiceChain",
                                          correctors = cms.vstring('L2RelativeJetCorrector%s%s' % jetCorrLabel,
                                                                   'L3AbsoluteJetCorrector%s%s' % jetCorrLabel),
                                          label= cms.string('L2L3JetCorrector%s%s' % jetCorrLabel)
                                          )
                             )
                ## add a clone of the type1MET correction
                ## and the following muonMET correction  
                addClone('metJESCorAK5CaloJet', inputUncorJetsLabel = jetCollection.value(),
                         corrector = cms.string('L2L3JetCorrector%s%s' % jetCorrLabel)
                         )
                addClone('metJESCorAK5CaloJetMuons', uncorMETInputTag = cms.InputTag(newLabel('metJESCorAK5CaloJet')))
                addClone('patMETs', metSource = cms.InputTag(newLabel('metJESCorAK5CaloJetMuons')))
                l1MET = getattr(process, newLabel('patMETs'))
                ## add new met collections output to the pat summary
                process.patCandidateSummary.candidates += [ cms.InputTag(newLabel('patMETs')) ]
        else:
            ## switch jetCorrFactors off
            l1Jets.addJetCorrFactors = False
#    algorithm = cms.string('AK5PF'),
#    level = cms.string('L2Relative')
#)
#process.ak5PFL3Absolute = cms.ESProducer("LXXXCorrectionESProducer",
#    algorithm = cms.string('AK5PF'),
#    level = cms.string('L3Absolute')
#)

##############################################################################
## Jet B-tagging
##############################################################################
process.load("RecoJets.JetAssociationProducers.ak5JTA_cff")
from RecoJets.JetAssociationProducers.ak5JTA_cff import ak5JetTracksAssociatorAtVertex
process.load("RecoBTag.Configuration.RecoBTag_cff")
import RecoBTag.Configuration.RecoBTag_cff as btag
process.ak5JetTracksAssociatorAtVertexAK5PF = ak5JetTracksAssociatorAtVertex.clone(
    jets=cms.InputTag("ak5PFJets"))
process.impactParameterTagInfosAK5PF = btag.impactParameterTagInfos.clone(
    jetTracks=cms.InputTag('ak5JetTracksAssociatorAtVertexAK5PF'))
process.secondaryVertexTagInfosAK5PF = btag.secondaryVertexTagInfos.clone(
    trackIPTagInfos=cms.InputTag('impactParameterTagInfosAK5PF'))
process.simpleSecondaryVertexHighEffBJetTagsAK5PF = btag.simpleSecondaryVertexHighEffBJetTags.clone(
    tagInfos=cms.VInputTag('secondaryVertexTagInfosAK5PF'))
process.simpleSecondaryVertexHighPurBJetTagsAK5PF = btag.simpleSecondaryVertexHighPurBJetTags.clone(
    tagInfos=cms.VInputTag('secondaryVertexTagInfosAK5PF'))
process.combinedSecondaryVertexBJetTagsAK5PF = btag.combinedSecondaryVertexBJetTags.clone(
    tagInfos=cms.VInputTag('impactParameterTagInfosAK5PF',
                           'secondaryVertexTagInfosAK5PF'))
process.btaggingSequenceAK5PF = cms.Sequence(
    process.ak5JetTracksAssociatorAtVertexAK5PF +
    process.impactParameterTagInfosAK5PF +
    process.secondaryVertexTagInfosAK5PF +
  L2Relative = cms.string("ak5PFL2Relative"),
  L3Absolute = cms.string("ak5PFL3Absolute")
)
if isData: pfJECS.append(
  L2L3Residual = cms.string("ak5PFResidual")
)

# b-tagging
# ---------
process.load("RecoJets.JetAssociationProducers.ak5JTA_cff")
from RecoJets.JetAssociationProducers.ak5JTA_cff import ak5JetTracksAssociatorAtVertex
process.load("RecoBTag.Configuration.RecoBTag_cff")
import RecoBTag.Configuration.RecoBTag_cff as btag
process.jetTracksAssociatorAtVertexAK5PF = ak5JetTracksAssociatorAtVertex.clone(
  jets = cms.InputTag("ak5PFJets"),
  tracks = cms.InputTag("unpackedTracksAndVertices"),
  pvSrc = cms.InputTag("unpackedTracksAndVertices")
)

process.impactParameterTagInfosAK5PF = btag.impactParameterTagInfos.clone(
  jetTracks = cms.InputTag('jetTracksAssociatorAtVertexAK5PF'),
  primaryVertex = cms.InputTag("unpackedTracksAndVertices")
)

process.secondaryVertexTagInfosAK5PF = btag.secondaryVertexTagInfos.clone(
  trackIPTagInfos = cms.InputTag('impactParameterTagInfosAK5PF')
)
process.simpleSecondaryVertexHighEffBJetTagsAK5PF = btag.simpleSecondaryVertexHighEffBJetTags.clone (
  tagInfos = cms.VInputTag('secondaryVertexTagInfosAK5PF')
)
process.simpleSecondaryVertexHighPurBJetTagsAK5PF = btag.simpleSecondaryVertexHighPurBJetTags.clone (
Beispiel #6
0
    def toolCode(self, process):
        jetCollection=self._parameters['jetCollection'].value
        doJTA=self._parameters['doJTA'].value
        doBTagging=self._parameters['doBTagging'].value
        jetCorrLabel=self._parameters['jetCorrLabel'].value
        doType1MET =self._parameters['doType1MET'].value
        genJetCollection=self._parameters['genJetCollection'].value
        doJetID=self._parameters['doJetID'].value
        jetIdLabel=self._parameters['jetIdLabel'].value
        outputModule=self._parameters['outputModule'].value
        postfix=self._parameters['postfix'].value

        ## save label of old input jet collection
        oldLabel = applyPostfix(process, "patJets", postfix).jetSource;
    
        ## replace input jet collection for generator matches if the
        ## genJetCollection is no empty
        if (process.patJets.addGenPartonMatch):
            applyPostfix(process, "patJetPartonMatch", postfix).src = jetCollection
        if (process.patJets.addGenJetMatch):
            applyPostfix(process, "patJetGenJetMatch", postfix).src = jetCollection
            applyPostfix(process, "patJetGenJetMatch", postfix).matched = genJetCollection
        if (process.patJets.getJetMCFlavour):
            applyPostfix(process, "patJetPartonAssociation", postfix).jets = jetCollection
            
        ## replace input jet collection for pat jet production
	applyPostfix(process, "patJets", postfix).jetSource = jetCollection
    
        ## make VInputTag from strings
        def vit(*args) : return cms.VInputTag( *[ cms.InputTag(x) for x in args ] )

        if (doJTA or doBTagging):
            ## replace jet track association
            process.load("RecoJets.JetAssociationProducers.ak5JTA_cff")
            from RecoJets.JetAssociationProducers.ak5JTA_cff import ak5JetTracksAssociatorAtVertex            
            setattr(process, "jetTracksAssociatorAtVertex"+postfix, ak5JetTracksAssociatorAtVertex.clone(jets = jetCollection)) 
            getattr(process, "patDefaultSequence"+postfix).replace(
                applyPostfix(process, "patJetCharge", postfix),
                getattr(process, "jetTracksAssociatorAtVertex" + postfix) #module with postfix that is not n patDefaultSequence
                + applyPostfix(process, "patJetCharge", postfix)
                )

            applyPostfix(process, "patJetCharge", postfix).src = 'jetTracksAssociatorAtVertex'+postfix
            applyPostfix(process, "patJets", postfix).trackAssociationSource = 'jetTracksAssociatorAtVertex'+postfix
        else:
            ## remove the jet track association from the std
            ## sequence
            removeIfInSequence(process,  "patJetCharge",  "patDefaultSequence", postfix)
            ## switch embedding of track association and jet
            ## charge estimate to 'False'
            applyPostfix(process, "patJets", postfix).addAssociatedTracks = False
            applyPostfix(process, "patJets", postfix).addJetCharge = False

        if (doBTagging):
            ## replace b tagging sequence; add postfix label 'AOD' as crab will
            ## crash when confronted with empy labels
            (btagSeq, btagLabels) = runBTagging(process, jetCollection, 'AOD',postfix)
            ## add b tagging sequence before running the allLayer1Jets modules
            getattr(process, "patDefaultSequence"+postfix).replace(
                getattr( process,"jetTracksAssociatorAtVertex"+postfix),
                getattr( process,"jetTracksAssociatorAtVertex"+postfix) + btagSeq
                )

            ## replace corresponding tags for pat jet production
            applyPostfix(process, "patJets", postfix).trackAssociationSource = btagLabels['jta']
            applyPostfix(process, "patJets", postfix).tagInfoSources = cms.VInputTag( *[ cms.InputTag(x) for x in btagLabels['tagInfos'] ] )
            applyPostfix(process, "patJets", postfix).discriminatorSources = cms.VInputTag( *[ cms.InputTag(x) for x in btagLabels['jetTags']  ] )
        else:
            ## remove b tagging from the std sequence
            removeIfInSequence(process,  "secondaryVertexNegativeTagInfos",  "patDefaultSequence", postfix)
            removeIfInSequence(process,  "simpleSecondaryVertexNegativeBJetTags",  "patDefaultSequence", postfix)
            ## switch embedding of b tagging for pat
            ## jet production to 'False'
            applyPostfix(process, "patJets", postfix).addBTagInfo = False
            ## adjust output
            if outputModule is not '':                
                getattr(process, outputModule).outputCommands.append("drop *_selectedPatJets_tagInfos_*")

        if (doJetID):
            jetIdLabelNew = jetIdLabel + 'JetID'
            applyPostfix(process, "patJets", postfix).jetIDMap = cms.InputTag( jetIdLabelNew )
        else:
            applyPostfix(process, "patJets", postfix).addJetID = cms.bool(False)
            
        if (jetCorrLabel!=None):
            ## replace jet energy corrections; catch
            ## a couple of exceptions first
            if (jetCorrLabel == False ):
                raise ValueError, "In switchJetCollection 'jetCorrLabel' must be set to 'None', not 'False'"
            if (jetCorrLabel == "None"):
                raise ValueError, "In switchJetCollection 'jetCorrLabel' must be set to 'None' (without quotes)"
            ## check for the correct format
            if type(jetCorrLabel) != type(('AK5Calo',['L2Relative'])): 
                raise ValueError, "In addJetCollection 'jetCorrLabel' must be 'None', or of type ('payload',['correction1', 'correction2'])"

            ## switch JEC parameters to the new jet collection
            applyPostfix(process, "patJetCorrFactors", postfix).src = jetCollection
            getattr( process, "patJetCorrFactors" + postfix).payload = jetCorrLabel[0]
            getattr( process, "patJetCorrFactors" + postfix).levels = jetCorrLabel[1]
            getattr( process, "patJets" + postfix).jetCorrFactorsSource = cms.VInputTag( cms.InputTag("patJetCorrFactors" + postfix ) )  

            ## switch type1MET corrections off for PFJets or JPTJets
            if ( jetCollection.getModuleLabel().find('CaloJets')<0 ):
                print '================================================='
                print 'Type1MET corrections are switched off for other  '
                print 'jet types but CaloJets. Users are recommened to  '
                print 'use pfMET together with PFJets & tcMET together  '
                print 'with JPT jets.                                   '
                print '================================================='
                doType1MET=False 

            ## redo the type1MET correction for the new jet collection
            if (doType1MET):
                ## in case there is no jet correction service in the paths add it
                ## as L2L3 if possible, as combined from L2 and L3 otherwise
                if not hasattr( process, '%sL2L3' % (jetCollection.getModuleLabel().replace("Jets", "")) ):
                    setattr( process, '%sL2L3' % (jetCollection.getModuleLabel().replace("Jets", "")),
                             cms.ESSource("JetCorrectionServiceChain",
                                          correctors = cms.vstring('%sL2Relative' % (jetCollection.getModuleLabel().replace("Jets", "")),
                                                                   '%sL3Absolute' % (jetCollection.getModuleLabel().replace("Jets", ""))
                                                                   )
                                          )
                             )                
                ## configure the type1MET correction the following muonMET
                ## corrections have the metJESCorAK5CaloJet as input and 
                ## are automatically correct  
                applyPostfix(process, "metJESCorAK5CaloJet", postfix).inputUncorJetsLabel = jetCollection.value()
                applyPostfix(process, "metJESCorAK5CaloJet", postfix).corrector = '%sL2L3' % (jetCollection.getModuleLabel().replace("Jets", ""))                
        else:
            ## remove the jetCorrFactors from the std sequence
            process.patJetMETCorrections.remove(process.patJetCorrFactors)
            ## switch embedding of jetCorrFactors off
            ## for pat jet production
            applyPostfix(process, "patJets", postfix).addJetCorrFactors = False
            applyPostfix(process, "patJets", postfix).jetCorrFactorsSource=[]        

        ## adjust output when switching to PFJets
        if (jetCollection.getModuleLabel().find('PFJets')>=0 ):
            ## in this case we can omit caloTowers and should keep pfCandidates
            if outputModule is not '':                
                getattr(process, outputModule).outputCommands.append("keep *_selectedPatJets_pfCandidates_*")
                getattr(process, outputModule).outputCommands.append("drop *_selectedPatJets_caloTowers_*")
Beispiel #7
0
    def apply(self,process):
        jetCollection=self._parameters['jetCollection'].value
        postfixLabel=self._parameters['postfixLabel'].value
        doJTA=self._parameters['doJTA'].value
        doBTagging=self._parameters['doBTagging'].value
        jetCorrLabel=self._parameters['jetCorrLabel'].value
        doType1MET =self._parameters['doType1MET'].value
        doL1Cleaning=self._parameters['doL1Cleaning'].value
        doL1Counters=self._parameters['doL1Counters'].value
        genJetCollection=self._parameters['genJetCollection'].value
        doJetID=self._parameters['doJetID'].value
        jetIdLabel=self._parameters['jetIdLabel'].value
        if hasattr(process, "addAction"):
            process.disableRecording()
        ### tool code  
        ## add module as process to the makeAllLayer1Jets sequence
        def addAlso(label, value):
            existing = getattr(process, label)
            setattr( process, label+postfixLabel, value)
            process.makeAllLayer1Jets.replace( existing, existing*value )
        ## clone and add a module as process to the
        ## default sequence
        def addClone(label, **replaceStatements):
            new = getattr(process, label).clone(**replaceStatements)
            addAlso(label, new)
        
        ## add a clone of allLayer1Jets
        addClone('allLayer1Jets', jetSource = jetCollection)
        ## add a clone of selectedLayer1Jets    
        addClone('selectedLayer1Jets', src=cms.InputTag('allLayer1Jets'+postfixLabel))
        ## add a clone of cleanLayer1Jets    
        if (doL1Cleaning or doL1Counters):
            addClone('cleanLayer1Jets', src=cms.InputTag('selectedLayer1Jets'+postfixLabel))
        ## add a clone of countLayer1Jets    
        if (doL1Counters):
            addClone('countLayer1Jets', src=cms.InputTag('cleanLayer1Jets'+postfixLabel))

        ## attributes of allLayer1Jets
        l1Jets = getattr(process, 'allLayer1Jets'+postfixLabel)

        ## add a clone of gen jet matching
        addClone('jetPartonMatch', src = jetCollection)
        addClone('jetGenJetMatch', src = jetCollection, matched = genJetCollection)
        ## add a clone of parton and flavour associations
        addClone('jetPartonAssociation', jets = jetCollection)
        addClone('jetFlavourAssociation', srcByReference = cms.InputTag('jetPartonAssociation'+postfixLabel))

        ## fix label for input tag
        def fixInputTag(x): x.setModuleLabel(x.moduleLabel+postfixLabel)
        ## fix label for vector of input tags
        def fixVInputTag(x): x[0].setModuleLabel(x[0].moduleLabel+postfixLabel)

        ## provide allLayer1Jet inputs with individual labels
        fixInputTag(l1Jets.genJetMatch)
        fixInputTag(l1Jets.genPartonMatch)
        fixInputTag(l1Jets.JetPartonMapSource)

        ## make VInputTag from strings 
        def vit(*args) : return cms.VInputTag( *[ cms.InputTag(x) for x in args ] )

        if (doJTA or doBTagging):
            ## add clone of jet track association        
            process.load("RecoJets.JetAssociationProducers.ak5JTA_cff")
            from RecoJets.JetAssociationProducers.ak5JTA_cff import ak5JetTracksAssociatorAtVertex
            ## add jet track association module to processes
            jtaLabel = 'jetTracksAssociatorAtVertex'+postfixLabel
            setattr( process, jtaLabel, ak5JetTracksAssociatorAtVertex.clone(jets = jetCollection) )
            process.makeAllLayer1Jets.replace(process.patJetCharge, getattr(process,jtaLabel)+process.patJetCharge)
            l1Jets.trackAssociationSource = cms.InputTag(jtaLabel)
            addClone('patJetCharge', src=cms.InputTag(jtaLabel)),
            fixInputTag(l1Jets.jetChargeSource)
        else:
            ## switch embedding of track association and jet
            ## charge estimate to 'False'        
            l1Jets.addAssociatedTracks = False
            l1Jets.addJetCharge = False
    
        if (doBTagging):
            ## add b tagging sequence
            (btagSeq, btagLabels) = runBTagging(process, jetCollection, postfixLabel)
            ## add b tagging sequence before running the allLayer1Jets modules
            process.makeAllLayer1Jets.replace(getattr(process,jtaLabel), getattr(process,jtaLabel)+btagSeq)
            ## replace corresponding tags for pat jet production
            l1Jets.trackAssociationSource = cms.InputTag(btagLabels['jta'])
            l1Jets.tagInfoSources = cms.VInputTag( *[ cms.InputTag(x) for x in btagLabels['tagInfos'] ] )
            l1Jets.discriminatorSources = cms.VInputTag( *[ cms.InputTag(x) for x in btagLabels['jetTags']  ] )
        else:
            ## switch general b tagging info switch off
            l1Jets.addBTagInfo = False
        
        if (doJetID):
            l1Jets.addJetID = cms.bool(True)
            jetIdLabelNew = jetIdLabel + 'JetID'
            l1Jets.jetIDMap = cms.InputTag( jetIdLabelNew )
        else :
            l1Jets.addJetID = cms.bool(False)

        if (jetCorrLabel != None):
            ## add clone of jet energy corrections;
            ## catch a couple of exceptions first
            if (jetCorrLabel == False ):
                raise ValueError, "In addJetCollection 'jetCorrLabel' must be set to 'None', not 'False'"
            if (jetCorrLabel == "None"):
                raise ValueError, "In addJetCollection 'jetCorrLabel' must be set to 'None' (without quotes)"
            ## check for the correct format
            if type(jetCorrLabel) != type(('AK5','Calo')): 
                raise ValueError, "In switchJetCollection 'jetCorrLabel' must be 'None', or of type ('Algo','Type')"

            ## add clone of jetCorrFactors
            addClone('jetCorrFactors', jetSource = jetCollection)
            switchJECParameters( getattr(process,'jetCorrFactors'+postfixLabel), jetCorrLabel[0], jetCorrLabel[1], oldAlgo='AK5',oldType='Calo' )
            fixVInputTag(l1Jets.jetCorrFactorsSource)

            ## add a clone of the type1MET correction for the new jet collection
            if (doType1MET):
                ## in case there is no jet correction service in the paths add it
                ## as L2L3 if possible, as combined from L2 and L3 otherwise
                if not hasattr( process, 'L2L3JetCorrector%s%s' % jetCorrLabel ):
                    setattr( process, 
                             'L2L3JetCorrector%s%s' % jetCorrLabel, 
                             cms.ESSource("JetCorrectionServiceChain",
                                          correctors = cms.vstring('L2RelativeJetCorrector%s%s' % jetCorrLabel,
                                                                   'L3AbsoluteJetCorrector%s%s' % jetCorrLabel),
                                          label= cms.string('L2L3JetCorrector%s%s' % jetCorrLabel)
                                          )
                             )
                ## add a clone of the type1MET correction
                ## and the following muonMET correction  
                addClone('metJESCorAK5CaloJet', inputUncorJetsLabel = jetCollection.value(),
                         corrector = cms.string('L2L3JetCorrector%s%s' % jetCorrLabel)
                         )
                addClone('metJESCorAK5CaloJetMuons', uncorMETInputTag = cms.InputTag("metJESCorAK5CaloJet"+postfixLabel))
                addClone('layer1METs', metSource = cms.InputTag("metJESCorAK5CaloJetMuons"+postfixLabel))
                l1MET = getattr(process, 'layer1METs'+postfixLabel)

                ## add new met collections output to the pat summary
                process.allLayer1Summary.candidates += [ cms.InputTag('layer1METs'+postfixLabel) ]
        else:
            ## switch jetCorrFactors off
            l1Jets.addJetCorrFactors = False
        if hasattr(process, "addAction"):
            process.enableRecording()
            action=self.__copy__()
            process.addAction(action)
Beispiel #8
0
pfJetSequenceEI = cms.Sequence(pfJetsEI + pfJetsPtrsEI)

pfNoJetEI = pfNoJet.clone(topCollection='pfJetsPtrsEI',
                          bottomCollection='pfNoElectronJME')

#### Taus ####
pfTausEI = pfTaus.clone()
pfTausPtrsEI = pfTausPtrs.clone(src=cms.InputTag("pfTausEI"))
pfNoTauEI = pfNoTau.clone(topCollection=cms.InputTag('pfTausPtrsEI'),
                          bottomCollection=cms.InputTag('pfJetsPtrsEI'))

pfTauEISequence = cms.Sequence(pfTausPreSequence + pfTausBaseSequence +
                               pfTausEI + pfTausPtrsEI)

#### B-tagging ####
pfJetTrackAssociatorEI = ak5JetTracksAssociatorAtVertex.clone(
    src=cms.InputTag("pfJetsEI"))
impactParameterTagInfosEI = impactParameterTagInfos.clone(
    jetTracks=cms.InputTag('pfJetTrackAssociatorEI'))
secondaryVertexTagInfosEI = secondaryVertexTagInfos.clone(
    trackIPTagInfos=cms.InputTag('impactParameterTagInfosEI'))
combinedSecondaryVertexBJetTagsEI = combinedSecondaryVertexBJetTags.clone(
    tagInfos=cms.VInputTag(cms.InputTag("impactParameterTagInfosEI"),
                           cms.InputTag("secondaryVertexTagInfosEI")))

#### MET ####
pfMetEI = pfMET.clone(jets=cms.InputTag("pfJetsEI"))

#EITopPAG = cms.Sequence(
EIsequence = cms.Sequence(pfPileUpEI + pfPileUpJMEEI + pfNoPileUpEI +
                          pfNoPileUpJMEEI + pfAllMuonsEI +
                          pfMuonsFromVertexEI + pfIsolatedMuonsEI + pfNoMuon +
Beispiel #9
0
pfTausPtrsEI = pfTausPtrs.clone(src=cms.InputTag("pfTausEI") )
pfNoTauEI = pfNoTau.clone(
    topCollection = cms.InputTag('pfTausPtrsEI'),
    bottomCollection = cms.InputTag('pfJetsPtrsEI')
    )

pfTauEISequence = cms.Sequence(
    pfTausPreSequence+
    pfTausBaseSequence+
    pfTausEI+
    pfTausPtrsEI
    )

#### B-tagging ####
pfJetTrackAssociatorEI = ak5JetTracksAssociatorAtVertex.clone (
    src = cms.InputTag("pfJetsEI")
    )
impactParameterTagInfosEI = impactParameterTagInfos.clone(
    jetTracks = cms.InputTag( 'pfJetTrackAssociatorEI' )
    )
secondaryVertexTagInfosEI = secondaryVertexTagInfos.clone(
    trackIPTagInfos = cms.InputTag( 'impactParameterTagInfosEI' )
    )
combinedSecondaryVertexBJetTagsEI = combinedSecondaryVertexBJetTags.clone(
    tagInfos = cms.VInputTag(cms.InputTag("impactParameterTagInfosEI"),
                             cms.InputTag("secondaryVertexTagInfosEI"))    
    )



#### MET ####
    def toolCode(self, process):
        """
        Tool code implementation
        """
        ## initialize parameters
        labelName='patJets'+self._parameters['labelName'].value
        postfix=self._parameters['postfix'].value
        jetSource=self._parameters['jetSource'].value
        algo=self._parameters['algo'].value
        jetCorrections=self._parameters['jetCorrections'].value
        btagDiscriminators=list(self._parameters['btagDiscriminators'].value)
        btagInfos=list(self._parameters['btagInfos'].value)
        jetTrackAssociation=self._parameters['jetTrackAssociation'].value
        outputModules=list(self._parameters['outputModules'].value)

        ## a list of all producer modules, which are already known to process
        knownModules = process.producerNames().split()
        ## determine whether btagging information is required or not
        if btagDiscriminators.count('None')>0:
            btagDiscriminators.remove('None')
        if btagInfos.count('None')>0:
            btagInfos.remove('None')
        bTagging=(len(btagDiscriminators)>0 or len(btagInfos)>0)
        ## construct postfix label for auxiliary modules; this postfix
        ## label will start with a capitalized first letter following
        ## the CMS nameing conventions and for improved readablility
        _labelName=labelName[:1].upper()+labelName[1:]
	#_labelName=labelName
        ## determine jet algorithm from jetSource; supported algo types
        ## are ak, kt, sc, ic. This loop expects that the algo type is
        ## followed by a single integer corresponding to the opening
        ## angle parameter dR times 10 (examples ak5, kt4, kt6, ...)
        _algo=algo
	#jetSource=cms.InputTag("ak5PFJets")
        for x in ["ak", "kt", "sc", "ic"]:
            if jetSource.getModuleLabel().lower().find(x)>-1:
                _algo=jetSource.getModuleLabel()[jetSource.getModuleLabel().lower().find(x):jetSource.getModuleLabel().lower().find(x)+3]
	#print _algo
        ## add new patJets to process (keep instance for later further modifications)
        from PhysicsTools.PatAlgos.producersLayer1.jetProducer_cfi import patJets
        if labelName in knownModules :
            _newPatJets=getattr(process, labelName+postfix)
            _newPatJets.jetSource=jetSource
        else :
            #setattr(process, labelName, patJets.clone(jetSource=jetSource))
            setattr(process, labelName+postfix, patJets.clone(jetSource=jetSource))
            _newPatJets=getattr(process, labelName+postfix)
            knownModules.append(labelName+postfix)
        ## add new selectedPatJets to process
        from PhysicsTools.PatAlgos.selectionLayer1.jetSelector_cfi import selectedPatJets
        if 'selected'+_labelName+postfix in knownModules :
            _newSelectedPatJets=getattr(process, 'selected'+_labelName+postfix)
            _newSelectedPatJets.src=labelName+postfix
        else :
            setattr(process, 'selected'+_labelName+postfix, selectedPatJets.clone(src=labelName+postfix))
            knownModules.append('selected'+_labelName+postfix)

        ## set postfix label to '' if there is no labelName given. In this case all
        ## modules should keep there names w/o postfixes. This will cover the case
        ## of switchJectCollection
        if self._parameters['labelName'].value == '' :
            _labelName = ''

	## add new patJetPartonMatch to process
        from PhysicsTools.PatAlgos.mcMatchLayer0.jetMatch_cfi import patJetPartonMatch
        if 'patJetPartonMatch'+_labelName+postfix in knownModules :
            _newPatJetPartonMatch=getattr(process, 'patJetPartonMatch'+_labelName+postfix)
            _newPatJetPartonMatch.src=jetSource
        else :
            setattr(process, 'patJetPartonMatch'+_labelName+postfix, patJetPartonMatch.clone(src=jetSource))
            knownModules.append('patJetPartonMatch'+_labelName+postfix)
        ## add new patJetGenJetMatch to process
        from PhysicsTools.PatAlgos.mcMatchLayer0.jetMatch_cfi import patJetGenJetMatch
        if 'patJetGenJetMatch'+_labelName+postfix in knownModules :
            _newPatJetGenJetMatch=getattr(process, 'patJetGenJetMatch'+_labelName+postfix)
            _newPatJetGenJetMatch.src=jetSource
            _newPatJetGenJetMatch.matched=_algo.lower()+'GenJets'+postfix
        else :
            setattr(process, 'patJetGenJetMatch'+_labelName+postfix, patJetGenJetMatch.clone(src=jetSource, matched=_algo+'GenJets'))
            knownModules.append('patJetGenJetMatch'+_labelName+postfix)
        ## add new patJetPartonAssociation to process
        from PhysicsTools.PatAlgos.mcMatchLayer0.jetFlavourId_cff import patJetPartonAssociation
        if 'patJetPartonAssociation'+_labelName+postfix in knownModules :
            _newPatJetPartonAssociation=getattr(process, 'patJetPartonAssociation'+_labelName+postfix, patJetPartonAssociation.clone(jets=jetSource))
            _newPatJetPartonAssociation.jets=jetSource
        else :
            setattr(process, 'patJetPartonAssociation'+_labelName+postfix, patJetPartonAssociation.clone(jets=jetSource))
            knownModules.append('patJetPartonAssociation'+_labelName+postfix)
        ## add new patJetPartonAssociation to process
        from PhysicsTools.PatAlgos.mcMatchLayer0.jetFlavourId_cff import patJetFlavourAssociation
        if 'patJetFlavourAssociation'+_labelName+postfix in knownModules :
            _newPatJetFlavourAssociation=getattr(process, 'patJetFlavourAssociation'+_labelName+postfix, patJetFlavourAssociation.clone(srcByReference='patJetPartonAssociation'+_labelName+postfix))
            _newPatJetFlavourAssociation.srcByReference='patJetPartonAssociation'+_labelName+postfix
        else:
            setattr(process, 'patJetFlavourAssociation'+_labelName+postfix, patJetFlavourAssociation.clone(srcByReference='patJetPartonAssociation'+_labelName+postfix))
            knownModules.append('patJetFlavourAssociation'+_labelName+postfix)
        ## modify new patJets collection accordingly
        _newPatJets.genJetMatch.setModuleLabel('patJetGenJetMatch'+_labelName+postfix)
        _newPatJets.genPartonMatch.setModuleLabel('patJetPartonMatch'+_labelName+postfix)
        _newPatJets.JetPartonMapSource.setModuleLabel('patJetFlavourAssociation'+_labelName+postfix)

        ## add jetTrackAssociation for btagging (or jetTracksAssociation only) if required by user
        if (jetTrackAssociation or bTagging):
            ## add new jetTracksAssociationAtVertex to process
            from RecoJets.JetAssociationProducers.ak5JTA_cff import ak5JetTracksAssociatorAtVertex
            if 'jetTracksAssociationAtVertex'+_labelName+postfix in knownModules :
                _newJetTracksAssociationAtVertex=getattr(process, 'jetTracksAssociatorAtVertex'+_labelName+postfix)
                _newJetTracksAssociationAtVertex.jets=jetSource
            else:
                setattr(process, 'jetTracksAssociatorAtVertex'+_labelName+postfix, ak5JetTracksAssociatorAtVertex.clone(jets=jetSource))
                knownModules.append('jetTracksAssociationAtVertex'+_labelName+postfix)
            ## add new patJetCharge to process
            from PhysicsTools.PatAlgos.recoLayer0.jetTracksCharge_cff import patJetCharge
            if 'patJetCharge'+_labelName+postfix in knownModules :
                _newPatJetCharge=getattr(process, 'patJetCharge'+_labelName+postfix)
                _newPatJetCharge.src='jetTracksAssociatorAtVertex'+_labelName+postfix
            else:
                setattr(process, 'patJetCharge'+_labelName+postfix, patJetCharge.clone(src = 'jetTracksAssociatorAtVertex'+_labelName+postfix))
                knownModules.append('patJetCharge'+_labelName+postfix)
            ## modify new patJets collection accordingly
            _newPatJets.addAssociatedTracks=True
            _newPatJets.trackAssociationSource=cms.InputTag('jetTracksAssociatorAtVertex'+_labelName+postfix)
            _newPatJets.addJetCharge=True
            _newPatJets.jetChargeSource=cms.InputTag('patJetCharge'+_labelName+postfix)
        else:
            ## modify new patJets collection accordingly
            _newPatJets.addAssociatedTracks=False
            _newPatJets.trackAssociationSource=''
            _newPatJets.addJetCharge=False
            _newPatJets.jetChargeSource=''
        ## run btagging if required by user
        if (bTagging):
            ## expand tagInfos to what is explicitely required by user + implicit
            ## requirements that come in from one or the other discriminator
            requiredTagInfos = list(btagInfos)
            for btagDiscr in btagDiscriminators :
                for requiredTagInfo in supportedBtagDiscr[btagDiscr] :
                    tagInfoCovered = False
                    for tagInfo in requiredTagInfos :
                        if requiredTagInfo == tagInfo :
                            tagInfoCovered = True
                            break
                    if not tagInfoCovered :
                        requiredTagInfos.append(requiredTagInfo)
            ## load sequences and setups needed fro btagging
	    ## This loads all available btagger, but the ones we need are added to the process by hand lader. Only needed to get the ESProducer. Needs improvement
            #loadWithPostFix(process,"RecoBTag.Configuration.RecoBTag_cff",postfix)
            process.load("RecoBTag.Configuration.RecoBTag_cff")
	    #addESProducers(process,'RecoBTag.Configuration.RecoBTag_cff')
            import RecoBTag.Configuration.RecoBTag_cff as btag

            ## prepare setups for simple secondary vertex infos
            setattr(process, "simpleSecondaryVertex2Trk", simpleSecondaryVertex2Trk)
            ## prepare setups for transient tracks
            setattr(process, "TransientTrackBuilderESProducer", TransientTrackBuilderESProducer)
            ## setup all required btagInfos : we give a dedicated treatment for all five different
            ## types of tagINfos here. A common treatment is possible but might require a more
            ## general approach anyway in coordination with the btaggin POG.
            for btagInfo in requiredTagInfos :
                if 'impactParameterTagInfos' in btagInfo :
                    setattr(process, btagInfo+_labelName+postfix, btag.impactParameterTagInfos.clone(jetTracks = cms.InputTag('jetTracksAssociatorAtVertex'+_labelName+postfix)))
                if 'secondaryVertexTagInfos' in btagInfo :
                    setattr(process, btagInfo+_labelName+postfix, btag.secondaryVertexTagInfos.clone(trackIPTagInfos = cms.InputTag('impactParameterTagInfos'+_labelName+postfix)))
                if 'secondaryVertexNegativeTagInfos' in btagInfo :
                    setattr(process, btagInfo+_labelName+postfix, btag.secondaryVertexNegativeTagInfos.clone(trackIPTagInfos = cms.InputTag('impactParameterTagInfos'+_labelName+postfix)))
                if 'softElectronTagInfos' in btagInfo :
                    setattr(process, btagInfo+_labelName+postfix, btag.softElectronTagInfos.clone(jets = cms.InputTag(_newJetCollection)))
                if 'softMuonTagInfos' in btagInfo :
                    setattr(process, btagInfo+_labelName+postfix, btag.softMuonTagInfos.clone(jets = cms.InputTag(_newJetCollection)))
            ## setup all required btagDiscriminators
            for btagDiscr in btagDiscriminators :
                setattr(process, btagDiscr+_labelName+postfix, getattr(btag, btagDiscr).clone(tagInfos = cms.VInputTag( *[ cms.InputTag(x+_labelName+postfix) for x in supportedBtagDiscr[btagDiscr] ] )))
            ## replace corresponding tags for pat jet production
            _newPatJets.tagInfoSources = cms.VInputTag( *[ cms.InputTag(x+_labelName+postfix) for x in btagInfos ] )
            _newPatJets.discriminatorSources = cms.VInputTag( *[ cms.InputTag(x+_labelName+postfix) for x in btagDiscriminators ] )
        else:
            _newPatJets.addBTagInfo = False
            ## adjust output module; these collections will be empty anyhow, but we do it to stay clean
            for outputModule in outputModules:
                    if hasattr(process,outputModule):
                        getattr(process,outputModule).outputCommands.append("drop *_"+'selected'+_labelName+postfix+"_tagInfos_*")

        ## add jet correction factors if required by user
        if (jetCorrections != None):
            ## check for the correct format
            if type(jetCorrections) != type(('PAYLOAD-LABEL',['CORRECTION-LEVEL-A','CORRECTION-LEVEL-B'], 'MET-LABEL')):
                raise ValueError, "In addJetCollection: 'jetCorrections' must be 'None' (as a python value w/o quotation marks), or of type ('PAYLOAD-LABEL', ['CORRECTION-LEVEL-A', \
                'CORRECTION-LEVEL-B', ...], 'MET-LABEL'). Note that 'MET-LABEL' can be set to 'None' (as a string in quotation marks) in case you do not want to apply MET(Type1) \
                corrections."
            ## determine type of jet constituents from jetSource; supported
            ## jet constituent types are calo, pf, jpt, for pf also particleflow
            ## is aloowed as part of the jetSource label, which might be used
            ## in CommonTools.ParticleFlow
            _type="NONE"
            if jetCorrections[0].count('PF')>0:
                _type='PF'
            elif jetCorrections[0].count('Calo')>0:
                _type='Calo'
            elif jetCorrections[0].count('JPT')>0:
                _type='JPT'
            else:
                raise TypeError, "In addJetCollection: Jet energy corrections are only supported for PF, JPT and Calo jets."
            from PhysicsTools.PatAlgos.recoLayer0.jetCorrFactors_cfi import patJetCorrFactors
            if 'patJetCorrFactors'+_labelName+postfix in knownModules :
                _newPatJetCorrFactors=getattr(process, 'patJetCorrFactors'+_labelName+postfix)
                _newPatJetCorrFactors.src=jetSource
            else :

                setattr(process, 'patJetCorrFactors'+_labelName+postfix, patJetCorrFactors.clone(src=jetSource))
                _newPatJetCorrFactors=getattr(process, "patJetCorrFactors"+_labelName+postfix)
            _newPatJetCorrFactors.payload=jetCorrections[0]
            _newPatJetCorrFactors.levels=jetCorrections[1]
            ## check whether L1Offset or L1FastJet is part of levels
            error=False
            for x in jetCorrections[1]:
                if x == 'L1Offset' :
                    if not error :
                        _newPatJetCorrFactors.useNPV=True
                        _newPatJetCorrFactors.primaryVertices='offlinePrimaryVertices'
                        ## we set this to True now as a L1 correction type should appear only once
                        ## otherwise levels is miss configured
                        error=True
                    else:
                        raise ValueError, "In addJetCollection: Correction levels for jet energy corrections are miss configured. An L1 correction type should appear not more than \
                        once. Check the list of correction levels you requested to be applied: ", jetCorrections[1]
                if x == 'L1FastJet' :
                    if not error :
                        if _type == "JPT" :
                            raise TypeError, "In addJetCollection: L1FastJet corrections are only supported for PF and Calo jets."
                        ## configure module
                        _newPatJetCorrFactors.useRho=True
                        _newPatJetCorrFactors.rho=cms.InputTag('kt6'+_type+'Jets', 'rho')
                        ## we set this to True now as a L1 correction type should appear only once
                        ## otherwise levels is miss configured
                        error=True
                    else:
                        raise ValueError, "In addJetCollection: Correction levels for jet energy corrections are miss configured. An L1 correction type should appear not more than \
                        once. Check the list of correction levels you requested to be applied: ", jetCorrections[1]
            _newPatJets.jetCorrFactorsSource=cms.VInputTag(cms.InputTag('patJetCorrFactors'+_labelName+postfix))
            ## configure MET(Type1) corrections
            if jetCorrections[2].lower() != 'none' and jetCorrections[2] != '':
                if not jetCorrections[2].lower() == 'type-1' and not jetCorrections[2].lower() == 'type-2':
                    raise valueError, "In addJetCollection: Wrong choice of MET corrections for new jet collection. Possible choices are None (or empty string), Type-1, Type-2 (i.e.\
                    Type-1 and Type-2 corrections applied). This choice is not case sensitive. Your choice was: ", jetCorrections[2]
                if _type == "JPT":
                    raise ValueError, "In addJecCollection: MET(type1) corrections are not supported for JPTJets. Please set the MET-LABEL to \"None\" (as string in quatiation \
                    marks) and use raw tcMET together with JPTJets."
                ## set up jet correctors for MET corrections
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFL1Fastjet
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFL1Offset
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFL2Relative
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFL3Absolute
                from JetMETCorrections.Configuration.JetCorrectionServicesAllAlgos_cff import ak5PFResidual

                setattr(process, jetCorrections[0]+'L1FastJet', ak5PFL1Fastjet.clone(algorithm=jetCorrections[0], srcRho=cms.InputTag('kt6'+_type+'Jets','rho')))
                setattr(process, jetCorrections[0]+'L1Offset', ak5PFL1Offset.clone(algorithm=jetCorrections[0]))
                setattr(process, jetCorrections[0]+'L2Relative', ak5PFL2Relative.clone(algorithm=jetCorrections[0]))
                setattr(process, jetCorrections[0]+'L3Absolute', ak5PFL3Absolute.clone(algorithm=jetCorrections[0]))
                setattr(process, jetCorrections[0]+'L2L3Residual', ak5PFResidual.clone(algorithm=jetCorrections[0]))
                setattr(process, jetCorrections[0]+'CombinedCorrector', cms.ESProducer( 'JetCorrectionESChain', correctors = cms.vstring()))
                for x in jetCorrections[1]:
                    if x != 'L1FastJet' and x != 'L1Offset' and x != 'L2Relative' and x != 'L3Absolute' and x != 'L2L3Residual':
                        raise ValueError, 'In addJetCollection: Unsupported JEC for MET(Type1). Currently supported jet correction levels are L1FastJet, L1Offset, L2Relative, \
                        L3Asolute, L2L3Residual. Requested was:', x
                    else:
                        getattr(process, jetCorrections[0]+'CombinedCorrector').correctors.append(jetCorrections[0]+x)

                ## set up MET(Type1) correction modules
                if _type == 'Calo':
                    from JetMETCorrections.Type1MET.caloMETCorrections_cff import caloJetMETcorr
                    from JetMETCorrections.Type1MET.caloMETCorrections_cff import caloType1CorrectedMet
                    from JetMETCorrections.Type1MET.caloMETCorrections_cff import caloType1p2CorrectedMet
                    setattr(process,jetCorrections[0]+'JetMETcorr'+postfix, caloJetMETcorr.clone(src=jetSource,srcMET = "corMetGlobalMuons",jetCorrections = cms.string(jetCorrections[0]+'CombinedCorrector'+postfix)))
                    setattr(process,jetCorrections[0]+'Type1CorMet'+postfix, caloType1CorrectedMet.clone(src = "corMetGlobalMuons"+postfix,srcType1Corrections = cms.VInputTag(cms.InputTag(jetCorrections[0]+'JetMETcorr'+postfix, 'type1'))))
                    setattr(process,jetCorrections[0]+'Type1p2CorMet'+postfix,caloType1p2CorrectedMet.clone(src = "corMetGlobalMuons"+postfix,srcType1Corrections = cms.VInputTag(cms.InputTag(jetCorrections[0]+'JetMETcorr'+postfix, 'type1')),srcUnclEnergySums = cms.VInputTag(cms.InputTag(jetCorrections[0]+'JetMETcorr'+postfix, 'type2'),cms.InputTag(jetCorrections[0]+'JetMETcorr'+postfix, 'offset'),cms.InputTag('muonCaloMETcorr'+postfix))))

                elif _type == 'PF':
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfCandsNotInJet
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfJetMETcorr
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfCandMETcorr
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfType1CorrectedMet
                    from JetMETCorrections.Type1MET.pfMETCorrections_cff import pfType1p2CorrectedMet
                    setattr(process,jetCorrections[0]+'CandsNotInJet'+postfix,pfCandsNotInJet.clone(topCollection = jetSource))
                    setattr(process,jetCorrections[0]+'CandMETcorr'+postfix, pfCandMETcorr.clone(src = cms.InputTag(jetCorrections[0]+'CandsNotInJet'+postfix)))
                    setattr(process,jetCorrections[0]+'JetMETcorr'+postfix, pfJetMETcorr.clone(src = jetSource))
                    setattr(process,jetCorrections[0]+'Type1CorMet'+postfix, pfType1CorrectedMet.clone(srcType1Corrections = cms.VInputTag(cms.InputTag(jetCorrections[0]+'JetMETcorr'+postfix, 'type1'))))
                    setattr(process,jetCorrections[0]+'Type1p2CorMet'+postfix, pfType1p2CorrectedMet.clone(srcType1Corrections = cms.VInputTag(cms.InputTag(jetCorrections[0]+'JetMETcorr'+postfix, 'type1')),srcUnclEnergySums = cms.VInputTag(cms.InputTag(jetCorrections[0]+'JetMETcorr'+postfix, 'type2'),cms.InputTag(jetCorrections[0]+'JetMETcorr'+postfix, 'offset'),cms.InputTag(jetCorrections[0]+'CandMETcorr'+postfix))))

                ## common configuration for Calo and PF
                if ('L1FastJet' in jetCorrections[1] or 'L1Fastjet' in jetCorrections[1]):
                    getattr(process,jetCorrections[0]+'JetMETcorr'+postfix).offsetCorrLabel = cms.string(jetCorrections[0]+'L1FastJet')
                elif ('L1Offset' in jetCorrections[1]):
                    getattr(process,jetCorrections[0]+'JetMETcorr'+postfix).offsetCorrLabel = cms.string(jetCorrections[0]+'L1Offset')
                else:
                    getattr(process,jetCorrections[0]+'JetMETcorr'+postfix).offsetCorrLabel = cms.string('')

                from PhysicsTools.PatAlgos.producersLayer1.metProducer_cfi import patMETs
                if jetCorrections[2].lower() == 'type-1':
                    setattr(process, 'patMETs'+_labelName+postfix, patMETs.clone(metSource = cms.InputTag(jetCorrections[0]+'Type1CorMet'+postfix), addMuonCorrections = False))
                elif jetCorrections[2].lower() == 'type-1':
                    setattr(process, 'patMETs'+_labelName+postfix, patMETs.clone(metSource = cms.InputTag(jetCorrections[0]+'Type1p2CorMet'+postfix), addMuonCorrections = False))
        else:
            ## switch jetCorrFactors off
            _newPatJets.addJetCorrFactors=False
Beispiel #11
0
process.patTriggerSequence = cms.Sequence()

from PhysicsTools.PatAlgos.tools.trigTools import *
switchOnTrigger(process, sequence = 'patTriggerSequence', hltProcess = '*', outputModule = '')




process.load("RecoJets.JetAssociationProducers.ak5JTA_cff")
from RecoJets.JetAssociationProducers.ak5JTA_cff import ak5JetTracksAssociatorAtVertex
process.load("RecoBTag.Configuration.RecoBTag_cff")
import RecoBTag.Configuration.RecoBTag_cff as btag

process.ak5JetTracksAssociatorAtVertexAK5PF = ak5JetTracksAssociatorAtVertex.clone(
  jets = cms.InputTag("ak5PFJets")
  )
process.impactParameterTagInfosAK5PF = btag.impactParameterTagInfos.clone(
  jetTracks = cms.InputTag('ak5JetTracksAssociatorAtVertexAK5PF')
  )
process.secondaryVertexTagInfosAK5PF = btag.secondaryVertexTagInfos.clone(
  trackIPTagInfos = cms.InputTag('impactParameterTagInfosAK5PF')
  )
process.simpleSecondaryVertexHighEffBJetTagsAK5PF = btag.simpleSecondaryVertexHighEffBJetTags.clone (
  tagInfos = cms.VInputTag('secondaryVertexTagInfosAK5PF')
  )
process.simpleSecondaryVertexHighPurBJetTagsAK5PF = btag.simpleSecondaryVertexHighPurBJetTags.clone (
  tagInfos = cms.VInputTag('secondaryVertexTagInfosAK5PF')
  )
process.combinedSecondaryVertexBJetTagsAK5PF = btag.combinedSecondaryVertexBJetTags.clone (
  tagInfos = cms.VInputTag('impactParameterTagInfosAK5PF','secondaryVertexTagInfosAK5PF')
    L3Absolute=cms.string("ak5PFL3Absolute"),
)
if isData:
    pfJECS.append(L2L3Residual=cms.string("ak5PFResidual"))

# b-tagging
# ---------
process.load("RecoJets.JetAssociationProducers.ak5JTA_cff")
from RecoJets.JetAssociationProducers.ak5JTA_cff import ak5JetTracksAssociatorAtVertex

process.load("RecoBTag.Configuration.RecoBTag_cff")
import RecoBTag.Configuration.RecoBTag_cff as btag

process.jetTracksAssociatorAtVertexAK5PF = ak5JetTracksAssociatorAtVertex.clone(
    jets=cms.InputTag("ak5PFJets"),
    tracks=cms.InputTag("unpackedTracksAndVertices"),
    pvSrc=cms.InputTag("unpackedTracksAndVertices"),
)

process.impactParameterTagInfosAK5PF = btag.impactParameterTagInfos.clone(
    jetTracks=cms.InputTag("jetTracksAssociatorAtVertexAK5PF"), primaryVertex=cms.InputTag("unpackedTracksAndVertices")
)

process.secondaryVertexTagInfosAK5PF = btag.secondaryVertexTagInfos.clone(
    trackIPTagInfos=cms.InputTag("impactParameterTagInfosAK5PF")
)
process.simpleSecondaryVertexHighEffBJetTagsAK5PF = btag.simpleSecondaryVertexHighEffBJetTags.clone(
    tagInfos=cms.VInputTag("secondaryVertexTagInfosAK5PF")
)
process.simpleSecondaryVertexHighPurBJetTagsAK5PF = btag.simpleSecondaryVertexHighPurBJetTags.clone(
    tagInfos=cms.VInputTag("secondaryVertexTagInfosAK5PF")