-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAstar.py
42 lines (37 loc) · 1.63 KB
/
Astar.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
from data.PriorityQueue import PriorityQueue
from haversine import haversine, Unit
class astarGraph():
def __init__(self, graph):
self.graph = graph
def heuristic(self, current, to_find):
return haversine((current['y'], current['x']),(to_find['y'], to_find['x']),unit=Unit.METERS)
def astar(self, start, to_find):
toVisit = PriorityQueue()
toVisit.put(start, 0)
visitedFromVertex = {}
costToVertex= {}
visitedFromVertex[start] = None
costToVertex[start] = 0
exploredVertices = 0
exploredEdges = 0
while not toVisit.empty():
current = toVisit.get()
exploredVertices += 1
if current == to_find:
path = []
while current != start:
path.append(current)
current = visitedFromVertex[current]
path.append(start)
path.reverse()
return path, exploredVertices, exploredEdges, costToVertex[to_find]
for neighbor in list(self.graph.neighbors(current)):
distance = self.graph[current][neighbor][0]["length"]
newCost = costToVertex[current] + distance
exploredEdges += 1
if neighbor not in costToVertex or newCost < costToVertex[neighbor]:
costToVertex[neighbor] = newCost
priority = newCost + self.heuristic(self.graph.nodes[neighbor], self.graph.nodes[to_find])
toVisit.put(neighbor, priority)
visitedFromVertex[neighbor] = current
return