LPAstar.py 7.2 KB

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