Example #1
0
  def build_network(self, logger,env):
    # nic0 -> client to cache server
    # nic1 -> cross rach(between cache servers
    # nic2 -> between backend and cache servers

    links={}
    nic_count =  int(self.config.get('Network', 'nic count'))
    self.nic_count = nic_count
    #print("nic COUNt is %d" %nic_count)
    coef = 1
    speed_unit = self.config.get('Network', 'unit')
    if speed_unit == 'Gbps':
        coef = 1024/8 # based on MB
        #coef = 1024*1024*1024
    elif speed_unit == 'Mbps':
        coef = 1
        #coef = 1024*1024
    elif speed_unit == 'Kbps':
        coef = 1024/8
    elif speed_unit == 'Bps':
        coef = 1


    for i in range(self.c_nodes):
      for j in range (nic_count-1):
        nic_id = "nic"+str(j)+" in"
        link_id = "nic"+str(j)+".in."+str(i)
        speed = float(self.config.get('Network', nic_id))*coef
        #speed = float(self.config.get('Network', nic_id).split("G")[0])/8*1000*1000*1000
        links[link_id]=simpy.Container(env, speed, init=speed)
        
        nic_id = "nic"+str(j)+" out"
        link_id = "nic"+str(j)+".out."+str(i)
        speed = float(self.config.get('Network', nic_id))*coef
        #speed = float(self.config.get('Network',nic_id).split("G")[0])/8*1000*1000*1000
        links[link_id]=simpy.Container(env, speed, init=speed)
    
    #DL link
    #nic_id = "nic"+str(nic_count-1)+" in"
    #link_id = "nic"+str(nic_count-1)+".in" 
    #speed = float(self.config.get('Network', nic_id).split("G")[0])/8*1000*1000*1000 
    nic_id = "dl"+" nic"+str(nic_count-1)+" in"
    link_id = "nic"+str(nic_count-1)+".in" 

    speed = float(self.config.get('Network', nic_id))*coef

    links[link_id]=simpy.Container(env, speed, init=speed)
    
    #nic_id = "nic"+str(nic_count-1)+" out"
    #link_id = "nic"+str(nic_count-1)+".out" 
    #speed = float(self.config.get('Network', nic_id).split("G")[0])/8*1000*1000*1000 
    nic_id = "dl"+ " nic"+str(nic_count-1)+" out"
    link_id = "nic"+str(nic_count-1)+".out" 

    speed = float(self.config.get('Network', nic_id))*coef

    links[link_id]=simpy.Container(env, speed, init=speed)
  
    #print("LINKS ARE %s" %links)
    return links
Example #2
0
    def set_environment(self, env=None, lock=False, p=1):
        """
        La funzione associa l'ambiente di test alla coda: se non specificato, l'ambiente viene creato al volo
        - "env" e' l'ambiente di simulazione
        - "lock" e' in booleano, indica se l'arrivo di richieste e' controllato dalla coda precedente
        - "p" e' la probabilita' con cui viene accettata la richiesta in arrivo (valore compreso tra 0 ed 1)
        """
        # Controllo dell'input
        ic.check_number(p, 'probability to accept a request', 0, 1)

        if env is None:
            # Creo al volo l'ambiente di test
            env = simpy.Environment()
        # Associazione
        self.env = env
        # Modulo per le statistiche
        self.stats = qs_stats.QS_StatsManager(self.env)
        # Sistema nel complesso e server interni sono modellizzati come risorse condivise
        self._QS = simpy.Resource(self.env, capacity=self.capacity)
        self._S = simpy.Resource(self.env, capacity=self.servers)
        # La popolazione viene modellizzata come contenitore di risorse condivise
        self._P = simpy.Container(self.env,
                                  capacity=self.population,
                                  init=self.population)
        # Se richiesto, e' possibile fare in modo che l'arrivo di una richiesta sia comandato dall'esterno (es: chained)
        if lock:
            self._LockedQueue = simpy.Container(self.env, capacity=INF, init=0)
            self.probToArrive = p
        else:
            # Nota: in questo caso, la coda di blocco e' totalmente ininfluente
            self._LockedQueue = simpy.Container(self.env,
                                                capacity=INF,
                                                init=INF)
            self.probToArrive = 1
