def mass(tau1, tau2, METpx, METpy):
    """
    Calculate and return the collinear mass and momentum fractions
    of tau1 and tau2
    TODO: set visible mass of taus. 1.2 GeV for 3p and 0.8 GeV for 1p
    """
    recTau1 = TLorentzVector()
    recTau2 = TLorentzVector()

    # tau 4-vector; synchronize for MMC calculation
    if tau1.numTrack < 3:
        recTau1.SetPtEtaPhiM(tau1.pt, tau1.eta, tau1.phi, 800.)  # MeV
    else:
        recTau1.SetPtEtaPhiM(tau1.pt, tau1.eta, tau1.phi, 1200.)  # MeV

    if tau2.numTrack < 3:
        recTau2.SetPtEtaPhiM(tau2.pt, tau2.eta, tau2.phi, 800.)  # MeV
    else:
        recTau2.SetPtEtaPhiM(tau2.pt, tau2.eta, tau2.phi, 1200.)  # MeV

    K = ROOT.TMatrixD(2, 2)
    K[0][0] = recTau1.Px()
    K[0][1] = recTau2.Px()
    K[1][0] = recTau1.Py()
    K[1][1] = recTau2.Py()

    if K.Determinant() == 0:
        return -1., -1111., -1111.

    M = ROOT.TMatrixD(2, 1)
    M[0][0] = METpx
    M[1][0] = METpy

    Kinv = K.Invert()

    X = Kinv * M

    X1 = X(0, 0)
    X2 = X(1, 0)

    x1 = 1. / (1. + X1)
    x2 = 1. / (1. + X2)

    p1 = recTau1 * (1. / x1)
    p2 = recTau2 * (1. / x2)
    m_col = (p1 + p2).M()
    m_vis = (recTau1 + recTau2).M()

    return m_vis, m_col, x1, x2
Exemple #2
0
def jet_Lorentz_4v(jet):
    for n in np.arange(len(jet)):
        if np.sum(jet[n,:]) != 0:
            v = TLorentzVector(0, 0, 0, 0)
            v.SetPtEtaPhiM(jet[n,0], jet[n,1], jet[n,2], jet[n,3])
            jet[n,:] = v.E(), v.Px(), v.Py(), v.Pz()
    return jet
def make_LHEparticle(p, id=None):
    if id != None:
        fv = TLorentzVector()

        try:
            m = p.Mass
        except AttributeError:
            m = 0

        try:
            pT = p.PT
        except AttributeError:
            pT = p.MET

        fv.SetPtEtaPhiM(pT, p.Eta, p.Phi, m)

        try:
            status = p.Status
        except AttributeError:
            status = 1

        _dict={'id':id,'status':status,\
                          'mother1':0,'mother2':0,'color1':0,'color2':0,\
                          'px':fv.Px(),'py':fv.Py(),'pz':fv.Pz(),'e':fv.Energy(),'m':fv.M(),'lifetime':0,'spin':0}
        lhepart = lhef.LHEParticle(**_dict)
        return lhepart
    else:
        print("id must be specified")
        pass
def TransBoosted_Angle(pt1,eta1,phi1,pt2,eta2,phi2,ptz,etaz,phiz,mass,Met,Metphi):
	mu1 = TLorentzVector()
	mu2 = TLorentzVector()
	zb = TLorentzVector()
	met = TLorentzVector()
	mu1.SetPtEtaPhiM(pt1,0,phi1,0)
	mu2.SetPtEtaPhiM(pt2,0,phi2,0)
	zb.SetPtEtaPhiM(ptz,0,phiz,mass)
	MET.SetPtEtaPhiM(Met,0,Metphi,0)
	MET.Boost(-zb.Px()/zb.Et(),-zb.Py()/zb.Et(),0)
	mu1.Boost(-zb.Px()/zb.Et(),-zb.Py()/zb.Et(),0)
	mu2.Boost(-zb.Px()/zb.Et(),-zb.Py()/zb.Et(),0)
	angleBoost_1 = MET.DeltaPhi(mu1)
	angleBoost_2 = MET.DeltaPhi(mu2)
	angleBoost_Z = MET.DeltaPhi(zb)
	return [angleBoost_Z,angleBoost_1,angleBoost_2]
def PTmiss_vect(Energy,parts):
	# here parts is visible parts
	#p=parts[0].p4-parts[0].p4
	p=TLorentzVector(0,0,0,Energy)
	for part in parts:
		p=p-part.P4()
	return p.Px(),p.Py()
Exemple #6
0
def computeProcessedFeatures(muon1_p4, muon2_p4, unpairedMuon_p4, jpsi_p4, bc_p4):
  if ( bc_p4.M() != 0): 
    bcPtCorrected = (bcPdgMass * bc_p4.Pt())/ bc_p4.M()
  else:
    bcPtCorrected = bc_p4.Pt()

  muonsSystem_p4 = muon1_p4 + muon2_p4 + unpairedMuon_p4

  bcCorrected_p4 = TLorentzVector()
  bcCorrected_p4.SetPtEtaPhiM(bcPtCorrected,
      muonsSystem_p4.Eta(),
      muonsSystem_p4.Phi(),
      #bc_p4.M())
      bcPdgMass)
  boostToBcCorrectedRestFrame = -bcCorrected_p4.BoostVector()
  #boostToJpsiRestFrame = -(muon1_p4+muon2_p4).BoostVector()
  boostToJpsiRestFrame = -jpsi_p4.BoostVector()

  unpairedMuonBoostedToBcCorrectedRestFrame_p4 = TLorentzVector() 
  unpairedMuonBoostedToBcCorrectedRestFrame_p4.SetPtEtaPhiM(unpairedMuon_p4.Pt(), unpairedMuon_p4.Eta(), unpairedMuon_p4.Phi(), unpairedMuon_p4.M())
  unpairedMuonBoostedToBcCorrectedRestFrame_p4.Boost(boostToBcCorrectedRestFrame)
  unpairedMuonBoostedToJpsiRestFrame_p4 = TLorentzVector() 
  unpairedMuonBoostedToJpsiRestFrame_p4.SetPtEtaPhiM(unpairedMuon_p4.Pt(), unpairedMuon_p4.Eta(), unpairedMuon_p4.Phi(), unpairedMuon_p4.M())
  unpairedMuonBoostedToJpsiRestFrame_p4.Boost(boostToJpsiRestFrame)

  nn_energyBcRestFrame = unpairedMuonBoostedToBcCorrectedRestFrame_p4.E()
  #nn_missMass2 = (bcCorrected_p4 - muon1_p4 - muon2_p4 - unpairedMuon_p4).M2()
  nn_missMass2 = (bcCorrected_p4 - jpsi_p4 - unpairedMuon_p4).M2()
  #nn_q2 = (bc_p4 - muon1_p4 - muon2_p4).M2()
  nn_q2 = (bcCorrected_p4 - jpsi_p4).M2()
  #nn_missPt = bcCorrected_p4.Pt() - muon1_p4.Pt() - muon2_p4.Pt() - unpairedMuon_p4.Pt()
  nn_missPt = bcCorrected_p4.Pt() - jpsi_p4.Pt() - unpairedMuon_p4.Pt()
  nn_energyJpsiRestFrame = unpairedMuonBoostedToJpsiRestFrame_p4.E()
  #nn_varPt = (muon1_p4 + muon2_p4).Pt() - unpairedMuon_p4.Pt()
  nn_varPt = jpsi_p4.Pt() - unpairedMuon_p4.Pt()
  nn_deltaRMu1Mu2 = muon1_p4.DeltaR(muon2_p4)
  nn_unpairedMuPhi = unpairedMuon_p4.Phi()
  nn_unpairedMuPt = unpairedMuon_p4.Pt()
  nn_unpairedMuEta = unpairedMuon_p4.Eta()

  featuresEntry = np.array([
    [bcCorrected_p4.Pt()], 
    [bcCorrected_p4.Px()], 
    [bcCorrected_p4.Py()], 
    [bcCorrected_p4.Pz()], 
    [bcCorrected_p4.E()], 
    [nn_energyBcRestFrame],
    [nn_missMass2],
    [nn_q2],
    [nn_missPt],
    [nn_energyJpsiRestFrame],
    [nn_varPt],
    [nn_deltaRMu1Mu2],
    [nn_unpairedMuPhi],
    [nn_unpairedMuPt],
    [nn_unpairedMuEta]], 
    dtype=np.double)

  return featuresEntry
Exemple #7
0
def momentum_aftr_boost(df, args):  #args must have 4 elements xyzt or pxpypzE
    px, py, pz = getXYZ(df, args)
    E = DfToNp(df[[args[3]]].dropna(axis=0))
    l = TLorentzVector()
    with np.nditer([px, py, pz, E, None, None, None, None]) as it:
        for pi, pj, pk, el, pm, pn, po, eq in it:
            l.SetPxPyPzE(pi, pj, pk, el)
            bi = pi / el
            l.Boost(-bi, 0, 0)
            pm[...] = l.Px()
            pn[...] = l.Py()
            po[...] = l.Pz()
            eq[...] = l.E()
        return (it.operands[4], it.operands[5], it.operands[6], it.operands[7])
Exemple #8
0
def boost(df, args):  #args must have 4 elements xyzt or pxpypzE
    px, py, pz = getXYZ(df, args)
    E = DfToNp(df[[args[3]]].dropna(axis=0))
    l = TLorentzVector()
    with np.nditer([px, py, pz, E, None, None, None, None]) as it:
        for pi, pj, pk, el, pm, en, phi, cost in it:
            l.SetPxPyPzE(pi, pj, pk, el)
            bi = pi / el
            bj = pj / el
            bk = pk / el
            l.Boost(-bi, -bj, -bk)
            pm[...] = l.Px()
            en[...] = l.E()
            phi[...] = l.Phi()
            cost[...] = l.CosTheta()
        return (it.operands[4], it.operands[5], it.operands[6], it.operands[7])
