def pythia_sim(cmd_file, part_name="unnamed", make_plots=False):
    # The main simulation. Takes a cmd_file as input. part_name 
    # is the name of the particle we're simulating decays from.
    # Only necessary for titling graphs.
    # Returns an array of 2D histograms, mapping eta, phi, with transverse
    # energy.
    pythia = Pythia(cmd_file, random_state=1)
    selection = ((STATUS == 1) & ~HAS_END_VERTEX)
    unclustered_particles    = []
    a                        = 0
    part_tensor              = []
    for event in pythia(events=num_events):
        jets_particle_eta    = []
        jets_particle_phi    = []
        jets_particle_energy = []
        vectors              = event.all(selection)
        sequence             = cluster(vectors, R=1.0, p=-1, ep=True)
        jets                 = sequence.inclusive_jets()
        unclustered_particles.append(sequence.unclustered_particles())
        part_data = []
        num_b_jets = 0
        for i, jet in enumerate(jets):
            if     np.abs(jet.userinfo[pid]) == 5:   num_b_jets += 1
            data = np.array((jet.mass, jet.eta, jet.phi, jet.pt))
            if     is_massless_or_isolated(jet): discarded_data.append(jet)
            else:  part_data.extend(data)
        # Calculate total number of b and non-b jets in the event
        # Histogram the particle data
        part_data = np.array(part_data)
        hist_array = hist_jet_vals(part_data) # is y-axis jet num or event num

    return np.array(part_tensor)
def generator(cut=0.0):
    params = {
        "Beams:idA": "11",
        "Beams:idB": "-11",
        "Beams:eCM": 91.1876,
        "WeakSingleBoson:ffbar2gmZ": "on",
        "23:onMode": "off",
        "23:onIfAny": "1 2 3 4 5",
        "PDF:lepton": "off"
    }
    pythia = Pythia(params=params)  #, random_state=1)

    # Consider only final-state particles
    selection = ((STATUS == 1) & ~HAS_END_VERTEX)

    # Array of pseudo-jets or particles to cluster
    particles = []
    array = []

    # Begin event loop. Generate events
    for event in pythia(events=1):
        array = event.all(selection)

    #For testing: filter out particles by energy
    particles = array[array["E"] > cut]

    return particles
Beispiel #3
0
def pythia_sim(cmd_file, part_name="", make_plots=False):
    # The main simulation. Takes a cmd_file as input. part_name
    # is the name of the particle we're simulating decays from.
    # Only necessary for titling graphs.
    # Returns an array of 2D histograms, mapping eta, phi, with transverse
    # energy.
    if part_name == "":
        for char in cmd_file:
            if char == ".":
                break
            else:
                part_name += char
    pythia = Pythia(cmd_file, random_state=1)
    selection = ((STATUS == 1) & ~HAS_END_VERTEX)
    unclustered_particles = []
    part_tensor = []
    a = 0
    for event in pythia(events=num_events):
        jets_particle_eta = []
        jets_particle_phi = []
        jets_particle_energy = []
        vectors = event.all(selection)
        sequence = cluster(vectors, R=1.0, p=-1, ep=True)
        jets = sequence.inclusive_jets()
        unclustered_particles.append(sequence.unclustered_particles())
        part_data = []
        for i, jet in enumerate(jets):
            part_data = return_particle_data(jet)
            if is_massless_or_isolated(jet):
                discarded_data.append(jet)
            else:
                jets_particle_eta.extend(part_data[0])
                jets_particle_phi.extend(part_data[1])
                jets_particle_energy.extend(part_data[2])
        plt.figure()
        part_tensor.append(
            plt.hist2d(jets_particle_eta,
                       jets_particle_phi,
                       weights=jets_particle_energy,
                       density=True,
                       range=[(-5, 5), (-1 * np.pi, np.pi)],
                       bins=(20, 32),
                       cmap='binary')[0])  # We're only taking the
        if not make_plots:
            plt.close(
            )  # Zeroth element, which is the raw data of the 2D Histogram
        if make_plots:
            plt.xlabel("$\eta$")
            plt.ylabel("$\phi$")
            plt.title("Particles from " + part_name)
            cbar = plt.colorbar()
            cbar.set_label('Tranverse Energy of Each Particle ($GeV$)')
            plt.savefig("hists/Jets_Particles_" + part_name + str(a) + ".png")
            plt.close()
        a += 1
    return np.array(part_tensor)
