def __init__(self, run_number):
        self.env = simpy.Environment()
        self.patient_counter = 0

        self.receptionist = simpy.Resource(self.env,
                                           capacity=g.number_of_receptionists)
        self.nurse = simpy.Resource(self.env, capacity=g.number_of_nurses)

        # If we want a queue where higher priority entities are seen first,
        # then the resource they queue for needs to be a PriorityResource
        self.ed_doctor = simpy.PriorityResource(
            self.env, capacity=g.number_of_ed_doctors)
        self.acu_doctor = simpy.PriorityResource(
            self.env, capacity=g.number_of_acu_doctors)

        self.run_number = run_number

        self.mean_q_time_registration = 0
        self.mean_q_time_triage = 0
        self.mean_q_time_ed_assessment = 0
        self.mean_q_time_acu_assessment = 0

        self.results_df = pd.DataFrame()
        self.results_df["P_ID"] = []
        self.results_df["Q_Time_Registration"] = []
        self.results_df["Q_Time_Triage"] = []
        self.results_df["Q_Time_ED_Assessment"] = []
        self.results_df["Q_Time_ACU_Assessment"] = []
        self.results_df.set_index("P_ID", inplace=True)
Example #2
0
 def __init__(self, env, CAPACITY1, CAPACITY2, CAPACITY3, CAPACITY4,
              CAPACITY5):
     self.env = env
     self.res_step1_tools = simpy.PriorityResource(env, capacity=CAPACITY1)
     self.res_step2_tools = simpy.PriorityResource(env, capacity=CAPACITY2)
     self.res_step3_tools = simpy.PriorityResource(env, capacity=CAPACITY3)
     self.res_step4_tools = simpy.PriorityResource(env, capacity=CAPACITY4)
     self.res_step5_tools = simpy.PriorityResource(env, capacity=CAPACITY5)
Example #3
0
    def __init__(self, simpy_env, id_num):
        self.simpy_env = simpy_env
        self.name = id_num
        self.queues = {
            'north': simpy.PriorityResource(simpy_env, 1),
            'south': simpy.PriorityResource(simpy_env, 1),
            'east': simpy.PriorityResource(simpy_env, 1),
            'west': simpy.PriorityResource(simpy_env, 1)
        }

        self.direction = (random.random() > 0.5)  # True is North
        self.light_change_time = 0.
        self.accrued_reward = 0.
        self.time_trigger = -1
        self.sojourn_time = -1
        return
Example #4
0
    def __init__(self, nr_resources=1, priority=False, *args, **kwargs):
        super().__init__(*args, **kwargs)
        """Initialization"""

        self.resource = (simpy.PriorityResource(
            self.env, capacity=nr_resources) if priority else simpy.Resource(
                self.env, capacity=nr_resources))
Example #5
0
 def __init__(self, env, num_landingstrips):
     self.env = env
     self.runway = simpy.PriorityResource(env, num_landingstrips)
     self.num_landingstrips = num_landingstrips
     self.snowplows = simpy.Resource(env, numPlows)
     self.plowingMachine = env.process(self.snowplow())
     self.deicetruckResource = simpy.Resource(env, numDeiceTrucks)
Example #6
0
 def messageDAG(self, D):
     messages = {
         v: simpy.PriorityResource(self.env, capacity=D.out_degree(v))
         for v in D.nodes if D.out_degree(v) > 0
     }
     for v in D.nodes:
         if D.out_degree(v) == 0:
             messages[v] = None
     for M in D.nodes:
         source, dest, idx = M
         method = D.nodes[M].get("method", None)
         packet_stats = D.nodes[M].get("packet_stats", False)
         sync = D.nodes[M].get("sync", True)
         message_size = D.nodes[M]["message_size"]
         self.env.process(
             self.DAGsend(source,
                          dest,
                          message_size,
                          messages[M],
                          D.out_degree(M),
                          [messages[x] for x in D.predecessors(M)],
                          packet_stats=packet_stats,
                          id=M,
                          method=method,
                          sync=sync))
