def makeseed(cluster1,cluster2,i1,i2,particles):
   p = TLorentzVector()
   r1 = [ROOT.Double(), ROOT.Double(), ROOT.Double()]
   r2 = [ROOT.Double(), ROOT.Double(), ROOT.Double()]
   cluster1.GetPoint(i1,r1[0],r1[1],r1[2])
   cluster2.GetPoint(i2,r2[0],r2[1],r2[2])
   
   x0 = 0
   z0 = zofx(r1,r2,x0)
   xExit = xofz(r1,r2,zDipoleExit)*cm2m
   q = 1 if(particles=="electrons") else -1
   H = (zDipoleExit-z0)*cm2m
   R = H*(LB)/xExit + xExit ## look this up in my sides
   P = 0.3*B*R
   
   v1 = TVector2(r1[2],r1[1])
   v2 = TVector2(r2[2],r2[1])
   u = rUnit2(v2,v1)
   uz = u.X()
   uy = u.Y()
   px = 0
   py = P*uy
   pz = P*uz
   p.SetPxPyPzE(px,py,pz,math.sqrt(P*P+me2))
   
   return p
Exemplo n.º 2
0
    def __init__(self, z_neg, z_pos, is_electron=True):
        #negative and positive extent along z, rotated by the respective angle
        self.is_electron = is_electron

        angle = 0.
        if self.is_electron: angle = -0.025

        self.vec_neg = TVector2(z_neg, 0).Rotate(angle)
        self.vec_pos = TVector2(z_pos, 0).Rotate(angle)
Exemplo n.º 3
0
    def calcDLDictionary(self, base={}, keepIdx=0, discardIdx=1):
        outputdict = {}
        outputdict["DL_dPhiLepW"] = []
        outputdict["DL_ST"] = []
        outputdict["DL_HT"] = []
        outputdict["DL_nJets30Clean"] = []

        Met2D = TVector2(self.metp4.Px(), self.metp4.Py())
        LepToDiscard2D = TVector2(self.tightLeps[discardIdx].p4().Px(),
                                  self.tightLeps[discardIdx].p4().Py())
        LepToKeep2D = TVector2(self.tightLeps[keepIdx].p4().Px(),
                               self.tightLeps[keepIdx].p4().Py())

        Met2D_AddFull = Met2D + LepToDiscard2D
        Met2D_AddThird = Met2D + (1 / 3. * LepToDiscard2D)

        recoWp4 = LepToKeep2D + Met2D
        outputdict["DL_dPhiLepW"].append(
            LepToKeep2D.DeltaPhi(recoWp4))  # [0]: not adding leptons to MET
        outputdict["DL_ST"].append(LepToKeep2D.Mod() + Met2D.Mod())
        outputdict["DL_HT"].append(base['HT'])
        outputdict["DL_nJets30Clean"].append(base['nJets30Clean'])

        recoWp4_AddFull = LepToKeep2D + Met2D_AddFull
        outputdict["DL_dPhiLepW"].append(LepToKeep2D.DeltaPhi(
            recoWp4_AddFull))  # [0]: adding lost lepton pt to met
        outputdict["DL_ST"].append(LepToKeep2D.Mod() + Met2D_AddFull.Mod())
        dlht = base['HT'] + (LepToDiscard2D.Mod()
                             if LepToDiscard2D.Mod() > 30. else 0.)
        outputdict["DL_HT"].append(dlht)
        dlnjet = base['nJets30Clean'] + (1
                                         if LepToDiscard2D.Mod() > 30. else 0)
        outputdict["DL_nJets30Clean"].append(dlnjet)

        recoWp4_AddThird = LepToKeep2D + Met2D_AddThird
        outputdict["DL_dPhiLepW"].append(LepToKeep2D.DeltaPhi(
            recoWp4_AddThird))  # [2]: adding 1/3 of lepton ptto met
        outputdict["DL_ST"].append(LepToKeep2D.Mod() + Met2D_AddThird.Mod())
        dlht = base['HT'] + (2 / 3. * LepToDiscard2D.Mod()
                             if 2 / 3. * LepToDiscard2D.Mod() > 30 else 0.)
        outputdict["DL_HT"].append(dlht)
        dlnjet = base['nJets30Clean'] + (
            1 if 2 / 3. * LepToDiscard2D.Mod() > 30. else 0)
        outputdict["DL_nJets30Clean"].append(dlnjet)

        #        print base['nJets30Clean'], outputdict["DL_nJets30Clean"]

        outputdict["l1l2ovMET"] = (self.tightLeps[0].pt +
                                   self.tightLeps[1].pt) / self.metp4.Pt()
        outputdict["Vecl1l2ovMET"] = (LepToKeep2D +
                                      LepToDiscard2D).Mod() / self.metp4.Pt()

        outputdict["DPhil1l2"] = LepToKeep2D.DeltaPhi(LepToDiscard2D)

        return outputdict
Exemplo n.º 4
0
def GetZfromM(vector1, vector2, mass):
    MT = sqrt(2 * vector1.Pt() * vector2.Pt() *
              (1 - cos(vector2.DeltaPhi(vector1))))
    if (MT < mass):
        Met2D = TVector2(vector2.Px(), vector2.Py())
        Lep2D = TVector2(vector1.Px(), vector1.Py())
        A = mass * mass / 2. + Met2D * Lep2D
        Delta = vector1.E() * vector1.E() * (A * A -
                                             Met2D.Mod2() * Lep2D.Mod2())
        MetZ1 = (A * vector1.Pz() + sqrt(Delta)) / Lep2D.Mod2()
        MetZ2 = (A * vector1.Pz() - sqrt(Delta)) / Lep2D.Mod2()
    else:
        MetZ1 = vector1.Pz() * vector2.Pt() / vector1.Pt()
        MetZ2 = vector1.Pz() * vector2.Pt() / vector1.Pt()
    return [MT, MetZ1, MetZ2]
Exemplo n.º 5
0
 def getDphiJ1MET(self):
     dphi_j1met = -99.
     met_phi = self.met_phi
     if self.n_jet > 0:
         j1phi = self.jet_phi[0]
         dphi_j1met = TVector2.Phi_mpi_pi(j1phi - met_phi)
     return dphi_j1met
Exemplo n.º 6
0
def RotateEvent(lep, jets, met_phi, phi):
    """Takes in LorentzVector lep, jets and rotates each along the Z axis by
    an angle phi
    @==========================================================
    @ Parameters
    lep: LorentzVector containing lepton information
    jets: Array of LorentzVectors containing jet information
    phi: Angle between 0 and 2 pi
    @==========================================================
    @ Return
    A rotated LorentzVector
    """
    # Missing Azimuthal Energy
    met_phi = TVector2.Phi_mpi_pi(met_phi + phi)

    # Lepton
    lep_new = TLorentzVector(lep)
    lep_new.RotateZ(phi)

    # Jets
    jets_new = []
    for j in jets:
        jets_new += [TLorentzVector(j)]
        j_new = jets_new[-1]
        j_new.btag = j.btag
        j_new.RotateZ(phi)

    return lep_new, jets_new, met_phi
Exemplo n.º 7
0
    def draw_2d(self):

        #make corner points
        vec = []
        vec.append(TVector2(self.length / 2, -self.height / 2))
        vec.append(TVector2(-self.length / 2, -self.height / 2))
        vec.append(TVector2(-self.length / 2, self.height / 2))
        vec.append(TVector2(self.length / 2, self.height / 2))

        #rotate and translate along electron beam
        vtrans = TVector2(-1, 0).Rotate(self.angle)
        vtrans.SetMagPhi(self.dist + self.length / 2, vtrans.Phi())
        for i in xrange(len(vec)):
            vec[i] = vec[i].Rotate(self.angle)
            vec[i] += vtrans

        #last point same as the first
        vec.append(vec[0])

        self.geom = TGraph(len(vec))
        self.geom.SetLineWidth(2)
        self.geom.SetLineColor(rt.kYellow + 1)
        self.geom.SetFillColor(rt.kYellow)
        for i in xrange(len(vec)):
            self.geom.SetPoint(i, vec[i].X(), vec[i].Y() * 100)

        self.geom.Draw("lfsame")

        #label
        self.label = TText(vtrans.X(),
                           (vtrans.Y() - self.height / 2 - 0.11) * 100 - 3,
                           "Lumi detector")
        self.label.SetTextSize(0.03)
        #self.label.SetTextAngle(90)
        #self.label.SetTextAlign(32)
        self.label.SetTextAlign(23)
        self.label.Draw("same")

        #label for low Q^2 tagger
        self.label_tag = TText(vtrans.X() + 2, (vtrans.Y() + 0.6) * 100 - 3,
                               "Place for low-Q2 tagger")
        self.label_tag.SetTextSize(0.03)
        #self.label.SetTextAngle(90)
        #self.label.SetTextAlign(32)
        self.label_tag.SetTextAlign(23)
        self.label_tag.Draw("same")
Exemplo n.º 8
0
    def add_point_2(self, hnam, vnam, mult2=1.):

        hnam = hnam.split(".")
        vnam = vnam.split(".")

        self.points.append(
            TVector2(self.geo.GetD(hnam[0], hnam[1]),
                     mult2 * self.geo.GetD(vnam[0], vnam[1])))
Exemplo n.º 9
0
    def rotate(self, theta):
        #rotate by angle theta about the origin

        #get new center_z and center_x by TVector2 rotation
        vec = TVector2(self.center_z, self.center_x).Rotate(theta)
        self.center_z = vec.X()
        self.center_x = vec.Y()

        #rotate along magnet center
        self.THETA = self.THETA - theta
Exemplo n.º 10
0
 def isMatched(self, eta, phi, genParticles, gpIdx=[], minDR=0.5):
     belong = -1
     for iGen in gpIdx:
         geta, gphi = genParticles.eta[iGen], genParticles.phi[iGen]
         deta = geta - eta
         dphi = TVector2.Phi_mpi_pi(gphi - phi)
         dR = TMath.Sqrt(deta**2 + dphi**2)
         if dR < minDR:
             belong = iGen
             break
     return belong