Example #3
0
def build_network(config, logger, env):
    # 1 Gbps = 125 MB/s
    # 10 Gbps = 1250 MB/s
    # 40 Gbps = 5000 MB/s
    TOR_SIZE = 1
    links = {}
    L1_In = float(config.get('Network',
                             'L1_In').split("G")[0]) / 8 * 1000 * 1000 * 1000
    L2_In = float(config.get('Network',
                             'L2_In').split("G")[0]) / 8 * 1000 * 1000 * 1000
    L1_Out = float(config.get('Network',
                              'L1_Out').split("G")[0]) / 8 * 1000 * 1000 * 1000
    L2_Out = float(config.get('Network',
                              'L2_Out').split("G")[0]) / 8 * 1000 * 1000 * 1000
    numNodes = int(config.get('Simulation', 'nodeNum'))
    if config.get('Simulation', 'L1') == "true":
        for i in range(numNodes):
            linkId = "L1in1r" + str(i)
            links[linkId] = simpy.Container(env, L1_In, init=L1_In)
            linkId = "L1out0r" + str(i)
            links[linkId] = simpy.Container(env, L1_Out, init=L1_Out)

    if config.get('Simulation', 'L2') == "true":
        for i in range(numNodes):
            linkId = "L2in1r" + str(i)
            links[linkId] = simpy.Container(env, L2_In, init=L2_In)
            linkId = "L2out0r" + str(i)
            links[linkId] = simpy.Container(env, L2_Out, init=L2_Out)
    linkId = "Cephout"
    links[linkId] = simpy.Container(env, L2_In, init=L2_In)

    return links
Example #4
0
 def __init__(self, env):
     self.wood = simpy.Container(env,
                                 capacity=wood_capacity,
                                 init=initial_wood)
     self.dispatch = simpy.Container(env,
                                     capacity=dispatch_capacity,
                                     init=0)
Example #5
0
    def __init__(self, env):
        # input process
        self.machinery = simpy.Container(env,
                                         capacity=machinery_capacity,
                                         init=initial_machinery)
        self.machinery_control = env.process(self.machinery_stock_control(env))
        self.components = simpy.Container(env,
                                          capacity=components_capacity,
                                          init=initial_components)
        self.components_control = env.process(
            self.components_stock_control(env))
        self.assembler = simpy.Container(env,
                                         capacity=assembler_capacity,
                                         init=0)
        self.assembler_control = env.process(self.assembler_stock_control(env))

        # activities
        #self.parts_sequencing = env.process(self.parts_sequencing_control(env))
        #self.setting_up_schedule = env.process(self.setting_up_schedule_control(env))
        #self.production_commence = env.process(self.production_commence_control(env))

        # output
        #self.quality_check = env.process(self.quality_check_control(env))
        #self.vehicle_assemble = env.process(self.vehicle_assemble_control(env))

        self.dispatch = simpy.Container(env,
                                        capacity=dispatch_capacity,
                                        init=0)
        self.dispatch_control = env.process(self.dispatch_vehicle_control(env))

        # Closure & monitor
        #self.transport_dealer = env.process(self.transport_dealer_control(env))
        self.env_status_monitor = env.process(self.env_status(env))
