예제 #1
0
    def beginLoop(self):
        super(JetStudiesAnalyzer, self).beginLoop()
        self.file = TFile("/".join([self.looperName, "testJets.root"]), "recreate")
        if self.cfg_ana.applyPFLooseId:
            from ROOT import PFJetIDSelectionFunctor

            self.isPFLooseFunc = PFJetIDSelectionFunctor(0, PFJetIDSelectionFunctor.LOOSE)
            ## Workaround: for some reason PyROOT does not bind nor PFJetIDSelectionFunctor(Jet)PFJetIDSelectionFunctor.getBitsTemplates
            from ROOT import pat

            self.isPFLooseFunc.bits = pat.strbitset()
            for i in "CHF", "NHF", "CEF", "NEF", "NCH", "nConstituents":
                self.isPFLooseFunc.bits.push_back(i)
            ## /Workaround
            self.isPFLoose = lambda x: self.isPFLooseFunc(x, self.isPFLooseFunc.bits)
        else:
            self.isPFLoose = lambda x: True

        # general histograms
        self.jetHistos = JetHistograms("Jets")
        self.cleanJetHistos = JetHistograms("CleanJets")
        self.cleanJetHistos_barrel = JetHistograms("CleanJets_barrel")
        self.cleanJetHistos_endtk = JetHistograms("CleanJets_endtk")
        self.cleanJetHistos_endNOtk = JetHistograms("CleanJets_endNOtk")
        self.cleanJetHistos_fwd = JetHistograms("CleanJets_fwd")
        self.matchedCleanJetHistos = JetHistograms("MatchedCleanJets")
        self.matchedCleanJetHistos_barrel = JetHistograms("MatchedCleanJets_barrel")
        self.matchedCleanJetHistos_endtk = JetHistograms("MatchedCleanJets_endtk")
        self.matchedCleanJetHistos_endNOtk = JetHistograms("MatchedCleanJets_endNOtk")
        self.matchedCleanJetHistos_fwd = JetHistograms("MatchedCleanJets_fwd")
        self.matchedCleanJetHistos_PtL = JetHistograms("MatchedCleanJets_ptLow")
        self.matchedCleanJetHistos_PtM = JetHistograms("MatchedCleanJets_ptMed")
        self.matchedCleanJetHistos_PtH = JetHistograms("MatchedCleanJets_ptHi")
        self.matchedCleanJetHistos_PtV = JetHistograms("MatchedCleanJets_ptVHi")
        self.LPtmatchedCleanJetHistos = JetHistograms("LPtMatchedCleanJets")
        self.HPtmatchedCleanJetHistos = JetHistograms("HPtMatchedCleanJets")
        self.unmatchedCleanJetHistos = JetHistograms("UnmatchedCleanJets")
        self.LPtUnmatchedCleanJetHistos = JetHistograms("LPtUnmatchedCleanJets")
        self.HPtUnmatchedCleanJetHistos = JetHistograms("HPtUnmatchedCleanJets")

        # histograms of the components fraction
        self.matchedCleanJetHistosComponents = FractionJetHistograms("MatchedCleanJetsCompontents")
        self.unmatchedCleanJetHistosComponents = FractionJetHistograms("UnmatchedCleanJetsCompontents")

        # histograms for the resolution of matched jets
        self.matchedCleanJetHistosResolution = ResolutionJetHistograms("MatchedCleanJetsResolution", 50, 1)
        self.matchedCleanJetHistosResolution_barrel = ResolutionJetHistograms(
            "MatchedCleanJetsResolution_barrel", 50, 1
        )
        self.matchedCleanJetHistosResolution_endtk = ResolutionJetHistograms("MatchedCleanJetsResolution_endtk", 50, 1)
        self.matchedCleanJetHistosResolution_endNOtk = ResolutionJetHistograms(
            "MatchedCleanJetsResolution_endNOtk", 50, 1
        )
        self.matchedCleanJetHistosResolution_fwd = ResolutionJetHistograms("MatchedCleanJetsResolution_fwd", 50, 1)
        # resolution of matched jets, all eta, bins of pt
        self.matchedCleanJetHistosResolution_PtL = ResolutionJetHistograms(
            "MatchedCleanJetsResolution_ptLow", 50, 1
        )  # <20
        self.matchedCleanJetHistosResolution_PtM = ResolutionJetHistograms(
            "MatchedCleanJetsResolution_ptMed", 50, 1
        )  # <40
        self.matchedCleanJetHistosResolution_PtH = ResolutionJetHistograms(
            "MatchedCleanJetsResolution_ptHi", 50, 1
        )  # <80
        self.matchedCleanJetHistosResolution_PtV = ResolutionJetHistograms(
            "MatchedCleanJetsResolution_ptVHi", 50, 1
        )  # >80

        self.doJetIdHisto = False
        if self.cfg_ana.doJetIdHisto:
            # histograms for pileup jet identification variables
            self.vtxBins = (0, 5, 10, 15, 20, 30)  ## (0,2,4,6,10,15,20,30,35)
            self.ptBins = (20, 30, 50)  ## (20,30,40,50,100)
            self.etaBins = (0, 1.4, 2.5, 3.0)
            self.puEtaLables = ["_barrel", "_endtk", "_endNOtk", "_fwd"]
            reweight_f = TF1("f", "pol2(0)+expo(3)")
            reweight_f.SetParameters(0.1955298, -0.003830591, 1.944794e-05, 4.649755, -0.1722024)
            self.reweight = ("pt", reweight_f)
            self.doJetIdHisto = True
            self.gluCleanHistosId = PileupJetHistograms(
                "GluonMatchedCleanHistosId",
                self.vtxBins,
                self.ptBins,
                self.etaBins,
                etalabels=self.puEtaLables,
                reweight=self.reweight,
                jetIdMva=self.cfg_ana.jetIdMva,
            )
            self.quarkCleanHistosId = PileupJetHistograms(
                "QuarkMatchedCleanHistosId",
                self.vtxBins,
                self.ptBins,
                self.etaBins,
                etalabels=self.puEtaLables,
                reweight=self.reweight,
                jetIdMva=self.cfg_ana.jetIdMva,
            )
            self.reweiMatchedCleanHistosId = PileupJetHistograms(
                "ReweiMatchedCleanHistosId",
                self.vtxBins,
                self.ptBins,
                self.etaBins,
                etalabels=self.puEtaLables,
                reweight=self.reweight,
                jetIdMva=self.cfg_ana.jetIdMva,
            )
            self.unmatchedCleanHistosId = PileupJetHistograms(
                "UnmatchedCleanHistosId",
                self.vtxBins,
                self.ptBins,
                self.etaBins,
                etalabels=self.puEtaLables,
                jetIdMva=self.cfg_ana.jetIdMva,
            )

        self.h_nvtx = TH1F("h_nvtx", "", 50, 0, 50)
        self.h_genjetspt = TH1F("h_genjetspt", "", 500, 0, 500)
        self.h_genjetspt2 = TH1F("h_genjetsptZOOM", "", 100, 0, 200)
        self.h_genjetspt_barrel = TH1F("h_genjetspt_barrel", "", 100, 0, 200)
        self.h_genjetspt_endtk = TH1F("h_genjetspt_endtk", "", 100, 0, 200)
        self.h_genjetspt_endNOtk = TH1F("h_genjetspt_endNOtk", "", 100, 0, 200)
        self.h_genjetspt_fwd = TH1F("h_genjetspt_fwd", "", 100, 0, 200)
        self.h_genjetspt_MR_barrel = TH1F("h_genjetspt_MatchedCleanReco_barrel", "", 100, 0, 200)
        self.h_genjetspt_MR_endtk = TH1F("h_genjetspt_MatchedCleanReco_endtk", "", 100, 0, 200)
        self.h_genjetspt_MR_endNOtk = TH1F("h_genjetspt_MatchedCleanReco_endNOtk", "", 100, 0, 200)
        self.h_genjetspt_MR_fwd = TH1F("h_genjetspt_MatchedCleanReco_fwd", "", 100, 0, 200)
        self.h_secondClosestVsPtratio = TH2F("h_secondClosestVsPtratio", "", 100, 0, 2, 100, 0, 6)
        self.h_avedistanceVSNvtx = TH2F("h_avedistanceVSNvtx", "", 50, 0, 50, 100, 0, 6)
        self.h_PTRatioVSgenEta = TH2F("h_PTRatioVSgenEta", "", 150, -5, 5, 100, 0, 2)
        self.h_PTRatioVSgenPt = TH2F("h_PTRatioVSgenPt", "", 200, 0, 100, 100, 0, 2)
        self.h_matchDR = TH1F("h_matchDR", "", 60, 0, 0.30)
        self.h_relPtVSmatchDR = TH2F("h_relPtVSmatchDR", "", 60, 0, 0.30, 100, 0, 2)
        self.h_relPtVSchFrac = TH2F("h_relPtVSchFrac", "", 100, 0, 1, 100, 0, 2)
예제 #2
0
    def beginLoop (self) :
        super (JetIDAnalyzer,self).beginLoop ()
        self.file = TFile ('/'.join ([self.looperName, 'testJets.root']),
                           'recreate')

        if self.cfg_ana.applyPFLooseId:
            from ROOT import PFJetIDSelectionFunctor 
            self.isPFLooseFunc = PFJetIDSelectionFunctor(0,PFJetIDSelectionFunctor.LOOSE)
            ## Workaround: for some reason PyROOT does not bind PFJetIDSelectionFunctor(Jet) nor PFJetIDSelectionFunctor.getBitsTemplates 
            from ROOT import pat        
            self.isPFLooseFunc.bits = pat.strbitset()
            for i in "CHF","NHF","CEF","NEF","NCH","nConstituents": self.isPFLooseFunc.bits.push_back(i) 
            ## /Workaround
            self.isPFLoose = lambda x : self.isPFLooseFunc(x,self.isPFLooseFunc.bits)
        else:
            self.isPFLoose = lambda x : True

        # general histograms
        self.jetHistos = JetHistograms ('Jets')
        self.cleanJetHistos = JetHistograms ('CleanJets')
        self.matchedCleanJetHistos = JetHistograms ('MatchedCleanJets')
        self.unmatchedCleanJetHistos = JetHistograms ('UnmatchedCleanJets')
        
        ## Pileup JetID
        if self.cfg_ana.jetIdMva:
            self.puidalgo = PileupJetIdNtupleAlgo(*self.cfg_ana.jetIdMva)
            self.runMva = True
        else:
            self.puidalgo = PileupJetIdNtupleAlgo()
            self.runMva = False
        
        self.vtxBins   = (0,10,15,20,30) ## (0,2,4,6,10,15,20,30,35)
        self.vtxBinLabels = mkBinLabels(self.vtxBins)
        self.ptBins    = (20,30,50) ## (20,30,40,50,100)
        self.etaBins   = (0,1.4,2.5,3.0)
        self.puEtaLables = ["_barrel","_endtk","_endNOtk","_fwd"]
        reweight_f = TF1("f","pol2(0)+expo(3)")
        reweight_f.SetParameters(0.1955298,-0.003830591,1.944794e-05,4.649755,-0.1722024)
        self.reweight = ("pt", reweight_f)

        ## PileUp histograms
        if self.cfg_ana.doJetIdHisto:
            # histograms for pileup jet identification variables
            
            self.gluCleanHistosId = PileupJetHistograms("GluonMatchedCleanHistosId",self.vtxBins,self.ptBins,self.etaBins,etalabels=self.puEtaLables,reweight=self.reweight)
            self.quarkCleanHistosId = PileupJetHistograms("QuarkMatchedCleanHistosId",self.vtxBins,self.ptBins,self.etaBins,etalabels=self.puEtaLables,reweight=self.reweight)
            self.reweiMatchedCleanHistosId = PileupJetHistograms("ReweiMatchedCleanHistosId",self.vtxBins,self.ptBins,self.etaBins,etalabels=self.puEtaLables,reweight=self.reweight)
            self.unmatchedCleanHistosId = PileupJetHistograms("UnmatchedCleanHistosId",self.vtxBins,self.ptBins,self.etaBins,etalabels=self.puEtaLables)

            
        ### self.jetKin = []
        ### for vtx in self.vtxBinLabels:
        ###     self.jetKin.append([])
        ###     for eta in self.puEtaLables:
        ###         self.jetKin[-1].append( JetHistograms('Jets%s%s' % (vtx,eta) ) )
        
        if self.cfg_ana.dumpTree:
            self.tree = TTree("tree","tree")
            self.tree.SetDirectory(self.file)

            self.puidalgo.bookBranches(self.tree)
            
            gROOT.ProcessLine("""struct MyTreeVars{ Int_t nvtx; Bool_t isMatched; Int_t jetFlavour; Float_t partonPt; Float_t genPt; Float_t genDr; }""")
            from ROOT import MyTreeVars
            self.treevars = MyTreeVars()
            
            for i,j in ("nvtx","I"),("isMatched","O"),("jetFlavour","I"),("partonPt","F"),("genPt","F"),("genDr","F"):
                self.tree.Branch(i,AddressOf(self.treevars,i),"%s/%s"%(i,j))
            
        self.h_nvtx = TH1F ("h_nvtx", "" ,50, 0, 50)
        self.h_genjetspt = TH1F ("h_genjetspt", "" ,500, 0, 500) ; 