Exemplo n.º 11
0
    def __init__(self, geom):

        #input points, in electron beamline frame
        if geom == "flat":
            self.pos = [(-21.7, -5), (-21.7, 5)]  # flat geometry
        if geom == "tilt":
            self.pos = [(-18.8, -5), (-21.7, 5)]  # tilted geometry

        #print the geometry
        self.print_position()

        #points in z and x, both in m
        self.zx_pos = []
        for i in self.pos:
            # z at 0 and x at 1, converted to cm
            self.zx_pos.append(TVector2(i[0], 0.01 * i[1]))

        #angle of initial rotation
        self.rotate(-0.008)
Exemplo n.º 12
0
    def analysis(self):
        pass
        #general analysis

        #Q3ER
        #m = self.elements["Q3ER"]
        #print "Q3ER", m.center_x, m.center_z

        #B2eR location and dimensions for low Q2 simulations
        #b2 = self.elements["B2ER"]
        #print "B2eR:"
        #print "x:", b2.center_x, "m"
        #print "z:", b2.center_z, "m"
        #print "length:", b2.length, "m"
        #print "rad1:", b2.rad1, "m"
        #print "rad2:", b2.rad2, "m"
        #print "field:", b2.field, "T"

        #print angle of selected magnets
        mag = self.elements["Q1ER"]
        vec = TVector2(mag.center_z, mag.center_x)
        print "theta:", TMath.Pi() - vec.Phi()
Exemplo n.º 13
0
    def draw(self):

        #edge points around a closed contour
        points = []
        points.append(TVector2(-self.dz / 2., -self.r2))
        points.append(TVector2(-self.dz / 2., self.r2))
        points.append(TVector2(self.dz / 2., self.r1))
        points.append(TVector2(self.dz / 2., -self.r1))
        points.append(TVector2(-self.dz / 2., -self.r2))

        #rotate and move to center
        pcen = TVector2(self.zpos, self.xpos)
        for i in range(len(points)):
            points[i] = points[i].Rotate(self.theta) + pcen

        #export points to the graph
        self.gbox = TGraph(len(points))
        self.gbox.SetLineColor(self.line_col)
        self.gbox.SetLineWidth(self.line_width)
        self.gbox.SetFillStyle(self.fill_style)
        self.gbox.SetFillColor(self.fill_col)

        for i in range(len(points)):
            self.gbox.SetPoint(i, points[i].X(), points[i].Y())

        self.gbox.Draw("lfsame")

        #label
        if self.label == "": return

        #label below the magnet
        if self.xpos < -1.:
            align = 32
            vlab = (self.xpos - self.r2) * 1.1

        #label above the magnet
        else:
            align = 12
            vlab = (self.xpos + self.r2) * 1.1

        self.glabel = TLatex(self.zpos, vlab, self.label)
        self.glabel.SetTextSize(0.03)
        self.glabel.SetTextAngle(90)
        self.glabel.SetTextAlign(align)
        self.glabel.Draw("same")
Exemplo n.º 14
0
    def draw_graph(self):

        #inner and outer radius
        if self.center_z < 0:
            rad_right = self.rad1
            rad_left = self.rad2
        else:
            rad_right = self.rad2
            rad_left = self.rad1

        #edge points of the magnet
        vec = []
        vec.append(TVector2(self.length / 2, rad_right))
        vec.append(TVector2(self.length / 2, -rad_right))
        vec.append(TVector2(-self.length / 2, -rad_left))
        vec.append(TVector2(-self.length / 2, rad_left))

        #rotate along magnet axis and move to magnet center
        vpos = TVector2(self.center_z, self.center_x)
        for i in xrange(len(vec)):
            vec[i] = vec[i].Rotate(-self.THETA) + vpos

        #export points to the graph
        self.gbox = TGraph(len(vec) + 1)
        self.gbox.SetLineColor(self.line_col)
        self.gbox.SetLineWidth(2)
        self.gbox.SetFillStyle(self.fill_style)
        self.gbox.SetFillColor(self.fill_col)

        for i in xrange(len(vec)):
            self.gbox.SetPoint(i, vec[i].X(), 100 * vec[i].Y())

        #last point same as the first
        self.gbox.SetPoint(len(vec), vec[0].X(), 100 * vec[0].Y())

        self.gbox.Draw("lfsame")

        #label
        if self.no_label: return
        #lx = (self.center_x + self.rad2)*100 + 4
        lx = (self.center_x + (self.rad1 + self.rad2) / 2) * 100 + 4
        if lx < 30: lx = 30
        align = 12
        #left down
        if (self.center_z < 0 and not self.is_electron) or self.label_down:
            lx = (self.center_x - self.rad2) * 100 - 4
            align = 32
        #right down
        if self.center_z > 0 and self.is_electron:
            lx = (self.center_x - self.rad2) * 100 - 4
            if lx > -25: lx = -25
            align = 32
            #label above the magnet
            if self.center_x < -0.4:
                lx = (self.center_x + self.rad2) * 100 + 4
                align = 12
        if self.label == "":
            self.label = self.name
        #self.glabel = TText(self.center_z, lx, self.label)
        self.glabel = TLatex(self.center_z, lx, self.label)
        self.glabel.SetTextSize(0.03)
        #self.glabel.SetTextSize(0.02)
        self.glabel.SetTextAngle(90)
        self.glabel.SetTextAlign(align)
        self.glabel.Draw("same")
Exemplo n.º 15
0
    def draw(self):

        #horizontal and vertical 1/2 size
        hsiz = self.dz / 2.
        if not self.y_project:
            vsiz = self.dx / 2.  # vertical is x
        else:
            vsiz = self.dy / 2.  # vertical is y

        #horizontal and vertical center
        hcen = self.zpos
        if not self.y_project:
            vcen = self.xpos  # vertical is x
        else:
            vcen = self.ypos  # vertical is y

        #print(hsiz, vsiz, hcen, vcen)

        #edge points around closed contour
        points = []
        points.append(TVector2(-hsiz, -vsiz))
        points.append(TVector2(-hsiz, vsiz))
        points.append(TVector2(hsiz, vsiz))
        points.append(TVector2(hsiz, -vsiz))
        points.append(TVector2(-hsiz, -vsiz))

        #rotate and move to center
        pcen = TVector2(hcen, vcen)
        for i in range(len(points)):
            points[i] = points[i].Rotate(self.theta) + pcen

        #export points to the graph
        self.gbox = TGraph(len(points))
        self.gbox.SetLineColor(self.line_col)
        self.gbox.SetLineWidth(self.line_width)
        self.gbox.SetFillStyle(self.fill_style)
        self.gbox.SetFillColor(self.fill_col)

        for i in range(len(points)):
            self.gbox.SetPoint(i, points[i].X(), points[i].Y())

        self.gbox.Draw("lfsame")

        #label
        if self.label == "": return

        #label below the segment
        if vcen < -1.:
            align = 32
            vlab = (vcen - vsiz) * 1.1

        #label above the segment
        else:
            align = 12
            vlab = (vcen + vsiz) * 1.1

        self.glabel = TLatex(hcen, vlab, self.label)
        self.glabel.SetTextSize(0.03)
        #self.glabel.SetTextSize(0.02)
        self.glabel.SetTextAngle(90)
        self.glabel.SetTextAlign(align)
        self.glabel.Draw("same")
Exemplo n.º 16
0
    def load_tab_sl(self, nam, smax=999):

        #load electron magnets from description table with s and l of the elements

        #table formatting
        ft = {"s": 3, "angle": 7, "name": 1, "etype": 2, "l": 4}
        #ft = {"s":5, "angle":7, "name":1, "etype":2, "l":6}

        #current position along electron beam
        bp = TVector2(0, 0)
        # x, z

        s0 = 0.  # movement in s
        l0 = 0.  # length of previous element
        theta = 0.  # angle of individual elements

        iel = 0  # element index

        for line in open(nam, "read"):

            ll = line.split()

            #comments and beginning line
            if ll[0][0] == "#" or ll[0][0] == "0": continue

            #load the s position and element length
            s = float(ll[ft["s"]])

            if smax < 0 and -s < smax: break

            delt = TVector2(0, s - s0 - l0 / 2)
            delt = delt.Rotate(theta)
            s0 = s

            #move to the next element
            bp += delt

            #add the element, magnets only
            name = ll[ft["name"]]
            etype = ll[ft["etype"]]

            if (etype != "Drift" and etype != "Marker"
                ) or name.find("ECRAB") >= 0 or name.find("D3ER") >= 0:
                #if True:

                #more instances of the same name
                if self.elements.get(name) is not None:
                    name = name + "_" + str(iel)
                    iel += 1

                self.elements[name] = magnet_tab_sl(ll, bp, theta)
                self.element_names.append(name)

                #print name, bp.X(), bp.Y()

            #move current position to the end of the current element
            l0 = float(ll[ft["l"]])
            delt = TVector2(0, l0 / 2)
            delt = delt.Rotate(theta)
            bp += delt

            #angle for the next element
            theta += float(ll[ft["angle"]])

        self.set_inner_radii()

        #electron tagger
        detector("lowQ2", -27, 0.472, 0.35, 0.1, 0.02, self.elements,
                 self.element_names)
Exemplo n.º 17
0
 def getDphiL1MET(self, l1phi):
     dphi_l1met = -99.
     met_phi = self.met_phi
     if l1phi:
         dphi_l1met = TVector2.Phi_mpi_pi(l1phi - met_phi)
     return dphi_l1met
