def costheta_CS(pt1, eta1, phi1, pt2, eta2, phi2, l1id):
    mu1 = TLorentzVector()
    mu2 = TLorentzVector()
    Q = TLorentzVector()

    if (l1id < 0):
        mu1.SetPtEtaPhiM(pt1, eta1, phi1, 0)
        mu2.SetPtEtaPhiM(pt2, eta2, phi2, 0)
    else:
        mu1.SetPtEtaPhiM(pt2, eta2, phi2, 0)
        mu2.SetPtEtaPhiM(pt1, eta1, phi1, 0)

    Q = mu1 + mu2

    mu1plus = ((2.0)**(-0.5)) * (mu1.E() + mu1.Pz())
    mu1minus = ((2.0)**(-0.5)) * (mu1.E() - mu1.Pz())

    mu2plus = ((2.0)**(-0.5)) * (mu2.E() + mu2.Pz())
    mu2minus = ((2.0)**(-0.5)) * (mu2.E() - mu2.Pz())

    costheta = ((2.0 / Q.Mag()) /
                ((Q.Mag()**2.0 + Q.Pt()**2.0)**(0.5))) * (mu1plus * mu2minus -
                                                          mu1minus * mu2plus)

    return costheta
Exemple #2
0
    def process(self, event):
        '''Smear the beam energy.
        
        The two incoming particle energies are smeared under
        a Gaussian pdf of width sigma relative to the beam energy
        
        All outgoing particles are then boosted to the new com
        system 
        '''
        genptcs = getattr(event, self.cfg_ana.gen_particles)
        sigma = self.cfg_ana.sigma
        f1 = random.gauss(1, sigma)
        f2 = random.gauss(1, sigma)
        
        beamptcs = [p for p in genptcs if p.status() == 4]
        pprint.pprint(beamptcs)
        
        assert(len(beamptcs) == 2)
        
        def smear(ptc, factor):
            e = ptc.p4().E() * factor
            pz = math.sqrt(e ** 2 - ptc.m() ** 2)
            if ptc.p4().Pz() < 0:
                pz = -pz                
            ptc._tlv.SetPxPyPzE( ptc.p4().Px(),
                                 ptc.p4().Py(),
                                 pz,
                                 e)        

        newcom = TLorentzVector()
        for ptc, factor in zip(beamptcs, [f1, f2]):
            smear(ptc, factor)
            ptc.p4().Print()
            print ptc.m()
            newcom += ptc.p4()
        
        print 'new com:'
        newcom.Print()
        boost = newcom.BoostVector()
        
        stablep4_before = TLorentzVector()
        stablep4 = TLorentzVector()
        for p in genptcs:
            if p in beamptcs:
                continue
            if p.status() == 1:
                stablep4_before += p._tlv
            # p._tlv.Boost(boost)
            p._tlv.Boost(boost)
            if p.status() == 1:
                stablep4 += p._tlv
                
        pprint.pprint(beamptcs)
        print newcom.E(), newcom.Pz()
        print stablep4.E(), stablep4.Pz()
        print stablep4_before.E(), stablep4_before.Pz()
        boost.Print()
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
Exemple #4
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
Exemple #5
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 #6
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 #7
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 #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
         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 #10
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 #11
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 #12
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 #13
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 #14
0
    b_had.SetPtEtaPhiM(
        tree.GetLeaf("Particle.PT").GetValue(indices['b_had']),
        tree.GetLeaf("Particle.Eta").GetValue(indices['b_had']),
        tree.GetLeaf("Particle.Phi").GetValue(indices['b_had']),
        tree.GetLeaf("Particle.Mass").GetValue(indices['b_had']))

    b_lep.SetPtEtaPhiM(
        tree.GetLeaf("Particle.PT").GetValue(indices['b_lep']),
        tree.GetLeaf("Particle.Eta").GetValue(indices['b_lep']),
        tree.GetLeaf("Particle.Phi").GetValue(indices['b_lep']),
        tree.GetLeaf("Particle.Mass").GetValue(indices['b_lep']))

    ##############################################################
    # CUTS USING PARTICLE LEVEL OBJECTS
    if (t_had.Pz() == 0.) or (t_had.M() != t_had.M()):
        print("Invalid t_had values, P_z = {0}, M = {1}".format(
            t_had.Pz(), t_had.M()))
        continue
    if (t_lep.Pz() == 0.) or (t_lep.M() != t_lep.M()):
        print("Invalid t_lep values, P_z = {0}, M = {1}".format(
            t_lep.Pz(), t_lep.M()))
        continue
    # if W_had.Pt() < 20:
    #     print("Invalid W_had.pt: {}".format(W_had.Pt()))
    #     continue
    # if W_lep.Pt() < 20:
    #     print("Invalid W_lep.pt: {}".format(W_lep.Pt()))
    #     continue
    # if b_had.Pt() < 20:
    #     print("Invalid b_had.pt: {}".format(b_had.Pt()))
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
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(),
    )
    print("tau_lorentz.Px()", tau_lorentz.Px())
