RTAAStar.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. """
  2. RTAAstar 2D (Real-time Adaptive A*)
  3. @author: huiming zhou
  4. """
  5. import os
  6. import sys
  7. import copy
  8. import math
  9. sys.path.append(os.path.dirname(os.path.abspath(__file__)) +
  10. "/../../Search_based_Planning/")
  11. from Search_2D import queue, plotting, env
  12. class RTAAStar:
  13. def __init__(self, s_start, s_goal, N, heuristic_type):
  14. self.s_start, self.s_goal = s_start, s_goal
  15. self.heuristic_type = heuristic_type
  16. self.Env = env.Env()
  17. self.u_set = self.Env.motions # feasible input set
  18. self.obs = self.Env.obs # position of obstacles
  19. self.N = N # number of expand nodes each iteration
  20. self.visited = [] # order of visited nodes in planning
  21. self.path = [] # path of each iteration
  22. self.h_table = {} # h_value table
  23. def init(self):
  24. """
  25. initialize the h_value of all nodes in the environment.
  26. it is a global table.
  27. """
  28. for i in range(self.Env.x_range):
  29. for j in range(self.Env.y_range):
  30. self.h_table[(i, j)] = self.h((i, j))
  31. def searching(self):
  32. self.init()
  33. s_start = self.s_start # initialize start node
  34. while True:
  35. OPEN, CLOSED, g_table, PARENT = \
  36. self.Astar(s_start, self.N)
  37. if OPEN == "FOUND": # reach the goal node
  38. self.path.append(CLOSED)
  39. break
  40. s_next, h_value = self.cal_h_value(OPEN, CLOSED, g_table, PARENT)
  41. for x in h_value:
  42. self.h_table[x] = h_value[x]
  43. s_start, path_k = self.extract_path_in_CLOSE(s_start, s_next, h_value)
  44. self.path.append(path_k)
  45. def cal_h_value(self, OPEN, CLOSED, g_table, PARENT):
  46. v_open = {}
  47. h_value = {}
  48. for (_, x) in OPEN.enumerate():
  49. v_open[x] = g_table[PARENT[x]] + 1 + self.h_table[x]
  50. s_open = min(v_open, key=v_open.get)
  51. f_min = v_open[s_open]
  52. for x in CLOSED:
  53. h_value[x] = f_min - g_table[x]
  54. return s_open, h_value
  55. def iteration(self, CLOSED):
  56. h_value = {}
  57. for s in CLOSED:
  58. h_value[s] = float("inf") # initialize h_value of CLOSED nodes
  59. while True:
  60. h_value_rec = copy.deepcopy(h_value)
  61. for s in CLOSED:
  62. h_list = []
  63. for s_n in self.get_neighbor(s):
  64. if s_n not in CLOSED:
  65. h_list.append(self.cost(s, s_n) + self.h_table[s_n])
  66. else:
  67. h_list.append(self.cost(s, s_n) + h_value[s_n])
  68. h_value[s] = min(h_list) # update h_value of current node
  69. if h_value == h_value_rec: # h_value table converged
  70. return h_value
  71. def Astar(self, x_start, N):
  72. OPEN = queue.QueuePrior() # OPEN set
  73. OPEN.put(x_start, self.h_table[x_start])
  74. CLOSED = [] # CLOSED set
  75. g_table = {x_start: 0, self.s_goal: float("inf")} # Cost to come
  76. PARENT = {x_start: x_start} # relations
  77. count = 0 # counter
  78. while not OPEN.empty():
  79. count += 1
  80. s = OPEN.get()
  81. CLOSED.append(s)
  82. if s == self.s_goal: # reach the goal node
  83. self.visited.append(CLOSED)
  84. return "FOUND", self.extract_path(x_start, PARENT), [], []
  85. for s_n in self.get_neighbor(s):
  86. if s_n not in CLOSED:
  87. new_cost = g_table[s] + self.cost(s, s_n)
  88. if s_n not in g_table:
  89. g_table[s_n] = float("inf")
  90. if new_cost < g_table[s_n]: # conditions for updating Cost
  91. g_table[s_n] = new_cost
  92. PARENT[s_n] = s
  93. OPEN.put(s_n, g_table[s_n] + self.h_table[s_n])
  94. if count == N: # expand needed CLOSED nodes
  95. break
  96. self.visited.append(CLOSED) # visited nodes in each iteration
  97. return OPEN, CLOSED, g_table, PARENT
  98. def get_neighbor(self, s):
  99. """
  100. find neighbors of state s that not in obstacles.
  101. :param s: state
  102. :return: neighbors
  103. """
  104. s_list = set()
  105. for u in self.u_set:
  106. s_next = tuple([s[i] + u[i] for i in range(2)])
  107. if s_next not in self.obs:
  108. s_list.add(s_next)
  109. return s_list
  110. def extract_path_in_CLOSE(self, s_end, s_start, h_value):
  111. path = [s_start]
  112. s = s_start
  113. while True:
  114. h_list = {}
  115. for s_n in self.get_neighbor(s):
  116. if s_n in h_value:
  117. h_list[s_n] = h_value[s_n]
  118. s_key = max(h_list, key=h_list.get) # move to the smallest node with min h_value
  119. path.append(s_key) # generate path
  120. s = s_key # use end of this iteration as the start of next
  121. if s_key == s_end: # reach the expected node in OPEN set
  122. return s_start, list(reversed(path))
  123. def extract_path(self, x_start, parent):
  124. """
  125. Extract the path based on the relationship of nodes.
  126. :return: The planning path
  127. """
  128. path = [self.s_goal]
  129. s = self.s_goal
  130. while True:
  131. s = parent[s]
  132. path.append(s)
  133. if s == x_start:
  134. break
  135. return list(reversed(path))
  136. def h(self, s):
  137. """
  138. Calculate heuristic.
  139. :param s: current node (state)
  140. :return: heuristic function value
  141. """
  142. heuristic_type = self.heuristic_type # heuristic type
  143. goal = self.s_goal # goal node
  144. if heuristic_type == "manhattan":
  145. return abs(goal[0] - s[0]) + abs(goal[1] - s[1])
  146. else:
  147. return math.hypot(goal[0] - s[0], goal[1] - s[1])
  148. def cost(self, s_start, s_goal):
  149. """
  150. Calculate Cost for this motion
  151. :param s_start: starting node
  152. :param s_goal: end node
  153. :return: Cost for this motion
  154. :note: Cost function could be more complicate!
  155. """
  156. if self.is_collision(s_start, s_goal):
  157. return float("inf")
  158. return math.hypot(s_goal[0] - s_start[0], s_goal[1] - s_start[1])
  159. def is_collision(self, s_start, s_end):
  160. if s_start in self.obs or s_end in self.obs:
  161. return True
  162. if s_start[0] != s_end[0] and s_start[1] != s_end[1]:
  163. if s_end[0] - s_start[0] == s_start[1] - s_end[1]:
  164. s1 = (min(s_start[0], s_end[0]), min(s_start[1], s_end[1]))
  165. s2 = (max(s_start[0], s_end[0]), max(s_start[1], s_end[1]))
  166. else:
  167. s1 = (min(s_start[0], s_end[0]), max(s_start[1], s_end[1]))
  168. s2 = (max(s_start[0], s_end[0]), min(s_start[1], s_end[1]))
  169. if s1 in self.obs or s2 in self.obs:
  170. return True
  171. return False
  172. def main():
  173. s_start = (10, 5)
  174. s_goal = (45, 25)
  175. rtaa = RTAAStar(s_start, s_goal, 240, "euclidean")
  176. plot = plotting.Plotting(s_start, s_goal)
  177. rtaa.searching()
  178. plot.animation_lrta(rtaa.path, rtaa.visited,
  179. "Real-time Adaptive A* (RTAA*)")
  180. if __name__ == '__main__':
  181. main()