def analyze(self, event): #called by the eventloop per-event
        """process event, return True (go to next module) or False (fail, go to next event)"""
        #Increment counter and skip events past the maxEventsToProcess, if larger than -1
        self.counter +=1
        if -1 < self.maxEventsToProcess < self.counter:
            return False        
        if self.probEvt:
            if event.event != self.probEvt:
                print("Skipping...")
                return False
        
        ###############################################
        ### Collections and Objects and isData check###
        ###############################################

        gens = Collection(event, "GenPart")
        bs = [gen for gen in gens if abs(gen.pdgId) == 5]
        Ws = [gen for gen in gens if abs(gen.pdgId) == 24]
        WFirst = [gen for gen in Ws if gen.genPartIdxMother > -1 and abs(gens[gen.genPartIdxMother].pdgId) == 6]#.sort(key=lambda g : gens[g.genPartIdxMother].pt, reverse=True)
        bFirst = [gen for gen in bs if gen.genPartIdxMother > -1 and abs(gens[gen.genPartIdxMother].pdgId) == 6]#.sort(key=lambda g : gens[g.genPartIdxMother].pt, reverse=True)
        tops = set([gen.genPartIdxMother for gen in WFirst])
        self.h_bfcount.Fill(len(bFirst))
        self.h_Wfcount.Fill(len(WFirst))
        bFirst = [gen for gen in bFirst if gen.genPartIdxMother in tops]
        self.h_bfpcount.Fill(len(bFirst))
        WFirst.sort(key=lambda g : gens[g.genPartIdxMother].pt, reverse=True)
        bFirst.sort(key=lambda g : gens[g.genPartIdxMother].pt, reverse=True)
        for i in xrange(len(WFirst)):
            b = bFirst[i]
            W = WFirst[i]
            t = gens[bFirst[i].genPartIdxMother]
            self.h_TopSystemPt[i].Fill(t.pt, b.pt, W.pt)
            stats = ""
            for flag, bits in self.bits.iteritems():
                if flag not in ['fromHardProcessBeforeFSR','isFirstCopy','isLastCopy','isLastCopyBeforeFSR']: continue
                if b.statusFlags & bits:
                    stats += " " + flag
            self.h_bSystemCorr[i].Fill(abs(t.eta - b.eta), b.pt, stats, 1.0)
            b_mass = (t.p4() - W.p4()).M()
            tVec = ROOT.Math.PtEtaPhiMVector(t.pt, t.eta, t.phi, t.mass)
            bVec = ROOT.Math.PtEtaPhiMVector(b.pt, b.eta, b.phi, b_mass)

        return True
def mL3(ev):
    # transverse mass of the three lepton system and met...
    all_leps = [l for l in Collection(ev, "LepGood")]
    nFO = getattr(ev, "nLepFO_Recl")
    chosen = getattr(ev, "iLepFO_Recl")
    leps = [all_leps[chosen[i]] for i in xrange(nFO)]

    if len(leps) < 3: return 0
    v1 = r.TLorentzVector()
    v2 = r.TLorentzVector()
    v3 = r.TLorentzVector()
    v1.SetPtEtaPhiM(leps[0].conePt, leps[0].eta, leps[0].phi, 0)
    v2.SetPtEtaPhiM(leps[1].conePt, leps[1].eta, leps[1].phi, 0)
    v3.SetPtEtaPhiM(leps[2].conePt, leps[2].eta, leps[2].phi, 0)
    v = v1 + v2 + v3
    met = ev.MET_pt if ev.year != 2017 else ev.METFixEE2017_pt
    met_phi = ev.MET_phi if ev.year != 2017 else ev.METFixEE2017_phi
    return sqrt((v.Et() + met)**2 - (v.Px() + met_px)**2 -
                (v.Py() + met_py)**2)
 def analyze(self, event):
     """process event, return True (go to next module) or False (fail, go to next event)"""
     coll = [Collection(event, x) for x in self.input]
     objects = [(coll[j][i], j, i) for j in range(self.nInputs)
                for i in range(len(coll[j]))]
     if self.selector:
         objects = [
             obj_j_i for obj_j_i in objects
             if self.selector[obj_j_i[1]](obj_j_i[0])
         ]
     objects.sort(key=self.sortkey, reverse=self.reverse)
     if self.maxObjects:
         objects = objects[:self.maxObjects]
     for bridx, br in enumerate(self.brlist_all):
         out = []
         for obj, j, i in objects:
             out.append(getattr(obj, br) if self.is_there[bridx][j] else 0)
         self.out.fillBranch("%s_%s" % (self.output, br), out)
     return True
