RTAAstar.py 7.0 KB

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