LPAstar.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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 plotting
  12. from Search_2D import env
  13. class LpaStar:
  14. def __init__(self, s_start, s_goal, heuristic_type):
  15. self.s_start, self.s_goal = s_start, s_goal
  16. self.heuristic_type = heuristic_type
  17. self.Env = env.Env()
  18. self.Plot = plotting.Plotting(self.s_start, self.s_goal)
  19. self.u_set = self.Env.motions
  20. self.obs = self.Env.obs
  21. self.x = self.Env.x_range
  22. self.y = self.Env.y_range
  23. self.g, self.rhs, self.U = {}, {}, {}
  24. for i in range(self.Env.x_range):
  25. for j in range(self.Env.y_range):
  26. self.rhs[(i, j)] = float("inf")
  27. self.g[(i, j)] = float("inf")
  28. self.rhs[self.s_start] = 0
  29. self.U[self.s_start] = self.CalculateKey(self.s_start)
  30. self.visited = set()
  31. self.count = 0
  32. self.fig = plt.figure()
  33. def run(self):
  34. self.Plot.plot_grid("Lifelong Planning A*")
  35. self.ComputeShortestPath()
  36. self.plot_path(self.extract_path())
  37. self.fig.canvas.mpl_connect('button_press_event', self.on_press)
  38. plt.show()
  39. def on_press(self, event):
  40. x, y = event.xdata, event.ydata
  41. if x < 0 or x > self.x - 1 or y < 0 or y > self.y - 1:
  42. print("Please choose right area!")
  43. else:
  44. x, y = int(x), int(y)
  45. print("Change position: s =", x, ",", "y =", y)
  46. self.visited = set()
  47. self.count += 1
  48. if (x, y) not in self.obs:
  49. self.obs.add((x, y))
  50. plt.plot(x, y, 'sk')
  51. else:
  52. self.obs.remove((x, y))
  53. plt.plot(x, y, marker='s', color='white')
  54. self.UpdateVertex((x, y))
  55. for s_n in self.get_neighbor((x, y)):
  56. self.UpdateVertex(s_n)
  57. self.ComputeShortestPath()
  58. self.plot_visited(self.visited)
  59. self.plot_path(self.extract_path())
  60. self.fig.canvas.draw_idle()
  61. def ComputeShortestPath(self):
  62. while True:
  63. s, v = self.TopKey()
  64. if v >= self.CalculateKey(self.s_goal) and \
  65. self.rhs[self.s_goal] == self.g[self.s_goal]:
  66. break
  67. self.U.pop(s)
  68. self.visited.add(s)
  69. if self.g[s] > self.rhs[s]: # over-consistent: deleted obstacles
  70. self.g[s] = self.rhs[s]
  71. else: # under-consistent: added obstacles
  72. self.g[s] = float("inf")
  73. self.UpdateVertex(s)
  74. for s_n in self.get_neighbor(s):
  75. self.UpdateVertex(s_n)
  76. def UpdateVertex(self, s):
  77. if s != self.s_start:
  78. self.rhs[s] = min(self.g[s_n] + self.cost(s_n, s)
  79. for s_n in self.get_neighbor(s))
  80. if s in self.U:
  81. self.U.pop(s)
  82. if self.g[s] != self.rhs[s]:
  83. self.U[s] = self.CalculateKey(s)
  84. def TopKey(self):
  85. """
  86. :return: return the min key and its value.
  87. """
  88. s = min(self.U, key=self.U.get)
  89. return s, self.U[s]
  90. def CalculateKey(self, s):
  91. return [min(self.g[s], self.rhs[s]) + self.h(s),
  92. min(self.g[s], self.rhs[s])]
  93. def get_neighbor(self, s):
  94. """
  95. find neighbors of state s that not in obstacles.
  96. :param s: state
  97. :return: neighbors
  98. """
  99. s_list = set()
  100. for u in self.u_set:
  101. s_next = tuple([s[i] + u[i] for i in range(2)])
  102. if s_next not in self.obs:
  103. s_list.add(s_next)
  104. return s_list
  105. def h(self, s):
  106. """
  107. Calculate heuristic.
  108. :param s: current node (state)
  109. :return: heuristic function value
  110. """
  111. heuristic_type = self.heuristic_type # heuristic type
  112. goal = self.s_goal # goal node
  113. if heuristic_type == "manhattan":
  114. return abs(goal[0] - s[0]) + abs(goal[1] - s[1])
  115. else:
  116. return math.hypot(goal[0] - s[0], goal[1] - s[1])
  117. def cost(self, s_start, s_goal):
  118. """
  119. Calculate Cost for this motion
  120. :param s_start: starting node
  121. :param s_goal: end node
  122. :return: Cost for this motion
  123. :note: Cost function could be more complicate!
  124. """
  125. if self.is_collision(s_start, s_goal):
  126. return float("inf")
  127. return math.hypot(s_goal[0] - s_start[0], s_goal[1] - s_start[1])
  128. def is_collision(self, s_start, s_end):
  129. if s_start in self.obs or s_end in self.obs:
  130. return True
  131. if s_start[0] != s_end[0] and s_start[1] != s_end[1]:
  132. if s_end[0] - s_start[0] == s_start[1] - s_end[1]:
  133. s1 = (min(s_start[0], s_end[0]), min(s_start[1], s_end[1]))
  134. s2 = (max(s_start[0], s_end[0]), max(s_start[1], s_end[1]))
  135. else:
  136. s1 = (min(s_start[0], s_end[0]), max(s_start[1], s_end[1]))
  137. s2 = (max(s_start[0], s_end[0]), min(s_start[1], s_end[1]))
  138. if s1 in self.obs or s2 in self.obs:
  139. return True
  140. return False
  141. def extract_path(self):
  142. """
  143. Extract the path based on the PARENT set.
  144. :return: The planning path
  145. """
  146. path = [self.s_goal]
  147. s = self.s_goal
  148. for k in range(100):
  149. g_list = {}
  150. for x in self.get_neighbor(s):
  151. if not self.is_collision(s, x):
  152. g_list[x] = self.g[x]
  153. s = min(g_list, key=g_list.get)
  154. path.append(s)
  155. if s == self.s_start:
  156. break
  157. return list(reversed(path))
  158. def plot_path(self, path):
  159. px = [x[0] for x in path]
  160. py = [x[1] for x in path]
  161. plt.plot(px, py, linewidth=2)
  162. plt.plot(self.s_start[0], self.s_start[1], "bs")
  163. plt.plot(self.s_goal[0], self.s_goal[1], "gs")
  164. def plot_visited(self, visited):
  165. color = ['gainsboro', 'lightgray', 'silver', 'darkgray',
  166. 'bisque', 'navajowhite', 'moccasin', 'wheat',
  167. 'powderblue', 'skyblue', 'lightskyblue', 'cornflowerblue']
  168. if self.count >= len(color) - 1:
  169. self.count = 0
  170. for x in visited:
  171. plt.plot(x[0], x[1], marker='s', color=color[self.count])
  172. def main():
  173. x_start = (5, 5)
  174. x_goal = (45, 25)
  175. lpastar = LpaStar(x_start, x_goal, "Euclidean")
  176. lpastar.run()
  177. if __name__ == '__main__':
  178. main()