def main():
    ##########################################################################################
    ##########################################################################################
    ##########################################################################################
    ### read fits to root file
    # fitsEx = GetFits()

    svd0Seed = ROOT.std.vector( float )()
    svd1Seed = ROOT.std.vector( float )()
    svd2Seed = ROOT.std.vector( float )()
    chi2xzSeed = ROOT.std.vector( float )()
    chi2yzSeed = ROOT.std.vector( float )()
    residxzSeed = ROOT.std.vector( float )()
    residyzSeed = ROOT.std.vector( float )()
    issigSeed = ROOT.std.vector( int )()
    iGenMatch = ROOT.std.vector( int )()
    x1Seed = ROOT.std.vector( float )()
    y1Seed = ROOT.std.vector( float )()
    z1Seed = ROOT.std.vector( float )()
    x2Seed = ROOT.std.vector( float )()
    y2Seed = ROOT.std.vector( float )()
    z2Seed = ROOT.std.vector( float )()
    x3Seed = ROOT.std.vector( float )()
    y3Seed = ROOT.std.vector( float )()
    z3Seed = ROOT.std.vector( float )()
    x4Seed = ROOT.std.vector( float )()
    y4Seed = ROOT.std.vector( float )()
    z4Seed = ROOT.std.vector( float )()
    pxSeed = ROOT.std.vector( float )()
    pySeed = ROOT.std.vector( float )()
    pzSeed = ROOT.std.vector( float )()
    eSeed  = ROOT.std.vector( float )()
    pxGen  = ROOT.std.vector( float )()
    pyGen  = ROOT.std.vector( float )()
    pzGen  = ROOT.std.vector( float )()
    eGen   = ROOT.std.vector( float )()
    qGen   = ROOT.std.vector( float )()
    iGen   = ROOT.std.vector( int )()
    tF = TFile("../data/root/seeds_"+proc+".root","RECREATE")
    tF.cd()
    tT = TTree("seeds","seeds")

    tT.Branch('svd0Seed',svd0Seed)
    tT.Branch('svd1Seed',svd1Seed)
    tT.Branch('svd2Seed',svd2Seed)
    tT.Branch('chi2xzSeed',chi2xzSeed)
    tT.Branch('chi2yzSeed',chi2yzSeed)
    tT.Branch('residxzSeed',residxzSeed)
    tT.Branch('residyzSeed',residyzSeed)
    tT.Branch('issigSeed',issigSeed)
    tT.Branch('iGenMatch',iGenMatch)
    tT.Branch('x1Seed',x1Seed)
    tT.Branch('y1Seed',y1Seed)
    tT.Branch('z1Seed',z1Seed)
    tT.Branch('x2Seed',x2Seed)
    tT.Branch('y2Seed',y2Seed)
    tT.Branch('z2Seed',z2Seed)
    tT.Branch('x3Seed',x3Seed)
    tT.Branch('y3Seed',y3Seed)
    tT.Branch('z3Seed',z3Seed)
    tT.Branch('x4Seed',x4Seed)
    tT.Branch('y4Seed',y4Seed)
    tT.Branch('z4Seed',z4Seed)
    tT.Branch('pxSeed',pxSeed)
    tT.Branch('pySeed',pySeed)
    tT.Branch('pzSeed',pzSeed)
    tT.Branch('eSeed',eSeed)
    tT.Branch('pxGen',pxGen)
    tT.Branch('pyGen',pyGen)
    tT.Branch('pzGen',pzGen)
    tT.Branch('eGen',eGen)
    tT.Branch('qGen',qGen)
    tT.Branch('iGen',iGen)


    histos = { "h_residuals_xz_sig": TH1D("residuals_xz_sig",";residuals_{xz};Tracks", 500,0,0.5),
            "h_residuals_yz_sig": TH1D("residuals_yz_sig",";residuals_{yz};Tracks", 500,0,500), 
            "h_residuals_xz_bkg": TH1D("residuals_xz_bkg",";residuals_{xz};Tracks", 500,0,0.5),
            "h_residuals_yz_bkg": TH1D("residuals_yz_bkg",";residuals_{yz};Tracks", 500,0,500),
            
            "h_svd_dd0_sig": TH1D("svd_dd0_sig",";svd_{dd0};Tracks", 500,21,24),
            "h_svd_dd0_bkg": TH1D("svd_dd0_bkg",";svd_{dd0};Tracks", 500,21,24), 
            "h_svd_dd1_sig": TH1D("svd_dd1_sig",";svd_{dd1};Tracks", 500,0,0.1),
            "h_svd_dd1_bkg": TH1D("svd_dd1_bkg",";svd_{dd1};Tracks", 500,0,0.1),
            "h_svd_dd2_sig": TH1D("svd_dd2_sig",";svd_{dd2};Tracks", 500,0,0.05),
            "h_svd_dd2_bkg": TH1D("svd_dd2_bkg",";svd_{dd2};Tracks", 500,0,0.05),
            
            "h_prob_xz_sig": TH1D("prob_xz_sig",";prob_{xz};Tracks", 500,0,1.0),
            "h_prob_yz_sig": TH1D("prob_yz_sig",";prob_{yz};Tracks", 500,0,1.0), 
            "h_prob_xz_bkg": TH1D("prob_xz_bkg",";prob_{xz};Tracks", 500,0,1.0),
            "h_prob_yz_bkg": TH1D("prob_yz_bkg",";prob_{yz};Tracks", 500,0,1.0),
            
            "h_chi2ndf_xz_sig": TH1D("chi2ndf_xz_sig",";chi2ndf_{xz};Tracks", 500,0,0.001),
            "h_chi2ndf_yz_sig": TH1D("chi2ndf_yz_sig",";chi2ndf_{yz};Tracks", 500,0,0.001), 
            "h_chi2ndf_xz_bkg": TH1D("chi2ndf_xz_bkg",";chi2ndf_{xz};Tracks", 500,0,0.001),
            "h_chi2ndf_yz_bkg": TH1D("chi2ndf_yz_bkg",";chi2ndf_{yz};Tracks", 500,0,0.001),
            
            "h_seed_resE" : TH1D("seed_resE", ";(E_{seed}-E_{gen})/E_{gen};Tracks",    100,-3,+3),
            "h_seed_resPz": TH1D("seed_resPz",";(Pz_{seed}-Pz_{gen})/Pz_{gen};Tracks", 100,-3,+3), 
            "h_seed_resPy": TH1D("seed_resPy",";(Py_{seed}-Py_{gen})/Py_{gen};Tracks", 100,-10,+10),
            
            "h_seed_resE_vs_x"  : TH2D("seed_resE_vs_x",  ";x;(E_{seed}-E_{gen})/E_{gen};Tracks",    100,detXmin,detXmax, 100,-5,+5),
            "h_seed_resPy_vs_x" : TH2D("seed_resPy_vs_x", ";x;(Py_{seed}-Py_{gen})/Py_{gen};Tracks", 100,detXmin,detXmax, 100,-10,+10),
            
            "h_N_sigacc":        TH1D("N_sigacc",        ";Track multiplicity;Events", 40,30,190),
            "h_N_all_seeds":     TH1D("N_all_seeds",     ";Track multiplicity;Events", 40,30,190),
            "h_N_matched_seeds": TH1D("N_matched_seeds", ";Track multiplicity;Events", 40,30,190),
            "h_N_good_seeds":    TH1D("N_good_seeds",    ";Track multiplicity;Events", 40,30,190),
            
            "h_seeding_score": TH1D("h_seeding_score", ";N_{seeds}^{matched}/N_{signa}^{in.acc} [%];Events", 20,91,101),
            "h_seeding_pool":  TH1D("h_seeding_pool",  ";N_{seeds}^{all}/N_{signa}^{in.acc} [%];Events", 50,90,590),
    }
    sidesarr = getLogicSidesArr()
    pdfname = "../output/pdf/seedingdemo_"+proc+".pdf"
    intfile = TFile("../data/root/rec_"+proc+".root","READ")
    intree = intfile.Get("res")
    nevents = intree.GetEntries()
    print("with %d events" % nevents)
    nmax = 100000
    n=0 ### init n
    for event in intree:
    Nsigall = 0
    Nsigacc = 0
    Nseeds = 0
    Nmatched = 0
    Ngood = 0
    
    ## clear the output vectors
    svd0Seed.clear()
    svd1Seed.clear()
    svd2Seed.clear()
    chi2xzSeed.clear()
    chi2yzSeed.clear()
    residxzSeed.clear()
    residyzSeed.clear()
    issigSeed.clear()
    iGenMatch.clear()
    x1Seed.clear()
    y1Seed.clear()
    z1Seed.clear()
    x2Seed.clear()
    y2Seed.clear()
    z2Seed.clear()
    x3Seed.clear()
    y3Seed.clear()
    z3Seed.clear()
    x4Seed.clear()
    y4Seed.clear()
    z4Seed.clear()
    
    pxSeed.clear()
    pySeed.clear()
    pzSeed.clear()
    eSeed.clear()
    
    pxGen.clear()
    pyGen.clear()
    pzGen.clear()
    eGen.clear()
    qGen.clear()
    iGen.clear()
    
    
    
    ### start the loop
    if(n>nmax): break
    
    ### draw?
    dodraw = (n<=NeventsToDraw)
    
    ### container for all clusters
    allpointsEside = initpoints()
    allpointsPside = initpoints()
    
    ## clusters' vectors are always written out (even if empty) for all gen tracks!
    ## each generated track in the vector always has 4 clusters accessed via TPolyMarker3D::GetPoint()
    for i in range(event.polm_clusters.size()):
        
        ###############################################################
        if(proc=="bppp"):
            if(sides=="e+" and event.qgen[i]<0): continue ## only positrons
            if(sides=="e-" and event.qgen[i]>0): continue ## only electrons
        if(proc=="trident" and event.qgen[i]<0): continue ## only positrons
        ###############################################################
        
        Nsigall += 1
        
        wgt  = event.wgtgen[i]
        pgen = event.pgen[i]
        ### cut on acceptance
        if(event.acctrkgen[i]!=1): continue
        
        Nsigacc += 1
        
        ### write the truth track momentum and its index
        pxGen.push_back(pgen.Px())
        pyGen.push_back(pgen.Py())
        pzGen.push_back(pgen.Pz())
        eGen.push_back(pgen.E())
        qGen.push_back(event.qgen[i])
        iGen.push_back(i)
        
        ### loop over all clusters of the track and put in the allpoints classified by the layer
        for jxy in range(event.polm_clusters[i].GetN()):
            rcls = [ ROOT.Double(), ROOT.Double(), ROOT.Double() ]
            event.polm_clusters[i].GetPoint(jxy,rcls[0],rcls[1],rcls[2]) ### the clusters
            if(rcls[0]>0): AddPoint(allpointsEside,rcls,True,i)
            if(rcls[0]<0): AddPoint(allpointsPside,rcls,True,i)
    Nsig4 = getNnon0(allpointsEside["Cls"][4])+getNnon0(allpointsPside["Cls"][4])
    
    
    ### embed some noise clusters
    rnd = TRandom()
    rnd.SetSeed()
    for kN in range(NnoiseClusters):
        for layer in layers:
            for side in sidesarr:
                x = 0
                if(side=="Pside"): x = rnd.Uniform(xPsideL,xPsideR)
                if(side=="Eside"): x = rnd.Uniform(xEsideL,xEsideR)
                y = rnd.Uniform(-0.75,+0.75)
                if(layer==1): z = 300
                if(layer==2): z = 310
                if(layer==3): z = 320
                if(layer==4): z = 330
                rnoise = [x,y,z]
                if(side=="Pside"): AddPoint(allpointsPside,rnoise)
                if(side=="Eside"): AddPoint(allpointsEside,rnoise)
    Nbkgsig4 = getNnon0(allpointsEside["Cls"][4])+getNnon0(allpointsPside["Cls"][4])
    
    
    ### just draw the full event
    drawall(pdfname+"(",allpointsEside,allpointsPside,dodraw)
    
    
    ### loop on the 2 sides
    for side in sidesarr:
        allpoints = allpointsEside if(side=="Eside") else allpointsPside
        
        ### the initial pool for pivot clusters
        Nall4 = getNnon0(allpoints["Cls"][4])
        
        ### loop over the clusters and start the seeding
        for j4 in range(Nall4):
            r4 = getpoint(allpoints["Cls"][4],j4)
            xpivot = r4[0]
            ### electron / positron?
            particlename = getparticlename(allpoints["Cls"][4],j4)
            ### get the yz window
            winpts_yz,winlin_yz = getyzwindow(allpoints["Cls"][4],j4)
            ### set the wide window starting from cluster_seed1 (window corners must be added clockwise!)
            winpts_xz_wide,winlin_xz_wide = getwidewindow(allpoints["Cls"][4],j4)
            ### discard all clusters which are not in the wide window
            widepoints = initpoints()
            trimwide(allpoints,widepoints,winpts_xz_wide,winpts_yz,xpivot)
            Nwide1 = getNnon0(widepoints["Cls"][1])
            # if(Nwide1<1): print("Failed Nwide1")
            ### draw the wide window
            draw(pdfname,widepoints,dodraw,particlename,winlin_yz,winlin_xz_wide)
            
            ### choose one cluster in layer 1 as the second seed
            for j1 in range(Nwide1):
                ### get the narrow window  (window corners must be added clockwise!)
                winpts_xz_narr,winlin_xz_narr = getnarrwindow(allpoints["Cls"][4],widepoints["Cls"][1],j4,j1)
                ### discard all clusters which are not in the narrow window
                narrpoints = initpoints()
                trimnarr(widepoints,narrpoints,winpts_xz_narr)
                Nnarr2 = getNnon0(narrpoints["Cls"][2])
                Nnarr3 = getNnon0(narrpoints["Cls"][3])
                
                ### check if there are at least 1 cluster in both layer 2 and layer 3 within the narrow window
                if(Nnarr2<1 or Nnarr3<1): continue
                
                ### draw the narrow window
                draw(pdfname,narrpoints,dodraw,particlename,None,winlin_xz_narr)
                
                ### get the seed - note: could be that there are several combinations but the seed momentum would be identical
                pseed = makeseed(allpoints["Cls"][4],widepoints["Cls"][1],j4,j1,particlename)
                # if(pseed.E()>Emax or pseed.E()<Emin): print("pseed.E()>Emax or pseed.E()<Emin")
                if(pseed.E()>Emax or pseed.E()<Emin): continue
                
                ### set the cluster in layer 1
                r1 = getpoint(widepoints["Cls"][1],j1)
                
                ### loop on the clusters in layer 2 and 3:
                for j2 in range(Nnarr2):
                # for j2 in range(narrpoints["Cls"][2].GetN()):
                r2 = getpoint(narrpoints["Cls"][2],j2)
                for j3 in range(Nnarr3):
                # for j3 in range(narrpoints["Cls"][3].GetN()):
                    r3 = getpoint(narrpoints["Cls"][3],j3)
                    Nseeds += 1
                    
                    issig1 = widepoints["IsSig"][1][j1]
                    issig2 = narrpoints["IsSig"][2][j2]
                    issig3 = narrpoints["IsSig"][3][j3]
                    issig4 = allpoints["IsSig"][4][j4]
                    
                    trkid4 = allpoints["TrkId"][4][j4]
                    trkid3 = narrpoints["TrkId"][3][j3]
                    trkid2 = narrpoints["TrkId"][2][j2]
                    trkid1 = widepoints["TrkId"][1][j1]
                    issig = (issig4 and issig1 and issig2 and issig3)
                    trkid = str(trkid4) if(trkid4==trkid1 and trkid1==trkid2 and trkid2==trkid3) else "mult"
                    issiguniq = (issig and trkid!="mult")
                    if(issiguniq): Nmatched += 1
        
                    ### two independent 2d fits
                    chi2_xz,prob_xz,chi2_yz,prob_yz = seed2dfit(pdfname,r1,r2,r3,r4,dodraw)
                    if(issiguniq):
                        histos["h_chi2ndf_xz_sig"].Fill(chi2_xz)
                        histos["h_chi2ndf_yz_sig"].Fill(chi2_yz)
                        histos["h_prob_xz_sig"].Fill(prob_xz)
                        histos["h_prob_yz_sig"].Fill(prob_yz)
                    else:
                        histos["h_chi2ndf_xz_bkg"].Fill(chi2_xz)
                        histos["h_chi2ndf_yz_bkg"].Fill(chi2_yz)
                        histos["h_prob_xz_bkg"].Fill(prob_xz)
                        histos["h_prob_yz_bkg"].Fill(prob_yz)
        
                    ### a single 3d fit
                    res_xz, res_yz = seed3dfit(pdfname,r1,r2,r3,r4,dodraw)
                    if(issiguniq):
                        histos["h_residuals_xz_sig"].Fill(res_xz)
                        histos["h_residuals_yz_sig"].Fill(res_yz)
                    else:
                        histos["h_residuals_xz_bkg"].Fill(res_xz)
                        histos["h_residuals_yz_bkg"].Fill(res_yz)
                        
                    ### a single 3d fit SVD
                    lfitpts, dd = seed3dfitSVD(pdfname,r1,r2,r3,r4,dodraw)
                    
                    ### set again the pseed according to lfit
                    cluster1 = TPolyMarker3D()
                    cluster2 = TPolyMarker3D()
                    cluster1.SetNextPoint(lfitpts[0][0],lfitpts[0][1],lfitpts[0][2])
                    cluster2.SetNextPoint(lfitpts[1][0],lfitpts[1][1],lfitpts[1][2])
                    if(isel(lfitpts[0][0])): pseed = makeseed(cluster2,cluster1,0,0,particlename)
                    else:                    pseed = makeseed(cluster1,cluster2,0,0,particlename)
                    if(pseed.E()>Emax or pseed.E()<Emin): continue
                    
                    ### the SVD alg
                    if(issiguniq):
                        histos["h_svd_dd0_sig"].Fill(dd[0])
                        histos["h_svd_dd1_sig"].Fill(dd[1])
                        histos["h_svd_dd2_sig"].Fill(dd[2])
                    else:
                        histos["h_svd_dd0_bkg"].Fill(dd[0])
                        histos["h_svd_dd1_bkg"].Fill(dd[1])
                        histos["h_svd_dd2_bkg"].Fill(dd[2])
                    
                    ### get the generated matched track momentum
                    pgen = TLorentzVector()
                    igen = -1
                    for k in range(iGen.size()):
                        if(iGen[k]==j4):
                            igen = k
                            break
                    
                    ### write out the good seeds
                    svd0Seed.push_back(dd[0])
                    svd1Seed.push_back(dd[1])
                    svd2Seed.push_back(dd[2])
                    chi2xzSeed.push_back(chi2_xz)
                    chi2yzSeed.push_back(chi2_yz)
                    residxzSeed.push_back(res_xz)
                    residyzSeed.push_back(res_yz)
                    issigSeed.push_back(issiguniq)
                    iGenMatch.push_back(igen)
                    x1Seed.push_back(r1[0])
                    y1Seed.push_back(r1[1])
                    z1Seed.push_back(r1[2])
                    x2Seed.push_back(r2[0])
                    y2Seed.push_back(r2[1])
                    z2Seed.push_back(r2[2])
                    x3Seed.push_back(r3[0])
                    y3Seed.push_back(r3[1])
                    z3Seed.push_back(r3[2])
                    x4Seed.push_back(r4[0])
                    y4Seed.push_back(r4[1])
                    z4Seed.push_back(r4[2])
                    pxSeed.push_back(pseed.Px())
                    pySeed.push_back(pseed.Py())
                    pzSeed.push_back(pseed.Pz())
                    eSeed.push_back(pseed.E())
                    
                    ### cut on some quality
                    isgood = (dd[1]<0.005 and dd[2]<0.0025)
                    if(not isgood): continue
                    Ngood += 1
                    
                    ### check perforrmance of seeding
                    pgen.SetPxPyPzE(pxGen[igen],pyGen[igen],pzGen[igen],eGen[igen])
                    resE = (pseed.E()-pgen.E())/pgen.E()
                    resPz = (pseed.Pz()-pgen.Pz())/pgen.Pz()
                    resPy = (pseed.Py()-pgen.Py())/pgen.Py()
                    histos["h_seed_resE"].Fill(resE)
                    histos["h_seed_resPz"].Fill(resPz)
                    histos["h_seed_resPy"].Fill(resPy)
                    histos["h_seed_resE_vs_x"].Fill(r4[0],resE)
                    histos["h_seed_resPy_vs_x"].Fill(r4[0],resPy)
                    
    histos["h_N_sigacc"].Fill(Nsigacc)       
    histos["h_N_all_seeds"].Fill(Nseeds)       
    histos["h_N_matched_seeds"].Fill(Nmatched)       
    histos["h_N_good_seeds"].Fill(Ngood)
    histos["h_seeding_score"].Fill(Nmatched/Nsigacc*100)
    histos["h_seeding_pool"].Fill(Nseeds/Nsigacc*100)
        
    if(dodraw):
        cnv = TCanvas("","",2000,2000)
        cnv.SaveAs(pdfname+")")
    print("Event: %g --> Nsigall=%g, Nsigacc=%g, Nseeds=%g, Nmatched=%g, Ngood=%g --> Seeds matching performance: Nmatched/Nsigacc=%5.1f%%" % (n,Nsigall,Nsigacc,Nseeds,Nmatched,Ngood,Nmatched/Nsigacc*100))

    tT.Fill()
    if(n%10==0 and n>0): print("  processed %d events" % n)
    n+=1
    print("Total events processed: ",n)










    cnv = TCanvas("","",1000,1000)
    cnv.Divide(2,2)
    cnv.cd(1)
    histos["h_chi2ndf_xz_sig"].SetLineColor(ROOT.kRed);   histos["h_chi2ndf_xz_sig"].Draw()
    histos["h_chi2ndf_xz_bkg"].SetLineColor(ROOT.kBlack); histos["h_chi2ndf_xz_bkg"].Draw("same")
    cnv.cd(2)
    histos["h_chi2ndf_yz_sig"].SetLineColor(ROOT.kRed);   histos["h_chi2ndf_yz_sig"].Draw()
    histos["h_chi2ndf_yz_bkg"].SetLineColor(ROOT.kBlack); histos["h_chi2ndf_yz_bkg"].Draw("same")
    cnv.cd(3)
    histos["h_prob_xz_sig"].SetLineColor(ROOT.kRed);   histos["h_prob_xz_sig"].Draw()
    histos["h_prob_xz_bkg"].SetLineColor(ROOT.kBlack); histos["h_prob_xz_bkg"].Draw("same")
    cnv.cd(4)
    histos["h_prob_yz_sig"].SetLineColor(ROOT.kRed);   histos["h_prob_yz_sig"].Draw()
    histos["h_prob_yz_bkg"].SetLineColor(ROOT.kBlack); histos["h_prob_yz_bkg"].Draw("same")
    cnv.SaveAs("../output/pdf/chi2ndf_"+proc+".pdf")

    cnv = TCanvas("","",1000,500)
    cnv.Divide(2,1)
    cnv.cd(1)
    histos["h_residuals_xz_sig"].SetLineColor(ROOT.kRed);   histos["h_residuals_xz_sig"].Draw()
    histos["h_residuals_xz_bkg"].SetLineColor(ROOT.kBlack); histos["h_residuals_xz_bkg"].Draw("same")
    cnv.cd(2)
    histos["h_residuals_yz_sig"].SetLineColor(ROOT.kRed);   histos["h_residuals_yz_sig"].Draw()
    histos["h_residuals_yz_bkg"].SetLineColor(ROOT.kBlack); histos["h_residuals_yz_bkg"].Draw("same")
    cnv.SaveAs("../output/pdf/resid3dfit_"+proc+".pdf")

    cnv = TCanvas("","",1500,500)
    cnv.Divide(3,1)
    cnv.cd(1)
    histos["h_svd_dd0_sig"].SetLineColor(ROOT.kRed);   histos["h_svd_dd0_sig"].Draw()
    histos["h_svd_dd0_bkg"].SetLineColor(ROOT.kBlack); histos["h_svd_dd0_bkg"].Draw("same")
    cnv.cd(2)
    histos["h_svd_dd1_sig"].SetLineColor(ROOT.kRed);   histos["h_svd_dd1_sig"].Draw()
    histos["h_svd_dd1_bkg"].SetLineColor(ROOT.kBlack); histos["h_svd_dd1_bkg"].Draw("same")
    cnv.cd(3)
    histos["h_svd_dd2_sig"].SetLineColor(ROOT.kRed);   histos["h_svd_dd2_sig"].Draw()
    histos["h_svd_dd2_bkg"].SetLineColor(ROOT.kBlack); histos["h_svd_dd2_bkg"].Draw("same")
    cnv.SaveAs("../output/pdf/svd3dfit_"+proc+".pdf")

    cnv = TCanvas("","",1000,1000)
    cnv.Divide(2,2)
    cnv.cd(1); histos["h_seed_resE"].Draw("hist")
    cnv.cd(2); histos["h_seed_resPy"].Draw("hist")
    cnv.cd(3); histos["h_seed_resE_vs_x"].Draw("col")
    cnv.cd(4); histos["h_seed_resPy_vs_x"].Draw("col")
    cnv.SaveAs("../output/pdf/seedsres_"+proc+".pdf")

    cnv = TCanvas("","",1500,500)
    cnv.Divide(3,1)
    cnv.cd(1)
    histos["h_N_sigacc"].SetLineColor(ROOT.kBlack); histos["h_N_sigacc"].Draw()
    histos["h_N_all_seeds"].SetLineColor(ROOT.kBlue); histos["h_N_all_seeds"].Draw("same")
    histos["h_N_matched_seeds"].SetLineColor(ROOT.kGreen); histos["h_N_matched_seeds"].Draw("same")
    histos["h_N_good_seeds"].SetLineColor(ROOT.kRed); histos["h_N_good_seeds"].Draw("same")
    cnv.cd(2)
    histos["h_seeding_pool"].Draw("hist")
    cnv.cd(3)
    histos["h_seeding_score"].Draw("hist")
    cnv.SaveAs("../output/pdf/seedsmult_"+proc+".pdf")

    tF.cd()
    tT.Write()
    tF.Write()
    tF.Close()


