Repository navigation
Expand file tree
/
Copy pathsimulation.py
More file actions
186 lines (139 loc) · 5.91 KB
/
Copy pathsimulation.py
File metadata and controls
186 lines (139 loc) · 5.91 KB
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
177
178
179
180
181
182
183
184
185
186
import heapq
from module import Graph, Zone, Connection, Drone, EndHub
from module import Visualization as Visual
from parser import MapData
class UnsolvableGraphError(Exception):
"""Exception raised when a graph algorithm cannot find a solution."""
pass
class Engine:
def __init__(self, data: MapData, graph: Graph) -> None:
"""Create a simulation engine.
Args:
data: Parsed map data.
graph: Graph built from the parsed map.
"""
self.data = data
self.graph = graph
self.node_obj = {
node.name: node for node in graph.adj_list.keys()
}
def dijkstra(self, start_zone: Zone) -> list[str]:
"""Compute the path from the start zone to the final zone.
Args:
start_zone: Zone where the search begins.
Returns:
The ordered list of zone names for the chosen path.
"""
distances: dict[str, float] = {
node.name: float('inf') for node in self.graph.adj_list.keys()
}
distances[start_zone.name] = 0
predecessors: dict[str, None | str] = {
node.name: None for node in self.graph.adj_list.keys()
}
heap: list[tuple[int | float, int, str]] = [
(0, start_zone.priority, start_zone.name)
]
visited = []
while heap:
zone_cost, zone_priority, zone_name = heapq.heappop(heap)
zone_node = self.node_obj[zone_name]
for neighbor_cost, neighbor in self.graph.get_neighbors(zone_node):
if (neighbor.name not in visited
and neighbor_cost + zone_cost < distances[neighbor.name]):
distances[neighbor.name] = neighbor_cost + zone_cost
predecessors[neighbor.name] = zone_name
heapq.heappush(
heap, (distances[neighbor.name],
neighbor.priority + zone_priority,
neighbor.name)
)
visited.append(zone_name)
return self.get_path(predecessors)
def get_path(self, predecessors: dict[str, None | str]) -> list[str]:
"""Reconstruct a path from predecessor links.
Args:
predecessors: Mapping of node name to predecessor name.
Returns:
The reconstructed path as a list of zone names.
Raises:
UnsolvableGraphError: If the path cannot reach a destination.
"""
path = []
node: str | None = next(reversed(predecessors.keys()))
while node is not None:
path.append(node)
node = predecessors[node]
path.reverse()
if len(path) == 1:
raise UnsolvableGraphError(
"The graph cannot be solved: no valid path or solution exists"
)
return path
def get_connection(self, zone1: Zone, zone2: Zone) -> Connection:
"""Return the connection between two zones.
Args:
zone1: First endpoint.
zone2: Second endpoint.
Returns:
The matching connection.
Raises:
ValueError: If no connection exists between the zones.
"""
for connection in self.data.connection_list:
if connection.zone1 == zone1 and connection.zone2 == zone2:
return connection
elif connection.zone1 == zone2 and connection.zone2 == zone1:
return connection
raise ValueError("No connection")
def simulation(self, drones: list[Drone]) -> None:
"""Run the turn-based drone simulation.
Args:
drones: Active drones to advance through the graph.
"""
console = Visual.Console()
while drones:
connection_list = []
for drone in drones[:]:
drone.next_zone = self.node_obj[drone.path.pop(0)]
zone_connection = self.get_connection(
drone.position, drone.next_zone
)
connection_list.append(zone_connection)
if drone.next_zone.default_metadata['zone'] == "restricted":
drone.transit_turns_left += 1
if drone.transit_turns_left == 2:
drone.next_zone.available += 1
if (drone.next_zone.available and
zone_connection.default_metadata["max_link_capacity"]):
drone.next_zone.available -= 1
zone_connection.default_metadata["max_link_capacity"] -= 1
if drone.transit_turns_left == 1:
next_zone_name = Visual.apply_color(drone.next_zone)
pre_zone_name = Visual.apply_color(drone.position)
console.print(
f"{drone.id}-"
f"{pre_zone_name}-"
f"{next_zone_name}",
end=" "
)
drone.path.insert(0, drone.next_zone.name)
else:
drone.position.available += 1
drone.position = drone.next_zone
drone.transit_turns_left = 0
position_name = Visual.apply_color(drone.position)
console.print(
f"{drone.id}-"
f"{position_name}", end=" "
)
else:
drone.transit_turns_left = 0
drone.path.insert(0, drone.next_zone.name)
if isinstance(drone.position, EndHub):
drones.remove(drone)
for connection in connection_list:
connection.default_metadata[
"max_link_capacity"
] = connection.fallback_max_link_capacity
print()