dfs.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. """
  2. DFS 2D
  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 DFS:
  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.path, self.policy, self.visited] = self.searching(self.xI, self.xG)
  20. self.fig_name = "Depth-first Searching"
  21. self.plotting.animation(self.path, self.visited, self.fig_name) # animation generate
  22. def searching(self, xI, xG):
  23. """
  24. Searching using DFS.
  25. :return: planning path, action in each node, visited nodes in the planning process
  26. """
  27. q_dfs = queue.QueueLIFO() # last-in-first-out queue
  28. q_dfs.put(xI)
  29. parent = {xI: xI} # record parents of nodes
  30. action = {xI: (0, 0)} # record actions of nodes
  31. visited = []
  32. while not q_dfs.empty():
  33. x_current = q_dfs.get()
  34. if x_current == xG:
  35. break
  36. visited.append(x_current)
  37. for u_next in self.u_set: # explore neighborhoods of current node
  38. x_next = tuple([x_current[i] + u_next[i] for i in range(len(x_current))])
  39. if x_next not in parent and x_next not in self.obs: # node not visited and not in obstacles
  40. q_dfs.put(x_next)
  41. parent[x_next], action[x_next] = x_current, u_next
  42. [path, policy] = self.extract_path(xI, xG, parent, action)
  43. return path, policy, visited
  44. @staticmethod
  45. def extract_path(xI, xG, parent, policy):
  46. """
  47. Extract the path based on the relationship of nodes.
  48. :param xI: Starting node
  49. :param xG: Goal node
  50. :param parent: Relationship between nodes
  51. :param policy: Action needed for transfer between two nodes
  52. :return: The planning path
  53. """
  54. path_back = [xG]
  55. acts_back = [policy[xG]]
  56. x_current = xG
  57. while True:
  58. x_current = parent[x_current]
  59. path_back.append(x_current)
  60. acts_back.append(policy[x_current])
  61. if x_current == xI:
  62. break
  63. return list(path_back), list(acts_back)
  64. if __name__ == '__main__':
  65. x_Start = (5, 5) # Starting node
  66. x_Goal = (49, 5) # Goal node
  67. dfs = DFS(x_Start, x_Goal)