Example #1
0
 def __init__(
     self,
     inputCollections = [
         [lambda event: Collection(event, "Electron"),["pt"]]
     ],
     saveAs = None,
     compareTo = None
 ):
     self.inputCollections = inputCollections
     self.saveAs = saveAs
     self.compareTo = compareTo
Example #2
0
 def __init__(self,
              inputCollection=lambda event: Collection(event, "Muon"),
              outputName="vetoMuons",
              muonMinPt=10.,
              muonMaxEta=2.4,
              globalOptions={"isData": False}):
     self.globalOptions = globalOptions
     self.inputCollection = inputCollection
     self.outputName = outputName
     self.muonMinPt = muonMinPt
     self.muonMaxEta = muonMaxEta
Example #3
0
 def __init__(
     self,
     inputCollection=lambda event: Collection(event, "Electron"),
     outputName="vetoElectrons",
     electronMinPt=10.,
     electronMaxEta=2.4,
 ):
     self.inputCollection = inputCollection
     self.outputName = outputName
     self.electronMinPt = electronMinPt
     self.electronMaxEta = electronMaxEta
 def correctJetMET_Data(self, event):
     """Process data event."""
     ###print ">>> %8s "%event.event + '-'*80
     
     # NOMINAL VALUES
     jets_pt_nom = [ ]
     if self.corrMET:
         met = Object(event, self.metBranchName)
         met_px_nom, met_py_nom = met.pt*cos(met.phi), met.pt*sin(met.phi)
     
     # APPLY JEC per jet
     jets = Collection(event, self.jetBranchName )
     rho  = getattr(event, self.rhoBranchName)
     for jet in jets:
         
         # RAW VALUES
         jet_pt0   = jet.pt
         if hasattr(jet,'rawFactor'):
           jet_pt_raw = jet_pt0 * (1 - jet.rawFactor)
         else:
           jet_pt_raw = -1.0 * jet_pt0 # if factor not present factor will be saved as -1
         
         # CALIBRATE - apply JES corrections
         if self.redoJEC:
           jet_pt_nom, jet_mass_nom = self.jetReCalibrator.correct(jet,rho)
           jet.pt   = jet_pt_nom
           jet.mass = jet_mass_nom
         else:
           jet_pt_nom   = jet.pt
           jet_mass_nom = jet.mass
         jets_pt_nom.append(jet_pt_nom)
         ###print "%10.4f %10.4f %10.5f %10.5f"%(jet_pt_raw,jet_pt_nom,jet.eta,jet.rawFactor)
         ###print "%10.4f %8.4f %8.4f %10.6f %10.6f"%(jet_pt_raw, jet_pt0, jet_pt_nom, jet.rawFactor, jet_pt_nom/jet_pt_raw-1.)
         
         #### UPDATE JET in event
         ###if self.updateEvent:
         ###  getattr(event,self.jetBranchName+'_pt')[jet._index] = jet_pt_nom
         
         # PROPAGATE JES corrections to MET
         if self.corrMET and jet_pt_nom > self.unclEnThreshold:
           jet_cosPhi = cos(jet.phi)
           jet_sinPhi = sin(jet.phi)
           met_px_nom = met_px_nom - (jet_pt_nom - jet_pt0)*jet_cosPhi
           met_py_nom = met_py_nom - (jet_pt_nom - jet_pt0)*jet_sinPhi
     
     # PREPARE MET for return
     if self.corrMET:
         met_nom = TLorentzVector(met_px_nom,met_py_nom,0,sqrt(met_px_nom**2+met_py_nom**2))
         ###if self.updateEvent:
         ###  setattr(event,self.metBranchName+'_pt',  met_vars['nom'].Pt())
         ###  setattr(event,self.metBranchName+'_phi', met_vars['nom'].Phi())
         return jets_pt_nom, met_nom
     
     return jets_pt_nom
Example #5
0
 def __init__(
     self,
     inputCollection = lambda event: Collection(event, "Muon"),
     outputName = "vetoMuons",
     muonMinPt = 10.,
     muonMaxEta = 2.4,
 ):
     self.inputCollection = inputCollection
     self.outputName = outputName
     self.muonMinPt = muonMinPt
     self.muonMaxEta = muonMaxEta
Example #6
0
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""
        jets = Collection(event, self.jetBranchName )
        jets_puId17 = []
        
        for jet in jets:
            jets_puId17.append(JetPuId17(jet.pt, jet.eta, jet.puIdDisc)) 
        
        self.out.fillBranch("%s_puId17" % self.jetBranchName, jets_puId17)

        return True
    def prepareEvent(self, event):

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

        # # ht selection
        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])
        if event.ht < 1000.:
            return False

        ## selection on AK8 jets
        event.fatjets = []
        for fj in event._allFatJets:
            if not (fj.pt > 200 and abs(fj.eta) < 2.4 and (fj.jetId & 2)):
                continue
            event.fatjets.append(fj)
        if len(event.fatjets) < 2:
            return False

        ## selection on SV
        event._allSV = Collection(event, "SV")
        event.secondary_vertices = []
        for sv in event._allSV:
            #             if sv.ntracks > 2 and abs(sv.dxy) < 3. and sv.dlenSig > 4:
            #             if sv.dlenSig > 4:
            if True:
                event.secondary_vertices.append(sv)
        if len(event.secondary_vertices) < 2:
            return False
        event.secondary_vertices = sorted(event.secondary_vertices,
                                          key=lambda x: x.pt,
                                          reverse=True)  # sort by pt
        #         event.secondary_vertices = sorted(event.secondary_vertices, key=lambda x : x.dxySig, reverse=True)  # sort by dxysig

        # selection on the probe jet (sub-leading in pT)
        probe_fj = event.fatjets[1]
        if not (probe_fj.pt > 200 and probe_fj.msoftdrop > 50
                and probe_fj.msoftdrop < 200):
            return False
        # require at least 1 SV matched to each subjet
        self.matchSVToSubjets(event, probe_fj)
        if len(probe_fj.subjets[0].sv_list) == 0 or len(
                probe_fj.subjets[1].sv_list) == 0:
            return False
        # match SV also to the leading jet
        self.matchSVToSubjets(event, event.fatjets[0])

        ## return True if passes selection
        return True
