-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule.py
More file actions
380 lines (313 loc) · 11 KB
/
Copy pathmodule.py
File metadata and controls
380 lines (313 loc) · 11 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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
from typing import TypedDict
from rich.console import Console
class DictMetaDataZone(TypedDict):
"""Typed metadata stored on a zone."""
zone: str
color: str
max_drones: int | float
class DictMetaDataConnection(TypedDict):
"""Typed metadata stored on a connection."""
max_link_capacity: int
class Zone:
def __init__(
self, name: str, coordinates: tuple[int, int], metadata: str | None
) -> None:
"""Create a zone with optional metadata.
Args:
name: Zone name.
coordinates: Zone coordinates on the map.
metadata: Optional metadata string in ``key=value`` form.
"""
self.name = name
self.coordinates = coordinates
self.default_metadata: DictMetaDataZone = {
"zone": "normal",
"color": "none",
"max_drones": 1,
}
if metadata is not None and metadata.strip():
self.set_metadata(metadata)
self.available = self.default_metadata["max_drones"]
if self.default_metadata["zone"] == "priority":
self.priority = 0
else:
self.priority = 1
def set_metadata(self, metadata: str) -> None:
"""Parse and validate zone metadata.
Args:
metadata: Metadata string in ``key=value`` form.
Raises:
ValueError: If the metadata format or values are invalid.
"""
zone_types = ["normal", "blocked", "restricted", "priority"]
colors = [
"black",
"blue",
"brown",
"crimson",
"cyan",
"darkred",
"gold",
"green",
"lime",
"magenta",
"maroon",
"orange",
"purple",
"rainbow",
"red",
"violet",
"yellow",
"gray"
]
tags = metadata.split()
for tag in tags:
try:
key, value = tag.split("=")
except ValueError:
raise ValueError(
"Invalid zone metadata: expected key=value"
)
if key == "zone":
if value not in zone_types:
raise ValueError(
"Invalid zone metadata for 'zone'"
)
self.default_metadata["zone"] = value
elif key == "color":
if value not in colors:
raise ValueError(
"Invalid zone metadata for 'color'"
)
self.default_metadata["color"] = value
elif key == "max_drones":
try:
max_drones = int(value)
except ValueError:
raise ValueError(
"Invalid zone metadata for 'max_drones': "
"expected a positive integer"
)
if max_drones <= 0:
raise ValueError(
"Invalid zone metadata for 'max_drones': "
"must be greater than 0"
)
self.default_metadata["max_drones"] = max_drones
else:
raise ValueError("Invalid zone metadata key")
class StartHub(Zone):
def __init__(
self, name: str, coordinates: tuple[int, int], metadata: str | None
) -> None:
"""Create the starting hub.
Args:
name: Hub name.
coordinates: Hub coordinates on the map.
metadata: Optional metadata string in ``key=value`` form.
"""
super().__init__(name, coordinates, metadata)
self.available = float('inf')
class EndHub(Zone):
def __init__(
self, name: str, coordinates: tuple[int, int], metadata: str | None
) -> None:
"""Create the ending hub.
Args:
name: Hub name.
coordinates: Hub coordinates on the map.
metadata: Optional metadata string in ``key=value`` form.
"""
super().__init__(name, coordinates, metadata)
self.available = float('inf')
class Hub(Zone):
def __init__(
self, name: str, coordinates: tuple[int, int], metadata: str | None
) -> None:
"""Create an intermediate hub.
Args:
name: Hub name.
coordinates: Hub coordinates on the map.
metadata: Optional metadata string in ``key=value`` form.
"""
super().__init__(name, coordinates, metadata)
class Connection:
def __init__(self, zone1: Zone, zone2: Zone, metadata: str | None) -> None:
"""Create a connection between two zones.
Args:
zone1: First endpoint.
zone2: Second endpoint.
metadata: Optional metadata string in ``key=value`` form.
"""
self.zone1 = zone1
self.zone2 = zone2
self.default_metadata: DictMetaDataConnection = {
"max_link_capacity": 1
}
self.fallback_max_link_capacity = 1
if metadata is not None and metadata.strip():
self.set_metadata(metadata)
def set_metadata(self, metadata: str) -> None:
"""Parse and validate connection metadata.
Args:
metadata: Metadata string in ``key=value`` form.
Raises:
ValueError: If the metadata format or values are invalid.
"""
tags = metadata.split()
for tag in tags:
try:
key, value = tag.split("=")
except ValueError:
raise ValueError(
"Invalid connection metadata: expected key=value"
)
if key != "max_link_capacity":
raise ValueError("Invalid connection metadata key")
try:
max_link_capacity = int(value)
except ValueError:
raise ValueError(
"Invalid connection metadata for 'max_link_capacity': "
"expected as integer"
)
if max_link_capacity <= 0:
raise ValueError(
"Invalid connection metadata for 'max_link_capacity': "
"must be greater than 0"
)
self.default_metadata["max_link_capacity"] = max_link_capacity
self.fallback_max_link_capacity = max_link_capacity
class ZoneFactory:
"""Factory for building zone instances from parsed map data."""
@staticmethod
def create(
create_type: str, name: str,
coordinates: tuple[int, int], metadata: str
) -> Zone:
"""Create a zone instance of the requested type.
Args:
create_type: Zone kind, such as ``start``, ``end`` or ``hub``.
name: Zone name.
coordinates: Zone coordinates on the map.
metadata: Optional metadata string.
Returns:
A zone instance matching ``create_type``.
Raises:
ValueError: If ``create_type`` is not supported.
"""
match create_type:
case "start":
return StartHub(name, coordinates, metadata)
case "end":
return EndHub(name, coordinates, metadata)
case "hub":
return Hub(name, coordinates, metadata)
case _:
raise ValueError(
"Invalid zone type: expected start, end, or hub"
)
class Drone:
def __init__(self, id: str, position: Zone, path: list[str]) -> None:
"""Create a drone with its current position and planned path.
Args:
id: Drone identifier.
position: Current zone.
path: Remaining path as zone names.
"""
self.id = id
self.position = position
self.path = path
self.transit_turns_left = 0
self.next_zone = position
class Graph:
"""Weighted graph of zones and connections."""
zone_cost = {
"normal": 1,
"blocked": float('inf'),
"restricted": 2,
"priority": 1
}
def __init__(self) -> None:
"""Initialize an empty adjacency list."""
self.adj_list: dict[Zone, list[tuple[int | float, Zone]]] = dict()
def add_nodes(self, node: Zone) -> None:
"""Add a zone to the graph.
Args:
node: Zone to add.
Raises:
ValueError: If the node already exists.
"""
if node not in self.adj_list:
self.adj_list[node] = list()
else:
raise ValueError("Node exist already")
def add_edges(self, connection: Connection) -> None:
"""Add a bidirectional edge for a connection.
Args:
connection: Connection to register in the graph.
Raises:
ValueError: If the edge already exists.
"""
zone1_cost = self.zone_cost[connection.zone1.default_metadata["zone"]]
zone2_cost = self.zone_cost[connection.zone2.default_metadata["zone"]]
if ((zone1_cost, connection.zone1) not in
self.adj_list[connection.zone2]
and (zone2_cost, connection.zone2) not in
self.adj_list[connection.zone1]):
self.adj_list[connection.zone2].append((
zone1_cost,
connection.zone1
))
self.adj_list[connection.zone1].append((
zone2_cost,
connection.zone2
))
else:
raise ValueError("Edge exist already")
def get_neighbors(self, node: Zone) -> list[tuple[int | float, Zone]]:
"""Return adjacent zones for a node.
Args:
node: Zone whose neighbors are requested.
Returns:
A list of ``(cost, zone)`` neighbor pairs.
"""
return self.adj_list[node]
class Visualization:
"""Format zones for colored terminal output."""
COLORS = {
"none": "#FFFFFF",
"black": "#000000",
"blue": "#0000FF",
"brown": "#A52A2A",
"crimson": "#DC143C",
"cyan": "#00FFFF",
"darkred": "#8B0000",
"gold": "#FFD700",
"green": "#008000",
"lime": "#00FF00",
"magenta": "#FF00FF",
"maroon": "#800000",
"orange": "#FFA500",
"purple": "#800080",
"red": "#FF0000",
"violet": "#EE82EE",
"yellow": "#FFFF00",
"gray": "#808080"
}
Console = Console
@classmethod
def apply_color(cls, zone: Zone) -> str:
"""Return a rich-formatted zone name.
Args:
zone: Zone to format.
Returns:
The zone name wrapped in color markup.
"""
if zone.default_metadata["color"] == "rainbow":
name = ""
for i, char in enumerate(zone.name, 0):
color = list(cls.COLORS.values())[i % len(cls.COLORS)]
name += f"[{color}]{char}"
return name
return f"[{cls.COLORS[zone.default_metadata['color']]}]{zone.name}"