D_star_Lite.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. """
  2. D_star_Lite 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 DStar:
  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() # class Env
  18. self.Plot = plotting.Plotting(s_start, s_goal)
  19. self.u_set = self.Env.motions # feasible input set
  20. self.obs = self.Env.obs # position of obstacles
  21. self.x = self.Env.x_range
  22. self.y = self.Env.y_range
  23. self.U = {}
  24. self.g, self.rhs = {}, {}
  25. self.km = 0
  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_goal] = 0
  31. self.U[self.s_goal] = self.CalculateKey(self.s_goal)
  32. self.fig = plt.figure()
  33. def run(self):
  34. self.Plot.plot_grid("Dynamic A* (D*)")
  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. s_curr = self.s_start
  47. s_last = self.s_start
  48. i = 0
  49. path = []
  50. while s_curr != self.s_goal:
  51. s_list = {}
  52. for s in self.get_neighbor(s_curr):
  53. s_list[s] = self.g[s] + self.cost(s_curr, s)
  54. s_curr = min(s_list, key=s_list.get)
  55. path.append(s_curr)
  56. if i < 1:
  57. self.km += self.h(s_last, s_curr)
  58. s_last = s_curr
  59. if (x, y) not in self.obs:
  60. self.obs.add((x, y))
  61. plt.plot(x, y, 'sk')
  62. self.g[(x, y)] = float("inf")
  63. self.rhs[(x, y)] = float("inf")
  64. else:
  65. self.obs.remove((x, y))
  66. plt.plot(x, y, marker='s', color='white')
  67. self.UpdateVertex((x, y))
  68. for s in self.get_neighbor((x, y)):
  69. self.UpdateVertex(s)
  70. i += 1
  71. self.ComputePath()
  72. self.plot_path(path)
  73. self.fig.canvas.draw_idle()
  74. def ComputePath(self):
  75. while True:
  76. s, v = self.TopKey()
  77. if v >= self.CalculateKey(self.s_start) and \
  78. self.rhs[self.s_start] == self.g[self.s_start]:
  79. break
  80. k_old = v
  81. self.U.pop(s)
  82. if k_old < self.CalculateKey(s):
  83. self.U[s] = self.CalculateKey(s)
  84. elif self.g[s] > self.rhs[s]:
  85. self.g[s] = self.rhs[s]
  86. for x in self.get_neighbor(s):
  87. self.UpdateVertex(x)
  88. else:
  89. self.g[s] = float("inf")
  90. self.UpdateVertex(s)
  91. for x in self.get_neighbor(s):
  92. self.UpdateVertex(x)
  93. def UpdateVertex(self, s):
  94. if s != self.s_goal:
  95. self.rhs[s] = float("inf")
  96. for x in self.get_neighbor(s):
  97. self.rhs[s] = min(self.rhs[s], self.g[x] + self.cost(s, x))
  98. if s in self.U:
  99. self.U.pop(s)
  100. if self.g[s] != self.rhs[s]:
  101. self.U[s] = self.CalculateKey(s)
  102. def CalculateKey(self, s):
  103. return [min(self.g[s], self.rhs[s]) + self.h(self.s_start, s) + self.km,
  104. min(self.g[s], self.rhs[s])]
  105. def TopKey(self):
  106. """
  107. :return: return the min key and its value.
  108. """
  109. s = min(self.U, key=self.U.get)
  110. return s, self.U[s]
  111. def h(self, s_start, s_goal):
  112. heuristic_type = self.heuristic_type # heuristic type
  113. if heuristic_type == "manhattan":
  114. return abs(s_goal[0] - s_start[0]) + abs(s_goal[1] - s_start[1])
  115. else:
  116. return math.hypot(s_goal[0] - s_start[0], s_goal[1] - s_start[1])
  117. def cost(self, s_start, s_end):
  118. if s_start in self.obs or s_end in self.obs:
  119. return float("inf")
  120. return 1
  121. def get_neighbor(self, s):
  122. nei_list = set()
  123. for u in self.u_set:
  124. s_next = tuple([s[i] + u[i] for i in range(2)])
  125. if s_next not in self.obs:
  126. nei_list.add(s_next)
  127. return nei_list
  128. def extract_path(self):
  129. path = []
  130. s = self.s_start
  131. count = 0
  132. while True:
  133. count += 1
  134. g_list = {}
  135. for x in self.get_neighbor(s):
  136. g_list[x] = self.g[x]
  137. s = min(g_list, key=g_list.get)
  138. if s == self.s_goal or count > 100:
  139. return list(reversed(path))
  140. path.append(s)
  141. @staticmethod
  142. def plot_path(path):
  143. px = [x[0] for x in path]
  144. py = [x[1] for x in path]
  145. plt.plot(px, py, marker='o')
  146. def main():
  147. s_start = (5, 5)
  148. s_goal = (45, 25)
  149. dstar = DStar(s_start, s_goal, "euclidean")
  150. dstar.run()
  151. if __name__ == '__main__':
  152. main()