-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenvironmental.py
445 lines (371 loc) · 16.2 KB
/
environmental.py
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
from vagabond.systems import node
from graphviz import Digraph
# This is a class that will be have all the different path finding algorithms
class env:
"""
A class representing an environment.
Attributes:
- get_neighbors (function): A function that returns the neighbors of a node.
- path (list): A list representing the path in the environment.
Methods:
- __init__(get_neighbors_func): Initializes the environment with the given get_neighbors function.
- __getitem__(index): Returns the node at the specified index in the path.
- __len__(): Returns the length of the path.
- __repr__(): Returns a string representation of the path.
- __str__(): Returns a string representation of the path.
- __iter__(): Returns an iterator for the path.
- get(): Returns the path as a list of nodes.
- add(node): Adds a node to the path.
- remove(node): Removes a node from the path.
- clear(): Clears the path.
- get_raw(): Returns an array of values from the path.
- display_path(filename='graph', directory='.'): Displays the path in a graph and saves it as a PNG file.
"""
#Functions -- Important Functions
get_neighbors = None
#Other Variables
path = []
#Constructor
def __init__(self, get_neighbors_func):
self.get_neighbors = get_neighbors_func
if not self.get_neighbors:
raise ValueError("get_neighbors function is not defined")
# Get a node from the path
def __getitem__(self, index):
try:
return self.path[index]
except IndexError:
raise IndexError("Index out of range") from None
# Get the length of the path
def __len__(self):
return len(self.path)
# Print the path
def __repr__(self):
return str(self.path)
# Print the path
def __str__(self):
return str(self.path)
# Make it iterable
def __iter__(self):
return iter(self.path)
# Get the path as a list of nodes
def get(self):
return self.path
#Add a node to the path
def add(self, node):
if not isinstance(node, node):
raise TypeError("node must be an instance of the node class. Got '{}' instead".format(type(node)))
self.path.append(node)
# Remove a node from the path
def remove(self, node):
if not isinstance(node, node):
raise TypeError("node must be an instance of the node class. Got '{}' instead".format(type(node)))
self.path.remove(node)
# Clear the path
def clear(self):
self.path = []
# Get array of values from the path
def get_raw(self):
if self.path == []:
return []
else:
return [node.value for node in self.path]
# display the path in a graph
def display_path(self, filename='graph', directory='.'):
"""
Display the path as a graph.
Args:
filename (str, optional): The name of the file to save the graph as. Defaults to 'graph'.
directory (str, optional): The directory to save the graph in. Defaults to '.'.
Returns:
dot: The graph object.
Raises:
ValueError: If the path is empty.
"""
if not self.path:
raise ValueError("Path is empty. Cannot display graph.")
dot = Digraph()
dot.node_attr.update(shape='rectangle')
for node in self.path:
make_str = "Node: " + node.name
if node.value is not None:
make_str += "\n----------\nValue: \n" + str(node.value)
dot.node(node.name, label=make_str)
if node.parent:
dot.edge(node.parent.name, node.name)
filepath = f"{directory}/{filename}"
dot.render(filepath, format='png', view=True)
print(f"Graph saved as '{filename}.png' in directory '{directory}'")
return dot
class astar(env):
"""
A* algorithm implementation for pathfinding in a graph.
Args:
get_neighbors_func (function): A function that returns the neighbors of a given node.
Attributes:
path (list): The path found by the A* algorithm.
Methods:
path(start_node, end_node): Finds the shortest path from start_node to end_node using the A* algorithm.
"""
"""
Initializes the A* algorithm.
Args:
get_neighbors_func (function): A function that returns the neighbors of a given node.
"""
"""
Finds the shortest path from start_node to end_node using the A* algorithm.
Args:
start_node (node): The starting node of the path.
end_node (node): The end node of the path.
Returns:
list: The shortest path from start_node to end_node.
Raises:
TypeError: If start_node or end_node is not an instance of the node class.
ValueError: If start_node or end_node is not defined.
"""
def __init__(self, get_neighbors_func):
super().__init__(get_neighbors_func)
def path(self, start_node = None, end_node = None):
"""
Finds the shortest path between two nodes in the graph.
Parameters:
start_node (node): The starting node of the path.
end_node (node): The ending node of the path.
Returns:
list: The shortest path as a list of nodes.
Raises:
TypeError: If start_node or end_node is not an instance of the node class.
ValueError: If start_node or end_node is not defined.
"""
if start_node is not None:
if not isinstance(start_node, node):
raise TypeError("start_node must be an instance of the node class. Got '{}' instead".format(type(start_node)))
else:
raise ValueError("start_node is not defined")
if end_node is not None:
if not isinstance(end_node, node):
raise TypeError("end_node must be an instance of the node class. Got '{}' instead".format(type(end_node)))
else:
raise ValueError("end_node is not defined")
unvisited = []
visited = []
# Add the start node to the unvisited list
unvisited.append(start_node)
while unvisited:
# Get the node with the minimum cost
current_node = min(unvisited, key=lambda x: x.cost)
# Remove the current node from the unvisited list
unvisited.remove(current_node)
# Add the current node to the visited list
visited.append(current_node)
# Check if the current node is the end node
if current_node == end_node:
path = []
while current_node:
path.append(current_node)
current_node = current_node.parent
self.path = path[::-1]
return self.path
# Get the neighbors of the current node
neighbors = self.get_neighbors(current_node)
# Loop through the neighbors
for neighbor_node in neighbors:
# Check if the neighbor is in the visited list
if neighbor_node in visited:
continue
# Check if the neighbor is in the unvisited list
if neighbor_node not in unvisited:
unvisited.append(neighbor_node)
else:
# Replace the neighbor node with the new node if the new node has a lower cost
for i, node_ in enumerate(unvisited):
if node_ == neighbor_node and node_.cost > neighbor_node.cost:
unvisited[i] = neighbor_node
return None
class bfs(env):
"""
Initializes a breadth-first search algorithm.
Parameters:
- get_neighbors_func: A function that takes a node as input and returns a list of its neighboring nodes.
"""
"""
Finds the shortest path from start_node to end_node using breadth-first search algorithm.
Parameters:
- start_node: The starting node of the path. Must be an instance of the node class.
- end_node: The ending node of the path. Must be an instance of the node class.
Returns:
- path: A list of nodes representing the shortest path from start_node to end_node.
Returns None if no path is found.
"""
def __init__(self, get_neighbors_func):
super().__init__(get_neighbors_func)
def path(self, start_node=None, end_node=None):
"""
Finds the path from start_node to end_node using breadth-first search algorithm.
Args:
start_node (node, optional): The starting node. Defaults to None.
end_node (node, optional): The target node. Defaults to None.
Raises:
TypeError: If start_node or end_node is not an instance of the node class.
ValueError: If start_node or end_node is not defined.
Returns:
list: The path from start_node to end_node, represented as a list of nodes.
Returns None if no path is found.
"""
if start_node is not None:
if not isinstance(start_node, node):
raise TypeError("start_node must be an instance of the node class. Got '{}' instead".format(type(start_node)))
else:
raise ValueError("start_node is not defined")
if end_node is not None:
if not isinstance(end_node, node):
raise TypeError("end_node must be an instance of the node class. Got '{}' instead".format(type(end_node)))
else:
raise ValueError("end_node is not defined")
queue = [start_node]
visited = set()
parent_map = {start_node: None}
while queue:
current_node = queue.pop(0)
if current_node == end_node:
path = []
while current_node:
path.append(current_node)
current_node = parent_map[current_node]
self.path = path[::-1]
return self.path
visited.add(current_node)
neighbors = self.get_neighbors(current_node)
for neighbor in neighbors:
if neighbor not in visited and neighbor not in queue:
parent_map[neighbor] = current_node
queue.append(neighbor)
return None
class dfs(env):
"""
Initializes a depth-first search algorithm.
Parameters:
- get_neighbors_func: A function that returns the neighbors of a given node.
Returns:
None
"""
"""
Finds a path from the start node to the end node using depth-first search.
Parameters:
- start_node: The starting node of the path. Must be an instance of the node class.
- end_node: The ending node of the path. Must be an instance of the node class.
Returns:
- path: A list of nodes representing the path from the start node to the end node.
Returns None if no path is found.
"""
def __init__(self, get_neighbors_func):
super().__init__(get_neighbors_func)
def path(self, start_node=None, end_node=None):
"""
Finds a path from the start_node to the end_node using a depth-first search algorithm.
Args:
start_node (node): The starting node of the path.
end_node (node): The target node to reach.
Returns:
list: A list of nodes representing the path from start_node to end_node,
or None if no path is found.
Raises:
TypeError: If start_node or end_node is not an instance of the node class.
ValueError: If start_node or end_node is not defined.
"""
if start_node is not None:
if not isinstance(start_node, node):
raise TypeError("start_node must be an instance of the node class. Got '{}' instead".format(type(start_node)))
else:
raise ValueError("start_node is not defined")
if end_node is not None:
if not isinstance(end_node, node):
raise TypeError("end_node must be an instance of the node class. Got '{}' instead".format(type(end_node)))
else:
raise ValueError("end_node is not defined")
stack = [start_node]
visited = set()
parent_map = {start_node: None}
while stack:
current_node = stack.pop()
if current_node == end_node:
path = []
while current_node:
path.append(current_node)
current_node = parent_map[current_node]
self.path = path[::-1]
return self.path
visited.add(current_node)
neighbors = self.get_neighbors(current_node)
for neighbor in neighbors:
if neighbor not in visited and neighbor not in stack:
parent_map[neighbor] = current_node
stack.append(neighbor)
return None
class dijkstra(env):
"""
Initializes a Dijkstra object.
Parameters:
- get_neighbors_func (function): A function that returns the neighbors of a given node.
Returns:
- None
"""
"""
Finds the shortest path between two nodes using Dijkstra's algorithm.
Parameters:
- start_node (node): The starting node of the path.
- end_node (node): The ending node of the path.
Returns:
- list: The shortest path from start_node to end_node, represented as a list of nodes.
- None: If no path is found.
"""
def __init__(self, get_neighbors_func):
super().__init__(get_neighbors_func)
def path(self, start_node=None, end_node=None):
"""
Finds the shortest path between two nodes in the graph.
Args:
start_node (node): The starting node of the path.
end_node (node): The ending node of the path.
Returns:
list: The shortest path as a list of nodes.
Raises:
TypeError: If start_node or end_node is not an instance of the node class.
ValueError: If start_node or end_node is not defined.
"""
if start_node:
if not isinstance(start_node, node):
raise TypeError("start_node must be an instance of the node class. Got '{}' instead".format(type(start_node)))
else:
raise ValueError("start_node is not defined")
if end_node:
if not isinstance(end_node, node):
raise TypeError("end_node must be an instance of the node class. Got '{}' instead".format(type(end_node)))
else:
raise ValueError("end_node is not defined")
unvisited = []
visited = []
start_node.cost = 0
unvisited.append(start_node)
while unvisited:
current_node = min(unvisited, key=lambda x: x.cost)
unvisited.remove(current_node)
visited.append(current_node)
if current_node == end_node:
path = []
while current_node:
path.append(current_node)
current_node = current_node.parent
self.path = path[::-1]
return self.path
neighbors = self.get_neighbors(current_node)
for neighbor in neighbors:
if neighbor in visited:
continue
new_cost = current_node.cost + neighbor.cost
if neighbor not in unvisited or new_cost < neighbor.cost:
neighbor.cost = new_cost
neighbor.parent = current_node
if neighbor not in unvisited:
unvisited.append(neighbor)
return None