def __init__(self,jind=0):

        self.py = pythia8.Pythia("", False)
        self.py.readString("SoftQCD:nonDiffractive = on")
        self.py.readString("Beams:eCM = 13000")
        self.py.readString("Print:quiet = on")
        self.py.readString("Random:setSeed = on")
        self.py.readString("Random:seed = "+str(jind))
        self.py.init()
예제 #2
0
def create_and_init_pythia(config_strings=[]):
	pythia = pythia8.Pythia()
	for s in config_strings:
		pythia.readString(s)
	for extra_s in ["Next:numberShowEvent = 0", "Next:numberShowInfo = 0", "Next:numberShowProcess = 0", "Next:numberCount = 0"]:
		pythia.readString(extra_s)
	if pythia.init():
		return pythia
	return None
예제 #3
0
def run(nevents, mass, width, debug=False):
    """ Run pythia """
    pythia = pythia8.Pythia('', debug)
    if not debug:
        pythia.readString('Init:showProcesses = off')
        pythia.readString('Init:showMultipartonInteractions = off')
        pythia.readString('Init:showChangedSettings = off')
        pythia.readString('Init:showChangedParticleData = off')
        pythia.readString('Next:numberCount = 0')
        pythia.readString('Next:numberShowInfo = 0')
        pythia.readString('Next:numberShowProcess = 0')
        pythia.readString('Next:numberShowEvent = 0')
    pythia.readString('Beams:eCM = 14000.')
    pythia.readString('WeakSingleBoson:ffbar2W = on')
    pythia.readString('24:m0 = {}'.format(mass))
    pythia.readString('24:doForceWidth = on')
    pythia.readString('24:mWidth = {}'.format(width))
    pythia.readString('24:onMode = off')
    pythia.readString('24:onIfMatch = 1 2')
    pythia.readString('24:onIfMatch = 1 4')
    pythia.readString('24:onIfMatch = 3 2')
    pythia.readString('24:onIfMatch = 3 4')
    pythia.readString('PartonLevel:FSR = off')
    pythia.readString('PartonLevel:ISR = off')
    pythia.readString('PartonLevel:MPI = off')
    pythia.readString('HadronLevel:all = off')
    pythia.readString('PartonLevel:Remnants = off')
    pythia.readString('Check:event = off')
    pythia.init()

    for iEvent in range(nevents):
        if not pythia.next():
            continue

        particles = []
        for particle in pythia.event:
            particles.append({
                'status': particle.status(),
                'isFinal': particle.isFinal(),
                'px': particle.px(),
                'py': particle.py(),
                'pz': particle.pz(),
                'e': particle.e(),
                'id': particle.id(),
            })

        event = {
            'eventNumber': iEvent,
            'wMass': mass,
            'wWidth': width,
            'particles': particles,
        }
        yield event

    if debug:
        pythia.stat()
예제 #4
0
def create_and_init_pythia(config_strings=[]):
    pythia = pythia8.Pythia()
    extra_s = [
        "Next:numberShowEvent = 0", "Next:numberShowInfo = 0",
        "Next:numberShowProcess = 0"
    ]
    config_strings.extend(extra_s)
    for s in config_strings:
        pythia.readString(s)
    if pythia.init():
        print('[i] pythia initialized with', config_strings)
        return pythia
    return None
예제 #5
0
def create_and_init_pythia(config_strings=[]):
    pythia = pythia8.Pythia()
    extra_s = [
        "Next:numberCount = 0", "Next:numberShowEvent = 0",
        "Next:numberShowInfo = 0", "Next:numberShowProcess = 0",
        "Stat:showProcessLevel = on"
    ]
    config_strings.extend(extra_s)
    for s in config_strings:
        pythia.readString(s)
    print("[i] strings read to PYTHIA ", [config_strings])
    if pythia.init():
        print('[i] pythia initialized with', config_strings)
        return pythia
    return None
예제 #6
0
def test_Pythia8():
    try:
        pythia = p8.Pythia()
    except ImportError:
        return 0
    pythia.readString("WeakSingleBoson:ffbar2gmZ = on")
    pythia.readString("Beams:idA =  11")
    pythia.readString("Beams:idB = -11")
    pythia.readString("Beams:eCM =  91.2")
    pythia.init()
    p8tohm = Pythia8ToHepMC3()
    p8tohm.m_store_pdf = True
    out = hm.WriterAscii(python_label() + "test_Pythia.hepmc")
    for iEvent in range(0, 100):
        if not pythia.next():
            continue
        nCharged = 0
        evt = hm.GenEvent()
        p8tohm.fill_next_event1(pythia, evt, iEvent)
        out.write_event(evt)
        evt.clear()
    pythia.stat()
    out.close()
    return 0