Exemple #9
0
 def GeneratePrimaries(self, anEvent):
     global debug, nevTot
     t_0 = time.time()
     npart = 0
     while npart == 0:
         myPythia.GenerateEvent()
         nevTot += 1
         myTimer['pythia'] += time.time() - t_0
         # pythia interaction happens at 0,0,0
         #x = rnr.Uniform(-3.,3.)
         #y = rnr.Uniform(-3.,3.)
         # leave this smearing for later
         # create new primaries and set them to the vertex
         particles = myPythia.GetListOfParticles()
         z = rnr.Exp(10 * cm) - 50. * m  # tungsten interaction length
         ztarget = G4ThreeVector(0 * cm, 0 * cm, z)
         vertex = G4PrimaryVertex(ztarget, 0.)
         v = TLorentzVector()
         for p in particles:
             if p.GetStatusCode() != 1: continue
             pid = p.GetPdgCode()
             if tauOnly and abs(pid) != 16: continue
             mkey = p.GetMother(0) + 1
             mother = myPythia.GetParticle(mkey)
             if JpsiMainly and abs(
                     pid) != 13 and mother.GetPdgCode() != 443:
                 continue
             qed = pid in qedlist  # use cut only for photons, leptons/neutrinos, protons and neutrons
             p.Momentum(v)
             Ekin = (v.E() - v.M())
             if Ekin * GeV < ecut and (qed or allPart): continue
             G4particle = G4PrimaryParticle(pid)
             G4particle.Set4Momentum(v.Px() * GeV,
                                     v.Py() * GeV,
                                     v.Pz() * GeV,
                                     v.E() * GeV)
             # store mother ID
             curPid = p.GetPdgCode() + 10000  # make it positive
             moPid = mother.GetPdgCode() + 10000
             w = curPid + moPid * 100000
             G4particle.SetWeight(w)
             vertex.SetPrimary(G4particle)
             npart += 1
     # if debug: myPythia.EventListing()
     anEvent.AddPrimaryVertex(vertex)
     if debug: print 'new event at ', ztarget.z / m
     myTimer['geant4_conv'] += time.time() - t_0
def Boosted_Angle(pt1, eta1, phi1, pt2, eta2, phi2, ptz, etaz, phiz, mass):
    mu1 = TLorentzVector()
    mu2 = TLorentzVector()
    zb = TLorentzVector()
    mu1.SetPtEtaPhiM(pt1, eta1, phi1, 0)
    mu2.SetPtEtaPhiM(pt2, eta2, phi2, 0)
    angle = mu1.Angle(mu2.Vect())
    zb.SetPtEtaPhiM(ptz, etaz, phiz, mass)
    angle_Z1 = zb.Angle(mu1.Vect())
    angle_Z2 = zb.Angle(mu2.Vect())
    mu1.Boost(-zb.Px() / zb.E(), -zb.Py() / zb.E(), -zb.Pz() / zb.E())
    mu2.Boost(-zb.Px() / zb.E(), -zb.Py() / zb.E(), -zb.Pz() / zb.E())
    angleBoost = mu1.Angle(mu2.Vect())
    angleBoost_Z1 = zb.Angle(mu1.Vect())
    angleBoost_Z2 = zb.Angle(mu2.Vect())
    #print "******&&&&******", angle, angleBoost
    return [angleBoost, angle, angleBoost_Z1, angle_Z1, angle_Z2]
Exemple #11
0
 def GeneratePrimaries(self, anEvent):
     global debug, nevTot
     t_0 = time.time()
     npart = 0
     while npart == 0:
         myPythia.GenerateEvent()
         nevTot += 1
         myTimer['pythia'] += time.time() - t_0
         # pythia interaction happens at 0,0,0
         #x = rnr.Uniform(-3.,3.)
         #y = rnr.Uniform(-3.,3.)
         # leave this smearing for later
         pos = G4ThreeVector(0 * cm, 0 * cm, -50 * m)
         vertex = G4PrimaryVertex(pos, 0.)
         # create new primaries and set them to the vertex
         particles = myPythia.GetListOfParticles()
         for p in particles:
             if p.GetStatusCode() != 1: continue
             pid = p.GetPdgCode()
             if tauOnly and abs(pid) != 16: continue
             if pid in notWanted: continue
             G4particle = G4PrimaryParticle(pid)
             v = TLorentzVector()
             p.Momentum(v)
             if v.E() * GeV < ecut: continue
             G4particle.Set4Momentum(v.Px() * GeV,
                                     v.Py() * GeV,
                                     v.Pz() * GeV,
                                     v.E() * GeV)
             vertex.SetPrimary(G4particle)
             # store mother ID
             mkey = p.GetMother(0) + 1
             mother = myPythia.GetParticle(mkey)
             curPid = p.GetPdgCode() + 10000  # make it positive
             moPid = mother.GetPdgCode() + 10000
             w = curPid + moPid * 100000
             G4particle.SetWeight(w)
             npart += 1
     if tauOnly and debug: myPythia.EventListing()
     anEvent.AddPrimaryVertex(vertex)
     myTimer['geant4_conv'] += time.time() - t_0
Exemple #12
0
    def print_vec(self, vec):
        print "theta vec:", TMath.Pi() - vec.Theta()
        print
        return
        print "pxyz:", vec.Px(), vec.Py(), vec.Pz()
        print "en, phi:", vec.E(), vec.Phi()
        print
        v3 = vec.Vect()
        print "vxyz:", v3.x(), v3.y(), v3.z()
        print "theta v3: ", TMath.Pi() - v3.Theta()
        print
        theta_add = 1e-5
        v3.SetTheta(v3.Theta() - theta_add)
        print "vxyz:", v3.x(), v3.y(), v3.z()
        print "theta v3: ", TMath.Pi() - v3.Theta()
        print

        vec2 = TLorentzVector(vec)
        vec3 = TLorentzVector(vec)

        vec.SetVect(v3)

        print "theta vec:", TMath.Pi() - vec.Theta()
        print "pxyz:", vec.Px(), vec.Py(), vec.Pz()
        print "en, phi:", vec.E(), vec.Phi()
        print

        vec2.SetTheta(vec2.Theta() - theta_add)

        print "theta vec:", TMath.Pi() - vec2.Theta()
        print "pxyz:", vec2.Px(), vec2.Py(), vec2.Pz()
        print "en, phi:", vec2.E(), vec2.Phi()
        print

        print "Delta theta, en, phi", vec3.Theta() - vec.Theta(), vec3.E(
        ) - vec.E(), vec3.Phi() - vec.Phi()
        print "Delta theta, en, phi", vec3.Theta() - vec2.Theta(), vec3.E(
        ) - vec2.E(), vec3.Phi() - vec2.Phi()
