LRTAstar.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. """
  2. LRTA_star 2D (Learning Real-time 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 LrtAStarN:
  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 = self.AStar(s_start, self.N) # OPEN, CLOSED sets in each iteration
  36. if OPEN == "FOUND": # reach the goal node
  37. self.path.append(CLOSED)
  38. break
  39. h_value = self.iteration(CLOSED) # h_value table of CLOSED nodes
  40. for x in h_value:
  41. self.h_table[x] = h_value[x]
  42. s_start, path_k = self.extract_path_in_CLOSE(s_start, h_value) # x_init -> expected node in OPEN set
  43. self.path.append(path_k)
  44. def extract_path_in_CLOSE(self, s_start, h_value):
  45. path = [s_start]
  46. s = s_start
  47. while True:
  48. h_list = {}
  49. for s_n in self.get_neighbor(s):
  50. if s_n in h_value:
  51. h_list[s_n] = h_value[s_n]
  52. else:
  53. h_list[s_n] = self.h_table[s_n]
  54. s_key = min(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 not in h_value: # reach the expected node in OPEN set
  58. return s_key, 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 s_n in self.get_neighbor(s):
  68. if s_n not in CLOSED:
  69. h_list.append(self.cost(s, s_n) + self.h_table[s_n])
  70. else:
  71. h_list.append(self.cost(s, s_n) + h_value[s_n])
  72. h_value[s] = min(h_list) # update h_value of current node
  73. if h_value == h_value_rec: # h_value table converged
  74. return h_value
  75. def AStar(self, x_start, N):
  76. OPEN = queue.QueuePrior() # OPEN set
  77. OPEN.put(x_start, self.h(x_start))
  78. CLOSED = [] # CLOSED set
  79. g_table = {x_start: 0, self.s_goal: float("inf")} # Cost to come
  80. PARENT = {x_start: x_start} # relations
  81. count = 0 # counter
  82. while not OPEN.empty():
  83. count += 1
  84. s = OPEN.get()
  85. CLOSED.append(s)
  86. if s == self.s_goal: # reach the goal node
  87. self.visited.append(CLOSED)
  88. return "FOUND", self.extract_path(x_start, PARENT)
  89. for s_n in self.get_neighbor(s):
  90. if s_n not in CLOSED:
  91. new_cost = g_table[s] + self.cost(s, s_n)
  92. if s_n not in g_table:
  93. g_table[s_n] = float("inf")
  94. if new_cost < g_table[s_n]: # conditions for updating Cost
  95. g_table[s_n] = new_cost
  96. PARENT[s_n] = s
  97. OPEN.put(s_n, g_table[s_n] + self.h_table[s_n])
  98. if count == N: # expand needed CLOSED nodes
  99. break
  100. self.visited.append(CLOSED) # visited nodes in each iteration
  101. return OPEN, CLOSED
  102. def get_neighbor(self, s):
  103. """
  104. find neighbors of state s that not in obstacles.
  105. :param s: state
  106. :return: neighbors
  107. """
  108. s_list = []
  109. for u in self.u_set:
  110. s_next = tuple([s[i] + u[i] for i in range(2)])
  111. if s_next not in self.obs:
  112. s_list.append(s_next)
  113. return s_list
  114. def extract_path(self, x_start, parent):
  115. """
  116. Extract the path based on the relationship of nodes.
  117. :return: The planning path
  118. """
  119. path_back = [self.s_goal]
  120. x_current = self.s_goal
  121. while True:
  122. x_current = parent[x_current]
  123. path_back.append(x_current)
  124. if x_current == x_start:
  125. break
  126. return list(reversed(path_back))
  127. def h(self, s):
  128. """
  129. Calculate heuristic.
  130. :param s: current node (state)
  131. :return: heuristic function value
  132. """
  133. heuristic_type = self.heuristic_type # heuristic type
  134. goal = self.s_goal # goal node
  135. if heuristic_type == "manhattan":
  136. return abs(goal[0] - s[0]) + abs(goal[1] - s[1])
  137. else:
  138. return math.hypot(goal[0] - s[0], goal[1] - s[1])
  139. def cost(self, s_start, s_goal):
  140. """
  141. Calculate Cost for this motion
  142. :param s_start: starting node
  143. :param s_goal: end node
  144. :return: Cost for this motion
  145. :note: Cost function could be more complicate!
  146. """
  147. if self.is_collision(s_start, s_goal):
  148. return float("inf")
  149. return math.hypot(s_goal[0] - s_start[0], s_goal[1] - s_start[1])
  150. def is_collision(self, s_start, s_end):
  151. if s_start in self.obs or s_end in self.obs:
  152. return True
  153. if s_start[0] != s_end[0] and s_start[1] != s_end[1]:
  154. if s_end[0] - s_start[0] == s_start[1] - s_end[1]:
  155. s1 = (min(s_start[0], s_end[0]), min(s_start[1], s_end[1]))
  156. s2 = (max(s_start[0], s_end[0]), max(s_start[1], s_end[1]))
  157. else:
  158. s1 = (min(s_start[0], s_end[0]), max(s_start[1], s_end[1]))
  159. s2 = (max(s_start[0], s_end[0]), min(s_start[1], s_end[1]))
  160. if s1 in self.obs or s2 in self.obs:
  161. return True
  162. return False
  163. def main():
  164. s_start = (10, 5)
  165. s_goal = (45, 25)
  166. lrta = LrtAStarN(s_start, s_goal, 250, "euclidean")
  167. plot = plotting.Plotting(s_start, s_goal)
  168. lrta.searching()
  169. plot.animation_lrta(lrta.path, lrta.visited,
  170. "Learning Real-time A* (LRTA*)")
  171. if __name__ == '__main__':
  172. main()