예제 #7
0

#==========================================================================

# The name of the MadGraph5_aMC@NLO executable.
# You must prepend this string with the path to the executable
# on your local installation, or otherwise make it available.
exe = "mg5_aMC"

# Create the histograms.
pyPtZ = pythia8.Hist("Pythia dN/dpTZ", 100, 0., 100.)
mgPtZ = pythia8.Hist("MadGraph dN/dpTZ", 100, 0., 100.)
amPtZ = pythia8.Hist("aMC@NLO dN/dpTZ", 100, 0., 100.)

# Produce leading-order events with Pythia.
pythia = pythia8.Pythia()
pythia.readString("Beams:eCM = 13000.")
pythia.readString("WeakSingleBoson:ffbar2gmZ = on")
pythia.readString("23:onMode = off")
pythia.readString("23:onIfMatch = -13 13")
pythia.readString("PhaseSpace:mHatMin = 80.")
run(pythia, pyPtZ, 100)

# Produce leading-order events with MadGraph 5.
pythia = pythia8.Pythia()
madgraph = pythia8.LHAupMadgraph(pythia, True, "madgraphrun", exe)
madgraph.readString("generate p p > mu+ mu-")
# Note the need for a blank character before "set".
madgraph.readString(" set ebeam1 6500")
madgraph.readString(" set ebeam2 6500")
madgraph.readString(" set mmll 80")
예제 #8
0
파일: gen.py 프로젝트: uc-lhcb/pv-finder
def run(lname, tEvt):
    name = "{}.root".format(lname)
    myhash = abs(hash(lname)) % 900000000
    print("Producing", tEvt, "tracks to", name, "with hash:", myhash)
    # Initialize Pythia.
    random = ROOT.TRandom3(myhash)
    pythia = pythia8.Pythia("", False)
    pythia.readString("Random:seed = {}".format(myhash))
    pythia.readString("Print:quiet = on")
    pythia.readString("SoftQCD:all = on")
    pythia.init()
    module = velo.ModuleMaterial("dat/run3.root")
    rffoil = velo.FoilMaterial("dat/run3.root")
    scatter = Scatter()

    # Create the output TFile and TTree.
    tfile = ROOT.TFile(name, "RECREATE")
    ttree = ROOT.TTree("data", "")

    # New interface
    # Create the writer handler and add branches
    writer = Writer(ttree)
    writer.add("pvr_x")
    writer.add("pvr_y")
    writer.add("pvr_z")
    writer.add("svr_x")
    writer.add("svr_y")
    writer.add("svr_z")
    writer.add("svr_pvr")
    writer.add("hit_x")
    writer.add("hit_y")
    writer.add("hit_z")
    writer.add("hit_prt")
    writer.add("prt_pid")
    writer.add("prt_px")
    writer.add("prt_py")
    writer.add("prt_pz")
    writer.add("prt_e")
    writer.add("prt_x")
    writer.add("prt_y")
    writer.add("prt_z")
    writer.add("prt_hits")
    writer.add("prt_pvr")
    writer.add("ntrks_prompt")


    number_rejected_events = 0

    # Fill the events.

    ttime = 0
    for iEvt in range(tEvt):
        start = time.time()
        ipv = 0
        npv = 0
        target_npv = np.random.poisson(7.6)
        iEvt += 1

        while npv < target_npv:
            if not pythia.next():
                continue

            # All distance measurements are in units of mm
            xPv, yPv, zPv = (
                random.Gaus(0, 0.055),
                random.Gaus(0, 0.055),
                random.Gaus(100, 63),
            )  # normal LHCb operation

            # pvr x and y spead can be found https://arxiv.org/pdf/1410.0149.pdf page 42. z dependent
            ## [-1000,-750, -500, -250] # mm

            writer["pvr_x"].append(xPv)
            writer["pvr_y"].append(yPv)
            writer["pvr_z"].append(zPv)
            number_of_detected_particles = 0
            # find heavy flavor SVs
            for prt in pythia.event:
                if not heavyFlavor(prt.id()):
                    continue
                # TODO: require particles with hits from the SVs
                writer["svr_x"].append(prt.xDec() + xPv)
                writer["svr_y"].append(prt.yDec() + yPv)
                writer["svr_z"].append(prt.zDec() + zPv)
                writer["svr_pvr"].append(ipv)

            for prt in pythia.event:
                if not prt.isFinal or prt.charge() == 0:
                    continue
                if not prtStable(prt.id()):
                    continue
                if abs(prt.zProd()) > 1000:
                    continue
                if (prt.xProd() ** 2 + prt.yProd() ** 2) ** 0.5 > 40:
                    continue
                if prt.pAbs() < 0.1:
                    continue
                prt.xProd(
                    prt.xProd() + xPv
                )  # Need to change the origin of the event before getting the hits
                prt.yProd(prt.yProd() + yPv)
                prt.zProd(prt.zProd() + zPv)
                hits = Hits(module, rffoil, scatter, prt)
                if len(hits) == 0:
                    continue
                if len(hits) > 2 and abs(zPv - prt.zProd()) < 0.001:
                    number_of_detected_particles += 1
                    # if prt.pAbs() < 0.2: print 'slow!', prt.pAbs(), prt.id()
                writer["prt_pid"].append(prt.id())
                writer["prt_px"].append(prt.px())
                writer["prt_py"].append(prt.py())
                writer["prt_pz"].append(prt.pz())
                writer["prt_e"].append(prt.e())
                writer["prt_x"].append(prt.xProd())
                writer["prt_y"].append(prt.yProd())
                writer["prt_z"].append(prt.zProd())
                writer["prt_pvr"].append(ipv)
                writer["prt_hits"].append(len(hits))
                for xHit, yHit, zHit in hits:
                    # xHit_recorded, yHit_recorded, zHit_recorded = np.random.uniform(-0.0275,0.0275)+xHit, np.random.uniform(-0.0275,0.0275)+yHit, zHit # normal
                    xHit_recorded, yHit_recorded, zHit_recorded = (
                        np.random.normal(0, 0.012) + xHit,
                        np.random.normal(0, 0.012) + yHit,
                        zHit,
                    )  # normal
                    writer["hit_x"].append(xHit_recorded)
                    writer["hit_y"].append(yHit_recorded)
                    writer["hit_z"].append(zHit_recorded)
                    writer["hit_prt"].append(len(writer["prt_e"]) - 1)
            # if number_of_detected_particles < 5: iEvt -= 1; number_rejected_events+=1; continue
            writer["ntrks_prompt"].append(number_of_detected_particles)
            ipv += 1
            if number_of_detected_particles > 0:
                npv += 1

        itime = time.time() - start
        ttime += itime
        if iEvt % 100 == 0:
          print(
            "{} Evt {}/{}, {:3} PVs, {:3} tracks in {:.3} s".format(
                name, iEvt, tEvt, npv, len(writer["pvr_z"]), itime
            )
        )
        writer.write()

    # Write and close the TTree and TFile.
    ttree.Print()
    ttree.Write(ttree.GetName(), ROOT.TObject.kOverwrite)
    tfile.Close()
    return ttime