def simular_turnoscapacidad(cantCajas, tiempoCaja, cantServidores, cantAsientos, tiempoCocina, cantMenus, cantCajasTarjeta, cantCapacidad):

    mes={2 : "FEBRERO", 3: "MARZO", 4: "ABRIL", 5: "MAYO", 6:"JUNIO", 7:"JULIO", 8:"AGOSTO",9:"SEPTIEMBRE",10:"OCTUBRE",11:"NOVIEMBRE", 12:"DICIEMBRE"}

    TOTAL=0

    tiempoCocina=tiempoCocina*60
    tiempoCaja=tiempoCaja*60

    for i in range(2,13):
        d = pd.read_csv("data/CSVs/tablas_simulacion/{}.csv".format(mes[i]), sep =",")
        dato = d.transpose()

        TOTAL11 = dato.loc['11'].sum()
        TOTAL12 = dato.loc['12'].sum()
        TOTAL13 = dato.loc['13'].sum()
        TOTAL14 = dato.loc['14'].sum()

        INTERVALTURNO11 =  (3600 / TOTAL11)
        INTERVALTURNO12 = (3600 / TOTAL12)
        INTERVALTURNO13 = (3600 / TOTAL13)
        INTERVALTURNO14 = (3600 / TOTAL14)

        TOTAL+=TOTAL11+TOTAL12+TOTAL13+TOTAL14

        random.seed(RANDOM_SEED)
        env = simpy.Environment()

        automatic_clerk= MonitoredResource("automatic clerk", env, capacity=cantCajasTarjeta)
        clerk = MonitoredResource("clerk", env, capacity=cantCajas)  # pasar de 2 a 3 cajas mejora muchisimo
        seats = MonitoredResource("seats", env, capacity=cantAsientos)
        server = MonitoredResource("server", env, capacity=cantServidores*2)
        delivery = simpy.Container(env, capacity=150)
        pase=simpy.Container(env, capacity=cantCapacidad)


        env.process(student_capacity_generator(env, 11, "", TOTAL11, INTERVALTURNO11, clerk, automatic_clerk, server, delivery, seats, tiempoCaja, pase, i))

        start_delayed(env, student_capacity_generator(env, 12, "", TOTAL12, INTERVALTURNO12, clerk, automatic_clerk, server, delivery, seats, tiempoCaja, pase, i), 3600)

        start_delayed(env, student_capacity_generator(env, 13, "", TOTAL13, INTERVALTURNO13, clerk, automatic_clerk, server, delivery, seats, tiempoCaja, pase, i), 7200)

        start_delayed(env, student_capacity_generator(env, 14, "", TOTAL14, INTERVALTURNO14, clerk, automatic_clerk, server, delivery, seats, tiempoCaja, pase, i), 10800)

        env.process(door(env,pase,cantCapacidad))
        env.process(kitchen(env, delivery, cantMenus, tiempoCocina))
        env.run(until=25200)

        # name | month | facultad | start_time | end_time | clerk_queue | automatic_clerk_queue | delivery_queue | seating_queue | total_waiting_time | activity_time
        df = None
        df = pd.DataFrame(dataframe, columns=['name', 'turno', 'month', 'facultad', 'start_time', 'end_time', 'clerk_queue', 'automatic_clerk_queue','delivery_queue',
                                              'seating_queue', 'total_waiting_time', 'activity_time'])

        resources.extend([clerk, automatic_clerk, server, seats])

    return df
Example #7
0
 def update(self, RDSEED):
     
     self.reset()
     for episode in range(LEPI):
         self.reset()
         print ("qlearing episode %d setpcont %d" % (episode,self.stepcount))
         random.seed(RDSEED)
         ul = soCoMM.UL()
         for i in range(ul.USERS_NUM):
             user = soCoMM.User(i)
             user.usersetting()
             user.usercreat()
             ul.USER_LIST.append(user)
         
         mec0 = soCoMM.MEC(0,ul)
         mec0.setMEC(0,0,0,2,50)
         mec1 = soCoMM.MEC(1,ul)
         mec1.setMEC(1000,0,0,4,50)
         mec2 = soCoMM.MEC(2,ul)
         mec2.setMEC(0,1000,0,6,50)
         mec3 = soCoMM.MEC(3,ul)
         mec3.setMEC(1000,1000,0,8,50)
         env_ = simpy.Environment()
         
         #env_.process(ul.mobile(env_))#user mobile 
         
         WAITING_LEN0 = simpy.Container(env_,BUFFER, init=len(mec0.WAITING_LIST))
         env_.process(mec0.runremote(env_,WAITING_LEN0))
         env_.process(mec0.refreshtrans(env_,WAITING_LEN0))
         env_.process(mec0.refreshsys(env_,flag=0))
         env_.process(self.step(mec0,env_))
         # initial observation
         WAITING_LEN1 = simpy.Container(env_,BUFFER, init=len(mec1.WAITING_LIST))
         env_.process(mec1.runremote(env_,WAITING_LEN1))
         env_.process(mec1.refreshtrans(env_,WAITING_LEN1))
         env_.process(mec1.refreshsys(env_,flag=0))
         env_.process(self.step(mec1,env_))
         
         WAITING_LEN2 = simpy.Container(env_,BUFFER, init=len(mec2.WAITING_LIST))
         env_.process(mec2.runremote(env_,WAITING_LEN2))
         env_.process(mec2.refreshtrans(env_,WAITING_LEN2))
         env_.process(mec2.refreshsys(env_,flag=0))
         env_.process(self.step(mec2,env_))
         # initial observation
         WAITING_LEN3 = simpy.Container(env_,BUFFER, init=len(mec3.WAITING_LIST))
         env_.process(mec3.runremote(env_,WAITING_LEN3))
         env_.process(mec3.refreshtrans(env_,WAITING_LEN3))
         env_.process(mec3.refreshsys(env_,flag=0))
         env_.process(self.step(mec3,env_))
         # initial observation
         
         env_.run(until=SIM_TIME)
     self.reset()