예제 #3
0
class JetStudiesAnalyzer(Analyzer):
    """A simple jet analyzer for Pietro."""

    ### def __init__(self,cfg_ana, cfg_comp, looperName):
    ###     loadLibs()
    ###     super (JetStudiesAnalyzer, self).__init__(cfg_ana, cfg_comp, looperName)

    def declareHandles(self):
        super(JetStudiesAnalyzer, self).declareHandles()
        self.handles["jets"] = AutoHandle(*self.cfg_ana.jetCollection)
        if self.cfg_ana.useGenLeptons:
            self.mchandles["genParticlesPruned"] = AutoHandle(
                *self.cfg_ana.GenParticlesCollection
                #                'genParticlesPruned',
                #                'std::vector<reco::GenParticle>'
            )
        else:
            self.mchandles["genParticles"] = AutoHandle("prunedGen", "std::vector<reco::GenParticle>")

        self.mchandles["genJets"] = AutoHandle(*self.cfg_ana.genJetsCollection)
        self.handles["vertices"] = AutoHandle(
            *self.cfg_ana.VtxCollection
            #            'offlinePrimaryVertices',
            #            'std::vector<reco::Vertex>'
        )

    # .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....

    def beginLoop(self):
        super(JetStudiesAnalyzer, self).beginLoop()
        self.file = TFile("/".join([self.looperName, "testJets.root"]), "recreate")
        if self.cfg_ana.applyPFLooseId:
            from ROOT import PFJetIDSelectionFunctor

            self.isPFLooseFunc = PFJetIDSelectionFunctor(0, PFJetIDSelectionFunctor.LOOSE)
            ## Workaround: for some reason PyROOT does not bind nor PFJetIDSelectionFunctor(Jet)PFJetIDSelectionFunctor.getBitsTemplates
            from ROOT import pat

            self.isPFLooseFunc.bits = pat.strbitset()
            for i in "CHF", "NHF", "CEF", "NEF", "NCH", "nConstituents":
                self.isPFLooseFunc.bits.push_back(i)
            ## /Workaround
            self.isPFLoose = lambda x: self.isPFLooseFunc(x, self.isPFLooseFunc.bits)
        else:
            self.isPFLoose = lambda x: True

        # general histograms
        self.jetHistos = JetHistograms("Jets")
        self.cleanJetHistos = JetHistograms("CleanJets")
        self.cleanJetHistos_barrel = JetHistograms("CleanJets_barrel")
        self.cleanJetHistos_endtk = JetHistograms("CleanJets_endtk")
        self.cleanJetHistos_endNOtk = JetHistograms("CleanJets_endNOtk")
        self.cleanJetHistos_fwd = JetHistograms("CleanJets_fwd")
        self.matchedCleanJetHistos = JetHistograms("MatchedCleanJets")
        self.matchedCleanJetHistos_barrel = JetHistograms("MatchedCleanJets_barrel")
        self.matchedCleanJetHistos_endtk = JetHistograms("MatchedCleanJets_endtk")
        self.matchedCleanJetHistos_endNOtk = JetHistograms("MatchedCleanJets_endNOtk")
        self.matchedCleanJetHistos_fwd = JetHistograms("MatchedCleanJets_fwd")
        self.matchedCleanJetHistos_PtL = JetHistograms("MatchedCleanJets_ptLow")
        self.matchedCleanJetHistos_PtM = JetHistograms("MatchedCleanJets_ptMed")
        self.matchedCleanJetHistos_PtH = JetHistograms("MatchedCleanJets_ptHi")
        self.matchedCleanJetHistos_PtV = JetHistograms("MatchedCleanJets_ptVHi")
        self.LPtmatchedCleanJetHistos = JetHistograms("LPtMatchedCleanJets")
        self.HPtmatchedCleanJetHistos = JetHistograms("HPtMatchedCleanJets")
        self.unmatchedCleanJetHistos = JetHistograms("UnmatchedCleanJets")
        self.LPtUnmatchedCleanJetHistos = JetHistograms("LPtUnmatchedCleanJets")
        self.HPtUnmatchedCleanJetHistos = JetHistograms("HPtUnmatchedCleanJets")

        # histograms of the components fraction
        self.matchedCleanJetHistosComponents = FractionJetHistograms("MatchedCleanJetsCompontents")
        self.unmatchedCleanJetHistosComponents = FractionJetHistograms("UnmatchedCleanJetsCompontents")

        # histograms for the resolution of matched jets
        self.matchedCleanJetHistosResolution = ResolutionJetHistograms("MatchedCleanJetsResolution", 50, 1)
        self.matchedCleanJetHistosResolution_barrel = ResolutionJetHistograms(
            "MatchedCleanJetsResolution_barrel", 50, 1
        )
        self.matchedCleanJetHistosResolution_endtk = ResolutionJetHistograms("MatchedCleanJetsResolution_endtk", 50, 1)
        self.matchedCleanJetHistosResolution_endNOtk = ResolutionJetHistograms(
            "MatchedCleanJetsResolution_endNOtk", 50, 1
        )
        self.matchedCleanJetHistosResolution_fwd = ResolutionJetHistograms("MatchedCleanJetsResolution_fwd", 50, 1)
        # resolution of matched jets, all eta, bins of pt
        self.matchedCleanJetHistosResolution_PtL = ResolutionJetHistograms(
            "MatchedCleanJetsResolution_ptLow", 50, 1
        )  # <20
        self.matchedCleanJetHistosResolution_PtM = ResolutionJetHistograms(
            "MatchedCleanJetsResolution_ptMed", 50, 1
        )  # <40
        self.matchedCleanJetHistosResolution_PtH = ResolutionJetHistograms(
            "MatchedCleanJetsResolution_ptHi", 50, 1
        )  # <80
        self.matchedCleanJetHistosResolution_PtV = ResolutionJetHistograms(
            "MatchedCleanJetsResolution_ptVHi", 50, 1
        )  # >80

        self.doJetIdHisto = False
        if self.cfg_ana.doJetIdHisto:
            # histograms for pileup jet identification variables
            self.vtxBins = (0, 5, 10, 15, 20, 30)  ## (0,2,4,6,10,15,20,30,35)
            self.ptBins = (20, 30, 50)  ## (20,30,40,50,100)
            self.etaBins = (0, 1.4, 2.5, 3.0)
            self.puEtaLables = ["_barrel", "_endtk", "_endNOtk", "_fwd"]
            reweight_f = TF1("f", "pol2(0)+expo(3)")
            reweight_f.SetParameters(0.1955298, -0.003830591, 1.944794e-05, 4.649755, -0.1722024)
            self.reweight = ("pt", reweight_f)
            self.doJetIdHisto = True
            self.gluCleanHistosId = PileupJetHistograms(
                "GluonMatchedCleanHistosId",
                self.vtxBins,
                self.ptBins,
                self.etaBins,
                etalabels=self.puEtaLables,
                reweight=self.reweight,
                jetIdMva=self.cfg_ana.jetIdMva,
            )
            self.quarkCleanHistosId = PileupJetHistograms(
                "QuarkMatchedCleanHistosId",
                self.vtxBins,
                self.ptBins,
                self.etaBins,
                etalabels=self.puEtaLables,
                reweight=self.reweight,
                jetIdMva=self.cfg_ana.jetIdMva,
            )
            self.reweiMatchedCleanHistosId = PileupJetHistograms(
                "ReweiMatchedCleanHistosId",
                self.vtxBins,
                self.ptBins,
                self.etaBins,
                etalabels=self.puEtaLables,
                reweight=self.reweight,
                jetIdMva=self.cfg_ana.jetIdMva,
            )
            self.unmatchedCleanHistosId = PileupJetHistograms(
                "UnmatchedCleanHistosId",
                self.vtxBins,
                self.ptBins,
                self.etaBins,
                etalabels=self.puEtaLables,
                jetIdMva=self.cfg_ana.jetIdMva,
            )

        self.h_nvtx = TH1F("h_nvtx", "", 50, 0, 50)
        self.h_genjetspt = TH1F("h_genjetspt", "", 500, 0, 500)
        self.h_genjetspt2 = TH1F("h_genjetsptZOOM", "", 100, 0, 200)
        self.h_genjetspt_barrel = TH1F("h_genjetspt_barrel", "", 100, 0, 200)
        self.h_genjetspt_endtk = TH1F("h_genjetspt_endtk", "", 100, 0, 200)
        self.h_genjetspt_endNOtk = TH1F("h_genjetspt_endNOtk", "", 100, 0, 200)
        self.h_genjetspt_fwd = TH1F("h_genjetspt_fwd", "", 100, 0, 200)
        self.h_genjetspt_MR_barrel = TH1F("h_genjetspt_MatchedCleanReco_barrel", "", 100, 0, 200)
        self.h_genjetspt_MR_endtk = TH1F("h_genjetspt_MatchedCleanReco_endtk", "", 100, 0, 200)
        self.h_genjetspt_MR_endNOtk = TH1F("h_genjetspt_MatchedCleanReco_endNOtk", "", 100, 0, 200)
        self.h_genjetspt_MR_fwd = TH1F("h_genjetspt_MatchedCleanReco_fwd", "", 100, 0, 200)
        self.h_secondClosestVsPtratio = TH2F("h_secondClosestVsPtratio", "", 100, 0, 2, 100, 0, 6)
        self.h_avedistanceVSNvtx = TH2F("h_avedistanceVSNvtx", "", 50, 0, 50, 100, 0, 6)
        self.h_PTRatioVSgenEta = TH2F("h_PTRatioVSgenEta", "", 150, -5, 5, 100, 0, 2)
        self.h_PTRatioVSgenPt = TH2F("h_PTRatioVSgenPt", "", 200, 0, 100, 100, 0, 2)
        self.h_matchDR = TH1F("h_matchDR", "", 60, 0, 0.30)
        self.h_relPtVSmatchDR = TH2F("h_relPtVSmatchDR", "", 60, 0, 0.30, 100, 0, 2)
        self.h_relPtVSchFrac = TH2F("h_relPtVSchFrac", "", 100, 0, 1, 100, 0, 2)

    # .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
    def process(self, iEvent, event):
        # read all the handles defined beforehand
        self.readCollections(iEvent)

        jetEtaCut = 4.5

        # get the vertexes
        event.vertices = self.handles["vertices"].product()
        self.h_nvtx.Fill(len(event.vertices))
        event.vertexBin = int(len(event.vertices))

        # get the jets in the jets variable
        jets = self.handles["jets"].product()
        # filter jets with some selections
        event.jets = [
            jet
            for jet in jets
            if (abs(jet.eta()) < jetEtaCut and jet.pt() > self.cfg_ana.ptCut and self.isPFLoose(jet))
        ]
        self.jetHistos.fillEvent(event.jets)

        # get status 2 leptons
        if "genParticlesPruned" in self.mchandles:
            event.genLeptons = [
                lep
                for lep in self.mchandles["genParticlesPruned"].product()
                if lep.status() == 3 and (abs(lep.pdgId()) == 11 or abs(lep.pdgId()) == 13 or abs(lep.pdgId()) == 15)
            ]
        else:
            event.genLeptons = [
                lep
                for lep in self.mchandles["genParticles"].product()
                if lep.status() == 3 and (abs(lep.pdgId()) == 11 or abs(lep.pdgId()) == 13 or abs(lep.pdgId()) == 15)
            ]
        # @ Pasquale: why level 3 and not level 2?
        #        event.selGenLeptons = [GenParticle (lep) for lep in event.genLeptons if (lep.pt ()>self.cfg_ana.ptCut and abs (lep.eta ()) < jetEtaCut)]

        # get genJets
        event.genJets = map(GenJet, self.mchandles["genJets"].product())
        # filter genjets as for reco jets
        event.myGenJets = [GenJet(jet) for jet in event.genJets if (jet.pt() > self.cfg_ana.genPtCut)]
        event.selGenJets = cleanObjectCollection(event.myGenJets, event.genLeptons, 0.2)
        # event.selGenJets = event.genJets
        for jet in event.selGenJets:
            self.h_genjetspt.Fill(jet.pt())
            self.h_genjetspt2.Fill(jet.pt())
            if abs(jet.eta()) < 1.4:
                self.h_genjetspt_barrel.Fill(jet.pt())
            elif 1.6 < abs(jet.eta()) < 2.5:
                self.h_genjetspt_endtk.Fill(jet.pt())
            elif 2.6 < abs(jet.eta()) < 2.9:
                self.h_genjetspt_endNOtk.Fill(jet.pt())
            elif 3.1 < abs(jet.eta()):
                self.h_genjetspt_fwd.Fill(jet.pt())

        event.noNegJets = [jet for jet in event.jets if (jet.jecFactor(0) > 0)]

        # first stats plots
        # print 'genLeptons : ' + repr (len (event.genLeptons)) + ' | genJets : ' + repr (len (event.genJets)) + ' | recoJets : ' + repr (len (event.jets))
        self.jetHistos.fillStats(len(event.selGenJets), len(event.noNegJets))

        # FIXME why are there cases in which there's 4 or 6 leptons?
        if len(event.genLeptons) > 2:
            return
        # in case I want to filter out taus
        # 11, 13, 15 : e, u, T
        #        event.genOneLepton = [GenParticle (part) for part in event.genLeptons if abs (part.pdgId ()) == 15]
        # remove leptons from jets if closer than 0.2
        event.cleanJets = cleanObjectCollection(event.noNegJets, event.genLeptons, 0.2)
        self.cleanJetHistos.fillEvent(event.cleanJets)
        for jet in event.cleanJets:
            if abs(jet.eta()) < 1.4:
                self.cleanJetHistos_barrel.fillJet(jet)
            elif 1.6 < abs(jet.eta()) < 2.5:
                self.cleanJetHistos_endtk.fillJet(jet)
            elif 2.6 < abs(jet.eta()) < 2.9:
                self.cleanJetHistos_endNOtk.fillJet(jet)
            elif 3.1 < abs(jet.eta()):
                self.cleanJetHistos_fwd.fillJet(jet)

        #        print len (jets),len (event.jets), len (event.noNegJets), len (event.cleanJets), len (event.genLeptons),"-->",(len (event.noNegJets) - len (event.cleanJets) - len (event.genLeptons))

        event.matchingCleanJets = matchObjectCollection2(event.cleanJets, event.selGenJets, 0.25)
        # assign to each jet its gen match (easy life :))
        for jet in event.cleanJets:
            jet.gen = event.matchingCleanJets[jet]
        # FIXME next step might be to put this in the matching and remove the boolean flags

        self.cleanJetHistos.fillEvent(event.cleanJets)

        event.matchedCleanJets = [jet for jet in event.matchingCleanJets if jet.gen != None]
        event.cleanGluJets = []
        event.cleanQuarkJets = []
        for jet in event.matchedCleanJets:
            flav = abs(jet.partonFlavour())
            if flav == 21:
                event.cleanGluJets.append(jet)
            elif flav > 0 and flav <= 3:
                event.cleanQuarkJets.append(jet)

        event.LPtmatchedCleanJets = [jet for jet in event.matchingCleanJets if jet.gen != None and jet.pt() <= 30]
        event.HPtmatchedCleanJets = [jet for jet in event.matchingCleanJets if jet.gen != None and jet.pt() > 30]

        self.matchedCleanJetHistos.fillEvent(event.matchedCleanJets)
        self.LPtmatchedCleanJetHistos.fillEvent(event.LPtmatchedCleanJets)
        self.HPtmatchedCleanJetHistos.fillEvent(event.HPtmatchedCleanJets)

        event.unmatchedCleanJets = [jet for jet in event.matchingCleanJets if jet.gen == None]
        event.LPtunmatchedCleanJets = [jet for jet in event.matchingCleanJets if jet.gen == None and jet.pt() <= 30]
        event.HPtunmatchedCleanJets = [jet for jet in event.matchingCleanJets if jet.gen == None and jet.pt() > 30]

        self.unmatchedCleanJetHistos.fillEvent(event.unmatchedCleanJets)
        self.LPtUnmatchedCleanJetHistos.fillEvent(event.LPtunmatchedCleanJets)
        self.HPtUnmatchedCleanJetHistos.fillEvent(event.HPtunmatchedCleanJets)

        self.matchedCleanJetHistosComponents.fillEvent(event.matchedCleanJets)

        self.unmatchedCleanJetHistosComponents.fillEvent(event.unmatchedCleanJets)

        self.matchedCleanJetHistosResolution.fillEvent(event.matchedCleanJets, len(event.vertices))

        for jet in event.matchedCleanJets:
            if abs(jet.gen.eta()) < 1.4:
                self.matchedCleanJetHistosResolution_barrel.fillJet(jet, len(event.vertices))
                self.matchedCleanJetHistos_barrel.fillJet(jet)
            elif 1.6 < abs(jet.gen.eta()) < 2.5:
                self.matchedCleanJetHistosResolution_endtk.fillJet(jet, len(event.vertices))
                self.matchedCleanJetHistos_endtk.fillJet(jet)
            elif 2.6 < abs(jet.gen.eta()) < 2.9:
                self.matchedCleanJetHistosResolution_endNOtk.fillJet(jet, len(event.vertices))
                self.matchedCleanJetHistos_endNOtk.fillJet(jet)
            elif 3.1 < abs(jet.gen.eta()):
                self.matchedCleanJetHistosResolution_fwd.fillJet(jet, len(event.vertices))
                self.matchedCleanJetHistos_fwd.fillJet(jet)

        # PG debugging for tails
        #         for jet in event.matchedCleanJets :
        #             minDelta = 10
        #             secondClosest = jet
        #             for recojet in event.cleanJets :
        #                 if recojet == jet :
        #                     continue
        #                 dr2 = deltaR2( jet.gen.eta (), jet.gen.phi (), recojet.eta (), recojet.phi ())
        #                 if dr2 < minDelta :
        #                     minDelta = dr2
        #                     secondClosest = recojet
        #             if len(event.vertices) < 10 or abs (jet.gen.eta ()) < 1.6: continue
        #             self.h_secondClosestVsPtratio.Fill (jet.pt () / jet.gen.pt (), math.sqrt (minDelta))
        #             #if (jet.pt () / jet.gen.pt () < 0.2) :
        #                 #print '------------'
        #                 #print jet.pt (), jet.eta (), jet.phi ()
        #                 #print jet.gen.pt (), jet.gen.eta (), jet.gen.phi ()
        #                 #print 'second reco closest to gen at distance', minDelta

        #         aveDeltaR = 0
        #         num = 0
        #         for recojet1 in event.cleanJets :
        #             minDelta = 10
        #             closest = recojet1
        #             for recojet2 in event.cleanJets :
        #                 if recojet1 == recojet2 : continue
        #                     dr2 = deltaR2( recojet1.eta (), recojet1.phi (), recojet2.eta (), recojet2.phi ())
        #                     if dr2 < minDelta :
        #                         minDelta = dr2
        #                         closest = recojet2
        #             if minDelta == 10 continue ;
        #             aveDeltaR = aveDeltaR + math.sqrt (minDelta)
        #             num = num + 1
        #         if num > 0 :
        #             aveDeltaR = aveDeltaR / num
        #            self.h_avedistanceVSNvtx.Fill (len(event.vertices), aveDeltaR)

        # AB: fill eta-dependent responses (in bins of gen pt)
        for jet in event.matchedCleanJets:
            if abs(jet.gen.pt()) < 20.0:
                self.matchedCleanJetHistosResolution_PtL.fillJet(jet, len(event.vertices))
                self.matchedCleanJetHistos_PtL.fillJet(jet)
            elif 20.0 < abs(jet.gen.pt()) < 40.0:
                self.matchedCleanJetHistosResolution_PtM.fillJet(jet, len(event.vertices))
                self.matchedCleanJetHistos_PtM.fillJet(jet)
            elif 40.0 < abs(jet.gen.pt()) < 80.0:
                self.matchedCleanJetHistosResolution_PtH.fillJet(jet, len(event.vertices))
                self.matchedCleanJetHistos_PtH.fillJet(jet)
            elif 80.0 < abs(jet.gen.pt()):
                self.matchedCleanJetHistosResolution_PtV.fillJet(jet, len(event.vertices))
                self.matchedCleanJetHistos_PtV.fillJet(jet)

        if self.doJetIdHisto:
            self.gluCleanHistosId.fillEvent(event.cleanGluJets, event.vertices)
            self.quarkCleanHistosId.fillEvent(event.cleanQuarkJets, event.vertices)
            ### self.matchedCleanHistosId.fillEvent(event.matchedCleanJets,event.vertices)
            self.reweiMatchedCleanHistosId.fillEvent(event.matchedCleanJets, event.vertices)
            self.unmatchedCleanHistosId.fillEvent(event.unmatchedCleanJets, event.vertices)

    # .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....

    def write(self):
        from ROOT import gROOT

        gROOT.SetBatch(True)
        self.jetHistos.Write(self.file)
        self.cleanJetHistos.Write(self.file)
        self.cleanJetHistos_barrel.Write(self.file)
        self.cleanJetHistos_endtk.Write(self.file)
        self.cleanJetHistos_endNOtk.Write(self.file)
        self.cleanJetHistos_fwd.Write(self.file)
        self.matchedCleanJetHistos.Write(self.file)
        self.matchedCleanJetHistos_barrel.Write(self.file)
        self.matchedCleanJetHistos_endtk.Write(self.file)
        self.matchedCleanJetHistos_endNOtk.Write(self.file)
        self.matchedCleanJetHistos_fwd.Write(self.file)

        self.matchedCleanJetHistos_PtL.Write(self.file)
        self.matchedCleanJetHistos_PtM.Write(self.file)
        self.matchedCleanJetHistos_PtH.Write(self.file)
        self.matchedCleanJetHistos_PtV.Write(self.file)

        self.LPtmatchedCleanJetHistos.Write(self.file)
        self.HPtmatchedCleanJetHistos.Write(self.file)
        self.LPtUnmatchedCleanJetHistos.Write(self.file)
        self.HPtUnmatchedCleanJetHistos.Write(self.file)

        self.unmatchedCleanJetHistos.Write(self.file)

        self.matchedCleanJetHistosComponents.summary()
        self.matchedCleanJetHistosComponents.Write(self.file)
        self.unmatchedCleanJetHistosComponents.summary()
        self.unmatchedCleanJetHistosComponents.Write(self.file)

        self.matchedCleanJetHistosResolution.summary()
        self.matchedCleanJetHistosResolution.Write(self.file)

        self.matchedCleanJetHistosResolution_barrel.summary()
        self.matchedCleanJetHistosResolution_barrel.Write(self.file)

        self.matchedCleanJetHistosResolution_endtk.summary()
        self.matchedCleanJetHistosResolution_endtk.Write(self.file)

        self.matchedCleanJetHistosResolution_endNOtk.summary()
        self.matchedCleanJetHistosResolution_endNOtk.Write(self.file)

        self.matchedCleanJetHistosResolution_fwd.summary()
        self.matchedCleanJetHistosResolution_fwd.Write(self.file)

        self.matchedCleanJetHistosResolution_PtL.summary()
        self.matchedCleanJetHistosResolution_PtL.Write(self.file)

        self.matchedCleanJetHistosResolution_PtM.summary()
        self.matchedCleanJetHistosResolution_PtM.Write(self.file)

        self.matchedCleanJetHistosResolution_PtH.summary()
        self.matchedCleanJetHistosResolution_PtH.Write(self.file)

        self.matchedCleanJetHistosResolution_PtV.summary()
        self.matchedCleanJetHistosResolution_PtV.Write(self.file)

        if self.doJetIdHisto:
            self.gluCleanHistosId.summary()
            self.gluCleanHistosId.Write(self.file)

            self.quarkCleanHistosId.summary()
            self.quarkCleanHistosId.Write(self.file)

            self.reweiMatchedCleanHistosId.summary()
            self.reweiMatchedCleanHistosId.Write(self.file)

            ### self.matchedCleanHistosId.Write(self.file)
            self.unmatchedCleanHistosId.Write(self.file)

        self.file.cd()
        self.h_nvtx.Write()
        self.h_genjetspt.Write()
        self.h_genjetspt2.Write()
        self.h_genjetspt_barrel.Write()
        self.h_genjetspt_endtk.Write()
        self.h_genjetspt_endNOtk.Write()
        self.h_genjetspt_fwd.Write()
        self.h_genjetspt_MR_barrel.Write()
        self.h_genjetspt_MR_endtk.Write()
        self.h_genjetspt_MR_endNOtk.Write()
        self.h_genjetspt_MR_fwd.Write()
        self.h_secondClosestVsPtratio.Write()
        self.h_avedistanceVSNvtx.Write()
        self.h_PTRatioVSgenEta.Write()
        self.h_PTRatioVSgenPt.Write()
        self.h_matchDR.Write()
        self.h_relPtVSmatchDR.Write()
        self.h_relPtVSchFrac.Write()
        self.file.Close()