Exemplo n.º 18
0
    def fill(self, event):
        #print 'this is the DSID: %s' % self.DSID
        weight=float(1.0)
        totalWeight=float(1.0)
        intLumi = 36300.0 #Same as used by Lorenzo Rossini
        #intLumi = 3230.0 #data16PeriodC (in pb^-1)
        #intLumi = 2582.0 #date16PeriodK (in pb^-1)
        #intLumi = 2222.0 #(in pb^-1)
        #intLumi = 2147.0 #(in pb^-1)
        #intLumi = 1948.44 #(in pb^-1)
        #intLumi = 5812.0 #(in pb^-1)
        #intLumi = 1.0

        #Initialize TLorentz vectors
        lep1Vec = ROOT.TLorentzVector()
        lep2Vec = ROOT.TLorentzVector()
        jet1Vec = ROOT.TLorentzVector()
        jet2Vec = ROOT.TLorentzVector()

        #Get variables from tree for filling histogram
        mu = event.mu
        nVtx = event.nVtx
        datasetNum = event.DatasetNumber
        MET=event.met_Et
        MET_Phi = event.met_Phi
        ht30 = event.Ht30
        if event.jetPt.size() > 0: jet1Vec.SetPtEtaPhiM(event.jetPt[0], event.jetEta[0], event.jetPhi[0], event.jetM[0])
        if event.jetPt.size() > 1: jet2Vec.SetPtEtaPhiM(event.jetPt[1], event.jetEta[1], event.jetPhi[1], event.jetM[1])
        dphi_j1met = TVector2.Phi_mpi_pi(jet1Vec.Phi() - MET_Phi) 
        dphi_j2met = TVector2.Phi_mpi_pi(jet2Vec.Phi() - MET_Phi) 
        nJet25 = event.nJet25
        mt = event.mt
        nLep_base = event.nLep_base
        nLep_signal = event.nLep_signal

        obs = observable()
        lep1Vec, lep1Charge, lep1Flavor = obs.getLep1TLVChargeFlavor(event)
        lep2Vec, lep2Charge, lep2Flavor = obs.getLep2TLVChargeFlavor(event)

        #Calculate dilepton variables
        lepPairVec = lep1Vec + lep2Vec
        mll = lepPairVec.M()
        ptll = lepPairVec.Pt()
        qlql = lep1Charge*lep2Charge
        dphi_l1met = TVector2.Phi_mpi_pi(lep1Vec.Phi() - MET_Phi) 
        dphi_l2met = TVector2.Phi_mpi_pi(lep2Vec.Phi() - MET_Phi) 
        dphi_l1l2  = lep2Vec.DeltaPhi(lep1Vec)
        mt_l1met = TMath.Sqrt(2*lep1Vec.Pt()*MET*(1-TMath.Cos(dphi_l1met)))
        mt_l2met = TMath.Sqrt(2*lep2Vec.Pt()*MET*(1-TMath.Cos(dphi_l2met)))
        mtautau = -999.
        dR_l1l2 = -999.
        if nLep_signal >= 2:
            dR_l1l2  = lep2Vec.DeltaR(lep1Vec)
            mtautau = obs.calcMtautau(event)

        genWeight = event.genWeight

        #Calculating weight
        if self.isdata:
            totalWeight = 1.0
        else:
            totalWeight = float(event.SherpaVjetsNjetsWeight*event.ttbarNNLOWeight*event.pileupWeight*event.eventWeight*event.leptonWeight*event.jvtWeight*event.bTagWeight*genWeight) #TODO: NO TRIGGER WEIGHT!!

        self.hists["mu"].Fill(float(mu), totalWeight)
        self.hists["MET"].Fill(float(MET), totalWeight)
        self.hists["Lep1Pt"].Fill(float(lep1Vec.Pt()), totalWeight)
        self.hists["Lep2Pt"].Fill(float(lep2Vec.Pt()), totalWeight)
        self.hists["Lep1Eta"].Fill(float(lep1Vec.Eta()), totalWeight)
        if lep1Flavor == 1: self.hists["ElPt"].Fill(int(lep1Vec.Pt()), totalWeight) 
        elif lep1Flavor == 2: self.hists["MuPt"].Fill(int(lep1Vec.Pt()), totalWeight) 
        if lep2Flavor == 1: self.hists["ElPt"].Fill(int(lep2Vec.Pt()), totalWeight) 
        elif lep2Flavor == 2: self.hists["MuPt"].Fill(int(lep2Vec.Pt()), totalWeight) 
        self.hists["Lep2Eta"].Fill(float(lep2Vec.Eta()), totalWeight)
        self.hists["Jet1Pt"].Fill(float(jet1Vec.Pt()), totalWeight)
        self.hists["Jet2Pt"].Fill(float(jet2Vec.Pt()), totalWeight)
        self.hists["nLepSignal"].Fill(float(nLep_signal), totalWeight)
        self.hists["nJet25"].Fill(float(nJet25), totalWeight)
        self.hists["nVtx"].Fill(float(nVtx), totalWeight)
        self.hists["mll"].Fill(float(mll), totalWeight)
        self.hists["mll2"].Fill(float(mll), totalWeight)
        self.hists["ptll"].Fill(float(ptll), totalWeight)
        self.hists["dphiJ1met"].Fill(float((-1)*math.fabs(dphi_j1met)), totalWeight)
        self.hists["dphiJ2met"].Fill(float((-1)*math.fabs(dphi_j2met)), totalWeight)
        self.hists["dphiL1met"].Fill(float(math.fabs(dphi_l1met)), totalWeight)
        self.hists["dphiL2met"].Fill(float(math.fabs(dphi_l2met)), totalWeight)
        self.hists["dphiL1L2"].Fill(float( math.fabs(dphi_l1l2)), totalWeight)
        self.hists["dRL1L2"].Fill(float(dR_l1l2), totalWeight)
        self.hists["lepCharge"].Fill(int(lep1Charge), totalWeight)
        self.hists["lepCharge"].Fill(int(lep2Charge), totalWeight)
        self.hists["qlql"].Fill(int(qlql), totalWeight)
        self.hists["lepFlavor"].Fill(int(lep1Flavor), totalWeight)
        self.hists["lepFlavor"].Fill(int(lep2Flavor), totalWeight)
        if (ht30): self.hists["METoverHt"].Fill(float(MET/ht30), totalWeight)
        self.hists["Ht30"].Fill(float(ht30), totalWeight)
        self.hists["Mt"].Fill(float(mt), totalWeight)
        self.hists["MtL1met"].Fill(float(mt_l1met), totalWeight)
        self.hists["MtL2met"].Fill(float(mt_l2met), totalWeight)
        self.hists["MTauTau"].Fill(float(mtautau), totalWeight)
Exemplo n.º 19
0
    def add_points(self, p):

        for i in p:
            # z at 0 and x at 1, converted to cm
            self.zx_pos.append( TVector2(i[0], 0.01*i[1]) )
Exemplo n.º 20
0
    def analyze(self, event):
        eventWeightLumi, lheWeight, stitchWeight, puWeight, qcdnloWeight, qcdnnloWeight, ewknloWeight, topWeight = 1., 1., 1., 1., 1., 1., 1., 1.
        triggerWeight, leptonWeight = 1., 1.
        isSingleMuonTrigger, isSingleMuonPhotonTrigger, isSingleMuonNoFiltersPhotonTrigger, isDoubleMuonTrigger, isDoubleMuonPhotonTrigger, isJPsiTrigger, isDisplacedTrigger = False, False, False, False, False, False, False
        nCleanElectron, nCleanMuon, nCleanTau, nCleanPhoton, nCleanJet, nCleanBTagJet, HT30 = 0, 0, 0, 0, 0, 0, 0
        cosThetaStar, cosTheta1, phi1 = -2., -2., -4.
        genCosThetaStar, genCosTheta1, genPhi1 = -2., -2., -4.

        for t in self.SingleMuonTriggers:
            if hasattr(event, t) and getattr(event, t): isSingleMuonTrigger = True
        for t in self.SingleMuonPhotonTriggers:
            if hasattr(event, t) and getattr(event, t): isSingleMuonPhotonTrigger = True
        for t in self.SingleMuonNoFiltersPhotonTriggers:
            if hasattr(event, t) and getattr(event, t): isSingleMuonNoFiltersPhotonTrigger = True
        for t in self.DoubleMuonTriggers:
            if hasattr(event, t) and getattr(event, t): isDoubleMuonTrigger = True
        for t in self.DoubleMuonPhotonTriggers:
            if hasattr(event, t) and getattr(event, t): isDoubleMuonPhotonTrigger = True
        for t in self.JPsiTriggers:
            if hasattr(event, t) and getattr(event, t): isJPsiTrigger = True
        for t in self.DisplacedTriggers:
            if hasattr(event, t) and getattr(event, t): isDisplacedTrigger = True
        
        lheWeight = 1.
        
        if self.isMC: 
            # Event weight
            if not self.isLO and hasattr(event, "LHEWeight_originalXWGTUP"): lheWeight = event.LHEWeight_originalXWGTUP
            
            # PU weight
            puWeight = self.puTool.getWeight(event.Pileup_nTrueInt)
        
        self.hists["Nevents"].Fill(0, lheWeight)
        self.hists["Acceptance"].Fill(0, lheWeight)
        self.hists["Cutflow"].Fill(0, lheWeight)
        

        # Gen studies
        if self.isMC and self.isSignal:
            genHIdx, genJPsiIdx, genMuon1Idx, genMuon2Idx, genPhotonIdx = -1, -1, -1, -1, -1
#            print "-"*40
            for i in range(event.nGenPart):
