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_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 test_notification_accepted_event(self): """Test to verify the mechanics of a notification being accepted 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 an instruction with an order, a courier and sends the accepted event order = Order(order_id=45) instruction = Route( stops=[ Stop(orders={order.order_id: order}, position=0), Stop(orders={order.order_id: order}, position=1) ], orders={order.order_id: order} ) dispatcher.unassigned_orders[order.order_id] = order courier = Courier(dispatcher=dispatcher, env=env, courier_id=89, on_time=on_time, off_time=off_time) courier.condition = 'idle' notification = Notification( courier=courier, instruction=instruction ) dispatcher.notification_accepted_event(notification=notification, courier=courier) env.run(until=initial_time + min_to_sec(10)) # Verify order and courier properties are modified and it is allocated correctly self.assertEqual(order.state, 'in_progress') self.assertEqual(order.acceptance_time, sec_to_time(initial_time)) self.assertEqual(order.courier_id, courier.courier_id) self.assertIn(order.order_id, dispatcher.assigned_orders.keys()) self.assertIsNotNone(courier.active_route) self.assertEqual(courier.active_route, instruction) self.assertEqual(dispatcher.unassigned_orders, {})
def execute(self, orders: List[Order], couriers: List[Courier], env_time: int) -> Tuple[List[Notification], MatchingMetric]: """Implementation of the policy""" matching_start_time = time.time() idle_couriers = [ courier for courier in couriers if courier.condition == 'idle' and courier.active_route is None ] prospects = self._get_prospects(orders, idle_couriers) estimations = self._get_estimations(orders, idle_couriers, prospects) notifications, notified_couriers = [], np.array([]) if bool(prospects.tolist()) and bool( estimations.tolist()) and bool(orders) and bool(idle_couriers): for order_ix, order in enumerate(orders): mask = np.where( np.logical_and( prospects[:, 0] == order_ix, np.logical_not( np.isin(prospects[:, 1], notified_couriers)))) if bool(mask[0].tolist()): order_prospects = prospects[mask] order_estimations = estimations[mask] min_time = order_estimations['time'].min() selection_mask = np.where( order_estimations['time'] == min_time) selected_prospect = order_prospects[selection_mask][0] notifications.append( Notification( courier=couriers[selected_prospect[1]], type=NotificationType.PICK_UP_DROP_OFF, instruction=Route( orders={order.order_id: order}, stops=[ Stop(location=order.pick_up_at, orders={order.order_id: order}, position=0, type=StopType.PICK_UP, visited=False), Stop(location=order.drop_off_at, orders={order.order_id: order}, position=1, type=StopType.DROP_OFF, visited=False) ]))) notified_couriers = np.append(notified_couriers, selected_prospect[1]) matching_time = time.time() - matching_start_time matching_metric = MatchingMetric(constraints=0, couriers=len(couriers), matches=len(notifications), matching_time=matching_time, orders=len(orders), routes=len(orders), routing_time=0., variables=0) return notifications, matching_metric
def notification_accepted_event(self, notification: Notification, courier: Courier): """Event detailing how the dispatcher handles the acceptance of a notification by a courier""" self._log( f'Dispatcher will handle acceptance of a {notification.type.label} notification ' f'from courier {courier.courier_id} (condition = {courier.condition})' ) if notification.type == NotificationType.PREPOSITIONING: courier.active_route = notification.instruction elif notification.type == NotificationType.PICK_UP_DROP_OFF: order_ids = (list(notification.instruction.orders.keys()) if isinstance(notification.instruction, Route) else [ order_id for stop in notification.instruction for order_id in stop.orders.keys() ]) processed_order_ids = [ order_id for order_id in order_ids if (order_id in self.canceled_orders.keys() or order_id in self.assigned_orders.keys() or order_id in self.fulfilled_orders.keys()) ] if bool(processed_order_ids): self._log( f'Dispatcher will update the notification to courier {courier.courier_id} ' f'based on these orders being already processed: {processed_order_ids}' ) notification.update(processed_order_ids) if ((isinstance(notification.instruction, Route) and bool(notification.instruction.orders) and bool(notification.instruction.stops)) or (isinstance(notification.instruction, list) and bool(notification.instruction) and bool(notification.instruction[0].orders))): order_ids = (list(notification.instruction.orders.keys()) if isinstance(notification.instruction, Route) else [ order_id for stop in notification.instruction for order_id in stop.orders.keys() ]) self._log( f'Dispatcher will handle acceptance of orders {order_ids} ' f'from courier {courier.courier_id} (condition = {courier.condition}). ' f'Instruction is a {"Route" if isinstance(notification.instruction, Route) else "List[Stop]"}' ) instruction_orders = ( notification.instruction.orders.items() if isinstance( notification.instruction, Route) else [ (order_id, order) for stop in notification.instruction for order_id, order in stop.orders.items() ]) for order_id, order in instruction_orders: del self.unassigned_orders[order_id] order.acceptance_time = sec_to_time(self.env.now) order.state = 'in_progress' order.courier_id = courier.courier_id self.assigned_orders[order_id] = order if courier.condition == 'idle' and isinstance( notification.instruction, Route): courier.active_route = notification.instruction elif courier.condition == 'picking_up' and isinstance( notification.instruction, list): for stop in notification.instruction: for order_id, order in stop.orders.items(): courier.active_route.orders[order_id] = order courier.active_stop.orders[order_id] = order courier.active_route.stops.append( Stop(location=stop.location, position=len(courier.active_route.stops), orders=stop.orders, type=stop.type)) courier.accepted_notifications.append(notification) else: self._log( f'Dispatcher will nullify notification to courier {courier.courier_id}. All orders canceled.' )
def _process_solution(self, solution: np.ndarray, matching_problem: MatchingProblem, env_time: int) -> List[Notification]: """Method to parse the optimizer solution into the notifications""" matching_solution = solution[0:len(matching_problem.prospects)] matched_prospects_ix = np.where(matching_solution >= SOLUTION_VALUE) matched_prospects = matching_problem.prospects[matched_prospects_ix] if not self._notification_filtering: notifications = [None] * len(matched_prospects) for ix, (courier_ix, route_ix) in enumerate(matched_prospects): courier, route = matching_problem.couriers[ courier_ix], matching_problem.routes[route_ix] instruction = route.stops[ 1:] if courier.condition == 'picking_up' else route notifications[ix] = Notification( courier=courier, instruction=instruction, type=NotificationType.PICK_UP_DROP_OFF) else: notifications = [] for ix, (courier_ix, route_ix) in enumerate(matched_prospects): courier, route = matching_problem.couriers[ courier_ix], matching_problem.routes[route_ix] instruction = route.stops[ 1:] if courier.condition == 'picking_up' else route notification = Notification( courier=courier, instruction=instruction, type=NotificationType.PICK_UP_DROP_OFF) _, time_to_first_stop = OSRMService.estimate_travelling_properties( origin=courier.location, destination=route.stops[0].location, vehicle=courier.vehicle) if isinstance(instruction, list) and courier.condition == 'picking_up': notifications.append(notification) elif courier.condition == 'idle': if route.time_since_ready( env_time ) > settings.DISPATCHER_PROSPECTS_MAX_READY_TIME: notifications.append(notification) elif (time_to_first_stop <= settings.DISPATCHER_PROSPECTS_MAX_STOP_OFFSET and time_to_sec( min(order.ready_time for order in route.orders.values())) <= env_time + settings.DISPATCHER_PROSPECTS_MAX_STOP_OFFSET): notifications.append(notification) elif time_to_first_stop > settings.DISPATCHER_PROSPECTS_MAX_STOP_OFFSET: notifications.append( Notification( courier=courier, instruction=Route(stops=[ Stop(location=route.stops[0].location, type=StopType.PREPOSITION) ]), type=NotificationType.PREPOSITIONING)) return notifications
def _get_notification_list(self, raw_data): """Return list of Yaks from raw server response""" try: return [Notification(raw, self) for raw in raw_data.json()["data"]] except (KeyError, ValueError): raise ParsingResponseError("Getting notifs failed", raw_data)
def test_notify_event_reject_picking_up(self, osrm): """Test to evaluate how a courier handles a notification while picking up and rejects it""" # Constants random.seed(4747474) on_time = time(12, 0, 0) off_time = time(15, 0, 0) # Services env = Environment(initial_time=hour_to_sec(12) + min_to_sec(12)) dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) # Creates a courier with low acceptance rate, an active route and in state of picking up. # Sends a new instruction, composed of a single new order active_order = Order( order_id=self.order_id, drop_off_at=self.drop_off_at, pick_up_at=self.pick_up_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, courier_id=self.courier_id, user=User(env=env)) dispatcher.assigned_orders[active_order.order_id] = active_order new_order = Order(order_id=17, drop_off_at=Location(lat=4.694627, lng=-74.038886), pick_up_at=self.pick_up_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, user=User(env=env)) dispatcher.unassigned_orders[new_order.order_id] = new_order 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=active_order.pick_up_at, acceptance_rate=0.01, active_route=Route(orders={self.order_id: active_order}, stops=[ Stop(location=self.pick_up_at, position=0, orders={self.order_id: active_order}, type=StopType.PICK_UP, visited=False), Stop(location=self.drop_off_at, position=1, orders={self.order_id: active_order}, type=StopType.DROP_OFF, visited=False) ]), on_time=on_time, off_time=off_time) instruction = Stop(location=new_order.drop_off_at, position=1, orders={new_order.order_id: new_order}, type=StopType.DROP_OFF, visited=False) notification = Notification(courier=courier, instruction=instruction) courier.state.interrupt() courier.active_stop = courier.active_route.stops[0] courier.state = env.process( courier._picking_up_state( orders={active_order.order_id: active_order})) env.process(courier.notification_event(notification)) env.run(until=hour_to_sec(14)) # Asserts: # - the courier didn't fulfill the new order, # - fulfilled the active order and # - is at a different start location. self.assertIsNone(new_order.pick_up_time) self.assertIsNone(new_order.drop_off_time) self.assertIsNone(new_order.courier_id) self.assertIn(courier.courier_id, new_order.rejected_by) self.assertIn(new_order.order_id, courier.rejected_orders) self.assertEqual(new_order.state, 'unassigned') self.assertIsNotNone(active_order.pick_up_time) self.assertIsNotNone(active_order.drop_off_time) self.assertEqual(active_order.courier_id, courier.courier_id) self.assertTrue(active_order.pick_up_time < active_order.drop_off_time) self.assertEqual(active_order.state, 'dropped_off') self.assertIsNone(courier.active_route) self.assertIsNone(courier.active_stop) self.assertNotEqual(courier.location, self.start_location) self.assertEqual(dispatcher.fulfilled_orders, {active_order.order_id: active_order}) self.assertEqual(dispatcher.unassigned_orders, {new_order.order_id: new_order}) self.assertEqual(courier.condition, 'idle') self.assertIn(courier.courier_id, dispatcher.idle_couriers.keys())
def test_notify_event_reject_idle(self, osrm): """Test to evaluate how a courier handles a notification while being idle and rejects it""" # Constants random.seed(122) on_time = time(12, 0, 0) off_time = time(15, 0, 0) # Services env = Environment(initial_time=hour_to_sec(12)) dispatcher = Dispatcher(env=env, matching_policy=DummyMatchingPolicy()) # Creates a courier with low acceptance rate and immediately send a new instruction, composed of a single order 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(order_id=self.order_id, drop_off_at=self.drop_off_at, pick_up_at=self.pick_up_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) dispatcher.unassigned_orders[order.order_id] = order instruction = Route(orders={self.order_id: order}, stops=[ Stop(location=self.pick_up_at, position=0, orders={self.order_id: order}, type=StopType.PICK_UP, visited=False), Stop(location=self.drop_off_at, position=1, orders={self.order_id: order}, type=StopType.DROP_OFF, visited=False) ]) notification = Notification(courier=courier, instruction=instruction) env.process(courier.notification_event(notification)) env.run(until=hour_to_sec(14)) # Asserts that the courier didn't fulfill the route self.assertIsNone(order.pick_up_time) self.assertIsNone(order.drop_off_time) self.assertIsNone(order.courier_id) self.assertIsNone(courier.active_route) self.assertIsNone(courier.active_stop) self.assertIn(courier.courier_id, order.rejected_by) self.assertIn(order.order_id, courier.rejected_orders) self.assertEqual(dispatcher.unassigned_orders, {order.order_id: order}) self.assertEqual(order.state, 'unassigned') self.assertEqual(courier.location, self.start_location) self.assertEqual(courier.condition, 'idle') self.assertIn(courier.courier_id, dispatcher.idle_couriers.keys())