ara_star.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import queue
  2. import plotting
  3. import env
  4. import matplotlib.pyplot as plt
  5. class AraStar:
  6. def __init__(self, x_start, x_goal, heuristic_type):
  7. self.xI, self.xG = x_start, x_goal
  8. self.heuristic_type = heuristic_type
  9. self.Env = env.Env() # class Env
  10. self.u_set = self.Env.motions # feasible input set
  11. self.obs = self.Env.obs # position of obstacles
  12. self.e = 3
  13. self.g = {self.xI: 0, self.xG: float("inf")}
  14. self.fig_name = "ARA_Star Algorithm"
  15. self.OPEN = queue.QueuePrior() # priority queue / OPEN
  16. self.CLOSED = []
  17. self.INCONS = []
  18. self.parent = {self.xI: self.xI}
  19. def searching(self):
  20. path = []
  21. self.OPEN.put(self.xI, self.fvalue(self.xI))
  22. self.ImprovePath()
  23. path.append(self.extract_path())
  24. while self.update_e() > 1:
  25. self.e -= 0.5
  26. OPEN_mid = [x for (p, x) in self.OPEN.enumerate()] + self.INCONS
  27. self.OPEN = queue.QueuePrior()
  28. for x in OPEN_mid:
  29. self.OPEN.put(x, self.fvalue(x))
  30. self.INCONS = []
  31. self.CLOSED = []
  32. self.ImprovePath()
  33. path.append(self.extract_path())
  34. return path
  35. def ImprovePath(self):
  36. while (not self.OPEN.empty() and self.fvalue(self.xG) >
  37. min([self.fvalue(x) for (p, x) in self.OPEN.enumerate()])):
  38. s = self.OPEN.get()
  39. self.CLOSED.append(s)
  40. for u_next in self.u_set:
  41. s_next = tuple([s[i] + u_next[i] for i in range(len(s))])
  42. if s_next not in self.obs:
  43. new_cost = self.g[s] + self.get_cost(s, u_next)
  44. if s_next not in self.g or new_cost < self.g[s_next]:
  45. self.g[s_next] = new_cost
  46. self.parent[s_next] = s
  47. if s_next not in self.CLOSED:
  48. self.OPEN.put(s_next, self.fvalue(s_next))
  49. else:
  50. self.INCONS.append(s_next)
  51. def update_e(self):
  52. c_OPEN, c_INCONS = float("inf"), float("inf")
  53. if not self.OPEN.empty():
  54. c_OPEN = min(self.g[x] + self.Heuristic(x) for (p, x) in self.OPEN.enumerate())
  55. if len(self.INCONS) != 0:
  56. c_INCONS = min(self.g[x] + self.Heuristic(x) for x in self.INCONS)
  57. if min(c_OPEN, c_INCONS) == float("inf"):
  58. return 1
  59. else:
  60. return min(self.e, self.g[self.xG] / min(c_OPEN, c_INCONS))
  61. def fvalue(self, x):
  62. h = self.e * self.Heuristic(x)
  63. return self.g[x] + h
  64. def extract_path(self):
  65. """
  66. Extract the path based on the relationship of nodes.
  67. :param policy: Action needed for transfer between two nodes
  68. :return: The planning path
  69. """
  70. path_back = [self.xG]
  71. x_current = self.xG
  72. while True:
  73. x_current = self.parent[x_current]
  74. path_back.append(x_current)
  75. if x_current == self.xI:
  76. break
  77. return list(path_back)
  78. @staticmethod
  79. def get_cost(x, u):
  80. """
  81. Calculate cost for this motion
  82. :param x: current node
  83. :param u: input
  84. :return: cost for this motion
  85. :note: cost function could be more complicate!
  86. """
  87. return 1
  88. def Heuristic(self, state):
  89. """
  90. Calculate heuristic.
  91. :param state: current node (state)
  92. :param goal: goal node (state)
  93. :param heuristic_type: choosing different heuristic functions
  94. :return: heuristic
  95. """
  96. heuristic_type = self.heuristic_type
  97. goal = self.xG
  98. if heuristic_type == "manhattan":
  99. return abs(goal[0] - state[0]) + abs(goal[1] - state[1])
  100. elif heuristic_type == "euclidean":
  101. return ((goal[0] - state[0]) ** 2 + (goal[1] - state[1]) ** 2) ** (1 / 2)
  102. else:
  103. print("Please choose right heuristic type!")
  104. def main():
  105. x_start = (5, 5) # Starting node
  106. x_goal = (49, 5) # Goal node
  107. arastar = AraStar(x_start, x_goal, "manhattan")
  108. plot = plotting.Plotting(x_start, x_goal)
  109. path = arastar.searching()
  110. plot.plot_grid("ARA*")
  111. print(arastar.e)
  112. for path_i in path:
  113. path_i.remove(x_start)
  114. path_i.remove(x_goal)
  115. path_x = [path_i[i][0] for i in range(len(path_i))]
  116. path_y = [path_i[i][1] for i in range(len(path_i))]
  117. plt.plot(path_x, path_y, linewidth='3', marker='o')
  118. plt.pause(1)
  119. plt.show()
  120. if __name__ == '__main__':
  121. main()