#                print i, "\t", event.GenPart_pdgId[i], "\t", event.GenPart_status[i], "\t", event.GenPart_statusFlags[i], "\t", event.GenPart_pt[i]
                if event.GenPart_pdgId[i] == 25 or event.GenPart_pdgId[i] == 23: genHIdx = i
                if event.GenPart_pdgId[i] == 443 and event.GenPart_genPartIdxMother[i] >= 0 and event.GenPart_pdgId[event.GenPart_genPartIdxMother[i]] == 25: genJPsiIdx = i
                if event.GenPart_pdgId[i] == 22 and event.GenPart_status[i] in [1, 23] and event.GenPart_genPartIdxMother[i] >= 0 and event.GenPart_pdgId[event.GenPart_genPartIdxMother[i]] == 25: genPhotonIdx = i #and (genPhotonIdx < 0 or event.GenPart_pt[i] > event.GenPart_pt[genPhotonIdx])
                if event.GenPart_pdgId[i] == -13 and event.GenPart_status[i] == 1 and event.GenPart_genPartIdxMother[i] >= 0 and event.GenPart_pdgId[event.GenPart_genPartIdxMother[i]] != 22 and (genMuon1Idx < 0 or event.GenPart_pt[i] > event.GenPart_pt[genMuon1Idx]): genMuon1Idx = i
                if event.GenPart_pdgId[i] == +13 and event.GenPart_status[i] == 1 and event.GenPart_genPartIdxMother[i] >= 0 and event.GenPart_pdgId[event.GenPart_genPartIdxMother[i]] != 22 and (genMuon2Idx < 0 or event.GenPart_pt[i] > event.GenPart_pt[genMuon2Idx]): genMuon2Idx = i
            
            if genHIdx >= 0 and genJPsiIdx >= 0 and genPhotonIdx >= 0 and genMuon1Idx >= 0 and genMuon2Idx >= 0:
                genH, genJPsi, genMuon1, genMuon2, genPhoton = TLorentzVector(), TLorentzVector(), TLorentzVector(), TLorentzVector(), TLorentzVector()
                if genHIdx >= 0: genH.SetPtEtaPhiM(event.GenPart_pt[genHIdx], event.GenPart_eta[genHIdx], event.GenPart_phi[genHIdx], event.GenPart_mass[genHIdx])
                if genJPsiIdx >= 0: genJPsi.SetPtEtaPhiM(event.GenPart_pt[genJPsiIdx], event.GenPart_eta[genJPsiIdx], event.GenPart_phi[genJPsiIdx], event.GenPart_mass[genJPsiIdx])
                if genPhotonIdx >= 0: genPhoton.SetPtEtaPhiM(event.GenPart_pt[genPhotonIdx], event.GenPart_eta[genPhotonIdx], event.GenPart_phi[genPhotonIdx], event.GenPart_mass[genPhotonIdx])
                if genMuon1Idx >= 0: genMuon1.SetPtEtaPhiM(event.GenPart_pt[genMuon1Idx], event.GenPart_eta[genMuon1Idx], event.GenPart_phi[genMuon1Idx], event.GenPart_mass[genMuon1Idx])
                if genMuon2Idx >= 0: genMuon2.SetPtEtaPhiM(event.GenPart_pt[genMuon2Idx], event.GenPart_eta[genMuon2Idx], event.GenPart_phi[genMuon2Idx], event.GenPart_mass[genMuon2Idx])
                
                # Recalculate candidate 4-vectors for consistent calculation of angular variables
                genJPsi = genMuon1 + genMuon2
                genH = genJPsi + genPhoton
                
                genCosThetaStar, genCosTheta1, genPhi1 = self.returnCosThetaStar(genH, genJPsi), self.returnCosTheta1(genJPsi, genMuon1, genMuon2, genPhoton), self.returnPhi1(genH, genMuon1, genMuon2)
                
                self.hists["genH_pt"].Fill(genH.Pt(), lheWeight)
                self.hists["genH_eta"].Fill(genH.Eta(), lheWeight)
                self.hists["genH_phi"].Fill(genH.Phi(), lheWeight)
                self.hists["genH_mass"].Fill(genH.M(), lheWeight)
                self.hists["genJPsi_pt"].Fill(genJPsi.Pt(), lheWeight)
                self.hists["genJPsi_eta"].Fill(genJPsi.Eta(), lheWeight)
                self.hists["genJPsi_phi"].Fill(genJPsi.Phi(), lheWeight)
                self.hists["genJPsi_mass"].Fill(genJPsi.M(), lheWeight)
                self.hists["genPhoton_pt"].Fill(genPhoton.Pt(), lheWeight)
                self.hists["genPhoton_eta"].Fill(genPhoton.Eta(), lheWeight)
                self.hists["genMuon1_pt"].Fill(max(genMuon1.Pt(), genMuon2.Pt()), lheWeight)
                self.hists["genMuon1_eta"].Fill(genMuon1.Eta(), lheWeight)
                self.hists["genMuon2_pt"].Fill(min(genMuon1.Pt(), genMuon2.Pt()), lheWeight)
                self.hists["genMuon2_eta"].Fill(genMuon2.Eta(), lheWeight)
                self.hists["genCosThetaStar"].Fill(genCosThetaStar, lheWeight)
                self.hists["genCosTheta1"].Fill(genCosTheta1, lheWeight)
                self.hists["genPhi1"].Fill(genPhi1, lheWeight)
                self.hists["genCosThetaStarZtoMM"].Fill(self.returnCosThetaStar(genH, genMuon1), lheWeight)
                
                # Reweight
                topWeight = 3./4. * (1. + genCosTheta1**2) # Transverse polarization (H, Z)
                if 'ZToJPsiG' in self.sampleName:
                    stitchWeight = 3./2. * (1. - genCosTheta1**2) # Longitudinal polarization (Z)
                
                # Acceptance
                if abs(genPhoton.Eta()) < 2.5:
                    self.hists["Acceptance"].Fill(1, lheWeight)
                    if abs(genMuon1.Eta()) < 2.4:
                        self.hists["Acceptance"].Fill(2, lheWeight)
                        if abs(genMuon2.Eta()) < 2.4:
                            self.hists["Acceptance"].Fill(3, lheWeight)
                            self.hists["Cutflow"].Fill(1, lheWeight)
                            if genPhoton.Pt() > 15. and genMuon1.Pt() > 5. and genMuon2.Pt() > 5.:
                                self.hists["Acceptance"].Fill(4, lheWeight)

        # Muons
        m1, m2 = -1, -1
        for i in range(event.nMuon):
            if event.Muon_pt[i] > self.thMuons[0 if m1 < 0 else 1] and abs(event.Muon_eta[i]) < 2.4 and event.Muon_looseId[i]:
                if m1 < 0: m1 = i
                if m2 < 0 and m1 >= 0 and event.Muon_charge[m1] != event.Muon_charge[i]: m2 = i
            
        if m1 < 0 or m2 < 0:
            if self.verbose >= 2: print "- No OS loose muons in acceptance"
            return False
            
        self.hists["Cutflow"].Fill(2, lheWeight)
        
        muon1, muon2 = TLorentzVector(), TLorentzVector()
        muon1.SetPtEtaPhiM(event.Muon_pt[m1], event.Muon_eta[m1], event.Muon_phi[m1], event.Muon_mass[m1])
        muon2.SetPtEtaPhiM(event.Muon_pt[m2], event.Muon_eta[m2], event.Muon_phi[m2], event.Muon_mass[m2])
        muonP = muon1 if event.Muon_charge[m1] > event.Muon_charge[m2] else muon2
        muonM = muon1 if event.Muon_charge[m1] < event.Muon_charge[m2] else muon2
        muon1v2, muon2v2 = TVector2(muon1.Px(), muon1.Py()), TVector2(muon2.Px(), muon2.Py())
        
        jpsi = muon1 + muon2
        
        if jpsi.M() < 2. or jpsi.M() > 12.:
            if self.verbose >= 2: print "- Dimuon invariant mass < 2 or > 12 GeV"
            return False
        
        self.hists["Cutflow"].Fill(3, lheWeight)
        
        # Photons
        p0 = -1
        for i in range(event.nPhoton):
            if event.Photon_pt[i] > self.thPhoton[0] and abs(event.Photon_eta[i]) < 2.5 and event.Photon_pfRelIso03_all[i] < 0.25: # and event.Photon_mvaID_WP80[i]:
                if p0 < 0: p0 = i
        
        if p0 < 0:
            if self.verbose >= 2: print "- No isolated photons in acceptance"
            return False
        
        self.hists["Cutflow"].Fill(4, lheWeight)
        
        photon = TLorentzVector()
        photon.SetPtEtaPhiM(event.Photon_pt[p0], event.Photon_eta[p0], event.Photon_phi[p0], event.Photon_mass[p0])
        photonv2 = TVector2(photon.Px(), photon.Py())
        
        met, metPlusPhoton = TVector2(), TVector2()
        met.SetMagPhi(event.MET_pt, event.MET_phi)
        metPlusPhoton.Set(met.Px() + photon.Px(), met.Py() + photon.Py())
        
        h = jpsi + photon

        jpsi_pt = jpsi.Pt()
        jpsi_eta = jpsi.Eta()
        jpsi_phi = jpsi.Phi()
        jpsi_mass = jpsi.M()
        jpsi_dEta = abs(muon1.Eta() - muon2.Eta())
        jpsi_dPhi = abs(muon1.DeltaPhi(muon2))
        jpsi_dR = muon1.DeltaR(muon2)
        
        h_pt = h.Pt()
        h_eta = h.Eta()
        h_phi = h.Phi()
        h_mass = h.M()
        h_dEta = abs(jpsi.Eta() - photon.Eta())
        h_dPhi = abs(jpsi.DeltaPhi(photon))
        h_dR = jpsi.DeltaR(photon)
        
        Muon1TrkIso, Muon2TrkIso = event.Muon_tkRelIso[m1], event.Muon_tkRelIso[m2]
        if jpsi_dR < 0.3:
            Muon1TrkIso = max(0., (Muon1TrkIso * event.Muon_pt[m1] * event.Muon_tunepRelPt[m1] - event.Muon_pt[m2] * event.Muon_tunepRelPt[m2])) / (event.Muon_pt[m1] * event.Muon_tunepRelPt[m1])
            Muon2TrkIso = max(0., (Muon2TrkIso * event.Muon_pt[m2] * event.Muon_tunepRelPt[m2] - event.Muon_pt[m1] * event.Muon_tunepRelPt[m1])) / (event.Muon_pt[m2] * event.Muon_tunepRelPt[m2])
        minMuonTrkIso = min(Muon1TrkIso, Muon2TrkIso)
        maxMuonTrkIso = max(Muon1TrkIso, Muon2TrkIso)
        minMuonIso = min(event.Muon_pfRelIso03_all[m1], event.Muon_pfRelIso03_all[m2])
        maxMuonIso = max(event.Muon_pfRelIso03_all[m1], event.Muon_pfRelIso03_all[m2])
        minMuonMetDPhi = min(abs(muon1v2.DeltaPhi(met)), abs(muon2v2.DeltaPhi(met)))
        maxMuonMetDPhi = max(abs(muon1v2.DeltaPhi(met)), abs(muon2v2.DeltaPhi(met)))
        photonMetDPhi = abs(photonv2.DeltaPhi(met))
        metPlusPhotonDPhi = abs(met.DeltaPhi(metPlusPhoton))
        
        cosThetaStar = self.returnCosThetaStar(h, jpsi)
        cosTheta1 = self.returnCosTheta1(jpsi, muonP, muonM, photon)
        phi1 = self.returnPhi1(h, muonP, muonM)

        # Weights
