LPAstar.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. """
  2. LPA_star 2D
  3. @author: huiming zhou
  4. """
  5. import os
  6. import sys
  7. import math
  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 LpaStar:
  15. def __init__(self, x_start, x_goal, heuristic_type):
  16. self.xI, self.xG = x_start, x_goal
  17. self.heuristic_type = heuristic_type
  18. self.Env = env.Env() # class Env
  19. self.Plot = plotting.Plotting(x_start, x_goal)
  20. self.u_set = self.Env.motions # feasible input set
  21. self.obs = self.Env.obs # position of obstacles
  22. self.x = self.Env.x_range
  23. self.y = self.Env.y_range
  24. self.U = queue.QueuePrior() # priority queue / U set
  25. self.g, self.rhs = {}, {}
  26. for i in range(self.Env.x_range):
  27. for j in range(self.Env.y_range):
  28. self.rhs[(i, j)] = float("inf")
  29. self.g[(i, j)] = float("inf")
  30. self.rhs[self.xI] = 0
  31. self.U.put(self.xI, self.Key(self.xI))
  32. def searching(self):
  33. self.fig = plt.figure()
  34. self.Plot.plot_grid("Lifelong Planning A*")
  35. self.ComputePath()
  36. self.plot_path(self.extract_path_test())
  37. self.fig.canvas.mpl_connect('button_press_event', self.on_press)
  38. print("hahha")
  39. plt.show()
  40. def on_press(self, event):
  41. x, y = event.xdata, event.ydata
  42. if x < 0 or x > self.x - 1 or y < 0 or y > self.y - 1:
  43. print("Please choose right area!")
  44. else:
  45. x, y = int(x), int(y)
  46. print("Change position: x =", x, ",", "y =", y)
  47. if (x, y) not in self.obs:
  48. self.obs.add((x, y))
  49. plt.plot(x, y, 'sk')
  50. self.rhs[(x, y)] = float("inf")
  51. self.g[(x, y)] = float("inf")
  52. for node in self.getSucc((x, y)):
  53. self.UpdateVertex(node)
  54. else:
  55. self.obs.remove((x, y))
  56. plt.plot(x, y, marker='s', color='white')
  57. self.UpdateVertex((x, y))
  58. self.ComputePath()
  59. self.plot_path(self.extract_path_test())
  60. self.fig.canvas.draw_idle()
  61. @staticmethod
  62. def plot_path(path):
  63. px = [x[0] for x in path]
  64. py = [x[1] for x in path]
  65. plt.plot(px, py, marker='o')
  66. def ComputePath(self):
  67. while self.U.top_key() < self.Key(self.xG) or \
  68. self.rhs[self.xG] != self.g[self.xG]:
  69. s = self.U.get()
  70. if self.g[s] > self.rhs[s]:
  71. self.g[s] = self.rhs[s]
  72. for x in self.getSucc(s):
  73. self.UpdateVertex(x)
  74. else:
  75. self.g[s] = float("inf")
  76. self.UpdateVertex(s)
  77. for x in self.getSucc(s):
  78. self.UpdateVertex(x)
  79. def getSucc(self, s):
  80. nei_list = set()
  81. for u in self.u_set:
  82. s_next = tuple([s[i] + u[i] for i in range(2)])
  83. if s_next not in self.obs and self.g[s_next] > self.g[s]:
  84. nei_list.add(s_next)
  85. return nei_list
  86. def getPred(self, s):
  87. nei_list = set()
  88. for u in self.u_set:
  89. s_next = tuple([s[i] + u[i] for i in range(2)])
  90. if s_next not in self.obs and self.g[s_next] < self.g[s]:
  91. nei_list.add(s_next)
  92. return nei_list
  93. def UpdateVertex(self, s):
  94. if s != self.xI:
  95. u_min = float("inf")
  96. for x in self.getPred(s):
  97. u_min = min(u_min, self.g[x] + self.get_cost(x, s))
  98. self.rhs[s] = u_min
  99. self.U.remove(s)
  100. if self.g[s] != self.rhs[s]:
  101. self.U.put(s, self.Key(s))
  102. def print_g(self):
  103. print("he")
  104. for k in range(self.Env.y_range):
  105. j = self.Env.y_range - k - 1
  106. string = ""
  107. for i in range(self.Env.x_range):
  108. if self.g[(i, j)] == float("inf"):
  109. string += ("00" + ', ')
  110. else:
  111. if self.g[(i, j)] // 10 == 0:
  112. string += ("0" + str(self.g[(i, j)]) + ', ')
  113. else:
  114. string += (str(self.g[(i, j)]) + ', ')
  115. print(string)
  116. def extract_path(self):
  117. path = []
  118. s = self.xG
  119. while True:
  120. g_list = {}
  121. for x in self.get_neighbor(s):
  122. g_list[x] = self.g[x]
  123. s = min(g_list, key=g_list.get)
  124. if s == self.xI:
  125. return list(reversed(path))
  126. path.append(s)
  127. def extract_path_test(self):
  128. path = []
  129. s = self.xG
  130. for k in range(100):
  131. g_list = {}
  132. for x in self.get_neighbor(s):
  133. g_list[x] = self.g[x]
  134. s = min(g_list, key=g_list.get)
  135. if s == self.xI:
  136. return list(reversed(path))
  137. path.append(s)
  138. return list(reversed(path))
  139. def get_neighbor(self, s):
  140. nei_list = set()
  141. for u in self.u_set:
  142. s_next = tuple([s[i] + u[i] for i in range(2)])
  143. if s_next not in self.obs:
  144. nei_list.add(s_next)
  145. return nei_list
  146. def Key(self, s):
  147. return [min(self.g[s], self.rhs[s]) + self.h(s),
  148. min(self.g[s], self.rhs[s])]
  149. def h(self, s):
  150. heuristic_type = self.heuristic_type # heuristic type
  151. goal = self.xG # goal node
  152. if heuristic_type == "manhattan":
  153. return abs(goal[0] - s[0]) + abs(goal[1] - s[1])
  154. else:
  155. return math.hypot(goal[0] - s[0], goal[1] - s[1])
  156. @staticmethod
  157. def get_cost(s_start, s_end):
  158. """
  159. Calculate cost for this motion
  160. :param s_start:
  161. :param s_end:
  162. :return: cost for this motion
  163. :note: cost function could be more complicate!
  164. """
  165. return 1
  166. def main():
  167. x_start = (5, 5)
  168. x_goal = (45, 25)
  169. lpastar = LpaStar(x_start, x_goal, "euclidean")
  170. lpastar.searching()
  171. if __name__ == '__main__':
  172. main()