forked from AIProjectWork/PackmanSearch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.py
498 lines (396 loc) · 16.1 KB
/
search.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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
# search.py
# ---------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# ([email protected]) and Dan Klein ([email protected]).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel ([email protected]).
"""
In search.py, you will implement generic search algorithms which are called by
Pacman agents (in searchAgents.py).
"""
import util
class SearchProblem:
"""
This class outlines the structure of a search problem, but doesn't implement
any of the methods (in object-oriented terminology: an abstract class).
You do not need to change anything in this class, ever.
"""
def getStartState(self):
"""
Returns the start state for the search problem.
"""
util.raiseNotDefined()
def isGoalState(self, state):
"""
state: Search state
Returns True if and only if the state is a valid goal state.
"""
util.raiseNotDefined()
def getSuccessors(self, state):
"""
state: Search state
For a given state, this should return a list of triples, (successor,
action, stepCost), where 'successor' is a successor to the current
state, 'action' is the action required to get there, and 'stepCost' is
the incremental cost of expanding to that successor.
"""
util.raiseNotDefined()
def getCostOfActions(self, actions):
"""
actions: A list of actions to take
This method returns the total cost of a particular sequence of actions.
The sequence must be composed of legal moves.
"""
util.raiseNotDefined()
def tinyMazeSearch(problem):
"""
Returns a sequence of moves that solves tinyMaze. For any other maze, the
sequence of moves will be incorrect, so only use this for tinyMaze.
"""
from game import Directions
s = Directions.SOUTH
w = Directions.WEST
return ["South", s, w, s, w, w, s, w]
"""
****** Depth First Search (DFS)
"""
result_success = "Success"
result_fail = "failed"
def depthFirstSearch(problem):
"""
Search the deepest nodes in the search tree first.
"""
# this will hold all the nodes we need to visit. It follows Last In First Out.
# so whatever node is inserted last, will be picked first to explore.
stack = util.Stack()
# visited list is a list of all visited node.
# In graph, it is possible that same node is connected by multiple branches. This may cause cyclic path.
# To avoid cyclic path of graph, we will check if node is never visited before inserting into the stack
visited = []
# Prepare first node.
# A DfsNode contains
# state (position in terms of X,Y)
# action (direction that requires to reach this node from previous)
starting_state = problem.getStartState() # initial X,Y position
starting_node = DfsNode(starting_state) # starting node with initial position. Action is None for this
result = dfs_explore(problem, stack, starting_node, visited) # starts exploring from start node
if result == result_success: # when goal is found at some depth
return directions_from_stack(stack) # returns list of direction from stack
elif result == result_fail: # when goal is not found after exploring entire graph
print "No solution found"
def dfs_explore(problem, stack, dfs_node, visited):
"""
This function will explore the given dfs_node
if dfs_node is the goal, then it will return result_success
else it will call recursive dfs_explore function for all of it's successor to find goal
:param problem: problem object
:param stack: main stack used to store nodes
:param dfs_node: current node to explore
:param visited: list of visited states
:return: result_success if current node or it's Descendant is goal
result_fail otherwise
"""
# mark current state as visited
visited.append(dfs_node.get_state())
# add node to the stack
stack.push(dfs_node)
# check if current state is goal
if problem.isGoalState(dfs_node.get_state()):
return result_success # return result_success if current node is goal
# if current node is not the goal, go for it's successors' exploration
successors = problem.getSuccessors(dfs_node.get_state())
for successor_state, successor_action, successor_cost in successors:
if successor_state not in visited:
# recursive call for successor
result = dfs_explore(problem, stack, DfsNode(successor_state, successor_action), visited)
if result == result_success:
return result_success
# if no descendant is goal, pop out the item from stack and return result_fail
stack.pop()
return result_fail
def directions_from_stack(stack):
"""
Program expects a list of actions that leads to the goal
For DFS, it can be derived from stack.
This function will prepare list of directions from the nodes of stack
:param stack: it is a stack of nodes [{state:((1,2), action:None},{state:((1,3), action:North},{state:((2,3),
action:East}]
:return: list of directions [North, East]
"""
directions = []
for dfs_node in stack.list:
if dfs_node.get_action() is not None:
directions.append(dfs_node.get_action())
return directions
class DfsNode:
"""
This is a node structure used for DFS problem. It contains state and action to reach that state.
"""
def __init__(self, state, action=None):
self.state = state
self.action = action
def get_state(self):
return self.state
def get_action(self):
return self.action
"""
*** Breadth First Search (BFS)
"""
def breadthFirstSearch(problem):
"""Search the shallowest nodes in the search tree first."""
queue = util.Queue()
visited = []
goal_node = None
path = None
# add starting Node as the first node of queue
visited.append(problem.getStartState())
queue.push(BfsNode(problem.getStartState()))
while not queue.isEmpty():
result = bfs_explore(problem, queue, visited)
if result is not None:
goal_node = result
break
if goal_node is not None:
# goal node found successfully.
path = directions_using_bfs_goal_node(goal_node)
else:
print "No solution found"
return path
def bfs_explore(problem, queue, visited):
# make first queue node as current one to explore it
current_node = queue.pop()
# check if current node is the goal node
if problem.isGoalState(current_node.get_state()):
return current_node
else:
# else add all unexplored successor nodes into the queue
# fetch all successors
successors = problem.getSuccessors(current_node.get_state())
for successor_state, successor_action, successor_cost in successors:
if successor_state not in visited:
visited.append(successor_state)
successor_node = BfsNode(successor_state, successor_action, current_node)
# todo: discuss pros and cons of commented code
# if problem.isGoalState(successor_node.get_state()):
# return successor_node
queue.push(successor_node)
return None
def directions_using_bfs_goal_node(goal_node):
directions = []
current_node = goal_node
while current_node.get_action() is not None:
directions.insert(0, current_node.get_action())
current_node = current_node.get_parent_node()
return directions
class BfsNode:
def __init__(self, state, action=None, parent_node=None):
self.state = state
self.action = action
self.parent_node = parent_node
def get_parent_node(self):
return self.parent_node
def get_state(self):
return self.state
def get_action(self):
return self.action
"""
*** Uniform Cost Search
"""
def uniformCostSearch(problem):
"""Search the node of least total cost first."""
queue = util.PriorityQueue()
# list of positions which are already
visited = []
# goal node with it's parent node in it. Required to get path.
goal_node = None
# list of directions which lead to the goal
path = None
# add starting Node as the first node of queue and mark it visited
visited.append([problem.getStartState(), 0])
queue.push(UcsNode(problem.getStartState()), 0)
# we need to go through the entire graph
while not queue.isEmpty():
# if it finds result not none, that is our final goal, it goes out of loop
result = ucsExplore(problem, queue, visited)
if result is not None:
goal_node = result
break
if goal_node is not None:
# goal node found successfully.
path = directions_using_ucs_goal_node(goal_node)
else:
print "No solution found"
return path
def ucsExplore(problem, queue, visited):
# make first queue node as current one to explore it
current_node = queue.pop()
# check if current node is the goal node
if problem.isGoalState(current_node.get_state()):
return current_node
else:
# else add all unexplored successor nodes into the queue
# fetch all successors
successors = problem.getSuccessors(current_node.get_state())
for successor_state, successor_action, successor_cost in successors:
successor_node = UcsNode(successor_state, successor_action, current_node, successor_cost)
if is_an_acceptable_ucs_node(successor_node, visited):
visited.append([successor_state, successor_node.get_cost_till_here()])
queue.push(successor_node, successor_node.get_cost_till_here())
return None
def is_an_acceptable_ucs_node(ucs_node, visited):
"""
For ucs, in two conditions a node can be acceptable
1. It is not yet visited
2. It has lower cost than earlier visit
:param ucs_node: node with position
:param visited: list of all visited nodes
:return: true if node can be added to the queue, false otherwise
"""
for visited_state, visited_cost in visited:
if ucs_node.get_state() == visited_state:
return visited_cost > ucs_node.get_cost_till_here()
return True
def directions_using_ucs_goal_node(goal_node):
"""
ucs node contains parent node. so by tracking up until starting node is reached we can find the path
:param goal_node: final node
:return: list of directions which can lead from starting position to goal position
"""
directions = []
current_node = goal_node
while current_node.get_action() is not None:
directions.insert(0, current_node.get_action())
current_node = current_node.get_parent_node()
return directions
class UcsNode:
"""
Required node structure for UCS algo
"""
def __init__(self, state, action=None, parent_node=None, cost=0):
self.state = state
self.action = action
self.parent_node = parent_node
self.cost = cost
if parent_node is not None:
self.cost_till_here = parent_node.cost_till_here + cost
else:
self.cost_till_here = cost
def get_parent_node(self):
return self.parent_node
def get_action(self):
return self.action
def get_state(self):
return self.state
def get_cost_till_here(self):
return self.cost_till_here
"""
*** A-Star
"""
def nullHeuristic(state, problem=None):
"""
A heuristic function estimates the cost from the current state to the nearest
goal in the provided SearchProblem. This heuristic is trivial.
"""
return 0
def aStarSearch(problem, heuristic=nullHeuristic):
"""Search the node that has the lowest combined cost and heuristic first."""
queue = util.PriorityQueue()
visited = []
goal_node = None
path = None
# add starting Node as the first node of queue and mark it as visited
starting_node = AStarNode(problem.getStartState(), None, None, 0, heuristic(problem.getStartState(), problem))
visited.append([starting_node.get_state(), starting_node.get_cost_till_here()])
queue.push(starting_node, starting_node.get_total_predicted_cost())
# look for answer until queue is empty
while not queue.isEmpty():
# if it finds result not none, that is our final goal, it goes out of loop
result = a_star_explore(problem, queue, visited, heuristic)
if result is not None:
goal_node = result
break
if goal_node is not None:
# goal node found successfully.
path = directions_using_ucs_goal_node(goal_node)
else:
print "No solution found"
return path
def a_star_explore(problem, queue, visited, heuristic):
# make first queue node as current one to explore it
current_node = queue.pop()
# check if current node is the goal node
if problem.isGoalState(current_node.get_state()):
return current_node
else:
# else add all unexplored successor nodes into the queue
# fetch all successors
successors = problem.getSuccessors(current_node.get_state())
for successor_state, successor_action, successor_cost in successors:
heuristic_value = heuristic(successor_state, problem)
successor_node = AStarNode(successor_state, successor_action,
current_node, successor_cost, heuristic_value)
if is_an_acceptable_a_star_node(successor_node, visited):
visited.append([successor_node.get_state(), successor_node.get_cost_till_here()])
queue.push(successor_node, successor_node.get_total_predicted_cost())
return None
def directions_using_astar_goal_node(goal_node):
"""
astar node contains parent node. so by tracking up until starting node is reached we can find the path
:param goal_node: final node
:return: list of directions which can lead from starting position to goal position
"""
directions = []
current_node = goal_node
while current_node.get_action() is not None:
directions.insert(0, current_node.get_action())
current_node = current_node.get_parent_node()
return directions
def is_an_acceptable_a_star_node(a_star_node, visited):
"""
For two cases, a node can be acceptable
1. It is not yet visited
2. It's cost till here is less than the recorded visit
:param a_star_node:
:param visited:
:return: true if the node is acceptable or false otherwise
"""
for visited_state, visited_cost in visited:
if a_star_node.get_state() == visited_state:
return visited_cost > a_star_node.get_cost_till_here()
return True
class AStarNode:
"""
Node structure required for A* algo
"""
def __init__(self, state, action=None, parent_node=None, cost=0, heuristic_cost=0):
self.state = state
self.action = action
self.parent_node = parent_node
self.cost = cost
if parent_node is not None:
self.cost_till_here = parent_node.cost_till_here + cost
else:
self.cost_till_here = cost
self.total_predicted_cost = self.cost_till_here + heuristic_cost
def get_parent_node(self):
return self.parent_node
def get_action(self):
return self.action
def get_state(self):
return self.state
def get_cost_till_here(self):
return self.cost_till_here
def get_total_predicted_cost(self):
return self.total_predicted_cost
# =====================================================================================================================#
# Abbreviations
bfs = breadthFirstSearch
dfs = depthFirstSearch
astar = aStarSearch
ucs = uniformCostSearch