bfs.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import queue
  2. import plotting
  3. import env
  4. class BFS:
  5. def __init__(self, x_start, x_goal):
  6. self.xI, self.xG = x_start, x_goal
  7. self.Env = env.Env()
  8. self.plotting = plotting.Plotting(self.xI, self.xG)
  9. self.u_set = self.Env.motions # feasible input set
  10. self.obs = self.Env.obs # position of obstacles
  11. [self.path, self.policy, self.visited] = self.searching(self.xI, self.xG)
  12. self.fig_name = "Breadth-first Searching"
  13. self.plotting.animation(self.path, self.visited, self.fig_name) # animation generate
  14. def searching(self, xI, xG):
  15. """
  16. Searching using BFS.
  17. :return: planning path, action in each node, visited nodes in the planning process
  18. """
  19. q_bfs = queue.QueueFIFO() # first-in-first-out queue
  20. q_bfs.put(xI)
  21. parent = {xI: xI} # record parents of nodes
  22. action = {xI: (0, 0)} # record actions of nodes
  23. visited = []
  24. while not q_bfs.empty():
  25. x_current = q_bfs.get()
  26. if x_current == xG:
  27. break
  28. visited.append(x_current)
  29. for u_next in self.u_set: # explore neighborhoods of current node
  30. x_next = tuple([x_current[i] + u_next[i] for i in range(len(x_current))])
  31. if x_next not in parent and x_next not in self.obs: # node not visited and not in obstacles
  32. q_bfs.put(x_next)
  33. parent[x_next], action[x_next] = x_current, u_next
  34. [path, policy] = self.extract_path(xI, xG, parent, action) # extract path
  35. return path, policy, visited
  36. def extract_path(self, xI, xG, parent, policy):
  37. """
  38. Extract the path based on the relationship of nodes.
  39. :param xI: Starting node
  40. :param xG: Goal node
  41. :param parent: Relationship between nodes
  42. :param policy: Action needed for transfer between two nodes
  43. :return: The planning path
  44. """
  45. path_back = [xG]
  46. acts_back = [policy[xG]]
  47. x_current = xG
  48. while True:
  49. x_current = parent[x_current]
  50. path_back.append(x_current)
  51. acts_back.append(policy[x_current])
  52. if x_current == xI: break
  53. return list(path_back), list(acts_back)
  54. if __name__ == '__main__':
  55. x_Start = (5, 5) # Starting node
  56. x_Goal = (49, 5) # Goal node
  57. bfs = BFS(x_Start, x_Goal)