D_star_Lite.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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.g, self.rhs, self.U = {}, {}, {}
  24. self.km = 0
  25. for i in range(1, self.Env.x_range - 1):
  26. for j in range(1, self.Env.y_range - 1):
  27. self.rhs[(i, j)] = float("inf")
  28. self.g[(i, j)] = float("inf")
  29. self.rhs[self.s_goal] = 0.0
  30. self.U[self.s_goal] = self.CalculateKey(self.s_goal)
  31. self.visited = set()
  32. self.count = 0
  33. self.fig = plt.figure()
  34. def run(self):
  35. self.Plot.plot_grid("D* Lite")
  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.s_start
  48. s_last = self.s_start
  49. i = 0
  50. path = [self.s_start]
  51. while s_curr != self.s_goal:
  52. s_list = {}
  53. for s in self.get_neighbor(s_curr):
  54. s_list[s] = self.g[s] + self.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.count += 1
  73. self.visited = set()
  74. self.ComputePath()
  75. self.plot_visited(self.visited)
  76. self.plot_path(path)
  77. self.fig.canvas.draw_idle()
  78. def ComputePath(self):
  79. while True:
  80. s, v = self.TopKey()
  81. if v >= self.CalculateKey(self.s_start) and \
  82. self.rhs[self.s_start] == self.g[self.s_start]:
  83. break
  84. k_old = v
  85. self.U.pop(s)
  86. self.visited.add(s)
  87. if k_old < self.CalculateKey(s):
  88. self.U[s] = self.CalculateKey(s)
  89. elif self.g[s] > self.rhs[s]:
  90. self.g[s] = self.rhs[s]
  91. for x in self.get_neighbor(s):
  92. self.UpdateVertex(x)
  93. else:
  94. self.g[s] = float("inf")
  95. self.UpdateVertex(s)
  96. for x in self.get_neighbor(s):
  97. self.UpdateVertex(x)
  98. def UpdateVertex(self, s):
  99. if s != self.s_goal:
  100. self.rhs[s] = float("inf")
  101. for x in self.get_neighbor(s):
  102. self.rhs[s] = min(self.rhs[s], self.g[x] + self.cost(s, x))
  103. if s in self.U:
  104. self.U.pop(s)
  105. if self.g[s] != self.rhs[s]:
  106. self.U[s] = self.CalculateKey(s)
  107. def CalculateKey(self, s):
  108. return [min(self.g[s], self.rhs[s]) + self.h(self.s_start, s) + self.km,
  109. min(self.g[s], self.rhs[s])]
  110. def TopKey(self):
  111. """
  112. :return: return the min key and its value.
  113. """
  114. s = min(self.U, key=self.U.get)
  115. return s, self.U[s]
  116. def h(self, s_start, s_goal):
  117. heuristic_type = self.heuristic_type # heuristic type
  118. if heuristic_type == "manhattan":
  119. return abs(s_goal[0] - s_start[0]) + abs(s_goal[1] - s_start[1])
  120. else:
  121. return math.hypot(s_goal[0] - s_start[0], s_goal[1] - s_start[1])
  122. def cost(self, s_start, s_goal):
  123. """
  124. Calculate cost for this motion
  125. :param s_start: starting node
  126. :param s_goal: end node
  127. :return: cost for this motion
  128. :note: cost function could be more complicate!
  129. """
  130. if self.is_collision(s_start, s_goal):
  131. return float("inf")
  132. return math.hypot(s_goal[0] - s_start[0], s_goal[1] - s_start[1])
  133. def is_collision(self, s_start, s_end):
  134. if s_start in self.obs or s_end in self.obs:
  135. return True
  136. if s_start[0] != s_end[0] and s_start[1] != s_end[1]:
  137. if s_end[0] - s_start[0] == s_start[1] - s_end[1]:
  138. s1 = (min(s_start[0], s_end[0]), min(s_start[1], s_end[1]))
  139. s2 = (max(s_start[0], s_end[0]), max(s_start[1], s_end[1]))
  140. else:
  141. s1 = (min(s_start[0], s_end[0]), max(s_start[1], s_end[1]))
  142. s2 = (max(s_start[0], s_end[0]), min(s_start[1], s_end[1]))
  143. if s1 in self.obs or s2 in self.obs:
  144. return True
  145. return False
  146. def get_neighbor(self, s):
  147. nei_list = set()
  148. for u in self.u_set:
  149. s_next = tuple([s[i] + u[i] for i in range(2)])
  150. if s_next not in self.obs:
  151. nei_list.add(s_next)
  152. return nei_list
  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_start]
  159. s = self.s_start
  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_goal:
  168. break
  169. return list(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. s_start = (5, 5)
  186. s_goal = (45, 25)
  187. dstar = DStar(s_start, s_goal, "euclidean")
  188. dstar.run()
  189. if __name__ == '__main__':
  190. main()