Example #8
0
 def __init__(self, name, env, station, load_station, user_input=False):
     self.station = station
     self.load_station = load_station
     self.loaded_stock = load_station.finished_stock
     self.oven_stock = simpy.Container(env, 1)
     self.mold_stock = simpy.Container(env, 1)
     self.user_input = user_input
     self.name = name
     self.env = env
     self.cycles = 0
     self.failures = 0
     self.process = env.process(self.run(self.env))
def schedule(env):

    global __running__
    global day_time

    #Res symbolisiert die frei zur Verfügung stehende Abfüll-Anlage
    #Bei Wartungsarbeiten wird so die Maschine blockiert
    res = simpy.PriorityResource(env, capacity=1)

    #Queque
    que_check = simpy.Container(env, capacity=100)
    que_fill = simpy.Container(env, capacity=FILLING_SATIONS)
    que_done = simpy.Container(env)
    que_rejected = simpy.Container(env)
    que_removed = simpy.Container(env)

    #Offset damit scheduling Funktioniert
    offset = 60 - (day_time.second % 60) if day_time.second % 60 > 0 else 0
    logging.debug(
        f"Wartet {offset} Sekunden bis mit den Scheduling begonnen wird")
    yield env.timeout(offset)
    update_time(env)

    while True:

        logging.debug(
            f"Datum:{day_time}|Queue_Check:{que_check.level}|Queue_Fill:{que_fill.level}|Queue_Done:{que_done.level}|Queue_Rej:{que_rejected.level}"
        )

        weekday = day_time.isoweekday()
        time = day_time.shift(minutes=VARIANCE_MEAN).format("HH:mm:ss")

        #Status
        if time in status.index:
            if not pd.isnull(status.loc[time][weekday]):
                if status.loc[time][weekday] == "r":
                    env.process(
                        proc_start_processes(env, res, que_check, que_fill,
                                             que_done, que_rejected,
                                             que_removed))
                else:
                    env.process(proc_end_processes(env))

        #Wartung
        if time in maintenance.index:
            if not pd.isnull(maintenance.loc[time][weekday]):
                time = int(maintenance.loc[time][weekday])
                env.process(proc_maintenance(env, time, res))

        yield env.timeout(60)
        update_time(env)