if __name__=="__main__":
    main()
Exemple #18
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 #19
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()
        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
Exemple #21
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
        
        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
            Z2_Z1SS = l_Z1 * Z2
            l1_Z1SS = l_Z1 * l1
    ## 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
    data.append(allmuons)
    isaved += 1

## Write the data object into a text file and a pickle file for students to use
Exemple #24
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
      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()




        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')]))
Exemple #27
0
        
        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()
        tofill['pi_minus1_py'] = pi_m_lv1.Py()
        tofill['pi_minus1_pz'] = pi_m_lv1.Pz()
Exemple #28
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()
Exemple #29
0
def selectEvents(fileName,saveProbes=False,saveSummary=False,outputDir='./',xsec=-1,correctionsMap={}):

    gSystem.ExpandPathName(fileName)
    file=TFile.Open(fileName)

    #exclusivity of triggers per PD
    eTriggersOnly  = ('SingleEle' in fileName)
    muTriggersOnly = ('SingleMu'  in fileName)

    #normalizations and corrections
    origEvents=1.0
    puWeightsGr=None
    if xsec>0 :
        origEvents=file.Get('smDataAnalyzer/cutflow').GetBinContent(1)
        if origEvents==0 :
            print '[Warning] 0 initial events ?'

        #derive pileup weights
        origPileup=file.Get('smDataAnalyzer/pileup')
        try:
            dataPileupFile=TFile.Open(correctionsMap['pu'])
            dataPileup=dataPileupFile.Get('pileup')
            normF=origPileup.Integral()/dataPileup.Integral()
            if normF>0 :
                puWeightsGr=TGraph()
                for xbin in xrange(1,origPileup.GetXaxis().GetNbins()+1) :
                    iweight=1.0
                    if origPileup.GetBinContent(xbin)>0 :
                        iweight=normF*dataPileup.GetBinContent(xbin)/origPileup.GetBinContent(xbin)
                        puWeightsGr.SetPoint( puWeightsGr.GetN(), origPileup.GetXaxis().GetBinCenter(xbin), iweight )
            dataPileupFile.Close()
        except :
            print 'No data pileup file provided or other error occurred. If you wish add -w pu,pu_file.root'

    jecCorrector=None
    jecUncertainty=None
    try:
        prefix='Data'
        if xsec>0 : prefix='MC'
        jecDir=correctionsMap['jec']

        gSystem.ExpandPathName(jecDir)
        jetCorLevels='L1FastJet'
        jetCorFiles=jecDir+'/'+prefix+'_L1FastJet_AK5PFchs.txt'
        jetCorLevels=jetCorLevels+':L2Relative'
        jetCorFiles=jetCorFiles+':'+jecDir+'/'+prefix+'_L2Relative_AK5PFchs.txt'
        jetCorLevels=jetCorLevels+':L3Absolute'
        jetCorFiles=jetCorFiles+':'+jecDir+'/'+prefix+'_L3Absolute_AK5PFchs.txt'
        #if prefix=='Data':
        #    jetCorLevels=jetCorLevels+':L2L3Residual'
        #    jetCorFiles=jetCorFiles+':'+jecDir+'/'+prefix+'_L2L3Residual_AK5PFchs.txt'
        jecCorrector=FactorizedJetCorrector(jetCorLevels,jetCorFiles)
        print 'Jet energy corrector initialized with levels ',jetCorLevels,' for ',prefix

        if prefix=='MC':
            jecUncertainty=JetCorrectionUncertainty(jecDir+"/"+prefix+"_Uncertainty_AK5PFchs.txt")
            print 'Jet uncertainty is ',jecUncertainty

    except Exception as e:
        print '[Error]',e



    tree=file.Get("smDataAnalyzer/data")
    nev = tree.GetEntries()

    outUrl=outputDir+'/'+os.path.basename(fileName)
    monitor=Monitor(outUrl)

    #same the initial normalization and cross section
    monitor.addValue(origEvents,'iniEvents')
    monitor.addValue(xsec,'crossSection')

    #some basic histograms
    monitor.addHisto('nvtx',    ';Vertices;Events',                       50,0,50)
    monitor.addHisto('nvtxraw', ';Vertices;Events',                       50,0,50)
    monitor.addHisto('vmass',   ';Mass [GeV];Events',                     50,0,250)
    monitor.addHisto('vmt',     ';Transverse mass [GeV];Events',          50,0,250)
    monitor.addHisto('vpt',     ';Boson transverse momentum [GeV];Events',50,0,250)
    monitor.addHisto('leg1pt',  ';Transverse momentum [GeV];Events',      50,0,250)
    monitor.addHisto('leg2pt',  ';Transverse momentum [GeV];Events',      50,0,250)
    monitor.addHisto('leg1iso', ';Relative isolation;Events',             50,0,0.5)
    monitor.addHisto('leg2iso', ';Relative isolation;Events',             50,0,0.5)

    #save a summary ntuple for analysis
    summaryTuple=None
    if saveSummary :
        varList='cat:weight:nvtx:njets'
        varList=varList+':v_mass:v_mt:v_pt:genv_mass:genv_pt'
        varList=varList+':leg1_pt:leg1_eta:leg1_phi:genleg1_pt:leg1_relIso'
        varList=varList+':leg2_pt:leg2_eta:leg2_phi:genleg2_pt:leg2_relIso'
        varList=varList+':sumEt:ht'
        varList=varList+':met_lesup:met_lesdown:met_jesup:met_jesdown:met_jerup:met_jerdown:met_umetup:met_umetdown'
        summaryTuple=TNtuple('data','summary',varList)
        summaryTuple.SetDirectory(0)
        monitor.addObject(summaryTuple)

    #save a dedicated ntuple for Tag and Probe
    probesTuple=None
    probesId   = array.array( 'f', [ 0 ] )
    probesPt   = array.array( 'f', [ 0 ] )
    probesEta  = array.array( 'f', [ 0 ] )
    probesPhi  = array.array( 'f', [ 0 ] )
    probesNvtx = array.array( 'f', [ 0 ] )
    probesMass = array.array( 'f', [ 0 ] )
    probesIsMatched = array.array( 'i', [0] )
    probesPassLoose = array.array( 'i', [ 0 ] )
    probesPassTight = array.array( 'i', [ 0 ] )
    probesFireTrigger = array.array( 'i', [ 0 ] )
    if saveProbes :
        probesTuple=TTree('tandp','summary for tandp')
        probesTuple.Branch( 'id', probesId, 'id/F' )
        probesTuple.Branch( 'pt', probesPt, 'pt/F' )
        probesTuple.Branch( 'eta', probesEta, 'eta/F' )
        probesTuple.Branch( 'phi', probesPhi, 'phi/F' )
        probesTuple.Branch( 'nvtx', probesNvtx, 'nvtx/F' )
        probesTuple.Branch( 'mass', probesMass, 'mass/F' )
        probesTuple.Branch( 'isMatched', probesIsMatched, 'isMatched/I' )
        probesTuple.Branch( 'passLoose', probesPassLoose, 'passLoose/I' )
        probesTuple.Branch( 'passTight', probesPassTight, 'passTight/I' )
        probesTuple.Branch( 'fireTrigger', probesFireTrigger, 'fireTrigger/I' )
        probesTuple.SetDirectory(0)
        monitor.addObject(probesTuple)

    #
    # LOOP OVER THE EVENTS
    #
    for iev in xrange(0,nev):
        tree.GetEntry(iev)
        if iev%10000 == 0 :
            sys.stdout.write("\r[ %d/100 ] completed" %(100.*iev/nev))
            sys.stdout.flush()

        #check mc truth (select V bosons from the hard process
        genBosonP4=TLorentzVector(0,0,0,0)
        genNeutP4=TLorentzVector(0,0,0,0)
        for g in xrange(0,tree.mcn):
            if tree.mc_status[g]!=3 : continue
            genP4=TLorentzVector(tree.mc_px[g],tree.mc_py[g],tree.mc_pz[g],tree.mc_en[g])
            if abs(tree.mc_id[g])==12 or abs(tree.mc_id[g])==14 or abs(tree.mc_id[g])==14 : genNeutP4=genNeutP4+genP4
            if abs(tree.mc_id[g])!=23 and abs(tree.mc_id[g])!=24 : continue
            genBosonP4=genP4
        
        #get triggers that fired
        eFire,mFire,emFire=decodeTriggerWord(tree.tbits)
        if eTriggersOnly :  mFire=False
        if muTriggersOnly : eFire=False

        #select the leptons
        leptonCands=[]
        validTags=[]
        lepSums=[TLorentzVector(0,0,0,0)]*3
        lepFlux=TLorentzVector(0,0,0,0)
        for l in xrange(0,tree.ln) :
            lep=LeptonCand(tree.ln_id[l],tree.ln_px[l],tree.ln_py[l],tree.ln_pz[l],tree.ln_en[l])
            if lep.p4.Pt()<20 : continue
            if abs(tree.ln_id[l])==11 :
                if math.fabs(lep.p4.Eta())>2.5 : continue
                if math.fabs(lep.p4.Eta())>1.4442 and math.fabs(lep.p4.Eta())<1.566 : continue
            if abs(tree.ln_id[l])==13 :
                if math.fabs(lep.p4.Eta())>2.1 : continue
            relIso, isLoose, isLooseIso, isTight, isTightIso = selectLepton(tree.ln_id[l],tree.ln_idbits[l],tree.ln_gIso[l],tree.ln_chIso[l],tree.ln_nhIso[l],tree.ln_puchIso[l],lep.p4.Pt())
            lep.selectionInfo(relIso,isLoose, isLooseIso, isTight, isTightIso)
            lep.triggerInfo(tree.ln_Tbits[l])

            #check the generator level information
            genMatchIdx=tree.ln_genid[l]
            if genMatchIdx < tree.mcn :
                lep.genMatch(tree.mc_id[genMatchIdx],tree.mc_px[genMatchIdx],tree.mc_py[genMatchIdx],tree.mc_pz[genMatchIdx],tree.mc_en[genMatchIdx])
            else :
                lep.genMatch(0,0,0,0,0)
            leptonCands.append(lep)

            if not saveProbes: continue
            if not isTight or not isTightIso or lep.Tbits==0 : continue
            if abs(lep.id)==11 and not eFire: continue
            if abs(lep.id)==13 and not mFire: continue

            validTags.append( len(leptonCands)-1 )
            lepSums[1]=lepSums[1]+lep.getP4('lesup')-lep.p4
            lepSums[2]=lepSums[2]+lep.getP4('lesdown')-lep.p4
            lepFlux=lepFlux+lep.p4

        #check if probes tree should be saved
        if saveProbes and len(validTags)>0:

            # choose a random tag
            tagIdx=random.choice(validTags)
            tag=leptonCands[tagIdx]

            #find probe
            probe=None
            for l in xrange(0,len(leptonCands)) :
                if l==tagIdx: continue
                if abs(tag.id)!=abs(leptonCands[l].id) : continue
                probe=leptonCands[l]
                break

            #for electrons save superclusters if probe is not found
            matchToEle=1
            #if abs(tag.id)==11 and probe is None :
            #    matchToEle=0
            #    for sc in xrange(0,tree.scn) :
            #        sc_en=tree.scn_e[sc]
            #        sc_eta=tree.scn_eta[sc]
            #        sc_phi=tree.scn_phi[sc]
            #        sc_pt=sc_en/math.cosh(sc_eta)
            #        sc_p4=TLorentzVector(0,0,0,0)
            #        sc_p4.SetPtEtaPhiE(sc_pt,sc_eta,sc_phi,sc_en)
            #        lscp4=tag.p4+sc_p4
            #        if math.fabs(lscp4.M()-91)>30 : continue
            #        scCand=LeptonCand(tag.id,sc_p4.Px(),sc_p4.Py(),sc_p4.Pz(),sc_p4.E())
            #        scCand.selectionInfo(0,0,0,0,0)
            #        scCand.triggerInfo(0)
            #        probe=scCand
            #        break
            if abs(tag.id)==13 : matchToEle=0

            #save info
            if probe is not None:
                tpp4=tag.p4+probe.p4
                if math.fabs(tpp4.M()-91)<30 :
                    probesId[0]=probe.id
                    probesPt[0]=probe.p4.Pt()
                    probesEta[0]=probe.p4.Eta()
                    probesPhi[0]=probe.p4.Phi()
                    probesNvtx[0]=tree.nvtx
                    probesMass[0]=tpp4.M()
                    probesIsMatched[0]=(probe.genId!=0)
                    probesPassLoose[0]=(probe.passLoose and probe.passLooseIso)
                    probesPassTight[0]=(probe.passTight and probe.passTightIso)
                    probesFireTrigger[0]=(probe.Tbits>0)
                    probesTuple.Fill()

        #jets
        selJets=[]
        jetSums=[TLorentzVector(0,0,0,0)]*5
        jetFlux=TLorentzVector(0,0,0,0)
        ht=0
        for j in xrange(0,tree.jn) :
            jet=JetCand(tree.jn_px[j],tree.jn_py[j],tree.jn_pz[j],tree.jn_en[j],tree.jn_area[j],tree.jn_torawsf[j])

            #cross clean with loose isolated leptons
            overlapFound=False
            for l in leptonCands:
                if not l.passLoose or not l.passLooseIso : continue
                dR=jet.p4.DeltaR(l.p4)
                if dR>0.4 : continue
                overlapFound=True
                break
            if overlapFound: continue

            #very loose kinematics cuts
            if math.fabs(jet.p4.Eta())>4.7 or jet.p4.Pt()<10 : continue

            #save it
            jet.genMatch(tree.jn_genpx[j],tree.jn_py[j],tree.jn_pz[j],tree.jn_en[j],tree.jn_genid[j],tree.jn_genflav[j])
            jet.updateJEC(jecCorrector,jecUncertainty,tree.rho,tree.nvtx)
            selJets.append(jet)

            #account for all the corrections you have applied
            jetSums[0]=jetSums[0] + jet.getCorrectedJet()          - jet.getCorrectedJet('raw')
            jetSums[1]=jetSums[1] + jet.getCorrectedJet('jesup')   - jet.getCorrectedJet()
            jetSums[2]=jetSums[2] + jet.getCorrectedJet('jesdown') - jet.getCorrectedJet()
            jetSums[3]=jetSums[3] + jet.getCorrectedJet('jerup')   - jet.getCorrectedJet()
            jetSums[4]=jetSums[4] + jet.getCorrectedJet('jerdown') - jet.getCorrectedJet()
            jetFlux=jetFlux+jet.p4
            ht=ht+jet.p4.Pt()

        # met
        metCand=METCand(tree.met_pt[0]*math.cos(tree.met_phi[0]),tree.met_pt[0]*math.sin(tree.met_phi[0]),0,tree.met_pt[0])
        metCand.genMatch(genNeutP4.Px(),genNeutP4.Py(),genNeutP4.Pz(),genNeutP4.E())
        metCand.addSumEts(tree.met_sumet[0], tree.met_chsumet[0])
        metCand.addJetCorrections(jetSums)
        metCand.addLeptonCorrections(lepSums)
        unclFlux=-(metCand.p4+lepFlux+jetFlux)
        unclSums=[TLorentzVector(0,0,0,0),unclFlux*0.10,unclFlux*(-0.10)]
        metCand.addUnclusteredCorrections(unclSums)

        #build the candidate
        vCand=buildVcand(eFire,mFire,emFire,leptonCands,metCand)
        if vCand is None : continue

        #prepare to save
        weight=1.0
        if puWeightsGr is not None:
            weight=puWeightsGr.Eval(tree.ngenITpu)

        #show isolations
        for ileg in [0,1]:
            hname='leg'+str(ileg+1)+'iso'
            lid=''
            if abs(vCand.m_legs[ileg].id)==11 :   lid='e'
            elif abs(vCand.m_legs[ileg].id)==13 : lid='mu'
            else : continue
            monitor.fill(hname,[lid],vCand.m_legs[ileg].relIso,weight)

        tags=[vCand.tag]
        monitor.fill('nvtxraw',tags, tree.nvtx,               1.0)
        monitor.fill('nvtx',   tags, tree.nvtx,               weight)
        monitor.fill('vmass',  tags, vCand.p4.M(),            weight)
        monitor.fill('vpt',    tags, vCand.p4.Pt(),           weight)
        monitor.fill('leg1pt', tags, vCand.m_legs[0].p4.Pt(), weight)
        monitor.fill('leg2pt', tags, vCand.m_legs[1].p4.Pt(), weight)

        for var in ['','lesup','lesdown','jesup','jesdown','jerup','jerdown','umetup','umetdown']:
            mtVar=vCand.computeMt(var)
            monitor.fill('vmt', [vCand.tag+var], mtVar, weight)


        if saveSummary :
            values=[
                vCand.id, weight, tree.nvtx, len(selJets),
                vCand.p4.M(), vCand.mt, vCand.p4.Pt(), genBosonP4.M(), genBosonP4.Pt(),
                vCand.m_legs[0].p4.Pt(),vCand.m_legs[0].p4.Eta(),vCand.m_legs[0].p4.Phi(), vCand.m_legs[0].genP4.Pt(), vCand.m_legs[0].relIso,
                vCand.m_legs[1].p4.Pt(),vCand.m_legs[1].p4.Eta(),vCand.m_legs[1].p4.Phi(), vCand.m_legs[1].genP4.Pt(), vCand.m_legs[1].relIso,
                metCand.sumet, ht,
                metCand.p4Vars['lesup'].Pt(),metCand.p4Vars['lesdown'].Pt(),metCand.p4Vars['jesup'].Pt(),metCand.p4Vars['jesdown'].Pt(),metCand.p4Vars['jerup'].Pt(),metCand.p4Vars['jerdown'].Pt(),metCand.p4Vars['umetup'].Pt(),metCand.p4Vars['umetdown'].Pt()
                ]
            summaryTuple.Fill(array.array("f",values))

    file.Close()
    monitor.close()