예제 #4
0
def main(options,args):
    
    from ROOT import TFile, TChain, gROOT, TF1, TH1, TGraph
    from CMGTools.RootTools.statistics.Histograms import Histograms
    from CMGTools.RootTools.utils.PileupJetHistograms import PileupJetHistograms, mkBinLabels, findBin
    from CMGTools.RootTools.analyzers.SimpleJetAnalyzer import ResolutionJetHistograms, FractionJetHistograms, JetHistograms

    ## customize the histograms filled by PileupJetHistograms
    if options.customPrototypes:
        PileupJetHistograms.prototypes={
            "d0"         : ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s","cm",100,0,2),
            "dZ"         : ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s","cm",100,0,10),
            
            "beta"         : ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s","",200,0,1.),
            "betaStar"     : ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s","",200,0,1.),
            "nParticles" : ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",50,0,50),
 
            "dRMean"     :("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",50,0,0.5),
            "dR2Mean"     :("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",50,0,0.25),
            
            "etaW"   :("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",50,0,0.5),
            "phiW"   :("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",50,0,0.5),
            "majW"   :("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",50,0,0.5),
            "minW"   :("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",50,0,0.5),
            "jetW"   :("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",50,0,0.5),
            
            "jetPt"      : ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s","GeV/c",300,0,150),
            "jetEta"     : ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",101,-5.05,5.05,),
            
            "nvtx"     : ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",50,.5,50.5),
            
            }
        if options.mvas != "":
            for mva in options.mvas.split(","):
                PileupJetHistograms.prototypes[mva] = ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",400,-1.,1.)
        if options.customPrototypes:
            PileupJetHistograms.prototypes["mva"] = ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",400,-1.,1.)

    
    ## cuts and binning
    genDrCut = 0.3
    genPtCut = 0.
    genDrAntiCut = 0.2

    vtxBins   = (1,10,20)
    ptBins    = (0,10,20,25,30,40,50)
    if options.inclusive:
            vtxBins   = (0,100)
            ptBins    = (0,20)
    vtxBinLabels = mkBinLabels(vtxBins)

    etaBins   = (0,2.5,2.75,3.0)
    puEtaLables = ["_TK","_HEin","_HEout","_HF"]

    ### etaBins   = (0,2.5,3.0)
    ### puEtaLables = ["_central","_endNOtk","_fwd"]
    
    reweight_f = TF1("f","pol2(0)+expo(3)")
    reweight_f.SetParameters(0.1955298,-0.003830591,1.944794e-05,4.649755,-0.1722024)
    reweight = ("jetPt", reweight_f)

    ## book histograms
    fout = TFile.Open(options.outfile,"recreate")
    fout.cd()

    if options.tmva:
        sig = PileupJetHistograms("signal",vtxBins,ptBins,etaBins,etalabels=puEtaLables,reweight=reweight)
        bkg = PileupJetHistograms("background",vtxBins,ptBins,etaBins,etalabels=puEtaLables,reweight=reweight)
    else:
        matchedCleanJetHistos = JetHistograms ('MatchedCleanJets')
        unmatchedCleanJetHistos = JetHistograms ('UnmatchedCleanJets')
        
        gluCleanHistosId = PileupJetHistograms("GluonMatchedCleanHistosId",vtxBins,ptBins,etaBins,etalabels=puEtaLables,reweight=reweight)
        quarkCleanHistosId = PileupJetHistograms("QuarkMatchedCleanHistosId",vtxBins,ptBins,etaBins,etalabels=puEtaLables,reweight=reweight)
        reweiMatchedCleanHistosId = PileupJetHistograms("ReweiMatchedCleanHistosId",vtxBins,ptBins,etaBins,etalabels=puEtaLables,reweight=reweight)
        unmatchedCleanHistosId = PileupJetHistograms("UnmatchedCleanHistosId",vtxBins,ptBins,etaBins,etalabels=puEtaLables)

    ## create TChain and MakeClass
    if "," in options.indir:
        files = []
        for d in options.indir.split(","):
            files += getListOfFiles( d, options.filePattern)
    else:
        files = getListOfFiles( options.indir, options.filePattern)
    print files
    chain = mkChain(files,options.treename)
    if options.tmva:
        tr    = mkReader(chain,True,"tmva_reader")
    else:
        tr    = mkReader(chain,options.redoReader)
    
    ## Loop over ntuples
    nentries = chain.GetEntries()
    print "Reading %d entries" % nentries
    for i in xrange(nentries):
        if i % 1000 == 0:
            print>> sys.stderr, "Entry %d (%1.0f%%)\r" % (i, float(i) / nentries * 100.),
        tr.GetEntry(i)

        ## TMVA training/test tree
        if options.tmva:
            if tr.classID == 0:
                ## tr.weight = tr.sigwei
                tr.weight = 1.
                sig.fillRootTuple(tr)
            else:
                tr.weight = 1.
                ## tr.weight = tr.bkgwei
                bkg.fillRootTuple(tr)
                
        ## Original ntuples
        else:
            if not tr.jetLooseID or tr.jetPt < 20.:
                continue
            
            if options.forceFlavour != 0:
                tr.jetFlavour = options.forceFlavour
            
            ## tr.weight = reweight[1](getattr(tr,reweight[0]))
            tr.weight = 1.
            
            if tr.isMatched and tr.jetGenDr < 0.3 and ( tr.jetGenPt > 10 or tr.jetGenPt/tr.jetPt > 0.7 ):
                reweiMatchedCleanHistosId.fillRootTuple(tr)
                matchedCleanJetHistos.fillRootTuple(tr)
                if abs(tr.jetFlavour) == 21:
                    gluCleanHistosId.fillRootTuple(tr)
                elif abs(tr.jetFlavour) <=3 and abs(tr.jetFlavour) !=0:
                    quarkCleanHistosId.fillRootTuple(tr)

            elif not tr.isMatched or ( tr.jetGenDr > 0.3 and tr.jetGenPt/tr.jetPt < 0.7 and tr.jetGenPt < 10 ):
                unmatchedCleanJetHistos.fillRootTuple(tr)
                unmatchedCleanHistosId.fillRootTuple(tr)

    ## Write out histograms
    for name,obj in locals().iteritems():
        if isinstance(obj,Histograms):
            obj.Write(fout)
        elif isinstance(obj,TH1) or isinstance(obj,TGraph):
            fout.cd()
            obj.Write()
        
    fout.Close()
