diff options
Diffstat (limited to 'src/scheduler.py')
| -rw-r--r-- | src/scheduler.py | 285 |
1 files changed, 285 insertions, 0 deletions
diff --git a/src/scheduler.py b/src/scheduler.py new file mode 100644 index 0000000..9a33aec --- /dev/null +++ b/src/scheduler.py @@ -0,0 +1,285 @@ +"""Scheduling of the simulation. + Does not run the pathfinding algorithm +""" + +from drone import Drone +from typing import List, Tuple +from graph import Graph +from models import Zone, ZoneType, Connection +from pathfinder import Pathfinder, PathResult + + +class Scheduler: + """Schedule multiple drones on a common path. + + If a zone of the path is RESTRICTED and congested, + i.e. at max capacity, a new path is computed for + that drone + """ + + def __init__( + self, + graph: Graph, + path: List[str], + number_of_drones: int, + ) -> None: + """Initialize the scheduler.""" + self.graph = graph + self.drones = [ + Drone(id_=index, path=path.copy()) + for index in range(1, number_of_drones + 1) + ] + + @property + def all_delivered(self) -> bool: + """Check if all drones have been delivered""" + return all(drone.delivered for drone in self.drones) + + def run(self) -> None: + """Run the simulation until all drones have reached the goal.""" + + # self.all_delivered using the property above + while not self.all_delivered: + movements = self._run_turn() + + if movements: + print(f"{' '.join(movements)}") + + def _list_moves(self) -> List[Tuple[Drone, str]]: + """This loop creates an object 'moves', a list + of Drone and the destination of their next + move. + """ + + moves: List[Tuple[Drone, str]] = [] + + for drone in self.drones: + if drone.delivered: + continue + + if drone.next_zone is None: + raise KeyError("No next zone") + dest_name: str = drone.next_zone + + if dest_name is not None: + moves.append((drone, dest_name)) + + return moves + + def _compute_new_path( + self, + src: Zone, + dest: Zone, + ) -> PathResult | None: + """ Compute new path when path is congested""" + + # get the end of the current path + end: Zone = self.graph.get_end() + + pathfinder: Pathfinder = Pathfinder(self.graph) + if pathfinder is None: + return None + path_result: PathResult | None = pathfinder.find_path(src.name, + end.name + ) + return path_result + + def _run_turn(self) -> List[str]: + """Calculate and apply valid movements for one turn. + + for each drone, the algorithm checks if the + drone can travel to its dest, and if so does so. + + Else, the algorithm computes a new path. + + If there no path is found; the algo moves on to + the next drone in the list. + """ + + moves: List[Tuple[Drone, str]] = self._list_moves() + + connections_to_clear: List[Connection] = [] + accepted: List[str] = [] + + for drone, dest_name in moves: + + # get src and dest + dest: Zone = self.graph.get_zone(dest_name) + src_name: str = drone.current_zone + src: Zone = self.graph.get_zone(src_name) + + if drone.in_transit is True: + connection = self.graph.get_connection(src, dest) + drone.leave_transit(src, + dest, + self.graph + ) + accepted.append(f"D{drone.id_}-" + f"{self._color_zone(dest_name)}-" + f"{dest.occupancy}/{dest.max_drones}") + connections_to_clear.append(self.graph.get_connection(src, + dest + ) + ) + continue + + # drone is on its way to restricted zone + if dest.zone_type == ZoneType.RESTRICTED: + connection = self.graph.get_connection(src, dest) + if connection.link_capacity > connection.link_occupancy \ + and dest.reservation < dest.max_drones: + dest.reservation += 1 + connection.link_occupancy += 1 + drone.in_transit = True + else: + # if zone is not restricted + while not self._can_enter(dest) \ + or not self._can_transit(src, dest): + + # if the zone is congested + if not self._can_enter(dest) and not dest.name == 'goal': + dest.congested = True + + # if the connection is congested + if not self._can_transit(src, dest): + self._connection_congested(src, dest, self.graph) + + path_result: PathResult | None = ( + self._compute_new_path(src, dest) + ) + if path_result is None: + break + + if self._new_dest_reachable(path_result): + drone.update_path(path_result) + dest = drone.update_dest(self.graph) + else: + break + + # when path_result is None + # for loop moves on to the next drone + connection = self.graph.get_connection(src, dest) + if dest.congested is True or connection.congested is True: + continue + + # regular move + drone.move() + self._increment_connection_occupancy(src, dest, self.graph) + if src.name != 'start': + src.occupancy -= 1 + # udpate occupancy of destination zone + if not dest.name == 'goal': + dest.occupancy += 1 + accepted.append(f"D{drone.id_}-" + f"{self._color_zone(dest.name)}-" + f"{dest.occupancy}/{dest.max_drones}") + connections_to_clear.append(connection) + + # drone is leaving source + if src.congested is True: + src.congested = False + + self._clear_connections_occupancy(connections_to_clear) + return accepted + + def _new_dest_reachable(self, path_result: PathResult) -> bool: + path = path_result.path + src_name = path[0] + src: Zone = self.graph.get_zone(src_name) + next_zone_name = path[1] + next_zone: Zone = self.graph.get_zone(next_zone_name) + if self._can_enter(next_zone) and self._can_transit(src, next_zone): + return True + else: + return False + + @staticmethod + def _increment_connection_occupancy(src: Zone, + dest: Zone, + graph: Graph + ) -> None: + """Increment the occupancy attribute of a Connection""" + connection = graph.get_connection(src, dest) + connection.link_occupancy += 1 + + @staticmethod + def _connection_congested(src: Zone, + dest: Zone, + graph: Graph + ) -> None: + """Toogle congested attribute of Connection to True""" + connection = graph.get_connection(src, dest) + connection.congested = True + + @staticmethod + def _clear_connections_occupancy(connections: List[Connection]) -> None: + """Clear occupancy of connections""" + for connection in connections: + if connection.dest.zone_type == ZoneType.RESTRICTED: + continue + connection.link_occupancy -= 1 + connection.congested = False + + # spin off color methods to its own class + def _color_zone( + self, + dest: str, + ) -> str: + """Color zone name if zone has a color attribute""" + zone = self.graph.get_zone(dest) + if zone.color is None: + return zone.name + if zone.color: + return self._color_string(zone, zone.color) + raise KeyError(f"No zone {dest}") + + def _color_string( + self, + zone: Zone, + zone_color: str + ) -> str: + all_colors: dict[str, str] = {'black': "\033[0;30m", + 'red': "\033[0;31m", + 'green': "\033[0;32m", + 'yellow': "\033[0;33m", + 'blue': "\033[0;34m", + 'magenta': "\033[0;35m", + 'cyan': "\033[0;36m", + 'white': "\033[0;37m", + 'gray': "\033[0;90m", + 'grey': "\033[0;90m", + # using 256-color mode + 'brown': "\033[38;5;137", + 'crimson': "\033[38;5;160m", + 'darkred': "\033[38;5;52m", + 'gold': "\033[38;5;226m", + 'lime': "\033[38;5;83m", + 'maroon': "\033[38;5;001m", + 'orange': "\033[38;5;208m", + 'purple': "\033[38;5;128m", + 'violet': "\033[38;5;93m", + 'pink': "\033[38;5;201m" + } + + for color in all_colors: + if zone_color == color: + return f"{all_colors[color]}{zone.name}\033[0m" + raise KeyError(f"No color '{zone_color}', check your map.") + + @staticmethod + def _can_enter(dest: Zone) -> bool: + """Return whether a destination has enough capacity.""" + if dest.is_end: + return True + + return dest.occupancy < dest.max_drones + + def _can_transit(self, + src: Zone, + dest: Zone + ) -> bool: + """Return whether a drone can transit through a connection.""" + + occupancy = self.graph.get_link_occupancy(src, dest) + capacity = self.graph.get_link_capacity(src, dest) + return occupancy < capacity |
