RTAAstar.py 7.8 KB

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