Exemple #13
0
def PruneGenr8File(fname_in,
                   fname_out,
                   E_GAMMA_VARY,
                   MIN_VAL,
                   MAX_VAL,
                   NACCEPTED,
                   MAX_EVENTS,
                   verbose=False):
    # print "input genr8 file: " + fname_in
    # print "output file: " + fname_out

    counter = 1

    line1_out = ""  #Run and event info
    line2_out = "1 1 0.000000\n"  #Gamma ID info
    line3_out = ""  #Gamma P4 info

    for line in open(fname_in, 'r'):

        if (NACCEPTED >= MAX_EVENTS):
            # print "Done generating this point!"
            break

        if (counter % 11 == 1):  #Event info
            value_in_line = 1
            run = ""
            event = ""
            for value in line.split():
                if (value_in_line == 1): run = value
                if (value_in_line == 2): event = value
                if (verbose and value_in_line == 1): print "Run " + value
                if (verbose and value_in_line == 2): print "Event " + value
                if (verbose and value_in_line == 3):
                    print "NParticles " + value
                value_in_line += 1
                # line1_out = run + " " + event + " " + "1\n"
                line1_out = run + " " + str(NACCEPTED + 1) + " " + "1\n"
        if (counter % 11 == 2):  #Gamma1 info
            value_in_line = 1
            for value in line.split():
                if (verbose and value_in_line == 1):
                    print "Particle number in event: " + value
                if (verbose and value_in_line == 2):
                    print "Particle enum value " + value
                if (verbose and value_in_line == 3):
                    print "Particle mass " + value
                value_in_line += 1
        if (counter % 11 == 3):  #Gamma1 p4
            value_in_line = 1
            p4_string = line.split()
            p4_gam1 = TLorentzVector(float(p4_string[1]), float(p4_string[2]),
                                     float(p4_string[3]), float(p4_string[4]))
            for value in line.split():
                if (verbose and value_in_line == 1): print "Charge: " + value
                if (verbose and value_in_line == 2): print "Px " + value
                if (verbose and value_in_line == 3): print "Py " + value
                if (verbose and value_in_line == 4): print "Pz " + value
                if (verbose and value_in_line == 5): print "E " + value
                value_in_line += 1
        if (counter % 11 == 4):  #Gamma2 info
            value_in_line = 1
            for value in line.split():
                if (verbose and value_in_line == 1):
                    print "Particle number in event: " + value
                if (verbose and value_in_line == 2):
                    print "Particle enum value " + value
                if (verbose and value_in_line == 3):
                    print "Particle mass " + value
                value_in_line += 1
        if (counter % 11 == 5):  #Gamma2 p4
            value_in_line = 1
            p4_string = line.split()
            p4_gam2 = TLorentzVector(float(p4_string[1]), float(p4_string[2]),
                                     float(p4_string[3]), float(p4_string[4]))
            for value in line.split():
                if (verbose and value_in_line == 1): print "Charge: " + value
                if (verbose and value_in_line == 2): print "Px " + value
                if (verbose and value_in_line == 3): print "Py " + value
                if (verbose and value_in_line == 4): print "Pz " + value
                if (verbose and value_in_line == 5): print "E " + value
                value_in_line += 1
        if (counter % 11 == 6):  #Pi+ info
            value_in_line = 1
            for value in line.split():
                if (verbose and value_in_line == 1):
                    print "Particle number in event: " + value
                if (verbose and value_in_line == 2):
                    print "Particle enum value " + value
                if (verbose and value_in_line == 3):
                    print "Particle mass " + value
                value_in_line += 1
        if (counter % 11 == 7):  #Pi+ p4
            value_in_line = 1
            for value in line.split():
                if (verbose and value_in_line == 1): print "Charge: " + value
                if (verbose and value_in_line == 2): print "Px " + value
                if (verbose and value_in_line == 3): print "Py " + value
                if (verbose and value_in_line == 4): print "Pz " + value
                if (verbose and value_in_line == 5): print "E " + value
                value_in_line += 1
        if (counter % 11 == 8):  #Pi- info
            value_in_line = 1
            for value in line.split():
                if (verbose and value_in_line == 1):
                    print "Particle number in event: " + value
                if (verbose and value_in_line == 2):
                    print "Particle enum value " + value
                if (verbose and value_in_line == 3):
                    print "Particle mass " + value
                value_in_line += 1
        if (counter % 11 == 9):  #Pi- p4
            value_in_line = 1
            for value in line.split():
                if (verbose and value_in_line == 1): print "Charge: " + value
                if (verbose and value_in_line == 2): print "Px " + value
                if (verbose and value_in_line == 3): print "Py " + value
                if (verbose and value_in_line == 4): print "Pz " + value
                if (verbose and value_in_line == 5): print "E " + value
                value_in_line += 1
        if (counter % 11 == 10):  #proton info
            value_in_line = 1
            for value in line.split():
                if (verbose and value_in_line == 1):
                    print "Particle number in event: " + value
                if (verbose and value_in_line == 2):
                    print "Particle enum value " + value
                if (verbose and value_in_line == 3):
                    print "Particle mass " + value
                value_in_line += 1
        if (counter % 11 == 0):  #proton p4
            value_in_line = 1
            for value in line.split():
                if (verbose and value_in_line == 1): print "Charge: " + value
                if (verbose and value_in_line == 2): print "Px " + value
                if (verbose and value_in_line == 3): print "Py " + value
                if (verbose and value_in_line == 4): print "Pz " + value
                if (verbose and value_in_line == 5): print "E " + value
                value_in_line += 1

            #Finished with this event. Check if one of the two photons passes cuts.
            #If so, save event and increment NACCEPTED
            if (verbose):
                print "Cut on energy? " + str(E_GAMMA_VARY)
                print "Cut on theta? " + str(not E_GAMMA_VARY)
                print "Min value: " + str(MIN_VAL)
                print "Max value: " + str(MAX_VAL)
                print "Gamma1 energy: " + str(p4_gam1.E())
                print "Gamma2 energy: " + str(p4_gam2.E())

            GAMMA1_PASSES = False
            if (E_GAMMA_VARY and MIN_VAL < p4_gam1.E()
                    and p4_gam1.E() < MAX_VAL
                    and p4_gam2.E() > E_SPECTATOR_MIN):
                GAMMA1_PASSES = True
            if (not E_GAMMA_VARY and MIN_VAL < p4_gam1.Theta() * 180 / 3.14159
                    and p4_gam1.Theta() * 180 / 3.14159 < MAX_VAL):
                GAMMA1_PASSES = True
            if (verbose and GAMMA1_PASSES):
                print "Gamma1 passes: "
                print "Min value: " + str(MIN_VAL)
                print "Max value: " + str(MAX_VAL)
                print "Gamma1 energy: " + str(p4_gam1.E())
            if (GAMMA1_PASSES):
                with open(fname_out, "a") as myfile:
                    line3_out = "   0 " + str(p4_gam1.Px()) + " " + str(
                        p4_gam1.Py()) + " " + str(p4_gam1.Pz()) + " " + str(
                            p4_gam1.E()) + "\n"
                    myfile.write(line1_out)
                    myfile.write(line2_out)
                    myfile.write(line3_out)
                    NACCEPTED += 1

            GAMMA2_PASSES = False
            if (E_GAMMA_VARY and MIN_VAL < p4_gam2.E()
                    and p4_gam2.E() < MAX_VAL
                    and p4_gam1.E() > E_SPECTATOR_MIN):
                GAMMA2_PASSES = True
            if (not E_GAMMA_VARY and MIN_VAL < p4_gam2.Theta() * 180 / 3.14159
                    and p4_gam2.Theta() * 180 / 3.14159 < MAX_VAL):
                GAMMA2_PASSES = True
            if (verbose and GAMMA2_PASSES):
                print "Gamma2 passes: "
                print "Min value: " + str(MIN_VAL)
                print "Max value: " + str(MAX_VAL)
                print "Gamma2 energy: " + str(p4_gam2.E())
            if (GAMMA2_PASSES):
                with open(fname_out, "a") as myfile:
                    line3_out = "   0 " + str(p4_gam2.Px()) + " " + str(
                        p4_gam2.Py()) + " " + str(p4_gam2.Pz()) + " " + str(
                            p4_gam2.E()) + "\n"
                    myfile.write(line1_out)
                    myfile.write(line2_out)
                    myfile.write(line3_out)
                    NACCEPTED += 1

            if (verbose):
                print "\n"

            # with open(fname_out, "a") as myfile:
            # myfile.write(line1_out)
            # myfile.write(line2_out)

        counter += 1

        # if(counter>200): break

    return NACCEPTED
Exemple #14
0
class particle:
    #_____________________________________________________________________________
    def __init__(self, pdg):
        #particle Lorentz vector
        self.vec = TLorentzVector()
        #index in particle list
        self.idx = 0
        #status code
        self.stat = 0
        #pdg code
        self.pdg = pdg
        #particle database for pass and codes
        self.pdgdat = TDatabasePDG.Instance()
        #mass, GeV
        self.mass = self.pdgdat.GetParticle(self.pdg).Mass()
        #parent particle id
        self.parent_id = 0
        #vertex coordinates, mm
        self.vx = 0.
        self.vy = 0.
        self.vz = 0.
        #precision for momentum and energy
        self.pxyze_prec = 6


    #_____________________________________________________________________________
    def write(self, out):
        #put event output line
        #index, status and pdg
        out.write("{0:10d}{1:11d}{2:11d}".format(self.idx, self.stat, self.pdg))
        #parent particle id
        out.write("{0:11d}".format(self.parent_id))
        #placeholder for daughter indices
        out.write("          0          0")
        #px, py, pz, energy
        pxyze_form = "{0:16."+str(self.pxyze_prec)+"f}"
        out.write( pxyze_form.format( self.vec.Px() ) )
        out.write( pxyze_form.format( self.vec.Py() ) )
        out.write( pxyze_form.format( self.vec.Pz() ) )
        out.write( pxyze_form.format( self.vec.E() ) )
        #mass
        out.write( "{0:16.6f}".format(self.mass) )
        #out.write("        0.000000")
        #vertex
        out.write( "{0:16.6f}".format(self.vx) )
        out.write( "{0:16.6f}".format(self.vy) )
        out.write( "{0:16.6f}".format(self.vz) )
        #end of line
        out.write("\n")

    #_____________________________________________________________________________
    def write_tx(self, track_list):

        #output line in TX format

        #Geant code and momentum
        lin = "TRACK:  "+str(self.pdgdat.ConvertPdgToGeant3(self.pdg))
        pxyz_form = " {0:."+str(self.pxyze_prec)+"f}"
        lin += pxyz_form.format( self.vec.Px() )
        lin += pxyz_form.format( self.vec.Py() )
        lin += pxyz_form.format( self.vec.Pz() )

        #track id
        lin += " " + str(len(track_list))

        #start and stop vertex and pdg
        lin += " 1 0 " + str(self.pdg)

        track_list.append(lin)

    #_____________________________________________________________________________
    def write_tparticle(self, particles, ipos):

        #write to TParticle clones array

        p = particles.ConstructedAt(ipos)

        p.SetMomentum(self.vec)
        p.SetPdgCode(self.pdg)
        p.SetProductionVertex(self.vx, self.vy, self.vz, 0)
