summaryrefslogtreecommitdiff
path: root/src/pathfinder.py
blob: 4464e5ae473fe0d1f96645131859df2fd5109f0e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
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.")