Beispiel #4
0
 def analyze(self, event):
     #self._n += 1
     jetvals = [
         getattr(j, self._bTagLabel) for j in Collection(event, 'Jet')
         if self._jetCut(j)
     ]
     for (W, cut) in zip(self._WPs, self._ops[event.year]):
         self.out.fillBranch("nBJet%s%s" % (self._label, W),
                             sum([(v > cut) for v in jetvals]))
     #if self._n < 20:
     #    print "New event: (year: %d) " % event.year
     #    for j in Collection(event, 'Jet'):
     #        print "  jet pt %6.1f  eta %+5.2f  id %2d  sel %1d    btag %+.4f" % (j.pt, j.eta, j.jetId, int(self._jetCut(j)),  getattr(j, self._bTagLabel))
     #    print "All btags of selected jets: ", jetvals
     #    print "WPs for this year: ", self._ops[event.year]
     #    for (W,cut) in zip(self._WPs,self._ops[event.year]):
     #        print "nBJet%s%s: %2d" % (self._label, W, sum([(v > cut) for v in jetvals]))
     #    print ""
     return True
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""
        if not self.isFastsim:
            return True

        genpar = Collection(event, "GenPart")

        mass = np.asarray([g.mass for g in genpar])
        pdgId = np.asarray([g.pdgId for g in genpar])
        status = np.asarray([g.status for g in genpar])
        mothermass = np.unique(mass[(status == 62) & (np.absolute(pdgId) >  1000000    ) ] )
        LSPmass    = np.unique(mass[(status == 1)  & (pdgId              == 1000022)])
        if mothermass.shape != (1,) or LSPmass.shape != (1,):
            print("Danger: mothermass or LSPmass is not unique")

        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Store output ~~~~~
        self.out.fillBranch("Stop0l_MotherMass", mothermass[0])
        self.out.fillBranch("Stop0l_LSPMass", LSPmass[0])
        return True
    def __init__(
        self,
        modelPath,
        featureDictFile,
        inputCollections = [lambda event: Collection(event, "Jet")],
        taggerName = "llpdnnx",
        predictionLabels = ["B","C","UDS","G","PU","isLLP_QMU_QQMU","isLLP_Q_QQ"], #this is how the output array from TF is interpreted
        evalValues = range(-1, 4),
        integrateDisplacementOrder = 3,
        globalOptions = {"isData":False},
    ):
        self.globalOptions = globalOptions
        self.inputCollections = inputCollections
        self.predictionLabels = predictionLabels
        self.evalValues = list(evalValues)
        self.nEvalValues = len(evalValues)
        self.integrateDisplacementOrder = integrateDisplacementOrder
        
        self.modelPath = os.path.expandvars(modelPath)
        print featureDictFile
        self.featureDict = imp.load_source(
            'feature_dict', 
            os.path.expandvars(featureDictFile)
        ).featureDict
        self.taggerName = taggerName
        if self.integrateDisplacementOrder != -1:
            self.integrate = True
            self.abscissas, self.weights = getAbscissasAndWeights(self.integrateDisplacementOrder)
        else:
            self.integrate = False

        if self.integrate:
            file_path = "PhysicsTools/NanoAODTools/data/hnl/L0.json"
            with open(file_path) as json_file:
                L0_values = json.load(json_file)
            for sample, L0 in L0_values.iteritems():
                print sample, L0
                for abscissa in self.abscissas:
                    logDisplacement = math.log10(L0*abscissa)
                    self.evalValues.append(logDisplacement)

        self.evalValues = np.array(self.evalValues, dtype=np.float32)
        print "Evaluation values:" , self.evalValues
    def analyze(self, event):
        if self.globalOptions['isData']:
            return True

        jets = self.inputCollection(event)
        jetOrigin = Collection(event, "jetorigin")

        latentVariableDict = {}

        for latentVariable in self.latentVariables:
            latentVariableDict[latentVariable] = [-1.] * len(jets)

        flavors = {}

        for k in sorted(self.flags.keys()):
            flavors[k] = [-1.] * len(jets)
            self.out.branch(self.outputName + "_" + k,
                            "F",
                            lenVar="n" + self.outputName)

        for ijet, jet in enumerate(jets):
            for k in sorted(self.flags.keys()):
                flavorFlag = 0.
                for originFlag in self.flags[k]:
                    flagValue = getattr(jetOrigin[jet._index], originFlag)
                    if (flagValue > 0.5):
                        flavorFlag = 1.
                        break
                flavors[k][ijet] = flavorFlag
                setattr(jet, k, flavorFlag > 0.5)
            for latentVariable in self.latentVariables:
                latentVariableDict[latentVariable][ijet] = getattr(
                    jetOrigin[jet._index], latentVariable)

        for k in sorted(self.flags.keys()):
            self.out.fillBranch(self.outputName + "_" + k, flavors[k])

        if not self.globalOptions['isData']:
            for latentVariable in self.latentVariables:
                self.out.fillBranch(self.outputName + "_" + latentVariable,
                                    latentVariableDict[latentVariable])

        return True
Beispiel #8
0
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""

        # Muon selection
        all_muons = Collection(event, "Muon")
        nMuons = len(all_muons)
        pass_muons = [
            mu for mu in all_muons if muonPassSelection(mu, skipIsolation=True)
        ]
        if self.isWlike:
            if nMuons < 2: return False
            # require that at least two muons pass the selection except isolation
            if len(pass_muons) < 2: return False
        else:
            if nMuons < 1: return False
            # require that at least one muon passes the selection except isolation
            if len(pass_muons) < 1: return False

        return True
