Astar.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. """
  2. A_star 2D
  3. @author: huiming zhou
  4. """
  5. import os
  6. import sys
  7. import math
  8. import heapq
  9. sys.path.append(os.path.dirname(os.path.abspath(__file__)) +
  10. "/../../Search_based_Planning/")
  11. from Search_based_Planning.Search_2D import plotting, env
  12. class AStar:
  13. def __init__(self, s_start, s_goal, heuristic_type):
  14. self.s_start = s_start
  15. self.s_goal = s_goal
  16. self.heuristic_type = heuristic_type
  17. self.Env = env.Env() # class Env
  18. self.u_set = self.Env.motions # feasible input set
  19. self.obs = self.Env.obs # position of obstacles
  20. self.OPEN = [] # priority queue / OPEN set
  21. self.CLOSED = [] # CLOSED set / VISITED order
  22. self.PARENT = dict() # recorded parent
  23. self.g = dict() # cost to come
  24. def searching(self):
  25. """
  26. A_star Searching.
  27. :return: path, visited order
  28. """
  29. self.PARENT[self.s_start] = self.s_start
  30. self.g[self.s_start] = 0
  31. self.g[self.s_goal] = math.inf
  32. heapq.heappush(self.OPEN,
  33. (self.f_value(self.s_start), self.s_start))
  34. while self.OPEN:
  35. _, s = heapq.heappop(self.OPEN)
  36. self.CLOSED.append(s)
  37. if s == self.s_goal: # stop condition
  38. break
  39. for s_n in self.get_neighbor(s):
  40. new_cost = self.g[s] + self.cost(s, s_n)
  41. if s_n not in self.g:
  42. self.g[s_n] = math.inf
  43. if new_cost < self.g[s_n]: # conditions for updating Cost
  44. self.g[s_n] = new_cost
  45. self.PARENT[s_n] = s
  46. heapq.heappush(self.OPEN, (self.f_value(s_n), s_n))
  47. return self.extract_path(self.PARENT), self.CLOSED
  48. def searching_repeated_astar(self, e):
  49. """
  50. repeated A*.
  51. :param e: weight of A*
  52. :return: path and visited order
  53. """
  54. path, visited = [], []
  55. while e >= 1:
  56. p_k, v_k = self.repeated_searching(self.s_start, self.s_goal, e)
  57. path.append(p_k)
  58. visited.append(v_k)
  59. e -= 0.5
  60. return path, visited
  61. def repeated_searching(self, s_start, s_goal, e):
  62. """
  63. run A* with weight e.
  64. :param s_start: starting state
  65. :param s_goal: goal state
  66. :param e: weight of a*
  67. :return: path and visited order.
  68. """
  69. g = {s_start: 0, s_goal: float("inf")}
  70. PARENT = {s_start: s_start}
  71. OPEN = []
  72. CLOSED = []
  73. heapq.heappush(OPEN,
  74. (g[s_start] + e * self.heuristic(s_start), s_start))
  75. while OPEN:
  76. _, s = heapq.heappop(OPEN)
  77. CLOSED.append(s)
  78. if s == s_goal:
  79. break
  80. for s_n in self.get_neighbor(s):
  81. new_cost = g[s] + self.cost(s, s_n)
  82. if s_n not in g:
  83. g[s_n] = math.inf
  84. if new_cost < g[s_n]: # conditions for updating Cost
  85. g[s_n] = new_cost
  86. PARENT[s_n] = s
  87. heapq.heappush(OPEN, (g[s_n] + e * self.heuristic(s_n), s_n))
  88. return self.extract_path(PARENT), CLOSED
  89. def get_neighbor(self, s):
  90. """
  91. find neighbors of state s that not in obstacles.
  92. :param s: state
  93. :return: neighbors
  94. """
  95. return [(s[0] + u[0], s[1] + u[1]) for u in self.u_set]
  96. def cost(self, s_start, s_goal):
  97. """
  98. Calculate Cost for this motion
  99. :param s_start: starting node
  100. :param s_goal: end node
  101. :return: Cost for this motion
  102. :note: Cost function could be more complicate!
  103. """
  104. if self.is_collision(s_start, s_goal):
  105. return math.inf
  106. return math.hypot(s_goal[0] - s_start[0], s_goal[1] - s_start[1])
  107. def is_collision(self, s_start, s_end):
  108. """
  109. check if the line segment (s_start, s_end) is collision.
  110. :param s_start: start node
  111. :param s_end: end node
  112. :return: True: is collision / False: not collision
  113. """
  114. if s_start in self.obs or s_end in self.obs:
  115. return True
  116. if s_start[0] != s_end[0] and s_start[1] != s_end[1]:
  117. if s_end[0] - s_start[0] == s_start[1] - s_end[1]:
  118. s1 = (min(s_start[0], s_end[0]), min(s_start[1], s_end[1]))
  119. s2 = (max(s_start[0], s_end[0]), max(s_start[1], s_end[1]))
  120. else:
  121. s1 = (min(s_start[0], s_end[0]), max(s_start[1], s_end[1]))
  122. s2 = (max(s_start[0], s_end[0]), min(s_start[1], s_end[1]))
  123. if s1 in self.obs or s2 in self.obs:
  124. return True
  125. return False
  126. def f_value(self, s):
  127. """
  128. f = g + h. (g: Cost to come, h: heuristic value)
  129. :param s: current state
  130. :return: f
  131. """
  132. return self.g[s] + self.heuristic(s)
  133. def extract_path(self, PARENT):
  134. """
  135. Extract the path based on the PARENT set.
  136. :return: The planning path
  137. """
  138. path = [self.s_goal]
  139. s = self.s_goal
  140. while True:
  141. s = PARENT[s]
  142. path.append(s)
  143. if s == self.s_start:
  144. break
  145. return list(path)
  146. def heuristic(self, s):
  147. """
  148. Calculate heuristic.
  149. :param s: current node (state)
  150. :return: heuristic function value
  151. """
  152. heuristic_type = self.heuristic_type # heuristic type
  153. goal = self.s_goal # goal node
  154. if heuristic_type == "manhattan":
  155. return abs(goal[0] - s[0]) + abs(goal[1] - s[1])
  156. else:
  157. return math.hypot(goal[0] - s[0], goal[1] - s[1])
  158. def main():
  159. s_start = (5, 5)
  160. s_goal = (45, 25)
  161. astar = AStar(s_start, s_goal, "euclidean")
  162. plot = plotting.Plotting(s_start, s_goal)
  163. path, visited = astar.searching()
  164. plot.animation(path, visited, "A*") # animation
  165. # path, visited = astar.searching_repeated_astar(2.5) # initial weight e = 2.5
  166. # plot.animation_ara_star(path, visited, "Repeated A*")
  167. if __name__ == '__main__':
  168. main()