IDA_star.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """
  2. IDA_Star 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 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. def ida_star(self):
  20. bound = self.h(self.xI)
  21. path = [self.xI]
  22. while True:
  23. t = self.searching(path, 0, bound)
  24. if t == self.xG:
  25. return path
  26. if t == float("inf"):
  27. return None
  28. bound = t
  29. def searching(self, path, g, bound):
  30. s = path[-1]
  31. f = g + self.h(s)
  32. if f > bound:
  33. return f
  34. if s == self.xG:
  35. return s
  36. res_min = float("inf")
  37. for u in self.u_set:
  38. s_next = tuple([s[i] + u[i] for i in range(len(s))])
  39. if s_next not in self.obs and s_next not in path:
  40. path.append(s_next)
  41. t = self.searching(path, g + 1, bound)
  42. if t == self.xG:
  43. return self.xG
  44. if t < res_min:
  45. res_min = t
  46. path.pop()
  47. return res_min
  48. def h(self, s):
  49. heuristic_type = self.heuristic_type
  50. goal = self.xG
  51. if heuristic_type == "manhattan":
  52. return abs(goal[0] - s[0]) + abs(goal[1] - s[1])
  53. elif heuristic_type == "euclidean":
  54. return ((goal[0] - s[0]) ** 2 + (goal[1] - s[1]) ** 2) ** (1 / 2)
  55. else:
  56. print("Please choose right heuristic type!")
  57. def main():
  58. x_start = (5, 5) # Starting node
  59. x_goal = (15, 25) # Goal node
  60. ida_star = IdaStar(x_start, x_goal, "manhattan")
  61. plot = plotting.Plotting(x_start, x_goal)
  62. path = ida_star.ida_star()
  63. if path:
  64. plot.animation(path, [], "IDA_Star")
  65. else:
  66. print("Path not found!")
  67. if __name__ == '__main__':
  68. main()