LRTAstar.py 6.7 KB

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