bfs.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @author: huiming zhou
  5. """
  6. import queue
  7. import tools
  8. import env
  9. import motion_model
  10. class BFS:
  11. def __init__(self, x_start, x_goal):
  12. self.u_set = motion_model.motions # feasible input set
  13. self.xI, self.xG = x_start, x_goal
  14. self.obs = env.obs_map() # position of obstacles
  15. tools.show_map(self.xI, self.xG, self.obs, "breadth-first searching")
  16. def searching(self):
  17. """
  18. Searching using BFS.
  19. :return: planning path, action in each node, visited nodes in the planning process
  20. """
  21. q_bfs = queue.QueueFIFO() # first-in-first-out queue
  22. q_bfs.put(self.xI)
  23. parent = {self.xI: self.xI} # record parents of nodes
  24. action = {self.xI: (0, 0)} # record actions of nodes
  25. while not q_bfs.empty():
  26. x_current = q_bfs.get()
  27. if x_current == self.xG:
  28. break
  29. if x_current != self.xI:
  30. tools.plot_dots(x_current, len(parent))
  31. for u_next in self.u_set: # explore neighborhoods of current node
  32. x_next = tuple([x_current[i] + u_next[i] for i in range(len(x_current))])
  33. if x_next not in parent and x_next not in self.obs: # node not visited and not in obstacles
  34. q_bfs.put(x_next)
  35. parent[x_next] = x_current
  36. action[x_next] = u_next
  37. [path_bfs, action_bfs] = tools.extract_path(self.xI, self.xG, parent, action) # extract path
  38. return path_bfs, action_bfs
  39. if __name__ == '__main__':
  40. x_Start = (5, 5) # Starting node
  41. x_Goal = (49, 5) # Goal node
  42. bfs = BFS(x_Start, x_Goal)
  43. [path_bf, actions_bf] = bfs.searching()
  44. tools.showPath(x_Start, x_Goal, path_bf)