def pythia_sim(cmd_file, part_name="unnamed", make_plots=False):
    # The main simulation. Takes a cmd_file as input. part_name 
    # is the name of the particle we're simulating decays from.
    # Only necessary for titling graphs.
    # Returns an array of 2D histograms, mapping eta, phi, with transverse
    # energy.
    pythia = Pythia(cmd_file, random_state=1)
    selection = ((STATUS == 1) & ~HAS_END_VERTEX)
    unclustered_particles = []
    a = 0
    part_tensor = []
    sj_data_per_event = []
    for event in pythia(events=num_events):
        lead_jet_invalid = False
        sub_jet_data = [] # There are multiple jets in each event
        jets_particle_eta = []
        jets_particle_phi = []
        jets_particle_energy = []
        vectors = event.all(selection)
        sequence = cluster(vectors, R=1.0, p=-1, ep=True)
        jets = sequence.inclusive_jets()
        unclustered_particles.append(sequence.unclustered_particles())
        part_data = []
        for i, jet in enumerate(jets):
            jet_data = (
                jet.mass, jet.eta, jet.phi, jet.pt,
                len(jet.constituents_array()), 2*jet.mass/jet.pt
            )
            part_data = return_particle_data(jet)
            if is_massless_or_isolated(jet):
                discarded_data.append(jet)
                if i == 0: lead_jet_invalid = True
            else:
                jets_particle_eta.extend(part_data[0])
                jets_particle_phi.extend(part_data[1])
                jets_particle_energy.extend(part_data[2])
            if i < 3:
                sub_jet_data.append(jet_data)
        lead_jet_valid = not lead_jet_invalid
        if lead_jet_valid:
            sj_data_per_event.append(np.array(sub_jet_data))
            plt.figure()
            part_tensor.append(plt.hist2d(jets_particle_eta, jets_particle_phi,
                        weights=jets_particle_energy, normed=True,
                        range=[(-5,5),(-1*np.pi,np.pi)],
                        bins=(20,32), cmap='binary')[0]) # We're only taking the
            plt.close() # Zeroth element, which is the raw data of the 2D Histogram
            if make_plots:
                plt.xlabel("$\eta$")
                plt.ylabel("$\phi$")
                plt.title("Particles from "+part_name)
                cbar = plt.colorbar()
                cbar.set_label('Tranverse Energy of Each Particle ($GeV$)')
                plt.savefig("hists/Jets_Particles_"+part_name+str(a)+".png")
            a += 1
    return np.array(part_tensor), np.array(sj_data_per_event)
Beispiel #5
0
def pythia_sim(cmd_file):
    # The main simulation. Takes a cmd_file as input.
    pythia = Pythia(cmd_file, random_state=1)
    selection = ((STATUS == 1) & ~HAS_END_VERTEX)
    unclustered_particles = []
    for event in pythia(events=num_events):
        vectors = event.all(selection)
        sequence = cluster(vectors, R=0.4, p=-1, ep=True)
        jets = sequence.inclusive_jets()
        print(NoneType_statistics(jets, debug_data))
Beispiel #6
0
def test_first_example():
    pythia = Pythia(get_cmnd('w'), random_state=1)

    selection = ((STATUS == 1) & ~HAS_END_VERTEX & (ABS_PDG_ID != 12) &
                 (ABS_PDG_ID != 14) & (ABS_PDG_ID != 16))

    # generate events while writing to ascii hepmc
    for event in hepmc_write('events.hepmc', pythia(events=1)):
        array1 = event.all(selection)

    # read the same event back from ascii hepmc
    for event in hepmc_read('events.hepmc'):
        array2 = event.all(selection)

    assert_array_equal(array1, array2)
Beispiel #7
0
def get_group_events(name, num_events, seed, train):
    # Generate group of Monte Carlo simulated proton-antiproton collision events
    # at the LHC, composed by particle readings (px,py,pz,e,m).
    # Input: name.cmnd config file for Pythia simulator.
    # generate events while writing to ascii hepmc
    momentum_four = ['px', 'py', 'pz', 'E']  #'mass', 'pdgid'
    group_events = []
    pythia = Pythia(os.path.join('./data/cfgs/', name + '.cmnd'),
                    random_state=seed)
    for event in hepmc_write('events.hepmc', pythia(events=num_events)):
        particles = event.all()
        if train == True:
            # If training, then return only background signals, not Higgs reading.
            particles = particles[particles['pdgid'] != 25]
        # Filter and transform np structured array to ndarray
        X = particles[momentum_four].copy()
        particles = X.view(np.float64).reshape(X.shape + (-1, ))
        group_events.append(particles)
    return group_events