예제 #9
0
def main07():

    # Pythia generator.
    pythia = pythia8.Pythia()

    # A class to generate the fictitious resonance initial state.
    sigma1GenRes = Sigma1GenRes()

    # Hand pointer to Pythia.
    pythia.setSigmaPtr(sigma1GenRes)

    # Read in the rest of the settings and data from a separate file.
    pythia.readFile("main07.cmnd")

    # Initialization.
    pythia.init()

    # Extract settings to be used in the main program.
    nEvent = pythia.mode("Main:numberOfEvents")
    nAbort = pythia.mode("Main:timesAllowErrors")

    # Histogram particle spectra.
    eGamma = pythia8.Hist("energy spectrum of photons", 100, 0., 250.)
    eE = pythia8.Hist("energy spectrum of e+ and e-", 100, 0., 250.)
    eP = pythia8.Hist("energy spectrum of p and pbar", 100, 0., 250.)
    eNu = pythia8.Hist("energy spectrum of neutrinos", 100, 0., 250.)
    eRest = pythia8.Hist("energy spectrum of rest particles", 100, 0., 250.)

    # Begin event loop.
    iAbort = 0
    for iEvent in range(0, nEvent):

        # Generate events. Quit if many failures.
        if not pythia.next():
            iAbort += 1
            if iAbort < nAbort: continue
            print(" Event generation aborted prematurely, owing to error!")
            break

        # Loop over all particles and analyze the final-state ones.
        for i in range(0, pythia.event.size()):
            if pythia.event[i].isFinal():
                idAbs = pythia.event[i].idAbs()
                eI = pythia.event[i].e()
                if idAbs == 22:
                    eGamma.fill(eI)
                elif idAbs == 11:
                    eE.fill(eI)
                elif idAbs == 2212:
                    eP.fill(eI)
                elif (idAbs == 12 or idAbs == 14 or idAbs == 16):
                    eNu.fill(eI)
                else:
                    eRest.fill(eI)
                    print(" Error: stable id = %d" % pythia.event[i].id())

    # Final statistics and histograms.
    pythia.stat()
    eGamma *= 2.5 / nEvent
    eE *= 2.5 / nEvent
    eP *= 2.5 / nEvent
    eNu *= 2.5 / nEvent
    eRest *= 2.5 / nEvent
    #print(eGamma,eE,eP,eNu,eRest)

    # Write Python code that can generate a PDF file with the spectra.
    # Assuming you have Python installed on your platform, do as follows.
    # After the program has run, type "python main07plot.py" (without the " ")
    # in a terminal window, and open "out07plot.pdf" in a PDF viewer.
    hpl = pythia8.HistPlot("main07plot")
    hpl.frame(
        "out07plot", "Particle energy spectra", "$E$ (GeV)",
        "$(1/N_{\\mathrm{event}}) \\mathrm{d}N / \\mathrm{d}E$ (GeV$^{-1}$)")
    hpl.add(eGamma, "-", "$\\gamma$")
    hpl.add(eE, "-", "$e^{\\pm}$")
    hpl.add(eP, "-", "$p/\\overline{p}$")
    hpl.add(eNu, "-", "$\\nu$")
    hpl.add(eRest, "-", "others")
    # Use logarithmic y scale.
    hpl.plot(True)