Example #10
0
def programm_execution(amount_cars, iterations):
    # Create environment and DSO contaier
    env = simpy.Environment()
    charger = simpy.Container(env, settings.DSO_CAP, init=settings.DSO_CAP)
    import_non_ev_loads()

    # start ampel monitor
    env.process(ampel_setter(env, charger))
    env.process(charger_checker(env, time, charger_level, charger))
    env.process(price_over_time(env, price))

    # create distributions
    soc = soc_distribution()
    start = start_of_charging_distribution()
    end = end_of_charging_distribution()

    # run cars and market
    cars = [Car(env=env, charger=charger, start=random.choice(start), soc=random.choice(soc), end=random.choice(end), name=i) for i in range(amount_cars)]
    market = Flexmarket(env, charger, cars)
    env.process(market.operate())
    for car in cars:
        env.process(car.operate())
        #env.process(car_monitor(env, car, car_values_over_time))

    # Execute!
    env.run(until=settings.SIM_TIME)

    #uncomment this for data export
    #data_export(cars, market, amount_cars, iterations, charger_level)

    plotter()
    plt.show()
    def __init__(self, m=1, mu1=0.5, s1=0.1, t1=0.2, t2=0.5, mu2=20, s2=2, l=4/3):
        self.job_distr = lambda: random.expovariate(1 / m)
        self.proc_distr = lambda: random.normalvariate(mu1, s1)
        self.prep_distr = lambda: random.uniform(t1, t2)
        self.break_distr = lambda: random.normalvariate(mu2, s2)
        self.repair_distr = lambda: random.expovariate(l)

        self.env = simpy.Environment()
        self.container_queue = simpy.Container(self.env)

        self.queue = []
        self.queue_times = []
        self.queue_sizes = []
        self.size_start_time = 0
        self.empty_times = []
        self.empty_start_time = 0
        self.busy = False

        self.total_times = {
            "free": [],
            "prep": [],
            "working": [],
            "repair": []
        }

        self.parts_need = 0
        self.parts_made = 0

        self.env.process(self.new_part())
        self.env.process(self.break_machine())
        self.process = self.env.process(self.working())
    def __init__(self,
                 train_id: str,
                 env: simpy.core.Environment,
                 capacity: int,
                 max_speed: int,
                 accel: float = 1.3):

        Locatable.__init__(self, (0, 0))
        Identifiable.__init__(self, train_id)

        self.capacity = capacity
        self._max_speed = max_speed
        self._acceleration = accel
        self.train_line: Union[None, Schedule] = None

        self._env = env
        self._passengers = simpy.Container(self._env,
                                           capacity=capacity,
                                           init=0)
        self.driving_direction = 1

        self._ticks_on_obj = 0

        self._currently_on_object: Union[Driveable, type(None)] = None

        self._lock_pass_put = threading.Lock()
        self._lock_pass_pop = threading.Lock()
        self._lock_drain = threading.Lock()

        self.sim_force_stop_time = 0
Example #13
0
    def __init__(self, env, name, initial_stock=None):
        """
        :param env: Environment of simpy simulation
        :param name: Unique FA name
        :param fa_name: Group name of FA such as Revenue, Tax etc.
        :param initial_stock: initial value of stocks for current FA
        """
        Observable.__init__(self)

        print("Initialize container with name: ", name)
        if initial_stock is not None:
            self.container = simpy.Container(env, init=initial_stock)
        else:
            self.container = simpy.Container(env)
        self.env = env
        self.name = name
Example #14
0
 def __init__(self, env: simpy.Environment, name: str, product: Product,
              processing_times: list, debug: bool, deletion_point: int):
     """
     Constructor for workstation
     :param env: the environment the workstation will be
     :param name:  of the workstation
     :param product:  the product that the workstation is building
     :param processing_times: the processing times generated in the .dat file
     :param debug: if debug mode should be on
     :param deletion_point: the deletion point of the model
     """
     self.name = name
     self.product = product
     self.buffers = {}
     for i in product.required_components:
         self.buffers[i] = simpy.Container(env, 2)
     self.env = env
     self.processing_times = processing_times
     self.products_made = 0
     env.process(self.workstation_process())
     self.wait_time = 0
     self.debug = debug
     self.deletion_point = deletion_point
     self.products_time = [0] * SIZE
     self.components_held = {}
     self.components_used = {}