Beispiel #9
0
    def analyze(self, event):
        tt_cand = []
        genParts = Collection(event, 'GenPart')
        for part in genParts:
            if abs(part.pdgId) == 6 and self.isLastCopy(part):
                tt_cand.append(part)

        weight = 1.
        if len(tt_cand) != 2:
            print 'WARNING: {} top quarks found. No pt reweighting applied'.format(
                len(tt_cand))
        elif tt_cand[0].pdgId * tt_cand[1].pdgId > 0:
            print 'WARNING: the two top quark candidated have the same charge. No pt reweighting applied'
        else:
            weight = self.getEventWeight(tt_cand)

        self.out.fillBranch('TopPtWeight', weight)

        return True
Beispiel #10
0
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""

        genParticles = Collection(event, "GenPart")

        # reobtain the indices of the good muons and the neutrino
        
        preFSRLepIdx1 = event.GenPart_preFSRLepIdx1
        preFSRLepIdx2 = event.GenPart_preFSRLepIdx2
        
        if preFSRLepIdx1 >= 0 and preFSRLepIdx2 >= 0:
            CStheta_preFSR, CSphi_preFSR = getCSangles(genParticles[preFSRLepIdx1], genParticles[preFSRLepIdx2])
        else: 
            CStheta_preFSR, CSphi_preFSR = -99., -99.

        self.out.fillBranch("CStheta_preFSR",CStheta_preFSR)
        self.out.fillBranch("CSphi_preFSR",CSphi_preFSR)

        return True
Beispiel #11
0
    def analyze(self, event):
        """Nominal variables"""
        jets = Collection(event, '%s' % self.jetbranch)
        met = Object(event, self.metbranch)
        metPt = getattr(met, "pt_nom", "pt")
        metPhi = getattr(met, "phi_nom", "phi")
        metPx = metPt * math.cos(metPhi)
        metPy = metPt * math.sin(metPhi)

        for group in self.groups:
            for sign in ['Up', 'Down']:
                jetVar = []
                metPxVar = metPx
                metPyVar = metPy
                for j in jets:
                    thePt = getattr(j, "pt_nom", "pt")
                    thePhi = getattr(j, "phi")
                    jetVar.append(0)
                    for comp in self.groups[group]:
                        jetVar[-1] = (jetVar[-1]**2 +
                                      (getattr(j, "pt_jes" + comp + sign) -
                                       thePt)**2)**0.5

                    metPxVar = metPxVar - (1 if sign == 'Up' else
                                           -1) * jetVar[-1] * math.cos(thePhi)
                    metPyVar = metPyVar - (1 if sign == 'Up' else
                                           -1) * jetVar[-1] * math.sin(thePhi)
                    jetVar[-1] = thePt + (1
                                          if sign == 'Up' else -1) * jetVar[-1]
                self.wrappedOutputTree.fillBranch(
                    "%s_pt_jes%s%s" % (self.jetbranch, group, sign), jetVar)
                self.wrappedOutputTree.fillBranch(
                    "%s_pt_jes%s%s" % (self.metbranch, group, sign),
                    (metPxVar**2 + metPyVar**2)**0.5)

                self.wrappedOutputTree.fillBranch(
                    "%s_phi_jes%s%s" % (self.metbranch, group, sign),
                    math.atan2(metPyVar, metPxVar))
        for br in self.dumpMore:
            self.wrappedOutputTree.fillBranch(br['name'],
                                              getattr(event, br['name']))

        return True
Beispiel #12
0
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""
        jets = Collection(event, "Jet")

        discr = None
        if self.algo == "csvv2":
            discr = "btagCSVV2"
        elif self.algo == "deepcsv":
            discr = "btagDeepB"
        elif self.algo == "cmva":
            discr = "btagCMVA"
        elif self.algo == "deepjet":
            discr = "btagDeepFlavB"
        else:
            raise ValueError(
                "ERROR: Invalid algorithm '%s'! Please choose either 'csvv2' or 'cmva'."
                % self.algo)

        preloaded_jets = [(jet.pt, jet.eta,
                           self.getFlavorBTV(jet.hadronFlavour),
                           getattr(jet, discr)) for jet in jets]
        reader = self.getReader('M', False)
        for central_or_syst in self.central_and_systs:
            central_or_syst = central_or_syst.lower()
            scale_factors = list(
                self.getSFs(preloaded_jets, central_or_syst, reader, 'auto',
                            False))
            self.out.fillBranch(
                self.branchNames_central_and_systs[central_or_syst],
                scale_factors)
        # shape corrections
        reader = self.getReader('shape_corr', True)
        for central_or_syst in self.central_and_systs_shape_corr:
            central_or_syst = central_or_syst.lower()
            scale_factors = list(
                self.getSFs(preloaded_jets, central_or_syst, reader, 'auto',
                            True))
            self.out.fillBranch(
                self.branchNames_central_and_systs_shape_corr[central_or_syst],
                scale_factors)

        return True