Example #7
0
 def __init__(self, env, ncajas, estacionamientos):
     self.abierto = True
     self.parking = simpy.PriorityResource(
         env, capacity=estacionamientos
     )  # Estacionamiento es una priorityResource
     self.cajas = []  # Lista de cajas
     self.env = env  # simpy
     for i in range(ncajas):
         self.cajas.append(Cola(env, SuperMercado.id_caja,
                                self))  # Agregamos las cajas
         SuperMercado.id_caja += 1
     self.C = sum([len(i.cola)
                   for i in self.cajas])  # Valor C del enunciado
     self.productos = dict(
     )  # diccionario con todos los productos y sus cantidades del super
     for i in productos:
         for j in productos[i]:
             self.productos[j] = productos[i][j]["cantidad"]
     self.tipos = dict()  # Diccionario con productos y su cantidad comprada
     self.clientes = []  # Lista de Clientes
     self.ganancias = 0  # Ganancias Totales
     self.llegada_cliente = 0
     self.clientes_id = 0
     self.abre_caja = 1000000000000  # Valor muy grande para no interferir en el programa
     self.gasto = deque()  # gasto por cada cliente que pasa por el super
     self.tiempo = deque()  # tiempo por cada cliente que pasa por el super
     self.cola = deque()  # tiempo que pasa en la cola cada cliente
    def __init__(self, env, sim_params, replication, arrival_data):

        # Extra Stuff
        self.env = env
        self.directory = sim_params.directory

        # Input_data
        self.curr_repl = replication
        self.input_data = deepcopy(sim_params)
        self.replication = replication

        # random streams
        self.rand_arrivals = np.random.RandomState()
        self.rand_other = np.random.RandomState()
        self.rand_arrivals.seed(replication)
        self.rand_other.seed(replication)

        # Resource
        self.scan_resource = simpy.PriorityResource(
            env, self.input_data.arrParams.capacity)

        # Results
        self.patient_results = []
        self.arr_queue_results = {
            'day': [],
            'initial_arrival': [],
            'end_queue': []
        }
Example #9
0
    def __init__(self, env, nbTasks, nbNodes_stg1, nbNodes_stg2, data1, data2):
        
        self.data1 = data1
        self.data2 = data2
        self.env = env
        self.nbTasks = nbTasks
        self.nbNodes_stg1 = nbNodes_stg1
        self.nbNodes_stg2 = nbNodes_stg2

        self.nodeDict_stg1 = {}
        for cpu in range(self.nbNodes_stg1):
            self.nodeDict_stg1["cpu%d"%cpu] = simpy.Resource(self.env, capacity=1)

        self.nodeDict_stg2 = {}
        for gpu in range(self.nbNodes_stg2):
            self.nodeDict_stg2["gpu%d"%gpu] = simpy.PriorityResource(self.env, capacity=1)

        self.sysTime = [0 for i in range(self.nbTasks+2)]
        self.departedStg1 = []
        self.departedStg2 = 0

        self.action1 = self.env.process(self.stg1Runner())
        self.action2 = self.env.process(self.stg2Runner())

        self.totalTime = None
Example #10
0
 def __init__(self, id, env, location, power, Number_of_chargers):
     self.env = env
     self.capacity = Number_of_chargers
     self.plugs = simpy.PriorityResource(self.env, capacity=Number_of_chargers)
     self.id = id
     self.location = location
     self.power = power  # kwh/min
     self.queue = []
Example #11
0
 def __init__(self, env):
     self.state = True
     self.env = env
     self.waiters = simpy.PriorityResource(self.env,
                                           capacity=waiterCapacity)
     self.cookers = simpy.Resource(self.env, capacity=cookerCapacity)
     self.env.process(self.restaurantState())
     self.env.process(self.customerArrive())
