Exemple #1
0
 def __init__(self, hostname, interfaces, mean_arrv_time, mean_pkt_size):
     
     arrv_time_distribution = functools.partial(random.expovariate, 1.0/float(mean_arrv_time))
     pkt_size_distribution  = functools.partial(random.expovariate, 1.0/float(mean_pkt_size))
     
     PacketGenerator.__init__(self,GlobalConfiguration.simpyEnv, hostname, arrv_time_distribution, pkt_size_distribution)
     
     self.hostname   = hostname
     self.interfaces = interfaces
Exemple #2
0
 def __init__(self, bandwidth, hostname):
     
     mean_arrv_rate = GlobalConfiguration.mean_arrv_rate
     mean_pkt_size  = GlobalConfiguration.mean_pkt_size
     
     arrv_time_distribution = functools.partial(random.expovariate, mean_arrv_rate)
     pkt_size_distribution  = functools.partial(random.expovariate, 1.0/float(mean_pkt_size))
     
     PacketGenerator.__init__(self, GlobalConfiguration.simpyEnv, hostname, arrv_time_distribution, pkt_size_distribution, rate = float(bandwidth))
     self.hostname = hostname
Exemple #3
0
    def set_packet_generator(self, lbd, possible_destinations):
        """
        :param lbd:
        :param possible_destinations:
        :return:
        """
        def dst_dist(gen, destinations):
            if destinations is None:
                return None
            else:
                return gen.choice(destinations)

        def next_packet_time(gen, lbd_):
            return gen.exponential(lbd_)

        packet_dst = partial(dst_dist, self.gen, possible_destinations)
        next_pkt_time = partial(next_packet_time, self.gen, lbd)
        self.packet_generator = PacketGenerator(env=self.env,
                                                id="{}_pg".format(self.id),
                                                adist=next_pkt_time,
                                                sdist=100,
                                                dstdist=packet_dst)

        ## LOOK AT THIS AGAIN - might want to consider putting it into a switch port
        self.packet_generator.out = self.packets_to_send
Exemple #4
0
    def _create_packet_generator(self, lbd, possible_destinations):
        def dstdist(gen, possible_destinations):
            if possible_destinations is None:
                return None
            else:
                return gen.choice(possible_destinations)

        def next_packet_time(gen, lbd):
            return gen.exponential(lbd)

        def packet_size():
            return 100

        dstdist_partial = partial(dstdist, self.gen, possible_destinations)
        next_packet_time_partial = partial(next_packet_time, self.gen, lbd)
        return PacketGenerator(env=self.env,
                               id="{}_pg".format(self.id),
                               adist=next_packet_time_partial,
                               sdist=packet_size,
                               dstdist=dstdist_partial)
Exemple #5
0
import simpy
from SimComponents import PacketGenerator, PacketSink, SwitchPort


def constArrival():
    return 1.5  # time interval


def constSize():
    return 100.0  # bytes


env = simpy.Environment()  # Create the SimPy environment
ps = PacketSink(env, debug=True)  # debug: every packet arrival is printed
pg = PacketGenerator(env, "SJSU", constArrival, constSize)
switch_port = SwitchPort(env, rate=200.0, qlimit=300)
# Wire packet generators and sinks together
pg.out = switch_port
switch_port.out = ps
env.run(until=20)
print("waits: {}".format(ps.waits))
print("received: {}, dropped {}, sent {}".format(ps.packets_rec,
                                                 switch_port.packets_drop,
                                                 pg.packets_sent))
Exemple #6
0
from SimComponents import PacketGenerator, PacketSink, FlowDemux, SnoopSplitter, \
    WFQServer, VirtualClockServer
import random
import simpy


def const_arrival():
    return 1


def data_generator():
    return random.random()


def const_size():
    return 123 * 8


if __name__ == '__main__':

    env = simpy.Environment()
    pg = PacketGenerator(env,
                         "SJSU",
                         const_arrival,
                         const_size,
                         data_generator,
                         initial_delay=0.0,
                         finish=35,
                         flow_id=0)
    pg.run()