Beispiel #8
0
def pythia_sim(cmd_file, part_name="", make_plots=False):
    # The main simulation. Takes a cmd_file as input. part_name
    # is the name of the particle we're simulating decays from.
    # Only necessary for titling graphs.
    # Returns an array of 2D histograms, mapping eta, phi, with transverse
    # energy.
    debug_data = [
    ]  # Deprecated but costs 1 operation per function call so negligble
    event_data = []  # Event data -> the leading jet(s) information
    sub_jet_data = []  # Continer for the multiple jets in each event
    discarded_data = [
    ]  # For analyzing what is thrown out from function is_massless_or_isolated
    unclustered_particles = []
    pythia = Pythia(cmd_file, random_state=1)
    selection = ((STATUS == 1) & ~HAS_END_VERTEX)
    for event in pythia(events=num_events):
        jetpts = []
        vectors = event.all(selection)
        sequence = cluster(vectors, R=0.4, p=-1,
                           ep=True)  # R is radius of jets.
        jets = sequence.inclusive_jets()
        unclustered_particles.append(sequence.unclustered_particles())
        for i, jet in enumerate(jets):
            data = (jet.mass, jet.eta, jet.phi, jet.pt,
                    len(jet.constituents_array()), 2 * jet.mass / jet.pt)
            if data[5] > 0.4:
                debug_data.append((jet, data))
            if is_massless_or_isolated(jet):
                discarded_data.append(jet)
            else:
                if i < top_i_jets:  # Todo: Append the leading 3 jets of the event
                    event_data.append(data)
                sub_jet_data.append(data)
    if make_plots:
        event_data = np.array(event_data)
        sub_jet_data = np.array(sub_jet_data)
        make_the_plots(event_data, sub_jet_data, part_name)
    event_data = np.array(event_data)
    sub_jet_data = np.array(sub_jet_data)
    return event_data, sub_jet_data
Beispiel #9
0
def pythia_sim(cmd_file, part_name=""):
    # The main simulation. Takes a cmd_file as input. part_name
    # is the name of the particle we're simulating decays from.
    # Only necessary for titling graphs.
    # Returns an array of 2D histograms, mapping eta, phi, with transverse
    # energy.
    pythia = Pythia(cmd_file, random_state=1)
    selection = ((STATUS == 1) & ~HAS_END_VERTEX)
    unclustered_particles = []
    debug_data = [
    ]  # Deprecated but costs 1 operation per function call so negligble
    discarded_data = [
    ]  # For analyzing what gets thrown out from function is_massless_or_isolated
    sj_data_per_event = []  # sub jet data indexed into each event

    for event in pythia(events=num_events):
        lead_jet_invalid = False
        sub_jet_data = []  # There are multiple jets in each event
        vectors = event.all(selection)
        sequence = cluster(
            vectors, R=0.4, p=-1,
            ep=True)  # Note to self: R might need to be changed to 1
        jets = sequence.inclusive_jets()
        unclustered_particles.append(sequence.unclustered_particles())

        for i, jet in enumerate(jets):
            data = (jet.mass, jet.eta, jet.phi, jet.pt,
                    len(jet.constituents_array()), 2 * jet.mass / jet.pt)
            if data[5] > 0.4:
                debug_data.append((jet, data))
            if is_massless_or_isolated(jet):
                discarded_data.append(jet)
                if i == 0: lead_jet_invalid = True
            if i < 3:
                sub_jet_data.append(data)
        if not lead_jet_invalid:
            sj_data_per_event.append(np.array(sub_jet_data))
    sj_data_per_event = np.array(sj_data_per_event)
    return sj_data_per_event