예제 #5
0
class JetIDAnalyzer (Analyzer) :
    '''A simple jet analyzer.'''
    
    def declareHandles (self) :
        super (JetIDAnalyzer, self).declareHandles ()
        self.handles['jets'] =  AutoHandle (
            *self.cfg_ana.jetCollection
            )
        if self.cfg_ana.useGenLeptons: 
            self.mchandles['leptons2'] =  AutoHandle (
                'genLeptonsStatus2',
                'std::vector<reco::GenParticle>'
                )
        else:
            self.mchandles['genParticles'] =  AutoHandle (
                'prunedGen',
                'std::vector<reco::GenParticle>'
                )
            
        ### self.mchandles['genJets'] =  AutoHandle (
        ###     *self.cfg_ana.genJetsCollection
        ###    )
        self.handles['vertices'] =  AutoHandle (
            'offlinePrimaryVertices',
            'std::vector<reco::Vertex>'
          )

# .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....

    def beginLoop (self) :
        super (JetIDAnalyzer,self).beginLoop ()
        self.file = TFile ('/'.join ([self.looperName, 'testJets.root']),
                           'recreate')

        if self.cfg_ana.applyPFLooseId:
            from ROOT import PFJetIDSelectionFunctor 
            self.isPFLooseFunc = PFJetIDSelectionFunctor(0,PFJetIDSelectionFunctor.LOOSE)
            ## Workaround: for some reason PyROOT does not bind PFJetIDSelectionFunctor(Jet) nor PFJetIDSelectionFunctor.getBitsTemplates 
            from ROOT import pat        
            self.isPFLooseFunc.bits = pat.strbitset()
            for i in "CHF","NHF","CEF","NEF","NCH","nConstituents": self.isPFLooseFunc.bits.push_back(i) 
            ## /Workaround
            self.isPFLoose = lambda x : self.isPFLooseFunc(x,self.isPFLooseFunc.bits)
        else:
            self.isPFLoose = lambda x : True

        # general histograms
        self.jetHistos = JetHistograms ('Jets')
        self.cleanJetHistos = JetHistograms ('CleanJets')
        self.matchedCleanJetHistos = JetHistograms ('MatchedCleanJets')
        self.unmatchedCleanJetHistos = JetHistograms ('UnmatchedCleanJets')
        
        ## Pileup JetID
        if self.cfg_ana.jetIdMva:
            self.puidalgo = PileupJetIdNtupleAlgo(*self.cfg_ana.jetIdMva)
            self.runMva = True
        else:
            self.puidalgo = PileupJetIdNtupleAlgo()
            self.runMva = False
        
        self.vtxBins   = (0,10,15,20,30) ## (0,2,4,6,10,15,20,30,35)
        self.vtxBinLabels = mkBinLabels(self.vtxBins)
        self.ptBins    = (20,30,50) ## (20,30,40,50,100)
        self.etaBins   = (0,1.4,2.5,3.0)
        self.puEtaLables = ["_barrel","_endtk","_endNOtk","_fwd"]
        reweight_f = TF1("f","pol2(0)+expo(3)")
        reweight_f.SetParameters(0.1955298,-0.003830591,1.944794e-05,4.649755,-0.1722024)
        self.reweight = ("pt", reweight_f)

        ## PileUp histograms
        if self.cfg_ana.doJetIdHisto:
            # histograms for pileup jet identification variables
            
            self.gluCleanHistosId = PileupJetHistograms("GluonMatchedCleanHistosId",self.vtxBins,self.ptBins,self.etaBins,etalabels=self.puEtaLables,reweight=self.reweight)
            self.quarkCleanHistosId = PileupJetHistograms("QuarkMatchedCleanHistosId",self.vtxBins,self.ptBins,self.etaBins,etalabels=self.puEtaLables,reweight=self.reweight)
            self.reweiMatchedCleanHistosId = PileupJetHistograms("ReweiMatchedCleanHistosId",self.vtxBins,self.ptBins,self.etaBins,etalabels=self.puEtaLables,reweight=self.reweight)
            self.unmatchedCleanHistosId = PileupJetHistograms("UnmatchedCleanHistosId",self.vtxBins,self.ptBins,self.etaBins,etalabels=self.puEtaLables)

            
        ### self.jetKin = []
        ### for vtx in self.vtxBinLabels:
        ###     self.jetKin.append([])
        ###     for eta in self.puEtaLables:
        ###         self.jetKin[-1].append( JetHistograms('Jets%s%s' % (vtx,eta) ) )
        
        if self.cfg_ana.dumpTree:
            self.tree = TTree("tree","tree")
            self.tree.SetDirectory(self.file)

            self.puidalgo.bookBranches(self.tree)
            
            gROOT.ProcessLine("""struct MyTreeVars{ Int_t nvtx; Bool_t isMatched; Int_t jetFlavour; Float_t partonPt; Float_t genPt; Float_t genDr; }""")
            from ROOT import MyTreeVars
            self.treevars = MyTreeVars()
            
            for i,j in ("nvtx","I"),("isMatched","O"),("jetFlavour","I"),("partonPt","F"),("genPt","F"),("genDr","F"):
                self.tree.Branch(i,AddressOf(self.treevars,i),"%s/%s"%(i,j))
            
        self.h_nvtx = TH1F ("h_nvtx", "" ,50, 0, 50)
        self.h_genjetspt = TH1F ("h_genjetspt", "" ,500, 0, 500) ; 
        

# .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
    def process (self, iEvent, event) :
        #read all the handles defined beforehand
        self.readCollections (iEvent)
        
        jetEtaCut = 4.5 
        
        # get the vertexes
        event.vertices = self.handles['vertices'].product ()
        self.h_nvtx.Fill (len (event.vertices))
        event.vertexBin = int (len (event.vertices))
        
        # get the jets in the jets variable
        jets = self.handles['jets'].product ()
        # filter jets with some selections
        event.jets = [ jet for jet in jets if ( abs(jet.eta()) < jetEtaCut and jet.pt()>self.cfg_ana.ptCut and self.isPFLoose(jet) ) ]
        self.jetHistos.fillEvent (event.jets)
        
        try:
            # get status 2 leptons
            if 'leptons2' in self.mchandles:
                event.genLeptons = map (GenParticle, self.mchandles['leptons2'].product ())
            else:
                event.genLeptons = [ lep for lep in self.mchandles['genParticles'].product() if lep.status() == 3 and (abs(lep.pdgId()) == 11 or abs(lep.pdgId()) == 13 or abs(lep.pdgId()) == 15) ]  
        except:
            event.genLeptons = None

        if event.genLeptons:
        #FIXME why are there cases in which there's 4 or 6 leptons?
            if len (event.genLeptons) != 2 :
                return
            # in case I want to filter out taus
            # 11, 13, 15 : e, u, T
            # remove leptons from jets if closer than 0.2
            event.cleanJets = cleanObjectCollection (event.jets, event.genLeptons, 0.2)
        else:
            event.cleanJets = event.jets
            
        ### event.matchingCleanJets = matchObjectCollection2 (event.cleanJets, event.selGenJets, 0.25)
        # assign to each jet its gen match (easy life :))
        event.selGenJets = []
        for jet in event.cleanJets :
            try:
                jet.gen = jet.genJet()
                jet.gen.pt()
                event.selGenJets.append(jet.gen) 
            except:
                jet.gen = None

        for jet in event.selGenJets : 
            self.h_genjetspt.Fill (jet.pt ())
        self.jetHistos.fillStats (len (event.selGenJets), len (event.jets))
        
        ### try:
        ###     # get genJets
        ###     event.genJets = map (GenJet, self.mchandles['genJets'].product ())
        ###     event.selGenJets = event.genJets
        ###     for jet in event.selGenJets : 
        ###         self.h_genjetspt.Fill (jet.pt ())
        ###         
        ###     # first stats plots
        ###     self.jetHistos.fillStats (len (event.selGenJets), len (event.jets))
        ### except:
        ###     pass
           

        ## run the PileupJetIdAlgo and attach the id to the jet
        ijet = 0
        for jet in event.cleanJets:
            try:
                jet.puIdentifier = self.puidalgo.computeIdVariables(jet.sourcePtr().get(),0.,event.vertices[0],self.runMva)
            except:
                jet.puIdentifier = self.puidalgo.computeIdVariables(jet,0.,event.vertices[0],self.runMva)
            if self.cfg_ana.dumpTree:
                ## self.puidalgo.fillJet(jet.puIdentifier,ijet,0)
                self.puidalgo.setIJetIEvent(ijet,0)
                self.treevars.nvtx = len(event.vertices)
                self.treevars.isMatched = False
                self.treevars.jetFlavour = -999
                self.treevars.genPt = 0.
                self.treevars.partonPt = 0.
                self.treevars.genDr = -100.
                if jet.gen:
                    self.treevars.isMatched  = True
                    self.treevars.jetFlavour = jet.partonFlavour()
                    self.treevars.genPt = jet.gen.pt()
                    self.treevars.genDr = deltaR(jet.gen.eta(),jet.gen.phi(),jet.eta(),jet.phi())
                    try:
                        self.treevars.partonPt = jet.genParton.pt()
                    except:
                        pass
                self.tree.Fill()
            ijet += 1

        self.cleanJetHistos.fillEvent (event.cleanJets)
        
        event.matchedCleanJets = [jet for jet in event.cleanJets if jet.gen != None]

        event.unmatchedCleanJets = [jet for jet in event.cleanJets if jet.gen == None]
        self.matchedCleanJetHistos.fillEvent (event.matchedCleanJets)
        self.unmatchedCleanJetHistos.fillEvent (event.unmatchedCleanJets)

        event.cleanGluJets = []
        event.cleanQuarkJets = []
        vtxbin = findBin(self.vtxBinLabels,len(event.vertices))
        for jet in event.matchedCleanJets:
            flav = abs(jet.partonFlavour()) 
            if flav == 21:
                event.cleanGluJets.append(jet)
            elif flav > 0 and flav <= 3:
                event.cleanQuarkJets.append(jet)
            jet.weight = self.reweight[1](getattr(jet,self.reweight[0])())
            etabin = findBin(self.etaBins,jet.eta())
            ### self.jetKin[vtxbin][etabin].fillJet(jet)

        if self.cfg_ana.doJetIdHisto:
            self.gluCleanHistosId.fillEvent(event.cleanGluJets,event.vertices)
            self.quarkCleanHistosId.fillEvent(event.cleanQuarkJets,event.vertices)
            ### self.matchedCleanHistosId.fillEvent(event.matchedCleanJets,event.vertices)
            self.reweiMatchedCleanHistosId.fillEvent(event.matchedCleanJets,event.vertices)
            self.unmatchedCleanHistosId.fillEvent(event.unmatchedCleanJets,event.vertices)
        
        
            

