-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.py
404 lines (339 loc) · 14.6 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
# 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
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
#####################################################
#####################################################
# Please enter the number of hours you spent on this
# assignment here
"""
num_hours_i_spent_on_this_assignment = 25-30
It would have been less if I had more experience with Python, the challenge for me was to use Python in a complex manner.
Though this won't be an issue for further assignments.
"""
#
#####################################################
#####################################################
#####################################################
#####################################################
# Give one short piece of feedback about the course so far. What
# have you found most interesting? Is there a topic that you had trouble
# understanding? Are there any changes that could improve the value of the
# course to you? (We will anonymize these before reading them.)
"""
The course theory is way easier than the assignments. I understood well about the concepts, yet it was super had to implement it in the assignment
It was fun though doing this assignment, took me about a 5 days of work (5 hours a day atleast). If more about the implementation is taught,
the class discusses only theory. I was blank while doing the assignment. I had to spend hours skimming through the book for helpful facts.
"""
#####################################################
#####################################################
"""
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 [s, s, w, s, w, w, s, w]
def depthFirstSearch(problem):
"""
Q1.1
Search the deepest nodes in the search tree first.
Your search algorithm needs to return a list of actions that reaches the
goal. Make sure to implement a graph search algorithm.
To get started, you might want to try some of these simple commands to
understand the search problem that is being passed in:
print ( problem.getStartState() )
You will get (5,5)
print (problem.isGoalState(problem.getStartState()) )
You will get True
print ( problem.getSuccessors(problem.getStartState()) )
You will get [((x1,y1),'South',1),((x2,y2),'West',1)]
"""
"*** YOUR CODE HERE ***"
"""First we make sure that the start state is not same as the goal state """
if problem.isGoalState(problem.getStartState()):
return []
"""As we need LIFO for DFS"""
from util import Stack
""""Now I have to initialize frontier with the initial state of the problem, according to fig 3.7"""
Frontier = Stack()
"""Now I push the valid start state"""
Frontier.push((problem.getStartState(),[]))
"""initializing empty explored set"""
statePath=[]
stateVisited=[]
while(True):
"""return failure if Frontier is empty """
if Frontier.isEmpty():
return []
"""choose a leaf node and remove it from Frontier"""
xy,statePath = Frontier.pop()
""" if it is the goal state, return it"""
if problem.isGoalState(xy):
return statePath
"""Add the node to the explored set"""
stateVisited.append(xy)
"""expand the chosen node """
succecorPath = problem.getSuccessors(xy)
"""print ( problem.getSuccessors(xy)), test for successor """
if succecorPath:
for paths in succecorPath:
"""Adding resulting nodes in Frontier only if not in frontier or explored set """
if paths[0] not in stateVisited :
newPath = statePath + [paths[1]]
"""
print(paths[0])
print(paths[1])
print(newPath) """
Frontier.push((paths[0],newPath))
def breadthFirstSearch(problem):
"""
Q1.2
Search the shallowest nodes in the search tree first."""
"*** YOUR CODE HERE ***"
"""The code is same as Depth First search, but we use Queue instead of Stack """
if problem.isGoalState(problem.getStartState()):
return []
"""As we need FIFO for DFS"""
from util import Queue
""""Now I have to initialize frontier with the initial state of the problem, according to fig 3.7"""
Frontier = Queue()
"""Now I push the valid start state"""
Frontier.push((problem.getStartState(),[]))
"""initializing empty explored set"""
statePath=[]
stateVisited=[]
while(True):
"""return failure if Frontier is empty """
if Frontier.isEmpty():
return []
"""choose a leaf node and remove it from Frontier"""
xy,statePath = Frontier.pop()
""" if it is the goal state, return it"""
if problem.isGoalState(xy):
return statePath
"""Add the node to the explored set"""
stateVisited.append(xy)
"""expand the chosen node """
succecorPath = problem.getSuccessors(xy)
"""print ( problem.getSuccessors(xy)), test for successor """
if succecorPath:
for paths in succecorPath:
"""Adding resulting nodes in Frontier only if not in frontier or explored set """
if paths[0] not in stateVisited and paths[0] not in (state[0] for state in Frontier.list):
"""A condtion is added in the above if, we had to check all the nodes where we have been (states) """
newPath = statePath + [paths[1]]
"""
print(paths[0])
print(paths[1])
print(newPath) """
Frontier.push((paths[0],newPath))
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):
"""
Q1.3
Search the node that has the lowest combined cost and heuristic first."""
"""Call heuristic(s,problem) to get h(s) value."""
"*** YOUR CODE HERE ***"
if problem.isGoalState(problem.getStartState()):
return []
"""As we need LIFO for DFS"""
from util import PriorityQueue
""" Initiliazing state of the problem"""
Frontier = PriorityQueue()
"""Pushing valid start state (this time we also have to consider priorities """
Frontier.push(problem.getStartState(),0)
"""Initializing empty explored set """
statePath=[]
stateVisited = []
tempPath=[]
""" Choosing a leaf node to remove it from Frontier"""
xy = Frontier.pop()
"""Initilaizing one more priority Queue for the path to our current """
pathCurrent=PriorityQueue()
"""Running the loop until we are not in goal state """
while not problem.isGoalState(xy):
"""Not a previosly visited node """
if xy not in stateVisited:
stateVisited.append(xy)
"""Getting Successors """
successorPath = problem.getSuccessors(xy)
"""This is where a major change occurs comapred to other two searches, so to clearly illustrate i used them individually instead of 'paths' """
for coordinate,direction,cost in successorPath:
newPath = statePath + [direction]
""" Getting cost of path with state in hand"""
costOfPath = problem.getCostOfActions(newPath) + heuristic(coordinate,problem)
"""
print(costOfPath)"""
if coordinate not in stateVisited:
"""
print(direction)
print(coordinate)
"""
Frontier.push(coordinate,costOfPath)
pathCurrent.push(newPath,costOfPath)
xy = Frontier.pop()
statePath = pathCurrent.pop()
return statePath
def priorityQueueDepthFirstSearch(problem):
"""
Q1.4a.
Reimplement DFS using a priority queue.
"""
"*** YOUR CODE HERE ***"
if problem.isGoalState(problem.getStartState()):
return []
"""As we need LIFO for DFS"""
from util import PriorityQueue
""""Now I have to initialize frontier with the initial state of the problem, according to fig 3.7"""
Frontier = PriorityQueue()
"""Now I push the valid start state"""
Frontier.push((problem.getStartState(),[]),0)
"""initializing empty explored set"""
statePath=[]
stateVisited=[]
i=10000
while(True):
"""return failure if Frontier is empty """
if Frontier.isEmpty():
return []
"""choose a leaf node and remove it from Frontier"""
xy,statePath = Frontier.pop()
""" if it is the goal state, return it"""
if problem.isGoalState(xy):
return statePath
"""Add the node to the explored set"""
stateVisited.append(xy)
"""expand the chosen node """
succecorPath = problem.getSuccessors(xy)
"""Special thanks to Piaza discussions """
succecorPath.reverse()
i=i-1
"""print ( problem.getSuccessors(xy)), test for successor """
if succecorPath:
for paths in succecorPath:
"""Adding resulting nodes in Frontier only if not in frontier or explored set """
if paths[0] not in stateVisited :
newPath = statePath + [paths[1]]
"""
print(paths[0])
print(paths[1])
print(newPath) """
Frontier.push((paths[0],newPath),i)
def priorityQueueBreadthFirstSearch(problem):
"""
Q1.4b.
Reimplement BFS using a priority queue.
"""
"*** YOUR CODE HERE ***"
if problem.isGoalState(problem.getStartState()):
return []
"""As we need LIFO for DFS"""
from util import PriorityQueue
""""Now I have to initialize frontier with the initial state of the problem, according to fig 3.7"""
Frontier = PriorityQueue()
"""Now I push the valid start state"""
Frontier.push((problem.getStartState(),[]),0)
"""initializing empty explored set"""
statePath=[]
stateVisited=[]
while(True):
"""return failure if Frontier is empty """
if Frontier.isEmpty():
return []
"""choose a leaf node and remove it from Frontier"""
xy,statePath = Frontier.pop()
""" if it is the goal state, return it"""
if problem.isGoalState(xy):
return statePath
"""Add the node to the explored set"""
stateVisited.append(xy)
"""expand the chosen node """
succecorPath = problem.getSuccessors(xy)
i=-1
"""print ( problem.getSuccessors(xy)), test for successor """
if succecorPath:
for paths in succecorPath:
"""Adding resulting nodes in Frontier only if not in frontier or explored set """
if paths[0] not in stateVisited :
newPath = statePath + [paths[1]]
"""
print(paths[0])
print(paths[1])
print(newPath) """
Frontier.push((paths[0],newPath),i)
i=i-1
#####################################################
#####################################################
# Discuss the results of comparing the priority-queue
# based implementations of BFS and DFS with your original
# implementations.
"""
for BFS
mediumMazeNode expanded are a little more with priority-queue
bigMazeNode expanded are a little less
for DFS it's same
This concludes that nodes expanded are same for DFS, but when we do BFS nodes are expanded differently in both cases.
Maybe this was the result was of the functioning.As queue works in FIFO and priority queue assign weight to nodes thus a different order for inseertion and extraction.
"""
#####################################################
#####################################################
# Abbreviations (please DO NOT change these.)
bfs = breadthFirstSearch
dfs = depthFirstSearch
astar = aStarSearch
bfs2 = priorityQueueBreadthFirstSearch
dfs2 = priorityQueueDepthFirstSearch