예제 #10
0
    def RunPythia(self):
        pythia = pythia8.Pythia()
        sigma1GenRes = Sigma1GenRes()
        pythia.setSigmaPtr(sigma1GenRes)
        pythia.readFile("inj.cmnd")
        s0 = str(self.eCM)
        s1 = str(self.eCM * 0.01)
        pythia.readString("Beams:eCM = " + s0)
        pythia.readString("999999:all = GeneralResonance void 1 0 0 " + s0 +
                          " " + s1 + " 0. 0. 0.")
        if (self.mode == 1):
            pythia.readString(
                "999999:addChannel = 1 1. 101 22 22  !  -> gamma gamma")
        elif (self.mode == 2):
            pythia.readString(
                "999999:addChannel = 1 1. 101 11 -11 !  -> e+ e-")
        elif (self.mode == 3):
            pythia.readString(
                "999999:addChannel = 1 1. 101 15 -15 !  -> tau+ tau-")
        elif (self.mode == 4):
            pythia.readString(
                "999999:addChannel = 1 1. 101 5  -5  !  -> b bbar")
        elif (self.mode == 5):
            pythia.readString(
                "999999:addChannel = 1 1. 101 24 -24 !  -> W+ W-")
        elif (self.mode == 6):
            pythia.readString(
                "999999:addChannel = 1 1. 101 13 -13 !  -> mu+ mu-")
        else:
            print("error: only gamma, e, tau, b, W and mu are supported")
            sys.exit(1)
        pythia.init()

        nEvent = pythia.mode("Main:numberOfEvents")
        nAbort = pythia.mode("Main:timesAllowErrors")

        iAbort = 0
        for iEvent in range(0, nEvent):

            if not pythia.next():
                iAbort += 1
                if iAbort < nAbort: continue
                print(" Event generation aborted prematurely, owing to error!")
                break

            # Loop over all particles and analyze the final-state ones.
            for i in range(0, pythia.event.size()):
                if pythia.event[i].isFinal():
                    idAbs = pythia.event[i].idAbs()
                    eI = pythia.event[i].e()
                    if idAbs == 22:
                        self.eGamma.fill(eI)
                    elif idAbs == 11:
                        self.eE.fill(eI)
                    elif idAbs == 2212:
                        self.eP.fill(eI)
                    elif (idAbs == 12 or idAbs == 14 or idAbs == 16):
                        self.eNu.fill(eI)
                    else:
                        self.eRest.fill(eI)
                        print(" Error: stable id = %d" % pythia.event[i].id())

        # Final statistics and histograms.
        pythia.stat()
        self.eGamma *= 1 / (self.dlnerg * nEvent)
        self.eE *= 1 / (self.dlnerg * nEvent)
        self.eP *= 1 / (self.dlnerg * nEvent)
        self.eNu *= 1 / (self.dlnerg * nEvent)
        self.eRest *= 1 / (self.dlnerg * nEvent)
        if (self.verbose > 0):
            print(self.eGamma, self.eE, self.eP, self.eNu, self.eRest)

        if (self.verbose > 1):
            # Write Python code that can generate a PDF file with the spectra.
            # Assuming you have Python installed on your platform, do as follows.
            # After the program has run, type "python main07plot.py" (without the " ")
            # in a terminal window, and open "out07plot.pdf" in a PDF viewer.
            hpl = pythia8.HistPlot("main07plot")
            hpl.frame(
                "out07plot", "Particle energy spectra", "$E$ (GeV)",
                "$(1/N_{\\mathrm{event}}) \\mathrm{d}N / \\mathrm{d}\ln E$)")
            hpl.add(self.eGamma, "-", "$\\gamma$")
            hpl.add(self.eE, "-", "$e^{\\pm}$")
            hpl.add(self.eP, "-", "$p/\\overline{p}$")
            hpl.add(self.eNu, "-", "$\\nu$")
            #hpl.add( self.eRest, "-", "others")
            # Use logarithmic y scale.
            hpl.plot(False)