Exemple #15
0
def PruneGenr8File(fname_in,
                   fname_out,
                   e_gamma_curr,
                   theta_curr,
                   verbose=False):

    # print "directory: " + os.getcwd()
    # print "input genr8 file: " + fname_in
    # print "output file: " + fname_out

    counter = 1

    line1_out = ""  #Run and event info
    line2_out = ""  #Gamma ID info
    line3_out = ""  #Gamma P4 info
    line4_out = ""  #Proton ID info
    line5_out = ""  #Proton P4 info
    line6_out = ""  #Pi+ ID info
    line7_out = ""  #Pi+ P4 info
    line8_out = ""  #Pi- ID info
    line9_out = ""  #Pi- P4 info

    rand = TRandom3(int(e_gamma_curr * 1000.))
    p4_proton = TLorentzVector()
    for line in open(fname_in, 'r'):

        if (counter % 9 == 1):  #Event info
            value_in_line = 1
            run = ""
            event = ""
            for value in line.split():
                if (value_in_line == 1): run = value
                if (value_in_line == 2): event = value
                if (verbose and value_in_line == 1): print "Run " + value
                if (verbose and value_in_line == 2): print "Event " + value
                if (verbose and value_in_line == 3):
                    print "NParticles " + value
                value_in_line += 1
                line1_out = run + " " + event + " " + "4\n"
        if (counter % 9 == 2):  #Pi0 info
            value_in_line = 1
            for value in line.split():
                if (verbose and value_in_line == 1):
                    print "Particle number in event: " + value
                if (verbose and value_in_line == 2):
                    print "Particle enum value " + value
                if (verbose and value_in_line == 3):
                    print "Particle mass " + value
                value_in_line += 1
        if (counter % 9 == 3):  #Pi0 p4
            value_in_line = 1
            p4_string = line.split()
            p4_gam1 = TLorentzVector(float(p4_string[1]), float(p4_string[2]),
                                     float(p4_string[3]), float(p4_string[4]))
            for value in line.split():
                if (verbose and value_in_line == 1): print "Charge: " + value
                if (verbose and value_in_line == 2): print "Px " + value
                if (verbose and value_in_line == 3): print "Py " + value
                if (verbose and value_in_line == 4): print "Pz " + value
                if (verbose and value_in_line == 5): print "E " + value
                value_in_line += 1
        if (counter % 9 == 4):  #Pi+ info
            value_in_line = 1
            line2_str = line
            for value in line.split():
                if (verbose and value_in_line == 1):
                    print "Particle number in event: " + value
                if (verbose and value_in_line == 2):
                    print "Particle enum value " + value
                if (verbose and value_in_line == 3):
                    print "Particle mass " + value
                value_in_line += 1
                line6_out = "3 8 0.13957\n"
        if (counter % 9 == 5):  #Pi+ p4
            value_in_line = 1
            p4_string = line.split()
            p4_pipl = TLorentzVector(float(p4_string[1]), float(p4_string[2]),
                                     float(p4_string[3]), float(p4_string[4]))
            for value in line.split():
                if (verbose and value_in_line == 1): print "Charge: " + value
                if (verbose and value_in_line == 2): print "Px " + value
                if (verbose and value_in_line == 3): print "Py " + value
                if (verbose and value_in_line == 4): print "Pz " + value
                if (verbose and value_in_line == 5): print "E " + value
                value_in_line += 1
            line7_out = "   1 " + str(p4_pipl.Px()) + " " + str(
                p4_pipl.Py()) + " " + str(p4_pipl.Pz()) + " " + str(
                    p4_pipl.E()) + "\n"
        if (counter % 9 == 6):  #Pi- info
            value_in_line = 1
            for value in line.split():
                if (verbose and value_in_line == 1):
                    print "Particle number in event: " + value
                if (verbose and value_in_line == 2):
                    print "Particle enum value " + value
                if (verbose and value_in_line == 3):
                    print "Particle mass " + value
                value_in_line += 1
                line8_out = "4 9 0.13957\n"
        if (counter % 9 == 7):  #Pi- p4
            value_in_line = 1
            p4_string = line.split()
            p4_pim = TLorentzVector(float(p4_string[1]), float(p4_string[2]),
                                    float(p4_string[3]), float(p4_string[4]))
            for value in line.split():
                if (verbose and value_in_line == 1): print "Charge: " + value
                if (verbose and value_in_line == 2): print "Px " + value
                if (verbose and value_in_line == 3): print "Py " + value
                if (verbose and value_in_line == 4): print "Pz " + value
                if (verbose and value_in_line == 5): print "E " + value
                value_in_line += 1
            line9_out = "   -1 " + str(p4_pim.Px()) + " " + str(
                p4_pim.Py()) + " " + str(p4_pim.Pz()) + " " + str(
                    p4_pim.E()) + "\n"
        if (counter % 9 == 8):  #proton info
            value_in_line = 1
            for value in line.split():
                if (verbose and value_in_line == 1):
                    print "Particle number in event: " + value
                if (verbose and value_in_line == 2):
                    print "Particle enum value " + value
                if (verbose and value_in_line == 3):
                    print "Particle mass " + value
                value_in_line += 1
                line4_out = "2 14 0.938272\n"
        if (counter % 9 == 0):  #proton p4
            value_in_line = 1
            p4_string = line.split()
            p4_proton = TLorentzVector(float(p4_string[1]),
                                       float(p4_string[2]),
                                       float(p4_string[3]),
                                       float(p4_string[4]))
            p4_proton_boost_px = p4_proton.Px()
            p4_proton_boost_py = p4_proton.Py()
            p4_proton_boost_pz = p4_proton.Pz()
            p4_proton_boost_E = sqrt(
                abs(p4_proton_boost_px**2 + p4_proton_boost_py**2 +
                    p4_proton_boost_pz**2 - 0.938272**2))
            p4_proton_boost = TLorentzVector(p4_proton_boost_px,
                                             p4_proton_boost_py,
                                             p4_proton_boost_pz,
                                             p4_proton_boost_E)

            for value in line.split():
                if (verbose and value_in_line == 1): print "Charge: " + value
                if (verbose and value_in_line == 2): print "Px " + value
                if (verbose and value_in_line == 3): print "Py " + value
                if (verbose and value_in_line == 4): print "Pz " + value
                if (verbose and value_in_line == 5): print "E " + value
                value_in_line += 1
                line5_out = "   1 " + str(p4_proton.Px()) + " " + str(
                    p4_proton.Py()) + " " + str(p4_proton.Pz()) + " " + str(
                        p4_proton.E()) + "\n"

            my_phi = p4_proton_boost.Phi() + 3.14159  #Opposite proton
            my_theta = theta_curr * (3.14159 / 180.)
            gamma_px = str(e_gamma_curr * TMath.Sin(my_theta) *
                           TMath.Cos(my_phi))
            gamma_py = str(e_gamma_curr * TMath.Sin(my_theta) *
                           TMath.Sin(my_phi))
            gamma_pz = str(e_gamma_curr * TMath.Cos(my_theta))
            line2_out = "1 1 0\n"
            line3_out = "   0 " + gamma_px + " " + gamma_py + " " + gamma_pz + " " + str(
                e_gamma_curr) + "\n"
            p4_gam_fcal = TLorentzVector(float(gamma_px), float(gamma_py),
                                         float(gamma_pz), e_gamma_curr)

            # print "Beam photon: " + str( (p4_gam_fcal+p4_proton_boost).E())

            with open(fname_out, "a") as myfile:
                myfile.write(line1_out)
                myfile.write(line2_out)
                myfile.write(line3_out)
                myfile.write(line4_out)
                myfile.write(line5_out)
                myfile.write(line6_out)
                myfile.write(line7_out)
                myfile.write(line8_out)
                myfile.write(line9_out)

        counter += 1

        # if(counter>200): break

    return
    0.9 * antitau_to_unrotate_info.shape[0]):, :]  #Get the last 10%!