Example #12
0
    def __init__(self, env, size):
        self.env = env
        self.size = size
        self.space = simpy.PriorityResource(
            env, capacity=size)  # roundabout resource

        self.lock = simpy.Resource(env,
                                   capacity=1)  # mutex for resources below
        self.next_exit = ('north', 9999)  # { 'dir' }
        self.occupying_cars = []  # { 'exit_dir' : time of exit }
Example #13
0
 def __init__(self, env, level, capacity=1, frequency=1, centre=1):
     self.env = env
     self.level = level
     self.capacity = capacity  # Max number of seats
     self.seats = simpy.PriorityResource(self.env, capacity=capacity)
     self.frequency = frequency  # Hours per week
     self.centre_id = centre  # Centre ID
     self.queue_array = []  # Array of Members in class and wait list
     self.outgoing_edges = []
     self.incoming_edges = []
     self.last_accepted_member = None
     self.last_accepted_centre = None
Example #14
0
    def __init__(self, env, mu, c, scheduler):
        self.env = env
        # Start the run process everytime an instance is created.
        self.c = c
        self.handled = 0

        if scheduler == "FIFO":
            self.server = simpy.Resource(env, self.c)
        elif scheduler == "SJF":
            self.server = simpy.PriorityResource(env, self.c)
        else:
            raise Exception("Unknown scheduler type.")
 def __init__(self, env, name, food_ready, out_pipe,
              hostToGuestInteractionTime, num_of_conversations):
     self.env = env
     self.name = name
     self.food_ready = food_ready
     self.out_pipe = out_pipe
     self.hostToGuestInteractionTime = hostToGuestInteractionTime
     self.conversation = simpy.PriorityResource(
         env, capacity=num_of_conversations)
     self.guests = []
     self.guests_notified = False
     self.timeSpentTalking = 0
Example #16
0
    def __init__(self, router_id, env, poisson_mean, num_packets):
        self.router_id = router_id
        self.env = env
        self.router_links = []
        self.poisson_mean = poisson_mean
        self.num_packets = num_packets
        self.num_packets_delivered = 0
        self.packet_queue = simpy.PriorityResource(self.env, capacity=1)

        # These are the packets that have been sucessfully transmitted.
        self.packets = {}
        self.env.process(self.generate_packet())
Example #17
0
 def __init__(self, env, latency, max_hosts = 100):
     self.next_available_address = 1
     self.channel = simpy.Resource(env)
     self.node_list_access = simpy.PriorityResource(env, capacity = 1)   # Para evitar conflito entre send_broadcast e check_lease
     self.env = env
     self.timeout = env.timeout
     self.latency = latency
     self.max_hosts = max_hosts
     self.full_capacity = False
     # DHCP Simples
     self.default_lease_time = 40
     self.addr_list = [{'node':None, 'lease':0} for i in range(self.max_hosts)] # O índice da lista serve como 'IP'
     self.node_list = []                                                 # Usamos esta lista para fazer broadcasts e checar empréstimos
    def __init__(self, env, lamb, mu, n_servers, n_clients):
        self.env = env
        # Start the run process everytime an instance is created.
        #Capacity is the amount of servers n, standard Queue is FIFO
        self.mu = mu
        self.lamb = lamb
        self.n_servers = n_servers
        self.n_clients = n_clients

        self.server = simpy.PriorityResource(env, capacity=n_servers)
        self.action = env.process(self.arriving(env, lamb, mu, self.server))
        self.waiting_times = []
        self.server_times = []
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 #20
0
    def __init__(self, node, *args, **kwargs):
        super().__init__(*args, **kwargs)
        """Initialization"""

        waiting_area_resources = 100
        self.waiting_area = {
            node: simpy.Resource(self.env, capacity=waiting_area_resources),
        }

        departure_resources = 4
        self.departure = {
            node: simpy.PriorityResource(self.env,
                                         capacity=departure_resources),
        }
