-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearchAI.py
More file actions
178 lines (132 loc) · 5.33 KB
/
searchAI.py
File metadata and controls
178 lines (132 loc) · 5.33 KB
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
from collections import deque
import heapq
MAX_DEPTH = 30
class Node:
"""
A class representing a node in the search tree.
Attributes:
state (tuple): The current state that the represented be the node.
parent (Node): The parent node (from which this node was expanded).
action (str): The action taken to reach this node.
path_cost (int): The cost of the path from the root node to this node.
"""
def __init__(self, state, parent=None, action=None, path_cost=0):
self.state = state
self.parent = parent
self.action = action
self.path_cost = path_cost
def expand(self, problem):
"""
Expands the current node into its child nodes by applying all possible actions.
"""
children = []
for action in problem.actions:
new_state, moved_num = problem.transition_model(self.state, action)
if new_state != self.state:
cost = self.path_cost + problem.action_cost(action)
children.append(Node(new_state, parent = self, action = moved_num, path_cost = cost))
return children
def __str__(self): # for debugging
action = self.action or "init"
return f"{action} {self.state}"
def __lt__(self, other):
# used by the heap when 2 node have the same heuristic value
return self.state < other.state
def get_path(self):
"""
Traces back path in the search tree from node to the initial node
by following parent nodes.
"""
path = []
node = self
while node.parent is not None:
path.insert(0, node.action)
node = node.parent
return ' -> '.join(map(str, path))
"""
Traces back path in the search tree from node to the initial node
by following parent nodes.
"""
def is_in_cycle(self):
node = self.parent
while node is not None:
if node.state == self.state:
return True
node = node.parent
return False
# ---------------------------------------------------------------
"""
=================================================================
Un-Informed Search
=================================================================
"""
def bfs(problem):
node, count = Node(problem.initial), 0
queue = deque([node])
reached = {node.state}
if problem.is_goal(node.state):
return node, count
while queue:
node = queue.popleft() # pop in FIFO order
count += 1
for child in node.expand(problem):
if problem.is_goal(child.state):
return child, count
if child.state not in reached:
reached.add(child.state)
queue.append(child)
return None, count
# ---------------------------------------------------------------
def iddfs(problem):
node, count = None, 0
depth = 0
while depth < MAX_DEPTH:
node, curr_count = depth_limited_search(problem, depth)
count += curr_count
if node is not None: #found solution
break
depth += 1
return node, count
def depth_limited_search(problem, limit_depth):
stack = deque([(Node(problem.initial), 0)]) # each entry is (node, depth)
count = 0
while stack:
node, depth = stack.pop() # pop from the head of the stack (LIFO)
if problem.is_goal(node.state):
return node, count
if depth < limit_depth and not node.is_in_cycle():
count += 1
for child in node.expand(problem):
stack.append((child, depth + 1))
return None, count
"""
=================================================================
Informed Search
=================================================================
"""
def best_search_first(problem, evaluation_func):
node = Node(problem.initial)
priority_queue = [ (evaluation_func(node), node) ]
reached = {node.state: 0} # dictionary of (k = state : v = path cost)
count = 0
while priority_queue:
_,node = heapq.heappop(priority_queue) # pop the node with the smallest evaluation
if problem.is_goal(node.state):
return node, count
count += 1
for child in node.expand(problem):
# if child is state that hasn't reached yet, or we found better path
if child.state not in reached or child.path_cost < reached[child.state]:
reached[child.state] = child.path_cost
heapq.heappush(priority_queue, (evaluation_func(node), child))
return None, count
# ---------------------------------------------------------------
def gbfs(problem, heuristic):
return best_search_first(problem, heuristic)
# ---------------------------------------------------------------
def a_star(problem, heuristic):
# inner function to evaluate A*'s f(n) = g(n) + h(n)
def evaluate_a_star(node):
return node.path_cost + heuristic(node)
return best_search_first(problem, evaluate_a_star)
# ---------------------------------------------------------------