# .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....

    def write (self):
        from ROOT import gROOT
        gROOT.SetBatch(True)

        self.jetHistos.Write (self.file)
        self.cleanJetHistos.Write (self.file)
        
        self.matchedCleanJetHistos.Write (self.file)
        self.unmatchedCleanJetHistos.Write (self.file)

        if self.cfg_ana.doJetIdHisto:
            self.gluCleanHistosId.summary()
            self.gluCleanHistosId.Write(self.file)
            
            self.quarkCleanHistosId.summary()
            self.quarkCleanHistosId.Write(self.file)
            
            self.reweiMatchedCleanHistosId.summary()
            self.reweiMatchedCleanHistosId.Write(self.file)
        
            ### self.matchedCleanHistosId.Write(self.file)
            self.unmatchedCleanHistosId.Write(self.file)
        
        ### for j in self.jetKin:
        ###     for h in j:
        ###         h.Write(self.file)
                
        self.file.cd ()
        self.h_nvtx.Write ()
        self.h_genjetspt.Write ()
        
        if self.cfg_ana.dumpTree:
            self.tree.Write()
        
        self.file.Close()
예제 #6
0
def main(options, args):

    from ROOT import TFile, TChain, gROOT, TF1, TH1, TGraph
    from CMGTools.RootTools.statistics.Histograms import Histograms
    from CMGTools.RootTools.utils.PileupJetHistograms import PileupJetHistograms, mkBinLabels, findBin
    from CMGTools.RootTools.analyzers.SimpleJetAnalyzer import ResolutionJetHistograms, FractionJetHistograms, JetHistograms

    ## customize the histograms filled by PileupJetHistograms
    if options.customPrototypes:
        PileupJetHistograms.prototypes = {
            "d0":
            ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",
             "cm", 100, 0, 2),
            "dZ":
            ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",
             "cm", 100, 0, 10),
            "beta":
            ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",
             "", 200, 0, 1.),
            "betaStar":
            ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",
             "", 200, 0, 1.),
            "nParticles":
            ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",
             50, 0, 50),
            "dRMean":
            ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",
             50, 0, 0.5),
            "dR2Mean":
            ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",
             50, 0, 0.25),
            "etaW":
            ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",
             50, 0, 0.5),
            "phiW":
            ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",
             50, 0, 0.5),
            "majW":
            ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",
             50, 0, 0.5),
            "minW":
            ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",
             50, 0, 0.5),
            "jetW":
            ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",
             50, 0, 0.5),
            "jetPt":
            ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",
             "GeV/c", 300, 0, 150),
            "jetEta": (
                "%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",
                101,
                -5.05,
                5.05,
            ),
            "nvtx":
            ("%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",
             50, .5, 50.5),
        }
        if options.mvas != "":
            for mva in options.mvas.split(","):
                PileupJetHistograms.prototypes[mva] = (
                    "%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",
                    400, -1., 1.)
        if options.customPrototypes:
            PileupJetHistograms.prototypes["mva"] = (
                "%(name)s %(hname)s%(jetbin)s;%(hname)s %(unitx)s;Jets %(unity)s",
                400, -1., 1.)

    ## cuts and binning
    genDrCut = 0.3
    genPtCut = 0.
    genDrAntiCut = 0.2

    vtxBins = (1, 10, 20)
    ptBins = (0, 10, 20, 25, 30, 40, 50)
    if options.inclusive:
        vtxBins = (0, 100)
        ptBins = (0, 20)
    vtxBinLabels = mkBinLabels(vtxBins)

    etaBins = (0, 2.5, 2.75, 3.0)
    puEtaLables = ["_TK", "_HEin", "_HEout", "_HF"]

    ### etaBins   = (0,2.5,3.0)
    ### puEtaLables = ["_central","_endNOtk","_fwd"]

    reweight_f = TF1("f", "pol2(0)+expo(3)")
    reweight_f.SetParameters(0.1955298, -0.003830591, 1.944794e-05, 4.649755,
                             -0.1722024)
    reweight = ("jetPt", reweight_f)

    ## book histograms
    fout = TFile.Open(options.outfile, "recreate")
    fout.cd()

    if options.tmva:
        sig = PileupJetHistograms("signal",
                                  vtxBins,
                                  ptBins,
                                  etaBins,
                                  etalabels=puEtaLables,
                                  reweight=reweight)
        bkg = PileupJetHistograms("background",
                                  vtxBins,
                                  ptBins,
                                  etaBins,
                                  etalabels=puEtaLables,
                                  reweight=reweight)
    else:
        matchedCleanJetHistos = JetHistograms('MatchedCleanJets')
        unmatchedCleanJetHistos = JetHistograms('UnmatchedCleanJets')

        gluCleanHistosId = PileupJetHistograms("GluonMatchedCleanHistosId",
                                               vtxBins,
                                               ptBins,
                                               etaBins,
                                               etalabels=puEtaLables,
                                               reweight=reweight)
        quarkCleanHistosId = PileupJetHistograms("QuarkMatchedCleanHistosId",
                                                 vtxBins,
                                                 ptBins,
                                                 etaBins,
                                                 etalabels=puEtaLables,
                                                 reweight=reweight)
        reweiMatchedCleanHistosId = PileupJetHistograms(
            "ReweiMatchedCleanHistosId",
            vtxBins,
            ptBins,
            etaBins,
            etalabels=puEtaLables,
            reweight=reweight)
        unmatchedCleanHistosId = PileupJetHistograms("UnmatchedCleanHistosId",
                                                     vtxBins,
                                                     ptBins,
                                                     etaBins,
                                                     etalabels=puEtaLables)

    ## create TChain and MakeClass
    if "," in options.indir:
        files = []
        for d in options.indir.split(","):
            files += getListOfFiles(d, options.filePattern)
    else:
        files = getListOfFiles(options.indir, options.filePattern)
    print files
    chain = mkChain(files, options.treename)
    if options.tmva:
        tr = mkReader(chain, True, "tmva_reader")
    else:
        tr = mkReader(chain, options.redoReader)

    ## Loop over ntuples
    nentries = chain.GetEntries()
    print "Reading %d entries" % nentries
    for i in xrange(nentries):
        if i % 1000 == 0:
            print >> sys.stderr, "Entry %d (%1.0f%%)\r" % (i, float(i) /
                                                           nentries * 100.),
        tr.GetEntry(i)

        ## TMVA training/test tree
        if options.tmva:
            if tr.classID == 0:
                ## tr.weight = tr.sigwei
                tr.weight = 1.
                sig.fillRootTuple(tr)
            else:
                tr.weight = 1.
                ## tr.weight = tr.bkgwei
                bkg.fillRootTuple(tr)

        ## Original ntuples
        else:
            if not tr.jetLooseID or tr.jetPt < 20.:
                continue

            if options.forceFlavour != 0:
                tr.jetFlavour = options.forceFlavour

            ## tr.weight = reweight[1](getattr(tr,reweight[0]))
            tr.weight = 1.

            if tr.isMatched and tr.jetGenDr < 0.3 and (
                    tr.jetGenPt > 10 or tr.jetGenPt / tr.jetPt > 0.7):
                reweiMatchedCleanHistosId.fillRootTuple(tr)
                matchedCleanJetHistos.fillRootTuple(tr)
                if abs(tr.jetFlavour) == 21:
                    gluCleanHistosId.fillRootTuple(tr)
                elif abs(tr.jetFlavour) <= 3 and abs(tr.jetFlavour) != 0:
                    quarkCleanHistosId.fillRootTuple(tr)

            elif not tr.isMatched or (tr.jetGenDr > 0.3
                                      and tr.jetGenPt / tr.jetPt < 0.7
                                      and tr.jetGenPt < 10):
                unmatchedCleanJetHistos.fillRootTuple(tr)
                unmatchedCleanHistosId.fillRootTuple(tr)

    ## Write out histograms
    for name, obj in locals().iteritems():
        if isinstance(obj, Histograms):
            obj.Write(fout)
        elif isinstance(obj, TH1) or isinstance(obj, TGraph):
            fout.cd()
            obj.Write()

    fout.Close()
예제 #7
0
    def beginLoop(self):
        super(JetIDAnalyzer, self).beginLoop()
        self.file = TFile('/'.join([self.looperName, 'testJets.root']),
                          'recreate')

        if self.cfg_ana.applyPFLooseId:
            from ROOT import PFJetIDSelectionFunctor
            self.isPFLooseFunc = PFJetIDSelectionFunctor(
                0, PFJetIDSelectionFunctor.LOOSE)
            ## Workaround: for some reason PyROOT does not bind PFJetIDSelectionFunctor(Jet) nor PFJetIDSelectionFunctor.getBitsTemplates
            from ROOT import pat
            self.isPFLooseFunc.bits = pat.strbitset()
            for i in "CHF", "NHF", "CEF", "NEF", "NCH", "nConstituents":
                self.isPFLooseFunc.bits.push_back(i)
            ## /Workaround
            self.isPFLoose = lambda x: self.isPFLooseFunc(
                x, self.isPFLooseFunc.bits)
        else:
            self.isPFLoose = lambda x: True

        # general histograms
        self.jetHistos = JetHistograms('Jets')
        self.cleanJetHistos = JetHistograms('CleanJets')
        self.matchedCleanJetHistos = JetHistograms('MatchedCleanJets')
        self.unmatchedCleanJetHistos = JetHistograms('UnmatchedCleanJets')

        ## Pileup JetID
        if self.cfg_ana.jetIdMva:
            self.puidalgo = PileupJetIdNtupleAlgo(*self.cfg_ana.jetIdMva)
            self.runMva = True
        else:
            self.puidalgo = PileupJetIdNtupleAlgo()
            self.runMva = False

        self.vtxBins = (0, 10, 15, 20, 30)  ## (0,2,4,6,10,15,20,30,35)
        self.vtxBinLabels = mkBinLabels(self.vtxBins)
        self.ptBins = (20, 30, 50)  ## (20,30,40,50,100)
        self.etaBins = (0, 1.4, 2.5, 3.0)
        self.puEtaLables = ["_barrel", "_endtk", "_endNOtk", "_fwd"]
        reweight_f = TF1("f", "pol2(0)+expo(3)")
        reweight_f.SetParameters(0.1955298, -0.003830591, 1.944794e-05,
                                 4.649755, -0.1722024)
        self.reweight = ("pt", reweight_f)

        ## PileUp histograms
        if self.cfg_ana.doJetIdHisto:
            # histograms for pileup jet identification variables

            self.gluCleanHistosId = PileupJetHistograms(
                "GluonMatchedCleanHistosId",
                self.vtxBins,
                self.ptBins,
                self.etaBins,
                etalabels=self.puEtaLables,
                reweight=self.reweight)
            self.quarkCleanHistosId = PileupJetHistograms(
                "QuarkMatchedCleanHistosId",
                self.vtxBins,
                self.ptBins,
                self.etaBins,
                etalabels=self.puEtaLables,
                reweight=self.reweight)
            self.reweiMatchedCleanHistosId = PileupJetHistograms(
                "ReweiMatchedCleanHistosId",
                self.vtxBins,
                self.ptBins,
                self.etaBins,
                etalabels=self.puEtaLables,
                reweight=self.reweight)
            self.unmatchedCleanHistosId = PileupJetHistograms(
                "UnmatchedCleanHistosId",
                self.vtxBins,
                self.ptBins,
                self.etaBins,
                etalabels=self.puEtaLables)

        ### self.jetKin = []
        ### for vtx in self.vtxBinLabels:
        ###     self.jetKin.append([])
        ###     for eta in self.puEtaLables:
        ###         self.jetKin[-1].append( JetHistograms('Jets%s%s' % (vtx,eta) ) )

        if self.cfg_ana.dumpTree:
            self.tree = TTree("tree", "tree")
            self.tree.SetDirectory(self.file)

            self.puidalgo.bookBranches(self.tree)

            gROOT.ProcessLine(
                """struct MyTreeVars{ Int_t nvtx; Bool_t isMatched; Int_t jetFlavour; Float_t partonPt; Float_t genPt; Float_t genDr; }"""
            )
            from ROOT import MyTreeVars
            self.treevars = MyTreeVars()

            for i, j in ("nvtx", "I"), ("isMatched",
                                        "O"), ("jetFlavour",
                                               "I"), ("partonPt",
                                                      "F"), ("genPt",
                                                             "F"), ("genDr",
                                                                    "F"):
                self.tree.Branch(i, AddressOf(self.treevars, i),
                                 "%s/%s" % (i, j))

        self.h_nvtx = TH1F("h_nvtx", "", 50, 0, 50)
        self.h_genjetspt = TH1F("h_genjetspt", "", 500, 0, 500)
