RTAAstar.py 7.0 KB

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