Beispiel #13
0
    def analyze(self, event):
        jets = [ j for j in Collection(event, self.jetcoll)] 
        ret = {} 
        for var in self.vars: 
            res = 1
            for jet in jets: 
                if jet.pt<25: continue
                res *= getattr(jet,var)
            ret[var] = res
        if not self.isGroups: 
            resCorrUp  =0; resCorrDown=0;
            resUnCorrUp=0; resUnCorrDown=0;
            for corr in self.corrs:
                resCorrUp     = (resCorrUp**2   + self.corrs[corr]    *(ret['btagSF_shape_up_jes%s'  %corr]-ret['btagSF_shape'])**2)**0.5
                resCorrDown   = (resCorrDown**2 + self.corrs[corr]    *(ret['btagSF_shape_down_jes%s'%corr]-ret['btagSF_shape'])**2)**0.5
                resUnCorrUp   = (resUnCorrUp**2   + (1-self.corrs[corr])*(ret['btagSF_shape_up_jes%s'  %corr]-ret['btagSF_shape'])**2)**0.5
                resUnCorrDown = (resUnCorrDown**2 + (1-self.corrs[corr])*(ret['btagSF_shape_down_jes%s'%corr]-ret['btagSF_shape'])**2)**0.5
            if self.corrs:
                for corr in self.corrs: 
                    ret.pop( 'btagSF_shape_up_jes%s'%corr)
                    ret.pop( 'btagSF_shape_down_jes%s'%corr)
            ret['btagSF_shape_up_jesCorr']     = resCorrUp     + ret['btagSF_shape'] 
            ret['btagSF_shape_down_jesCorr']   = -resCorrDown   + ret['btagSF_shape']
            ret['btagSF_shape_up_jesUnCorr']   = resUnCorrUp   + ret['btagSF_shape']
            ret['btagSF_shape_down_jesUnCorr'] = -resUnCorrDown + ret['btagSF_shape']

        else: 
            for corr in self.corrs:
                ret['btagSF_shape_grouped_up_jes%s'%corr] =0; ret['btagSF_shape_grouped_down_jes%s'%corr] =0; 
                for comp in self.corrs[corr]:
                    if comp == "RelativeSample": continue # not here
                    ret['btagSF_shape_grouped_up_jes%s'%corr] = ( ret['btagSF_shape_grouped_up_jes%s'%corr]**2 + (ret['btagSF_shape_up_jes%s'  %comp]-ret['btagSF_shape'])**2)**0.5

                    ret['btagSF_shape_grouped_down_jes%s'%corr] = ( ret['btagSF_shape_grouped_down_jes%s'%corr]**2 + (ret['btagSF_shape_down_jes%s'  %comp]-ret['btagSF_shape'])**2)**0.5
                    ret.pop( 'btagSF_shape_up_jes%s'%comp)
                    ret.pop( 'btagSF_shape_down_jes%s'%comp)
                ret['btagSF_shape_up_jes%s'%corr]   = ret['btagSF_shape_grouped_up_jes%s'%corr] + ret['btagSF_shape'] 
                ret['btagSF_shape_down_jes%s'%corr] = -ret['btagSF_shape_grouped_down_jes%s'%corr] + ret['btagSF_shape'] 
                ret.pop( 'btagSF_shape_grouped_up_jes%s'%corr )
                ret.pop( 'btagSF_shape_grouped_down_jes%s'%corr )
        writeOutput(self, ret)
        return True
    def analyze(self, event):
        genParticles = Collection(event, "GenPart")

        higgses = sorted(set(map(lambda genPartPair: genPartPair[0], filter(
          lambda genPart:
            genPart[1].pdgId == 25 and \
            (genParticles[genPart[1].genPartIdxMother].pdgId != 25 if genPart[1].genPartIdxMother >= 0 else True),
          enumerate(genParticles)
        ))))
        nofHiggs = len(higgses)

        decayModeVals = []
        if 0 < nofHiggs < 3:
            for idxHiggs in range(nofHiggs):
                higgs_daus = []
                higgs_idx = higgses[idxHiggs]
                while True:
                    for idx, genPart in enumerate(genParticles):
                        if genPart.genPartIdxMother == higgs_idx:
                            if genPart.pdgId == 25:
                                higgs_idx = idx
                                break
                            else:
                                higgs_daus.append(idx)
                    if len(higgs_daus) == 2:
                        break
                higgs_daus_pdgId = list(
                    sorted(set(
                        map(lambda idx: abs(genParticles[idx].pdgId),
                            higgs_daus)),
                           reverse=True))
                decayModeVal = sum(
                    map(lambda pdgId: pdgId[1] * 10**(4 * pdgId[0]),
                        enumerate(higgs_daus_pdgId)))
                decayModeVals.append(decayModeVal)

        genHiggsDecayModeVal = sum(
            map(lambda decMode: decMode[1] * 10**(6 * decMode[0]),
                enumerate(sorted(set(decayModeVals), reverse=True))))

        self.out.fillBranch(self.genHiggsDecayModeName, genHiggsDecayModeVal)
        return True