Beispiel #10
0
def generate_events(config_path, nevents):
    '''
    Arguments:
    ----------
        config_path:
        nevents:

    Returns:
    --------
        events_particles:
        events_weights:
    '''
    pythia = Pythia(config_path, verbosity=1)
    variations = pythia.weight_labels
    if variations == ['']:
        variations = ['Baseline']  # to match hard-coded decision in Pythia

    # only consider final state particles that are not neutrinos
    selection = ((STATUS == 1) & ~HAS_END_VERTEX &  # final state
                 (ABS_PDG_ID != 12) & (ABS_PDG_ID != 14) & (ABS_PDG_ID != 16)
                 )  # not a neutrino

    # placeholders for particles and weights
    events_particles = []
    events_weights = []
    # generate events from pythia
    for event in pythia(events=nevents):
        events_weights.append(event.weights.astype('float32'))
        events_particles.append(event.all(selection))
    # convert to numpy arrays for usability
    events_weights = np.array(events_weights)
    # defaults to 'f0' if no variations are specified!!
    events_weights = events_weights.view(dtype=[(n, 'float32')
                                                for n in variations])
    events_particles = np.array(events_particles)

    return events_particles, events_weights
Beispiel #11
0
def pythia_sim(cmd_file, part_name=""):
    # The main simulation. Takes a cmd_file as input. part_name
    # is the name of the particle we're simulating decays from.
    # Only necessary for titling graphs.
    # Returns an array of 2D histograms, mapping eta, phi, with transverse
    # energy.
    pythia = Pythia(cmd_file, random_state=1)
    if part_name == "higgsWW":
        events_data_package = event_hists("ff2HffTww")
        higgs_data_package = higgs_hists("higgsww")
    else:
        events_data_package = event_hists("ff2HffTzz")
        higgs_data_package = higgs_hists("higgszz")
    bquarksAtEvent = []
    bjetsAtEvent = []
    otherJetsAtEvent = []
    for event in pythia(events=num_events):
        bjets = []
        bquarks = []
        otherjets = []
        final_state_selection = ((STATUS == 1) & ~HAS_END_VERTEX &
                                 (ABS_PDG_ID != 12) & (ABS_PDG_ID != 14) &
                                 (ABS_PDG_ID != 16))
        particles = event.all(return_hepmc=True)
        for particle in particles:
            update(bquarks, higgs_data_package, particle)
        jet_inputs = event.all(final_state_selection)
        jet_sequence = cluster(jet_inputs, ep=True, R=0.4, p=-1)
        jets = jet_sequence.inclusive_jets(ptmin=20)
        for jet in jets:
            update_if_bjet(jet, bquarks, events_data_package, bjets, otherjets)
        bquarksAtEvent.append(bquarks)
        bjetsAtEvent.append(bjets)
        otherJetsAtEvent.append(otherjets)
    higgs_data_package.save_1d_hists()
    higgs_dat.append(higgs_data_package)
    return events_data_package, bquarksAtEvent, bjetsAtEvent, otherJetsAtEvent
Beispiel #12
0
# ----------------------------------------------------------------------
# Import Statements
# ----------------------------------------------------------------------
import numpy as np
import matplotlib
import pandas as pd
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from numpythia import Pythia, hepmc_write, hepmc_read
from numpythia import STATUS, HAS_END_VERTEX, ABS_PDG_ID
from numpythia.testcmnd import get_cmnd
from numpy.testing import assert_array_equal
# ----------------------------------------------------------------------
# Constant Definitions
# ----------------------------------------------------------------------
pythia = Pythia(get_cmnd('w'), random_state=1)
pdg_to_part = {
   1  : 'd',
   2  : 'u',
   3  : 's',
   4  : 'c',
   5  : 'b',
   6  : 't',
   7  : 'b\'',
   8  : 't\'',
   11 : 'e^-',  
   12 : 'v_e', 
   13 : 'mu^-',  
   14 : 'v_mu', 
   15 : 't^-', 
   16 : 'v_t', 
Beispiel #13
0
                        help="The random seed to initialize with")
    parser.add_argument('--nevent',
                        type=int,
                        default=10,
                        help="The number of events to generate")
    parser.add_argument('--out', help="The output npy file")
    args = parser.parse_args()

    try:
        os.makedirs(os.path.dirname(args.out))
    except OSError as e:
        import errno
        if e.errno != errno.EEXIST:
            raise

    pythia = Pythia(args.config, random_state=args.seed)

    # for some stupid reason there has to be at least two terms for
    # this selection thing to work.
    sel = (STATUS == 1) & ~HAS_END_VERTEX & (ABS_PDG_ID != 12) & (
        ABS_PDG_ID != 14) & (ABS_PDG_ID != 16)

    dtype = [('ntrk1', int), ('ntrk2', int)] + [('wt_%s' % l, float)
                                                for l in pythia.weight_labels]
    results = []
    for ievt, event in enumerate(pythia(events=args.nevent)):
        if ievt % 100 == 0:
            print("Processing event %d/%d" % (ievt, args.nevent))

        weights = list(event.weights)
