-
Notifications
You must be signed in to change notification settings - Fork 1
/
search.py
370 lines (295 loc) · 12.2 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
import util
import heapq
# def astar_search(problem, heuristic=None):
# """
# A* search algorithm.
#
# Args:
# problem: An instance of a search problem.
# heuristic: A heuristic function that estimates the cost to reach the goal from a given state (optional).
#
# Returns:
# A list of actions that lead to the goal state, or None if no solution is found.
# """
# frontier = [(problem.getStartState(), [], 0)] # Priority queue: (state, actions, cost)
# explored = set()
#
# while frontier:
# state, actions, cost = frontier.pop(0)
#
# if state in explored:
# continue
#
# if problem.isGoalState(state):
# return actions
#
# explored.add(state)
#
# for successor, action, step_cost in problem.getSuccessors(state):
# if successor not in explored:
# priority = cost + step_cost
# if heuristic:
# priority += heuristic(successor, problem)
# frontier.append((successor, actions + [action], cost + step_cost))
# frontier.sort(key=lambda x: x[2] + heuristic(x[0], problem))
#
# return None # No solution found
# def astar_search(problem, heuristic=None):
# frontier = util.PriorityQueue()
# explored = set()
#
# start_state = problem.getStartState()
# start_node = (start_state, [], 0)
#
# frontier.push(start_node, 0)
#
# while not frontier.isEmpty():
# state, actions, cost = frontier.pop()
#
# if state in explored:
# continue
#
# if problem.isGoalState(state):
# return actions
#
# explored.add(state)
#
# for successor, action, step_cost in problem.getSuccessors(state):
# if successor not in explored:
# new_cost = cost + step_cost
# if heuristic:
# priority = new_cost + heuristic(successor, problem)
# else:
# priority = new_cost
# frontier.push((successor, actions + [action], new_cost), priority)
#
# return None
def astar_search(problem, heuristic=None):
frontier = util.PriorityQueue()
explored = set()
start_state = problem.getStartState()
start_node = (start_state, [], 0)
frontier.push(start_node, 0)
while not frontier.isEmpty():
state, actions, cost = frontier.pop()
if problem.isGoalState(state):
return actions
if state not in explored:
explored.add(state)
for successor, action, step_cost in problem.getSuccessors(state):
new_cost = cost + step_cost
if successor not in explored:
if heuristic:
priority = new_cost + heuristic(successor, problem)
else:
priority = new_cost
frontier.push((successor, actions + [action], new_cost), priority)
# Example usage:
# path = astar_search(problem, heuristic=h1)
class SearchProblem:
def getStartState(self):
util.raiseNotDefined()
def isGoalState(self, 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):
util.raiseNotDefined()
def tinyMazeSearch(problem):
from game import Directions
s = Directions.SOUTH
w = Directions.WEST
return [s, s, w, s, w, w, s, w]
# def depthFirstSearch(problem):
#
# #states to be explored (LIFO). holds nodes in form (state, action)
# frontier = util.Stack()
# #previously explored states (for path checking), holds states
# exploredNodes = []
# #define start node
# startState = problem.getStartState()
# startNode = (startState, [])
#
# frontier.push(startNode)
#
# while not frontier.isEmpty():
# #begin exploring last (most-recently-pushed) node on frontier
# currentState, actions = frontier.pop()
#
# if currentState not in exploredNodes:
# #mark current node as explored
# exploredNodes.append(currentState)
################Debugging, DFS TOO SLOW################
# def depthFirstSearch(problem):
# #states to be explored (LIFO). holds nodes in form (state, action)
# frontier = util.Stack()
# #previously explored states (for path checking), holds states
# exploredNodes = set() # Change this line
# #define start node
# startState = problem.getStartState()
# startNode = (startState, [])
#
# frontier.push(startNode)
#
# while not frontier.isEmpty():
# #begin exploring last (most-recently-pushed) node on frontier
# currentState, actions = frontier.pop()
#
# if currentState not in exploredNodes:
# #mark current node as explored
# exploredNodes.add(currentState) # And this line
#
# if problem.isGoalState(currentState):
# return actions
# else:
# #get list of possible successor nodes in
# #form (successor, action, stepCost)
# successors = problem.getSuccessors(currentState)
#
# #push each successor to frontier
# for succState, succAction, succCost in successors:
# newAction = actions + [succAction]
# newNode = (succState, newAction)
# frontier.push(newNode)
#
# return actions
########################################Changed the DFS code to this, we limited it because it takes a long time#############################################
def depthFirstSearch(problem, limit=10000):
frontier = util.Stack()
exploredNodes = set()
startState = problem.getStartState()
startNode = (startState, [], 0) # Add depth information
frontier.push(startNode)
while not frontier.isEmpty():
currentState, actions, depth = frontier.pop() # Get depth information
if currentState not in exploredNodes and depth <= limit: # Check the depth
exploredNodes.add(currentState)
if problem.isGoalState(currentState):
return actions
else:
successors = problem.getSuccessors(currentState)
for succState, succAction, succCost in successors:
newAction = actions + [succAction]
newNode = (succState, newAction, depth + 1) # Increase the depth
frontier.push(newNode)
return actions
# def breadthFirstSearch(problem):
#
# #to be explored (FIFO)
# frontier = util.Queue()
#
# #previously expanded states (for cycle checking), holds states
# exploredNodes = []
#
# startState = problem.getStartState()
# startNode = (startState, [], 0) #(state, action, cost)
#
# frontier.push(startNode)
#
# while not frontier.isEmpty():
# #begin exploring first (earliest-pushed) node on frontier
# currentState, actions, currentCost = frontier.pop()
#
# if currentState not in exploredNodes:
# #put popped node state into explored list
# exploredNodes.append(currentState)
#Debugging, BFS TOO SLOW
def breadthFirstSearch(problem):
frontier = util.Queue()
#previously expanded states (for cycle checking), holds states
exploredNodes = set() # Change this line
startState = problem.getStartState()
startNode = (startState, [], 0) #(state, action, cost)
frontier.push(startNode)
while not frontier.isEmpty():
#begin exploring first (earliest-pushed) node on frontier
currentState, actions, currentCost = frontier.pop()
if currentState not in exploredNodes:
#put popped node state into explored list
exploredNodes.add(currentState) # And this line
# ... rest of your code ...
if problem.isGoalState(currentState):
return actions
else:
#list of (successor, action, stepCost)
successors = problem.getSuccessors(currentState)
for succState, succAction, succCost in successors:
newAction = actions + [succAction]
newCost = currentCost + succCost
newNode = (succState, newAction, newCost)
frontier.push(newNode)
return actions
def uniformCostSearch(problem):
#to be explored (FIFO): holds (item, cost)
frontier = util.PriorityQueue()
#previously expanded states (for cycle checking), holds state:cost
exploredNodes = {}
startState = problem.getStartState()
startNode = (startState, [], 0) #(state, action, cost)
frontier.push(startNode, 0)
while not frontier.isEmpty():
#begin exploring first (lowest-cost) node on frontier
currentState, actions, currentCost = frontier.pop()
if (currentState not in exploredNodes) or (currentCost < exploredNodes[currentState]):
#put popped node's state into explored list
exploredNodes[currentState] = currentCost
if problem.isGoalState(currentState):
return actions
else:
#list of (successor, action, stepCost)
successors = problem.getSuccessors(currentState)
for succState, succAction, succCost in successors:
newAction = actions + [succAction]
newCost = currentCost + succCost
newNode = (succState, newAction, newCost)
frontier.update(newNode, newCost)
return actions
def nullHeuristic(state, problem=None):
return 0
def aStarSearch(problem, heuristic=nullHeuristic):
#to be explored (FIFO): takes in item, cost+heuristic
frontier = util.PriorityQueue()
exploredNodes = [] #holds (state, cost)
startState = problem.getStartState()
startNode = (startState, [], 0) #(state, action, cost)
frontier.push(startNode, 0)
while not frontier.isEmpty():
#begin exploring first (lowest-combined (cost+heuristic) ) node on frontier
currentState, actions, currentCost = frontier.pop()
#put popped node into explored list
currentNode = (currentState, currentCost)
exploredNodes.append((currentState, currentCost))
if problem.isGoalState(currentState):
return actions
else:
#list of (successor, action, stepCost)
successors = problem.getSuccessors(currentState)
#examine each successor
for succState, succAction, succCost in successors:
newAction = actions + [succAction]
newCost = problem.getCostOfActions(newAction)
newNode = (succState, newAction, newCost)
#check if this successor has been explored
already_explored = False
for explored in exploredNodes:
#examine each explored node tuple
exploredState, exploredCost = explored
if (succState == exploredState) and (newCost >= exploredCost):
already_explored = True
#if this successor not explored, put on frontier and explored list
if not already_explored:
frontier.push(newNode, newCost + heuristic(succState, problem))
exploredNodes.append((succState, newCost))
return actions
# Abbreviations
bfs = breadthFirstSearch
dfs = depthFirstSearch
astar = aStarSearch
ucs = uniformCostSearch