Beispiel #15
0
 def analyze(self,event):
   """Dump LHE information for each gen particle in given event."""
   print "%s event %s %s"%('-'*10,event.event,'-'*50)
   self.nevents += 1
   leptonic = False
   particles = Collection(event,'GenPart')
   #particles = Collection(event,'LHEPart')
   print " \033[4m%7s %8s %10s %8s %8s %10s %8s %8s %8s %8s %8s %9s %10s %11s %11s \033[0m"%(
     "index","pdgId","particle","moth","mothid", "moth part", "dR","pt","eta", "phi", "status","prompt","last copy", "hard scatter", "W ancestor")
   for i, particle in enumerate(particles):
       mothidx  = particle.genPartIdxMother
       if 0<=mothidx<len(particles):
           moth    = particles[mothidx]
           mothpid = moth.pdgId
           mothdR  = min(10,particle.DeltaR(moth)) #particle.p4().DeltaR(moth.p4())
       else:
           mothpid = 0
           mothdR  = -1
       prompt    = hasBit(particle.statusFlags,0)
       lastcopy  = hasBit(particle.statusFlags,13)
       hardprocess = hasBit(particle.statusFlags,7)
       hasWancestor = (self.hasAncestor( particle, 24, particles) and abs(particle.pdgId)<5)
       try:
           particleName =  Particle.from_pdgid(int(particle.pdgId)).name
       except:
           particleName = str(particle.pdgId)
       try:
           motherName = Particle.from_pdgid(int(mothpid)).name if mothpid != 0 else 'initial'
       except:
           particleName = str(particle.pdgId)
       print " %7d %8d %10s %8d %8d %10s %8.2f %8.2f %8.2f %8.2f %8d %9s %10s %11s %11s"%(
       i,particle.pdgId,particleName,mothidx,mothpid,motherName,mothdR,particle.pt, particle.eta, particle.phi ,particle.status,prompt,lastcopy,hardprocess, hasWancestor)
       if abs(particle.pdgId) in [11,13,15]:
           leptonic = True
       if leptonic:
           self.nleptons += 1
   
   def endJob(self):
       print '-'*70
       if self.nevents>0:
           print "  %-10s %4d / %-4d (%.1f%%)"%('leptonic:',self.nleptons,self.nevents,100.0*self.nleptons/self.nevents)
       print "%s done %s"%('-'*10,'-'*54)
Beispiel #16
0
    def getWeight(self, event):
        """Get pre-fire weight"""

        # WEIGHTS
        weightDown = 1.
        weightNom = 1.
        weightUp = 1.

        # LOOP over JETS
        jets = Collection(event, 'Jet')
        for jid, jet in enumerate(jets):  # First loop over all jets
            jetpt = jet.pt
            ###if self.UseEMpT:
            ###  jetpt *= (jet.chEmEF + jet.neEmEF)

            if jetpt >= self.JetMinPt and self.JetMinEta <= abs(
                    jet.eta) <= self.JetMaxEta:
                pfProbDown, pfProbNom, pfProbUp = self.getPrefireProbability(
                    self.jetmap, jet.eta, jetpt, self.JetMaxPt)
                jetWeightDown = 1. - pfProbDown
                jetWeightNom = 1. - pfProbNom
                jetWeightUp = 1. - pfProbUp
            else:
                jetWeightDown = 1.0
                jetWeightNom = 1.0
                jetWeightUp = 1.0

            # The higher prefire-probablity between the jet and the lower-pt photon(s)/elecron(s) from the jet is chosen
            egWeightDown, egWeightNom, egWeightUp = self.getEGPrefireWeight(
                event, jid)
            weightDown *= min(jetWeightDown, egWeightDown)
            weightNom *= min(jetWeightNom, egWeightNom)
            weightUp *= min(jetWeightUp, egWeightUp)

        # Then loop over all photons/electrons not associated to jets
        egWeightDown, egWeightNom, egWeightUp = self.getEGPrefireWeight(
            event, -1)
        weightDown *= egWeightDown
        weightNom *= egWeightNom
        weightUp *= egWeightUp

        return weightDown, weightNom, weightUp