예제 #8
0
class JetIDAnalyzer(Analyzer):
    '''A simple jet analyzer.'''
    def declareHandles(self):
        super(JetIDAnalyzer, self).declareHandles()
        self.handles['jets'] = AutoHandle(*self.cfg_ana.jetCollection)
        if self.cfg_ana.useGenLeptons:
            self.mchandles['leptons2'] = AutoHandle(
                'genLeptonsStatus2', 'std::vector<reco::GenParticle>')
        else:
            self.mchandles['genParticles'] = AutoHandle(
                'prunedGen', 'std::vector<reco::GenParticle>')

        ### self.mchandles['genJets'] =  AutoHandle (
        ###     *self.cfg_ana.genJetsCollection
        ###    )
        self.handles['vertices'] = AutoHandle('offlinePrimaryVertices',
                                              'std::vector<reco::Vertex>')

# .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....

    def beginLoop(self):
        super(JetIDAnalyzer, self).beginLoop()
        self.file = TFile('/'.join([self.looperName, 'testJets.root']),
                          'recreate')

        if self.cfg_ana.applyPFLooseId:
            from ROOT import PFJetIDSelectionFunctor
            self.isPFLooseFunc = PFJetIDSelectionFunctor(
                0, PFJetIDSelectionFunctor.LOOSE)
            ## Workaround: for some reason PyROOT does not bind PFJetIDSelectionFunctor(Jet) nor PFJetIDSelectionFunctor.getBitsTemplates
            from ROOT import pat
            self.isPFLooseFunc.bits = pat.strbitset()
            for i in "CHF", "NHF", "CEF", "NEF", "NCH", "nConstituents":
                self.isPFLooseFunc.bits.push_back(i)
            ## /Workaround
            self.isPFLoose = lambda x: self.isPFLooseFunc(
                x, self.isPFLooseFunc.bits)
        else:
            self.isPFLoose = lambda x: True

        # general histograms
        self.jetHistos = JetHistograms('Jets')
        self.cleanJetHistos = JetHistograms('CleanJets')
        self.matchedCleanJetHistos = JetHistograms('MatchedCleanJets')
        self.unmatchedCleanJetHistos = JetHistograms('UnmatchedCleanJets')

        ## Pileup JetID
        if self.cfg_ana.jetIdMva:
            self.puidalgo = PileupJetIdNtupleAlgo(*self.cfg_ana.jetIdMva)
            self.runMva = True
        else:
            self.puidalgo = PileupJetIdNtupleAlgo()
            self.runMva = False

        self.vtxBins = (0, 10, 15, 20, 30)  ## (0,2,4,6,10,15,20,30,35)
        self.vtxBinLabels = mkBinLabels(self.vtxBins)
        self.ptBins = (20, 30, 50)  ## (20,30,40,50,100)
        self.etaBins = (0, 1.4, 2.5, 3.0)
        self.puEtaLables = ["_barrel", "_endtk", "_endNOtk", "_fwd"]
        reweight_f = TF1("f", "pol2(0)+expo(3)")
        reweight_f.SetParameters(0.1955298, -0.003830591, 1.944794e-05,
                                 4.649755, -0.1722024)
        self.reweight = ("pt", reweight_f)

        ## PileUp histograms
        if self.cfg_ana.doJetIdHisto:
            # histograms for pileup jet identification variables

            self.gluCleanHistosId = PileupJetHistograms(
                "GluonMatchedCleanHistosId",
                self.vtxBins,
                self.ptBins,
                self.etaBins,
                etalabels=self.puEtaLables,
                reweight=self.reweight)
            self.quarkCleanHistosId = PileupJetHistograms(
                "QuarkMatchedCleanHistosId",
                self.vtxBins,
                self.ptBins,
                self.etaBins,
                etalabels=self.puEtaLables,
                reweight=self.reweight)
            self.reweiMatchedCleanHistosId = PileupJetHistograms(
                "ReweiMatchedCleanHistosId",
                self.vtxBins,
                self.ptBins,
                self.etaBins,
                etalabels=self.puEtaLables,
                reweight=self.reweight)
            self.unmatchedCleanHistosId = PileupJetHistograms(
                "UnmatchedCleanHistosId",
                self.vtxBins,
                self.ptBins,
                self.etaBins,
                etalabels=self.puEtaLables)

        ### self.jetKin = []
        ### for vtx in self.vtxBinLabels:
        ###     self.jetKin.append([])
        ###     for eta in self.puEtaLables:
        ###         self.jetKin[-1].append( JetHistograms('Jets%s%s' % (vtx,eta) ) )

        if self.cfg_ana.dumpTree:
            self.tree = TTree("tree", "tree")
            self.tree.SetDirectory(self.file)

            self.puidalgo.bookBranches(self.tree)

            gROOT.ProcessLine(
                """struct MyTreeVars{ Int_t nvtx; Bool_t isMatched; Int_t jetFlavour; Float_t partonPt; Float_t genPt; Float_t genDr; }"""
            )
            from ROOT import MyTreeVars
            self.treevars = MyTreeVars()

            for i, j in ("nvtx", "I"), ("isMatched",
                                        "O"), ("jetFlavour",
                                               "I"), ("partonPt",
                                                      "F"), ("genPt",
                                                             "F"), ("genDr",
                                                                    "F"):
                self.tree.Branch(i, AddressOf(self.treevars, i),
                                 "%s/%s" % (i, j))

        self.h_nvtx = TH1F("h_nvtx", "", 50, 0, 50)
        self.h_genjetspt = TH1F("h_genjetspt", "", 500, 0, 500)

# .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....

    def process(self, iEvent, event):
        #read all the handles defined beforehand
        self.readCollections(iEvent)

        jetEtaCut = 4.5

        # get the vertexes
        event.vertices = self.handles['vertices'].product()
        self.h_nvtx.Fill(len(event.vertices))
        event.vertexBin = int(len(event.vertices))

        # get the jets in the jets variable
        jets = self.handles['jets'].product()
        # filter jets with some selections
        event.jets = [
            jet for jet in jets
            if (abs(jet.eta()) < jetEtaCut and jet.pt() > self.cfg_ana.ptCut
                and self.isPFLoose(jet))
        ]
        self.jetHistos.fillEvent(event.jets)

        try:
            # get status 2 leptons
            if 'leptons2' in self.mchandles:
                event.genLeptons = map(GenParticle,
                                       self.mchandles['leptons2'].product())
            else:
                event.genLeptons = [
                    lep for lep in self.mchandles['genParticles'].product()
                    if lep.status() == 3 and (abs(lep.pdgId()) == 11 or abs(
                        lep.pdgId()) == 13 or abs(lep.pdgId()) == 15)
                ]
        except:
            event.genLeptons = None

        if event.genLeptons:
            #FIXME why are there cases in which there's 4 or 6 leptons?
            if len(event.genLeptons) != 2:
                return
            # in case I want to filter out taus
            # 11, 13, 15 : e, u, T
            # remove leptons from jets if closer than 0.2
            event.cleanJets = cleanObjectCollection(event.jets,
                                                    event.genLeptons, 0.2)
        else:
            event.cleanJets = event.jets

        ### event.matchingCleanJets = matchObjectCollection2 (event.cleanJets, event.selGenJets, 0.25)
        # assign to each jet its gen match (easy life :))
        event.selGenJets = []
        for jet in event.cleanJets:
            try:
                jet.gen = jet.genJet()
                jet.gen.pt()
                event.selGenJets.append(jet.gen)
            except:
                jet.gen = None

        for jet in event.selGenJets:
            self.h_genjetspt.Fill(jet.pt())
        self.jetHistos.fillStats(len(event.selGenJets), len(event.jets))

        ### try:
        ###     # get genJets
        ###     event.genJets = map (GenJet, self.mchandles['genJets'].product ())
        ###     event.selGenJets = event.genJets
        ###     for jet in event.selGenJets :
        ###         self.h_genjetspt.Fill (jet.pt ())
        ###
        ###     # first stats plots
        ###     self.jetHistos.fillStats (len (event.selGenJets), len (event.jets))
        ### except:
        ###     pass

        ## run the PileupJetIdAlgo and attach the id to the jet
        ijet = 0
        for jet in event.cleanJets:
            try:
                jet.puIdentifier = self.puidalgo.computeIdVariables(
                    jet.sourcePtr().get(), 0., event.vertices[0], self.runMva)
            except:
                jet.puIdentifier = self.puidalgo.computeIdVariables(
                    jet, 0., event.vertices[0], self.runMva)
            if self.cfg_ana.dumpTree:
                ## self.puidalgo.fillJet(jet.puIdentifier,ijet,0)
                self.puidalgo.setIJetIEvent(ijet, 0)
                self.treevars.nvtx = len(event.vertices)
                self.treevars.isMatched = False
                self.treevars.jetFlavour = -999
                self.treevars.genPt = 0.
                self.treevars.partonPt = 0.
                self.treevars.genDr = -100.
                if jet.gen:
                    self.treevars.isMatched = True
                    self.treevars.jetFlavour = jet.partonFlavour()
                    self.treevars.genPt = jet.gen.pt()
                    self.treevars.genDr = deltaR(jet.gen.eta(), jet.gen.phi(),
                                                 jet.eta(), jet.phi())
                    try:
                        self.treevars.partonPt = jet.genParton.pt()
                    except:
                        pass
                self.tree.Fill()
            ijet += 1

        self.cleanJetHistos.fillEvent(event.cleanJets)

        event.matchedCleanJets = [
            jet for jet in event.cleanJets if jet.gen != None
        ]

        event.unmatchedCleanJets = [
            jet for jet in event.cleanJets if jet.gen == None
        ]
        self.matchedCleanJetHistos.fillEvent(event.matchedCleanJets)
        self.unmatchedCleanJetHistos.fillEvent(event.unmatchedCleanJets)

        event.cleanGluJets = []
        event.cleanQuarkJets = []
        vtxbin = findBin(self.vtxBinLabels, len(event.vertices))
        for jet in event.matchedCleanJets:
            flav = abs(jet.partonFlavour())
            if flav == 21:
                event.cleanGluJets.append(jet)
            elif flav > 0 and flav <= 3:
                event.cleanQuarkJets.append(jet)
            jet.weight = self.reweight[1](getattr(jet, self.reweight[0])())
            etabin = findBin(self.etaBins, jet.eta())
            ### self.jetKin[vtxbin][etabin].fillJet(jet)

        if self.cfg_ana.doJetIdHisto:
            self.gluCleanHistosId.fillEvent(event.cleanGluJets, event.vertices)
            self.quarkCleanHistosId.fillEvent(event.cleanQuarkJets,
                                              event.vertices)
            ### self.matchedCleanHistosId.fillEvent(event.matchedCleanJets,event.vertices)
            self.reweiMatchedCleanHistosId.fillEvent(event.matchedCleanJets,
                                                     event.vertices)
            self.unmatchedCleanHistosId.fillEvent(event.unmatchedCleanJets,
                                                  event.vertices)

# .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....

    def write(self):
        from ROOT import gROOT
        gROOT.SetBatch(True)

        self.jetHistos.Write(self.file)
        self.cleanJetHistos.Write(self.file)

        self.matchedCleanJetHistos.Write(self.file)
        self.unmatchedCleanJetHistos.Write(self.file)

        if self.cfg_ana.doJetIdHisto:
            self.gluCleanHistosId.summary()
            self.gluCleanHistosId.Write(self.file)

            self.quarkCleanHistosId.summary()
            self.quarkCleanHistosId.Write(self.file)

            self.reweiMatchedCleanHistosId.summary()
            self.reweiMatchedCleanHistosId.Write(self.file)

            ### self.matchedCleanHistosId.Write(self.file)
            self.unmatchedCleanHistosId.Write(self.file)

        ### for j in self.jetKin:
        ###     for h in j:
        ###         h.Write(self.file)

        self.file.cd()
        self.h_nvtx.Write()
        self.h_genjetspt.Write()

        if self.cfg_ana.dumpTree:
            self.tree.Write()

        self.file.Close()