Example #8
0
    def analyze(self, event):
        #get +/- gen weight as in countHistogramModule
        binary_gen_weight = self.get_binary_event_weight(event)
        #cutflow all events
        self.fill_cutflow(1, binary_gen_weight)

        ###
        ##HLT
        ###
        HLT_select = False
        for trigger in self._triggers:
            if event[trigger]:
                HLT_select = 1
                break
        if not HLT_select: return False
        #cutflow after hlt
        self.fill_cutflow(2, binary_gen_weight)

        ###
        ##Objects
        ###
        electrons = sorted(filter(lambda x: self.eleSel(x),
                                  Collection(event, "Electron")),
                           key=lambda x: x.pt)
        bJets = sorted(filter(lambda x: self.bjetSel(x, "nom"),
                              Collection(event, "Jet")),
                       key=lambda x: x.pt)

        ###
        ##Electrons
        ###
        if not self.selectDiEle(electrons): return False
        self.fill_cutflow(3, binary_gen_weight)

        ###
        ##Jets
        ###
        if not len(bJets) == 1: return False
        self.fill_cutflow(4, binary_gen_weight)

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

        cleanjets = Collection(event, "CleanJet")

        # latino's
        # loose
        bWP_v1 = {'2016': 0.1522, '2017': 0.1522, '2018': 0.1241}

        # alberto's
        # https://github.com/zucchett/NanoSkim/blob/master/Skimmer/samesign.py#L118-L135
        # medium
        bWP_v2 = {'2016': 0.6321, '2017': 0.4941, '2018': 0.4184}

        bJet20 = filter(self.jetSel, cleanjets)
        bJet30 = filter(lambda x: x.pt > 30 and abs(x.eta) < 2.5, cleanjets)

        nbjet_v1 = 0
        btagSF_v1 = 1.
        bReqSF_v1 = 1.
        nbjet_v2 = 0
        btagSF_v2 = 1.
        bReqSF_v2 = 1.

        # v1
        for ijet in bJet20:
            jetIdx = ijet.jetIdx
            if jetIdx < 0: continue
            if event.Jet_btagDeepB[jetIdx] > bWP_v1[self.year]: nbjet_v1 += 1

        btagSF_v1 = sum(
            map(lambda y: ROOT.TMath.Log(event.Jet_btagSF_shape[y.jetIdx]),
                bJet20)) if self.isMC else 1.

        # v2
        for ijet in bJet30:
            jetIdx = ijet.jetIdx
            if jetIdx < 0: continue
            if event.Jet_btagDeepB[jetIdx] >= bWP_v2[self.year]: nbjet_v2 += 1

        btagSF_v2 = sum(
            map(lambda y: ROOT.TMath.Log(event.Jet_btagSF_shape[y.jetIdx]),
                bJet30)) if self.isMC else 1.

        self.out.fillBranch("bVeto_v1", 1 if nbjet_v1 == 0 else 0)
        self.out.fillBranch("bVeto_v2", 1 if nbjet_v2 == 0 else 0)
        self.out.fillBranch("bVetoSF_v1", ROOT.TMath.Exp(btagSF_v1))
        self.out.fillBranch("bVetoSF_v2", ROOT.TMath.Exp(btagSF_v2))

        # 2017 missing some
        #https://github.com/latinos/PlotsConfigurations/blob/master/Configurations/WH_SS/Full2017nanov6/aliases.py#L146-L149

        return True
Example #10
0
    def selectLeptons(self, event):
        # do lepton selection
        event.looseLeptons = [
        ]  # used for jet lepton cleaning and lepton counting

        electrons = Collection(event, "Electron")
        for el in electrons:
            el.etaSC = el.eta + el.deltaEtaSC
            if el.pt > 7 and abs(el.eta) < 2.4 and abs(el.dxy) < 0.05 and abs(
                    el.dz) < 0.2 and el.pfRelIso03_all < 0.4:
                if el.mvaFall17V2noIso_WP90:
                    event.looseLeptons.append(el)

        muons = Collection(event, "Muon")
        for mu in muons:
            if mu.pt > 5 and abs(mu.eta) < 2.4 and abs(mu.dxy) < 0.5 and abs(
                    mu.dz) < 1.0 and mu.pfRelIso04_all < 0.4:
                if mu.looseId:
                    event.looseLeptons.append(mu)

        event.looseLeptons.sort(key=lambda x: x.pt, reverse=True)
 def analyze(self, event):
     """process event, return True (go to next module) or False (fail, go to next event)"""
     jets = Collection(event, self.jetColl)
     for u, branchname in self.uncerts:
         uworker = self.factorizedUncertainties[u]
         jetUn = []
         for j in jets:
             uworker.setJetEta(j.eta)
             uworker.setJetPt(j.pt)
             jetUn.append(uworker.getUncertainty(True))
         self.out.fillBranch(branchname, jetUn)
     return True
