Astar.py 6.1 KB

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