Beispiel #17
0
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""

        jets = Collection(event, "Jet")

        # Options
        self.JetMinPt = 20  # Min/Max Values may need to be fixed for new maps
        self.JetMaxPt = 500
        self.JetMinEta = 2.0
        self.JetMaxEta = 3.0
        self.PhotonMinPt = 20
        self.PhotonMaxPt = 500
        self.PhotonMinEta = 2.0
        self.PhotonMaxEta = 3.0

        for i, bname in zip([0, 1, -1], self.branchnames):
            self.variation = i
            prefw = 1.0

            for jid, jet in enumerate(jets):  # First loop over all jets
                jetpf = 1.0
                PhotonInJet = []

                jetpt = jet.pt
                if self.UseEMpT: jetpt *= (jet.chEmEF + jet.neEmEF)

                if jetpt >= self.JetMinPt and abs(
                        jet.eta) <= self.JetMaxEta and abs(
                            jet.eta) >= self.JetMinEta:
                    jetpf *= 1 - self.GetPrefireProbability(
                        self.jet_map, jet.eta, jetpt, self.JetMaxPt)

                phopf = self.EGvalue(event, jid)
                prefw *= min(
                    jetpf, phopf
                )  # The higher prefire-probablity between the jet and the lower-pt photon(s)/elecron(s) from the jet is chosen

            prefw *= self.EGvalue(
                event, -1
            )  # Then loop over all photons/electrons not associated to jets
            self.out.fillBranch(bname, prefw)
        return True
def gettoppt(event):
    """Calculate top pT."""
    #print '-'*80
    particles = Collection(event, 'GenPart')
    toppt1 = -1
    toppt2 = -1
    for id in range(event.nGenPart):
        particle = particles[id]
        PID = abs(particle.pdgId)
        if PID == 6 and particle.status == 62:
            #print "%3d: PID=%3d, mass=%3.1f, pt=%3.1f, status=%2d"%(id,particle.pdgId,particle.mass,particle.pt,particle.status)
            if particle.pt > toppt1:
                if toppt1 == -1:
                    toppt1 = particle.pt
                else:
                    toppt2 = toppt1
                    toppt1 = particle.pt
            else:
                toppt2 = particle.pt
    return toppt1, toppt2
Beispiel #19
0
 def __init__(
         self,
         inputCollection=lambda event: Collection(event, "Jet"),
         taggerName="llpdnnx",
         outputName="llpdnnx",
         predictionLabels=[
             "B", "C", "UDS", "G", "PU", "isLLP_QMU_QQMU", "isLLP_Q_QQ"
         ],  #this is how the output array from TF is interpreted
         logctauValues=range(-1, 4),
         multiplicities=[0, 1, 2],
         globalOptions={"isData": False}):
     self.globalOptions = globalOptions
     self.inputCollection = inputCollection
     self.outputName = outputName
     self.predictionLabels = predictionLabels
     self.logctauValues = logctauValues
     self.multiplicities = multiplicities
     self.logctauLabels = map(lambda ctau: getCtauLabel(ctau),
                              logctauValues)
     self.taggerName = taggerName
    def loop_over_taus(self):
        self.taus = []
        for tau in Collection(self.event,"Tau"):
            # check overlap with passing muon
            muOverlap = any([tau.DeltaR(mu) < 0.3 for mu in self.muons])
            # check overlap with passing electon
            elOverlap = any([tau.DeltaR(el) < 0.3 for el in self.electrons])


            # apply cut
            # receipe for deep2017v2p1 # all WP is tight
            # https://twiki.cern.ch/twiki/bin/viewauth/CMS/TauIDRecommendationForRun2
            if tau.pt>20 and abs(tau.eta)<2.3 \
                and (not muOverlap) and (not elOverlap) \
                and tau.idDecayModeNewDMs \
                and tau.idDeepTau2017v2p1VSe>=32 \
                and tau.idDeepTau2017v2p1VSjet>=32 \
                and tau.idDeepTau2017v2p1VSmu>=8 \
                :
                self.taus.append(tau)
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""
        jets = Collection(event, self.jetCollectionName)
        met_phi = getattr(event, self.metCollectionName + "_phi")

        if (len(jets) > 0 and met_phi):

            Min = 1000000
            for jet in jets:
                phi = abs(jet.p4().Phi() - met_phi)

                if (Min > phi):
                    Min = phi

            if (Min == 1000000):
                Min = -1000
            self.out.fillBranch("JetMetMin_dPhijj", Min)
        else:
            self.out.fillBranch("JetMetMin_dPhijj", -1000)
        return True