#        if self.isMC:
#            triggerWeight = self.muSFs.getTriggerSF(event.Muon_pt[m1], event.Muon_eta[m1])
#            IdSF1 = self.muSFs.getIdSF(event.Muon_pt[0], event.Muon_eta[0], 2)
#            IsoSF1 = self.muSFs.getIsoSF(event.Muon_pt[0], event.Muon_eta[0])
#            IdSF2 = self.muSFs.getIdSF(event.Muon_pt[1], event.Muon_eta[1], 2)
#            IsoSF2 = self.muSFs.getIsoSF(event.Muon_pt[1], event.Muon_eta[1])
#            IdIsoSF3 = self.elSFs.getIdIsoSF(event.Electron_pt[0], event.Electron_eta[0])
#            leptonWeight = IdSF1 * IsoSF1 * IdSF2 * IsoSF2 * IdIsoSF3
        
        passedMETFilters = True
        filters = ["Flag_goodVertices", "Flag_globalSuperTightHalo2016Filter", "Flag_BadPFMuonFilter", "Flag_EcalDeadCellTriggerPrimitiveFilter", "Flag_HBHENoiseFilter", "Flag_HBHENoiseIsoFilter", "Flag_ecalBadCalibFilter", "Flag_ecalBadCalibFilterV2"]
        if not self.isMC: filters += ["Flag_eeBadScFilter"]
        for f in filters:
            if hasattr(event, f) and getattr(event, f) == False: passedMETFilters = False
#        try:
##            if event.Flag_goodVertices: print "Flag_goodVertices"
##            if event.Flag_globalSuperTightHalo2016Filter: print "Flag_globalSuperTightHalo2016Filter"
##            if event.Flag_BadPFMuonFilter: print "Flag_BadPFMuonFilter"
##            if event.Flag_EcalDeadCellTriggerPrimitiveFilter: print "Flag_EcalDeadCellTriggerPrimitiveFilter"
##            if event.Flag_HBHENoiseFilter: print "Flag_HBHENoiseFilter"
##            if event.Flag_HBHENoiseIsoFilter: print "Flag_HBHENoiseIsoFilter"
###            if (self.isMC or event.Flag_eeBadScFilter): print "Flag_eeBadScFilter"
##            if event.Flag_ecalBadCalibFilter: print "Flag_ecalBadCalibFilterV2"
#            if event.Flag_goodVertices and event.Flag_globalSuperTightHalo2016Filter and event.Flag_BadPFMuonFilter and event.Flag_EcalDeadCellTriggerPrimitiveFilter and event.Flag_HBHENoiseFilter and event.Flag_HBHENoiseIsoFilter: # and event.Flag_ecalBadCalibFilter: #and (self.isMC or event.Flag_eeBadScFilter): FIXME
#                passedMETFilters = True
##            if not self.isMC:
##                if not event.Flag_eeBadScFilter:
##                    passedMETFilters = False
#        except:
#            passedMETFilters = False
        
        
        
        ### Event variables ###
        
        # Muons
        for i in range(event.nMuon):
            if i != m1 and i != m2 and event.Muon_pt[i] > 10. and abs(event.Muon_eta[i]) < 2.4 and event.Muon_looseId[i] and event.Muon_pfRelIso03_all[i] < 0.15:
                nCleanMuon += 1
        
        # Electrons
        for i in range(event.nElectron):
            if event.Electron_pt[i] > 10. and abs(event.Electron_eta[i]) < 2.5 and event.Electron_cutBased[i] >= 2:
                nCleanElectron += 1
        
        # Taus
        for i in range(event.nTau):
            if event.Tau_pt[i] > 20. and abs(event.Tau_eta[i]) < 2.5 and event.Tau_idDeepTau2017v2p1VSe[i] >= 16 and event.Tau_idDeepTau2017v2p1VSmu[i] >= 8 and event.Tau_idDeepTau2017v2p1VSjet[i] >= 16 and event.Tau_rawIsodR03[i] < 0.15:
                nCleanTau += 1
        
        # Photons
        for i in range(event.nPhoton):
            if i != p0 and event.Photon_pt[i] > 15. and abs(event.Photon_eta[i]) < 2.5 and event.Photon_pfRelIso03_all[i] < 0.15 and event.Photon_mvaID_WP90[i]:
                nCleanPhoton += 1
        
        # Jets and Event variables
        for i in range(event.nJet):
            if event.Jet_jetId[i] >= 6 and abs(event.Jet_eta[i]) < 2.5:
                HT30 += event.Jet_pt[i]
                nCleanJet += 1
                if event.Jet_btagDeepB[i] >= self.btagMedium: nCleanBTagJet += 1
        
        
        if self.isMC: eventWeightLumi = self.lumiWeight * lheWeight * puWeight * topWeight * qcdnloWeight * qcdnnloWeight * ewknloWeight * triggerWeight * leptonWeight
        
        self.out.fillBranch("isMC", self.isMC)
        self.out.fillBranch("is2016", (self.year == 2016))
        self.out.fillBranch("is2017", (self.year == 2017))
        self.out.fillBranch("is2018", (self.year == 2018))
        self.out.fillBranch("isSingleMuonTrigger", isSingleMuonTrigger)
        self.out.fillBranch("isSingleMuonPhotonTrigger", isSingleMuonPhotonTrigger)
        self.out.fillBranch("isSingleMuonNoFiltersPhotonTrigger", isSingleMuonNoFiltersPhotonTrigger)
        self.out.fillBranch("isDoubleMuonTrigger", isDoubleMuonTrigger)
        self.out.fillBranch("isDoubleMuonPhotonTrigger", isDoubleMuonPhotonTrigger)
        self.out.fillBranch("isJPsiTrigger", isJPsiTrigger)
        self.out.fillBranch("passedMETFilters", passedMETFilters)
        self.out.fillBranch("nCleanElectron", nCleanElectron)
        self.out.fillBranch("nCleanMuon", nCleanMuon)
        self.out.fillBranch("nCleanTau", nCleanTau)
        self.out.fillBranch("nCleanPhoton", nCleanPhoton)
        self.out.fillBranch("nCleanJet", nCleanJet)
        self.out.fillBranch("nCleanBTagJet", nCleanBTagJet)
        self.out.fillBranch("HT30", HT30)
        self.out.fillBranch("iPhoton", p0)
        self.out.fillBranch("iMuon1", m1)
        self.out.fillBranch("iMuon2", m2)
        #
        self.out.fillBranch("Muon1_pt", event.Muon_pt[m1])
        self.out.fillBranch("Muon1_eta", event.Muon_eta[m1])
        self.out.fillBranch("Muon2_pt", event.Muon_pt[m2])
        self.out.fillBranch("Muon2_eta", event.Muon_eta[m2])
        self.out.fillBranch("Muon1_pfRelIso03_all", event.Muon_pfRelIso03_all[m1])
        self.out.fillBranch("Muon2_pfRelIso03_all", event.Muon_pfRelIso03_all[m2])
        self.out.fillBranch("Muon1_mediumId", event.Muon_mediumId[m1])
        self.out.fillBranch("Muon2_mediumId", event.Muon_mediumId[m2])
        self.out.fillBranch("Muon1_ip3d", event.Muon_ip3d[m1])
        self.out.fillBranch("Muon2_ip3d", event.Muon_ip3d[m2])
        self.out.fillBranch("minMuonIso", minMuonIso)
        self.out.fillBranch("maxMuonIso", maxMuonIso)
        self.out.fillBranch("minMuonTrkIso", minMuonTrkIso)
        self.out.fillBranch("maxMuonTrkIso", maxMuonTrkIso)
        self.out.fillBranch("Muon12_diffdxy", abs(event.Muon_dxy[m1]-event.Muon_dxy[m2]))
        self.out.fillBranch("Muon12_diffdz", abs(event.Muon_dz[m1]-event.Muon_dz[m2]))
        self.out.fillBranch("Muon12_signdxy", abs(event.Muon_dxy[m1]-event.Muon_dxy[m2]) / math.sqrt(event.Muon_dxyErr[m1]**2 + event.Muon_dxyErr[m2]**2))
        self.out.fillBranch("Muon12_signdz", abs(event.Muon_dz[m1]-event.Muon_dz[m2]) / math.sqrt(event.Muon_dzErr[m1]**2 + event.Muon_dzErr[m2]**2))
        self.out.fillBranch("Photon1_pt", event.Photon_pt[p0])
        self.out.fillBranch("Photon1_eta", event.Photon_eta[p0])
        self.out.fillBranch("Photon1_mvaID_WP80", event.Photon_mvaID_WP80[p0])
        self.out.fillBranch("Photon1_pfRelIso03_all", event.Photon_pfRelIso03_all[p0])
        #
        self.out.fillBranch("JPsi_pt", jpsi_pt)
        self.out.fillBranch("JPsi_eta", jpsi_eta)
        self.out.fillBranch("JPsi_phi", jpsi_phi)
        self.out.fillBranch("JPsi_mass", jpsi_mass)
        self.out.fillBranch("JPsi_dEta", jpsi_dEta)
        self.out.fillBranch("JPsi_dPhi", jpsi_dPhi)
        self.out.fillBranch("JPsi_dR", jpsi_dR)
        self.out.fillBranch("H_pt", h_pt)
        self.out.fillBranch("H_eta", h_eta)
        self.out.fillBranch("H_phi", h_phi)
        self.out.fillBranch("H_mass", h_mass)
        self.out.fillBranch("H_dEta", h_dEta)
        self.out.fillBranch("H_dPhi", h_dPhi)
        self.out.fillBranch("H_dR", h_dR)
        self.out.fillBranch("minMuonMetDPhi", minMuonMetDPhi)
        self.out.fillBranch("maxMuonMetDPhi", maxMuonMetDPhi)
        self.out.fillBranch("photonMetDPhi", photonMetDPhi)
        self.out.fillBranch("metPlusPhotonDPhi", metPlusPhotonDPhi)
        self.out.fillBranch("cosThetaStar", cosThetaStar)
        self.out.fillBranch("cosTheta1", cosTheta1)
        self.out.fillBranch("phi1", phi1)
        self.out.fillBranch("genCosThetaStar", genCosThetaStar)
        self.out.fillBranch("genCosTheta1", genCosTheta1)
        self.out.fillBranch("genPhi1", genPhi1)
        self.out.fillBranch("lumiWeight", self.lumiWeight)
        self.out.fillBranch("lheWeight", lheWeight)
        self.out.fillBranch("stitchWeight", stitchWeight)
        self.out.fillBranch("puWeight", puWeight)
        self.out.fillBranch("topWeight", topWeight)
        self.out.fillBranch("qcdnloWeight", qcdnloWeight)
        self.out.fillBranch("qcdnnloWeight", qcdnnloWeight)
        self.out.fillBranch("ewknloWeight", ewknloWeight)
        self.out.fillBranch("triggerWeight", triggerWeight)
        self.out.fillBranch("leptonWeight", leptonWeight)
        self.out.fillBranch("eventWeightLumi", eventWeightLumi)
        
        if self.verbose >= 2: print "+ Tree filled"
        
        return True
