-
Notifications
You must be signed in to change notification settings - Fork 0
/
SP21-BCS-009 LAB 5.py
359 lines (309 loc) · 14.4 KB
/
SP21-BCS-009 LAB 5.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
# -*- coding: utf-8 -*-
"""Untitled0.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/18l48wZeWiRZkxVFbxfISNgGVptZtFcub
"""
# hill climbing
import random
import math
class Node:
def __init__(self, state, parent, actions, heuristic, totalCost):
self.state = state
self.parent = parent
self.actions = actions
self.totalCost = totalCost
self.heuristic = heuristic
def hillclimbing(ist, gst):
initialstate = ist
goalstate = gst
# creating two lists
explored = []
solution = []
# graph
graph = {'A': Node('A', None, [('F', 1)], (0, 0), 0),
'B': Node('B', None, [('G', 1), ('C', 1)], (2, 0), 0),
'C': Node('C', None, [('B', 1), ('D', 1)], (3, 0), 0),
'D': Node('D', None, [('C', 1), ('E', 1)], (4, 0), 0),
'E': Node('E', None, [('D', 1)], (5, 0), 0),
'F': Node('F', None, [('A', 1), ('H', 1)], (0, 1), 0),
'G': Node('G', None, [('B', 1), ('J', 1)], (2, 1), 0),
'H': Node('H', None, [('F', 1), ('I', 1), ('M', 1)], (0, 2), 0),
'I': Node('I', None, [('N', 1), ('J', 1), ('H', 1)], (1, 2), 0),
'J': Node('J', None, [('G', 1), ('I', 1)], (2, 2), 0),
'K': Node('K', None, [('L', 1), ('P', 1)], (4, 2), 0),
'L': Node('L', None, [('K', 1), ('Q', 1)], (5, 2), 0),
'M': Node('M', None, [('H', 1), ('N', 1), ('R', 1)], (0, 3), 0),
'N': Node('N', None, [('I', 1), ('M', 1), ('S', 1)], (1, 3), 0),
'O': Node('O', None, [('P', 1), ('U', 1)], (3, 3), 0),
'P': Node('P', None, [('O', 1), ('Q', 1), ('K', 1)], (4, 3), 0),
'Q': Node('Q', None, [('L', 1), ('P', 1), ('V', 1)], (5, 3), 0),
'R': Node('R', None, [('M', 1), ('S', 1)], (0, 4), 0),
'S': Node('S', None, [('N', 1), ('R', 1), ('T', 1)], (1, 4), 0),
'T': Node('T', None, [('S', 1), ('U', 1), ('W', 1)], (2, 4), 0),
'U': Node('U', None, [('O', 1), ('T', 1)], (3, 4), 0),
'V': Node('V', None, [('Q', 1), ('Y', 1)], (5, 4), 0),
'W': Node('W', None, [('T', 1)], (2, 5), 0),
'X': Node('X', None, [('Y', 1)], (4, 5), 0),
'Y': Node('Y', None, [('V', 1)], (5, 5), 0)
}
# defining the parent node
parentnode = initialstate
# calculating the parent's cost
parentcost = math.sqrt(
(graph[goalstate].heuristic[0] - graph[initialstate].heuristic[0])**2
+
(graph[goalstate].heuristic[1] - graph[initialstate].heuristic[1])**2
)
# calculating the cost of the minchild
# not sure why we are subtracting 1
minChildCost = parentcost-1
# now defining the conditions where we go to a node and call it a parent, then we check it's children
# to look for the child with the minimum cost(local maxima).
# we repeat the process until we reach the goal state(global maxima).
# usually this method does not yield the goal state rather it gets stuck on a local maxima.
# for that case we will solve this problem using local beam search
while parentnode != goalstate:
# bestnode is the node with the minimum cost at the moment
bestnode = parentnode
minChildCost = parentcost
# appending the checked node (which will technically be a parentnode) to the explored list
# we are basically referring the current node (that we are present on at the moment) as the parent node
explored.append(parentnode)
# looking for the next node with the minimum cost which we will move towards
# this node will be one of the childrens of the current node(parent node)
for child in graph[parentnode].actions:
# graph[parentnode].actions is referring to the list of children present in the graph dictionary corresponding to the parentnode key
if child[0] not in explored:
# calculating the new cost
childcost = math.sqrt(
(graph[goalstate].heuristic[0] -
graph[child[0]].heuristic[0])**2
+
(graph[goalstate].heuristic[1] -
graph[child[0]].heuristic[1])**2
)
# checking if childcost is lesser than the current minchildcost
if childcost < minChildCost:
bestnode = child[0]
minChildCost = childcost
# checking if the bestnode is equal to the parentnode(its the case where either we have reached the goal state)
# (or are stuck at some local maxima)
if bestnode == parentnode:
break
# if thats not the case then, make the current node as the parent node and move forward
parentnode = bestnode
parentcost = minChildCost
# appending the node to the solution list
solution.append(parentnode)
return solution
# main
solution = hillclimbing('A', 'Y')
print(solution)
# random restart hill climbing
class Node:
def __init__(self, state, parent, actions, totalCost, heuristic):
self.state = state
self.parent = parent
self.actions = actions
self.totalCost = totalCost
self.heuristic = heuristic
graph = {
"A": Node("A", None, [("F", 1)], 0, (0, 0)),
"B": Node("B", None, [("G", 1), ("C", 1)], 0, (2, 0)),
"C": Node("C", None, [("B", 1), ("D", 1)], 0, (3, 0)),
"D": Node("D", None, [("C", 1), ("E", 1)], 0, (4, 0)),
"E": Node("E", None, [("D", 1)], 0, (5, 0)),
"F": Node("F", None, [("A", 1), ("H", 1)], 0, (0, 1)),
"G": Node("G", None, [("B", 1), ("J", 1)], 0, (2, 1)),
"H": Node("H", None, [("F", 1), ("I", 1), ("M", 1)], 0, (0, 2)),
"I": Node("I", None, [("H", 1), ("J", 1), ("N", 1)], 0, (1, 2)),
"J": Node("J", None, [("G", 1), ("I", 1)], 0, (2, 2)),
"K": Node("K", None, [("L", 1), ("P", 1)], 0, (4, 2)),
"L": Node("L", None, [("K", 1), ("Q", 1)], 0, (5, 2)),
"M": Node("M", None, [("H", 1), ("N", 1), ("R", 1)], 0, (0, 3)),
"N": Node("N", None, [("I", 1), ("M", 1), ("S", 1)], 0, (1, 3)),
"O": Node("O", None, [("P", 1), ("U", 1)], 0, (3, 3)),
"P": Node("P", None, [("O", 1), ("Q", 1)], 0, (4, 3)),
"Q": Node("Q", None, [("L", 1), ("P", 1), ("V", 1)], 0, (5, 3)),
"R": Node("R", None, [("M", 1), ("S", 1)], 0, (0, 4)),
"S": Node("S", None, [("N", 1), ("R", 1), ("T", 1)], 0, (1, 4)),
"T": Node("T", None, [("S", 1), ("U", 1), ("W", 1)], 0, (2, 4)),
"U": Node("U", None, [("O", 1), ("T", 1)], 0, (3, 4)),
"V": Node("V", None, [("Q", 1), ("Y", 1)], 0, (5, 4)),
"W": Node("W", None, [("T", 1)], 0, (2, 5)),
"X": Node("X", None, [("Y", 1)], 0, (4, 5)),
"Y": Node("Y", None, [("V", 1), ("X", 1)], 0, (5, 5))
}
def randomRestartHillClimbing(graph, initialState, goalState):
count = 0
while True:
count += 1
parentNode = initialState
parentCost = math.sqrt(((graph[goalState].heuristic[0] - graph[initialState].heuristic[0])**2) + (
(graph[goalState].heuristic[1] - graph[initialState].heuristic[1])**2))
explored = []
solution = []
minChildCost = parentCost - 1
# while loop ends because of this statement
while parentNode != goalState:
bestNode = parentNode
minChildCost = parentCost
explored.append(parentNode)
# checking the children of the current node
# the child with the lowest cost will become the next bestnode
for child in graph[parentNode].actions:
# make sure the control does not go to the previous nodes
if child[0] not in explored:
childCost = math.sqrt(((graph[goalState].heuristic[0] - graph[child[0]].heuristic[0]) ** 2) + (
(graph[goalState].heuristic[1] - graph[child[0]].heuristic[1]) ** 2))
if childCost < minChildCost:
bestNode = child[0]
minChildCost = childCost
# while loop can also break because of this statement
if bestNode == parentNode:
break
else:
parentNode = bestNode
parentCost = minChildCost
solution.append(parentNode)
# converting hill climbing into random restart hill climbing
if len(solution) != 0 and solution[(len(solution) - 1)] == goalState:
# once the goal state has been found the outtermost while(true) loop will end by returning the following values
return initialState, solution, count
# converting the dict keys into a list
values = list(graph.keys())
# removing the goal state from values because initialstate cannot be the same as goalstate
values.remove(goalState)
initialState = random.choice(values)
initialState, solution, count = randomRestartHillClimbing(graph, "A", "Y")
print("Number of tries:", count)
print("Initial State:", initialState)
print(solution)
# local beam search
class Node:
def __init__(self, state, parent, actions, totalCost, heuristic):
self.state = state
self.parent = parent
self.actions = actions
self.totalCost = totalCost
self.heuristic = heuristic
graph = {
"A": Node("A", None, [("F", 1)], 0, (0, 0)),
"B": Node("B", None, [("G", 1), ("C", 1)], 0, (2, 0)),
"C": Node("C", None, [("B", 1), ("D", 1)], 0, (3, 0)),
"D": Node("D", None, [("C", 1), ("E", 1)], 0, (4, 0)),
"E": Node("E", None, [("D", 1)], 0, (5, 0)),
"F": Node("F", None, [("A", 1), ("H", 1)], 0, (0, 1)),
"G": Node("G", None, [("B", 1), ("J", 1)], 0, (2, 1)),
"H": Node("H", None, [("F", 1), ("I", 1), ("M", 1)], 0, (0, 2)),
"I": Node("I", None, [("H", 1), ("J", 1), ("N", 1)], 0, (1, 2)),
"J": Node("J", None, [("G", 1), ("I", 1)], 0, (2, 2)),
"K": Node("K", None, [("L", 1), ("P", 1)], 0, (4, 2)),
"L": Node("L", None, [("K", 1), ("Q", 1)], 0, (5, 2)),
"M": Node("M", None, [("H", 1), ("N", 1), ("R", 1)], 0, (0, 3)),
"N": Node("N", None, [("I", 1), ("M", 1), ("S", 1)], 0, (1, 3)),
"O": Node("O", None, [("P", 1), ("U", 1)], 0, (3, 3)),
"P": Node("P", None, [("O", 1), ("Q", 1)], 0, (4, 3)),
"Q": Node("Q", None, [("L", 1), ("P", 1), ("V", 1)], 0, (5, 3)),
"R": Node("R", None, [("M", 1), ("S", 1)], 0, (0, 4)),
"S": Node("S", None, [("N", 1), ("R", 1), ("T", 1)], 0, (1, 4)),
"T": Node("T", None, [("S", 1), ("U", 1), ("W", 1)], 0, (2, 4)),
"U": Node("U", None, [("O", 1), ("T", 1)], 0, (3, 4)),
"V": Node("V", None, [("Q", 1), ("Y", 1)], 0, (5, 4)),
"W": Node("W", None, [("T", 1)], 0, (2, 5)),
"X": Node("X", None, [("Y", 1)], 0, (4, 5)),
"Y": Node("Y", None, [("V", 1), ("X", 1)], 0, (5, 5))
}
def localBeamSearch(graph, initialState, goalState, beamWidth):
parentNode = initialState
parentCost = math.sqrt(((graph[goalState].heuristic[0] - graph[initialState].heuristic[0])**2) + (
(graph[goalState].heuristic[1] - graph[initialState].heuristic[1])**2))
explored = []
solution = []
minChildCost = parentCost - 1
bestNodes = []
while parentNode != goalState:
print("Parent Node:", parentNode)
bestNode = parentNode
minChildCost = parentCost
explored.append(parentNode)
for child in graph[parentNode].actions:
if child[0] not in explored:
childCost = math.sqrt(((graph[goalState].heuristic[0] - graph[child[0]].heuristic[0]) ** 2) + (
(graph[goalState].heuristic[1] - graph[child[0]].heuristic[1]) ** 2))
bestNodes.append((childCost, child[0]))
if childCost < minChildCost:
bestNode = child[0]
minChildCost = childCost
# sorting the child nodes
bestNodes.sort()
print("Child Nodes:", bestNodes)
bestNodes = bestNodes[:beamWidth]
if bestNode == parentNode:
if len(bestNodes) < 1:
break
elif bestNode == bestNodes[0][1]:
bestNodes.pop(0)
minChildCost, bestNode = bestNodes.pop(0)
last = solution[len(solution) - 2]
for n in graph[last].actions:
if bestNode in n:
solution.pop()
else:
minChildCost, bestNode = bestNodes.pop(0)
parentNode = bestNode
parentCost = minChildCost
solution.append(parentNode)
return solution
solution = localBeamSearch(graph, "A", "Y", 2)
print("Solution:", solution)
# UCS
graph = {
"A": Node("A", None, [("B", 6), ("C", 9), ("E", 1)], 0),
"B": Node("B", None, [("A", 6), ("D", 3), ("E", 4)], 0),
"C": Node("C", None, [("A", 9), ("F", 2), ("G", 3)], 0),
"D": Node("D", None, [("B", 3), ("E", 5), ("F", 7)], 0),
"E": Node("E", None, [("A", 1), ("B", 4), ("D", 5), ("F", 6)], 0),
"F": Node("F", None, [("C", 2), ("E", 6), ("D", 7)], 0),
"G": Node("G", None, [("C", 3)], 0),
}
def findMin(frontier):
minVal = math.inf
node = ""
for i in frontier:
if minVal > frontier[i][1]:
minVal = frontier[i][1]
node = i
return node
def UCS(graph, initialState, goalState):
frontier = dict()
frontier[initialState] = (None, 0)
explored = []
while len(frontier) != 0:
currentNode = findMin(frontier)
del frontier[currentNode]
explored.append(currentNode)
if graph[currentNode].state == goalState:
return actionSequence(graph, goalState)
for child in graph[currentNode].actions:
currentCost = child[1] + graph[currentNode].totalCost
if child[0] not in frontier and child[0] not in explored:
graph[child[0]].parent = currentNode
graph[child[0]].totalCost = currentCost
frontier[child[0]] = (currentNode, currentCost)
elif child[0] in frontier:
if frontier[child[0]][1] > currentCost:
frontier[child[0]] = (currentNode, currentCost)
graph[child[0]].parent = currentNode
graph[child[0]].totalCost = currentCost
def actionSequence(graph, goalState):
solution = [goalState]
currentParent = graph[goalState].parent
while currentParent != None:
solution.append(currentParent)
currentParent = graph[currentParent].parent
solution.reverse()
return solution
solution = UCS(graph, "C", "B")
print(solution)