diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/drone.py | 77 | ||||
| -rw-r--r-- | src/graph.py | 131 | ||||
| -rw-r--r-- | src/main.py | 52 | ||||
| -rw-r--r-- | src/models.py | 90 | ||||
| -rw-r--r-- | src/parser.py | 564 | ||||
| -rw-r--r-- | src/pathfinder.py | 176 | ||||
| -rw-r--r-- | src/scheduler.py | 285 |
7 files changed, 1375 insertions, 0 deletions
diff --git a/src/drone.py b/src/drone.py new file mode 100644 index 0000000..d47a08a --- /dev/null +++ b/src/drone.py @@ -0,0 +1,77 @@ +"""Class and methods for a drone""" + +from dataclasses import dataclass, field +from typing import List +from graph import Graph +from models import Zone, Connection +from pathfinder import PathResult + + +@dataclass +class Drone: + """ + Represent one drone travelling along a fixed path + Initialize path as an empty list using the default factory of + library dataclass. + """ + + id_: int + path: List[str] = field(default_factory=list) + path_index: int = 0 + delivered: bool = False + in_transit: bool = False + + # read-only, no parentheses needed to call + @property + def current_zone(self) -> str: + """Return the drone's current zone.""" + return self.path[self.path_index] + + @property + def next_zone(self) -> str | None: + """Return the next zone, or None if the drone is delivered.""" + next_index = self.path_index + 1 + + if next_index >= len(self.path): + return None + + return self.path[next_index] + + def move(self) -> str | None: + """Move the drone to its next zone.""" + dest = self.next_zone + + if dest is None: + self.delivered = True + return None + + self.path_index += 1 + + if self.path_index == len(self.path) - 1: + self.delivered = True + + return dest + + def leave_transit(self, src: Zone, dest: Zone, graph: Graph) -> None: + """Leave transit to restricted zone""" + self.move() + connection = graph.get_connection(src, dest) + connection.congested = False + dest.congested = False + connection.link_occupancy -=1 + dest.occupancy += 1 + dest.reservation -= 1 + self.in_transit = False + + def update_path(self, path_result: PathResult) -> None: + """ Update drone's path""" + self.path = path_result.path + self.path_index = 0 + + def update_dest(self, graph: Graph) -> Zone: + """"Return drone's destination""" + if self.next_zone is None: + raise KeyError("That is it! No next zone") + dest_name: str = self.next_zone + dest: Zone = graph.get_zone(dest_name) + return dest diff --git a/src/graph.py b/src/graph.py new file mode 100644 index 0000000..c986c16 --- /dev/null +++ b/src/graph.py @@ -0,0 +1,131 @@ +"""Converts map info into a graph""" + +from models import MapData, Zone, Connection +from typing import List + + +class Graph: + """Represents zone connectivity for a drone map.""" + + def __init__( + self, + drone_map: MapData + ) -> None: + self._zones: dict[str, Zone] = {} + # a list of adjacent zones per zone + self._adjacency: dict[str, List[Zone]] = {} + # a list of connections per zone + self._connections: dict[str, List[Connection]] = {} + self._build(drone_map) + + def _build( + self, + drone_map: MapData + ) -> None: + """Build a bidirectional adjacency list. + + There is no duplicate connection i.e. only a-b and no b-a + so when we append a connection to a zone, we also need to + append the reverse connection to its destination. + """ + all_zones = [ + drone_map.start, + drone_map.end, + *drone_map.zones, + ] + + # create dictionaries' keys + for zone in all_zones: + self._zones[zone.name] = zone + self._adjacency[zone.name] = [] + self._connections[zone.name] = [] + + for connection in drone_map.connections: + src = connection.src + dest = connection.dest + + self._adjacency[src.name].append(dest) + self._adjacency[dest.name].append(src) + + self._connections[src.name].append(connection) + reverse = Connection( + src=dest, + dest=src, + link_capacity=connection.link_capacity + ) + self._connections[dest.name].append(reverse) + + def neighbours( + self, + zone_name: str + ) -> List[Zone]: + """Return zones directly connected to the given zone.""" + if zone_name not in self._adjacency: + raise KeyError(f"Unknown zone: {zone_name}") + + return self._adjacency[zone_name] + + def get_link_capacity( + self, + src: Zone, + dest: Zone + ) -> int: + """Return the max capacity for a link between two zones.""" + if src.name not in self._adjacency: + raise KeyError(f"Unknown zone: {src.name}") + if dest.name not in self._adjacency: + raise KeyError(f"Unknown zone: {dest.name}") + connection = self.get_connection(src, dest) + return connection.link_capacity + + def get_link_occupancy( + self, + src: Zone, + dest: Zone + ) -> int: + """Return the occupancy for a link between two zones.""" + if src.name not in self._adjacency: + raise KeyError(f"Unknown zone: {src.name}") + if dest.name not in self._adjacency: + raise KeyError(f"Unknown zone: {dest.name}") + connection = self.get_connection(src, dest) + return connection.link_occupancy + + def get_zone( + self, + zone_name: str + ) -> Zone: + """Return a zone by name.""" + return self._zones[zone_name] + + def get_start(self) -> Zone: + """Return the end zone""" + zones = self._zones + for zone in zones.values(): + if zone.is_start is True: + return zone + raise KeyError(f"No zone {zone}") + + def get_end(self) -> Zone: + """Return the start zone""" + zones = self._zones + for zone in zones.values(): + if zone.is_end is True: + return zone + raise KeyError(f"No zone {zone}") + + def get_connection( + self, + src: Zone, + dest: Zone + ) -> Connection: + if src.name not in self._adjacency: + raise KeyError(f"Unknown zone: {src.name}") + if dest.name not in self._adjacency: + raise KeyError(f"Unknown zone: {dest.name}") + """Return the connection between two zones""" + connections = self._connections[src.name] + for connection in connections: + if connection.dest.name == dest.name: + return connection + raise KeyError(f"No connection between {src} and {dest}") diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..faa7e96 --- /dev/null +++ b/src/main.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +from graph import Graph +from parser import Parser +from pathfinder import Pathfinder +from scheduler import Scheduler +import sys +from visualiser import Visualiser + + +def main() -> None: + """Parse a map, + create a graph, + find the shortest path, + run the simulation through the scheduler + """ + if len(sys.argv) != 2: + print("Usage: './main.py <map_file>' or 'make run MAP=path/to/map'") + return + + try: + parser = Parser() + + drone_map = parser.parse_map() + + graph = Graph(drone_map) + + pathfinder = Pathfinder(graph) + + result = pathfinder.find_path( + drone_map.start.name, + drone_map.end.name, + ) + + if result is None: + print("No valid path found.") + return + + scheduler = Scheduler( + graph=graph, + path=result.path, + number_of_drones=drone_map.nb_drones, + ) + + scheduler.run() +# Visualiser(graph, drone_map, scheduler).run() + + except Exception as e: + print(e) + + +if __name__ == "__main__": + main() diff --git a/src/models.py b/src/models.py new file mode 100644 index 0000000..6af4d65 --- /dev/null +++ b/src/models.py @@ -0,0 +1,90 @@ +"""Classes for Zone, Connections and the map""" +from enum import Enum +from typing_extensions import Self + +from pydantic import BaseModel, Field, model_validator + + +class ZoneType(str, Enum): + """Valid zone types.""" + + NORMAL = "normal" + BLOCKED = "blocked" + RESTRICTED = "restricted" + PRIORITY = "priority" + + +class Zone(BaseModel): + """Represents a zone in the drone network.""" + + name: str = Field(min_length=1) + x: int + y: int + zone_type: ZoneType = Field(default=ZoneType.NORMAL) + color: str | None = None + max_drones: int = Field(default=1, ge=1) + is_start: bool = Field(default=False) + is_end: bool = Field(default=False) + connections: list[str] = Field(default_factory=list) + occupancy: int = Field(default=0, ge=0) + congested: bool = Field(default=False) + reservation: int = Field(default=0, ge=0) + + @model_validator(mode="after") + def validate_name(self) -> Self: + + # checking for space here is not so useful because parsing fails anyway + if " " in self.name or "-" in self.name: + raise ValueError("zone names must not contain spaces or dashes") + + if self.zone_type != ZoneType.BLOCKED and self.max_drones == 0: + raise ValueError("A non-blocked zone type must have capacity of " + "at least one drone.") + + return self + + +class Connection(BaseModel): + """Represents bidirectional link between two connection.""" + + src: Zone + dest: Zone + link_capacity: int = Field(default=1, ge=0) + link_occupancy: int = Field(default=0, ge=0) + congested: bool = Field(default=False) + + @model_validator(mode="after") + def validate_connection(self) -> Self: + + if self.src == self.dest: + raise ValueError("a connection cannot connect a zone to itself") + + if self.src.zone_type != ZoneType.BLOCKED \ + and self.dest.zone_type != ZoneType.BLOCKED \ + and self.link_capacity == 0: + raise ValueError("A connection to a non-blocked zone" + "must have a capacity of at least one drone.") + + return self + + +class MapData(BaseModel): + """All data needed to run a simulation.""" + + nb_drones: int = Field(gt=0) + start: Zone + end: Zone + zones: list[Zone] + connections: list[Connection] + + @model_validator(mode="after") + def post_validate(self) -> Self: + + same_name = self.start.name == self.end.name + same_position = (self.start.x == self.end.x + and self.start.y == self.end.y) + + if self.start == self.end or same_name or same_position: + raise ValueError("Start and end zones cannot overlap.") + + return self diff --git a/src/parser.py b/src/parser.py new file mode 100644 index 0000000..dffba84 --- /dev/null +++ b/src/parser.py @@ -0,0 +1,564 @@ +#!/usr/bin/env python3 +""" Parser for the file with specification for the map""" +import argparse +from argparse import Namespace +from pathlib import Path + +from models import Connection, MapData, Zone, ZoneType + + +class ParseError(Exception): + """Parsing errors""" + pass + + +class Parser: + """Parse a drone map file into a MapData instance.""" + + VALID_KEYS = { + "nb_drones", + "start_hub", + "end_hub", + "hub", + "connection", + } + + def __init__(self) -> None: + self.args = self.parse_args() + + def parse_map(self) -> MapData: + """Parse the input file and return a validated MapData.""" + + lines = self._read_file() + lines = self._clean_lines(lines) + + self._check_keys_valid(lines) + + nb_drones = self._parse_nb_drones(lines) + + start = self._parse_start_end_zone( + lines, + nb_drones, + is_start=True, + ) + + end = self._parse_start_end_zone( + lines, + nb_drones, + is_start=False, + ) + + zones = self._parse_zones( + lines, + nb_drones, + start, + end, + ) + + connections = self._parse_connections( + lines, + zones, + start, + end, + ) + return MapData( + nb_drones=nb_drones, + start=start, + end=end, + zones=zones, + connections=connections, + ) + + def parse_args(self) -> Namespace: + """Parse command-line arguments and return a + 'method that runs the parser and places the + extracted data in a 'argparse.Namespace' + object' see argparse documention. + """ + + parser = argparse.ArgumentParser() + parser.add_argument( + "filename", + type=Path, + help="Path to the map file" + ) + return parser.parse_args() + + def _read_file(self) -> list[str]: + """Read all lines from the input file. + Returns a list of lines. + """ + + filename: Path = self.args.filename + + if not filename.exists(): + raise FileNotFoundError( + f"Map file not found: {filename}" + ) + + if not filename.is_file(): + raise ValueError( + f"Not a regular file: {filename}" + ) + + try: + lines = filename.read_text().splitlines() + except PermissionError: + raise PermissionError( + f"Check the permission of file: {filename}" + ) + except OSError: + raise OSError( + f"Unable to read map file: {filename}" + ) + + if not lines: + raise ValueError( + f"Map file is empty: {filename}" + ) + + return lines + + def _clean_lines(self, lines: list[str]) -> list[str]: + """ + Remove blank lines and comments. + Inline comments are also removed. + Returns a list of 'cleaned' lines. + """ + + cleaned: list[str] = [] + + for line in lines: + if line.startswith('#'): + continue + + if line: + cleaned.append(line) + + return cleaned + + def _check_keys_valid(self, lines: list[str]) -> None: + """Check that every line starts with a supported map key. + The start_hub, end_hub, and nb_drones keys may each appear only once. + init seen_keys + add key to seen_keys + check whether new key is already in seen_keys + + Second arg of split is 'maxsplit'. + + See top of the file for VALID_KEYS. + """ + + unique_keys = {"start_hub", "end_hub", "nb_drones"} + seen_keys: set[str] = set() + + for line in lines: + if ":" not in line: + raise ValueError( + f"Invalid line; expected '<key>: ...': {line}" + ) + + key = line.split(":", 1)[0].strip() + + if key not in self.VALID_KEYS: + raise ValueError( + f"Unknown map key '{key}' in line: {line}" + ) + + if key in unique_keys: + if key in seen_keys: + raise ValueError( + f"Duplicate map key '{key}': {line}" + ) + + seen_keys.add(key) + + def _parse_nb_drones(self, lines: list[str]) -> int: + """Extract and validate the number of drones.""" + + if not lines[0].startswith("nb_drones"): + raise ParseError( + "ParseError: The first line does not define" + "the number of drones." + ) + + value = lines[0].split(":", 1)[1].strip() + + try: + nb_drones = int(value) + except ValueError: + raise ValueError( + f"Invalid number of drones: {value!r}" + ) + + if nb_drones <= 0: + raise ValueError( + "The number of drones must be greater than zero." + ) + + return nb_drones + + def _parse_start_end_zone( + self, + lines: list[str], + nb_drones: int, + is_start: bool = False, + ) -> Zone: + """Check whether zone is start or end. + Extract the line. + Extract and process the start or end zone.""" + + zone_key = "start_hub" if is_start else "end_hub" + + line = self._get_line(lines, zone_key) + + return self._process_zone_line( + line=line, + nb_drones=nb_drones, + zone=zone_key, + is_start=is_start, + is_end=not is_start, + ) + + def _get_line( + self, + lines: list[str], + zone: str, + ) -> str: + """Return the unique start_hub or end_hub line. + Raise an error if start_* or end_hub is not defined. + Raise an error if multiple start_* or end_hub are defined. + """ + + count = 0 + for line in lines: + if line.startswith(zone): + count += 1 + matching_line = line + + if count == 0: + raise ParseError( + f"ParseError: No {zone} defined." + ) + elif count > 1: + raise ParseError( + f"ParseError: Multiple {zone}s defined." + ) + + return matching_line + + def _process_zone_line( + self, + line: str, + nb_drones: int, + zone: str = "zone", + is_start: bool = False, + is_end: bool = False, + ) -> Zone: + """ + Parse a zone line and return a zone object. + + Supported format: + + hub: name x y [zone=restricted color=blue max_drones=3] + hub: name x y [color=blue max_drones=3] + hub: name x y [color=blue] + start_hub: name x y [color=green] + end_hub: name x y [color=red] + + About split(): If maxsplit is given, at most maxsplit + splits are done (thus, the list will have at most + maxsplit+1 elements). + """ + + expected_prefix = f"{zone}:" + + if not line.startswith(expected_prefix): + raise ValueError( + f"Expected a '{zone}' line, got: {line}" + ) + + after_column = line[len(expected_prefix):].strip() + + # zone_type is default if unspecified + zone_type: ZoneType = ZoneType.NORMAL + color: str | None = None + max_drones = nb_drones if is_start or is_end else 1 + + parts = after_column.split(maxsplit=3) + + # without metadata + if len(parts) == 3: + name, x_value, y_value = parts + + # with metadata + elif len(parts) == 4 \ + and parts[3].startswith('[') \ + and parts[3].endswith(']'): + name, x_value, y_value, metadata = parts + metadata = metadata.strip("[]") + pairs = metadata.split(" ") + + for pair in pairs: + try: + # split metadata pairs + key, value = pair.split("=", 1) + except ValueError: + raise ValueError( + f"Invalid metadata: '{pair}' " + f"for zone '{name}'. " + f"Must be 'key=value'." + ) + key = key.strip().lower() + value = value.strip() + + if key == "color": + color = value + elif key == "zone": + try: + zone_type = ZoneType[value.upper()] # Enum lookup + except KeyError: + raise ParseError( + f"ParseError: Invalid zone type '{value}' " + f"for zone '{name}'." + ) + elif key == "max_drones": + try: + max_drones = int(value) + except ValueError: + raise ValueError( + f"Invalid max_drones value: '{value}'" + f"for zone '{name}'. " + f"Must be an integer." + ) + else: + raise ValueError( + f"Invalid key: '{key}'" + ) + else: + raise ValueError( + f"Invalid syntax for line: '{line}'. " + f"Should be <zone>: <name> <x> <y> [...]. " + f"<name> should not have spaces or dashes." + ) + try: + x = int(x_value) + y = int(y_value) + except ValueError: + raise ValueError( + f"Zone coordinates must be integers: {line}" + ) + + return Zone( + name=name, + x=x, + y=y, + color=color, + zone_type=zone_type, + max_drones=max_drones, + is_start=is_start, + is_end=is_end, + ) + + def _parse_zones( + self, + lines: list[str], + nb_drones: int, + start: Zone, + end: Zone, + ) -> list[Zone]: + """Parse all ordinary zone lines.""" + + zones: list[Zone] = [] + + for line in lines: + if not line.startswith("hub:"): + continue + + zone = self._process_zone_line( + line=line, + nb_drones=nb_drones, + zone="hub", + ) + + zones.append(zone) + + self._verify_unique_zone(zones, start, end) + + return zones + + def _verify_unique_zone( + self, + zones: list[Zone], + start: Zone, + end: Zone, + ) -> bool: + """Ensure that all zone names and coordinates are unique.""" + + all_zones = [start, end, *zones] + + names = [zone.name for zone in all_zones] + + if len(names) != len(set(names)): + raise ValueError( + "Zone names must be unique." + ) + + coordinates = [ + (zone.x, zone.y) + for zone in all_zones + ] + + if len(coordinates) != len(set(coordinates)): + raise ValueError( + "Zone coordinates must be unique." + ) + + return True + + def _parse_connections( + self, + lines: list[str], + zones: list[Zone], + start: Zone, + end: Zone, + ) -> list[Connection]: + """Parse all connection lines.""" + + connections: list[Connection] = [] + + for line in lines: + if not line.startswith("connection:"): + continue + + connection = self._process_conn_line( + line=line, + zones=zones, + start=start, + end=end, + ) + + connections.append(connection) + + if self._check_duplicated_connections(connections): + raise ParseError("ParseError: Duplicated connections.") + + return connections + + def _process_conn_line( + self, + line: str, + zones: list[Zone], + start: Zone, + end: Zone, + ) -> Connection: + """Parse a connection line.""" + + prefix = "connection:" + + if not line.startswith(prefix): + raise ValueError( + f"Invalid connection line: {line}" + ) + + value = line[len(prefix):].strip() + link_capacity_raw: str | None = None + link_capacity_value: int = 1 + + if len(value.split(" ")) > 1: + conn_pair, link_capacity_raw = value.split(" ") + else: + conn_pair = value + + if conn_pair.count("-") != 1: + raise ValueError( + f"Invalid connection definition: {line}. " + "Expected 'connection: zone1-zone2'." + ) + + src_name, dest_name = [ + part.strip() + for part in conn_pair.split("-", 1) + ] + + all_zones = [start, end, *zones] + zone_by_name = { + zone.name: zone + for zone in all_zones + } + + if src_name not in zone_by_name: + raise ValueError( + f"Unknown source zone '{src_name}' in: {line}" + ) + + if dest_name not in zone_by_name: + raise ValueError( + f"Unknown destination zone '{dest_name}' in: {line}" + ) + + src = zone_by_name[src_name] + dest = zone_by_name[dest_name] + + # Store the connection name on both endpoint zones. + connection_name = f"{src.name}-{dest.name}" + + if connection_name not in src.connections: + src.connections.append(connection_name) + + reverse_name = f"{dest.name}-{src.name}" + + if reverse_name not in dest.connections: + dest.connections.append(reverse_name) + + if link_capacity_raw: + try: + link_capacity_pair = link_capacity_raw.strip("[]") + key, link_capacity_value_str = link_capacity_pair.split("=") + # convert to a str to make mypy happy + link_capacity_value = int(link_capacity_value_str) + except ValueError: + raise ValueError( + f"Capacity must be an int: {link_capacity_value}" + ) + + return Connection( + src=src, + dest=dest, + link_capacity=link_capacity_value + ) + + def _check_duplicated_connections( + self, + connections: list[Connection], + ) -> bool: + """Ensure that a connection is not defined more than once + Use frozenset() so that pairs of endpoints are hashable. + A -> B and B -> A produce the same key. + See README for more info. + """ + seen: set[frozenset[str]] = set() + + for connection in connections: + key = frozenset({ + connection.src.name, + connection.dest.name, + }) + + if key in seen: + raise ValueError( + "Duplicated connection found: " + f"{connection.src.name}-{connection.dest.name}" + ) + + seen.add(key) + + return False + + +if __name__ == "__main__": + try: + drone_map = Parser().parse_map() + print(drone_map.model_dump_json(indent=2)) + except (ValueError, FileNotFoundError, OSError) as err: + raise SystemExit(f"Error: {err}") diff --git a/src/pathfinder.py b/src/pathfinder.py new file mode 100644 index 0000000..4464e5a --- /dev/null +++ b/src/pathfinder.py @@ -0,0 +1,176 @@ +"""Pathfinding algorithm for maps.""" + +from dataclasses import dataclass +from heapq import heappop, heappush +from typing import Dict, List, Optional, Tuple +from graph import Graph +from models import Zone, ZoneType + + +@dataclass(frozen=True) +class PathResult: + """Store the result of a shortest-path search. + + Use frozen=True since paths won't change. + """ + + cost: int + path: list[str] + + def get_path(self) -> list[str]: + return self.path + + +class Pathfinder: + """Find the lowest-cost path through a zone graph.""" + + def __init__(self, graph: Graph) -> None: + """Initialize the pathfinder.""" + self.graph = graph + + def find_path( + self, + start_name: str, + goal_name: str + ) -> Optional[PathResult]: + """Find the cheapest path, preferring priority zones on ties. + + Movement cost is the primary criterion. If two paths have the same + movement cost, the path entering more priority zones is preferred. + """ + self._validate_zone_name(start_name) + self._validate_zone_name(goal_name) + + # Maps a zone to its best comparison value: + # (movement_cost, negative_priority_count) + best_values: Dict[str, Tuple[int, int]] = { + start_name: (0, 0), + } + + previous: Dict[str, Optional[str]] = { + start_name: None, + } + + # The negative count makes more priority zones preferable because + # heapq always removes the smallest tuple. + queue: List[Tuple[int, int, str]] = [ + (0, 0, start_name), + ] + + while queue: + # pop the smallest/ child, lowest cost + # negative priority = lower is better + current_cost, negative_priority_count, current_name = ( + heappop(queue) + ) + + current_value = ( + current_cost, + negative_priority_count, + ) + + if current_value != best_values.get(current_name): + continue + + if current_name == goal_name: + path = self._reconstruct_path( + previous, + start_name, + goal_name, + ) + + return PathResult( + cost=current_cost, + path=path, + ) + + for neighbour in self.graph.neighbours(current_name): + if neighbour.zone_type == ZoneType.BLOCKED: + continue + + # when a drone is recomputing the shortest path + # we skip the zone that is congested + if neighbour.congested: + continue + + # when a drone is recomputing the shortest path + # we skip the connection that is congested + current = self.graph.get_zone(current_name) + connection = self.graph.get_connection( + current, + neighbour + ) + if connection.congested is True: + continue + + movement_cost = self._movement_cost(neighbour) + enters_priority = ( + neighbour.zone_type == ZoneType.PRIORITY + ) + + new_cost = current_cost + movement_cost + new_negative_priority_count = ( + negative_priority_count + - int(enters_priority) + ) + + new_value = ( + new_cost, + new_negative_priority_count, + ) + + neighbour_name = neighbour.name + old_value = best_values.get(neighbour_name) + + if old_value is None or new_value < old_value: + best_values[neighbour_name] = new_value + previous[neighbour_name] = current_name + + heappush( + queue, + ( + new_cost, + new_negative_priority_count, + neighbour_name, + ), + ) + + return None + + @staticmethod + def _movement_cost(destination: Zone) -> int: + """Return the cost of entering a destination zone.""" + if destination.zone_type == ZoneType.RESTRICTED: + return 2 + + return 1 + + def _validate_zone_name(self, zone_name: str) -> None: + """Validate that a zone exists in the graph.""" + try: + self.graph.get_zone(zone_name) + except KeyError: + raise ValueError( + f"Unknown zone: {zone_name}" + ) + + @staticmethod + def _reconstruct_path( + previous: Dict[str, Optional[str]], + start_name: str, + goal_name: str, + ) -> List[str]: + """Reconstruct a path from predecessor information.""" + path: List[str] = [] + current_name: Optional[str] = goal_name + + while current_name is not None: + path.append(current_name) + + if current_name == start_name: + path.reverse() + return path + + current_name = previous.get(current_name) + + raise SystemError("Unable to reconstruct the shortest path.") 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 |
