示例#1
0
    def add_connection(self,
                       dst_node,
                       rate,
                       qlimit,
                       monitor_rate,
                       propagation_delay,
                       bidirectional=False):
        port_id = self.get_port_id(dst_node.id)
        new_port = SwitchPort(self.env,
                              rate=rate,
                              qlimit=qlimit,
                              limit_bytes=False,
                              id=port_id)
        self.output_ports[port_id] = new_port

        link_id = self.get_link_id(dst_node.id)
        new_link = Link(self.env,
                        id=link_id,
                        delay=propagation_delay,
                        dst=dst_node,
                        src=self.id,
                        switch_port=new_port)
        self.routes[link_id] = new_link

        new_port.out = new_link

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

        port_monitor_id = new_port.id
        dist_partial = partial(dist, self.gen, monitor_rate)
        port_monitor = PortMonitor(self.env, port=new_port, dist=dist_partial)
        self.port_monitors[port_monitor_id] = port_monitor

        if bidirectional:
            dst_node.add_connection(self, rate, qlimit, monitor_rate,
                                    propagation_delay)
示例#2
0
    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
    branch2.outs[1] = switch_port4
    pg3.out = switch_port3
    pg2.out = switch_port4
    switch_port3.out = ps1
    switch_port4.out = ps2
    # Run it
    env.run(until=4000)
    print(ps2.waits[-10:])
    # print pm.sizes[-10:]
    # print ps.arrivals[-10:]
    print("average wait source 1 to output 3 = {}".format(
        sum(ps1.waits) / len(ps1.waits)))
示例#3
0
    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,
                                                     switch_port.packets_drop,
                                                     pg.packets_sent))
    print("loss rate: {}".format(
        float(switch_port.packets_drop) / switch_port.packets_rec))
    print("average system occupancy: {:.3f}".format(
        float(sum(pm.sizes)) / len(pm.sizes)))
示例#4
0
    ps3 = PacketSink(env, debug=False, rec_arrivals=True, selector=selector3)

    pg1 = PacketGenerator(env, "SJSU1", adist1, sdist)
    pg2 = PacketGenerator(env, "SJSU2", adist2, sdist)
    pg3 = PacketGenerator(env, "SJSU3", adist3, sdist)
    router = Router(env, 3)
    switch_port1 = SwitchPort(env, port_rate)
    switch_port2 = SwitchPort(env, port_rate)
    switch_port3 = SwitchPort(env, port_rate)
    switch_port4 = SwitchPort(env, port_rate)

    # Wire packet generators, switch ports, and sinks together
    pg1.out = switch_port1
    pg2.out = switch_port1
    pg3.out = switch_port1
    switch_port1.out = router
    router.outs[0] = switch_port2
    router.outs[1] = switch_port3
    router.outs[2] = switch_port4

    switch_port2.out = ps1
    switch_port3.out = ps2
    switch_port4.out = ps3

    # Run it
    env.run(until=10000)
    print(ps2.waits[-10:])
    # print pm.sizes[-10:]
    # print ps.arrivals[-10:]
    print(
        f'switch port 1 packet count {switch_port1.packets_rec}, and packet drop {switch_port1.packets_drop}'
示例#5
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)
                     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
    '''

    switch_port1.out = switch_port2
    switch_port2.out = ps2

    env.run(until=2000)
    #print(ps2.waits[-10:])
    print("average wait = {:.3f}".format(sum(ps2.waits) / len(ps2.waits)))

    #theorical Mean Sojourn Time

    #Calculate CI
    confidence_level = 0.95
    degrees_freedom = len(ps2.waits) - 1
    sample_mean = np.mean(ps2.waits)
    sample_standard_error = scipy.stats.sem(ps2.waits)
    confidence_interval = scipy.stats.t.interval(confidence_level,
                                                 degrees_freedom, sample_mean,