Example #21
0
def simulate():
    env = simpy.Environment()

    runways = simpy.PriorityResource(env, capacity=2)
    gen = PlaneGenerator(env, runways)

    env.run(until=SIM_TIME)

    gen.planes.sort(key=lambda x: x.arrival_time)

    landing_means = take_means(gen.planes, "landing")
    takeoff_means = take_means(gen.planes, "takeoff")

    return landing_means, takeoff_means
Example #22
0
    def __init__(self, env, conf, net, id=None, layer=None, logger=None):

        self.env = env
        self.conf = conf
        self.layer = layer
        self.net = net
        self.logger = logger
        self.id = id or random_string(self.conf["misc"]["id_len"])

        self.max_capacity = 100
        # Resource queue to model congestion
        self.resource_queue = simpy.PriorityResource(
            self.env, capacity=self.max_capacity)
        self.queue = []
Example #23
0
def test_resource_with_priority_queue(env):
    def process(env, delay, resource, priority, res_time):
        yield env.timeout(delay)
        req = resource.request(priority=priority)
        yield req
        assert env.now == res_time
        yield env.timeout(5)
        resource.release(req)

    resource = simpy.PriorityResource(env, capacity=1)
    env.process(process(env, 0, resource, 2, 0))
    env.process(process(env, 2, resource, 3, 10))
    env.process(process(env, 2, resource, 3, 15))  # Test equal priority
    env.process(process(env, 4, resource, 1, 5))
    env.run()
 def __init__(self, env, host, gathering, name, in_pipe,
              guest_interaction_time, num_of_conversations, max_hunger):
     self.env = env
     self.host = host
     self.gathering = gathering
     self.name = name
     self.in_pipe = in_pipe
     self.guest_interaction_time = guest_interaction_time
     self.conversation = simpy.PriorityResource(
         env, capacity=num_of_conversations)
     self.food_ready = False
     self.hunger = 0
     self.max_hunger = max_hunger
     self.ate_food = False
     self.waiting_time = 1
     self.timeSpentTalking = 0
 def set_up_resources(self):
     """
     Set up:
     self.resources: A dictionary of resource objects
     self.resources_available: A dictionary of count of resources available
     self.resources_occupied: A dictionary of count of resources occupied
     """
     # Set up resources
     for key, value in self._params.resource_numbers.items():
         # Store resource objects in a dictionary
         # Set up dictionaries of available and occupied
         self.resources_available[key] = value
         self.resources_occupied[key] = 0
         if value > 0:
             self.resources[key] = simpy.PriorityResource(
                 self._env, capacity=value)
Example #26
0
    def __init__(self, vehSeatCapacity, rollingStockType, simEnv):

        assert (vehSeatCapacity >
                0), "vehSeatCapacity (%s) must be positive" % vehSeatCapacity

        self.doorServiceRateMean = Parameter.boardAlightServiceTimesPerVehicle[
            rollingStockType]

        self.rollingStockType = rollingStockType
        self.cabin = CabinResource(simEnv, vehSeatCapacity)
        self.door = simpy.PriorityResource(simEnv, capacity=1)

        #log book of ridership at arrival (before doors open)
        self.totalRidershipAtArrival = dict()
        self.auxiliaryRidershipAtArrival = dict()
        self.trackedRidershipAtArrival = dict()