Exemple #7
0
if __name__ == '__main__':

    def const_arrival():
        return 1.25

    def const_arrival2():
        return 1.25

    def const_size():
        return 100.0

    env = simpy.Environment()
    pg = PacketGenerator(env,
                         "SJSU",
                         const_arrival,
                         const_size,
                         initial_delay=0.0,
                         finish=35,
                         flow_id=0)
    pg2 = PacketGenerator(env,
                          "SJSU",
                          const_arrival2,
                          const_size,
                          initial_delay=20.0,
                          finish=35,
                          flow_id=1)
    ps = PacketSink(env, rec_arrivals=True, absolute_arrivals=True)
    ps2 = PacketSink(env, rec_arrivals=True, absolute_arrivals=True)
    ps_snoop1 = PacketSink(env, rec_arrivals=True, absolute_arrivals=True)
    ps_snoop2 = PacketSink(env, rec_arrivals=True, absolute_arrivals=True)
    # Set up the virtual clock switch port
Exemple #8
0
#!/usr/bin/env python

from SimComponents import PacketGenerator, PacketSink, FlowDemux, SnoopSplitter, \
    WFQServer, VirtualClockServer
import random
import simpy


def const_arrival():
    return 1
def data_generator():
    return random.random()

def const_size():
    return 123*8


if __name__ == '__main__':

    env = simpy.Environment()
    pg = PacketGenerator(env, "SJSU", const_arrival, const_size, data_generator, initial_delay=0.0, finish=35, flow_id=0)
    pg.run()
if __name__ == '__main__':

    mean_pkt_size = 100.0
    adist = functools.partial(random.expovariate,
                              0.5)  #exploentioal arrival time
    sdist = functools.partial(random.expovariate,
                              0.01)  #Mean size of packet 100 bytes
    #port_rate = float(functools.partial(random.expovariate,0.5)) # Servace Bit Rate
    port_rate = 1000.0
    samp_dist1 = functools.partial(random.expovariate, 1.0)
    samp_dist2 = functools.partial(random.expovariate, 1.0)
    qlimit = 10000  #FIFO Queue Size
    env = simpy.Environment()

    pg = PacketGenerator(env, "Greg", adist, sdist)  #Package Generator
    ps1 = PacketSink(env, debug=False,
                     rec_arrivals=True)  #Package Sink for packages
    ps2 = PacketSink(env, debug=False, rec_arrivals=True)

    switch_port1 = SwitchPort(env, port_rate,
                              qlimit=10000)  # define two queues
    switch_port2 = SwitchPort(env, port_rate, qlimit=10000)

    pm1 = PortMonitor(env, switch_port1, samp_dist1)  #define port monitor
    pm2 = PortMonitor(env, switch_port2, samp_dist2)

    pg.out = switch_port1
    '''switch_port1.out = ps1
    ps1 = switch_port2
    '''
Exemple #10
0
from random import expovariate
import simpy
from SimComponents import PacketGenerator, PacketSink


def constArrival():  # Constant arrival distribution for generator 1
    return 1.5


def constArrival2():
    return 2.0


def distSize():
    return expovariate(0.01)


env = simpy.Environment()  # Create the SimPy environment
# Create the packet generators and sink
ps = PacketSink(env, debug=True)  # debugging enable for simple output
pg = PacketGenerator(env, "EE283", constArrival, distSize)
pg2 = PacketGenerator(env, "SJSU", constArrival2, distSize)
# Wire packet generators and sink together
pg.out = ps
pg2.out = ps
env.run(until=20)
import matplotlib.pyplot as plt

from SimComponents import PacketGenerator, PacketSink, ShaperTokenBucket

if __name__ == '__main__':

    def const_arrival():
        return 2.5

    def const_size():
        return 100.0

    env = simpy.Environment()
    pg = PacketGenerator(env,
                         "SJSU",
                         const_arrival,
                         const_size,
                         initial_delay=7.0,
                         finish=35)
    pg2 = PacketGenerator(env,
                          "SJSU",
                          const_arrival,
                          const_size,
                          initial_delay=7.0,
                          finish=35)
    ps = PacketSink(env, rec_arrivals=True, absolute_arrivals=True)
    ps2 = PacketSink(env, rec_arrivals=True, absolute_arrivals=True)
    source_rate = 8.0 * const_size() / const_arrival(
    )  # the average source rate
    bucket_rate = 0.5 * source_rate
    bucket_size = 1.0 * const_size()
    shaper = ShaperTokenBucket(env, bucket_rate, bucket_size)
