def test_pick_up_waiting_time(self, osrm): """Test to verify the mechanics of the waiting time are correctly designed""" # Constants random.seed(290) on_time = time(6, 0, 0) off_time = time(8, 0, 0) # Services env = Environment(initial_time=hour_to_sec(6)) dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) # Creates a courier and sets it to pick up stuff 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, acceptance_rate=0.01, on_time=on_time, off_time=off_time) order = Order(ready_time=time(6, 15, 0), order_id=23) stop = Stop(orders={order.order_id: order}, type=StopType.PICK_UP) env.process(courier._execute_stop(stop)) dispatcher.state.interrupt() # Run until there are no more events and assert the courier experienced waiting time. env.run(until=hour_to_sec(7)) self.assertTrue(order.pick_up_time >= time( 6, int(order.ready_time.minute + order.pick_up_service_time / 60))) # For another test, if the order's ready time has expired, the courier doesn't experience waiting time env = Environment(initial_time=hour_to_sec(6)) dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) 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, acceptance_rate=0.01, on_time=on_time, off_time=off_time) order = Order(ready_time=time(4, 0, 0), order_id=23) stop = Stop(orders={order.order_id: order}, type=StopType.PICK_UP) env.process(courier._execute_stop(stop)) dispatcher.state.interrupt() env.run(until=hour_to_sec(7)) self.assertTrue( time(order.pick_up_time.hour, order.pick_up_time.minute) <= time( 6, int(order.pick_up_service_time / 60)))
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 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)
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( max_entities=10, inter_arrival_time=0, parallel_proc_time=10, sequential_proc_time=10, expected_end=50, ) -> float: model = model_module.Model(Environment()) model.source.max_entities = max_entities model.source.inter_arrival_time = inter_arrival_time model.parallel_proc.process_time = parallel_proc_time model.sequential_proc.process_time = sequential_proc_time t0 = time.time() model.env.run() t = time.time() - t0 assert model.sink.overall_count_in == model.source.overall_count_in assert model.parallel_proc.overall_count_in == model.source.max_entities / 2 assert model.sequential_proc.overall_count_in == model.source.max_entities / 2 assert model.env.now == expected_end return t
def test_visualized_run(): if os.name != "nt" and os.environ.get("DISPLAY", "") == "": print("no display, animated run pointless (e.g. inside a container)") return env = Environment() model = Model(env) width = 336 height = 331 gui = Tk() canvas = ScaledCanvasTk(gui, width, height) visualizer = ProcessVisualizer( canvas, flow_speed=FLOW_SPEED, background_image_path="examples/wait_for_interrupt/diagram.png", default_entity_icon_path= "examples/basics/visualization/simple_entity_icon.png", ) for block in model.model_components.values(): block.visualizer = visualizer model.env.run() assert model.sink.overall_count_in == model.source.max_entities assert model.sink_2.overall_count_in == model.source_2.max_entities gui.destroy()
def test_submit_courier_assigned(self): """Test to verify how a user submits and order and doesn't cancel since a courier is assigned""" # Constants random.seed(666) # Services env = Environment(initial_time=hour_to_sec(12)) dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) # Create a user, have it submit an order immediately and after some minutes, assign a courier 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.process(TestsDispatcher.assign_courier(user, env, dispatcher)) env.run(until=hour_to_sec(13)) # Verify order is created but not canceled because a courier was assigned self.assertTrue(user.order) self.assertIsNotNone(user.order.courier_id) self.assertIsNone(user.order.cancellation_time) self.assertEqual(dispatcher.assigned_orders, {self.order_id: user.order}) self.assertEqual(dispatcher.unassigned_orders, {}) self.assertEqual(user.condition, 'waiting')
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 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_calculate_earnings(self): """Test to verify the mechanics of calculating the shift's earnings""" # Constants random.seed(523) on_time = time(0, 0, 0) off_time = time(2, 0, 0) # Services env = Environment() # Creates a two hour - shift courier courier = Courier(env=env, on_time=on_time, off_time=off_time) # Verifies for two scenarios how the earnings are calculated. # In the first test, raw earnings from orders are chosen. # In the second test, the hourly earnings rate is chosen. # Test 1. Creates courier earnings to select the raw earnings from orders. # Asserts that these earnings are selected over the hourly earnings rate courier.fulfilled_orders = [Order()] * 7 courier.earnings = courier._calculate_earnings() self.assertEqual( courier.earnings, len(courier.fulfilled_orders) * settings.COURIER_EARNINGS_PER_ORDER) # Test 2. Creates courier earnings to select the hourly earnings rate. # Asserts that these earnings are selected over the order earnings courier.fulfilled_orders = [Order()] * 2 courier.earnings = courier._calculate_earnings() self.assertEqual( courier.earnings, sec_to_hour(time_diff(courier.off_time, courier.on_time)) * settings.COURIER_EARNINGS_PER_HOUR)
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 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_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_courier_available_event(self): """Test to verify the mechanics of how the dispatcher sets a courier to available""" # Constants initial_time = hour_to_sec(14) on_time = time(14, 0, 0) off_time = time(15, 0, 0) service_time = min_to_sec(6) # Services env = Environment(initial_time=initial_time) dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) # Creates a courier and sets it to the picking state courier = Courier(dispatcher=dispatcher, env=env, courier_id=32, on_time=on_time, off_time=off_time) dispatcher.idle_couriers = {courier.courier_id: courier} env.process(courier._picking_up_state( orders={ 21: Order(drop_off_service_time=service_time, ready_time=time(14, 20, 0)) } )) env.run(until=initial_time + min_to_sec(10)) # Verify courier properties are modified and it is allocated correctly self.assertEqual(courier.condition, 'picking_up') self.assertIn(courier.courier_id, dispatcher.picking_up_couriers.keys()) self.assertEqual(dispatcher.idle_couriers, {})
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())
class Actor: """A class used to handle the standard structure of an actor's state and events""" configure_logs() env: Optional[Environment] = Environment() state: Optional[Process] = None condition: str = '' def __post_init__(self): """Immediately after the actor is created, it starts idling""" self._log('Actor logged on') self.state = self.env.process(self._idle_state()) def _idle_state(self): """State that simulates the actor being idle and waiting for events""" yield def _log(self, msg: str): """Method to log detailed information of the actor's actions""" log(env=self.env, actor_name=self.__class__.__name__, condition=self.condition, msg=msg)
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 = 800 height = 600 gui = Tk() canvas = ScaledCanvasTk(gui, width, height) visualizer = ProcessVisualizer( canvas, flow_speed=FLOW_SPEED, background_image_path="examples/basics/visualization/bpmn_example.png", default_entity_icon_path= "examples/basics/visualization/simple_entity_icon.png", ) for block in model.model_components.values(): block.visualizer = visualizer model.env.run(until=float("inf")) assert model.sink.overall_count_in == model.source.max_entities == MAX_ENTITIES gui.destroy()
def test_courier_idle_event(self, *args): """Test to verifiy the mechanics of how a courier is set to idle by the dispatcher""" # Constants initial_time = hour_to_sec(14) courier_id = 85 time_delta = min_to_sec(10) random.seed(26) on_time = time(14, 0, 0) off_time = time(15, 0, 0) # Verifies 3 test cases: when the courier is busy, available or idle. # For each test case, assert the courier starts in a set and ends up in the idle set # Test 1: courier is busy env = Environment(initial_time=initial_time) dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) courier = Courier(dispatcher=dispatcher, env=env, courier_id=courier_id, on_time=on_time, off_time=off_time) dispatcher.moving_couriers = {courier.courier_id: courier} dispatcher.courier_idle_event(courier) env.run(until=initial_time + time_delta) self.assertIn(courier.courier_id, dispatcher.idle_couriers.keys()) self.assertEqual(dispatcher.moving_couriers, {}) self.assertEqual(dispatcher.picking_up_couriers, {}) # Test 2: courier is available env = Environment(initial_time=initial_time) dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) courier = Courier(dispatcher=dispatcher, env=env, courier_id=courier_id, on_time=on_time, off_time=off_time) dispatcher.picking_up_couriers = {courier.courier_id: courier} dispatcher.courier_idle_event(courier) env.run(until=initial_time + time_delta) self.assertIn(courier.courier_id, dispatcher.idle_couriers.keys()) self.assertEqual(dispatcher.moving_couriers, {}) self.assertEqual(dispatcher.picking_up_couriers, {}) # Test 3: courier is idle env = Environment(initial_time=initial_time) dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) courier = Courier(dispatcher=dispatcher, env=env, courier_id=courier_id, on_time=on_time, off_time=off_time) dispatcher.idle_couriers = {courier.courier_id: courier} dispatcher.courier_idle_event(courier) env.run(until=initial_time + time_delta) self.assertIn(courier.courier_id, dispatcher.idle_couriers.keys()) self.assertEqual(dispatcher.moving_couriers, {}) self.assertEqual(dispatcher.picking_up_couriers, {})
def test_model_execution_geo_visualizer(): env = Environment() model = Model(env) env.run() time_without_visualizer = env.now env = Environment() model = Model(env) canvas_dict = {} geo_canvas = GeoWebCanvas(canvas_dict) geo_visualizer = GeoVisualizer(geo_canvas) model.drive_tour.set_geo_visualizer(geo_visualizer) env.run() time_with_visualizer = env.now assert model.sink.overall_count_in == model.source.max_entities assert time_with_visualizer == time_without_visualizer
def test_courier_busy_event(self, *args): """Test to verify the mechanics of how the dispatcher sets a courier to busy""" # Constants initial_time = hour_to_sec(14) courier_id = 14 time_delta = min_to_sec(10) on_time = time(14, 0, 0) off_time = time(15, 0, 0) service_time = min_to_sec(7) # Verifies 2 test cases for how the courier transitions to being busy # For each test case, assert the courier starts in a set and ends up in the busy set # Test 1: courier starts dropping off state env = Environment(initial_time=initial_time) dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) courier = Courier(dispatcher=dispatcher, env=env, courier_id=courier_id, on_time=on_time, off_time=off_time) env.process(courier._dropping_off_state( orders={ 21: Order(drop_off_service_time=service_time, ready_time=time(12, 20, 0)) } )) env.run(until=initial_time + time_delta) self.assertEqual(courier.condition, 'dropping_off') self.assertEqual(dispatcher.dropping_off_couriers, {courier.courier_id: courier}) self.assertEqual(dispatcher.idle_couriers, {}) # Test 2: courier start moving state env = Environment(initial_time=initial_time) dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) courier = Courier( dispatcher=dispatcher, env=env, courier_id=courier_id, location=Location(lat=4.690296, lng=-74.043929), on_time=on_time, off_time=off_time ) env.process(courier._moving_state(destination=Location(lat=4.689697, lng=-74.055495))) env.run(until=initial_time + time_delta) self.assertEqual(courier.condition, 'moving') self.assertEqual(dispatcher.moving_couriers, {courier.courier_id: courier}) self.assertEqual(dispatcher.idle_couriers, {})
def test_buffer_event(self): """Test to verify how the mechanics of the dispatcher buffering orders work""" # Constants initial_time = hour_to_sec(16) placement_time = time(16, 0, 0) time_delta = min_to_sec(10) # Verifies two test cases for how the dispatcher buffers orders # For each test, assert the correct number of orders are buffered # Test 1: schedules the submission of three orders and assert that only two are buffered env = Environment(initial_time=initial_time) dispatcher = Dispatcher( env=env, buffering_policy=RollingBufferingPolicy(), matching_policy=DummyMatchingPolicy() ) order_1 = Order(order_id=1, placement_time=placement_time) order_2 = Order(order_id=2, placement_time=placement_time) order_3 = Order(order_id=3, placement_time=placement_time) dispatcher.order_submitted_event(order_1, preparation_time=time(16, 0, 27), ready_time=time(16, 10, 0)) dispatcher.order_submitted_event(order_2, preparation_time=time(16, 0, 43), ready_time=time(16, 10, 0)) dispatcher.order_submitted_event(order_3, preparation_time=time(18, 0, 0), ready_time=time(18, 10, 0)) env.run(until=initial_time + time_delta) self.assertEqual(len(dispatcher.unassigned_orders), 2) # Test 2: schedules the submission of three orders and assert that all three orders are buffered env = Environment(initial_time=initial_time) dispatcher = Dispatcher( env=env, buffering_policy=RollingBufferingPolicy(), matching_policy=DummyMatchingPolicy() ) order_1 = Order(order_id=1, placement_time=placement_time) order_2 = Order(order_id=2, placement_time=placement_time) order_3 = Order(order_id=3, placement_time=placement_time) dispatcher.order_submitted_event(order_1, preparation_time=time(16, 0, 27), ready_time=time(16, 10, 0)) dispatcher.order_submitted_event(order_2, preparation_time=time(16, 0, 43), ready_time=time(16, 10, 0)) dispatcher.order_submitted_event(order_3, preparation_time=time(16, 4, 1), ready_time=time(16, 14, 0)) env.run(until=initial_time + time_delta) self.assertEqual(len(dispatcher.unassigned_orders), 3)
class Config(object): env = Environment() # 随机种子配置 RANDOM_SEED = 42 # package生成器配置信息 NUM_PACKAGES = 10 # 生成package数量/个 INTERVAL_TIME = 10 # 生成package间隔/s # 包裹传送带类型:pipline 类/simpy.Store/simpy.PriorityStore TYPE_PIP_LINE = Store(env) #配置传送带的类型
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 main_run(): """""" env = Environment() priority_store = PriorityStore(env=env) res_port = Resource(env=env, capacity=2) for i in range(NUM_PACKAGE): env.process( put_package_queue(env=env, id=i, res=res_port, queue=priority_store)) #env.process(get_package(env, priority_store)) env.run()
def test_log_off(self): """Test to evaluate the scheduling of the courier logging off works correctly""" # Constants random.seed(888) on_time = time(8, 0, 0) off_time = time(14, 0, 0) initial_time = hour_to_sec(8) # Verifies for two test cases the scheduling of the courier logging off works correctly. # In one case, the courier log off event doesn't yet happen. In the other test, it does # Test 1: the courier achieves the log off after a given time env = Environment(initial_time=initial_time) dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) courier = Courier(env=env, dispatcher=dispatcher, courier_id=84, on_time=on_time, off_time=off_time) env.run(until=initial_time + hour_to_sec(10)) self.assertEqual(dispatcher.logged_off_couriers, {courier.courier_id: courier}) self.assertEqual(dispatcher.idle_couriers, {}) self.assertEqual(courier.condition, 'logged_off') # Test 2: the courier doesn't achieve the log off because the simulation ends before env = Environment(initial_time=initial_time) dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) courier = Courier(env=env, dispatcher=dispatcher, courier_id=84, on_time=on_time, off_time=off_time) env.run(until=initial_time + hour_to_sec(2)) self.assertEqual(dispatcher.idle_couriers, {courier.courier_id: courier}) self.assertEqual(dispatcher.logged_off_couriers, {}) self.assertEqual(courier.condition, 'idle')
def simulate(num_nodes, area, simtime, logfile, channel_model, net_layers, depl_eng, node_config): """ Creates a simulation Parameters: area -- Area object (e.g DiscArea) logfile -- Path to file where logs should be saved channel_model -- Channel model object net_layers -- list of net layer classes depl_eng -- Node deployment class node_config -- Node configurator """ # 1. Set up simulation engine, logger sim_eng = Environment() logger = PacketLogger(logfile) # 2. Deploy the nodes in the area gw, nodes = depl_eng.deploy_nodes(num_nodes, PeriodicLoraNode, channel_model, area) # 3. Common channel channel = Channel(gw + nodes, channel_model, logger) # 4. Configure nodes node_config.configure(nodes, gw, area, channel_model) # 5. Set up network stack for all nodes for g in gw: g.sim = sim_eng g.config_net_stack(net_layers, logger, channel) for n in nodes: # Register node with simulator n.period = 60 # TODO period is static for now n.sim = sim_eng # Register node application with simulation engine sim_eng.process(n.app_process()) n.config_net_stack(net_layers, logger, channel) logger.add_node(n) # All set now for starting the simulation sim_eng.run(until=simtime) # Save logger results logger.persist() der = sum([n['tx_success'] / n['sent'] for n in logger.pkt_log.values()]) / len(nodes) print('Avg DER=%0.2f' % der) return der
def test_simple_run(): """run model""" env = Environment() model = model_module.Model(env) model.source.max_entities = 10**4 # increase for higher runtime model.source.inter_arrival_time = 0 # increase for lower runtime model.env.run() assert model.sink.overall_count_in == model.source.overall_count_in assert model.sink.overall_count_in == model.source.max_entities print("\n\nsimulation done.\n\n")
def test_notify_prepositioning_event_accept_idle(self, osrm): """Test to evaluate how a courier handles a prepositioning notification while being idle and accepts it""" # Constants random.seed(348) initial_time = hour_to_sec(17) time_delta = min_to_sec(10) on_time = time(17, 0, 0) off_time = time(17, 30, 0) # Services env = Environment(initial_time=initial_time) dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) # Creates a courier with high acceptance rate and immediately send a prepositioning notification 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, acceptance_rate=0.99, on_time=on_time, off_time=off_time) instruction = Route(orders=None, stops=[ Stop(location=self.pick_up_at, position=0, orders=None, type=StopType.PREPOSITION, visited=False) ]) notification = Notification(courier=courier, instruction=instruction, type=NotificationType.PREPOSITIONING) env.process(courier.notification_event(notification)) env.run(until=initial_time + time_delta) # Asserts that the courier fulfilled the route and is at a different start location self.assertIsNone(courier.active_route) self.assertIsNone(courier.active_stop) self.assertEqual(dispatcher.fulfilled_orders, {}) self.assertNotEqual(courier.location, self.start_location) self.assertEqual(courier.condition, 'idle') self.assertIn(courier.courier_id, dispatcher.idle_couriers.keys())
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 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