Example #12
0
    def analyze(self, event):
        parts  = Collection(event, 'GenPart')
        nparts = len(parts)
	m1 = -1
	m2 = -1
	for p in parts:
		if getattr(p, "pdgId") == self.p1: m1 = getattr(p,"mass")
		if getattr(p, "pdgId") == self.p2: m2 = getattr(p,"mass")
 
        self.wrappedOutputTree.fillBranch('SMSMassLSP', m1)
        self.wrappedOutputTree.fillBranch('SMSMassNLSP', m2)
        return True
    def analyze(self, event):
        genParticles = [x for x in Collection(event, "GenPart")]

        for gen in genParticles:
            #sTop
            if abs(gen.pdgId) == 1000006:
                self.wrappedOutputTree.fillBranch("GenSusyMStop", gen.mass)
            #Neutralino
            if gen.pdgId == 1000022:
                self.wrappedOutputTree.fillBranch("GenSusyMNeutralino",
                                                  gen.mass)
        return True
 def analyze(self, event):
     leps = [l for l in Collection(event, 'LepGood') ]
     ret = [ 0 for l in leps ]
     if len(leps) == 2:
         for i,l1 in enumerate(leps):
             l2 = leps[1-i]
             if abs(l2.genPartFlav) not in (1,15): continue
             if l2.mvaTTH < 0.9: continue
             if deltaR(l1.eta, l1.phi, l2.eta, l2.phi) < 0.8: continue
             ret[i] = 1
     self.out.fillBranch("LepGood_otherLeptonSelection", ret)
     return True
    def analyze(self, event):
        if self.prescaleFactor == 1:
            self.wrappedOutputTree.fillBranch(self.label, self.prescaleFactor)
            return True

        toBePrescaled = True
        if self.minLeptons > 0:
            muons = filter(self.muonSel, Collection(event, 'Muon'))
            electrons = filter(self.electronSel, Collection(event, 'Electron'))
            leps = muons + electrons
            if len(leps) < self.minLeptonsNoPrescale:
                return False
            if len(leps) >= self.minLeptons:
                if self.requireSameSignPair:
                    if any([(l1.charge * l2.charge > 0)
                            for l1, l2 in itertools.combinations(leps, 2)]):
                        toBePrescaled = False
                else:
                    toBePrescaled = False
        if self.minJets > -1:  #was 0, changed to -1: if 0 cannot clean jets and keep them all
            jets = filter(self.jetSel, Collection(event, 'Jet'))
            if len(jets) >= self.minJets:
                toBePrescaled = False
        if self.minMET > 0:
            if event.MET_pt > self.minMET:
                toBePrescaled = False
        if not toBePrescaled:
            self.wrappedOutputTree.fillBranch(self.label, 1)
            return True
        elif self.prescaleFactor == 0:
            return False
        self.events += 1
        evno = self.events
        if self.useEventNumber:  # use run and LS number multiplied by some prime numbers
            evno = event.event * 223 + event.luminosityBlock * 997
        if (evno % self.prescaleFactor == 1):
            self.wrappedOutputTree.fillBranch(self.label, self.prescaleFactor)
            return True
        else:
            return False
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""
        self.CheckisData(event)
        electrons = Collection(event, "Electron")
        muons = Collection(event, "Muon")
        isotracks = Collection(event, "IsoTrack")
        jets = Collection(event, "Jet")
        met = Object(event, "MET")
        flags = Object(event, "Flag")
        stop0l = Object(event, "Stop0l")

        ## Baseline Selection
        PassJetID = self.PassJetID(jets)
        PassEventFilter = self.PassEventFilter(flags) and PassJetID
        PassLeptonVeto = self.PassLeptonVeto(electrons, muons, isotracks)
        PassNjets = self.PassNjets(jets)
        PassMET = met.pt >= 250
        PassHT = stop0l.HT >= 300
        PassdPhiLowDM = self.PassdPhi(jets, [0.5, 0.15, 0.15])
        PassdPhiHighDM = self.PassdPhi(jets, [0.5, 0.5, 0.5, 0.5])
        PassBaseline = PassEventFilter and PassLeptonVeto and PassNjets and PassMET and PassHT and PassdPhiLowDM
        PasshighDM = PassBaseline and stop0l.nJets >= 5 and PassdPhiHighDM and stop0l.nbtags >= 1
        PasslowDM       = PassBaseline and stop0l.nTop == 0 and stop0l.nW == 0 and stop0l.nResolved == 0 and \
                stop0l.Mtb < 175 and stop0l.ISRJetPt > 200 and stop0l.METSig > 10

        ### Store output
        self.out.fillBranch("Pass_JetID", PassJetID)
        self.out.fillBranch("Pass_EventFilter", PassEventFilter)
        self.out.fillBranch("Pass_LeptonVeto", PassLeptonVeto)
        self.out.fillBranch("Pass_NJets20", PassNjets)
        self.out.fillBranch("Pass_MET", PassMET)
        self.out.fillBranch("Pass_HT", PassHT)
        self.out.fillBranch("Pass_dPhiMET", PassdPhiLowDM)
        self.out.fillBranch("Pass_dPhiMETLowDM", PassdPhiLowDM)
        self.out.fillBranch("Pass_dPhiMETHighDM", PassdPhiHighDM)
        self.out.fillBranch("Pass_Baseline", PassBaseline)
        self.out.fillBranch("Pass_highDM", PasshighDM)
        self.out.fillBranch("Pass_lowDM", PasslowDM)

        return True