Exemple #12
0

def constArrival(): # Constant arrival distribution for generator 1
    return 10

def constArrival2(): # Constant arrival distribution for generator 2
    return 15

def distSize(): # Random packet size distribution
    return expovariate(0.01)


env = simpy.Environment()  # Create the SimPy environment
# Create the packet generators and sink
ps = PacketSink(env, debug=True)  # debugging enable for simple output
pg = PacketGenerator(env, "EE283", constArrival, distSize)
pg2 = PacketGenerator(env, "SJSU", constArrival2, distSize)
# Wire packet generators and sink together
q1 = ocx.queue("q1")
q2 = ocx.queue("q2")


pg.out  = q1
pg2.out = q2

p = ocx.port(env)
p.all_queues = [q1,q2]
q1.x = p
q2.x = p
# Run it
env.run(until=200)
Exemple #13
0
def distSize():  #size of the packet
    return expovariate(0.01)


def delay():
    return random.randint(1, 100)


if __name__ == '__main__':
    env = simpy.Environment()  # Create the SimPy environment
    # Create the packet generators and sink
    ps = PacketSink(env, debug=True)  # debugging enable for simple output
    pg = PacketGenerator(
        env,
        "PH",
        constArrival,
        distSize,
    )
    pg2 = PacketGenerator(
        env,
        "PT",
        constArrival2,
        distSize,
    )
    # Wire packet generators and sink together
    pg.out = ps
    pg2.out = ps

    env.run(2000)  # Run it
