def schedule_paper_drop(obj, contact_type, reminder_type, delay): # add to summary of paper given out if reminder_type == 'pq' and oo.record_paper_summary: for key, value in obj.rep.paper_summary.items(): value[str(getattr(obj, key))][math.floor(obj.rep.env.now / 24)] += 1 for key, value in obj.rep.paper_totals.items(): value[str(getattr(obj, key))] += 1 output_type = contact_type + "_" + reminder_type + "_posted" # use this as output key if oo.record_posted: obj.rep.output_data[output_type].append( oo.generic_output(obj.rep.reps, obj.district.district, obj.la, obj.lsoa, obj.digital, obj.hh_type, obj.hh_id, obj.env.now)) if delay > 0: start_delayed(obj.env, obj.receive_reminder(reminder_type), delay) else: obj.env.process(obj.receive_reminder(reminder_type)) yield obj.env.timeout(0)
def light(): """ This generator function simulates state changes of the traffic light. For simplicity, the light is either green or red--there is no yellow state. """ global env, light while True: # Section 4.2.1: Change the light to green. light = 'green' print("\nThe light turned green at time %.3f." % env.now) # If there are cars in the queue, schedule a departure event: if len(queue): # Generate departure delay as a random draw from triangular # distribution: delay = random.triangular(left=t_depart_left, mode=t_depart_mode, right=t_depart_right) start_delayed(env, departure(), delay=delay) # Schedule event that will turn the light red: yield env.timeout(t_green) # Section 4.2.2: Change the light to red. light = 'red' print("\nThe light turned red at time %.3f." % env.now) # Schedule event that will turn the light green: yield env.timeout(t_red)
def test_start_delayed(env): def pem(env): assert env.now == 5 yield env.timeout(1) start_delayed(env, pem(env), delay=5) env.run()
def message(self, source, dest, message_size, start_time, id=None, method=None, sync=True, packet_stats=False): if start_time == 0: self.env.process( self.send(source, dest, message_size, id=id, method=method, sync=sync, packet_stats=packet_stats)) else: start_delayed( self.env, self.send(route, message_size, id=id, method=method, sync=sync, packet_stats=packet_stats), start_time)
def __init__(self, env, events): self.events = events self.assistant = simpy.Resource(env, CAPACITY) self.requestCount = 0 self.toRecord = False i = 0 for e in self.events: i += 1 start_delayed(env, self.accident(env, i), e)
def runBq(self, with_preempt): self.process = self.env.process(self.runBqHelper(with_preempt)) start_delayed(self.env, self.inject_failure(), INITIAL_FAILURE_DELAY) self.env.process(self.monitorWorkDone()) self.savedJobs = self.allJobs[:] while True: try: yield self.process self.env.exit() except simpy.Interrupt as e: self.process.interrupt(e.cause)
def cloudletSpaceShared(self): for cloudlet in self._resourceList: cloudlet._processingTime = cloudlet._cloudletLength/(cloudlet._numberOfPes*cloudlet.vm.mips) cloudlet._remainingTime = cloudlet._processingTime if cloudlet.submissionTime == 0: self._context.process(cloudlet._process(self._context)) cloudlet.status = 1 else: start_delayed(self._context,cloudlet._process(self._context),cloudlet._submissionTime) cloudlet.status = 1
def load_schedule(self, regular_sche, extra_sche): # schedule personel shifts t = tu.time_sec("2015-12-14 00:00:00") prev = 0 for i in range(77): for day in regular_sche: for h in day: delta = h - prev if delta > 0: for j in range(delta): start_delayed(self.env, self.assistent_join(), t - self.zeroTime) prev += 1 if delta < 0: for j in range(-delta): start_delayed(self.env, self.assistent_leave(), t - self.zeroTime) prev -= 1 t += 3600 for e in extra_sche: t = tu.time_sec(e[0] + " 00:00:00") for i in range(e[1]): start_delayed(self.env, self.assistent_join(), t - self.zeroTime) t = tu.time_sec(e[0] + " 23:59:59") for i in range(e[1]): start_delayed(self.env, self.assistent_leave(), t - self.zeroTime) self.extraEvents = len(extra_sche) self.regular_sche = regular_sche
def __init__(self, env, events, capacity=2): self.CAPACITY = capacity self.events = events self.assistant = simpy.Resource(env, self.CAPACITY) self.requestCount = 0 self.toRecord = False # move just before the first event zeroTime = self.events[0] - 1 env.run(zeroTime) i = 0 for evnt in self.events: i += 1 start_delayed(env, self.accident(env, Call(evnt, i)), evnt - zeroTime)
def __init__(self, env, rep, district, input_data, letter_type): self.env = env self.rep = rep self.district = district self.input_data = input_data self.letter_type = letter_type self.blanket = h.str2bool(self.input_data["blanket"]) self.targets = self.input_data["targets"] self.start_sim_time = h.get_event_time(self) self.period = self.input_data["period"] # add process to decide who to send letters too...but with a delay start_delayed(self.env, self.fu_letter(), self.start_sim_time)
def cloudletSpaceShared(self): for cloudlet in self._resourceList: cloudlet._processingTime = cloudlet._cloudletLength / ( cloudlet._numberOfPes * cloudlet.vm.mips) cloudlet._remainingTime = cloudlet._processingTime if cloudlet.submissionTime == 0: self._context.process(cloudlet._process(self._context)) cloudlet.status = 1 else: start_delayed(self._context, cloudlet._process(self._context), cloudlet._submissionTime) cloudlet.status = 1
def __init__(self, env: simpy.Environment, name): self.name = name self.light_vertical = True self.queue_W = deque() self.queue_N = deque() self.queue_E = deque() self.queue_S = deque() self.env = env if not manual: self.action = env.process(self.run()) # Schedule first arrival of a car: t_first_arrival = np.random.exponential(t_interarrival_mean) start_delayed(env, self.arrival(), delay=t_first_arrival)
def start(): global env while True: # If there are cars in the queue, schedule a departure event: if len(q1) or len(q2) or len(q3) or len(q4): # Generate departure delay as a random draw from triangular # distribution: delay= random.triangular(left=t_depart_left, mode=t_depart_mode, right=t_depart_right) start_delayed(env, departure(), delay=delay) yield env.timeout(t_green) yield env.timeout(t_red)
def light(): """ Simulates state changes of the traffic light. """ global env, light while True: light= 'green' print("\nThe light turned green at time %.3f." % env.now) if len(queue): delay= random.triangular(left=t_depart_left, mode=t_depart_mode, right=t_depart_right) start_delayed(env, departure(), delay=delay) yield env.timeout(t_green) light= 'red' print("\nThe light turned red at time %.3f." % env.now) yield env.timeout(t_red)
def parent(env): print(f'parent start at {env.now}') sub_proc = yield start_delayed( env, sub(env), delay=3) # delay 3 unit time, then call sub(env) print(f'sub_proc start at {env.now}') ret = yield sub_proc # this yield is necessary to get the sub(env) return print(f'parent ret start at {env.now} ret={ret}') return ret
def switchAndDepart(self): """ This generator function simulates state changes of the traffic light. For simplicity, the light is either green or red--there is no yellow state. """ # Section 4.2.1: Change the light to green. self.switch_light() # If there are cars in the queue, schedule a departure event: if self.light_vertical: if len(self.queue_W): # Generate departure delay as a random draw from triangular # distribution: delay = np.random.triangular(left=t_depart_left, mode=t_depart_mode, right=t_depart_right) start_delayed(self.env, self.departure(self.queue_W), delay=delay) if len(self.queue_E): # Generate departure delay as a random draw from triangular # distribution: delay = np.random.triangular(left=t_depart_left, mode=t_depart_mode, right=t_depart_right) start_delayed(self.env, self.departure(self.queue_E), delay=delay) else: if len(self.queue_N): # Generate departure delay as a random draw from triangular # distribution: delay = np.random.triangular(left=t_depart_left, mode=t_depart_mode, right=t_depart_right) start_delayed(self.env, self.departure(self.queue_N), delay=delay) if len(self.queue_S): # Generate departure delay as a random draw from triangular # distribution: delay = np.random.triangular(left=t_depart_left, mode=t_depart_mode, right=t_depart_right) start_delayed(self.env, self.departure(self.queue_S), delay=delay)
def respond(self, delay=0): """represents the hh responding - not the return being received by census""" if self.responded is False: self.responded = True self.resp_time = self.env.now # add to hh response event log self.output_data['Respond'].append(response(self.rep.reps, self.district.input_data["LA"], self.digital, self.hh_type, self.resp_time)) if self.delay == 0: # digital self.env.process(censusv2.ret_rec(self, self.rep)) else: # paper start_delayed(self.env, censusv2.ret_rec(self, self.rep), delay) yield self.env.timeout((self.rep.sim_hours) - self.env.now) # hh does no more (without intervention)
def __init__(self, filename, qos=20): self.env = simpy.Environment() self.capacity = 1 self.assistant = simpy.Container(self.env, 100, self.capacity) self.requestCount = 0 self.waitAgg = 0 self.count = 0 self.qos = qos self.aboveQos = 0 self.sim_data = [] self.extraEvents = 0 self.events = CallCenter.load_events(filename) self.regular_sche = None # schedule calls # move just before the first event (operator in service is the first event - before the first call) self.zeroTime = tu.time_sec("2015-12-14 00:00:00") - 1 self.env.run(self.zeroTime) i = 0 for evnt in self.events: i += 1 start_delayed(self.env, self.accident(self.env, Call(evnt, i)), evnt - self.zeroTime)
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
def household_returns(self, delay=0): """represents the hh returning their form - not the return being counted as a response by census""" if not self.return_sent: self.return_sent = True self.resp_time = self.env.now # add to hh response event log if oo.record_return_sent: self.output_data['Return_sent'].append(oo.generic_output(self.rep.reps, self.district.district, self.la, self.lsoa, self.digital, self.hh_type, self.hh_id, self.resp_time)) if self.calc_delay() == 0: # digital self.env.process(hq.ret_rec(self, self.rep)) else: # paper start_delayed(self.env, hq.ret_rec(self, self.rep), delay) yield self.env.timeout(0) # hh does no more (without intervention)
def __init__(self, rep, env, district, input_data, co_id): self.rep = rep self.env = env self.district = district self.input_data = input_data self.co_id = co_id self.rnd = self.rep.rnd self.action_plan = [] self.start_date = dt.datetime.strptime((self.input_data['start_date']), '%Y, %m, %d').date() self.end_date = dt.datetime.strptime((self.input_data['end_date']), '%Y, %m, %d').date() self.has_pq = h.str2bool(self.input_data['has_pq']) self.has_postcard = h.str2bool(self.input_data['has_postcard']) self.start_sim_time = h.get_entity_time( self) # self.co_start_time() # the sim time the co starts work self.end_sim_time = h.get_entity_time( self, "end") # self.co_end_time() # the sim time the co ends work self.active_time = [] # as above but for active time # start work at correct time start_delayed(self.env, self.co_working_test(), self.start_sim_time)
def parent(env): sub_proc = yield start_delayed(env, sub(env), delay=3) ret = yield sub_proc return ret
return e.between_green(count) print("\nSimulation of Cars Arriving at Intersection Controlled by a Traffic " "Light\n\n") # Initialize environment: env= simpy.Environment() # Schedule first change of the traffic light: env.process(light()) # Schedule first arrival of a car: t_first_arrival= random.exponential(t_interarrival_mean) start_delayed(env, arrival(), delay=t_first_arrival) # Schedule first statistical monitoring event: env.process(monitor()) # Let the simulation run for specified time: env.run(until=end_time) e.save_model() # Section 6: Report statistics. print("\n\n *** Statistics ***\n\n") print("Mean number of cars waiting: %.3f" % (Q_stats.cars_waiting / float(Q_stats.count)))
def delayed_exec(self, delay, func, *args, **kwargs): func = ensure_generator(self.env, func, *args, **kwargs) start_delayed(self.env, func, delay=delay)
# 3 - Coupon cost # 4 - orders that took more than 2 hours to deliver print("Policy %s:" % (POLICY)) #### MAIN LOOP week = 1 while week < 101: #### Set simulation environment env = simpy.Environment() drone_company = DroneCompany(env) ############################## Rate changes schedule ############################################ for i in range(0, 5): mult = i * 24 start_delayed(env, drone_company.changeRate(1), ((5 + mult) * 60)) start_delayed(env, drone_company.changeRate(2), (10 + mult) * (60)) start_delayed(env, drone_company.changeRate(3), (16 + mult) * (60)) if i != 4: start_delayed(env, drone_company.changeRate(4), (22 + mult) * (60)) else: start_delayed(env, drone_company.changeRate(5), (22 + mult) * 60) ############################## Rate changes schedule ############################################ env.process(ordersArrival(env, drone_company)) env.run() # the simulation will run until all orders have been processed. # calculate how much days, hours and minutes the simulation was running. days = np.floor(env.now / (60 * 24)) hours = np.floor((env.now / 60) - (days * 24)) minutes = ((env.now / 60) - (days * 24) - hours) * 60
def start_fu(self): hh_list = sorted(list(self.input_data['households'].keys())) delay = min([self.input_data['households'][hh]['FU_start_time'] for hh in hh_list]) start_delayed(self.env, censusv2.start_fu(self.env, self), delay)
last_return_count = returned_books_count last_return_time = books_return_time daily_return_times.append( today_return_time / (today_return_count * ONE_DAY) if today_return_count > 0 else 0) daily_lost_patience.append(lost_patience_counts - last_lost_patience) last_lost_patience = lost_patience_counts yield env.timeout(ONE_DAY) # Process for random addition of books env.process(book_generator(env, available_books, book_names)) start_delayed(env, dailyReporter(env), delay=ONE_DAY - 1) print("Starting simulation") env.run(until=RUN_DURATION) print("Simulation completed") sns.set(style="darkgrid") df = pd.DataFrame({ 'time': np.arange(RUN_DURATION//ONE_DAY), 'total books': daily_total_book_counts, 'borrowed_books': daily_borrowed_counts, 'Average return times': daily_return_times, 'Daily patience lost': daily_lost_patience}) print(df[:15])
def parent(env): # Pay attention to the additional yield needed for the helper process. sub_proc = yield start_delayed(env, sub(env), delay=3) ret = yield sub_proc print(ret, env.now) return ret
def __init__(self, env, events, capacity=2, qos=20): self.CAPACITY = capacity self.events = events self.assistant = simpy.Container(env, 100,self.CAPACITY) self.requestCount = 0 self.toRecord = False self.waitAgg = 0 self.count = 0 self.qos = qos self.aboveQos = 0 #schedule calls # move just before the first event zeroTime = self.events[0] - 1 env.run(zeroTime) i = 0 for evnt in self.events: i += 1 start_delayed(env, self.accident(env, Call(evnt, i)), evnt - zeroTime) #schedule personel shifts endTime = self.events[-1] t = tu.time("2015-12-14 00:00:00") while tu.sec(t) < endTime: # mon-fri +1, 10-19 for i in range(5): t = tu.plusHours(t,9) start_delayed(env, self.assistent_join(env), tu.sec(t) - zeroTime) t = tu.plusHours(t,1) #one more mon - fri, 10-14 start_delayed(env, self.assistent_join(env), tu.sec(t) - zeroTime) t = tu.plusHours(t,4) start_delayed(env, self.assistent_leave(env), tu.sec(t) - zeroTime) t = tu.plusHours(t,5) start_delayed(env, self.assistent_leave(env), tu.sec(t) - zeroTime) t = tu.plusHours(t,5) # sat-sun +1, 10-18 for i in range(2): t = tu.plusHours(t,10) start_delayed(env, self.assistent_join(env), tu.sec(t) - zeroTime) t = tu.plusHours(t,9) start_delayed(env, self.assistent_leave(env), tu.sec(t) - zeroTime) t = tu.plusHours(t,5)
random.seed([1, 2, 3]) TOTAL_TIME = 300.0 ARRIVAL_RATE = 0.2 t_green= 30.0; t_red= 40.0 t_depart_left= 1.6; t_depart_mode= 2.0; t_depart_right= 2.4 queue= deque() arrival_count= departure_count= 0 Q_stats= Struct(count=0, cars_waiting=0) W_stats= Struct(count=0, waiting_time=0.0) # Run the simulation print("\nSimulation started!\n\n") env= simpy.Environment() env.process(light()) start_delayed(env, arrival(), delay=random.exponential(1.0 / ARRIVAL_RATE)) env.process(monitor()) env.run(until=TOTAL_TIME) # Report statistics. print("\n\n ======== Statistics =======\n\n") print("Mean number of cars waiting: %.3f" % (Q_stats.cars_waiting / float(Q_stats.count))) print("Mean waiting time (seconds): %.3f" % (W_stats.waiting_time / float(W_stats.count)))
import math import simpy from simpy.util import start_delayed from environment import ForwardableRealtimeEnvironment from systems.producers import CogenerationUnit, PeakLoadBoiler from systems.storages import HeatStorage, ElectricalInfeed from systems.consumers import ThermalConsumer, ElectricalConsumer # initialize real-time environment env = ForwardableRealtimeEnvironment( initial_time=0, factor=1.0/3600.0, strict=False) # initialize power systems heat_storage = HeatStorage(env=env) electrical_infeed = ElectricalInfeed() cu = CogenerationUnit(env=env, heat_storage=heat_storage, electrical_infeed=electrical_infeed) plb = PeakLoadBoiler(env=env, heat_storage=heat_storage) thermal_consumer = ThermalConsumer(env=env, heat_storage=heat_storage) electrical_consumer = ElectricalConsumer(env=env, electrical_infeed=electrical_infeed) # add power system to simulation environment env.process(thermal_consumer.update()) env.process(electrical_consumer.update()) env.process(cu.update()) # start plb 10h after simulation start start_delayed(env, plb.update(), 10 * 3600)
def checkin_book(self, book): ''' Process function to check in a book PARAMETERS:- book (Book object) : The book to be returned ''' # global LOGS_ENABLED if(LOGS_ENABLED): print("Day %03d Student %s is reading %s" % (self.env.now//ONE_DAY, self.name, book.name)) reading_time = random.normalvariate(BOOKS_RETURN_MEAN, BOOKS_RETURN_SD) if(reading_time < ONE_HOUR): # Reading time is dependent on a random normal distribution reading_time = ONE_HOUR yield self.env.timeout(reading_time) if((env.now % ONE_DAY) < OPENING_TIME): # If Library is not yet open yield self.env.timeout(random.uniform(OPENING_TIME, CLOSING_TIME) - self.env.now % ONE_DAY) elif((self.env.now % ONE_DAY) > CLOSING_TIME): # Library is closed yield self.env.timeout(ONE_DAY + (random.uniform(OPENING_TIME, CLOSING_TIME)) - self.env.now % ONE_DAY) if(self.env.now % ONE_WEEK >= SUNDAY): # It's sunday! yield env.timeout(ONE_DAY + random.uniform(OPENING_TIME, CLOSING_TIME) - self.env.now % ONE_DAY) if(LOGS_ENABLED): print("Day %03d Student %s is returning %s" % (self.env.now//ONE_DAY, self.name, book.name)) book.status = Status.RETURNING # Checking if book is lost with counter.request() as req: # Wait for counter to be free or until patience runs out results = yield req | env.timeout(self.patience) if(req not in results): # We lost patience if(LOGS_ENABLED): print("Day %03d Student %s lost patience while returning book %s. They will be back in an hour" % ( self.env.now//ONE_DAY, self.name, book.name)) global lost_patience_counts lost_patience_counts += 1 self.free.succeed self.free = self.env.event() if(env.now > book.due_date): yield self.env.process(self.checkin_book(book)) else: # If book is not due today, return back tomorrow yield start_delayed(env, self.checkin_book(book), delay=ONE_DAY) return None if(random.random() < PROB_LOSE_TRESHOLD): # Probability that the book is lost if(LOGS_ENABLED): print("Day %03d Student %s lost the book %s" % (self.env.now//ONE_DAY, self.name, book.name)) book.status = Status.LOST global books_lost_count books_lost_count += 1 if(book.status == Status.LOST): # If book is lost yield self.env.timeout(random.randint(LOST_TIME_MIN, LOST_TIME_MAX)) elif(book.due_date >= self.env.now): # If returning on time yield self.env.timeout(random.randint(CHECKIN_MIN_TIME, CHECKIN_MAX_TIME)) else: # If returning late yield self.env.timeout(random.randint(LATE_CHECKIN_MIN, LATE_CHECKIN_MAX)) if(book.status != Status.LOST): book.resouce.release(book.req) book.status = Status.AVAILABLE global returned_books_count returned_books_count += 1 global books_return_time books_return_time += env.now - book.due_date self.books_borrowed.remove(book) self.free.succeed() # The student is now free self.free = self.env.event()
#including : think about the last_jobend if len(running_jobs[j.user_id]) == 0: user_info[j.user_id]['last_jobend'] = env.now def job_process(j): job_submit(j) yield env.timeout(j.wait_time) job_start(j) yield env.timeout(j.run_time) job_end(j) from simpy.util import start_delayed for j in data: start_delayed(env, job_process(j), j.submit_time) #TODO:DEL dataframe #print(users) #for user in users: #print("User %s with %s campaigns:" %(user.uid,len(user.campaign_deque))) #for campaign in user.campaign_deque: #print(campaign) #for job in campaign.jobs: #print(job) #if arguments['--verbose'] == True: #system.set_monitor(system_monitor(system,env,FileBackend(env,'csim_system.log'))) #ubackend=FileBackend(env,'csim_users.log') #for u in users:
file_csv = open("equal.txt", "a+") print("\nSimulation of Cars Arriving at Intersection Controlled by a Traffic\n\n") # Total number of seconds to be simulated: end_time= float(argv[1]) # Initialize environment: env= simpy.Environment() # Schedule first change of the traffic light: env.process(start()) # Schedule first arrival of a car: t_first_arrival= random.exponential(t_interarrival_mean) start_delayed(env, arrival(), delay=t_first_arrival) # Schedule first statistical monitoring event: env.process(monitor()) # Let the simulation run for specified time: env.run(until=end_time) # Section 6: Report statistics. print("\n\n *** Statistics ***\n\n") print("Mean number of cars waiting: %.3f" % (Q_stats.cars_waiting / float(Q_stats.count)))
def set_action(tasks): for task in tasks: if delays[task.id] > 0: task.action = start_delayed(task.env, task.run(), delays[task.id]) else: task.action = env.process(task.run())
def receive_reminder(self, reminder_type): # a reminder has been received. This determines the outcome fo that reminder and if it was worthwhile. if oo.record_reminder_received: self.rep.output_data[reminder_type + '_received'].append(oo.reminder_received(self.rep.reps, self.district.district, self.la, self.lsoa, self.digital, self.hh_type, self.hh_id, self.env.now, reminder_type)) # set resp according to type of hh and reminder if not self.resp_planned and reminder_type == 'pq' and self.engaged: self.paper_allowed = True self.resp_level = 100 # so this assumes if you provide paper to those engaged they will respond elif not self.resp_planned: behaviour = self.default_behaviour() # and get relevant figures try: response_data = self.input_data["behaviours"][reminder_type][behaviour] except: pass self.resp_level = response_data["response"] if self.rep.total_ad_instances > 0: self.help_level = response_data["help"] else: self.help_level = 0 # recorded if wasted, unnecessary or successful if self.responded: if oo.record_reminder_wasted: self.rep.output_data[reminder_type + '_wasted'].append(oo.reminder_wasted(self.rep.reps, self.district.district, self.la, self.lsoa, self.digital, self.hh_type, self.hh_id, self.env.now, reminder_type)) elif self.resp_planned: if oo.record_reminder_unnecessary: self.rep.output_data[reminder_type + '_unnecessary'].append(oo.reminder_unnecessary(self.rep.reps, self.district.district, self.la, self.lsoa, self.digital, self.hh_type, self.hh_id, self.env.now, reminder_type)) # now move on to the relevant action based on extracted values reminder_test = self.rnd.uniform(0, 100) if not self.resp_planned and reminder_test <= self.resp_level: if oo.record_reminder_success: self.rep.output_data[reminder_type + '_success'].append(oo.reminder_success(self.rep.reps, self.district.district, self.la, self.lsoa, self.digital, self.hh_type, self.hh_id, self.env.now, reminder_type)) # change to a start delayed at appropriate time depending on day.... delay = h.get_time_of_return(self.env.now, self.rep) # yield self.env.process(self.household_returns(self.calc_delay())) ########## # if this is a pq, but a digital household, calculate if the household retunrs via paper or digital? # Or assume use preferred method for now? # could use paper first paper prop to set this? so set digital to true or false... ########## start_delayed(self.env, self.household_returns(self.calc_delay()), delay) yield self.env.timeout(0) elif not self.resp_planned and (self.resp_level < reminder_test <= self.resp_level + self.help_level): # call for help...needs to be based on appropriate distribution...not a hardcoded uniform function! # also may not do this if intend to respond? yield self.env.timeout(self.rnd.uniform(0, 8)) if oo.record_do_nothing: self.output_data[reminder_type + '_contact'].append(oo.generic_output(self.rep.reps, self.district.district, self.la, self.lsoa, self.digital, self.hh_type, self.hh_id, self.env.now)) yield self.env.process(self.contact()) else: # nowt if oo.record_do_nothing: self.output_data[reminder_type + '_failed'].append(oo.generic_output(self.rep.reps, self.district.district, self.la, self.lsoa, self.digital, self.hh_type, self.hh_id, self.env.now)) yield self.env.timeout(0)
def __init__(self, rep, name): # values fed into class self.rep = rep self.district = name # created by and belong too the class self.rnd = self.rep.rnd self.env = self.rep.env self.input_data = self.rep.input_data['districts'][name] self.households = [] # list of household objects in the district self.district_co = [] # list of CO assigned to the district self.letters = [] # list of letters to be sent to hh in the district self.total_households = 0 # count of total including those not represented by objects # self.return_rate = 0 # self.travel_dist = 0 # average travel distance between hh for district self.early_responders = 0 # records number of hh who return prior to first interaction self.postal_delay = self.input_data['postal_delay'] self.total_responses = 0 if self.input_data["census officer"]: self.create_co() if self.input_data["letter_phases"]: self.create_letterphases( ) # set processes to start the sending of letters try: self.first_visit = min( [co.start_sim_time for co in self.district_co]) except ValueError as e: # if no visits then set to end of sim self.first_visit = self.rep.sim_hours try: self.first_letter = min( [letter.start_sim_time for letter in self.letters]) except ValueError as e: # if no letters then set to end of sim self.first_letter = self.rep.sim_hours if self.district_co: self.first_interaction = min( self.first_visit, self.first_letter) # time of first interaction start_delayed(self.env, FFU.start_fu(self.env, self), math.floor(self.first_visit / 24) * 24) else: self.first_interaction = 0 # create households that exist in the district self.create_households() # randomise list - so ignore priority self.rnd.shuffle(self.households) try: self.hh_area = self.input_data['district_area'] / len( self.households) self.initial_hh_sep = 2 * (math.sqrt(self.hh_area / math.pi)) except ZeroDivisionError as e: warning_detail = ("Zero division error in run: ", self.rep.run, ", rep: ", self.rep.reps, " for district: ", self.district, ". HH separation set to zero") # write out a warning here but don't stop the sim just set the dist to zero if oo.record_warnings: self.rep.output_data['Warnings'].append( oo.warnings(self.rep.reps, e, warning_detail)) self.initial_hh_sep = 0 self.env.process(self.av_travel_dist()) self.env.process(self.start_hh()) start_delayed(self.env, self.non_response(), self.rep.sim_hours - 0.0000001)
def cloudletTimeShared(self): processTimes = {} resourceListStart = [] resourceListDelayed = [] for cloudlet in self._resourceList: if cloudlet._submissionTime == 0: processTimes[cloudlet] = cloudlet._cloudletLength/(cloudlet._numberOfPes*cloudlet._vm.mips) cloudlet._remainingTime = cloudlet._cloudletLength/(cloudlet._numberOfPes*cloudlet._vm.mips) resourceListStart.append(cloudlet) cloudlet.status = 1 else: resourceListDelayed.append(cloudlet) time = 0 while len(processTimes) == 0: time += 100 dummyList = list(resourceListDelayed) for cloudlet in dummyList: if time >= cloudlet._submissionTime: processTimes[cloudlet] = cloudlet._cloudletLength/(cloudlet._numberOfPes*cloudlet._vm.mips) cloudlet._remainingTime = cloudlet._cloudletLength/(cloudlet._numberOfPes*cloudlet._vm.mips) resourceListDelayed.remove(cloudlet) cloudlet.status = 1 while True: dummyList = list(resourceListDelayed) for cloudlet in dummyList: if time >= cloudlet._submissionTime: processTimes[cloudlet] = cloudlet._cloudletLength/(cloudlet._numberOfPes*cloudlet._vm.mips) cloudlet._remainingTime = cloudlet._cloudletLength/(cloudlet._numberOfPes*cloudlet._vm.mips) resourceListDelayed.remove(cloudlet) keys = processTimes.keys() for i in keys: dummyList = list(resourceListDelayed) for cloudlet in dummyList: if time >= cloudlet._submissionTime: processTimes[cloudlet] = cloudlet._cloudletLength/(cloudlet._numberOfPes*cloudlet._vm.mips) cloudlet._remainingTime = cloudlet._cloudletLength/(cloudlet._numberOfPes*cloudlet._vm.mips) resourceListDelayed.remove(cloudlet) if time == 0: self._context.process(i._process(self._context,100)) else: start_delayed(self._context,i._process(self._context,100),time) processTimes[i] -= 100 if processTimes[i] <= 0: del processTimes[i] time += 100 if len(processTimes) == 0: if len(resourceListDelayed) == 0: break else: time += 100
N=user_info[j.user_id]['usercount'] user_info[j.user_id]['usermean']=user_info[j.user_id]['usermean']*N/(N+1) + j.run_time /(N+1) #including : think about the last_jobend if len(running_jobs[j.user_id])==0: user_info[j.user_id]['last_jobend']=env.now def job_process(j): job_submit(j) yield env.timeout(j.wait_time) job_start(j) yield env.timeout(j.run_time) job_end(j) from simpy.util import start_delayed for j in data: start_delayed(env,job_process(j),j.submit_time) #TODO:DEL dataframe #print(users) #for user in users: #print("User %s with %s campaigns:" %(user.uid,len(user.campaign_deque))) #for campaign in user.campaign_deque: #print(campaign) #for job in campaign.jobs: #print(job) #if arguments['--verbose'] == True: #system.set_monitor(system_monitor(system,env,FileBackend(env,'csim_system.log'))) #ubackend=FileBackend(env,'csim_users.log') #for u in users: