diff options
| author | yctct <yctct@yctct.com> | 2026-11-25 17:56:21 +0100 |
|---|---|---|
| committer | yctct <yctct@yctct.com> | 2026-11-25 17:56:21 +0100 |
| commit | 489b223db74f468032c1eeb6ca18ee6a4da3bc33 (patch) | |
| tree | a360664813443859ebfc0dcce79dec7fddf93c9f /src/pathfinder.py | |
Add files, first commit
Diffstat (limited to 'src/pathfinder.py')
| -rw-r--r-- | src/pathfinder.py | 176 |
1 files changed, 176 insertions, 0 deletions
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.") |