Beispiel #22
0
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""
        ret={}
        jets = Collection(event,self.jetCollection)
        #isDataEvent = event.isData
        for V in self.vars:
            branch = getattr(self, "JetDummy_"+V)
            ret[self.jetCollection+self.label+"_"+V] = [getattr(j,V) for j in jets]
        if event._tree._ttreereaderversion > self._ttreereaderversion: # do this check at every event, as other modules might have read further branches
            self.initReaders(event._tree)
        # do NOT access other branches in python between the check/call to initReaders and the call to C++ worker code
        ## Algo
        cleanJets = self._worker.run()
        ## Output
        self.out.fillBranch('n'+self.jetCollection+self.label, len(cleanJets))
        self.out.fillBranch(self.jetCollection+self.label+"_"+self.jetidvar, [ int(j) for j in cleanJets ])
        for V in self.vars:
            self.out.fillBranch(self.jetCollection+self.label+"_"+V, [ ret[self.jetCollection+self.label+"_"+V][j] for j in cleanJets ])

        return True
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""

        if not self.isMC:
            return True

        genparts = Collection(event, "GenPart")
        for idx, gp in enumerate(genparts):
            if not hasattr(gp, 'dauIdx'):
                gp.dauIdx = []
            if gp.genPartIdxMother >= 0:
                mom = genparts[gp.genPartIdxMother]
                if not hasattr(mom, 'dauIdx'):
                    mom.dauIdx = [idx]
                else:
                    mom.dauIdx.append(idx)

        genTops = []
        for gp in genparts:
            if gp.statusFlags & (1 << 13) == 0:
                # 13: isLastCopy
                continue
            if abs(gp.pdgId) == 6:
                genTops.append(gp)

        topptWeight = 1.

        if len(genTops) == 2:

            # ttbar (+X ?)
            def wgt(pt):
                return np.exp(0.0615 - 0.0005 * np.clip(pt, 0, 800))

            topptWeight = np.sqrt(wgt(genTops[0].pt) * wgt(genTops[1].pt))

        self.out.fillBranch('topptWeight', topptWeight)
        # accumulation hists
        self.h_genwgt.Fill(0.5, event.genWeight)
        self.h_ttbar_topptwgt.Fill(0.5, topptWeight * event.genWeight)

        return True
Beispiel #24
0
def genmatch(event, index, out=None):
    """Match reco tau to gen particles, as there is a bug in the nanoAOD matching
    for lepton to tau fakes of taus reconstructed as DM1."""
    genmatch = 0
    dR_min = 0.2
    particles = Collection(event, 'GenPart')
    eta_reco = event.Tau_eta[index]
    phi_reco = event.Tau_phi[index]

    # lepton -> tau fakes
    for id in range(event.nGenPart):
        particle = particles[id]
        PID = abs(particle.pdgId)
        if (particle.status != 1 and PID != 13) or particle.pt < 8: continue
        dR = deltaR(eta_reco, phi_reco, particle.eta, particle.phi)
        if dR < dR_min:
            if hasBit(particle.statusFlags, 0):  # isPrompt
                if PID == 11:
                    genmatch = 1
                    dR_min = dR
                elif PID == 13:
                    genmatch = 2
                    dR_min = dR
            elif hasBit(particle.statusFlags,
                        5):  # isDirectPromptTauDecayProduct
                if PID == 11:
                    genmatch = 3
                    dR_min = dR
                elif PID == 13:
                    genmatch = 4
                    dR_min = dR

    # real tau leptons
    for id in range(event.nGenVisTau):
        dR = deltaR(eta_reco, phi_reco, event.GenVisTau_eta[id],
                    event.GenVisTau_phi[id])
        if dR < dR_min:
            dR_min = dR
            genmatch = 5

    return genmatch
Beispiel #25
0
 def analyze(self, event):
     """Dump gen information for each gen particle in given event."""
     print "\n%s event %s %s" % ('-' * 10, event.event, '-' * 68)
     self.nevents += 1
     leptonic = False
     particles = Collection(event, 'GenPart')
     #particles = Collection(event,'LHEPart')
     seeds = []  # seeds for decay chain
     chain = {}  # decay chain
     print " \033[4m%7s %8s %8s %8s %8s %8s %8s %8s %9s %10s  \033[0m" % (
         "index", "pdgId", "moth", "mothid", "dR", "pt", "eta", "status",
         "prompt", "last copy")
     for i, particle in enumerate(particles):
         mothidx = particle.genPartIdxMother
         if 0 <= mothidx < len(particles):
             moth = particles[mothidx]
             mothpid = moth.pdgId
             mothdR = min(
                 9999,
                 particle.DeltaR(moth))  #particle.p4().DeltaR(moth.p4())
         else:
             mothpid = -1
             mothdR = -1
         eta = max(-9999, min(9999, particle.eta))
         prompt = hasbit(particle.statusFlags, 0)
         lastcopy = hasbit(particle.statusFlags, 13)
         print " %7d %8d %8d %8d %8.2f %8.2f %8.2f %8d %9s %10s" % (
             i, particle.pdgId, mothidx, mothpid, mothdR, particle.pt, eta,
             particle.status, prompt, lastcopy)
         if abs(particle.pdgId) in [11, 13, 15]:
             leptonic = True
         if mothidx in chain:  # add to decay chain
             chain[mothidx].append(i)
             chain[i] = []  # daughters
         elif abs(particle.pdgId
                  ) in self.seedpids:  # save as decay chain seed
             seeds.append(i)
             chain[i] = []  # daughters
     if leptonic:
         self.nleptons += 1
     print parsechain(particles, seeds, chain)  # print decay chain
    def prepareEvent(self, event):

        logging.debug('processing event %d' % event.event)

        ## select leading photon
        event._allPhotons = Collection(event, "Photon")
        event.photons = []
        for pho in event._allPhotons:
            if not (pho.pt > 200 and abs(pho.eta) < 2.4 and
                    (pho.cutBasedBitmap & 2)
                    and pho.electronVeto):  # medium ID
                continue
            event.photons.append(pho)

        if len(event.photons) < 1:
            return False

        ## selection on AK8 jets / drop if overlaps with a photon
        event.ak8jets = []
        for fj in event._allAK8jets:
            if not (fj.pt > 200 and abs(fj.eta) < 2.4 and (fj.jetId & 2)):
                continue
            # require jet and photon to be back-to-back
            if deltaPhi(event.photons[0], fj) < 2:
                continue
