-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathastar.py
278 lines (215 loc) · 8.44 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
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
'''Name: Amit Rokade
Problem 1: Solving Maze using A* Algorithm
(Note: THe following program runs with turtle graphics and runs slowly for mazes as turtle draws every cell
, to turn them on comment lines 118-124 , 307-317)
'''
import turtle,sys,math,random,time
grid=[]
with open("big_maze") as file:
for line in file:
grid.append(line.split())
cellHeight=20
cellWidth=20
rows=len(grid)
# print("Rows",rows)
cols=len(grid[0])
# print("Columns",cols)
goal=(rows-1,cols-1)
start=(0,0)
print("NOTE: TURTLE GRAPHICS ARE OFF BY DEFAULT, REFER COMMENTS TO TURN THEM ON...")
print()
print()
heuristic= [[0 for x in range(cols)] for y in range(rows)]
f= [[0 for x in range(cols)] for y in range(rows)]
g= [[0 for x in range(cols)] for y in range(rows)]
visited_list=[]
to_be_explored_list=[]
neighbors={}
path_dict={}
path=[]
startg=0
t=turtle.Turtle()
# t.goto(-600,600)
t.hideturtle()
t.speed(0)
t._tracer(False)
n=[1,2,3,4]
states_traversed={}
depth=0
def main(rows,cols,heuristic,f,g,visited_list,to_be_explored_list,neighbors,path_dict,t,n,start,states_traversed,depth):
'''A* algorithm is run on different heuristics'''
for number in n:
list = ["Euclidean Heuristic", "Manhattan Heuristic", "Random Heuristic", "Zero Heuristic"]
print("HEURISTIC :",list[number-1])
t.screen.title(list[number-1])
start_time=time.time()
color_grid(rows,cols,heuristic,neighbors,number)
# print("HEURISTICS")
for x in range(rows):
for y in range(cols):
pass
# print(heuristic[x][y])
# print(f[x][y])
# print("Printing neighbors")
# print(neighbors)
to_be_explored_list.append(start)
draw_filled_rect(start[0],start[1],"blue")
states_traversed[start]=1
path_found=False
path_found=search_min_path(heuristic,f,g,visited_list,to_be_explored_list,neighbors,path_dict,number,start,states_traversed,depth)
end_time=time.time()
print("Time taken is: ",end_time-start_time)
print("Maze Path ",path_found)
rows = len(grid)
print("Rows", rows)
cols = len(grid[0])
print("Columns", cols)
goal = (rows - 1, cols - 1)
start = (0, 0)
heuristic = [[0 for x in range(cols)] for y in range(rows)]
f = [[0 for x in range(cols)] for y in range(rows)]
g = [[0 for x in range(cols)] for y in range(rows)]
visited_list = []
to_be_explored_list = []
neighbors = {}
path_dict = {}
t = turtle.Turtle()
# t.goto(-600,600)
t.hideturtle()
t.speed(0)
states_traversed={}
depth=0
t._tracer(False)
print("-----------------------------------")
turtle.mainloop()
def color_grid(rows,cols,heuristic,neighbors,number):
'''Used to draw the matrix in turtle and add neighbors for every cell, adjacent cells with walls are not added'''
for x in range(rows):
for y in range(cols):
# print(x,y)
add_neighbors(x,y,rows,cols,neighbors)
heuristic[x][y]=compute_heuristic(x,y,number)
# if(grid[x][y]=='0'):
# draw_filled_rect(x,y,"white")
# elif(grid[x][y]=='1'):
# draw_filled_rect(x,y,"black")
# else:
# draw_filled_rect(x,y,"green")
def search_min_path(heuristic,f,g,visited_list,to_be_explored_list,neighbors,path_dict,number,start,states_traversed,depth):
'''Used to backtrack and calculate minimum path'''
while (len(to_be_explored_list) > 0):
parent = to_be_explored_list[0]
min_f_cell = to_be_explored_list[0]
min_f_val = f[to_be_explored_list[0][0]][to_be_explored_list[0][1]]
# finding cell with minimum f(n) in open list
for i in range(len(to_be_explored_list)):
x = to_be_explored_list[i][0]
y = to_be_explored_list[i][1]
temp_val = f[x][y]
if temp_val <= min_f_val:
min_f_val = temp_val
min_f_cell = to_be_explored_list[i]
if min_f_cell == goal:
# print("End reached")
temp = goal
draw_filled_rect(goal[0],goal[1],"green")
depth+=1
while (temp != start):
val = path_dict[temp]
path.append(val)
temp = path_dict[temp]
draw_filled_rect(val[0],val[1],"green")
depth+=1
# print(path)
print("Depth:",depth)
print("States Traversed:", len(states_traversed))
print("Branching Factor:",math.e**(math.log(len(states_traversed))/depth))
return True
to_be_explored_list.remove(min_f_cell)
visited_list.append(min_f_cell)
# find minimum from all the neighbors
for neighbor in neighbors[min_f_cell]:
'''' if neighbor is not in closed list, only then check for it'''
if neighbor not in visited_list:
''' first calculating temporary g value'''
neighbor_curr_g = g[x][y] + 10;
if neighbor in to_be_explored_list:
''' If neighbor already in open list and then look for the better g value'''
if (neighbor_curr_g < g[neighbor[0]][neighbor[1]]):
# print("Updating current neighbor from ",g[neighbor[0]][neighbor[1]]," to ",neighbor_curr_g)
g[neighbor[0]][neighbor[1]] = neighbor_curr_g
''' Adding child -> parent to dictionary'''
path_dict[neighbor] = (min_f_cell[0], min_f_cell[1])
else:
''' New un-explored neighbor found ; now setting its g value and adding it to open list
print("Setting the g value of neighbor to be ","",neighbor_curr_g)'''
g[neighbor[0]][neighbor[1]] = neighbor_curr_g
to_be_explored_list.append(neighbor)
draw_filled_rect(neighbor[0], neighbor[1], "blue")
toAdd=(neighbor[0],neighbor[1])
states_traversed[toAdd]=1
''' Adding child -> parent to dictionary'''
path_dict[neighbor] = (min_f_cell[0], min_f_cell[1])
'''Updating heuristic value'''
heuristic[neighbor[0]][neighbor[1]]=compute_heuristic(neighbor[0],neighbor[1],number)
'''Updating f value'''
f[neighbor[0]][neighbor[1]] = g[neighbor[0]][neighbor[1]] + heuristic[neighbor[0]][neighbor[1]]
'''print("F value for ",neighbor[0],neighbor[1]," is ",f[neighbor[0]][neighbor[1]])'''
else:
# Cell skipped
pass
def calc_gn(x,y):
return g[x][y]+10
def compute_heuristic(x,y,number):
'''EUCLEDIAN,MANHATTAN,RANDOM OR ZERO HEURISTICS'''
if number ==1:
'''EUCLEDIAN'''
return math.sqrt((goal[0]-x)**2)+((goal[1]-y)**2)
elif number ==2:
'''Manhattan'''
return (abs(goal[0]-x))*10+(abs(goal[1]-y))*10
elif number ==3:
'''Random'''
return random.randint(1,200)
else:
'''Zero'''
return 0
def add_neighbors(x,y,rows,cols,neighbors):
'''Adding neighbors for the given cell'''
curr_key=(x,y)
list_of_neighbors=[]
if (y<cols-1):
if grid[x][y+1]!='1':
list_of_neighbors.append((x,y+1))
if (x<rows-1):
if grid[x+1][y]!='1':
list_of_neighbors.append((x+1, y))
if(y>0):
if grid[x][y-1]!='1':
list_of_neighbors.append((x,y-1))
if (x>0) :
if grid[x-1][y]!='1':
list_of_neighbors.append((x-1,y))
copy=[]
for neighbor in list_of_neighbors:
if curr_key in neighbors:
neighbors.setdefault(curr_key,[]).append(neighbor)
else:
neighbors[curr_key]=[neighbor]
copy.extend(neighbors[curr_key])
def draw_filled_rect(x,y,color):
'''Drawing cell using turtle'''
pass
# t.up()
#
# t.goto(y*cellWidth-400,-x*cellHeight+400)
# t.down()
# t.begin_fill()
# t.fillcolor(color)
# for i in range(4):
# t.forward(cellWidth)
# t.left(90)
# t.end_fill()
# t.up()
if __name__=="__main__":
main(rows,cols,heuristic,f,g,visited_list,to_be_explored_list,neighbors,path_dict,t,n,start,states_traversed,depth)