Example #17
0
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""
        jet_coll = Collection(event, self.jetColl)
        nJet = jet_coll._len
        if 'Clean' in self.jetColl:
            ori_jet_coll = Collection(event, self.jetColl.replace('Clean', ''))
        order = []
        for iJet in range(nJet):
            pt = jet_coll[iJet]['pt']
            eta = jet_coll[iJet]['eta']
            if 'Clean' in self.jetColl:
                jetId = ori_jet_coll[jet_coll[iJet]['jetIdx']]['jetId']
                puId = ori_jet_coll[jet_coll[iJet]['jetIdx']]['puId']
            else:
                jetId = jet_coll[iJet]['jetId']
                puId = jet_coll[iJet]['puId']
            pu_loose = bool(puId & (1 << 2))
            pu_medium = bool(puId & (1 << 1))
            pu_tight = bool(puId & (1 << 0))

            goodJet = True
            if pt < self.minpt: goodJet = False
            if abs(eta) > self.maxeta: goodJet = False
            if jetId < self.jetid: goodJet = False
            if self.pujetid == 'loose' and not pu_loose: goodJet = False
            if self.pujetid == 'medium' and not pu_medium: goodJet = False
            if self.pujetid == 'tight' and not pu_tight: goodJet = False
            if self.pujetid == 'custom' and pt <= 50:
                if not pu_loose: goodJet = False
                #if abs(eta) > 2.5 and not pu_medium : goodJet = False

            if goodJet: order.append(iJet)

        for typ in self.CollBr:
            for bname in self.CollBr[typ]:
                temp_b = bname.replace(self.jetColl + '_', '')
                temp_v = [jet_coll[iJet][temp_b] for iJet in order]
                self.out.fillBranch(bname, temp_v)

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

        # Order in pt the collection merging muons and electrons
        # lepMerger must be already called
        Lepton = Collection(event, "Lepton")
        self.Lepton_4vecId = []
        for iLep in range(3):
            if len(Lepton) > iLep:
                self.Lepton_4vecId.append(
                    (ROOT.TLorentzVector(), Lepton[iLep].pdgId))
                self.Lepton_4vecId[-1][0].SetPtEtaPhiM(Lepton[iLep].pt,
                                                       Lepton[iLep].eta,
                                                       Lepton[iLep].phi, 0)

        self.MET = ROOT.TLorentzVector()
        self.MET.SetPtEtaPhiM(event.PuppiMET_pt, 0, event.PuppiMET_phi, 0)

        self.CleanJet_4vecId = []
        Jet = Collection(event, "Jet")
        for j in Collection(event, "CleanJet"):
            self.CleanJet_4vecId.append(
                (ROOT.TLorentzVector(), Jet[j.jetIdx].btagCMVA))
            self.CleanJet_4vecId[-1][0].SetPtEtaPhiM(j.pt, j.eta, j.phi, 0)

        self.l3_isOk = False if len(self.Lepton_4vecId) < 3 else True
        self.WH3l_isOk = self._WH3l_isOk()

        self.ZH3l_isOk = self._ZH3l_setXLepton()
        self.ZH3l_CleanJet_4vecId = [
            j for j in self.CleanJet_4vecId
            if j[0].Pt() > 30 and abs(j[0].Eta()) < 4.7
        ]

        for nameBranchKey in self.newbranches.keys():
            self.out.fillBranch(nameBranchKey,
                                getattr(self, nameBranchKey)())

        return True