Exemplo n.º 21
0
def shoot_in_cell(eta, phi, eta_min, eta_max, phi_min, phi_max, z, shoot_type, small_cell_side,\
                      large_cell_side, limit_first_zone, type, vertex_number, edge_number):

    if type not in ['Triangles', 'Hexagons']:
        raise Exception(
            'shoot_cell_center() not implemented for geometry type ' + type)
    if eta < eta_min or eta > eta_max or\
       TVector2.Phi_mpi_pi(phi-phi_min) < 0 or TVector2.Phi_mpi_pi(phi-phi_max) > 0:
        raise Exception(
            "Error: trying to shoot particle outside geometry window")

    # Find center
    theta0 = 2. * m.atan(m.exp(-eta_max))
    theta = 2. * m.atan(m.exp(-eta))
    r0 = z * m.tan(theta0)
    r = z * m.tan(theta)
    x0 = r0 * m.cos(phi_min)
    y0 = r0 * m.sin(phi_min)
    x = r * m.cos(phi)
    y = r * m.sin(phi)

    if x * x + y * y <= limit_first_zone * limit_first_zone:
        cell_side = small_cell_side
    else:
        cell_side = large_cell_side

    if type is 'Triangles':
        dxdi = cell_side / 2.
        dxdj = cell_side / 2.
        dydj = cell_side * m.sqrt(3.) / 2.
    else:
        dxdi = cell_side * m.sqrt(3.)
        dxdj = cell_side * m.sqrt(3.) / 2.
        dydj = cell_side * 3. / 2.

    j = round((y - y0) / dydj)
    i = round((x - x0 - j * dxdj) / dxdi)
    x_center = x0 + i * dxdi + j * dxdj
    y_center = y0 + j * dydj

    if type is 'Triangles' and int(i) % 2:
        y_center += cell_side * m.sqrt(3) / 6.

    if shoot_type == "cell_center":
        r_center = m.sqrt(x_center**2 + y_center**2)
        theta_center = m.atan(r_center / z)
        eta_shoot = -m.log(m.tan(theta_center / 2.))
        phi_cell = m.copysign(m.acos(x_center / r_center), y_center)

    elif shoot_type == "cell_vertex":
        # Get position of vertices
        vertex = vertices(type, int(i), cell_side)
        if vertex_number >= len(vertex):
            raise Exception('Vertex {0} doesn\'t exist for type {1}'.format(
                vertex_number, type))
        x_vertex, y_vertex = vertex[vertex_number]
        x_vertex += x_center
        y_vertex += y_center
        r_vertex = m.sqrt(x_vertex**2 + y_vertex**2)
        theta_vertex = m.atan(r_vertex / z)
        eta_shoot = -m.log(m.tan(theta_vertex / 2.))
        phi_cell = m.copysign(m.acos(x_vertex / r_vertex), y_vertex)

    elif shoot_type == "cell_edge":
        edges = edge_centers(type, int(i), cell_side)
        if edge_number >= len(edges):
            raise Exception('Edge {0} doesn\'t exist for type {1}'.format(
                edge_number, type))
        x_edge, y_edge = edges[edge_number]
        x_edge += x_center
        y_edge += y_center
        r_edge = m.sqrt(x_edge**2 + y_edge**2)
        theta_edge = m.atan(r_edge / z)
        eta_shoot = -m.log(m.tan(theta_edge / 2.))
        phi_cell = m.copysign(m.acos(x_edge / r_edge), y_edge)

    else:
        raise Exception(
            'The shoot type should be cell_center, cell_edge or cell_vertex')

    return eta_shoot, phi_cell
Exemplo n.º 22
0
    def process(self, **kwargs):
        tree = kwargs['tree']
        input = kwargs['input']
        output = kwargs['output']

        #cmssw_base = os.getenv('CMSSW_BASE')
        #sys.path.append(cmssw_base+'/src/LatinoAnalysis/Gardener/python/data/met/')
        #locateParaFile= cmssw_base+'/src/LatinoAnalysis/Gardener/python/data/met/'+self.paraFile
        #print locateParaFile
        #exec("paraSet = " +self.sample)
        #print 'para. name:', paraSet.name, paraSet.varType, paraSet.fx, paraSet.paraX[0], paraSet.paraX[1], paraSet.fy, paraSet.paraY[0], paraSet.paraY[1]
        #self.extractPara()
        try:
            ROOT.gROOT.LoadMacro(
                self.cmssw_base +
                '/src/LatinoAnalysis/Gardener/python/variables/metXYshift.C+g')
        except RuntimeError:
            ROOT.gROOT.LoadMacro(
                self.cmssw_base +
                '/src/LatinoAnalysis/Gardener/python/variables/metXYshift.C++g'
            )

        MetXYshift = ROOT.metXYshift(
            self.cmssw_base + "/src/LatinoAnalysis/Gardener/python/data/met/" +
            self.paraFile)

        MetXYshift.printPara()

        self.connect(tree, input)

        nentries = self.itree.GetEntries()
        #nentries = 10
        print ' - Input entries:', nentries
        savedentries = 0

        #print "cmssw_base =", cmssw_base
        # Create branches for otree, the ones that will be modified
        self.metVariables = [
            'corrMetPfType1', 'corrMetPfType1Phi', 'corrMetPfRaw',
            'corrMetPfRawPhi'
        ]

        # Clone the tree with new branches added
        self.clone(output, self.metVariables)

        # Now actually connect the branches
        corrMetPfType1 = numpy.ones(1, dtype=numpy.float32)
        corrMetPfType1Phi = numpy.ones(1, dtype=numpy.float32)
        corrMetPfRaw = numpy.ones(1, dtype=numpy.float32)
        corrMetPfRawPhi = numpy.ones(1, dtype=numpy.float32)

        self.otree.Branch('corrMetPfType1', corrMetPfType1, 'corrMetPfType1/F')
        self.otree.Branch('corrMetPfType1Phi', corrMetPfType1Phi,
                          'corrMetPfType1Phi/F')
        self.otree.Branch('corrMetPfRaw', corrMetPfType1, 'corrMetPfRaw/F')
        self.otree.Branch('corrMetPfRawPhi', corrMetPfType1Phi,
                          'corrMetPfRawPhi/F')

        # Input tree
        itree = self.itree

        #-----------------------------------------------------------------------
        print ' - Starting event loop'
        step = 50000

        #nentries = 10
        corx = ROOT.Double(0)
        cory = ROOT.Double(0)

        oldMetPfType1 = ROOT.Double(0)
        oldMetPfType1Phi = ROOT.Double(0)
        corrMetPfType1_x = ROOT.Double(0)
        corrMetPfType1_y = ROOT.Double(0)
        corrMetPftype1_2d = TVector2()

        oldMetPfRaw = ROOT.Double(0)
        oldMetPfRawPhi = ROOT.Double(0)
        corrMetPfRaw_x = ROOT.Double(0)
        corrMetPfRaw_y = ROOT.Double(0)
        corrMetPfRaw_2d = TVector2()

        nGoodVtx = ROOT.Double(0)

        for i in xrange(nentries):
            itree.GetEntry(i)

            nGoodVtx = itree.nGoodVtx

            # 76x ----------------------------------------------------------------
            if self.cmssw >= 763:
                oldMetPfType1 = itree.metPfType1
                oldMetPfType1Phi = itree.metPfType1Phi
                oldMetPfRaw = itree.metPfRaw
                oldMetPfRawPhi = itree.metPfRawPhi

            # 74x ----------------------------------------------------------------
            else:
                oldMetPfType1 = itree.pfType1Met
                oldMetPfType1Phi = itree.pfType1Metphi
                oldMetPfRaw = itree.metPfRaw
                oldMetPfRawPhi = itree.metPfRawPhi

#varType = "multiplicity":0, "ngoodVertices":1, "sumPt":2
            if MetXYshift.ParVar() == 0:
                #print "multiplicity ===================="
                #MetXYshift.CalcXYshiftCorr(
                #    self.sample,
                #    multi,
                #      #itree.egammaHFPlus_counts,#TODO need to be changed to ele
                #      #itree.egammaHFMinus_counts,#TODO need to be changed to mu
                #      corx, cory
                #)
                print "MetXYshift sumPt not ready"
                sys.exit(0)
            elif MetXYshift.ParVar() == 1:

                MetXYshift.CalcXYshiftCorr(self.sample, nGoodVtx,
                                           oldMetPfType1, corx, cory)

            elif MetXYshift.ParVar() == 2:
                print "MetXYshift sumPt not ready"
                sys.exit(0)
            else:
                print "no case of parVar; exiting"
                sys.exit(0)

            #################################
