LRTAstar.py 7.5 KB

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