Example #19
0
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""
        
        Jets = Collection(event, 'Jet')
        CleanJets = Collection(event, 'CleanJet')
        nCleanJets = CleanJets._len
        nbtagged = 0

        for iJet in range(nCleanJets):
            if (CleanJets[iJet].pt > 20. and ROOT.TMath.Abs(CleanJets[iJet].eta) < 2.5 and Jets[CleanJets[iJet].jetIdx].btagDeepB > self.bVetoCut):
                nbtagged += 1
            else:
                continue
                
        if 'TTTo2L2Nu' in str(self.inputFile):
            MCweight = (event.topGenPt * event.antitopGenPt > 0.) * (ROOT.TMath.Sqrt(ROOT.TMath.Exp(-1.43717e-02 - 1.18358e-04*event.topGenPt - 1.70651e-07*event.topGenPt*event.topGenPt + 4.47969/(event.topGenPt+28.7)) * ROOT.TMath.Exp(-1.43717e-02 - 1.18358e-04*event.antitopGenPt - 1.70651e-07*event.antitopGenPt*event.antitopGenPt + 4.47969/(event.antitopGenPt+28.7)))) + (event.topGenPt * event.antitopGenPt <= 0.)
        elif '_WWTo2L2Nu_' in str(self.inputFile):
            MCweight = event.nllW
        elif '_M-50' in str(self.inputFile): #DY high mass
            MCweight = (((0.623108 + 0.0722934*event.gen_ptll - 0.00364918*event.gen_ptll*event.gen_ptll + 6.97227e-05*event.gen_ptll*event.gen_ptll*event.gen_ptll - 4.52903e-07*event.gen_ptll*event.gen_ptll*event.gen_ptll*event.gen_ptll)*(event.gen_ptll<45)*(event.gen_ptll>0) + 1*(event.gen_ptll>=45))*(ROOT.TMath.Abs(event.gen_mll-90)<3) + (ROOT.TMath.Abs(event.gen_mll-90)>3))
        elif '_M-10to50' in str(self.inputFile): #DY low mass
            MCweight = ((0.632927+0.0456956*event.gen_ptll-0.00154485*event.gen_ptll*event.gen_ptll+2.64397e-05*event.gen_ptll*event.gen_ptll*event.gen_ptll-2.19374e-07*event.gen_ptll*event.gen_ptll*event.gen_ptll*event.gen_ptll+6.99751e-10*event.gen_ptll*event.gen_ptll*event.gen_ptll*event.gen_ptll*event.gen_ptll)*(event.gen_ptll>0)*(event.gen_ptll<100)+(1.41713-0.00165342*event.gen_ptll)*(event.gen_ptll>=100)*(event.gen_ptll<300)+1*(event.gen_ptll>=300))
        elif '50_HT' in str(self.inputFile): #HT binned samples
            MCweight = ((0.632927+0.0456956*event.gen_ptll-0.00154485*event.gen_ptll*event.gen_ptll+2.64397e-05*event.gen_ptll*event.gen_ptll*event.gen_ptll-2.19374e-07*event.gen_ptll*event.gen_ptll*event.gen_ptll*event.gen_ptll+6.99751e-10*event.gen_ptll*event.gen_ptll*event.gen_ptll*event.gen_ptll*event.gen_ptll)*(event.gen_ptll>0)*(event.gen_ptll<100)+(1.41713-0.00165342*event.gen_ptll)*(event.gen_ptll>=100)*(event.gen_ptll<300)+1*(event.gen_ptll>=300))
        elif (('GluGluWWTo2' in str(self.inputFile)) or ('GluGluToWW' in str(self.inputFile))):
            MCweight = 1.53/1.4
        elif (('ZZTo2L2Nu' in str(self.inputFile)) or ('ZZTo2L2Q' in str(self.inputFile)) or ('ZZTo4L' in str(self.inputFile)) or ('WZTo2L2Q' in str(self.inputFile))):
            MCweight = 1.11
        else:
            MCweight = 1.0

        self.out.fillBranch('nbtaggedJets',nbtagged)
        self.out.fillBranch('metpt',eval(self.metpt))
        self.out.fillBranch('metsig',eval(self.metsig))
        self.out.fillBranch('lep1pt',eval(self.lep1pt))
        self.out.fillBranch('lep2pt',eval(self.lep2pt))
        self.out.fillBranch('specialMCWeigths',MCweight)

        return True
