D_star_Lite.py 5.8 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 queue
  12. from Search_2D import plotting
  13. from Search_2D import env
  14. class DStar:
  15. def __init__(self, x_start, x_goal, heuristic_type):
  16. self.xI, self.xG = x_start, x_goal
  17. self.heuristic_type = heuristic_type
  18. self.Env = env.Env() # class Env
  19. self.Plot = plotting.Plotting(x_start, x_goal)
  20. self.u_set = self.Env.motions # feasible input set
  21. self.obs = self.Env.obs # position of obstacles
  22. self.x = self.Env.x_range
  23. self.y = self.Env.y_range
  24. self.U = queue.QueuePrior() # priority queue / U set
  25. self.g, self.rhs = {}, {}
  26. self.km = 0
  27. for i in range(self.Env.x_range):
  28. for j in range(self.Env.y_range):
  29. self.rhs[(i, j)] = float("inf")
  30. self.g[(i, j)] = float("inf")
  31. self.rhs[self.xG] = 0
  32. self.U.put(self.xG, self.Key(self.xG))
  33. self.fig = plt.figure()
  34. def run(self):
  35. self.Plot.plot_grid("Dynamic A* (D*)")
  36. self.ComputePath()
  37. self.plot_path(self.extract_path())
  38. self.fig.canvas.mpl_connect('button_press_event', self.on_press)
  39. plt.show()
  40. def on_press(self, event):
  41. x, y = event.xdata, event.ydata
  42. if x < 0 or x > self.x - 1 or y < 0 or y > self.y - 1:
  43. print("Please choose right area!")
  44. else:
  45. x, y = int(x), int(y)
  46. print("Change position: x =", x, ",", "y =", y)
  47. s_curr = self.xI
  48. s_last = self.xI
  49. i = 0
  50. path = []
  51. while s_curr != self.xG:
  52. s_list = {}
  53. for s in self.get_neighbor(s_curr):
  54. s_list[s] = self.g[s] + self.get_cost(s_curr, s)
  55. s_curr = min(s_list, key=s_list.get)
  56. path.append(s_curr)
  57. if i < 1:
  58. self.km += self.h(s_last, s_curr)
  59. s_last = s_curr
  60. if (x, y) not in self.obs:
  61. self.obs.add((x, y))
  62. plt.plot(x, y, 'sk')
  63. self.g[(x, y)] = float("inf")
  64. self.rhs[(x, y)] = float("inf")
  65. else:
  66. self.obs.remove((x, y))
  67. plt.plot(x, y, marker='s', color='white')
  68. self.UpdateVertex((x, y))
  69. for s in self.get_neighbor((x, y)):
  70. self.UpdateVertex(s)
  71. i += 1
  72. self.ComputePath()
  73. self.plot_path(path)
  74. self.fig.canvas.draw_idle()
  75. @staticmethod
  76. def plot_path(path):
  77. px = [x[0] for x in path]
  78. py = [x[1] for x in path]
  79. plt.plot(px, py, marker='o')
  80. def ComputePath(self):
  81. while self.U.top_key() < self.Key(self.xI) or \
  82. self.rhs[self.xI] != self.g[self.xI]:
  83. k_old = self.U.top_key()
  84. s = self.U.get()
  85. if k_old < self.Key(s):
  86. self.U.put(s, self.Key(s))
  87. elif self.g[s] > self.rhs[s]:
  88. self.g[s] = self.rhs[s]
  89. for x in self.get_neighbor(s):
  90. self.UpdateVertex(x)
  91. else:
  92. self.g[s] = float("inf")
  93. self.UpdateVertex(s)
  94. for x in self.get_neighbor(s):
  95. self.UpdateVertex(x)
  96. def UpdateVertex(self, s):
  97. if s != self.xG:
  98. self.rhs[s] = float("inf")
  99. for x in self.get_neighbor(s):
  100. self.rhs[s] = min(self.rhs[s], self.g[x] + self.get_cost(s, x))
  101. self.U.remove(s)
  102. if self.g[s] != self.rhs[s]:
  103. self.U.put(s, self.Key(s))
  104. def Key(self, s):
  105. return [min(self.g[s], self.rhs[s]) + self.h(self.xI, s) + self.km,
  106. min(self.g[s], self.rhs[s])]
  107. def h(self, s_start, s_goal):
  108. heuristic_type = self.heuristic_type # heuristic type
  109. if heuristic_type == "manhattan":
  110. return abs(s_goal[0] - s_start[0]) + abs(s_goal[1] - s_start[1])
  111. else:
  112. return math.hypot(s_goal[0] - s_start[0], s_goal[1] - s_start[1])
  113. def get_cost(self, s_start, s_end):
  114. if s_start in self.obs or s_end in self.obs:
  115. return float("inf")
  116. return 1
  117. def get_neighbor(self, s):
  118. nei_list = set()
  119. for u in self.u_set:
  120. s_next = tuple([s[i] + u[i] for i in range(2)])
  121. if s_next not in self.obs:
  122. nei_list.add(s_next)
  123. return nei_list
  124. def extract_path(self):
  125. path = []
  126. s = self.xI
  127. count = 0
  128. while True:
  129. count += 1
  130. g_list = {}
  131. for x in self.get_neighbor(s):
  132. g_list[x] = self.g[x]
  133. s = min(g_list, key=g_list.get)
  134. if s == self.xG or count > 100:
  135. return list(reversed(path))
  136. path.append(s)
  137. def print_g(self):
  138. print("he")
  139. for k in range(self.Env.y_range):
  140. j = self.Env.y_range - k - 1
  141. string = ""
  142. for i in range(self.Env.x_range):
  143. if self.g[(i, j)] == float("inf"):
  144. string += ("00" + ', ')
  145. else:
  146. if self.g[(i, j)] // 10 == 0:
  147. string += ("0" + str(self.g[(i, j)]) + ', ')
  148. else:
  149. string += (str(self.g[(i, j)]) + ', ')
  150. print(string)
  151. def main():
  152. x_start = (5, 5)
  153. x_goal = (45, 25)
  154. dstar = DStar(x_start, x_goal, "euclidean")
  155. dstar.run()
  156. if __name__ == '__main__':
  157. main()