Example #15
0
    def update(self, RDSEED):
        self.reset()
        for episode in range(LEPI):
            self.reset()
            print("learing episode %d" % (episode))
            random.seed(RDSEED)
            for i in range(USERS_NUM):
                user = soCoM.User(i)
                user.usersetting()
                user.usercreat()
                self.mec.USER_LIST.append(user)
            env_ = simpy.Environment()
            WAITING_LEN_ = simpy.Container(env_,
                                           BUFFER,
                                           init=len(self.mec.WAITING_LIST))

            observation = self.mec.getstate()
            env_.process(self.mec.runremote(env_, WAITING_LEN_))
            env_.process(self.mec.refreshsys(env_, WAITING_LEN_))
            env_.process(self.step(self.mec, observation, env_, WAITING_LEN_))
            env_.run(until=SIM_TIME)

            self.stepcount += 1
        self.setpcount = 0
        self.reset()
Example #16
0
    def addLink(self,
                linkID=None,
                turns={},
                type='link',
                length=0,
                t0=1,
                MU=1,
                nodeID=None,
                coordinates=((0, 0), (0, 0))):
        if linkID in self.links:
            print('Error: Link %d has already been defined!' % linkID)
        else:
            if 'exit' not in turns.keys():
                turns['exit'] = np.min((1 - sum(turns.values()), 1))

            self.links[linkID] = {
                'length': length,
                'turns': turns,
                't0': t0,
                'MU': MU
            }
            if nodeID is None:
                chars = string.ascii_uppercase + string.digits
                nodeID = ''.join([random.choice(chars) for i in range(8)])
            if nodeID not in self.nodes.keys():
                self.addNode(nodeID, cap=1)

            self.links[linkID]['node'] = self.nodes[nodeID]
            self.links[linkID]['queue'] = simpy.Container(self.env)
            self.links[linkID]['coordinates'] = coordinates
            print('Created link %s at node %s' % (linkID, nodeID))
Example #17
0
def proceso(nombre, env, cpu, memoria):
    memoria = simpy.Container(env, MEMORIA_RAM, init=MEMORIA_RAM)

    with cpu.request() as req:
        print('%s llegando a %1.f' % (nombre, env.now))
        start = env.now

        #se pide la cantidad de memoria necesaria
        yield req

        #Se da la memoria pedida
        memoria_requerida = random.randint(*NIVEL_DE_MEMORIA)

        yield memoria.get(memoria_requerida)

        #la ejecucion de instrucciones toma tiempo
        yield env.timeout(memoria_requerida / VELOCIDAD)

        tiempo_proceso = env.now - start
        print('%s termino ejecutando instrucciones en %.1f segundos.' %
              (nombre, tiempo_proceso))
        #print (memoria_requerida)
        #print (memoria.level)

        lista.append(tiempo_proceso)
        #print (lista)
        total = sum(lista)
        print(
            'PROMEDIO DE TIEMPO QUE ESTA EL PROCESO EN LA COMPUTADORA HASTA EL MOMENTO %1.f'
            % (total / CANT_PROCESOS))
Example #18
0
    def __init__(self, env):
        self.cpu = simpy.Resource(env, capacity=2)
        self.memoria = simpy.Container(env, init=100, capacity=100)
        self.average = 0

        # How many programs the CPU is gonna work
        totalProcesses = 25
        contador = 1
        intervalo = 10

        while contador <= totalProcesses:
            instrucciones = random.randint(1, 10)
            mem = random.randint(1, 10)
            respuesta = random.randint(1, 2)

            # el intervalo sirve para lambda = (1.0/intervalo) que nos dara
            # una secuencia de numeros del 0 al infinito, la cual siempre
            # se repetira si es ingresado el mismo numero al principio

            inicio = random.expovariate(1.0 / intervalo)

            # Finalmente se crea, con los argumentos anteriores, un nuevo proceso
            contador = contador + 1
            env.process(
                self.Simulacion(env, "Proceso %d" % contador, inicio, mem,
                                instrucciones, respuesta))