for event in range(pred.shape[0]):
    tau_lorentz_no_neutrino = TLorentzVector()
    #    firedCount = 0
    for index in range(0, tau_features_test.shape[1], 3):
        lorentz = TLorentzVector()
        lorentz.SetPtEtaPhiM((tau_features_test[event][index]),
                             (tau_features_test[event][index + 1]),
                             (tau_features_test[event][index + 2]), (0.139))

        tau_lorentz_no_neutrino += lorentz
        print("I fired")
        #firedCount += 1
    tofill['tau_pt_no_neutrino'] = tau_lorentz_no_neutrino.Pt()
    print("tau_lorentz_neutrino.Px()", tau_lorentz_no_neutrino.Px())
    print("tau_lorentz_no_neutrino.Py()", tau_lorentz_no_neutrino.Py())
    print("tau_lorentz_no_neutrino.Pz()", tau_lorentz_no_neutrino.Pz())
    print("tau_lorentz_no_neutrino.E()", tau_lorentz_no_neutrino.E())
    tofill['tau_eta_no_neutrino'] = tau_lorentz_no_neutrino.Eta()
    tofill['tau_phi_no_neutrino'] = tau_lorentz_no_neutrino.Phi()
    tofill['tau_mass_no_neutrino'] = tau_lorentz_no_neutrino.M()
    print("tau_mass_no_neutrino", tau_lorentz_no_neutrino.M())
    print("tau_eta_no_neutrino", tau_lorentz_no_neutrino.Eta())

    tau_lorentz = TLorentzVector()
    tau_lorentz.SetPxPyPzE(
        tau_lorentz_no_neutrino.Px(),
        tau_lorentz_no_neutrino.Py(),
        tau_lorentz_no_neutrino.Pz(),
        tau_lorentz_no_neutrino.E(),
Exemple #17
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
Exemple #18
0
def jetdisplay():

    inputfile1 = "wwlj_truth.root"
    inputfile2 = "wwlj.root"

    inputfile1 = TFile(inputfile1)
    inputfile2 = TFile(inputfile2)
    print "Analyzing: " + str(inputfile1) + " \n"
    tree1 = TTree()
    tree2 = TTree()
    inputfile1.GetObject("truth", tree1)
    inputfile2.GetObject("B4", tree2)
    tree1.AddFriend(tree2)

    outputfile = "wwlj_output"
    displayfile = TFile(outputfile + ".root", "RECREATE")

    graphmass = TH1F("mass_jet", "mass_jet", 100, 0., 200.)
    graphmass_truth = TH1F("mass_jet_truth", "mass_jet_truth", 100, 0., 200.)

    #loop over events
    for Event in range(int(10)):

        tree1.GetEntry(Event)

        #Set values of the tree
        numtru = tree1.mcs_n
        print numtru

        muvec = []
        inputparticles_tru = []
        nmuon = 0
        #loop over true particles
        for itru in range(0, numtru):
            partid = tree1.mcs_pdgId[itru]

            #for particle depositing in calo, store them as input for jet building
            if abs(partid) != 13 and abs(partid) != 12 and abs(
                    partid) != 14 and abs(partid) != 16:
                trup = TLorentzVector()
                trup.SetPtEtaPhiM(tree1.mcs_pt[itru], tree1.mcs_eta[itru],
                                  tree1.mcs_phi[itru], tree1.mcs_m[itru])
                inputparticles_tru.append(
                    fastjet.PseudoJet(trup.Px(), trup.Py(), trup.Pz(),
                                      trup.E()))
            #store muons in event
            if abs(partid) == 13:
                muon = TLorentzVector()
                muon.SetPtEtaPhiM(tree1.mcs_pt[itru], tree1.mcs_eta[itru],
                                  tree1.mcs_phi[itru], tree1.mcs_m[itru])
                muvec.append(muon)
                nmuon = nmuon + 1
        print " nmuon ", nmuon

        #now build truth jets
        jet_def = fastjet.JetDefinition(fastjet.ee_genkt_algorithm,
                                        2 * math.pi, 1.)
        clust_seq = fastjet.ClusterSequence(inputparticles_tru, jet_def)
        jetexc = fastjet.sorted_by_E(clust_seq.exclusive_jets(int(2)))
        print "*********** jets ************"
        for jet in jetexc:
            print jet.e(), jet.eta(), jet.phi()
        print "*********** muons ************"
        for muon in muvec:
            print muon.E(), muon.Eta(), muon.Phi()

        jet1_truth = jetexc[0]
        jet2_truth = jetexc[1]
        j = jet1_truth + jet2_truth
        graphmass_truth.Fill(j.m())

        # now handle calo sim
        BarrelR_VectorSignals = tree2.VectorSignalsR
        BarrelL_VectorSignals = tree2.VectorSignalsL
        BarrelR_VectorSignalsCher = tree2.VectorSignalsCherR
        BarrelL_VectorSignalsCher = tree2.VectorSignalsCherL
        VectorR = tree2.VectorR
        VectorL = tree2.VectorL

        Calib_BarrelL_VectorSignals = calibration.calibscin(
            BarrelL_VectorSignals)
        Calib_BarrelR_VectorSignals = calibration.calibscin(
            BarrelR_VectorSignals)
        Calib_BarrelL_VectorSignalsCher = calibration.calibcher(
            BarrelL_VectorSignalsCher)
        Calib_BarrelR_VectorSignalsCher = calibration.calibcher(
            BarrelR_VectorSignalsCher)

        energy = float(
            sum(Calib_BarrelR_VectorSignals) +
            sum(Calib_BarrelL_VectorSignals))
        print " simulated energy ", energy
        if (energy > 0):
            threshold = 0.1
            inputparticles_scin = []
            inputparticles_cher = []

            #right part
            for towerindex in range(75 * 36):
                theta, phi, eta = newmap_truth.maptower(towerindex, "right")
                energy_scin = Calib_BarrelR_VectorSignals[towerindex]
                pt_scin = energy_scin * np.sin(theta * math.pi / 180.)

                energy_cher = Calib_BarrelR_VectorSignalsCher[towerindex]
                pt_cher = energy_cher * np.sin(theta * math.pi / 180.)

                towerscin = TLorentzVector()
                towerscin.SetPtEtaPhiM(pt_scin, eta, phi * math.pi / 180., 0.)
                towercher = TLorentzVector()
                towercher.SetPtEtaPhiM(pt_cher, eta, phi * math.pi / 180., 0.)
                deltamumin = 999999.
                for muon in muvec:
                    deltaR = abs(towerscin.DeltaR(muon))
                    if deltaR < deltamumin:
                        deltamumin = deltaR
                if energy_scin > threshold:
                    if deltamumin < 0.1:
                        print " deltamumin ", deltamumin
                    if deltamumin > 0.1:
                        inputparticles_scin.append(
                            fastjet.PseudoJet(towerscin.Px(), towerscin.Py(),
                                              towerscin.Pz(), towerscin.E()))
                        inputparticles_cher.append(
                            fastjet.PseudoJet(towercher.Px(), towercher.Py(),
                                              towercher.Pz(), towercher.E()))

            #left part
            for towerindex in range(75 * 36):
                theta, phi, eta = newmap_truth.maptower(towerindex, "left")
                energy_scin = Calib_BarrelL_VectorSignals[towerindex]
                pt_scin = energy_scin * np.sin(theta * math.pi / 180.)

                energy_cher = Calib_BarrelL_VectorSignalsCher[towerindex]
                pt_cher = energy_cher * np.sin(theta * math.pi / 180.)

                towerscin = TLorentzVector()
                towerscin.SetPtEtaPhiM(pt_scin, eta, phi * math.pi / 180., 0.)
                towercher = TLorentzVector()
                towercher.SetPtEtaPhiM(pt_cher, eta, phi * math.pi / 180., 0.)
                deltamumin = 999999.
                for muon in muvec:
                    deltaR = abs(towerscin.DeltaR(muon))
                    if deltaR < deltamumin:
                        deltamumin = deltaR
                if energy_scin > threshold:
                    if deltamumin < 0.1:
                        print " deltamumin ", deltamumin
                    if deltamumin > 0.1:
                        inputparticles_scin.append(
                            fastjet.PseudoJet(towerscin.Px(), towerscin.Py(),
                                              towerscin.Pz(), towerscin.E()))
                        inputparticles_cher.append(
                            fastjet.PseudoJet(towercher.Px(), towercher.Py(),
                                              towercher.Pz(), towercher.E()))

        print "len: ", len(inputparticles_scin)
        print "lencher: ", len(inputparticles_cher)

        jet_def = fastjet.JetDefinition(fastjet.ee_genkt_algorithm,
                                        2 * math.pi, 1.)

        clust_seq = fastjet.ClusterSequence(inputparticles_scin, jet_def)
        clust_seq_cher = fastjet.ClusterSequence(inputparticles_cher, jet_def)

        print "n jet: ", len(clust_seq.exclusive_jets(int(2))), len(
            clust_seq_cher.exclusive_jets(int(2)))
        jet1_scin = clust_seq.exclusive_jets(int(2))[0]
        jet2_scin = clust_seq.exclusive_jets(int(2))[1]

        jet1_cher = clust_seq_cher.exclusive_jets(int(2))[0]
        jet2_cher = clust_seq_cher.exclusive_jets(int(2))[1]

        #merge jet
        jet1, jet2 = mergejet(jet1_scin, jet2_scin, jet1_cher, jet2_cher)
        jet = jet1 + jet2
        graphmass.Fill(jet.m())
    graphmass.Write()
    graphmass_truth.Write()
Exemple #19
0
    tmp_unrotated_Px = tmp_unrotated_PxPyPz_vec[0]
    tmp_unrotated_Py = tmp_unrotated_PxPyPz_vec[1]
    tmp_unrotated_Pz = tmp_unrotated_PxPyPz_vec[2]

    Global_4vec = ROOT.TLorentzVector()
    Global_4vec.SetPxPyPzE(tmp_unrotated_Px, tmp_unrotated_Py,
                           tmp_unrotated_Pz, tmp_E)

    return Global_4vec


##### test #####

v = TLorentzVector()
v.SetPxPyPzE(-3.6740152498, -2.79192430698, 21.6557548444, 22.1777103583)
print "Px,Py,Pz,E,M:", v.Px(), v.Py(), v.Pz(), v.E(), v.M()
print "tau_orig_theta, tau_orig_phi:", v.Theta(), v.Phi()
tau_orig_theta_test = v.Theta()
tau_orig_phi_test = v.Phi()

toPrint = rotateToVisTauMomPointsInEtaEqualsZero(tau_orig_theta_test,
                                                 tau_orig_phi_test, v)
#
print toPrint

newPx = toPrint.Px()
newPy = toPrint.Py()
newPz = toPrint.Pz()
newE = toPrint.E()
newM = toPrint.M()
newTheta = toPrint.Theta()
Exemple #20
0
            MinPtRatio[0] = min( (l1+l2).Pt(), (q1+q2).Pt() ) / (l1+l2+q1+q2).M() 
            SqrtSSPt[0] = -99.
            nbtag[0] = nb
            nbtagInFatjet[0] = nb

        #Es *= Heaviside(np.sqrt((l1+l2).Pt()**2+(q1+q2).Pt()**2)/(l1+l2+q1+q2).M()-0.4)
        #Es *= Heaviside(105e+3-(q1+q2).M())
        #Es *= Heaviside((q1+q2).M()-70e+3)
        
        # Invariant mass of Z1 and Z2
        Mll[0] = (l1 + l2).M()
        Mjj[0] = (q1 + q2).M()
        Mlljj[0] = (l1 + l2 + q1 + q2).M()

        # Boost to X's static system
        l_X = TLorentzRotation().Boost(-1.*X.Px()/X.E(), -1.*X.Py()/X.E(), -1.*X.Pz()/X.E())
        X = l_X * X;
        Z1 = l_X * Zll;
        Z2 = l_X * Zjj;
        l1 = l_X * l1;
        l2 = l_X * l2;
        q1 = l_X * q1;
        q2 = l_X * q2;
    
        # Boost to Z1's static system
        l_Z1 = TLorentzRotation().Boost(-1.*Z1.Px()/Z1.E(), -1.*Z1.Py()/Z1.E(), -1.*Z1.Pz()/Z1.E())
        Z1_Z1SS = l_Z1 * Z1
        Z2_Z1SS = l_Z1 * Z2
        l1_Z1SS = l_Z1 * l1
        l2_Z1SS = l_Z1 * l2
        
        v_jet = TLorentzVector()
        pv2sv = TVector3()

        njet = 0
        for ievt in range(jet_njets.shape[0]):
            for ijet in range(jet_njets[ievt]):

                v_jet.SetPtEtaPhiM(jet_pt[ijet], jet_eta[ijet], jet_phi[ijet],
                                   jet_m[ijet])

                if jet_sv1_vtx_x_raw[ievt][ijet].shape[0] == 1:
                    dx = jet_sv1_vtx_x_raw[ievt][ijet][0] - PVx[ievt]
                    dy = jet_sv1_vtx_y_raw[ievt][ijet][0] - PVy[ievt]
                    dz = jet_sv1_vtx_z_raw[ievt][ijet][0] - PVz[ievt]
                    pv2sv.SetXYZ(dx, dy, dz)
                    jetAxis = TVector3(v_jet.Px(), v_jet.Py(), v_jet.Pz())

                    jet_sv1_L3d[ijet + njet] = sqrt(dx**2 + dy**2 + dz**2)
                    jet_sv1_Lxy[ijet + njet] = sqrt(dx**2 + dy**2)
                    jet_sv1_dR[ijet + njet] = pv2sv.DeltaR(jetAxis)

                else:
                    jet_sv1_L3d[ijet + njet] = -100
                    jet_sv1_Lxy[ijet + njet] = -100
                    jet_sv1_dR[ijet + njet] = -1

            njet += jet_njets[ievt]

        print "jet_sv1_l3d", jet_sv1_L3d
        print "jet_sv1_lxy", jet_sv1_Lxy
        print "jet_sv1_dR", jet_sv1_dR
        print "Higgs"

    # No higgs event
    else:
        #print "No Higgs!"
        for pin in range(0, branchParticle.GetEntriesFast()):
            #for pin in range(0, 20):
            part = branchParticle.At(pin)
            if (abs(part.PID) == 24 and part.Status == 22):
                wpart.SetPtEtaPhiE(part.PT, part.Eta, part.Phi, part.E)

    for etrenrty in range(0, branchTrack.GetEntriesFast()):
        eterm = branchTrack.At(etrenrty)
        temp.SetPtEtaPhiE(eterm.PT, eterm.Eta, eterm.Phi,
                          eterm.PT * np.cosh(eterm.Eta))
        vectors.append((temp.E(), temp.Px(), temp.Py(), temp.Pz()))

    for pentry in range(0, branchPhoton.GetEntriesFast()):
        pterm = branchPhoton.At(pentry)
        temp.SetPtEtaPhiE(pterm.ET, pterm.Eta, pterm.Phi, pterm.E)
        vectors.append((temp.E(), temp.Px(), temp.Py(), temp.Pz()))

    for nentry in range(0, branchNeutral.GetEntriesFast()):
        nterm = branchNeutral.At(nentry)
        temp.SetPtEtaPhiE(nterm.ET, nterm.Eta, nterm.Phi, nterm.E)
        vectors.append((temp.E(), temp.Px(), temp.Py(), temp.Pz()))

    vects = np.asarray(vectors,
                       dtype=np.dtype([('E', 'f8'), ('px', 'f8'), ('py', 'f8'),
                                       ('pz', 'f8')]))
        G *= Heaviside(4.5 - abs(q2.Eta()))
        G *= Heaviside(q1.Pt() - 30.0e+3)
        G *= Heaviside(q2.Pt() - 30.0e+3)

        if G > 0:

            # Invariant mass of Z1 and Z2
            mll[0] = (l1 + l2).M()
            mqq[0] = (q1 + q2).M()
            mZZ[0] = (l1 + l2 + q1 + q2).M()
            PtZZ[0] = (l1 + l2 + q1 + q2).Pt()
            Ptll[0] = (l1 + l2).Pt()
            Ptqq[0] = (q1 + q2).Pt()

            # Boost to X's static system
            l_X = TLorentzRotation().Boost(-1. * X.Px() / X.E(),
                                           -1. * X.Py() / X.E(),
                                           -1. * X.Pz() / X.E())
            X = l_X * X
            Z1 = l_X * Z1
            Z2 = l_X * Z2
            l1 = l_X * l1
            l2 = l_X * l2
            q1 = l_X * q1
            q2 = l_X * q2

            # Boost to Z1's static system
            l_Z1 = TLorentzRotation().Boost(-1. * Z1.Px() / Z1.E(),
                                            -1. * Z1.Py() / Z1.E(),
                                            -1. * Z1.Pz() / Z1.E())
            Z1_Z1SS = l_Z1 * Z1
            if posMu1 < 0: posMu1 = imu

    ## Skip events without a +/- charge pair
    if posMu1 < 0 or negMu1 < 0: continue

    ## Fill these chosen muons into the TLorentzVectors
    posMuon1.SetPtEtaPhiM(t.Muon_pt[posMu1], t.Muon_eta[posMu1],
                          t.Muon_phi[posMu1], t.Muon_mass[posMu1])
    negMuon1.SetPtEtaPhiM(t.Muon_pt[negMu1], t.Muon_eta[negMu1],
                          t.Muon_phi[negMu1], t.Muon_mass[negMu1])

    ## Create a list of physics quantities
    allmuons = [
        posMuon1.E(),
        negMuon1.E(),
        posMuon1.Px(),
        negMuon1.Px(),
        posMuon1.Py(),
        negMuon1.Py(),
        posMuon1.Pz(),
        negMuon1.Pz()
    ]

    ## Test it! This is just for you
    Z = posMuon1 + negMuon1
    hist.Fill(Z.M())

    ## Store this event's information into the text file
    textfile.write(str(allmuons)[1:-2] + '\n')

    ## Store this event's information into the data object
Exemple #25
0
class particle:
    #_____________________________________________________________________________
    def __init__(self, pdg):
        #particle Lorentz vector
        self.vec = TLorentzVector()
        #index in particle list
        self.idx = 0
        #status code
        self.stat = 0
        #pdg code
        self.pdg = pdg
        #particle database for pass and codes
        self.pdgdat = TDatabasePDG.Instance()
        #mass, GeV
        self.mass = self.pdgdat.GetParticle(self.pdg).Mass()
        #parent particle id
        self.parent_id = 0
        #vertex coordinates, mm
        self.vx = 0.
        self.vy = 0.
        self.vz = 0.
        #precision for momentum and energy
        self.pxyze_prec = 6

    #_____________________________________________________________________________
    def write_tx(self, track_list):

        #output line in TX format

        #Geant code and momentum
        lin = "TRACK:  " + str(self.pdgdat.ConvertPdgToGeant3(self.pdg))
        pxyz_form = " {0:." + str(self.pxyze_prec) + "f}"
        lin += pxyz_form.format(self.vec.Px())
        lin += pxyz_form.format(self.vec.Py())
        lin += pxyz_form.format(self.vec.Pz())

        #track id
        lin += " " + str(len(track_list))

        #start and stop vertex and pdg
        lin += " 1 0 " + str(self.pdg)

        track_list.append(lin)

    #_____________________________________________________________________________
    def write_tparticle(self, particles, ipos):

        #write to TParticle clones array

        p = particles.ConstructedAt(ipos)

        p.SetMomentum(self.vec)
        p.SetPdgCode(self.pdg)
        p.SetProductionVertex(self.vx, self.vy, self.vz, 0)

    #_____________________________________________________________________________
    def make_hepmc_particle(self, hepmc):

        #create HepMC3 particle

        p = hepmc.GenParticle(
            hepmc.FourVector(self.vec.Px(), self.vec.Py(), self.vec.Pz(),
                             self.vec.E()), self.pdg, 1)

        return p
Exemple #26
0
    #  print len(_jetPt)
    if ((len(_lPt) != 0) & (len(_jetPt) != 0)):
        total_entries1 = total_entries1 + 1
        qt_l = TLorentzVector(0, 0, 0, 0)
        for i in range(0, len(_lPt)):
            qt_l1 = TLorentzVector(0, 0, 0, 0)
            qt_l1.SetPtEtaPhiE(_lPt[i], _lEta[i], _lPhi[i], _lenergy[i])
            qt_l += qt_l1
        qt_jet = TLorentzVector(0, 0, 0, 0)
        for i in range(0, len(_jetPt)):
            qt_jet1 = TLorentzVector(0, 0, 0, 0)
            qt_jet1.SetPtEtaPhiE(_jetPt[i], _jetEta[i], _jetPhi[i],
                                 _jetenergy[i])
            qt_jet += qt_jet1

        qt_l_x = qt_l.Px()
        qt_l_y = qt_l.Py()
        qt_jet_x = qt_jet.Px()
        qt_jet_y = qt_jet.Py()
        qt_dot = qt_l_x * qt_jet_x + qt_l_y * qt_jet_y
        up = qt_dot / (qt_l.Pt())

        h_qt_qt.Fill(abs(qt_l.Pt()), abs(qt_l.Pt()))
        h_qt_up.Fill(abs(qt_l.Pt()), abs(up))

        test = abs(qt_l.Pt())
        print "#########"
        print test
        print "-----"
        print up
        print "#########"
Exemple #27
0
        taup_tofill['pi_plus2_normpt'] = pi_p_lv2.Pt() / ptTot
        taup_tofill['pi_plus3_normpt'] = pi_p_lv3.Pt() / ptTot
        
        taup_tofill['ignore_branch'] = taup_lv.M()
        taup_ntuple.Fill(array('f',taup_tofill.values()))
        """
    

    if tag_upsilon:
        print 'Found Upsilon -> tau+ tau- -> pi+*3 pi-*3'
        
        tofill = OrderedDict(zip(branches, [-99.] * len(branches)))

        upsilon_lv = neu_lv + antineu_lv + pi_m_lv1 + pi_m_lv2 + pi_m_lv3 + pi_p_lv1 + pi_p_lv2 + pi_p_lv3
        
        tofill['taup_neu_px'] = antineu_lv.Px()
        tofill['taup_neu_py'] = antineu_lv.Py()
        tofill['taup_neu_pz'] = antineu_lv.Pz()
        
        tofill['pi_plus1_px'] = pi_p_lv1.Px()
        tofill['pi_plus1_py'] = pi_p_lv1.Py()
        tofill['pi_plus1_pz'] = pi_p_lv1.Pz()
        tofill['pi_plus2_px'] = pi_p_lv2.Px()
        tofill['pi_plus2_py'] = pi_p_lv2.Py()
        tofill['pi_plus2_pz'] = pi_p_lv2.Pz()
        tofill['pi_plus3_px'] = pi_p_lv3.Px()
        tofill['pi_plus3_py'] = pi_p_lv3.Py()
        tofill['pi_plus3_pz'] = pi_p_lv3.Pz()
        tofill['taup_m'] = taup_lv.M()
        
        tofill['pi_minus1_px'] = pi_m_lv1.Px()
Exemple #28
0
    def process(self, event):

        #survival variable is for an artififcal cut flow because the real selection is done in the ROOT macro
        survival = 'dead'
        self.counters['cut_flow'].inc('All events')

        det = getattr(event, self.cfg_ana.det)
        if det == 1:
            print 'no Solution for scaling factor!'
            return False

        jets = getattr(event, self.cfg_ana.input_jets)
        if len(jets) == 2:
            self.counters['cut_flow'].inc('2 jets')
#bjets are actually all jets
        bjets = [jet for jet in jets]
        realbjets = [jet for jet in jets
                     if jet.tags['bmatch']]  #assuming 100% b-tag efficiency
        if len(realbjets) == 2:
            self.counters['cut_flow'].inc('2 b jets')
            survival = 'alive'
        elif len(realbjets) == 1:
            self.counters['cut_flow'].inc('1 b jet')

#emratio returns the energy ration (electromagnetic E/total E) of the jet in which it is the greatest
        emratio = []
        for i in range(2):
            emratio.append(bjets[i].constituents[22].e() / bjets[i].e())
        setattr(event, self.cfg_ana.emratio, max(emratio))

        #Total visible mass######################################
        pvis = bjets[0].p4() + bjets[1].p4()
        mvis = pvis.M()
        setattr(event, self.cfg_ana.mvis, mvis)

        if mvis < 10 or mvis > 180:
            survival = 'dead'
        elif survival == 'alive':
            self.counters['cut_flow'].inc('mvis between 10 and 180')

#missing mass############################################
        misenergy = getattr(event, self.cfg_ana.misenergy)
        if misenergy.m() > 125 or misenergy.m() < 65:
            survival = 'dead'
        elif survival == 'alive':
            self.counters['cut_flow'].inc('m_miss between 65 and 125')

#transversal momentum###########################################
#cross check: succeeded
#        print 'compare ', bjets[0].pt(),' to ',math.sqrt(bjets[0].p3().Px()**2+bjets[0].p3().Py()**2)

        pTges = 0
        lix = []
        liy = []
        for jet in bjets:
            lix.append(jet.p3().Px())
            liy.append(jet.p3().Py())
        xve = lix[0] + lix[1]
        yve = liy[0] + liy[1]
        pTges = math.sqrt(xve**2 + yve**2)
        setattr(event, self.cfg_ana.pTges, pTges)
        if pTges <= 15.:
            survival = 'dead'
        elif survival == 'alive':
            self.counters['cut_flow'].inc('Trans momentum > 15 GeV')
#cross check: succeeded
#        pTtest=math.sqrt((bjets[0].p3().Px()+bjets[1].p3().Px())**2+(bjets[0].p3().Py()+bjets[1].p3().Py())**2)
#        print 'compare ',pTtest,' to ', pTges

#longitudinal moementum############################################
        pLges = 0
        liz = []
        for jet in bjets:
            liz.append(jet.p3().Pz())
        pLges = abs(liz[0] + liz[1])
        setattr(event, self.cfg_ana.pLges, abs(pLges))
        if abs(pLges) >= 50.:
            survival = 'dead'
        elif survival == 'alive':
            self.counters['cut_flow'].inc('Long momentum < 50 GeV')
#cross check: succeeded
#        pLtest=math.sqrt((bjets[0].p3().Pz()+bjets[1].p3().Pz())**2)
#        print 'compare ',pLtest,' to ',pLges

#alpha: angle between the 2 jets############################################
#       skalarp is the scalar product of bjet_1 and bjet_2; skalarpa(b) is the product of bjet_1(bjet_2)
#       with itself
        skalarp = bjets[1].p3().Px() * bjets[0].p3().Px() + bjets[0].p3().Py(
        ) * bjets[1].p3().Py() + bjets[0].p3().Pz() * bjets[1].p3().Pz()
        skalarpa = bjets[0].p3().Px() * bjets[0].p3().Px() + bjets[0].p3().Py(
        ) * bjets[0].p3().Py() + bjets[0].p3().Pz() * bjets[0].p3().Pz()
        skalarpb = bjets[1].p3().Px() * bjets[1].p3().Px() + bjets[1].p3().Py(
        ) * bjets[1].p3().Py() + bjets[1].p3().Pz() * bjets[1].p3().Pz()

        #        print bjets[0].scalarp(bjets[0])
        cosa = skalarp / (math.sqrt(skalarpa) * math.sqrt(skalarpb))
        #          alpha is the angle between the two jets in degrees
        try:
            alpha = 360 * math.acos(cosa) / (2 * math.pi)
        except ValueError:
            #Very Rare...something like 1 of 100000 events in qqbar
            #This ValueError is very weird and must come from some roudning problems in python. It happens very rarely. The particles are exactly back to back so cosa is -1 but the way cosa is calc it becomes just slightly smaller than -1 and math.acos(cosa) returns ValueError. Instead of returning False its prob better to set alpha to 180. But gonna check this in more detail
            print "#################ValueError#################"
            print "cosa= ", cosa  #this prints 1 or -1
            print "skalarp= ", skalarp
            print "skalarpa=", skalarpa
            print "skalarpb=", skalarpb
            return False
        setattr(event, self.cfg_ana.alpha, alpha)
        if alpha < 100:
            survival = 'dead'
        elif survival == 'alive':
            self.counters['cut_flow'].inc('Angle between jets > 100 degrees')

#cross variable ################################################################
#       normal vector of the plane between the two vectors i.e. cross product
        normvec = TLorentzVector(0, 0, 0, 0)
        normvec.SetPx(bjets[0].p3().Py() * bjets[1].p3().Pz() -
                      bjets[0].p3().Pz() * bjets[1].p3().Py())
        normvec.SetPy(bjets[0].p3().Pz() * bjets[1].p3().Px() -
                      bjets[0].p3().Px() * bjets[1].p3().Pz())
        normvec.SetPz(bjets[0].p3().Px() * bjets[1].p3().Py() -
                      bjets[0].p3().Py() * bjets[1].p3().Px())

        cross = abs(normvec.Pz() / (math.sqrt(skalarpa * skalarpb)))
        cross = math.asin(cross) * 180. / math.pi

        setattr(event, self.cfg_ana.cross, cross)

        #cross check for cross variable (Patricks code): succeeded
        #	p1=TVector3(bjets[0].p3().Px(),bjets[0].p3().Py(),bjets[0].p3().Pz())
        #	p2=TVector3(bjets[1].p3().Px(),bjets[1].p3().Py(),bjets[1].p3().Pz())
        #	cross2=p1.Unit().Cross(p2.Unit())
        #	cross2=abs(cross2.Unit().z())
        #	cross2=math.asin(cross2)*180./math.pi

        #cross check: succeeded
        #        print 'compare: ',bjets[0].norm(), 'to : ',math.sqrt(bjets[0].scalarp(bjets[0]))

        # cross check: succeeded
        #        print abs(normvec.Pz()),'-----',abs((bjets[0].cross(bjets[1])).Pz())

        #       beta is the angle between the plane of the two jets and the beamaxis
        #ZeroDivisonError
        if math.sqrt(normvec.Px()**2 + normvec.Py()**2 + normvec.Pz()**2) == 0:
            print "##########normvec has norm of 0!!!#########"
            #A very rare case...about 1 in 1000000 qqbar events
            #reason is the angle between the 2 jets is 0
            print "Px= ", normvec.Px()
            print "Py= ", normvec.Py()
            print "Pz= ", normvec.Pz()
            print "jet energies= ", bjets[0].e(), "_,", bjets[1].e()
            print "angle betwee nthe jets= ", alpha  #this returns 0
            return False
        cosb = normvec.Pz() / (math.sqrt(normvec.Px()**2 + normvec.Py()**2 +
                                         normvec.Pz()**2))
        beta = 360 * math.acos(cosb) / (2 * math.pi)
        beta1 = 180 - beta

        #cross check Colins acoplanarity code: succeeded
        #	j1=bjets[0].p3()
        #	j2=bjets[1].p3()
        #	axis=TVector3(0,0,1)
        #	normal = j1.Cross(j2).Unit()
        #	angle=normal.Angle(axis)-math.pi/2.
        #	print angle,angle*180./math.pi,90-min(beta,beta1),cross2

        # cross check: succeeded
        #        sintest=abs(normvec.Pz())/(math.sqrt(normvec.Px()**2+normvec.Py()**2+normvec.Pz()**2))
        #        betatest=360*math.asin(sintest)/(2*math.pi)
        #        print 'compare ',betatest, ' to ',90-min(beta,beta1)

        setattr(event, self.cfg_ana.beta, 90 - min(beta, beta1))
        if cross < 10:
            survival = 'dead'
        elif survival == 'alive':
            self.counters['cut_flow'].inc('cross > 10')

        if survival == 'alive':
            self.counters['cut_flow'].inc('Total # of events after cuts')
        setattr(event, self.cfg_ana.cutlife, survival)

        #cross check:succeeded
        #        ptcs = getattr(event, self.cfg_ana.particles)
        #        pvis = TLorentzVector(0,0,0,0)
        #        for ptc in ptcs:
        #            pvis+=ptc.p4()
        #        print pvis.M()
        #        print mvis

        #Total number of charged tracks
        nchargedtracks = bjets[0].constituents[211].num(
        ) + bjets[1].constituents[211].num()
        setattr(event, self.cfg_ana.ctracks, nchargedtracks)
Exemple #29
0
def jetdisplay():
	outputfile = "Jetdisplay"
	displayfile = TFile(outputfile+".root","RECREATE")

	inputfile = "wwlj1k.root"

	inputfile = TFile(inputfile)
	print "Analyzing: "+str(inputfile)+" \n"
	tree = TTree()
	inputfile.GetObject("B4", tree)	

	graph = TH1F("energyjet", "energyjet", 100, 0., 200.)
	graph2 = TH1F("energycherjet", "energycherjet", 100, 0., 200.)
	graph3 = TH1F("energyscinjet", "energyscinjet", 100, 0., 200.)
	graphmass = TH1F("mass_jet", "mass_jet", 100, 0., 200.)

	graph4 = TH1F("energy", "energy", 100, 0., 200.)
	graph5 = TH1F("energycher", "energycher", 100, 0., 200.)
	graph6 = TH1F("energyscin", "energyscin", 100, 0., 200.)

	#loop over events
	for Event in range(tree.GetEntries()):	

		tree.GetEntry(Event)	

		#Set values of the tree
		PrimaryParticleName = tree.PrimaryParticleName # MC truth: primary particle Geant4 name
		PrimaryParticleEnergy = tree.PrimaryParticleEnergy
		EnergyTot = tree.EnergyTot # Total energy deposited in calorimeter
		Energyem = tree.Energyem # Energy deposited by the em component
		EnergyScin = tree.EnergyScin # Energy deposited in Scin fibers (not Birk corrected)
		EnergyCher = tree.EnergyCher # Energy deposited in Cher fibers (not Birk corrected)
		NofCherenkovDetected = tree.NofCherenkovDetected # Total Cher p.e. detected
		BarrelR_VectorSignals = tree.VectorSignalsR  # Vector of energy deposited in Scin fibers (Birk corrected)
		BarrelL_VectorSignals = tree.VectorSignalsL  # Vector of energy deposited in Scin fibers (Birk corrected)
		BarrelR_VectorSignalsCher = tree.VectorSignalsCherR # Vector of Cher p.e. detected in Cher fibers
		BarrelL_VectorSignalsCher = tree.VectorSignalsCherL 	
		VectorR = tree.VectorR
		VectorL = tree.VectorL
		
		Calib_BarrelL_VectorSignals = calibration.calibscin(BarrelL_VectorSignals)
		Calib_BarrelR_VectorSignals = calibration.calibscin(BarrelR_VectorSignals)
		Calib_BarrelL_VectorSignalsCher = calibration.calibcher(BarrelL_VectorSignalsCher)
		Calib_BarrelR_VectorSignalsCher = calibration.calibcher(BarrelR_VectorSignalsCher)

		energy = float(sum(Calib_BarrelR_VectorSignals)+sum(Calib_BarrelL_VectorSignals))
		energycher = float(sum(Calib_BarrelR_VectorSignalsCher)+sum(Calib_BarrelL_VectorSignalsCher))
		threshold = 0.0 #(GeV)	

		if energy>70.:
			
			#event displays with signals (p.e.)
			#if Event < 1:
				#displayfile.cd()
				#ROOTHistograms.create_eventdisplay_scin("Jet", BarrelR_VectorSignals, BarrelL_VectorSignals, "signal"+str(Event)) 
				#ROOTHistograms.create_eventdisplay_cher("Jet", BarrelR_VectorSignalsCher, BarrelL_VectorSignalsCher, "signal"+str(Event))
		
			#event displays with energy (GeV)	
			if Event<10:
					displayfile.cd()
					ROOTHistograms.create_eventdisplay_scin("Jet_energy", Calib_BarrelR_VectorSignals, Calib_BarrelL_VectorSignals, "energy"+str(Event), threshold) 
					ROOTHistograms.create_eventdisplay_cher("Jet_energy", Calib_BarrelR_VectorSignalsCher, Calib_BarrelL_VectorSignalsCher, "energy"+str(Event), threshold)	
			
			inputparticles_scin = []
			inputparticles_cher = []

			#right part
			for towerindex in range(75*36):	
				theta, phi, eta = newmap.maptower(towerindex, "right")
				energy_scin = Calib_BarrelR_VectorSignals[towerindex]
				pt_scin = energy_scin*np.sin(theta*math.pi/180.)

				energy_cher = Calib_BarrelR_VectorSignalsCher[towerindex]
				pt_cher = energy_cher*np.sin(theta*math.pi/180.)
				
				towerscin = TLorentzVector()
				towerscin.SetPtEtaPhiM(pt_scin, eta, phi*math.pi/180., 0.)
				towercher = TLorentzVector()
				towercher.SetPtEtaPhiM(pt_cher, eta, phi*math.pi/180., 0.)	

				if energy_scin > threshold:
					#print "truth towers: "+str(energy_scin)+" "+str(eta)+" "+str(phi)
					inputparticles_scin.append(fastjet.PseudoJet(towerscin.Px(), towerscin.Py(), towerscin.Pz(), towerscin.E()))
					inputparticles_cher.append(fastjet.PseudoJet(towercher.Px(), towercher.Py(), towercher.Pz(), towercher.E()))
			
			#left part
			for towerindex in range(75*36):	
				theta, phi, eta = newmap.maptower(towerindex, "left")
				energy_scin = Calib_BarrelL_VectorSignals[towerindex]
				pt_scin = energy_scin*np.sin(theta*math.pi/180.)
				
				energy_cher = Calib_BarrelL_VectorSignalsCher[towerindex]
				pt_cher = energy_cher*np.sin(theta*math.pi/180.)
				
				towerscin = TLorentzVector()
				towerscin.SetPtEtaPhiM(pt_scin, eta, phi*math.pi/180., 0.)
				towercher = TLorentzVector()
				towercher.SetPtEtaPhiM(pt_cher, eta, phi*math.pi/180., 0.)	

				if energy_scin > threshold:
					#print "truth towers: "+str(energy_scin)+" "+str(eta)+" "+str(phi)
					inputparticles_scin.append(fastjet.PseudoJet(towerscin.Px(), towerscin.Py(), towerscin.Pz(), towerscin.E()))
					inputparticles_cher.append(fastjet.PseudoJet(towercher.Px(), towercher.Py(), towercher.Pz(), towercher.E()))

			jet_def = fastjet.JetDefinition(fastjet.ee_genkt_algorithm, 2*math.pi, 1.)
			
			clust_seq = fastjet.ClusterSequence(inputparticles_scin, jet_def)	

			print "Event: "+str(Event)+" energy (GeV): "+str(energy)+" n-jets: "+str(len(clust_seq.exclusive_jets(int(2))))+" truth: "+str(len(inputparticles_scin))
			
			clust_seq_cher = fastjet.ClusterSequence(inputparticles_cher, jet_def)

			jet1_scin = fastjet.sorted_by_E(clust_seq.exclusive_jets(int(2)))[0]
			jet2_scin = fastjet.sorted_by_E(clust_seq.exclusive_jets(int(2)))[1]

			jet1_cher = fastjet.sorted_by_E(clust_seq_cher.exclusive_jets(int(2)))[0]
			jet2_cher = fastjet.sorted_by_E(clust_seq_cher.exclusive_jets(int(2)))[1]

			print "DeltaR jet1_scin: "+str(jet1_scin.delta_R(jet1_cher))+" "+str(jet1_scin.delta_R(jet2_cher))

			c = 0.34 #chi factor

			jet1, jet2 = mergejet(jet1_scin, jet2_scin, jet1_cher, jet2_cher)

			graph.Fill(jet1.e()+jet2.e())
			graph3.Fill(jet1_scin.e()+jet2_scin.e())
			graph2.Fill(jet1_cher.e()+jet2_cher.e())
			j = jet1+jet2
			graphmass.Fill(j.m())
			
			graph4.Fill((energy-c*energycher)/(1.-c))
			graph5.Fill(energycher)
			graph6.Fill(energy)
	
	graph.Write()
	graph2.Write()
	graph3.Write()
	graph4.Write()
	graph5.Write()
	graph6.Write()
	graphmass.Write()
      Py = rp.Unit().Y()*P0
      Pz = rp.Unit().Z()*P0
      
      E0 = ROOT.TMath.Sqrt(P0*P0+me2)
      p4 = TLorentzVector()
      p4.SetXYZM(Px,Py,Pz,me)
      wgt0 = 1
      pdgId0 = 11 if(rnd.Uniform()>0.5) else -11
      
      ### fill output vectors
      wgt.push_back(wgt0)  
      pdgId.push_back(pdgId0)  
      vx.push_back(vx0)
      vy.push_back(vy0)
      vz.push_back(vz0)
      px.push_back(p4.Px())
      py.push_back(p4.Py())
      pz.push_back(p4.Pz())
      E.push_back(p4.E())
      
   if(n%100==0): print("done %g out of %g" % (n,Nevt))
   tt.Fill()
   
tf.Write()
tf.Write()
tf.Close()