# Correction of PfType1
#################################
#print 'corx: ', corx, ' cory: ', cory
            oldMetPfType1_x = oldMetPfType1 * math.cos(oldMetPfType1Phi)
            oldMetPfType1_y = oldMetPfType1 * math.sin(oldMetPfType1Phi)

            #print '=========================='
            #print 'old xy ', corrMetPfType1_x, corrMetPfType1_y
            corrMetPfType1_x = corx + oldMetPfType1_x
            corrMetPfType1_y = cory + oldMetPfType1_y
            #print 'new xy ', corrMetPfType1_x, corrMetPfType1_y
            corrMetPftype1_2d.Set(corrMetPfType1_x, corrMetPfType1_y)
            #corrPftype1Met_2d = TVector2(corrMetPfType1_x, corrMetPfType1_y)
            corrMetPfType1[0] = corrMetPftype1_2d.Mod()
            corrMetPfType1Phi[0] = corrMetPftype1_2d.Phi()
            corrMetPfType1Phi[0] = self.phiLessPi(corrMetPfType1Phi)

            #corrMetPfType1 = math.sqrt(corrMetPfType1_x * corrMetPfType1_x + corrMetPfType1_y*corrMetPfType1_y)
            #corrMetPfType1Phi = math.asin(corrMetPfType1_y / corrMetPfType1 )

            #print 'oldMet, phi: ', oldMetPfType1, oldMetPfType1Phi
            #print 'newMet, phi: ', corrMetPfType1[0], corrMetPfType1Phi[0]

            #################################
            # Correction of PfRaw
            #################################
            oldMetPfRaw_x = oldMetPfRaw * math.cos(oldMetPfRawPhi)
            oldMetPfRaw_y = oldMetPfRaw * math.sin(oldMetPfRawPhi)

            corrMetPfRaw_x = corx + oldMetPfRaw_x
            corrMetPfRaw_y = cory + oldMetPfRaw_y
            corrMetPfRaw_2d.Set(corrMetPfRaw_x, corrMetPfRaw_y)
            corrMetPfRaw[0] = corrMetPfRaw_2d.Mod()
            corrMetPfRawPhi[0] = corrMetPfRaw_2d.Phi()
            corrMetPfRawPhi[0] = self.phiLessPi(corrMetPfRawPhi)

            if (i > 0 and i % step == 0.):
                print i, 'events processed ::', nentries, 'oldMetPfType1:', oldMetPfType1, 'corrMetPfType1:', corrMetPfType1[
                    0], 'oldMetPfType1Phi:', oldMetPfType1Phi, 'corrMetPfType1Phi:', corrMetPfType1Phi[
                        0]
                print 'oldMetPfRaw:', oldMetPfRaw, 'corrMetPfRaw:', corrMetPfRaw[
                    0], 'oldMetPfRawPhi:', oldMetPfRawPhi, 'corrMetPfRawPhi:', corrMetPfRawPhi[
                        0]

            self.otree.Fill()
            savedentries += 1
        self.disconnect()
        print ' - Event loop completed'
        print ' - Saved entries:', savedentries
Exemplo n.º 23
0
    def process(self, event):
        self.tree.reset()
        higgses = event.higgses

        if len(higgses) > 0:
            self.tree.fill('weight', event.weight)
            print len(higgses)

            # Reco Higgs
            higgs = higgses[0]
            l1 = higgs.legs[0]
            l2 = higgs.legs[1]

            fillParticle(self.tree, 'll', higgs)
            fillMet(self.tree, 'met', event.met)

            fillLepton(self.tree, 'l1', l1)
            fillLepton(self.tree, 'l2', l2)

            if abs(l1.pdgid()) == abs(l2.pdgid()):
                self.tree.fill('is_sf', 1.0)
                self.tree.fill('is_of', 0.0)
            else:
                self.tree.fill('is_sf', 0.0)
                self.tree.fill('is_of', 1.0)

            hpx = higgs.pt() * math.cos(higgs.phi())
            hpy = higgs.pt() * math.sin(higgs.phi())
            metx = event.met.pt() * math.cos(event.met.phi())
            mety = event.met.pt() * math.sin(event.met.phi())

            pth = math.sqrt((hpx + metx)**2 + (hpy + mety)**2)

            dphi_ll = TVector2.Phi_mpi_pi(l1.phi() - l2.phi())
            dphi_llmet = TVector2.Phi_mpi_pi(higgs.phi() - event.met.phi())

            mt = math.sqrt(2 * higgs.pt() * event.met.pt() *
                           (1 - math.cos(dphi_llmet)))

            mll = higgs.m()
            ptll = higgs.pt()
            met = event.met.pt()

            met_d_ptll = metx * hpx + mety * hpy
            mr = math.sqrt((mll**2 - met_d_ptll + math.sqrt(
                (mll**2 + ptll**2) * (mll**2 + met**2))))

            pl1 = ROOT.TLorentzVector()
            pl2 = ROOT.TLorentzVector()
            pMet = ROOT.TVector3()

            pl1.SetPtEtaPhiM(l1.pt(), l1.eta(), l1.phi(), l1.m())
            pl2.SetPtEtaPhiM(l2.pt(), l2.eta(), l2.phi(), l2.m())
            pMet.SetPtEtaPhi(event.met.pt(), 0.0, event.met.phi())

            def calcMR(L1, L2):
                E = L1.P() + L2.P()
                Pz = L1.Pz() + L2.Pz()
                MR = math.sqrt(E * E - Pz * Pz)
                return MR

            def calcMRNEW(L1, L2, M):
                vI = M + L1.Vect() + L2.Vect()
                vI.SetZ(0.0)
                PpQ = calcMR(L1, L2)
                vptx = (L1 + L2).Px()
                vpty = (L1 + L2).Py()
                vpt = ROOT.TVector3()
                vpt.SetXYZ(vptx, vpty, 0.0)
                MR2 = 0.5 * (PpQ * PpQ - vpt.Dot(vI) + PpQ *
                             sqrt(PpQ * PpQ + vI.Dot(vI) - 2. * vI.Dot(vpt)))
                return MR2

            mr = 2 * math.sqrt(calcMRNEW(pl1, pl2, pMet))

            self.tree.fill('mt', mt)
            self.tree.fill('mr', mr)
            self.tree.fill('higgs_pt', pth)
            self.tree.fill('dphi_ll', abs(dphi_ll))
            self.tree.fill('dphi_llmet', abs(dphi_llmet))
            self.tree.fill('nbjets', len(event.selected_bs))
            self.tree.fill('nljets', len(event.selected_lights))
            self.tree.fill('njets',
                           len(event.selected_lights) + len(event.selected_bs))

            self.tree.tree.Fill()
Exemplo n.º 24
0
    def add_point_const(self, hnam, vnam, mult2=1.):

        hpos = float(str(self.geo.GetConst(hnam)))
        vpos = float(str(self.geo.GetConst(vnam)))

        self.points.append(TVector2(hpos, mult2 * vpos))
Exemplo n.º 25
0
            minRelIso[cst.Tau] = Chain._tauCombinedIsoDBRaw3Hits[lepton]
            lIndex[cst.Tau] = lepton

    #Event selection
    if (minRelIso[cst.Muon] == 999999 or minRelIso[cst.Tau] == 999999):
        continue  #Remove events without tau and muon
    if (Chain._lCharge[lIndex[cst.Muon]] == Chain._lCharge[lIndex[cst.Tau]]):
        continue  #Remove same charge pairs

    if sample.name == 'DYJetsToLL_M-10to50_bkgr' or sample.name == 'DYJetsToLL_M-50_bkgr':
        if geometricMatch(Chain, lIndex[cst.Tau]): continue
    elif 'DYJets' in sample.name:
        if not geometricMatch(Chain, lIndex[cst.Tau]): continue

    lVec = []
    MetVec = TVector2()
    MuTransVec = TVector2()
    TauTransVec = TVector2()
    for whichlep in xrange(cst.NumberOfLeptons):
        vec = TLorentzVector()
        lVec.append(vec)
        lVec[whichlep].SetPtEtaPhiE(Chain._lPt[lIndex[whichlep]],
                                    Chain._lEta[lIndex[whichlep]],
                                    Chain._lPhi[lIndex[whichlep]],
                                    Chain._lE[lIndex[whichlep]])

    MetVec.SetMagPhi(Chain._met, Chain._metPhi)
    MuTransVec.SetMagPhi(Chain._lPt[lIndex[cst.Muon]],
                         Chain._lPhi[lIndex[cst.Muon]])
    TauTransVec.SetMagPhi(Chain._lPt[lIndex[cst.Tau]],
                          Chain._lPhi[lIndex[cst.Tau]])
