RTAAstar.py 6.7 KB

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