def test_always_idle(self, osrm): """Test to evaluate a courier never moving""" # Constants random.seed(187) on_time = time(0, 0, 0) off_time = time(5, 0, 0) # Services env = Environment() dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) # Creates a courier and runs a simulation courier = Courier( acceptance_policy=self.acceptance_policy, dispatcher=dispatcher, env=env, movement_evaluation_policy=self.movement_evaluation_policy, movement_policy=self.movement_policy, courier_id=self.courier_id, vehicle=self.vehicle, location=self.start_location, on_time=on_time, off_time=off_time) env.run(until=hour_to_sec(4)) # Asserts that the courier is idle and never moved self.assertEqual(courier.condition, 'idle') self.assertEqual(courier.location, self.start_location) self.assertIn(courier.courier_id, dispatcher.idle_couriers.keys())
def cross_sim(): """ cross module test: Cross 模块测试单元 """ env = Environment() INPUT_QUEUE_ID.extend( [''.join([MACHINE_ID, '_in', str(i)]) for i in range(NUM_PORT_IN)] ) OUTPUT_QUEUE_ID.extend( [''.join([MACHINE_ID, '_out', str(i)]) for i in range(NUM_PORT_OUT)] ) for id in INPUT_QUEUE_ID: INPUT_QUEUE_DIC.update({id: PriorityStore(env=env)}) for id in OUTPUT_QUEUE_ID: OUTPUT_QUEUE_DIC.update({id: PriorityStore(env=env)}) generator_queue_res = Resource(env=env, capacity=QUEUE_RES) generator_package_res = Resource(env=env, capacity=PACKAGE_RES) packages(env=env, generator_package_res=generator_package_res, generator_queue_res=generator_queue_res) hospital = Hospital(env=env,id_h=MACHINE_ID, hospital_capacity=NUM_PEOPLE, input_dic=INPUT_QUEUE_DIC, output_dic=OUTPUT_QUEUE_DIC) env.run()
def test_visualized_run(): """test visualized run""" if os.name != "nt" and os.environ.get("DISPLAY", "") == "": print("no display, animated run pointless (e.g. inside a container)") # (this check for DISPLAY does not work on win) return env = Environment() model = Model(env) model.source.max_entities = MAX_ENTITIES width = 451 height = 212 gui = Tk() canvas = ScaledCanvasTk(gui, width, height) visualizer = ProcessVisualizer( canvas, flow_speed=FLOW_SPEED, background_image_path="examples/tilemap/diagram.png", default_entity_icon_path="examples/tilemap/simple_entity_icon.png", ) for block in model.model_components.values(): block.visualizer = visualizer env.run() assert model.sink.overall_count_in == MAX_ENTITIES gui.destroy()
def go_to_movies(mv_env: simpy.Environment, moviegoer: int, theater: Theater): arrival_time: float = mv_env.now print(f'Moviegoer #{moviegoer} arrived to the theater at time interval #{arrival_time}.') with theater.cashier.request() as request: print(f'Moviegoer #{moviegoer} started waiting for a cashier to ' f'purchase a ticket at time interval #{mv_env.now}.') yield request yield mv_env.process(theater.purchase_ticket()) print(f'Moviegoer #{moviegoer} purchased a ticket at time interval #{mv_env.now}') if random.choice([True, False]): with theater.server.request() as request: print(f'Moviegoer #{moviegoer} started waiting for a server to ' f'purchase snacks at time interval#{mv_env.now}.') yield request yield mv_env.process(theater.purchase_food()) print(f'Moviegoer #{moviegoer} purchased snacks at time interval #{mv_env.now}.') with theater.usher.request() as request: print(f'Moviegoer #{moviegoer} is waiting for an usher to check their ticket.') yield request yield mv_env.process(theater.check_ticket()) print(f'The ticket for moviegoer #{moviegoer} was checked at time interval #{mv_env.now}') wait_times.append(mv_env.now - arrival_time)
def set_param(self, name, value): if hasattr(self, name): self.__setattr__(name, value) self.env = Environment() self._create_processors() else: raise AttributeError('simulation do not has this attribution')
def test_movement_state(self, osrm): """Test to evaluate how a courier moves with dummy movement""" # Constants random.seed(365) on_time = time(0, 0, 0) off_time = time(5, 0, 0) env = Environment() dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) # Creates a courier and runs a simulation courier = Courier( acceptance_policy=self.acceptance_policy, dispatcher=dispatcher, env=env, movement_evaluation_policy=self.movement_evaluation_policy, movement_policy=self.movement_policy, courier_id=self.courier_id, vehicle=self.vehicle, location=self.start_location, on_time=on_time, off_time=off_time) env.run(until=hour_to_sec(4) + min_to_sec(5)) # Asserts that the courier moved and is is in a different location self.assertEqual(courier.condition, 'moving') self.assertNotEqual(courier.location, self.start_location) self.assertIn(courier.courier_id, dispatcher.moving_couriers.keys())
def test_prepositioning_notification_rejected_event(self): """Test to verify the mechanics of a prepositioning notification being rejected by a courier""" # Constants initial_time = hour_to_sec(14) on_time = time(14, 0, 0) off_time = time(15, 0, 0) # Services env = Environment(initial_time=initial_time) dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) # Creates a prepositioning notification, a courier and sends the rejected event instruction = Route( stops=[ Stop(position=0, type=StopType.PREPOSITION), Stop(position=1, type=StopType.PREPOSITION) ] ) courier = Courier(dispatcher=dispatcher, env=env, courier_id=981, on_time=on_time, off_time=off_time) notification = Notification(courier=courier, instruction=instruction, type=NotificationType.PREPOSITIONING) dispatcher.notification_rejected_event(notification=notification, courier=courier) env.run(until=initial_time + min_to_sec(30)) # Verify order and courier properties are modified and it is allocated correctly self.assertIsNone(courier.active_route)
def test_orders_dropped_off_event(self): """Test to verify the mechanics of orders being dropped off""" # Constants initial_time = hour_to_sec(14) on_time = time(14, 0, 0) off_time = time(16, 0, 0) # Services env = Environment(initial_time=initial_time) dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) # Creates an order and sends the picked up event order = Order(order_id=45, user=User(env=env)) dispatcher.assigned_orders[order.order_id] = order courier = Courier(on_time=on_time, off_time=off_time) dispatcher.orders_dropped_off_event(orders={order.order_id: order}, courier=courier) env.run(until=initial_time + hour_to_sec(1)) # Verify order properties are modified and it is allocated correctly self.assertEqual(order.state, 'dropped_off') self.assertEqual(order.drop_off_time, sec_to_time(initial_time)) self.assertIn(order.order_id, dispatcher.fulfilled_orders.keys()) self.assertEqual(dispatcher.assigned_orders, {}) self.assertIn(order.order_id, courier.fulfilled_orders)
def test_tk_process_visualization(flow_speed=1e6): """test visualized run""" if os.name != "nt" and os.environ.get("DISPLAY", "") == "": print("no display, animated run pointless (e.g. inside a container)") # (this check for DISPLAY does not work on win) return env = Environment() model = Model(env) width = 451 height = 212 gui = Tk() canvas = ScaledCanvasTk(gui, width, height) visualizer = ProcessVisualizer( canvas, flow_speed=flow_speed, background_image_path="main/visu/diagram.png", default_entity_icon_path="main/visu/simple_entity_icon.png", ) for block in model.model_components.values(): block.visualizer = visualizer env.run() gui.destroy() assert env.now > 0
def run(self): data_dir = self.__data_dir label, cluster, load_f, n_apps = self.__label, self.__cluster, self.__load_f, self.__n_apps output_size_scale_factor = self.__output_size_scale_factor scheduler, sched_config = self.__scheduler, self.__sched_config env = Environment() meter = Meter(env) cluster = cluster.clone(env, meter) scheduler = scheduler(env, cluster, meter=meter, **sched_config) load_gen = TraceBasedApplicationGenerator(env, load_f, scheduler, output_size_scale_factor, n_apps) cluster.start() scheduler.start() load_gen.start() self.logger.info('Testing %s' % label) env.run() avg_runtime = np.mean( [a.end_time - a.start_time for a in load_gen.apps]) meter.save('%s/%s' % (data_dir, label)) with open('%s/%s/general.json' % (data_dir, label), 'r+') as f: general = json.load(f) general.update(avg_runtime=avg_runtime) f.seek(0) json.dump(general, f) self.logger.info('Finish testing %s' % label)
class Simulation: """Manage a simulation.""" def __init__(self, network: Network, routing_protocol: str, deadline: float) -> None: self.env = Environment() self.medium = Medium(self.env) send_data_function = self.medium.send_data_to_medium simulation_nodes = convert_to_simulation_nodes(network.nodes, routing_protocol, deadline, send_data_function, self.env) simulation_links = convert_to_simulation_links(network.links, simulation_nodes) self.medium.setup_links(simulation_links) self.network = SimulationNetwork(simulation_nodes, simulation_links) self.deadline = deadline def run(self, time: float, seed_value: int = DEFAULT_SEED) -> None: """Runs the simulation for a given time in seconds.""" seed(seed_value) # Restart the seed self.env.run(until=time) def show_performance(self): """Calls a routine to show the performance of the simulation.""" NetworkPerformance(self.network, self.deadline)
def test_submit_wait_for_order(self, *args): """Test to verify how a user submits an order but doesn't cancel even without courier, deciding to wait""" # Constants random.seed(157) # Services env = Environment(initial_time=hour_to_sec(12)) dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) # Create a user and have it submit an order immediately user = User(cancellation_policy=self.cancellation_policy, dispatcher=dispatcher, env=env) user.submit_order_event( order_id=self.order_id, pick_up_at=self.pick_up_at, drop_off_at=self.drop_off_at, placement_time=self.placement_time, expected_drop_off_time=self.expected_drop_off_time, preparation_time=self.preparation_time, ready_time=self.ready_time) env.run(until=hour_to_sec(13)) # Verify order is created but not canceled, disregarding the lack of a courier self.assertTrue(user.order) self.assertIsNone(user.order.courier_id) self.assertIsNone(user.order.cancellation_time) self.assertEqual(dispatcher.unassigned_orders, {self.order_id: user.order}) self.assertEqual(user.condition, 'waiting')
def gravity_model_contact_events(agents: List[Agent], positions: np.array, env: simpy.Environment, rng: np.random.Generator): tree = KDTree(data=positions) close_pairs = list(tree.query_pairs(r=contact_distance_upper_bound)) inverse_distances = np.array( [np.linalg.norm(positions[idx1] - positions[idx2]) ** -contact_rate_gravity_exponent for idx1, idx2 in close_pairs]) inverse_distances /= inverse_distances.sum() while True: choices = rng.choice(a=close_pairs, p=inverse_distances, size=len(agents)).tolist() for choice in choices: yield env.timeout(delay=rng.exponential(scale=1 / len(agents) / contact_rate_per_individual)) contact_agents = [agents[idx] for idx in choice if not agents[idx].state.symptomatic() or rng.uniform() > p_symptomatic_individual_isolates] if len(contact_agents) < 2: # Symptomatic self-isolation means this is no longer a contact event and doesn't need # recording. Skip to the next event. continue infected = get_infected(contact_agents, rng=rng) for i in infected: env.process(generator=infection_events(env=env, infected=i, rng=rng))
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 = {}
def customer(env: simpy.Environment, customer_id: int, infected: bool, store: Store, path: List[int], traversal_time: float, thres: int = 50): """ Simpy process simulating a single customer :param env: Simpy environment on which the simulation runs :param customer_id: ID of customer :param infected: True if infected :param store: Store object :param path: Assigned customer shopping path :param traversal_time: Mean time before moving to the next node in path (also called waiting time) :param thres: Threshold length of queue outside. If queue exceeds threshold, customer does not enter the queue and leaves. """ arrive = env.now if store.num_customers_waiting_outside > thres: store.log( f'Customer {customer_id} does not queue up, since we have over {thres} customers waiting outside ' + f'({store.num_customers_waiting_outside})') return else: store.num_customers_waiting_outside += 1 with store.counter.request() as my_turn_to_enter: result = yield my_turn_to_enter | store.is_closed_event store.num_customers_waiting_outside -= 1 wait = env.now - arrive if my_turn_to_enter not in result: store.log( f'Customer {customer_id} leaves the queue after waiting {wait:.2f} min, as shop is closed' ) return if my_turn_to_enter in result: store.log( f'Customer {customer_id} enters the shop after waiting {wait :.2f} min with shopping path {path}.' ) start_node = path[0] store.add_customer(customer_id, start_node, infected, wait) for start, end in zip(path[:-1], path[1:]): store.customers_next_zone[customer_id] = end has_moved = False while not has_moved: # If it hasn't moved, wait a bit yield env.timeout(random.expovariate(1 / traversal_time)) has_moved = store.move_customer(customer_id, infected, start, end) yield env.timeout(random.expovariate( 1 / traversal_time)) # wait before leaving the store store.remove_customer(customer_id, path[-1], infected)
def car(env: simpy.Environment): while True: print(f'{env.now} 开始停车充电') charge_duration = 5 yield env.process(charge(env, charge_duration)) print(f"{env.now} 开始行驶") trip_duration = 2 yield env.timeout(trip_duration)
def car(env:simpy.Environment): while True: print(f"{env.now}开始停车") parking_duration = 5 yield env.timeout(parking_duration) print(f"{env.now}开始开车") trip_duration = 2 yield env.timeout(trip_duration)
def simulation( env: simpy.Environment, canteen: Canteen, customers: Tuple[Customer, ...]) -> Generator[simpy.Event, None, None]: """ This is the simulation. """ for customer in customers: if customer.arrival > env.now: yield env.timeout(customer.arrival - env.now) env.process(service(env, canteen, customer))
def laboratory(env: simpy.Environment, scaling: float) -> Lab: lab = Lab( queue=PriorityQueue(), capacity=INITIAL_CAPACITY, env=env, scaling=scaling, ) env.process(influenza_exams_demand(lab)) env.process(lab.run()) return lab
def test_if_source_is_creating_entities(): """test source""" env = Environment() core_source = Source(env, "source", inter_arrival_time=0) entity_receiver = EntityReceiver(env) core_source.successors.append(entity_receiver) env.run(until=1) assert len( entity_receiver.received_entities) == core_source.overall_count_in assert core_source.overall_count_in == core_source.max_entities
def car(env: simpy.Environment)->None: """ demo car """ while 1: print("start parking at %d" % env.now) parking_duration = 5 yield env.timeout(parking_duration) print("start driving at %d" % env.now) trip_duration = 2 yield env.timeout(trip_duration)
def test_read_put_put(store: ReadableFilterStore, env: simpy.Environment): def pem(): rd_event = store.read(lambda val: val == (1, )) yield store.put((2,)) assert not rd_event.triggered # assert (1,) not found yield store.put((1,)) assert rd_event.triggered # assert (1,) found env.process(pem()) env.run() assert store.items == [(2,), (1,)] # check only (1,) removed
def gas_station_control(env: simpy.Environment, fuel_pump: simpy.Container) -> Generator: """Periodically check the level of the *fuel_pump* and call the tank truck if the level falls below a threshold.""" while True: if fuel_pump.level / fuel_pump.capacity * 100 < THRESHOLD: # We need to call the tank truck now! print(f"Calling tank truck at {env.now:.1f}") # Wait for the tank truck to arrive and refuel the station yield env.process(tank_truck(env, fuel_pump)) yield env.timeout(10) # Check every 10 seconds
def test_get_put_put(store, env: simpy.Environment): def pem(): get_event = store.get(lambda val: val == (1, )) yield store.put((2,)) assert not get_event.triggered # assert (1,) not found yield store.put((1,)) assert get_event.triggered # assert (1,) found env.process(pem()) env.run() assert store.items == [(2,)] # assert (1,) removed and (2,) not removed
def car(env: simpy.Environment): while True: print(f'{env.now} 开始停车充电') charge_duration = 5 try: yield env.process(charge(env, charge_duration)) except simpy.Interrupt: print("被中断了。希望电池有电。。。") print(f"{env.now} 开始行驶") trip_duration = 2 yield env.timeout(trip_duration)
def __init__(self, env: Environment, client: AbstractClient, dataCol: DataCollector): self.env = env self.client = client self.dataCol = dataCol self.period = EngineController.PASSIVE_PERIOD self.desiredPower = EngineController.PASSIVE_POWER env.process(self.passiveProcess()) env.process(self.runEngineProcess()) self.shouldStart = BulkDecider(self, dataCol) self.shouldStop = BulkDecider(self, dataCol) self.lastStopTime = -EngineController.RESTART_DELAY self.mode = ""
def test_value_from_subprocess(env: simpy.Environment): def proc(): yield env.timeout(2) assert env.now == 2 ret_val = yield env.process(delayed_42(env)) assert env.now == 3 assert ret_val == 42 return ret_val * 2 p = env.process(proc()) run_val = env.run() assert run_val is None assert p.value == 84 assert env.now == 3
def __init__(self, network: Network, routing_protocol: str, deadline: float) -> None: self.env = Environment() self.medium = Medium(self.env) send_data_function = self.medium.send_data_to_medium simulation_nodes = convert_to_simulation_nodes(network.nodes, routing_protocol, deadline, send_data_function, self.env) simulation_links = convert_to_simulation_links(network.links, simulation_nodes) self.medium.setup_links(simulation_links) self.network = SimulationNetwork(simulation_nodes, simulation_links) self.deadline = deadline
def __init__(self, simulation_input: DesInputModel): self.sim_def = simulation_input.sim_def self.queue_input = simulation_input.queues self.process_input = simulation_input.processes self.resource_input = simulation_input.resources self.simpy_env = Environment() self.queue_dict: Dict[str, ContinuousQueue] = {} self.resource_dict: Dict[str, BasicResource] = {} self.process_dict: Dict[str, ProcessObject] = {} self.process_output: List[ProcessOutput] = [] self.queue_output: List[QueueStateOutput] = [] self.resource_output: List[ResouceOutput] = [] self.append_process_output = self.process_output.append self.append_queue_output = self.queue_output.append self.append_resource_output = self.resource_output.append
def test_simple_run(): """run model""" env = Environment() model = model_module.Model(env) model.source.max_entities = 1 model.source.inter_arrival_time = 0 model.tilemover.speed = 1 env.run() assert model.sink.overall_count_in == 1 assert env.now == 17.05 * SCALE # depends on scale: 17.05 * tilemap_scale print("\n\nsimulation done.\n\n")
def main(stop): record = Recorder() record.reset() enviro = Environment() logqueue = makeLogging() board = Blackboard() board.put('logqueue',logqueue) board.put('enviro',enviro) toavg = Store(enviro) AGV(toavg) SmartMixingCell("SMC1",toavg) enviro.run(until=stop) logqueue.put('HALT') retval = record.generateRecord() return retval
class Simulation(ResourceAccessService): def __init__(self, simulation_input, *args, **kwargs): """ :type simulation_input: study_model.simulation.simulation_input.SimulationInput """ super(Simulation, self).__init__(*args, **kwargs) self._step = 0 """ :type: int """ self._environment = Environment() self._students = simulation_input.students self._resources = simulation_input.resources self._curriculum = simulation_input.curriculum self._register_resources(self._resources) @property def state(self): """ :rtype: SimulationState """ return SimulationState(self._students, self._resources, self._curriculum) def _grant_initial_access_permissions(self): for student in self._students: for resource in self._resources: self.grant_access(student, resource) def run(self): student_stop_conditions = [] for resource in self._resources: resource.resource_access_service = self resource.env = self._environment for student in self._students: student.curriculum = self._curriculum student.env = self._environment self._environment.process(student.start()) student_stop_conditions.append(student.stop_participation_event) self._grant_initial_access_permissions() self._environment.run(self._environment.all_of(student_stop_conditions))
def __init__(self, simulation_input, *args, **kwargs): """ :type simulation_input: study_model.simulation.simulation_input.SimulationInput """ super(Simulation, self).__init__(*args, **kwargs) self._step = 0 """ :type: int """ self._environment = Environment() self._students = simulation_input.students self._resources = simulation_input.resources self._curriculum = simulation_input.curriculum self._register_resources(self._resources)
""" release all items """ # list(map(lambda x: x.release(), items)) for i,v in enumerate(items): print(i,v) print(len(list(requested_list))) v.release(list(requested_list)[0]) def test1(env, items): requested_list = request_all(items) import ipdb; ipdb.set_trace() yield env.timeout(11) print(env.now) release_all(items,requested_list) def test2(env, items): requested_list = request_all(items) yield env.timeout(11) print(env.now) release_all(items,requested_list) env = Environment() res_list = [Resource(env, capacity=1) for i in range(10)] env.process(test1(env, res_list)) env.process(test2(env, res_list)) env.run()
#___ONLINE LEARNING___ from simpy import Environment,simulate,Monitor from swfpy import io if arguments['--verbose']==True: import logging from simpy.util import start_delayed if arguments['--verbose']==True: global_logger = logging.getLogger('global') hdlr = logging.FileHandler('predictor.log') formatter = logging.Formatter('%(levelname)s %(message)s') hdlr.setFormatter(formatter) global_logger.addHandler(hdlr) #Getting a simulation environment env = Environment() #logging function if arguments['--verbose']==True: def global_log(msg): prefix='%.1f'%env.now global_logger.info(prefix+': '+msg) else: def global_log(msg): pass if tool=="sgd": #___SGD___ print("sgd") loss=arguments["<loss>"] if loss not in [ 'squared_loss', 'huber', 'epsilon_insensitive', 'squared_epsilon_insensitive','maeloss']:
def p(env, res, s): for i in range(10): yield env.timeout(1) yield res.event res.request('push', i) env.process(run(env, 'push end', res, i, s)) def p2(env, res, s): for i in range(10): res.request('land', i) env.process(run(env, 'land end', res, i, s)) def run(env, events, res, i, s): yield env.timeout(24) res.release() print(i, events, env.now, res.num) env = Environment() event = Event(env) s = Store(env) res = Res(env, event, capacity=10) env.process(p(env, res, s)) env.process(p2(env, res, s)) env.run()
elif config["scheduler"]["predictor"]["name"]=="predictor_sgdlinear": #if arguments["<loss>"] not in ["squared_loss"]: #raise ValueError("loss not supported. supported losses=%s"%(supported_losses.__str__())) #if arguments["<penalty>"] not in ["none"]: #raise ValueError("penalty not supported. supported penalties=%s"%(supported_penalties.__str__())) from predictors.predictor_sgdlinear import PredictorSgdlinear predictor=PredictorSgdlinear(config) elif config["scheduler"]["predictor"]["name"]=="predictor_knn": from predictors.predictor_knn import PredictorKNN predictor=PredictorKNN(config) else: raise ValueError("no valid predictor specified") iprint("Predictor created.") #Getting a simulation environment env = Environment() pred=[] loss=[] if hasattr(predictor,"model"): coeffs=[] #system variables running_jobs=[] def job_process(j): yield env.timeout(j.submit_time) l=predictor.predict(j,env.now,running_jobs) if not l==None: loss.append(l) pred.append(j.predicted_run_time)
from Hardware import * from Common import * from VirtualAlgorithms import * from LocalAlgorithms import * from Monitoring import * #retrieving arguments arguments = docopt(__doc__, version='1.0.0rc2') print(arguments) #verbose? if arguments['--verbose']==True: print(arguments) #Getting a simulation environment env = Environment() #logger: global_logger = logging.getLogger('global') hdlr = logging.FileHandler('csim_global.log') formatter = logging.Formatter('%(levelname)s %(message)s') hdlr.setFormatter(formatter) global_logger.addHandler(hdlr) #logging level if arguments['--verbose']==True: global_logger.setLevel(logging.INFO) else: global_logger.setLevel(logging.ERROR) #logging function
yield env.timeout(2*60) nodes.release(node) def paircrafparking(env,airplane,roads,nodes): yield roads.put(airplane) def road_gen(env,road): yield env.timeout(np.random.randint(20,100)) r = road.get() yield r if __name__ == '__main__': pushing_list = [i for i in range(20)] env = Environment() # rule 1 road = Store(env,capacity=3) # rule 2 wait_queue = Resource(env,capacity=20) # rule 3 nodes = Resource(env,capacity=4) # env.process(test(env,road)) for airplane in pushing_list: env.process(aircraftpushing(env,airplane,road,nodes,wait_queue)) for i in range(100): env.process(road_gen(env,road)) env.run()