LPAstar.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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.U = {}
  24. self.g, self.rhs = {}, {}
  25. for i in range(self.Env.x_range):
  26. for j in range(self.Env.y_range):
  27. self.rhs[(i, j)] = float("inf")
  28. self.g[(i, j)] = float("inf")
  29. self.rhs[self.s_start] = 0
  30. self.U[self.s_start] = self.CalculateKey(self.s_start)
  31. self.fig = plt.figure()
  32. def run(self):
  33. self.Plot.plot_grid("Lifelong Planning A*")
  34. self.ComputePath()
  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: x =", x, ",", "y =", y)
  45. if (x, y) not in self.obs:
  46. self.obs.add((x, y))
  47. plt.plot(x, y, 'sk')
  48. else:
  49. self.obs.remove((x, y))
  50. plt.plot(x, y, marker='s', color='white')
  51. self.UpdateVertex((x, y))
  52. for s_n in self.get_neighbor((x, y)):
  53. self.UpdateVertex(s_n)
  54. self.ComputePath()
  55. self.plot_path(self.extract_path())
  56. self.fig.canvas.draw_idle()
  57. def ComputePath(self):
  58. while True:
  59. s, v = self.TopKey()
  60. if v >= self.CalculateKey(self.s_goal) and \
  61. self.rhs[self.s_goal] == self.g[self.s_goal]:
  62. break
  63. self.U.pop(s)
  64. if self.g[s] > self.rhs[s]: # over-consistent: deleted obstacles
  65. self.g[s] = self.rhs[s]
  66. else: # under-consistent: added obstacles
  67. self.g[s] = float("inf")
  68. self.UpdateVertex(s)
  69. for s_n in self.get_neighbor(s):
  70. self.UpdateVertex(s_n)
  71. def UpdateVertex(self, s):
  72. if s != self.s_start:
  73. self.rhs[s] = min(self.g[s_n] + self.cost(s_n, s)
  74. for s_n in self.get_neighbor(s))
  75. if s in self.U:
  76. self.U.pop(s)
  77. if self.g[s] != self.rhs[s]:
  78. self.U[s] = self.CalculateKey(s)
  79. def TopKey(self):
  80. """
  81. :return: return the min key and its value.
  82. """
  83. s = min(self.U, key=self.U.get)
  84. return s, self.U[s]
  85. def CalculateKey(self, s):
  86. return [min(self.g[s], self.rhs[s]) + self.h(s),
  87. min(self.g[s], self.rhs[s])]
  88. def get_neighbor(self, s):
  89. """
  90. find neighbors of state s that not in obstacles.
  91. :param s: state
  92. :return: neighbors
  93. """
  94. s_list = set()
  95. for u in self.u_set:
  96. s_next = tuple([s[i] + u[i] for i in range(2)])
  97. if s_next not in self.obs:
  98. s_list.add(s_next)
  99. return s_list
  100. def h(self, s):
  101. """
  102. Calculate heuristic.
  103. :param s: current node (state)
  104. :return: heuristic function value
  105. """
  106. heuristic_type = self.heuristic_type # heuristic type
  107. goal = self.s_goal # goal node
  108. if heuristic_type == "manhattan":
  109. return abs(goal[0] - s[0]) + abs(goal[1] - s[1])
  110. else:
  111. return math.hypot(goal[0] - s[0], goal[1] - s[1])
  112. def cost(self, s_start, s_end):
  113. """
  114. calculate edge cost: (s_start, s_end)
  115. :param s_start: start node
  116. :param s_end: end node
  117. :return: cost
  118. """
  119. # if one of the vertex in obstacles: return infinity.
  120. if s_start in self.obs or s_end in self.obs:
  121. return float("inf")
  122. return 1
  123. def extract_path(self):
  124. """
  125. Extract the path based on the PARENT set.
  126. :return: The planning path
  127. """
  128. path = []
  129. s = self.s_goal
  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.s_start:
  136. break
  137. path.append(s)
  138. return list(reversed(path))
  139. @staticmethod
  140. def plot_path(path):
  141. px = [x[0] for x in path]
  142. py = [x[1] for x in path]
  143. plt.plot(px, py, marker='o')
  144. def main():
  145. x_start = (5, 5)
  146. x_goal = (45, 25)
  147. lpastar = LpaStar(x_start, x_goal, "manhattan")
  148. lpastar.run()
  149. if __name__ == '__main__':
  150. main()