Example #20
0
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""
        ## Getting objects
        jets = Collection(event, "Jet")
        electrons = Collection(event, "Electron")
        muons = Collection(event, "Muon")
        met = Object(event, self.metBranchName)
        genpart = Collection(event, "GenPart")

        ## Selecting objects
        self.Electron_Stop0l = map(self.SelEle, electrons)
        self.Muon_Stop0l = map(self.SelMuon, muons)

        ## Jet variables
        MtEleMET, MtMuonMET = self.SelMtlepMET(electrons, muons, met)

        ### Store output
        self.out.fillBranch("Stop0l_MtEleMET", MtEleMET)
        self.out.fillBranch("Stop0l_MtMuonMET", MtMuonMET)
        self.out.fillBranch("Stop0l_nElectron", sum(self.Electron_Stop0l))
        self.out.fillBranch("Stop0l_nMuon", sum(self.Muon_Stop0l))
        return True
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""
        
        Jets = Collection(event, 'Jet')
        CleanJets = Collection(event, 'CleanJet')
        nCleanJets = CleanJets._len
        nbtagged = 0

        for iJet in range(nCleanJets):
            if (CleanJets[iJet].pt > 20. and ROOT.TMath.Abs(CleanJets[iJet].eta) < 2.5 and Jets[CleanJets[iJet].jetIdx].btagDeepB > self.bVetoCut):
                nbtagged += 1
            else:
                continue
                
        if 'TTTo2L2Nu' in str(self.inputFile):
            MCweight = (event.topGenPt * event.antitopGenPt > 0.) * (ROOT.TMath.Sqrt(ROOT.TMath.Exp(-0.158631 + 2.00214e-04*event.topGenPt - 3.09496e-07*event.topGenPt*event.topGenPt + 34.93/(event.topGenPt+135.633)) * ROOT.TMath.Exp(-0.158631 + 2.00214e-04*event.antitopGenPt - 3.09496e-07*event.antitopGenPt*event.antitopGenPt + 34.93/(event.antitopGenPt+135.633)))) + (event.topGenPt * event.antitopGenPt <= 0.)
        elif '_WWTo2L2Nu_' in str(self.inputFile):
            MCweight = event.nllW
        elif '_M-50' in str(self.inputFile): #DY high mass
            MCweight = (0.876979+event.gen_ptll*(4.11598e-03)-(2.35520e-05)*event.gen_ptll*event.gen_ptll)*(1.10211 * (0.958512 - 0.131835*ROOT.TMath.Erf((event.gen_ptll-14.1972)/10.1525)))*(event.gen_ptll<140)+0.891188*(event.gen_ptll>=140)
        elif '_M-10to50' in str(self.inputFile): #DY low mass
            MCweight = (8.61313e-01+event.gen_ptll*4.46807e-03-1.52324e-05*event.gen_ptll*event.gen_ptll)*(1.08683 * (0.95 - 0.0657370*ROOT.TMath.Erf((event.gen_ptll-11.)/5.51582)))*(event.gen_ptll<140)+1.141996*(event.gen_ptll>=140)
        elif '50_HT' in str(self.inputFile): #DY low mass
            MCweight = (8.61313e-01+event.gen_ptll*4.46807e-03-1.52324e-05*event.gen_ptll*event.gen_ptll)*(1.08683 * (0.95 - 0.0657370*ROOT.TMath.Erf((event.gen_ptll-11.)/5.51582)))*(event.gen_ptll<140)+1.141996*(event.gen_ptll>=140)
        elif (('GluGluWWTo2' in str(self.inputFile)) or ('GluGluToWW' in str(self.inputFile))):
            MCweight = 1.53/1.4
        elif (('ZZTo2L2Nu' in str(self.inputFile)) or ('ZZTo2L2Q' in str(self.inputFile)) or ('ZZTo4L' in str(self.inputFile)) or ('WZTo2L2Q' in str(self.inputFile))):
            MCweight = 1.11
        else:
            MCweight = 1.0

        self.out.fillBranch('nbtaggedJets',nbtagged)
        self.out.fillBranch('metpt',eval(self.metpt))
        self.out.fillBranch('metsig',eval(self.metsig))
        self.out.fillBranch('lep1pt',eval(self.lep1pt))
        self.out.fillBranch('lep2pt',eval(self.lep2pt))
        self.out.fillBranch('specialMCWeigths',MCweight)

        return True
Example #22
0
def matchgenvistau(event, tau, dRmin=0.5):
    """Help function to match tau object to gen vis tau."""
    # TO CHECK: taumatch.genPartIdxMother==tau.genPartIdx ?
    taumatch = None
    for genvistau in Collection(event, 'GenVisTau'):
        dR = genvistau.DeltaR(tau)
        if dR < dRmin:
            dRmin = dR
            taumatch = genvistau
    if taumatch:
        return taumatch.pt, taumatch.eta, taumatch.phi, taumatch.status
    else:
        return -1, -9, -9, -1
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""
        electrons = sorted(filter(lambda x: self.eleSel(x,53), Collection(event, "Electron")), key=lambda x: x.pt)
        muons = sorted(filter(lambda x: self.muSel(x,53), Collection(event, "Muon")), key=lambda x: x.pt_corrected)

        electronsLowPt = sorted(filter(lambda x: self.eleSel(x,24), Collection(event, "Electron")), key=lambda x: x.pt)
        muonsLowPt = sorted(filter(lambda x: self.muSel(x,24), Collection(event, "Muon")), key=lambda x: x.pt_corrected)

        isDiMu = self.selectDiMu(electrons, muons)
        isDiEle = self.selectDiEle(electrons, muons)
        isEleMu = self.selectEleMu(electrons, muons)

        nLowPtLep = len(electronsLowPt)+len(muonsLowPt)

        self.out.fillBranch("IncMumu", isDiMu)
        self.out.fillBranch("IncEe", isDiEle)
        self.out.fillBranch("IncEmu", isEleMu)

        self.out.fillBranch("IncMumuLowPt", isDiMu and nLowPtLep<3)
        self.out.fillBranch("IncEeLowPt", isDiEle and nLowPtLep<3)
        self.out.fillBranch("IncEmuLowPt", isEleMu and nLowPtLep<3)
        return (isDiMu or isDiEle or isEleMu)
Example #24
0
    def triggerMatching(self, event, muonVec, filterBit):
        trigObject = Collection(event, "TrigObj")

        if filterBit == 2:
            for obj in trigObject:
                if obj.id == 13:
                    matched = [
                        5e-2 > np.sqrt((obj.eta - muon.fourVec.Eta())**2 +
                                       (obj.phi - muon.fourVec.Phi())**2)
                        for muon in muonVec
                    ]

        return True in matched