Beispiel #14
0
from numpythia import Pythia, ABS_PDG_ID

#selection = ( (ABS_PDG_ID == 310) )
params = {"softQCD:all": "on", "Beams:eCM": 13000}

# dtype=[('E', '<f8'), ('px', '<f8'), ('py', '<f8'), ('pz', '<f8'), ('mass', '<f8'), ('prodx', '<f8'), ('prody', '<f8'), ('prodz', '<f8'), ('prodt', '<f8'), ('pdgid', '<i4'), ('status', '<i4')])
i = 0
out = []
for event in Pythia(params=params):
    ks0s = filter(lambda x: x[-2] == 310, event.all())
    if len(ks0s):
        out.extend(ks0s)
        i += 1
    if i == 100: break

## ASSUME KS0S COME FROM X,Y,Z = 0, 0, 0
## DECAY THEM FOLLOWING PROPER LIFETIME EXPONENTIAL DECAY:
## TAKE KS0 LIFETIME. WITH EXPONENTIAL DISTRIBUTION, DETERMINE (RANDOM) LIFETIME (EXPLORE TRandom3 in ROOT) TRandom3().Expo(life)
## CALCULATE DECAY POINT (USE BOOST)

## ALEXANDRE
## plot fraction in theta<400, z decay<500 mm for 8,13,14,27 TeV for k+, ks, sigma, lambda

## ADRIAN
## DECAY THEM WITH ROOT TGenPhaseSpace (setDecay to pipiee)
## THEN SMEAR MOMENTUM OF PIONS ACCORDING TO LHCB RESOLUTION, USE 1% FOR PIONS AND 5% FOR ELECTRONS. USE TRandom3().Gauss(momento_true,reso)
## COMPUTE KS0 MASS IN BOTH CASES. (RECO WITH STANDARD MASS, AFTER USING 'TRICK')
Beispiel #15
0
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from pyjet import cluster


def print_debug_data(dd):
    for tup in dd:
        j = tup[1]
        print("Mass = ", j[0], "\tpT = ", j[3], "\tEffR = ", j[5])


# -----------------------------------------------------------------------
# Generate Events
# -----------------------------------------------------------------------
pythia = Pythia('zz.cmnd', random_state=1)
selection = ((STATUS == 1) & ~HAS_END_VERTEX)
unclustered_particles = list()


# -----------------------------------------------------------------------
# Generate Jets and Histogram Data
# -----------------------------------------------------------------------
def is_massless_or_isolated(jet):
    # Returns true if a jet has nconsts = 1 and has a pdgid equal to that
    # of a photon or a gluon
    if len(jet.constituents_array()) == 1:
        if np.abs(jet.info['pdgid']) == 21 or np.abs(jet.info['pdgid']) == 22:
            return True
        # if a muon is outside of the radius of the jet, discard it
        if np.abs(jet.info['pdgid']) == 13:
Beispiel #16
0
    mjj = array('f', [0])
    ystarjj = array('f', [0])

    t.Branch('ptj1', ptj1, 'ptj1/F')
    t.Branch('etaj1', etaj1, 'etaj1/F')
    t.Branch('phij1', phij1, 'phij1/F')
    t.Branch('ej1', ej1, 'ej1/F')
    t.Branch('ptj2', ptj2, 'ptj2/F')
    t.Branch('etaj2', etaj2, 'etaj2/F')
    t.Branch('phij2', phij2, 'phij2/F')
    t.Branch('ej2', ej2, 'ej2/F')
    t.Branch('mjj', mjj, 'mjj/F')
    t.Branch('ystarjj', ystarjj, 'ystarjj/F')

    # generate events
    pythia = Pythia(config=runtype + '.cmd')
    events = pythia(events=nevents)
    #print(type(events))

    # loop over events
    for e in events:

        # get the event record
        allparts = e.all(return_hepmc=True)

        # get the two outgoing partons

        j1 = ROOT.TLorentzVector()
        j2 = ROOT.TLorentzVector()

        count = 0