LPAstar.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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.s_start, self.s_goal = x_start, x_goal
  17. self.heuristic_type = heuristic_type
  18. self.Env = env.Env()
  19. self.Plot = plotting.Plotting(x_start, x_goal)
  20. self.u_set = self.Env.motions
  21. self.obs = self.Env.obs
  22. self.x = self.Env.x_range
  23. self.y = self.Env.y_range
  24. self.U = queue.QueuePrior()
  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.s_start] = 0
  31. self.U.put(self.s_start, self.Key(self.s_start))
  32. self.fig = plt.figure()
  33. def run(self):
  34. self.Plot.plot_grid("Lifelong Planning A*")
  35. self.ComputePath()
  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: x =", x, ",", "y =", y)
  46. if (x, y) not in self.obs:
  47. self.obs.add((x, y))
  48. plt.plot(x, y, 'sk')
  49. else:
  50. self.obs.remove((x, y))
  51. plt.plot(x, y, marker='s', color='white')
  52. self.UpdateVertex((x, y))
  53. for s_n in self.get_neighbor((x, y)):
  54. self.UpdateVertex(s_n)
  55. self.ComputePath()
  56. self.plot_path(self.extract_path())
  57. self.fig.canvas.draw_idle()
  58. def ComputePath(self):
  59. while self.U.top_key() < self.Key(self.s_goal) or \
  60. self.rhs[self.s_goal] != self.g[self.s_goal]:
  61. s = self.U.get()
  62. if self.g[s] > self.rhs[s]: # over-consistent: deleted obstacles
  63. self.g[s] = self.rhs[s]
  64. else: # under-consistent: added obstacles
  65. self.g[s] = float("inf")
  66. self.UpdateVertex(s)
  67. for s_n in self.get_neighbor(s):
  68. self.UpdateVertex(s_n)
  69. def UpdateVertex(self, s):
  70. if s != self.s_start:
  71. self.rhs[s] = min([self.g[s_n] + self.cost(s_n, s)
  72. for s_n in self.get_neighbor(s)])
  73. self.U.remove(s)
  74. if self.g[s] != self.rhs[s]:
  75. self.U.put(s, self.Key(s))
  76. def get_neighbor(self, s):
  77. """
  78. find neighbors of state s that not in obstacles.
  79. :param s: state
  80. :return: neighbors
  81. """
  82. s_list = set()
  83. for u in self.u_set:
  84. s_next = tuple([s[i] + u[i] for i in range(2)])
  85. if s_next not in self.obs:
  86. s_list.add(s_next)
  87. return s_list
  88. def Key(self, s):
  89. return [min(self.g[s], self.rhs[s]) + self.h(s),
  90. min(self.g[s], self.rhs[s])]
  91. def h(self, s):
  92. heuristic_type = self.heuristic_type # heuristic type
  93. goal = self.s_goal # goal node
  94. if heuristic_type == "manhattan":
  95. return abs(goal[0] - s[0]) + abs(goal[1] - s[1])
  96. else:
  97. return math.hypot(goal[0] - s[0], goal[1] - s[1])
  98. def cost(self, s_start, s_end):
  99. if s_start in self.obs or s_end in self.obs:
  100. return float("inf")
  101. return 1
  102. def extract_path(self):
  103. path = []
  104. s = self.s_goal
  105. for k in range(100):
  106. g_list = {}
  107. for x in self.get_neighbor(s):
  108. g_list[x] = self.g[x]
  109. s = min(g_list, key=g_list.get)
  110. if s == self.s_start:
  111. break
  112. path.append(s)
  113. return list(reversed(path))
  114. @staticmethod
  115. def plot_path(path):
  116. px = [x[0] for x in path]
  117. py = [x[1] for x in path]
  118. plt.plot(px, py, marker='o')
  119. def print_g(self):
  120. print("he")
  121. for k in range(self.Env.y_range):
  122. j = self.Env.y_range - k - 1
  123. string = ""
  124. for i in range(self.Env.x_range):
  125. if self.g[(i, j)] == float("inf"):
  126. string += ("00" + ', ')
  127. else:
  128. if self.g[(i, j)] // 10 == 0:
  129. string += ("0" + str(self.g[(i, j)]) + ', ')
  130. else:
  131. string += (str(self.g[(i, j)]) + ', ')
  132. print(string)
  133. def main():
  134. x_start = (5, 5)
  135. x_goal = (45, 25)
  136. lpastar = LpaStar(x_start, x_goal, "manhattan")
  137. lpastar.run()
  138. if __name__ == '__main__':
  139. main()