Example #25
0
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""

        genParticles = Collection(event, "GenPart")
        genDressedLeptons = Collection(event,"GenDressedLepton")

        # reobtain the indices of the good muons and the neutrino
        
        bareMuonIdx = event.GenPart_bareMuonIdx
        NeutrinoIdx = event.GenPart_NeutrinoIdx
        preFSRMuonIdx = event.GenPart_preFSRMuonIdx
        dressMuonIdx = event.GenDressedLepton_dressMuonIdx
        
        if bareMuonIdx >= 0 and NeutrinoIdx >= 0:
            CStheta_bare, CSphi_bare = getCSangles(genParticles[bareMuonIdx], genParticles[NeutrinoIdx])
        else:
            CStheta_bare, CSphi_bare = -99., -99.

        if preFSRMuonIdx >= 0 and NeutrinoIdx >= 0:
            CStheta_preFSR, CSphi_preFSR = getCSangles(genParticles[preFSRMuonIdx], genParticles[NeutrinoIdx])
        else: 
            CStheta_preFSR, CSphi_preFSR = -99., -99.

        if dressMuonIdx  >= 0 and NeutrinoIdx >= 0:
            CStheta_dress, CSphi_dress = getCSangles(genDressedLeptons[dressMuonIdx], genParticles[NeutrinoIdx])
        else:
            CStheta_dress, CSphi_dress = -99., -99.

        
        self.out.fillBranch("CStheta_bare",CStheta_bare)
        self.out.fillBranch("CSphi_bare",CSphi_bare)

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

        self.out.fillBranch("CStheta_dress",CStheta_dress)
        self.out.fillBranch("CSphi_dress",CSphi_dress)

        return True
Example #26
0
 def getEmbeddingSelectionTriggerSF(self, event):
     """Get SF for embedding trigger selection efficiency. we use the two gentaus in the event
        Since we know from the embedding, that there are always two of those in the event, this can be done
     """
     parameters = {}
     genparticles = Collection(event, 'GenPart')
     i = 1
     for genparticle in genparticles:
         if abs(genparticle.pdgId) == 15:
             parameters["gt{}_pt".format(i)] = genparticle.pt
             parameters["gt{}_eta".format(i)] = abs(genparticle.eta)
             i += 1
     return self.sftool_seltrg.getSF(parameters)
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""
        ## Getting objects
        electrons = Collection(event, "Electron")
        muons = Collection(event, "Muon")
        isotracks = Collection(event, "IsoTrack")
        jets = Collection(event, "Jet")
        isvs = Collection(event, "SB")
        photons = Collection(event, "Photon")
        met = Object(event, self.metBranchName)
        flags = Object(event, "Flag")

        ## Selecting objects
        self.Electron_Stop0l = map(self.SelEle, electrons)
        self.Muon_Stop0l = map(self.SelMuon, muons)
        self.IsoTrack_Stop0l = map(lambda x: self.SelIsotrack(x, met),
                                   isotracks)
        self.Jet_Stop0l = map(self.SelJets, jets)
        local_BJet_Stop0l = map(self.SelBtagJets, jets)
        self.BJet_Stop0l = [
            a and b for a, b in zip(self.Jet_Stop0l, local_BJet_Stop0l)
        ]
        self.SB_Stop0l = map(self.SelSoftb, isvs)
        self.Photon_Stop0l = map(self.SelPhotons, photons)

        ## Jet variables
        jet_phi = np.asarray([jet.phi for jet in jets])
        Jet_dPhi = jet_phi - met.phi
        np.subtract(Jet_dPhi,
                    2 * math.pi,
                    out=Jet_dPhi,
                    where=(Jet_dPhi >= math.pi))
        np.add(Jet_dPhi,
               2 * math.pi,
               out=Jet_dPhi,
               where=(Jet_dPhi < -1 * math.pi))
        np.fabs(Jet_dPhi, out=Jet_dPhi)
        ## TODO: Need to improve speed
        HT = self.CalHT(jets)
        Mtb, Ptb = self.CalMTbPTb(jets, met)

        ### Store output
        self.out.fillBranch("Electron_Stop0l", self.Electron_Stop0l)
        self.out.fillBranch("Muon_Stop0l", self.Muon_Stop0l)
        self.out.fillBranch("IsoTrack_Stop0l", self.IsoTrack_Stop0l)
        self.out.fillBranch("Jet_btagStop0l", self.BJet_Stop0l)
        self.out.fillBranch("Jet_Stop0l", self.Jet_Stop0l)
        self.out.fillBranch("SB_Stop0l", self.SB_Stop0l)
        self.out.fillBranch("Photon_Stop0l", self.Photon_Stop0l)
        self.out.fillBranch("Jet_dPhiMET", Jet_dPhi)
        self.out.fillBranch("Stop0l_HT", HT)
        self.out.fillBranch("Stop0l_Mtb", Mtb)
        self.out.fillBranch("Stop0l_Ptb", Ptb)
        self.out.fillBranch("Stop0l_nJets", sum(self.Jet_Stop0l))
        self.out.fillBranch("Stop0l_nbtags", sum(self.BJet_Stop0l))
        self.out.fillBranch("Stop0l_nSoftb", sum(self.SB_Stop0l))
        self.out.fillBranch("Stop0l_METSig",
                            met.pt / math.sqrt(HT) if HT > 0 else 0)
        return True
