dfs.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import queue
  2. import plotting
  3. import env
  4. class DFS:
  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 = "Depth-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 DFS.
  17. :return: planning path, action in each node, visited nodes in the planning process
  18. """
  19. q_dfs = queue.QueueLIFO() # last-in-first-out queue
  20. q_dfs.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_dfs.empty():
  25. x_current = q_dfs.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_dfs.put(x_next)
  33. parent[x_next], action[x_next] = x_current, u_next
  34. [path, policy] = self.extract_path(xI, xG, parent, action)
  35. return path, policy, visited
  36. @staticmethod
  37. def extract_path(xI, xG, parent, policy):
  38. """
  39. Extract the path based on the relationship of nodes.
  40. :param xI: Starting node
  41. :param xG: Goal node
  42. :param parent: Relationship between nodes
  43. :param policy: Action needed for transfer between two nodes
  44. :return: The planning path
  45. """
  46. path_back = [xG]
  47. acts_back = [policy[xG]]
  48. x_current = xG
  49. while True:
  50. x_current = parent[x_current]
  51. path_back.append(x_current)
  52. acts_back.append(policy[x_current])
  53. if x_current == xI:
  54. break
  55. return list(path_back), list(acts_back)
  56. if __name__ == '__main__':
  57. x_Start = (5, 5) # Starting node
  58. x_Goal = (49, 5) # Goal node
  59. dfs = DFS(x_Start, x_Goal)