bfs.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. """
  2. BFS 2D (Breadth-first Searching)
  3. @author: huiming zhou
  4. """
  5. import os
  6. import sys
  7. sys.path.append(os.path.dirname(os.path.abspath(__file__)) +
  8. "/../../Search-based Planning/")
  9. from Search_2D import queue
  10. from Search_2D import plotting
  11. from Search_2D import env
  12. class BFS:
  13. def __init__(self, x_start, x_goal):
  14. self.xI, self.xG = x_start, x_goal
  15. self.Env = env.Env()
  16. self.plotting = plotting.Plotting(self.xI, self.xG)
  17. self.u_set = self.Env.motions # feasible input set
  18. self.obs = self.Env.obs # position of obstacles
  19. self.OPEN = queue.QueueFIFO() # OPEN set: visited nodes
  20. self.OPEN.put(self.xI)
  21. self.CLOSED = [] # CLOSED set: explored nodes
  22. self.PARENT = {self.xI: self.xI} # relations
  23. def searching(self):
  24. """
  25. :return: path, order of visited nodes in the planning
  26. """
  27. while not self.OPEN.empty():
  28. s = self.OPEN.get()
  29. if s == self.xG:
  30. break
  31. self.CLOSED.append(s)
  32. for u_next in self.u_set: # explore neighborhoods
  33. s_next = tuple([s[i] + u_next[i] for i in range(2)])
  34. if s_next not in self.PARENT and s_next not in self.obs: # node not visited and not in obstacles
  35. self.OPEN.put(s_next)
  36. self.PARENT[s_next] = s
  37. return self.extract_path(), self.CLOSED
  38. def extract_path(self):
  39. """
  40. Extract the path based on the relationship of nodes.
  41. :return: The planning path
  42. """
  43. path = [self.xG]
  44. s = self.xG
  45. while True:
  46. s = self.PARENT[s]
  47. path.append(s)
  48. if s == self.xI:
  49. break
  50. return list(path)
  51. def main():
  52. x_start = (5, 5) # Starting node
  53. x_goal = (45, 25) # Goal node
  54. bfs = BFS(x_start, x_goal)
  55. plot = plotting.Plotting(x_start, x_goal)
  56. fig_name = "Breadth-first Searching (BFS)"
  57. path, visited = bfs.searching()
  58. plot.animation(path, visited, fig_name) # animation
  59. if __name__ == '__main__':
  60. main()