-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolver.py
351 lines (300 loc) · 12.7 KB
/
solver.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
from search_node import SearchNodes
from puzzle import PuzzleHelper
import sys
from time import time
# Action constants
UP = 'UP'
DOWN = 'DOWN'
LEFT = 'LEFT'
RIGHT = 'RIGHT'
ACTIONS = [UP, DOWN, LEFT, RIGHT]
class Solver:
def heuristic_cost(self, puzzle, heuristic):
"""
Calculates the costs for 8 puzzle state, based on some heuristics
:param puzzle:
:param heuristic:
:return:
"""
cost = 0
if heuristic == 'misplaced':
for i in range(1, 10):
if puzzle[i-1] != i % 9:
cost += 1
elif heuristic == 'manhattan':
for i in range(1, 10):
value = puzzle[i-1]
expected = i % 9
if value != expected:
position = value - 1 if value != 0 else 9
exp_row, exp_col = (position // 3, position % 3)
cur_row, cur_col = ((i - 1) // 3, (i - 1) % 3)
cost += abs(cur_row - exp_row) + abs(cur_col - exp_col)
return cost
def no_information_solver(self, puzzle, mode):
"""
Solves the 8-puzzle, can be used for bfs or dfs
:param puzzle: Array containing 8-puzzle
:param mode: String containing mode (bfs, dfs)
:return:
"""
searches = 0
# Initializes search nodes and inserts first state into Frontier
if PuzzleHelper.check_puzzle_finished(puzzle):
return puzzle, searches, []
search_node = SearchNodes(mode)
search_node.push_frontier(puzzle, None, None)
while search_node.frontier_has_next():
searches += 1
node_puzzle = search_node.pop_frontier()[0]
search_node.push_explored(node_puzzle)
for action in ACTIONS:
child_puzzle = PuzzleHelper.move_puzzle(node_puzzle[:], action)
if child_puzzle is not None \
and not search_node.is_explored(child_puzzle) \
and not search_node.is_in_frontier(child_puzzle):
# If finished, returns solution
if PuzzleHelper.check_puzzle_finished(child_puzzle):
return child_puzzle, searches, search_node.get_solution(node_puzzle, action)
# Else, add to frontier
search_node.push_frontier(child_puzzle, node_puzzle, action)
return None, searches, []
def greedy_solver(self, puzzle, mode):
"""
Solves the 8-puzzle using Greedy Heuristics (passed via mode)
:param puzzle: Array containing the 8-puzzle
:param mode: string containing the heuristic mode
:return:
"""
def expected_cost(current_puzzle, mode):
return self.heuristic_cost(current_puzzle, mode)
searches = 0
if PuzzleHelper.check_puzzle_finished(puzzle):
return puzzle, searches, []
search_node = SearchNodes('greedy_sum')
cost = expected_cost(puzzle, mode)
search_node.push_frontier(puzzle, None, None, cost=cost, depth=0)
while search_node.frontier_has_next():
searches += 1
node_puzzle, parent_depth = search_node.pop_frontier(return_depth=True)
search_node.push_explored(node_puzzle)
if PuzzleHelper.check_puzzle_finished(node_puzzle):
return node_puzzle, searches, search_node.get_solution(node_puzzle, None)
for action in ACTIONS:
child_puzzle = PuzzleHelper.move_puzzle(node_puzzle[:], action)
if child_puzzle is not None \
and not search_node.is_explored(child_puzzle) \
and not search_node.is_in_frontier(child_puzzle):
depth = 1 + parent_depth
cost = depth + expected_cost(child_puzzle, mode)
search_node.push_frontier(child_puzzle, node_puzzle, action, cost=cost, depth=depth)
return None, searches, []
def greedy_sum_of_misplaced(self, puzzle):
"""
Searches a solution for 8 puzzle using sum of misplaced
tiles as a cost (aka 1 misplaced tile, + 1 in sum)
:param puzzle: Array containing the puzzle state
:return:
"""
return self.greedy_solver(puzzle, 'misplaced')
def greedy_sum_manhattan(self, puzzle):
"""
Searches a solution for 8 puzzle using manhattam sum
(sum of distance for each block, with distance being
how many movements are needed to reach desired state)
:param puzzle: Array containing the puzzle state
:return:
"""
return self.greedy_solver(puzzle, 'manhattan')
def bfs(self, puzzle):
"""
Searches a solution for 8 puzzle, using Breadth-First Search
:param puzzle: Array containing the puzzle state
:return:
"""
return self.no_information_solver(puzzle, 'bfs')
def dfs(self, puzzle):
"""
Searches a solution for 8 puzzle, using Depth-First Search
:param puzzle: Array containing the puzzle state
:return:
"""
return self.no_information_solver(puzzle, 'dfs')
def ids(self, puzzle):
"""
Searches multiple depths of a DFS search, looking
for solutions of 8 puzzle
:param puzzle: Array containing the puzzle state
:return:
"""
cumulative_searches = 0
for i in range(0, 32):
solution, searches, movements = self.dls(puzzle, i)
cumulative_searches += searches
if solution is not None:
return solution, cumulative_searches, movements
return None, cumulative_searches, []
def dls(self, puzzle, limit):
return self.dls_recursive(puzzle, limit)
def dls_recursive(self, puzzle, limit):
"""
Recursive Function for searching using DFS with a limited depth.
Used for IDS.
:param puzzle: Array containing the puzzle state
:param limit: maximum depth it can search
:return:
"""
searches = 1
if PuzzleHelper.check_puzzle_finished(puzzle):
return puzzle, searches, ''
elif limit == 0:
return None, searches, ''
else:
cutoff = False
for action in ACTIONS:
child_puzzle = PuzzleHelper.move_puzzle(puzzle[:], action)
if child_puzzle is not None:
result, child_searches, movements = self.dls_recursive(child_puzzle, limit - 1)
searches += child_searches
if result is None:
cutoff = True
else:
movements += action[0]
return result, searches, movements
if cutoff:
return None, 0, []
def ucs(self, puzzle):
"""
Searches a solution for 8 puzzle, using Universal Cost Search
:param puzzle: Array containing the puzzle state
:return:
"""
searches = 0
# Initializes search nodes and inserts first state into Frontier
if PuzzleHelper.check_puzzle_finished(puzzle):
return puzzle, searches, []
search_node = SearchNodes('ucs')
search_node.push_frontier(puzzle, None, None, cost=0)
while search_node.frontier_has_next():
searches += 1
node_puzzle, parent_cost = search_node.pop_frontier(return_cost=True)
search_node.push_explored(node_puzzle)
if PuzzleHelper.check_puzzle_finished(node_puzzle):
return node_puzzle, searches, search_node.get_solution(node_puzzle, None)
for action in ACTIONS:
child_puzzle = PuzzleHelper.move_puzzle(node_puzzle[:], action)
cost = parent_cost + 1
if child_puzzle is not None \
and not search_node.is_explored(child_puzzle) \
and not search_node.is_in_frontier(child_puzzle):
search_node.push_frontier(child_puzzle, node_puzzle, action, cost=cost)
elif child_puzzle is not None and search_node.is_in_frontier(child_puzzle):
search_node.swap_frontier_if_better(child_puzzle, node_puzzle, action, cost, cost)
return None, searches, []
def A_star(self, puzzle, mode):
"""
Searches a solution for 8 puzzle, using A Star algorithm.
:param puzzle: Array containing the puzzle state
:return:
"""
searches = 0
search_node = SearchNodes('astar')
current_cost = self.heuristic_cost(puzzle, mode)
search_node.push_frontier(puzzle, None, None, current_cost, 0)
while search_node.frontier_has_next():
searches += 1
node_puzzle, depth = search_node.pop_frontier(return_depth=True)
if PuzzleHelper.check_puzzle_finished(node_puzzle):
return node_puzzle, searches, search_node.get_solution(node_puzzle, None)
search_node.push_explored(node_puzzle)
for action in ACTIONS:
child_depth = depth + 1
child_puzzle = PuzzleHelper.move_puzzle(node_puzzle[:], action)
if child_puzzle is not None:
if not search_node.is_explored(child_puzzle):
cost = child_depth + self.heuristic_cost(child_puzzle, mode)
if not search_node.is_in_frontier(child_puzzle):
search_node.push_frontier(child_puzzle, node_puzzle, action, cost, child_depth)
else:
search_node.swap_frontier_if_better(child_puzzle, node_puzzle, action, cost, child_depth)
return None, searches, []
def A_star_manhattan(self, puzzle):
"""
Calls A* search with Manhattan Distance Heuristic
:param puzzle: Array containing the puzzle state
:return:
"""
return self.A_star(puzzle, 'manhattan')
def A_star_misplaced(self, puzzle):
"""
Calls A* search with Misplaced Tiles Heuristic
:param puzzle: Array containing the puzzle state
:return:
"""
return self.A_star(puzzle, 'misplaced')
def hill_climb(self, puzzle, k):
"""
Searches for solutions using hill climb, in order to find
local best solutions.
:param puzzle: Array containing the puzzle state
:return:
"""
searches = 0
search_node = SearchNodes('hill')
current_cost = self.heuristic_cost(puzzle, 'manhattan')
search_node.push_frontier(puzzle, None, None, current_cost)
side_move = -1
movements = []
while True:
searches += 1
neighbor, neighbor_cost, neigh_action = search_node.pop_frontier(return_cost=True)
if neigh_action is not None:
movements.append(neigh_action)
if PuzzleHelper.check_puzzle_finished(neighbor):
return neighbor, searches, movements
if neighbor_cost >= current_cost:
side_move += 1
if side_move == k:
break
current_cost = neighbor_cost
for action in ACTIONS:
child_puzzle = PuzzleHelper.move_puzzle(neighbor[:], action)
if child_puzzle is not None:
child_cost = self.heuristic_cost(child_puzzle, 'misplaced')
search_node.push_frontier(child_puzzle, neighbor, action, child_cost)
return None, searches, []
if __name__ == '__main__':
method = sys.argv[1]
puzzle = sys.argv[2].split(' ')
puzzle = [int(x) for x in puzzle]
solver = Solver()
solution = None
start = time()
if method == 'bfs':
solution = solver.bfs(puzzle)
elif method == 'ids':
solution = solver.ids(puzzle)
elif method == 'ucs':
solution = solver.ucs(puzzle)
elif method == 'greedymis':
solution = solver.greedy_sum_of_misplaced(puzzle)
elif method == 'greedyman':
solution = solver.greedy_sum_manhattan(puzzle)
elif method == 'aman':
solution = solver.A_star_manhattan(puzzle)
elif method == 'amis':
solution = solver.A_star_misplaced(puzzle)
elif method == 'hill':
solution = solver.hill_climb(puzzle, 100)
print('METHOD:', method)
if solution[0] is None:
print('ERROR: Could not solve')
print('Expansions:', solution[1])
else:
PuzzleHelper.print_puzzle(solution[0])
print('Expansions:', solution[1])
print('Solution:', solution[2])
print('Solution Size:', len(solution[2]))
print('Took', time() - start, 'seconds')
print('/' * 20)
print()