dfs.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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.OPEN = queue.QueueLIFO() # U 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. Searching using DFS.
  26. :return: planning path, action in each node, visited nodes in the planning process
  27. """
  28. while not self.OPEN.empty():
  29. s = self.OPEN.get()
  30. if s == self.xG:
  31. break
  32. self.CLOSED.append(s)
  33. for u in self.u_set: # explore neighborhoods
  34. s_next = tuple([s[i] + u[i] for i in range(2)])
  35. if s_next not in self.PARENT and s_next not in self.obs: # node not visited and not in obstacles
  36. self.OPEN.put(s_next)
  37. self.PARENT[s_next] = s
  38. return self.extract_path(), self.CLOSED
  39. def extract_path(self):
  40. """
  41. Extract the path based on the relationship of nodes.
  42. :return: The planning path
  43. """
  44. path = [self.xG]
  45. s = self.xG
  46. while True:
  47. s = self.PARENT[s]
  48. path.append(s)
  49. if s == self.xI:
  50. break
  51. return list(path)
  52. def main():
  53. x_start = (5, 5)
  54. x_goal = (45, 25)
  55. dfs = DFS(x_start, x_goal)
  56. plot = plotting.Plotting(x_start, x_goal)
  57. fig_name = "Depth-first Searching (DFS)"
  58. path, visited = dfs.searching()
  59. plot.animation(path, visited, fig_name) # animation
  60. if __name__ == '__main__':
  61. main()