Example #28
0
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""

        # muon selection
        event._allMuons = Collection(event, "Muon")
        event.muons = [mu for mu in event._allMuons if mu.pt > 55 and abs(mu.eta) < 2.4 and abs(
            mu.dxy) < 0.2 and abs(mu.dz) < 0.5 and mu.tightId and mu.miniPFRelIso_all < 0.10]
        if len(event.muons) != 1:
            return False

        self.selectLeptons(event)
        self.correctJetsAndMET(event)

        # met selection
        if event.met.pt < 50.0:
            return False

        # leptonic W pt cut
        event.mu = event.muons[0]
        event.leptonicW = polarP4(event.mu) + event.met.p4()
        if event.leptonicW.Pt() < 100.0:
            return False

        # at least one b-jet, in the same hemisphere of the muon
        event.bjets = [j for j in event.ak4jets if j.btagDeepB > self.DeepCSV_WP_M and
                       abs(deltaPhi(j, event.mu)) < 2]
        if len(event.bjets) == 0:
            return False

        # require fatjet away from the muon
        probe_jets = [fj for fj in event.fatjets if abs(deltaPhi(fj, event.mu)) > 2]
        if len(probe_jets) == 0:
            return False

        probe_jets = probe_jets[:1]
        self.loadGenHistory(event, probe_jets)
        self.evalTagger(event, probe_jets)
        self.evalMassRegression(event, probe_jets)

        # fill output branches
        self.fillBaseEventInfo(event)
        self.fillFatJetInfo(event, probe_jets)

        # fill
        self.out.fillBranch("passMuTrig", passTrigger(event, ['HLT_Mu50', 'HLT_TkMu50']))
        self.out.fillBranch("muon_pt", event.mu.pt)
        self.out.fillBranch("muon_eta", event.mu.eta)
        self.out.fillBranch("muon_miniIso", event.mu.miniPFRelIso_all)
        self.out.fillBranch("leptonicW_pt", event.leptonicW.Pt())

        return True
Example #29
0
    def analyze(self, event):
        """process event, return True (go to next module) or False (fail, go to next event)"""
        jets = sorted(filter(lambda x: self.alljetSel(x, 'nom'),
                             Collection(event, "Jet")),
                      key=lambda x: x.pt)
        jetPt = [20., 30., 50., 70., 100., 140., 200., 300., 600., 1000.]
        self.Pass.clear()
        Dummy1 = ROOT.std.vector('int')()
        Dummy1.resize(10, 0)
        self.Pass.resize(3, Dummy1)
        self.Total.clear()
        Dummy2 = ROOT.std.vector('int')()
        Dummy2.resize(10, 0)
        self.Total.resize(3, Dummy2)

        if self.isMC:
            for j in jets:
                # select flavor
                flavour = 2
                if j.genJetIdx >= 0:
                    if j.hadronFlavour == 5:
                        flavour = 0
                    elif j.hadronFlavour == 4:
                        flavour = 1
                if self.select_btag(j):
                    self.bTagEffTH2F.Fill(flavour, j.pt)

                self.TotalTH2F.Fill(flavour, j.pt)

        if self.isMC:
            for j in jets:
                bin = 9
                for k in reversed(jetPt):
                    if j.pt > k:
                        break
                    bin -= 1
                if bin >= 0:
                    flavor = 2
                    if j.genJetIdx >= 0:
                        if j.hadronFlavour == 5:
                            flavor = 0
                        elif j.hadronFlavour == 4:
                            flavor = 1
                    if self.select_btag(j):
                        self.Pass[flavor][bin] += 1
                    self.Total[flavor][bin] += 1
        else:
            pass
        self.out._tree.Fill()

        return True
Example #30
0
    def analyze(self, event):
        coll = Collection(event, self.CollTC)
        nColl = len(coll)

        if self.doMET:
            met = Object(event, self.METobj)
            met_px = met['pt'] * math.cos(met['phi'])
            met_py = met['pt'] * math.sin(met['phi'])

        # Create new pt
        new_pt = []
        for iObj in range(nColl):
            if self.isUp:
                tmp_pt = coll[iObj]['pt'] + coll[iObj][
                    self.CorrSrc] * coll[iObj]['pt']
            else:
                tmp_pt = coll[iObj]['pt'] - coll[iObj][
                    self.CorrSrc] * coll[iObj]['pt']
            new_pt.append(tmp_pt)

            # MET
            if self.doMET and tmp_pt > self.minJetEn:
                pt_diff = tmp_pt - coll[iObj]['pt']
                met_px -= pt_diff * (math.cos(coll[iObj]['pt']))
                met_py -= pt_diff * (math.sin(coll[iObj]['pt']))
        if self.doMET:
            new_MET_pt = math.sqrt(met_px**2 + met_py**2)
            new_MET_phi = math.atan2(met_px, met_py)

        # Reorder
        order = []
        for idx1, pt1 in enumerate(new_pt):
            pt_idx = 0
            for idx2, pt2 in enumerate(new_pt):
                if pt1 < pt2 or (pt1 == pt2 and idx1 > idx2): pt_idx += 1
            order.append(pt_idx)

        # Fill branches
        for typ in self.CollBr:
            for bname in self.CollBr[typ]:
                if '_pt' in bname:
                    temp_v = [new_pt[idx] for idx in order]
                    self.out.fillBranch(bname, temp_v)
                else:
                    temp_b = bname.replace(self.CollTC + '_', '')
                    temp_v = [coll[idx][temp_b] for idx in order]
                    self.out.fillBranch(bname, temp_v)
        if self.doMET:
            self.out.fillBranch(self.METobj + '_pt', new_MET_pt)
            self.out.fillBranch(self.METobj + '_phi', new_MET_phi)
        return True