Exemple #14
0
def MM1K(lamda, mu, ql, user, port_rate, Tsim, bins, directorio):
    try:
        plt.close('all')

        ############# DEFINICION DE LOS PARAMETROS DEL MODELO #########################
        #    Creacion de carpeta temporal para guardar graficos
        if os.path.exists(directorio + 'temp_graficos'):
            shutil.rmtree(directorio + 'temp_graficos')
        os.mkdir(directorio + 'temp_graficos')
        #Parametros del Sumidero
        debugSink = False  #o False, muestra en la salida lo que llega al servidor
        rec_arrivalsSink = True  #Si es verdadero los arribos se graban
        abs_arrivalsSink = False  # true, se graban tiempos de arribo absoluto; False, el tiempo entre arribos consecutivos

        #Parametros del Generador de Paquetes.
        mu_paq = ((mu * 8) / port_rate)

        adist = functools.partial(
            random.expovariate, lamda)  #Tiempo de inter arribo de los paquetes
        sdist = functools.partial(random.expovariate,
                                  mu_paq)  # Tamaño de los paquetes

        #Parametros del Monitor
        Smd = lamda
        samp_dist = functools.partial(random.expovariate, Smd)

        ###############################################################################

        ############# CREACION DEL ENTORNO Y SUS COMPONENTES  #########################

        # Creación del Entorno de Simpy
        env = simpy.Environment()

        # Creación del Generador de Paquetes y Servidor
        psink = PacketSink(env,
                           debug=debugSink,
                           rec_arrivals=rec_arrivalsSink,
                           absolute_arrivals=abs_arrivalsSink)

        pg = PacketGenerator(env, user, adist, sdist)

        switch_port = SwitchPort(env, rate=port_rate, qlimit=ql)

        # PortMonitor para rastrear los tamaños de cola a lo largo del tiempo
        pm = PortMonitor(env, switch_port, samp_dist, count_bytes=True)

        ###############################################################################

        ############# CONEXION DE LOS COMPONENTES DEL MODELO  #########################

        pg.out = switch_port
        switch_port.out = psink

        # Correr la simulacion del entorno. Paramatro el tiempo
        env.run(until=Tsim)

        ###############################################################################

        ############# MUESTRA DE RESULTADOS  ##########################################

        pkt_drop = switch_port.packets_drop
        pkt_recibidos_serv = psink.packets_rec
        pkt_enviados = pg.packets_sent
        ocup_sistema_L = float(sum(pm.sizes)) / len(pm.sizes)
        intensidad_trafico = lamda / mu
        if lamda != mu:
            pk = (((1 - intensidad_trafico) * intensidad_trafico**(ql)) /
                  (1 - intensidad_trafico**(ql + 1)))
        else:
            pk = 1 / (ql + 1)

        lamda_eficaz = lamda * (1 - pk)
        espera_sist_W = ocup_sistema_L / lamda_eficaz
        espera_cola_Wq = espera_sist_W - 1 / mu
        ocup_cola_Lq = espera_cola_Wq * lamda_eficaz
        tasa_perdida = lamda * pk

        ###############################################################################

        ############# GRAFICOS  #######################################################
        directorio = directorio + "temp_graficos/"
        #--------- NORMALIZADOS-----------------------------------------------------
        fig, axis = plt.subplots()
        axis.hist(psink.waits,
                  bins,
                  normed=True,
                  alpha=1,
                  edgecolor='black',
                  linewidth=1)
        axis.set_title("Tiempos de Espera - Normalizado")
        axis.set_xlabel("Tiempo")
        axis.set_ylabel("Frecuencia de ocurrencia")
        fig.savefig(directorio + "WaitHistogram_normal.png")

        fig, axis = plt.subplots()
        axis.hist(pm.sizes,
                  bins,
                  normed=True,
                  alpha=1,
                  edgecolor='black',
                  linewidth=1)
        axis.set_title("Tiempos de Ocupación del Sistema - Normalizado")
        axis.set_xlabel("Nro")
        axis.set_ylabel("Frecuencia de ocurrencia")
        fig.savefig(directorio + "QueueHistogram_normal.png")

        fig, axis = plt.subplots()
        axis.hist(psink.arrivals,
                  bins,
                  normed=True,
                  alpha=1,
                  edgecolor='black',
                  linewidth=1)
        axis.set_title("Tiempos de Inter-Arribo a la Cola - Normalizado")
        axis.set_xlabel("Tiempo")
        axis.set_ylabel("Frecuencia de ocurrencia")
        fig.savefig(directorio + "ArrivalHistogram_normal.png")

        #---------SIN NORMALIZAR-----------------------------------------------------
        fig, axis = plt.subplots()
        axis.hist(psink.waits,
                  bins,
                  normed=False,
                  alpha=1,
                  edgecolor='black',
                  linewidth=1)
        axis.set_title("Tiempos de Espera")
        axis.set_xlabel("Tiempo")
        axis.set_ylabel("Frecuencia de ocurrencia ")
        fig.savefig(directorio + "WaitHistogram.png")

        fig, axis = plt.subplots()
        axis.hist(pm.sizes,
                  bins,
                  normed=False,
                  alpha=1,
                  edgecolor='black',
                  linewidth=1)
        axis.set_title("Tiempos de Ocupación del Sistema")
        axis.set_xlabel("Nro")
        axis.set_ylabel("Frecuencia de ocurrencia")
        fig.savefig(directorio + "QueueHistogram.png")

        fig, axis = plt.subplots()
        axis.hist(psink.arrivals,
                  bins,
                  normed=False,
                  alpha=1,
                  edgecolor='black',
                  linewidth=1)
        axis.set_title("Tiempos de Inter-Arribo a la Cola")
        axis.set_xlabel("Tiempo")
        axis.set_ylabel("Frecuencia de ocurrencia")
        fig.savefig(directorio + "ArrivalHistogram.png")

        datos = psink.data
        str1 = '&'.join(datos)
        aux_str1 = str1
        str1 = aux_str1.replace('&', '\n')
        aux_str1 = str1
        str1 = (aux_str1.replace(',', '  \t  '))

        return str1, espera_sist_W, pkt_drop, pkt_enviados, tasa_perdida, ocup_sistema_L, pkt_recibidos_serv, intensidad_trafico, espera_cola_Wq, ocup_cola_Lq

    except:
        error = traceback.format_exc()
        QMessageBox.critical(
            None, 'Error de ejecucion', "Detalle del error:\n\n" + error +
            '\n\nPor favor, revise la documentacion del programa.',
            QMessageBox.Ok)
        sys.exit(0)
    adist2 = functools.partial(random.expovariate, 0.04375)  #(1/40 + 1/16)/2
    # The same distribution of pkt sizes for both.
    sdist = functools.partial(my_paretovariate, 81.5)  # xm = 1.1 alpha = 81.5
    #sdist = functools.partial(random.expovariate, 1.0 / mean_pkt_size)
    samp_dist = functools.partial(random.expovariate, 0.04375)
    # The same port rate  for all routers
    port_rate = 100 / 8 * 10**6  # 100Mbit/s
    qlim = 4 * 10**6  #4Mb

    # Create the SimPy environment. This is the thing that runs the simulation.
    env = simpy.Environment()

    ps1 = PacketSink(env, debug=False, rec_arrivals=True)
    # figure out the use of selector
    # ps1 = PacketSink(env, debug=False, rec_arrivals=True)
    pg1 = PacketGenerator(env, 'src1', adist1, sdist)
    pg2 = PacketGenerator(env, 'src2', adist2, sdist)
    branch1 = RandomBrancher(env, [0.50, 0.50])
    branch2 = RandomBrancher(env, [0.50, 0.50])
    #pseudoBrancher
    branch3 = RandomBrancher(env, [1.00, 0.00])
    switch_port1 = SwitchPort(env, port_rate, qlimit=qlim)
    switch_port2 = SwitchPort(env, port_rate, qlimit=qlim)
    switch_port3 = SwitchPort(env, port_rate, qlimit=qlim)
    switch_port4 = SwitchPort(env, port_rate, qlimit=qlim)
    switch_port5 = SwitchPort(env, port_rate, qlimit=qlim)

    # Wire packet generators, switch ports, and sinks together
    pg1.out = switch_port1
    switch_port1.out = branch1
    branch1.outs[0] = switch_port3