#             if deltaR(event.photons[0], fj) < self._jetConeSize:
#                 continue
            event.ak8jets.append(fj)
        if len(event.ak8jets) < 1:
            return False

        ## ht
        event.ak4jets = []
        for j in event._allJets:
            if not (j.pt > 25 and abs(j.eta) < 2.4 and (j.jetId & 2)):
                continue
            event.ak4jets.append(j)
        event.ht = sum([j.pt for j in event.ak4jets])

        ## return True if passes selection
        return True
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""
        muons = list(Collection(event, "Muon"))

        evtweight = 1.0
        if self.isMC:
            evtweight = event.genWeight

        #################################################
        # Register cut before ANY selection
        ##################################################
        self.RegisterCut("Cut0:NoSelection", evtweight)

        #################################################
        #
        # Muon selection
        #
        ##################################################
        #
        # Select muons
        #
        muonsLoose = []
        for mu in muons:
            #
            # Loose selection
            #
            if mu.pt < 20. or abs(mu.eta) > 2.6: continue
            if mu.looseId is False and mu.highPtId < 1: continue
            muonsLoose.append(mu)
        #
        # CHECK: AT LEAST 2 Loose muon.
        # Skip event if doSkim=True
        #
        if len(muonsLoose) < 2:
            if self.doSkim:
                return False
        else:
            self.RegisterCut("Cut1:>=2LooseMuon", evtweight)

        return True
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""
        ## Getting objects
        if not self.isData: genpart = Collection(event, "GenPart")

        if "TTbar" in self.sampleName:
            toppt_wgt, toppt_only, toppt_mgpow, toppt_up, toppt_dn = self.topPTWeight(
                genpart)
        else:
            toppt_wgt = 1.
            toppt_only = 1.
            toppt_mgpow = 1.
            toppt_up = 1.
            toppt_dn = 1.
        #print("toppt_wgt: {0}".format(toppt_lep))
        self.out.fillBranch('Stop0l_topptWeight', toppt_wgt)
        self.out.fillBranch('Stop0l_topMGPowWeight', toppt_mgpow)
        self.out.fillBranch('Stop0l_topptOnly', toppt_only)
        self.out.fillBranch('Stop0l_topptOnly_Up', toppt_up)
        self.out.fillBranch('Stop0l_topptOnly_Down', toppt_dn)

        return True
Beispiel #29
0
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""
        if self.isMC == 0: return False

        genpart = Collection(event, "GenPart")
        allGenPart = list(filter(lambda x: x.pt > -9999, genpart))
        if self.flavour != None:
            flavourGenPart = list(
                filter(lambda x: str(abs(x.pdgId)) in self.flavour, genpart))

        else:
            flavourGenPart = allGenPart

        momIdx2 = []

        for j in allGenPart:
            if j in flavourGenPart:
                if j.genPartIdxMother > 0:
                    if genpart[j.genPartIdxMother].pdgId != j.pdgId:
                        momIdx2.append(j.genPartIdxMother)
                    else:
                        mom = genpart[j.genPartIdxMother]
                        son = j

                        while (mom.pdgId == son.pdgId
                               and son.genPartIdxMother > 0
                               and mom.genPartIdxMother > 0):

                            son = mom
                            mom = genpart[son.genPartIdxMother]
                        if (mom.pdgId == son.pdgId): momIdx2.append(-1)
                        else: momIdx2.append(allGenPart.index(mom))

                else: momIdx2.append(-1)
            else: momIdx2.append(-1)

        self.out.fillBranch("GenPart_genPartIdxMother_prompt", momIdx2)

        return True
    def analyze(self, event):
        genParticles = Collection(event, "GenPart")

        genHiggsDecayModeVal = 0
        nofHiggs = len(
            list(
                filter(lambda genParticle: genParticle.pdgId == 25,
                       genParticles)))
        if nofHiggs > 0:
            h0_daus = list(filter(
              lambda genParticle: genParticle.genPartIdxMother >= 0 and \
                                  genParticles[genParticle.genPartIdxMother].pdgId == 25 and \
                                  genParticle.pdgId != 25,
              genParticles
            ))
            genHiggsDecayModeVal = abs(
                h0_daus[0].pdgId if len(h0_daus) >= 1 else 0)
            genHiggsDecayModeVal += abs(h0_daus[1].pdgId if len(h0_daus) >= 2 and \
                                                            abs(h0_daus[0].pdgId) != abs(h0_daus[1].pdgId) else 0) * 10000

        self.out.fillBranch(self.genHiggsDecayModeName, genHiggsDecayModeVal)
        return True