Example #19
0
    def __init__(self, env, plate, start_zone, start_soc, vehicle_config,
                 energymix_conf, sim_scenario_conf, sim_start_time):

        engine_type = sim_scenario_conf["engine_type"]
        model = sim_scenario_conf["vehicle_model_name"]
        if engine_type == "electric":
            energymix = energymix_conf
        else:
            energymix = {}
        super().__init__(vehicle_config[engine_type][model], energymix)

        self.env = env
        self.plate = plate
        self.zone = start_zone
        #self.alpha = sim_scenario_conf["alpha"]

        #self.battery_capacity = vehicle_config["battery_capacity"]
        #self.energy_efficiency = vehicle_config["energy_efficiency"]

        self.available = True
        self.soc = simpy.Container(env, init=start_soc, capacity=100)
        self.current_status = {
            "time": sim_start_time,
            "status": "available",
            "soc": self.soc.level,
            "zone": self.zone
        }
        self.status_dict_list = [self.current_status]
Example #20
0
    def initialize_port(self):
        """
        Initializes a Port object with a simpy.Container of scour protection
        material.
        """

        self.port = simpy.Container(self.env)
Example #21
0
 def __init__(self,env,num_chargers,tanks_capacity,max_level, trucks_num):
     self.env = env
     self.dispenser = simpy.Resource(env,capacity= num_chargers)
     self.tanks = simpy.Container(env,init=100,capacity=tanks_capacity)
     self.max_level = max_level
     self.monitor_tank = env.process(self.monitor_tank(env,max_level))
     self.trucks = simpy.Resource(env,capacity=trucks_num)
Example #22
0
 def __init__(self, env, instructionsRead):
     self.env = env
     self.ram = simpy.Container(
         env, init=100, capacity=100)  #cambio de capacidad de memoria RAM
     self.cpu = simpy.Resource(
         env, capacity=2)  #cambio de capacidada de procesar del CPU
     self.instructionsRead = instructionsRead
Example #23
0
    def __init__(self,
                 env: simpy.Environment,
                 products: Tuple[str, ...],
                 capacities: Tuple[int, ...],
                 init: Optional[Tuple[int, ...]] = None) -> None:
        """
        Initialize.

        :param env: The simulation environment.
        :param products: The products handled.
        :param capacities: The capacity of the different Store incorporated.
        :param init: The initial quantities in the containers. If not provided is
                    set by default equal to the capacity.

        """
        self.env = env
        self.products = products
        self.capacities: Dict[str, int] = {
            p: q
            for p, q in zip(products, capacities)
        }

        init = init or tuple(capacities)
        self.containers: Dict[str, simpy.Container] = {
            p: simpy.Container(env, c, init=i)
            for p, c, i in zip(products, capacities, init)
        }
Example #24
0
def test_container(env, log):
    """A *container* is a resource (of optinally limited capacity) where
    you can put in our take out a discrete or continuous amount of
    things (e.g., a box of lump sugar or a can of milk).  The *put* and
    *get* operations block if the buffer is to full or to empty. If they
    return, the process nows that the *put* or *get* operation was
    successfull.

    """
    def putter(env, buf, log):
        yield env.timeout(1)
        while True:
            yield buf.put(2)
            log.append(('p', env.now))
            yield env.timeout(1)

    def getter(env, buf, log):
        yield buf.get(1)
        log.append(('g', env.now))

        yield env.timeout(1)
        yield buf.get(1)
        log.append(('g', env.now))

    buf = simpy.Container(env, init=0, capacity=2)
    env.process(putter(env, buf, log))
    env.process(getter(env, buf, log))
    env.run(until=5)

    assert log == [('p', 1), ('g', 1), ('g', 2), ('p', 2)]
Example #25
0
    def __init__(self,
                 env,
                 uid,
                 latitude,
                 longitude,
                 capacity,
                 count=1,
                 init=0.1):
        '''
        '''
        assert capacity, f"capacity: {capacity}"
        assert count, f"count: {count}"

        self.env = env
        # Уникальный идентификатор контейнерной площадки
        self.uid = uid
        # Широта контейнерной площадки
        self.latitude = latitude
        # Долгота контейнерной площадки
        self.longitude = longitude
        # Количество контейнеров на контейнерной площадке
        self.count = count
        # Максимальная емкость
        self.capacity = capacity * self.count
        # Наряд на вывоз мусора
        self.order_uid = None
        self.resource = simpy.Container(self.env,
                                        capacity=self.capacity * 10,
                                        init=init)