mygen = myPattern()
mygen2 = myPattern()

def arrivals1():
    return next(mygen)

def arrivals2():
    return next(mygen2)

def const_size():
    return 200.0

env = simpy.Environment()
# Create two identical packet generators based on your pattern
# one will go through a shaper and one will not
pg = PacketGenerator(env, "CSU", arrivals1, const_size, initial_delay=0.0, finish=60)
pg2 = PacketGenerator(env, "EB", arrivals2, const_size, initial_delay=0.0, finish=60)

# Two packet sinks to measure the arrival times
ps = PacketSink(env, rec_arrivals=True, absolute_arrivals=True)
ps2 = PacketSink(env, rec_arrivals=True, absolute_arrivals=True)

bucket_rate = # You need to fill this in
bucket_size = # You need to fill this in
shaper = ShaperTokenBucket(env, bucket_rate, bucket_size)
pg.out = ps
pg2.out = shaper
shaper.out = ps2
env.run(until=10000)
print(ps.arrivals)
Exemple #17
0
if __name__ == '__main__':
    # Set up arrival and packet size distributions
    # Using Python functools to create callable functions for random variates with fixed parameters.
    # each call to these will produce a new random value.

    adist = functools.partial(random.expovariate, 0.5)
    sdist = functools.partial(random.expovariate, 0.01)  # mean size 100 bytes
    samp_dist = functools.partial(random.expovariate, 1.0)
    port_rate = 1000.0

    # Create the SimPy environment
    env = simpy.Environment()
    # Create the packet generators and sink
    ps = PacketSink(env, debug=False, rec_arrivals=True)
    pg = PacketGenerator(env, "Test", adist, sdist)
    switch_port = SwitchPort(env, port_rate, qlimit=10000)
    # Using a PortMonitor to track queue sizes over time
    pm = PortMonitor(env, switch_port, samp_dist)
    # Wire packet generators, switch ports, and sinks together
    pg.out = switch_port
    switch_port.out = ps
    # Run it
    env.run(until=8000)
    print("Last 10 waits: " +
          ", ".join(["{:.3f}".format(x) for x in ps.waits[-10:]]))
    print("Last 10 queue sizes: {}".format(pm.sizes[-10:]))
    print("Last 10 sink arrival times: " +
          ", ".join(["{:.3f}".format(x) for x in ps.arrivals[-10:]]))
    print("average wait = {:.3f}".format(sum(ps.waits) / len(ps.waits)))
    print("received: {}, dropped {}, sent {}".format(switch_port.packets_rec,
if __name__ == '__main__':

    def const_arrival():
        return 3.0  # 1.0 => 12Gbps, 5 => 2.4Gbps 3 => 4Gbps

    def const_size():
        return 1500.0

    pir = 6000.0  # 6Gbps
    pbs = 3000  # bytes
    cir = 3000.0  # 3Gbps
    cbs = 4000  # bytes

    env = simpy.Environment()
    pg = PacketGenerator(env, "SJSU", const_arrival, const_size)
    ps_green = PacketSink(env, rec_arrivals=True, absolute_arrivals=True)
    ps_yellow = PacketSink(env, rec_arrivals=True, absolute_arrivals=True)
    ps_red = PacketSink(env, rec_arrivals=True, absolute_arrivals=True)
    marker = TrTCM(env, pir, pbs, cir, cbs)
    demux = FlowDemux([ps_green, ps_yellow, ps_red])
    pg.out = marker
    marker.out = demux
    env.run(until=50)

    fig, ax1 = plt.subplots()
    ax1.vlines(ps_green.arrivals,
               0.0,
               1.0,
               colors="g",
               linewidth=2.0,
Exemple #19
0
    samp_dist = functools.partial(random.expovariate, 0.50)
    port_rate = 2.2 * 8 * mean_pkt_size  # want a rate of 2.2 packets per second

    # Create the SimPy environment. This is the thing that runs the simulation.
    env = simpy.Environment()

    # Create the packet generators and sink
    def selector(pkt):
        return pkt.src == "SJSU1"

    def selector2(pkt):
        return pkt.src == "SJSU2"

    ps1 = PacketSink(env, debug=False, rec_arrivals=True, selector=selector)
    ps2 = PacketSink(env, debug=False, rec_waits=True, selector=selector2)
    pg1 = PacketGenerator(env, "SJSU1", adist1, sdist)
    pg2 = PacketGenerator(env, "SJSU2", adist2, sdist)
    pg3 = PacketGenerator(env, "SJSU3", adist3, sdist)
    branch1 = RandomBrancher(env, [0.75, 0.25])
    branch2 = RandomBrancher(env, [0.65, 0.35])
    switch_port1 = SwitchPort(env, 's1', port_rate)
    switch_port2 = SwitchPort(env, 's2', port_rate)
    switch_port3 = SwitchPort(env, 's3', port_rate)
    switch_port4 = SwitchPort(env, 's4', port_rate)

    # Wire packet generators, switch ports, and sinks together
    pg1.out = switch_port1
    switch_port1.out = branch1
    branch1.outs[0] = switch_port2
    switch_port2.out = branch2
    branch2.outs[0] = switch_port3
Exemple #20
0
"""
Simple example of PacketGenerator and PacketSink from the SimComponents module.
Creates two constant rate packet generators and wires them to one sink.
Copyright 2014 Dr. Greg M. Bernstein
Released under the MIT license
"""
from random import expovariate
import simpy
from SimComponents import PacketGenerator, PacketSink


def constArrival():  # Constant arrival distribution for generator 1
    return 1.5

def constArrival2():
    return 2.0

def distSize():
    return expovariate(0.01)

if __name__ == '__main__':
    env = simpy.Environment()  # Create the SimPy environment
    # Create the packet generators and sink
    ps = PacketSink(env, debug=True)  # debugging enable for simple output
    pg = PacketGenerator(env, "1", constArrival, distSize)
    pg2 = PacketGenerator(env, "2", constArrival2, distSize)
    # Wire packet generators and sink together
    pg.out = ps
    pg2.out = ps
    env.run(until=20) # Run it