예제 #9
0
    def beginLoop (self) :
        super (SimpleJetAnalyzer,self).beginLoop ()
        self.file = TFile ('/'.join ([self.looperName, 'testJets.root']),
                           'recreate')
        if self.cfg_ana.applyPFLooseId:
            from ROOT import PFJetIDSelectionFunctor 
            self.isPFLooseFunc = PFJetIDSelectionFunctor(0,PFJetIDSelectionFunctor.LOOSE)
            ## Workaround: for some reason PyROOT does not bind nor PFJetIDSelectionFunctor(Jet)PFJetIDSelectionFunctor.getBitsTemplates 
            from ROOT import pat        
            self.isPFLooseFunc.bits = pat.strbitset()
            for i in "CHF","NHF","CEF","NEF","NCH","nConstituents": self.isPFLooseFunc.bits.push_back(i) 
            ## /Workaround
            self.isPFLoose = lambda x : self.isPFLooseFunc(x,self.isPFLooseFunc.bits)
        else:
            self.isPFLoose = lambda x : True

        # general histograms
        self.jetHistos = JetHistograms ('Jets')
        self.cleanJetHistos = JetHistograms ('CleanJets')
        self.matchedCleanJetHistos = JetHistograms ('MatchedCleanJets')
        self.matchedCleanJetHistos_barrel = JetHistograms ('MatchedCleanJets_barrel')
        self.matchedCleanJetHistos_endtk = JetHistograms ('MatchedCleanJets_endtk')
        self.matchedCleanJetHistos_endNOtk = JetHistograms ('MatchedCleanJets_endNOtk')
        self.matchedCleanJetHistos_fwd = JetHistograms ('MatchedCleanJets_fwd')
        self.LPtmatchedCleanJetHistos = JetHistograms ('LPtMatchedCleanJets') 
        self.HPtmatchedCleanJetHistos = JetHistograms ('HPtMatchedCleanJets')
        self.unmatchedCleanJetHistos = JetHistograms ('UnmatchedCleanJets')
        self.LPtUnmatchedCleanJetHistos = JetHistograms ('LPtUnmatchedCleanJets') 
        self.HPtUnmatchedCleanJetHistos = JetHistograms ('HPtUnmatchedCleanJets')

        # histograms of the components fraction
        self.matchedCleanJetHistosComponents = FractionJetHistograms ('MatchedCleanJetsCompontents')
        self.unmatchedCleanJetHistosComponents = FractionJetHistograms ('UnmatchedCleanJetsCompontents')

        # histograms for the resolution of matched jets
        self.matchedCleanJetHistosResolution = ResolutionJetHistograms ('MatchedCleanJetsResolution', 50, 1)
        self.matchedCleanJetHistosResolution_barrel = ResolutionJetHistograms ('MatchedCleanJetsResolution_barrel', 50, 1)
        self.matchedCleanJetHistosResolution_endtk = ResolutionJetHistograms ('MatchedCleanJetsResolution_endtk', 50, 1)
        self.matchedCleanJetHistosResolution_endNOtk = ResolutionJetHistograms ('MatchedCleanJetsResolution_endNOtk', 50, 1)
        self.matchedCleanJetHistosResolution_fwd = ResolutionJetHistograms ('MatchedCleanJetsResolution_fwd', 50, 1)

        print 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
        self.doJetIdHisto = False
        if self.cfg_ana.doJetIdHisto:
            print 'doing jet ID'
            # histograms for pileup jet identification variables
            self.vtxBins   = (0,5,10,15,20,30) ## (0,2,4,6,10,15,20,30,35)
            self.ptBins    = (20,30,50) ## (20,30,40,50,100)
            self.etaBins   = (0,1.4,2.5,3.0)
            self.puEtaLables = ["_barrel","_endtk","_endNOtk","_fwd"]
            reweight_f = TF1("f","pol2(0)+expo(3)")
            reweight_f.SetParameters(0.1955298,-0.003830591,1.944794e-05,4.649755,-0.1722024)
            self.reweight = ("pt", reweight_f)
            self.doJetIdHisto = True
            self.gluCleanHistosId = PileupJetHistograms("GluonMatchedCleanHistosId",self.vtxBins,self.ptBins,self.etaBins,etalabels=self.puEtaLables,reweight=self.reweight,
                                                        jetIdMva=self.cfg_ana.jetIdMva)
            self.quarkCleanHistosId = PileupJetHistograms("QuarkMatchedCleanHistosId",self.vtxBins,self.ptBins,self.etaBins,etalabels=self.puEtaLables,reweight=self.reweight,
                                                          jetIdMva=self.cfg_ana.jetIdMva)
            self.reweiMatchedCleanHistosId = PileupJetHistograms("ReweiMatchedCleanHistosId",self.vtxBins,self.ptBins,self.etaBins,etalabels=self.puEtaLables,reweight=self.reweight,
                                                                 jetIdMva=self.cfg_ana.jetIdMva)
            self.unmatchedCleanHistosId = PileupJetHistograms("UnmatchedCleanHistosId",self.vtxBins,self.ptBins,self.etaBins,etalabels=self.puEtaLables,
                                                              jetIdMva=self.cfg_ana.jetIdMva)
            
        self.h_nvtx = TH1F ("h_nvtx", "" ,50, 0, 50)
        self.h_genjetspt = TH1F ("h_genjetspt", "" ,500, 0, 500)
        self.h_secondClosestVsPtratio = TH2F ("h_secondClosestVsPtratio", "" ,100, 0, 2, 100, 0, 6)
        self.h_avedistanceVSNvtx = TH2F ("h_avedistanceVSNvtx", "" ,50, 0, 50, 100, 0, 6)
        self.h_PTRatioVSgenEta = TH2F ("h_PTRatioVSgenEta", "" ,150, -5, 5, 100, 0, 2)
        self.h_PTRatioVSgenPt = TH2F ("h_PTRatioVSgenPt", "" ,200, 0, 100, 100, 0, 2)
        self.h_matchDR = TH1F ("h_matchDR", "" ,60, 0, 0.30)
        self.h_relPtVSmatchDR = TH2F ("h_relPtVSmatchDR", "" ,60, 0, 0.30, 100, 0, 2)
        self.h_relPtVSchFrac = TH2F ("h_relPtVSchFrac", "" ,100, 0, 1, 100, 0, 2)
예제 #10
0
class SimpleJetAnalyzer (Analyzer) :
    '''A simple jet analyzer for Pietro.'''
    ### def __init__(self,cfg_ana, cfg_comp, looperName):
    ###     loadLibs()
    ###     super (SimpleJetAnalyzer, self).__init__(cfg_ana, cfg_comp, looperName)

    def declareHandles (self) :
        super (SimpleJetAnalyzer, self).declareHandles ()
        self.handles['jets'] =  AutoHandle (
            *self.cfg_ana.jetCollection
            )
        if self.cfg_ana.useGenLeptons: 
            self.mchandles['genParticlesPruned'] =  AutoHandle (
                *self.cfg_ana.GenParticlesCollection
                )
        else:
            self.mchandles['genParticles'] =  AutoHandle (
                'prunedGen',
                'std::vector<reco::GenParticle>'
                )
            
        self.mchandles['genJets'] =  AutoHandle (
            *self.cfg_ana.genJetsCollection
           )
        self.handles['vertices'] =  AutoHandle (
            *self.cfg_ana.VtxCollection
           )

# .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....

    def beginLoop (self) :
        super (SimpleJetAnalyzer,self).beginLoop ()
        self.file = TFile ('/'.join ([self.looperName, 'testJets.root']),
                           'recreate')
        if self.cfg_ana.applyPFLooseId:
            from ROOT import PFJetIDSelectionFunctor 
            self.isPFLooseFunc = PFJetIDSelectionFunctor(0,PFJetIDSelectionFunctor.LOOSE)
            ## Workaround: for some reason PyROOT does not bind nor PFJetIDSelectionFunctor(Jet)PFJetIDSelectionFunctor.getBitsTemplates 
            from ROOT import pat        
            self.isPFLooseFunc.bits = pat.strbitset()
            for i in "CHF","NHF","CEF","NEF","NCH","nConstituents": self.isPFLooseFunc.bits.push_back(i) 
            ## /Workaround
            self.isPFLoose = lambda x : self.isPFLooseFunc(x,self.isPFLooseFunc.bits)
        else:
            self.isPFLoose = lambda x : True

        # general histograms
        self.jetHistos = JetHistograms ('Jets')
        self.cleanJetHistos = JetHistograms ('CleanJets')
        self.matchedCleanJetHistos = JetHistograms ('MatchedCleanJets')
        self.matchedCleanJetHistos_barrel = JetHistograms ('MatchedCleanJets_barrel')
        self.matchedCleanJetHistos_endtk = JetHistograms ('MatchedCleanJets_endtk')
        self.matchedCleanJetHistos_endNOtk = JetHistograms ('MatchedCleanJets_endNOtk')
        self.matchedCleanJetHistos_fwd = JetHistograms ('MatchedCleanJets_fwd')
        self.LPtmatchedCleanJetHistos = JetHistograms ('LPtMatchedCleanJets') 
        self.HPtmatchedCleanJetHistos = JetHistograms ('HPtMatchedCleanJets')
        self.unmatchedCleanJetHistos = JetHistograms ('UnmatchedCleanJets')
        self.LPtUnmatchedCleanJetHistos = JetHistograms ('LPtUnmatchedCleanJets') 
        self.HPtUnmatchedCleanJetHistos = JetHistograms ('HPtUnmatchedCleanJets')

        # histograms of the components fraction
        self.matchedCleanJetHistosComponents = FractionJetHistograms ('MatchedCleanJetsCompontents')
        self.unmatchedCleanJetHistosComponents = FractionJetHistograms ('UnmatchedCleanJetsCompontents')

        # histograms for the resolution of matched jets
        self.matchedCleanJetHistosResolution = ResolutionJetHistograms ('MatchedCleanJetsResolution', 50, 1)
        self.matchedCleanJetHistosResolution_barrel = ResolutionJetHistograms ('MatchedCleanJetsResolution_barrel', 50, 1)
        self.matchedCleanJetHistosResolution_endtk = ResolutionJetHistograms ('MatchedCleanJetsResolution_endtk', 50, 1)
        self.matchedCleanJetHistosResolution_endNOtk = ResolutionJetHistograms ('MatchedCleanJetsResolution_endNOtk', 50, 1)
        self.matchedCleanJetHistosResolution_fwd = ResolutionJetHistograms ('MatchedCleanJetsResolution_fwd', 50, 1)

        print 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
        self.doJetIdHisto = False
        if self.cfg_ana.doJetIdHisto:
            print 'doing jet ID'
            # histograms for pileup jet identification variables
            self.vtxBins   = (0,5,10,15,20,30) ## (0,2,4,6,10,15,20,30,35)
            self.ptBins    = (20,30,50) ## (20,30,40,50,100)
            self.etaBins   = (0,1.4,2.5,3.0)
            self.puEtaLables = ["_barrel","_endtk","_endNOtk","_fwd"]
            reweight_f = TF1("f","pol2(0)+expo(3)")
            reweight_f.SetParameters(0.1955298,-0.003830591,1.944794e-05,4.649755,-0.1722024)
            self.reweight = ("pt", reweight_f)
            self.doJetIdHisto = True
            self.gluCleanHistosId = PileupJetHistograms("GluonMatchedCleanHistosId",self.vtxBins,self.ptBins,self.etaBins,etalabels=self.puEtaLables,reweight=self.reweight,
                                                        jetIdMva=self.cfg_ana.jetIdMva)
            self.quarkCleanHistosId = PileupJetHistograms("QuarkMatchedCleanHistosId",self.vtxBins,self.ptBins,self.etaBins,etalabels=self.puEtaLables,reweight=self.reweight,
                                                          jetIdMva=self.cfg_ana.jetIdMva)
            self.reweiMatchedCleanHistosId = PileupJetHistograms("ReweiMatchedCleanHistosId",self.vtxBins,self.ptBins,self.etaBins,etalabels=self.puEtaLables,reweight=self.reweight,
                                                                 jetIdMva=self.cfg_ana.jetIdMva)
            self.unmatchedCleanHistosId = PileupJetHistograms("UnmatchedCleanHistosId",self.vtxBins,self.ptBins,self.etaBins,etalabels=self.puEtaLables,
                                                              jetIdMva=self.cfg_ana.jetIdMva)
            
        self.h_nvtx = TH1F ("h_nvtx", "" ,50, 0, 50)
        self.h_genjetspt = TH1F ("h_genjetspt", "" ,500, 0, 500)
        self.h_secondClosestVsPtratio = TH2F ("h_secondClosestVsPtratio", "" ,100, 0, 2, 100, 0, 6)
        self.h_avedistanceVSNvtx = TH2F ("h_avedistanceVSNvtx", "" ,50, 0, 50, 100, 0, 6)
        self.h_PTRatioVSgenEta = TH2F ("h_PTRatioVSgenEta", "" ,150, -5, 5, 100, 0, 2)
        self.h_PTRatioVSgenPt = TH2F ("h_PTRatioVSgenPt", "" ,200, 0, 100, 100, 0, 2)
        self.h_matchDR = TH1F ("h_matchDR", "" ,60, 0, 0.30)
        self.h_relPtVSmatchDR = TH2F ("h_relPtVSmatchDR", "" ,60, 0, 0.30, 100, 0, 2)
        self.h_relPtVSchFrac = TH2F ("h_relPtVSchFrac", "" ,100, 0, 1, 100, 0, 2)