Example #26
0
    def __init__(self, env, name):
        self.env = env
        self.name = name

        self.battery = simpy.Container(env, init=600, capacity=1000)
        self.fuel_tank = simpy.Container(env, init=500, capacity=1000)

        self.crew = simpy.Container(env, init=20, capacity=50)
        self.computation = simpy.Container(env, init=20, capacity=1000)

        self.dead = env.event()

        self.reactor = env.process(Reactor(env, self).run())
        self.lifesupport = env.process(Lifesupport(env, self).run())

        env.process(self.run())
Example #27
0
def SimulationRL(rho, rl):

    random.seed(RANDOM_SEED)
    mec = soCoM.MEC()
    mec.RHO = rho * mec.RHO

    print("Envronment create!")
    env = simpy.Environment()
    print("User create!")
    for i in range(mec.USERS_NUM):
        user = soCoM.User(i)
        user.usersetting()
        user.usercreat()
        mec.USER_LIST.append(user)

    WAITING_LEN = simpy.Container(env, BUFFER, init=len(mec.WAITING_LIST))
    env.process(mec.runremote(env, WAITING_LEN))
    env.process(
        mec.refreshsys(env, WAITING_LEN, rl.name, 'rho' + str(mec.RHO), 1))
    env.process(mec.offloadDQ(env, WAITING_LEN, rl))
    env.process(mec.writelog(env, rl.name, 'rho', int(mec.RHO)))
    env.run(until=SIM_TIME)
    mec.writeoffload(rl.name, 'rho', int(mec.RHO))
    for u in mec.USER_LIST:
        u.userprint()
Example #28
0
 def __init__(self, *args, **kwargs):
     super(TopTest, self).__init__(*args, **kwargs)
     self.container = simpy.Container(self.env)
     self.resource = simpy.Resource(self.env)
     self.queue = Queue(self.env)
     self.pool = Pool(self.env)
     self.a = CompA(self)
     self.b = CompB(self)
     hints = {}
     if self.env.config['sim.log.enable']:
         hints['log'] = {'level': 'INFO'}
     if self.env.config['sim.vcd.enable']:
         hints['vcd'] = {}
     if self.env.config['sim.db.enable']:
         hints['db'] = {}
     self.auto_probe('container', **hints)
     self.auto_probe('resource', **hints)
     self.auto_probe('queue', **hints)
     self.auto_probe('pool', **hints)
     self.trace_some = self.get_trace_function('something',
                                               vcd={'var_type': 'real'},
                                               log={'level': 'INFO'})
     self.trace_other = self.get_trace_function('otherthing',
                                                vcd={
                                                    'var_type': 'integer',
                                                    'init': ('z', 'z'),
                                                    'size': (8, 8)
                                                })
     self.add_process(self.loop)
Example #29
0
    def __init__(self, env, plate, start_zone, start_soc, vehicle_config,
                 energymix_conf, sim_scenario_conf, sim_start_time):
        engine_type = sim_scenario_conf["engine_type"]
        model = sim_scenario_conf["vehicle_model_name"]

        if engine_type == "electric":
            energymix = energymix_conf
        else:
            energymix = {}

        # Get the vehicle config for "Electric"-"generic e scooter"
        super().__init__(vehicle_config[engine_type][model], energymix)

        self.env = env
        self.plate = plate
        self.zone = start_zone

        self.available = True
        self.soc = simpy.Container(env, init=start_soc,
                                   capacity=100)  # soc: State of Charge

        self.current_status = {
            "time": sim_start_time,
            "status": "available",
            "soc": self.soc.level,
            "zone": self.zone
        }
        self.status_dict_list = [self.current_status]
Example #30
0
 def generateReservoirs(self, env, levels):
     '''
         Helper method to generate reservoirs
     '''
     for fuel in levels:
         self.RESERVOIRS[fuel] = simpy.Container(env,
                                                 levels[fuel],
                                                 init=levels[fuel])