예제 #11
0
    p = prt.pAbs()
    if p == 0: return hits
    vx, vy, vz = prt.xProd(), prt.yProd(), prt.zProd(),
    px, py, pz = prt.px() / p, prt.py() / p, prt.pz() / p
    hit = mtr.intersect(vx, vy, vz, px, py, pz)
    while hit.T() != 0:
        vx, vy, vz = hit.X(), hit.Y(), hit.Z()
        hits += [[vx, vy, vz]]
        vx, vy, vz = vx + px * 0.1, vy + py * 0.1, vz + pz * 0.1
        hit = mtr.intersect(vx, vy, vz, px, py, pz)
    return hits


# Initialize Pythia.
random = ROOT.TRandom3()
pythia = pythia8.Pythia('', False)
pythia.readString('Print:quiet = on')
pythia.readString('SoftQCD:all = on')
pythia.init()
material = velo.ModuleMaterial('/Users/weisser/MIT_Dropbox/LbVMWeisser_shared/'
                               'Tracking/Simulated_Velo/fastsim/dat/run3.root')

# Create the output TFile and TTree.
tfile = ROOT.TFile(save_path + 'pvs_weisser.root', 'RECREATE')
#tfile = ROOT.TFile(save_path+'pvs_weisser_test2.root', 'RECREATE')
#tfile = ROOT.TFile(save_path+'pvs_weisser_easy.root', 'RECREATE')
#tfile = ROOT.TFile(save_path+'pvs_weisser_1M.root', 'RECREATE')
ttree = ROOT.TTree('data', '')

# Create the writer handler, add branches, and initialize.
writer = Writer()
예제 #12
0
import sys, time, array
import socket
import pythia8
import pickle
from ROOT import TLorentzVector, TGenPhaseSpace

ISDEB = 0
system_name = socket.gethostname()
if len(sys.argv) > 1: jobid = int(sys.argv[1])
else:
    jobid = 0
    ISDEB = 1

particles = []

py = pythia8.Pythia("", False)
py.readString("HardQCD:hardbbbar = on")
py.readString("Beams:eCM = 14000")
py.readString("Print:quiet = on")
py.readString("Random:setSeed = on")
py.readString("Random:seed = " + str(jobid))
py.init()


def toLV(track):
    lv = TLorentzVector()
    lv.SetPxPyPzE(track.px() * 1000,
                  track.py() * 1000,
                  track.pz() * 1000,
                  track.e() * 1000)  ## in MeV!
    return lv