# .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....
    def process (self, iEvent, event) :
        #read all the handles defined beforehand
        self.readCollections (iEvent)
        
        jetEtaCut = 4.5 
        
        # get the vertexes
        event.vertices = self.handles['vertices'].product ()
        self.h_nvtx.Fill (len (event.vertices))
        event.vertexBin = int (len (event.vertices))
        
        # get the jets in the jets variable
        jets = self.handles['jets'].product ()
        # filter jets with some selections
        event.jets = [ jet for jet in jets if ( abs(jet.eta()) < jetEtaCut and jet.pt()>self.cfg_ana.ptCut and self.isPFLoose(jet) ) ]
        self.jetHistos.fillEvent (event.jets)
        
        # get status 2 leptons
        if 'genParticlesPruned' in self.mchandles:
            event.genLeptons = [ lep for lep in self.mchandles['genParticlesPruned'].product() if lep.status() == 3 and (abs(lep.pdgId()) == 11 or abs(lep.pdgId()) == 13 or abs(lep.pdgId()) == 15) ]
        else:
            event.genLeptons = [ lep for lep in self.mchandles['genParticles'].product() if lep.status() == 3 and (abs(lep.pdgId()) == 11 or abs(lep.pdgId()) == 13 or abs(lep.pdgId()) == 15) ]  
# @ Pasquale: why level 3 and not level 2?
#        event.selGenLeptons = [GenParticle (lep) for lep in event.genLeptons if (lep.pt ()>self.cfg_ana.ptCut and abs (lep.eta ()) < jetEtaCut)]
        
        # get genJets
        event.genJets = map (GenJet, self.mchandles['genJets'].product ())
        # filter genjets as for reco jets
        event.myGenJets = [GenJet (jet) for jet in event.genJets if (jet.pt ()>self.cfg_ana.genPtCut)]
        event.selGenJets = cleanObjectCollection (event.myGenJets, event.genLeptons, 0.2)
        # event.selGenJets = event.genJets
        for jet in event.selGenJets : 
            self.h_genjetspt.Fill (jet.pt ())
        
        event.noNegJets = [ jet for jet in event.jets if (jet.jecFactor(0) > 0) ]
#        event.noNegJets = [ jet for jet in event.jets]
        
        # first stats plots
        # print 'genLeptons : ' + repr (len (event.genLeptons)) + ' | genJets : ' + repr (len (event.genJets)) + ' | recoJets : ' + repr (len (event.jets))
        self.jetHistos.fillStats (len (event.selGenJets), len (event.noNegJets))
        
        #FIXME why are there cases in which there's 4 or 6 leptons?
        if len (event.genLeptons) > 2 :
            return
        # in case I want to filter out taus
        # 11, 13, 15 : e, u, T
#        event.genOneLepton = [GenParticle (part) for part in event.genLeptons if abs (part.pdgId ()) == 15]
        # remove leptons from jets if closer than 0.2
        event.cleanJets = cleanObjectCollection (event.noNegJets, event.genLeptons, 0.2)
#        event.cleanJets = event.noNegJets
        self.cleanJetHistos.fillEvent (event.cleanJets)
        
#        print len (jets),len (event.jets), len (event.noNegJets), len (event.cleanJets), len (event.genLeptons),"-->",(len (event.noNegJets) - len (event.cleanJets) - len (event.genLeptons))

        event.matchingCleanJets = matchObjectCollection2 (event.cleanJets, event.selGenJets, 0.25)
        # assign to each jet its gen match (easy life :))
        for jet in event.cleanJets :
            jet.gen = event.matchingCleanJets[ jet ]
        # FIXME next step might be to put this in the matching and remove the boolean flags

        event.matchedCleanJets = [jet for jet in event.matchingCleanJets if jet.gen != None]
        event.cleanGluJets = []
        event.cleanQuarkJets = []
        for jet in event.matchedCleanJets:
            flav = abs(jet.partonFlavour()) 
            if flav == 21:
                event.cleanGluJets.append(jet)
            elif flav > 0 and flav <= 3:
                event.cleanQuarkJets.append(jet)

        event.LPtmatchedCleanJets = [jet for jet in event.matchingCleanJets if jet.gen != None and jet.pt () <= 30]
        event.HPtmatchedCleanJets = [jet for jet in event.matchingCleanJets if jet.gen != None and jet.pt () > 30]

        self.matchedCleanJetHistos.fillEvent (event.matchedCleanJets)
        self.LPtmatchedCleanJetHistos.fillEvent (event.LPtmatchedCleanJets)
        self.HPtmatchedCleanJetHistos.fillEvent (event.HPtmatchedCleanJets)

        event.unmatchedCleanJets = [jet for jet in event.matchingCleanJets if jet.gen == None]
        event.LPtunmatchedCleanJets = [jet for jet in event.matchingCleanJets if jet.gen == None and jet.pt () <= 30]
        event.HPtunmatchedCleanJets = [jet for jet in event.matchingCleanJets if jet.gen == None and jet.pt () > 30]
        
        self.unmatchedCleanJetHistos.fillEvent (event.unmatchedCleanJets)
        self.LPtUnmatchedCleanJetHistos.fillEvent (event.LPtunmatchedCleanJets)
        self.HPtUnmatchedCleanJetHistos.fillEvent (event.HPtunmatchedCleanJets)
        
        self.matchedCleanJetHistosComponents.fillEvent (event.matchedCleanJets)
        
        self.unmatchedCleanJetHistosComponents.fillEvent (event.unmatchedCleanJets)
        
        self.matchedCleanJetHistosResolution.fillEvent (event.matchedCleanJets, len (event.vertices))
        
        for jet in event.matchedCleanJets :
            if abs (jet.gen.eta ()) < 1.4 :
                self.matchedCleanJetHistosResolution_barrel.fillJet (jet, len (event.vertices))
                self.matchedCleanJetHistos_barrel.fillJet (jet)
            elif 1.6 < abs (jet.gen.eta ()) < 2.5 :    
                self.matchedCleanJetHistosResolution_endtk.fillJet (jet, len (event.vertices))
                self.matchedCleanJetHistos_endtk.fillJet (jet)
            elif 2.6 < abs (jet.gen.eta ()) < 2.9 :    
                self.matchedCleanJetHistosResolution_endNOtk.fillJet (jet, len (event.vertices))
                self.matchedCleanJetHistos_endNOtk.fillJet (jet)
            elif 3.1 < abs (jet.gen.eta ()) :    
                self.matchedCleanJetHistosResolution_fwd.fillJet (jet, len (event.vertices))
                self.matchedCleanJetHistos_fwd.fillJet (jet)

        ##PG debugging for tails
        #for jet in event.matchedCleanJets :
            #deltaRR = deltaR( jet.eta (), jet.phi (), jet.gen.eta (), jet.gen.phi ())
            #self.h_matchDR.Fill (deltaRR)
            #self.h_relPtVSmatchDR.Fill (deltaRR, jet.pt () / jet.gen.pt ())
            #if abs (jet.gen.eta ()) > 2.5 and abs (jet.gen.eta ()) < 3 :
                #self.h_relPtVSchFrac.Fill (jet.chargedHadronEnergyFraction (), jet.pt () / jet.gen.pt ())

            #if jet.gen.pt () > 20 and jet.gen.pt () < 40 :
                #self.h_PTRatioVSgenEta.Fill (jet.gen.eta (), jet.pt () / jet.gen.pt ())
            #if abs (jet.gen.eta ()) > 1.6 :
                #self.h_PTRatioVSgenPt.Fill (jet.gen.pt (), jet.pt () / jet.gen.pt ())

            #minDelta = 10
            #secondClosest = jet
            #for recojet in event.cleanJets :
                #if recojet == jet : continue
                #dr2 = deltaR2( jet.gen.eta (), jet.gen.phi (), recojet.eta (), recojet.phi ())
                #if dr2 < minDelta :
                    #minDelta = dr2
                    #secondClosest = recojet 
            ##if len(event.vertices) < 10 or abs (jet.gen.eta ()) < 1.6: continue
            #self.h_secondClosestVsPtratio.Fill (jet.pt () / jet.gen.pt (), math.sqrt (minDelta))
            #if jet.pt () / jet.gen.pt () < 0.2 and jet.gen.pt () > 20 and abs (jet.gen.eta ()) < 3 and abs (jet.gen.eta ()) > 2.5 :
                #print '============',len(event.genLeptons)
                #print jet.pt (), jet.eta (), jet.phi (), jet.jecFactor (0)
                #print jet.gen.pt (), jet.gen.eta (), jet.gen.phi ()
                #print '------------ leptons:'
                #for lept in event.genLeptons :
                    #print lept.pt (), lept.eta (), lept.phi ()
                #print '------------'
                #for recojet in event.cleanJets :
                    #print "RECO",recojet.pt (), recojet.eta (), recojet.phi (), recojet.jecFactor (0)
                #for genjet in event.selGenJets :
                    #print "GEN ",genjet.pt (), genjet.eta (), genjet.phi ()

        #aveDeltaR = 0
        #num = 0
        #for recojet1 in event.cleanJets :
            #minDelta = 10
            #closest = recojet1
            #for recojet2 in event.cleanJets :
                #if recojet1 == recojet2 : continue
                #dr2 = deltaR2( recojet1.eta (), recojet1.phi (), recojet2.eta (), recojet2.phi ())
                #if dr2 < minDelta :
                    #minDelta = dr2
                    #closest = recojet2
            #if minDelta == 10 : continue
            #aveDeltaR = aveDeltaR + math.sqrt (minDelta)
            #num = num + 1
        #if num > 0 :
            #aveDeltaR = aveDeltaR / num
            #self.h_avedistanceVSNvtx.Fill (len(event.vertices), aveDeltaR)


        if self.doJetIdHisto:
            self.gluCleanHistosId.fillEvent(event.cleanGluJets,event.vertices)
            self.quarkCleanHistosId.fillEvent(event.cleanQuarkJets,event.vertices)
            ### self.matchedCleanHistosId.fillEvent(event.matchedCleanJets,event.vertices)
            self.reweiMatchedCleanHistosId.fillEvent(event.matchedCleanJets,event.vertices)
            self.unmatchedCleanHistosId.fillEvent(event.unmatchedCleanJets,event.vertices)
        

# .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... .... ....

    def write (self):
        from ROOT import gROOT
        gROOT.SetBatch(True)
        self.jetHistos.Write (self.file)
        self.cleanJetHistos.Write (self.file)
        self.matchedCleanJetHistos.Write (self.file)
        self.matchedCleanJetHistos_barrel.Write (self.file)
        self.matchedCleanJetHistos_endtk.Write (self.file)
        self.matchedCleanJetHistos_endNOtk.Write (self.file)
        self.matchedCleanJetHistos_fwd.Write (self.file)
        
        self.LPtmatchedCleanJetHistos.Write (self.file)
        self.HPtmatchedCleanJetHistos.Write (self.file)
        self.LPtUnmatchedCleanJetHistos.Write (self.file)
        self.HPtUnmatchedCleanJetHistos.Write (self.file)

        self.unmatchedCleanJetHistos.Write (self.file)

        self.matchedCleanJetHistosComponents.summary ()
        self.matchedCleanJetHistosComponents.Write (self.file)
        self.unmatchedCleanJetHistosComponents.summary ()
        self.unmatchedCleanJetHistosComponents.Write (self.file)

        self.matchedCleanJetHistosResolution.summary ()
        self.matchedCleanJetHistosResolution.Write (self.file)
        
        self.matchedCleanJetHistosResolution_barrel.summary ()
        self.matchedCleanJetHistosResolution_barrel.Write (self.file)
        
        self.matchedCleanJetHistosResolution_endtk.summary ()
        self.matchedCleanJetHistosResolution_endtk.Write (self.file)
        
        self.matchedCleanJetHistosResolution_endNOtk.summary ()
        self.matchedCleanJetHistosResolution_endNOtk.Write (self.file)
        
        self.matchedCleanJetHistosResolution_fwd.summary ()
        self.matchedCleanJetHistosResolution_fwd.Write (self.file)

        if self.doJetIdHisto:
            self.gluCleanHistosId.summary()
            self.gluCleanHistosId.Write(self.file)
            
            self.quarkCleanHistosId.summary()
            self.quarkCleanHistosId.Write(self.file)
            
            self.reweiMatchedCleanHistosId.summary()
            self.reweiMatchedCleanHistosId.Write(self.file)
        
            ### self.matchedCleanHistosId.Write(self.file)
            self.unmatchedCleanHistosId.Write(self.file)
        
        self.file.cd ()
        self.h_nvtx.Write ()
        self.h_genjetspt.Write ()
        self.h_secondClosestVsPtratio.Write ()
        self.h_avedistanceVSNvtx.Write ()
        self.h_PTRatioVSgenEta.Write ()
        self.h_PTRatioVSgenPt.Write ()
        self.h_matchDR.Write ()
        self.h_relPtVSmatchDR.Write ()
        self.h_relPtVSchFrac.Write ()
        
        self.file.Close()