Example #27
0
def Simulation(env, clinic, workerSchedule, patientSchedule, outfile):
    global patientCount
    global patientCompleted
    resources = [
        simpy.PriorityResource(env, 1) for _ in range(len(clinic.stations))
    ]
    patientCount = len(patientSchedule.patients)
    patientCompleted = 0
    for i in range(len(workerSchedule.healthcare)):
        env.process(
            workerRun(env, workerSchedule.healthcare[i], clinic, resources))
    for i in range(len(patientSchedule.patients)):
        env.process(
            patientRun(env, patientSchedule.patients[i], clinic, resources,
                       patientSchedule))
    env.run(until=(endTime - startTime) + 1)

    #Clinic Statistics From Simulation Run
    # Average Time in Clinic
    averageClinicTime = 0
    for person in patientSchedule.patients:
        averageClinicTime = averageClinicTime + person.completionTime
    averageClinicTime = averageClinicTime / (len(patientSchedule.patients))

    # Average Idle time for a patient
    averageDownTime = 0
    for person in patientSchedule.patients:
        averageDownTime = averageDownTime + (person.completionTime -
                                             person.timeInService)
        print(person.completionTime)

        personwait = {
            "Name": "personWaitTime",
            "patientName": person.name,
            "startTime": (person.completionTime - person.timeInService)
        }
        db[patientSchedule.date + "result"].insert_one(personwait)

    averageDownTime = averageDownTime / (len(patientSchedule.patients))

    #write statistics to DB
    clinicStats = {
        "Name": "clinicStats",
        "averageClinicTime": averageClinicTime,
        "averageDownTime": averageDownTime
    }
    db[patientSchedule.date + "result"].insert_one(clinicStats)
Example #28
0
def test_sorted_queue_maxlen(env):
    """Requests must fail if more than *maxlen* requests happen
    concurrently."""
    resource = simpy.PriorityResource(env, capacity=10)
    resource.put_queue.maxlen = 1

    def process(env, resource):
        resource.request(priority=1)
        try:
            resource.request(priority=1)
            pytest.fail('Expected a RuntimeError')
        except RuntimeError as e:
            assert e.args[0] == 'Cannot append event. Queue is full.'
        yield env.timeout(0)

    env.process(process(env, resource))
    env.run()
        def __init__(self, env, id):
            self.id = id

            self.speed = building_group.speed
            self.acceleration = building_group.acceleration
            self.jerk = building_group.jerk
            self.carCapacity = building_group.carCapacity
            self.passengerTransferTime = building_group.passengerTransferTime
            self.doorOpeningTime = building_group.doorOpeningTime
            self.doorClosingTime = building_group.doorClosingTime
            # car start running at floor_id=0
            self.carPosition = 0
            # so first destination is floor_id=0:
            self.destination_floor_id = 0
            # car up: (run direction = 1)  car down: (run direction = -1)
            # initial runDirection is up:
            self.runDirection = 1
            # floor where car will go when is empty:
            self.returnFloor = 0
            # car have capacity limit. This is limiter:
            self.carUsage = simpy.PriorityResource(env,
                                                   capacity=self.carCapacity)
            # buffor for avoid once again loaading of passengers just served:
            self.just_inside = []
            #self.doorOpened = env.process(doorOpened(env))
            self.doorOpened_reactivate = env.event()

            # caches for simulation run:
            self.passengersInCar = []
            self.passengersInCarDest = []
            # cache for statistics:
            self.carDepartures = []
            # cache for movement beetween floors:
            #  - simulation time
            #  - actual car height in building
            #  - actual speed
            #  - actual acceleration
            #  - actual jerk
            self.carMovement = [[], [], [], [], []]
            # avarage car load factor for in current simulation:
            self.avgClfValue = 0
Example #30
0
def test_sorted_queue_maxlen(env):
    """Requests must fail if more than *maxlen* requests happen
    concurrently."""
    resource = simpy.PriorityResource(env, capacity=1)
    resource.put_queue.maxlen = 1

    def process(env, resource):
        # The first request immediately triggered and does not enter the queue.
        resource.request(priority=1)
        # The second request is enqueued.
        resource.request(priority=1)
        try:
            # The third request will now fail.
            resource.request(priority=1)
            pytest.fail('Expected a RuntimeError')
        except RuntimeError as e:
            assert e.args[0] == 'Cannot append event. Queue is full.'
        yield env.timeout(0)

    env.process(process(env, resource))
    env.run()