search.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. """Search (Chapters 3-4)
  2. The way to use this code is to subclass Problem to create a class of problems,
  3. then create problem instances and solve them with calls to the various search
  4. functions."""
  5. from .utils import (
  6. is_in, memoize, print_table, Stack, FIFOQueue, PriorityQueue, name
  7. )
  8. import sys
  9. infinity = float('inf')
  10. # ______________________________________________________________________________
  11. class Problem:
  12. """The abstract class for a formal problem. You should subclass
  13. this and implement the methods actions and result, and possibly
  14. __init__, goal_test, and path_cost. Then you will create instances
  15. of your subclass and solve them with the various search functions."""
  16. def __init__(self, initial, goal=None):
  17. """The constructor specifies the initial state, and possibly a goal
  18. state, if there is a unique goal. Your subclass's constructor can add
  19. other arguments."""
  20. self.initial = initial
  21. self.goal = goal
  22. def actions(self, state):
  23. """Return the actions that can be executed in the given
  24. state. The result would typically be a list, but if there are
  25. many actions, consider yielding them one at a time in an
  26. iterator, rather than building them all at once."""
  27. raise NotImplementedError
  28. def result(self, state, action):
  29. """Return the state that results from executing the given
  30. action in the given state. The action must be one of
  31. self.actions(state)."""
  32. raise NotImplementedError
  33. def goal_test(self, state):
  34. """Return True if the state is a goal. The default method compares the
  35. state to self.goal or checks for state in self.goal if it is a
  36. list, as specified in the constructor. Override this method if
  37. checking against a single self.goal is not enough."""
  38. if isinstance(self.goal, list):
  39. return is_in(state, self.goal)
  40. else:
  41. return state == self.goal
  42. def path_cost(self, c, state1, action, state2):
  43. """Return the cost of a solution path that arrives at state2 from
  44. state1 via action, assuming cost c to get up to state1. If the problem
  45. is such that the path doesn't matter, this function will only look at
  46. state2. If the path does matter, it will consider c and maybe state1
  47. and action. The default method costs 1 for every step in the path."""
  48. return c + 1
  49. def value(self, state):
  50. """For optimization problems, each state has a value. Hill-climbing
  51. and related algorithms try to maximize this value."""
  52. raise NotImplementedError
  53. # ______________________________________________________________________________
  54. class Node:
  55. """A node in a search tree. Contains a pointer to the parent (the node
  56. that this is a successor of) and to the actual state for this node. Note
  57. that if a state is arrived at by two paths, then there are two nodes with
  58. the same state. Also includes the action that got us to this state, and
  59. the total path_cost (also known as g) to reach the node. Other functions
  60. may add an f and h value; see best_first_graph_search and astar_search for
  61. an explanation of how the f and h values are handled. You will not need to
  62. subclass this class."""
  63. def __init__(self, state, parent=None, action=None, path_cost=0):
  64. "Create a search tree Node, derived from a parent by an action."
  65. self.state = state
  66. self.parent = parent
  67. self.action = action
  68. self.path_cost = path_cost
  69. self.depth = 0
  70. if parent:
  71. self.depth = parent.depth + 1
  72. def __repr__(self):
  73. return "<Node %s>" % (self.state,)
  74. def __lt__(self, node):
  75. return self.state < node.state
  76. def expand(self, problem):
  77. "List the nodes reachable in one step from this node."
  78. return [self.child_node(problem, action)
  79. for action in problem.actions(self.state)]
  80. def child_node(self, problem, action):
  81. "[Figure 3.10]"
  82. next = problem.result(self.state, action)
  83. return Node(next, self, action,
  84. problem.path_cost(self.path_cost, self.state,
  85. action, next))
  86. def solution(self):
  87. "Return the sequence of actions to go from the root to this node."
  88. return [node.action for node in self.path()[1:]]
  89. def path(self):
  90. "Return a list of nodes forming the path from the root to this node."
  91. node, path_back = self, []
  92. while node:
  93. path_back.append(node)
  94. node = node.parent
  95. return list(reversed(path_back))
  96. # We want for a queue of nodes in breadth_first_search or
  97. # astar_search to have no duplicated states, so we treat nodes
  98. # with the same state as equal. [Problem: this may not be what you
  99. # want in other contexts.]
  100. def __eq__(self, other):
  101. return isinstance(other, Node) and self.state == other.state
  102. def __hash__(self):
  103. return hash(self.state)
  104. # ______________________________________________________________________________
  105. # Uninformed Search algorithms
  106. def tree_search(problem, frontier):
  107. """Search through the successors of a problem to find a goal.
  108. The argument frontier should be an empty queue.
  109. Don't worry about repeated paths to a state. [Figure 3.7]"""
  110. frontier.append(Node(problem.initial))
  111. while frontier:
  112. node = frontier.pop()
  113. if problem.goal_test(node.state):
  114. return node
  115. frontier.extend(node.expand(problem))
  116. return None
  117. def graph_search(problem, frontier):
  118. """Search through the successors of a problem to find a goal.
  119. The argument frontier should be an empty queue.
  120. If two paths reach a state, only use the first one. [Figure 3.7]"""
  121. frontier.append(Node(problem.initial))
  122. explored = set()
  123. while frontier:
  124. node = frontier.pop()
  125. if problem.goal_test(node.state):
  126. return node
  127. explored.add(node.state)
  128. frontier.extend(child for child in node.expand(problem)
  129. if child.state not in explored and
  130. child not in frontier)
  131. return None
  132. def breadth_first_tree_search(problem):
  133. "Search the shallowest nodes in the search tree first."
  134. return tree_search(problem, FIFOQueue())
  135. def depth_first_tree_search(problem):
  136. "Search the deepest nodes in the search tree first."
  137. return tree_search(problem, Stack())
  138. def depth_first_graph_search(problem):
  139. "Search the deepest nodes in the search tree first."
  140. return graph_search(problem, Stack())
  141. def breadth_first_search(problem):
  142. "[Figure 3.11]"
  143. node = Node(problem.initial)
  144. if problem.goal_test(node.state):
  145. return node
  146. frontier = FIFOQueue()
  147. frontier.append(node)
  148. explored = set()
  149. while frontier:
  150. node = frontier.pop()
  151. explored.add(node.state)
  152. for child in node.expand(problem):
  153. if child.state not in explored and child not in frontier:
  154. if problem.goal_test(child.state):
  155. return child
  156. frontier.append(child)
  157. return None
  158. def best_first_graph_search(problem, f):
  159. """Search the nodes with the lowest f scores first.
  160. You specify the function f(node) that you want to minimize; for example,
  161. if f is a heuristic estimate to the goal, then we have greedy best
  162. first search; if f is node.depth then we have breadth-first search.
  163. There is a subtlety: the line "f = memoize(f, 'f')" means that the f
  164. values will be cached on the nodes as they are computed. So after doing
  165. a best first search you can examine the f values of the path returned."""
  166. f = memoize(f, 'f')
  167. node = Node(problem.initial)
  168. if problem.goal_test(node.state):
  169. return node
  170. frontier = PriorityQueue(min, f)
  171. frontier.append(node)
  172. explored = set()
  173. while frontier:
  174. node = frontier.pop()
  175. if problem.goal_test(node.state):
  176. return node
  177. explored.add(node.state)
  178. for child in node.expand(problem):
  179. if child.state not in explored and child not in frontier:
  180. frontier.append(child)
  181. elif child in frontier:
  182. incumbent = frontier[child]
  183. if f(child) < f(incumbent):
  184. # del frontier[incumbent]
  185. frontier.append(child)
  186. return None
  187. def uniform_cost_search(problem):
  188. "[Figure 3.14]"
  189. return best_first_graph_search(problem, lambda node: node.path_cost)
  190. def depth_limited_search(problem, limit=50):
  191. "[Figure 3.17]"
  192. def recursive_dls(node, problem, limit):
  193. if problem.goal_test(node.state):
  194. return node
  195. elif limit == 0:
  196. return 'cutoff'
  197. else:
  198. cutoff_occurred = False
  199. for child in node.expand(problem):
  200. result = recursive_dls(child, problem, limit - 1)
  201. if result == 'cutoff':
  202. cutoff_occurred = True
  203. elif result is not None:
  204. return result
  205. return 'cutoff' if cutoff_occurred else None
  206. # Body of depth_limited_search:
  207. return recursive_dls(Node(problem.initial), problem, limit)
  208. def iterative_deepening_search(problem):
  209. "[Figure 3.18]"
  210. for depth in range(sys.maxsize):
  211. result = depth_limited_search(problem, depth)
  212. if result != 'cutoff':
  213. return result
  214. # ______________________________________________________________________________
  215. # Informed (Heuristic) Search
  216. greedy_best_first_graph_search = best_first_graph_search
  217. # Greedy best-first search is accomplished by specifying f(n) = h(n).
  218. def astar_search(problem, h=None):
  219. """A* search is best-first graph search with f(n) = g(n)+h(n).
  220. You need to specify the h function when you call astar_search, or
  221. else in your Problem subclass."""
  222. h = memoize(h or problem.h, 'h')
  223. return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
  224. # ______________________________________________________________________________
  225. # Other search algorithms
  226. def recursive_best_first_search(problem, h=None):
  227. "[Figure 3.26]"
  228. h = memoize(h or problem.h, 'h')
  229. def RBFS(problem, node, flimit):
  230. if problem.goal_test(node.state):
  231. return node, 0 # (The second value is immaterial)
  232. successors = node.expand(problem)
  233. if len(successors) == 0:
  234. return None, infinity
  235. for s in successors:
  236. s.f = max(s.path_cost + h(s), node.f)
  237. while True:
  238. # Order by lowest f value
  239. successors.sort(key=lambda x: x.f)
  240. best = successors[0]
  241. if best.f > flimit:
  242. return None, best.f
  243. if len(successors) > 1:
  244. alternative = successors[1].f
  245. else:
  246. alternative = infinity
  247. result, best.f = RBFS(problem, best, min(flimit, alternative))
  248. if result is not None:
  249. return result, best.f
  250. node = Node(problem.initial)
  251. node.f = h(node)
  252. result, bestf = RBFS(problem, node, infinity)
  253. return result
  254. # ______________________________________________________________________________
  255. # Code to compare searchers on various problems.
  256. class InstrumentedProblem(Problem):
  257. """Delegates to a problem, and keeps statistics."""
  258. def __init__(self, problem):
  259. self.problem = problem
  260. self.succs = self.goal_tests = self.states = 0
  261. self.found = None
  262. def actions(self, state):
  263. self.succs += 1
  264. return self.problem.actions(state)
  265. def result(self, state, action):
  266. self.states += 1
  267. return self.problem.result(state, action)
  268. def goal_test(self, state):
  269. self.goal_tests += 1
  270. result = self.problem.goal_test(state)
  271. if result:
  272. self.found = state
  273. return result
  274. def path_cost(self, c, state1, action, state2):
  275. return self.problem.path_cost(c, state1, action, state2)
  276. def value(self, state):
  277. return self.problem.value(state)
  278. def __getattr__(self, attr):
  279. return getattr(self.problem, attr)
  280. def __repr__(self):
  281. return '<%4d/%4d/%4d/%s>' % (self.succs, self.goal_tests,
  282. self.states, str(self.found)[:4])
  283. def compare_searchers(problems, header,
  284. searchers=[breadth_first_tree_search,
  285. breadth_first_search,
  286. depth_first_graph_search,
  287. iterative_deepening_search,
  288. depth_limited_search,
  289. recursive_best_first_search]):
  290. def do(searcher, problem):
  291. p = InstrumentedProblem(problem)
  292. searcher(p)
  293. return p
  294. table = [[name(s)] + [do(s, p) for p in problems] for s in searchers]
  295. print_table(table, header)