IDAstar.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. """
  2. IDA_Star 2D (Iteratively Deepening A*)
  3. @author: huiming zhou
  4. """
  5. import os
  6. import sys
  7. import matplotlib.pyplot as plt
  8. sys.path.append(os.path.dirname(os.path.abspath(__file__)) +
  9. "/../../Search-based Planning/")
  10. from Search_2D import plotting
  11. from Search_2D import env
  12. class IdaStar:
  13. def __init__(self, x_start, x_goal, heuristic_type):
  14. self.xI, self.xG = x_start, x_goal
  15. self.heuristic_type = heuristic_type
  16. self.Env = env.Env() # class Env
  17. self.u_set = self.Env.motions # feasible input set
  18. self.obs = self.Env.obs # position of obstacles
  19. self.visited = []
  20. def ida_star(self):
  21. bound = self.h(self.xI)
  22. path = [self.xI]
  23. while True:
  24. t = self.searching(path, 0, bound)
  25. if t == self.xG:
  26. return path, self.visited
  27. if t == float("inf"):
  28. return [], self.visited
  29. bound = t
  30. def searching(self, path, g, bound):
  31. s = path[-1]
  32. self.visited.append(s)
  33. f = g + self.h(s)
  34. if f > bound:
  35. return f
  36. if s == self.xG:
  37. return s
  38. res_min = float("inf")
  39. for u in self.u_set:
  40. s_next = tuple([s[i] + u[i] for i in range(len(s))])
  41. if s_next not in self.obs and s_next not in path:
  42. path.append(s_next)
  43. t = self.searching(path, g + 1, bound)
  44. if t == self.xG:
  45. return self.xG
  46. if t < res_min:
  47. res_min = t
  48. path.pop()
  49. return res_min
  50. def h(self, s):
  51. heuristic_type = self.heuristic_type
  52. goal = self.xG
  53. if heuristic_type == "manhattan":
  54. return abs(goal[0] - s[0]) + abs(goal[1] - s[1])
  55. elif heuristic_type == "euclidean":
  56. return ((goal[0] - s[0]) ** 2 + (goal[1] - s[1]) ** 2) ** (1 / 2)
  57. else:
  58. print("Please choose right heuristic type!")
  59. def main():
  60. x_start = (5, 5)
  61. x_goal = (15, 20)
  62. ida_star = IdaStar(x_start, x_goal, "manhattan")
  63. plot = plotting.Plotting(x_start, x_goal)
  64. path, visited = ida_star.ida_star()
  65. if path:
  66. plot.plot_grid("Iteratively Deepening A*")
  67. plot.plot_path(visited, 'gray', True)
  68. plot.plot_path(path)
  69. plt.show()
  70. else:
  71. print("Path not found!")
  72. if __name__ == '__main__':
  73. main()