Exemplo n.º 26
0
    def process(self, event):
        self.tree.reset()

        # just the ll pair added into a particle for convenience
        higgses = event.higgses

        leptons = event.selected_leptons
        leptons.sort(key=lambda x: x.pt(), reverse=True)

        jets = event.jets_nolepton
        jets.sort(key=lambda x: x.pt(), reverse=True)

        met = event.met
        '''
        for jet in jets:
           print jet
        '''

        sign = lambda x: x and (1, -1)[x < 0]
        same_sign_pair = []
        # this gives orders pairs (so twice as many as we need)
        for i in itertools.permutations(leptons, 2):
            #print 'new lep pair', i[0], i[1]
            if sign(i[0].pdgid()) == sign(i[1].pdgid()):
                same_sign_pair.append(i)

        if len(same_sign_pair) > 0 and len(jets) > 1:

            self.tree.fill('weight', 1.)
            self.tree.fill('njets', len(jets))
            self.tree.fill('nleptons', len(leptons))

            l1 = leptons[0]
            l2 = leptons[1]
            j1 = jets[0]
            j2 = jets[1]

            fillParticle(self.tree, 'lpt1', l1)
            fillParticle(self.tree, 'lpt2', l2)

            fillParticle(self.tree, 'jpt1', j1)
            fillParticle(self.tree, 'jpt2', j2)

            leptons.sort(key=lambda x: abs(x.eta()))
            jets.sort(key=lambda x: abs(x.eta()))

            l1 = leptons[0]
            l2 = leptons[1]
            j1 = jets[0]
            j2 = jets[1]

            fillParticle(self.tree, 'leta1', l1)
            fillParticle(self.tree, 'leta2', l2)

            fillParticle(self.tree, 'jeta1', j1)
            fillParticle(self.tree, 'jeta2', j2)

            if abs(l1.pdgid()) == abs(l2.pdgid()):
                self.tree.fill('is_sf', 1.0)
                self.tree.fill('is_of', 0.0)
            else:
                self.tree.fill('is_sf', 0.0)
                self.tree.fill('is_of', 1.0)

            higgs = higgses[0]
            mll = higgs.m()

            dphi_ll = TVector2.Phi_mpi_pi(l1.phi() - l2.phi())
            dphi_jj = TVector2.Phi_mpi_pi(j1.phi() - j2.phi())
            dphi_llmet = TVector2.Phi_mpi_pi(higgs.phi() - event.met.phi())

            mt = math.sqrt(2 * higgs.pt() * event.met.pt() *
                           (1 - math.cos(dphi_llmet)))

            mll = higgs.m()
            ptll = higgs.pt()
            met = event.met.pt()
            hpx = higgs.pt() * math.cos(higgs.phi())
            hpy = higgs.pt() * math.sin(higgs.phi())
            metx = event.met.pt() * math.cos(event.met.phi())
            mety = event.met.pt() * math.sin(event.met.phi())
            met_d_ptll = metx * hpx + mety * hpy
            mr = math.sqrt((mll**2 - met_d_ptll + math.sqrt(
                (mll**2 + ptll**2) * (mll**2 + met**2))))

            self.tree.fill('mt', mt)
            self.tree.fill('mr', mr)

            mjj = math.sqrt((j1.e() + j2.e())**2 -
                            (j1.p4().Px() + j2.p4().Px())**2 -
                            (j1.p4().Py() + j2.p4().Py())**2 -
                            (j1.p4().Pz() + j2.p4().Pz())**2)
            ptjj = math.sqrt((j1.p4().Px() + j2.p4().Px())**2 +
                             (j1.p4().Py() + j2.p4().Py())**2)

            self.tree.fill('mll', mll)
            self.tree.fill('mjj', mjj)

            self.tree.fill('ptll', higgs.pt())
            self.tree.fill('ptjj', ptjj)

            deta_ll = abs(l1.eta() - l2.eta())
            deta_jj = abs(j1.eta() - j2.eta())

            self.tree.fill('detall', deta_ll)
            self.tree.fill('detajj', deta_jj)

            #mll2 = math.sqrt( (l1.e()+l2.e())**2 - (l1.p4().Px()+l2.p4().Px())**2  - (l1.p4().Py()+l2.p4().Py())**2  - (l1.p4().Pz()+l2.p4().Pz())**2 )

            self.tree.fill('dphill', abs(dphi_ll))
            self.tree.fill('dphijj', abs(dphi_jj))
            self.tree.fill('dphillmet', abs(dphi_llmet))

            fillMet(self.tree, 'met', event.met)

            self.tree.tree.Fill()
Exemplo n.º 27
0
    def __call__(self, event, base={}):

        # prepare output
        ret = {}
        for name in self.branches:
            if type(name) == 'tuple':
                ret[name] = []
            elif type(name) == 'str':
                ret[name] = -999.0

        # get some collections from initial tree
        leps = [l for l in Collection(event, "LepGood", "nLepGood")]
        jets = [j for j in Collection(event, "Jet", "nJet")]

        njet = len(jets)
        nlep = len(leps)

        # MET
        metp4 = ROOT.TLorentzVector(0, 0, 0, 0)
        metp4.SetPtEtaPhiM(event.met_pt, event.met_eta, event.met_phi,
                           event.met_mass)
        pmiss = array.array('d', [
            event.met_pt * cos(event.met_phi),
            event.met_pt * sin(event.met_phi)
        ])

        ####################################
        # import output from previous step #
        #base = keyvals
        ####################################

        # get selected leptons
        tightLeps = []
        tightLepsIdx = base['tightLepsIdx']
        tightLeps = [leps[idx] for idx in tightLepsIdx]
        nTightLeps = len(tightLeps)

        # get selected jets
        centralJet30 = []
        centralJet30idx = base['centralJet30idx']
        centralJet30 = [jets[idx] for idx in centralJet30idx]
        nCentralJet30 = len(centralJet30)

        # B jets
        BJetMedium30 = []
        BJetMedium30idx = base['BJetMedium30idx']
        nBJetMedium30 = base['nBJetMedium30']
        '''
        for idx,jet in enumerate(centralJet30):
        if idx in BJetMedium30idx:
        BJetMedium30.append(jet)
        '''

        #print 'here',event.evt, nTightLeps, len(centralJet30), nBJetMedium30

        ##################################################################
        # The following variables need to be double-checked for validity #
        ##################################################################

        ## B tagging WPs for CSVv2 (CSV-IVF)
        ## L: 0.423, M: 0.814, T: 0.941
        ## from: https://twiki.cern.ch/twiki/bin/view/CMSPublic/SWGuideBTagging#Preliminary_working_or_operating

        bTagWP = 0.814  # MediumWP for CSVv2
        #bTagWP = 0.732 # MediumWP for CMVA

        # deltaPhi between the (single) lepton and the reconstructed W (lep + MET)
        # ST of lepton and MET
        DL_ST = []
        DL_dPhiLepW = []

        LepToKeep_pt = -999
        l1l2ovMET = -999
        Vecl1l2ovMET = -999

        DPhil1l2 = -999

        if len(tightLeps) == 2:
            passPreSel = False
            SumP4 = tightLeps[0].p4() + tightLeps[1].p4()
            if tightLeps[0].charge != tightLeps[1].charge: passPreSel = True
            if tightLeps[0].pdgId == -tightLeps[1].pdgId and abs(SumP4.M() -
                                                                 91.2) < 10.:
                passPreSel = False

            if passPreSel:
                random = TRandom2(event.evt * event.lumi)
                uniform01 = random.Rndm()
                lepToKeep = int(uniform01 > 0.5)
                lepToDiscard = int(not lepToKeep)

                Met2D = TVector2(metp4.Px(), metp4.Py())
                LepToDiscard2D = TVector2(tightLeps[lepToDiscard].p4().Px(),
                                          tightLeps[lepToDiscard].p4().Py())
                LepToKeep2D = TVector2(tightLeps[lepToKeep].p4().Px(),
                                       tightLeps[lepToKeep].p4().Py())

                Met2D_AddFull = Met2D + LepToDiscard2D
                Met2D_AddThird = Met2D + (1 / 3. * LepToDiscard2D)
                LepToKeep_pt = LepToKeep2D.Mod()

                recoWp4 = LepToKeep2D + Met2D
                DL_dPhiLepW.append(LepToKeep2D.DeltaPhi(
                    recoWp4))  # [0]: not adding leptons to MET
                DL_ST.append(LepToKeep2D.Mod() + Met2D.Mod())

                recoWp4_AddFull = LepToKeep2D + Met2D_AddFull
                DL_dPhiLepW.append(LepToKeep2D.DeltaPhi(
                    recoWp4_AddFull))  # [0]: adding lost lepton pt to met
                DL_ST.append(LepToKeep2D.Mod() + Met2D_AddFull.Mod())

                recoWp4_AddThird = LepToKeep2D + Met2D_AddThird
                DL_dPhiLepW.append(LepToKeep2D.DeltaPhi(
                    recoWp4_AddThird))  # [2]: adding 1/3 of lepton ptto met
                DL_ST.append(LepToKeep2D.Mod() + Met2D_AddThird.Mod())

                l1l2ovMET = (tightLeps[0].pt + tightLeps[1].pt) / metp4.Pt()
                Vecl1l2ovMET = (LepToKeep2D +
                                LepToDiscard2D).Mod() / metp4.Pt()

                DPhil1l2 = LepToKeep2D.DeltaPhi(LepToDiscard2D)

        ret["nLostLepTreatments"] = 3
        if len(DL_ST) != ret["nLostLepTreatments"]:
            for i in range(0, ret["nLostLepTreatments"]):
                DL_ST.append(-999)
                DL_dPhiLepW.append(-999)

        ret["DL_ST"] = DL_ST
        ret["DL_dPhiLepW"] = DL_dPhiLepW

        ret['DL_LepGoodOne_pt'] = LepToKeep_pt
        ret['DL_l1l2ovMET'] = l1l2ovMET
        ret['DL_Vecl1l2ovMET'] = Vecl1l2ovMET
        ret['DL_DPhil1l2'] = DPhil1l2

        return ret
Exemplo n.º 28
0
def Calculate_DeltaPhi(phi_1, phi_2):
    dphi = TVector2.Phi_mpi_pi(phi_1 - phi_2)
    return fabs(dphi)
    ntrt = histTreeData.trk_nTRT
    E = histTreeData.trk_nclusters_EM_200 + histTreeData.trk_nclusters_HAD_200
    if (ntrt > 20 and E > 0):
        if (etaemb2 < -100):
            etacal = etaeme2
        elif (etaeme2 < -100):
            etacal = etaemb2

        if (phiemb2 < -100):
            phical = phieme2
        elif (phieme2 < -100):
            phical = phiemb2

        deta = abs(etacal - etatrck)

        dphi = TVector2.Phi_0_2pi(
            TVector2.Phi_0_2pi(phitrck) - TVector2.Phi_0_2pi(phical))
        dphi = TMath.Min(dphi, (2.0 * math.pi) - dphi)

        dR = math.sqrt(deta * deta + dphi * dphi)

        if (dR > 1.5):
            print("momentum: ", p, "\n Track Eta: ", etatrck, "\n Track Phi",
                  phitrck, "\n Calorimeter Eta: ", etacal,
                  "\n Calorimeter Phi: ", phical, "\n")

        trckvcalextdiff.Fill(p, dR)

entries = histTreeMonte.GetEntriesFast()
trckvcalextdiffMonte = TH2D("trck_vs_cal_ext_Monte",
                            "Track vs Calorimeter Extrapolated Differences",
                            100, 0, 10, 100, 0, 5)
Exemplo n.º 30
0
    def add_point(self, nam, hnam, vnam, mult2=1.):

        self.points.append(
            TVector2(self.geo.GetD(nam, hnam),
                     mult2 * self.geo.GetD(nam, vnam)))