LRTAstar.py 6.7 KB

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