Anytime_D_star.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. """
  2. Anytime_D_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 ADStar:
  14. def __init__(self, s_start, s_goal, eps, 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.OPEN = {}, {}, {}
  24. for i in range(1, self.Env.x_range - 1):
  25. for j in range(1, self.Env.y_range - 1):
  26. self.rhs[(i, j)] = float("inf")
  27. self.g[(i, j)] = float("inf")
  28. self.rhs[self.s_goal] = 0.0
  29. self.eps = eps
  30. self.OPEN[self.s_goal] = self.Key(self.s_goal)
  31. self.CLOSED, self.INCONS = set(), dict()
  32. self.visited = set()
  33. self.count = 0
  34. self.count_env_change = 0
  35. self.obs_add = set()
  36. self.obs_remove = set()
  37. self.title = "Anytime D*: Small changes" # significant changes
  38. self.fig = plt.figure()
  39. def run(self):
  40. self.Plot.plot_grid(self.title)
  41. self.ComputeOrImprovePath()
  42. self.plot_visited()
  43. self.plot_path(self.extract_path())
  44. self.visited = set()
  45. while True:
  46. if self.eps <= 1.0:
  47. break
  48. self.eps -= 0.5
  49. self.OPEN.update(self.INCONS)
  50. for s in self.OPEN:
  51. self.OPEN[s] = self.Key(s)
  52. self.CLOSED = set()
  53. self.ComputeOrImprovePath()
  54. self.plot_visited()
  55. self.plot_path(self.extract_path())
  56. self.visited = set()
  57. plt.pause(0.5)
  58. self.fig.canvas.mpl_connect('button_press_event', self.on_press)
  59. plt.show()
  60. def on_press(self, event):
  61. x, y = event.xdata, event.ydata
  62. if x < 0 or x > self.x - 1 or y < 0 or y > self.y - 1:
  63. print("Please choose right area!")
  64. else:
  65. self.count_env_change += 1
  66. x, y = int(x), int(y)
  67. print("Change position: x =", x, ",", "y =", y)
  68. # for small changes
  69. if self.title == "Anytime D*: Small changes":
  70. if (x, y) not in self.obs:
  71. self.obs.add((x, y))
  72. plt.plot(x, y, 'sk')
  73. self.g[(x, y)] = float("inf")
  74. self.rhs[(x, y)] = float("inf")
  75. else:
  76. self.obs.remove((x, y))
  77. plt.plot(x, y, marker='s', color='white')
  78. self.UpdateState((x, y))
  79. for sn in self.get_neighbor((x, y)):
  80. self.UpdateState(sn)
  81. while True:
  82. if len(self.INCONS) == 0:
  83. break
  84. self.OPEN.update(self.INCONS)
  85. for s in self.OPEN:
  86. self.OPEN[s] = self.Key(s)
  87. self.CLOSED = set()
  88. self.ComputeOrImprovePath()
  89. self.plot_visited()
  90. self.plot_path(self.extract_path())
  91. # plt.plot(self.title)
  92. self.visited = set()
  93. if self.eps <= 1.0:
  94. break
  95. else:
  96. if (x, y) not in self.obs:
  97. self.obs.add((x, y))
  98. self.obs_add.add((x, y))
  99. plt.plot(x, y, 'sk')
  100. if (x, y) in self.obs_remove:
  101. self.obs_remove.remove((x, y))
  102. else:
  103. self.obs.remove((x, y))
  104. self.obs_remove.add((x, y))
  105. plt.plot(x, y, marker='s', color='white')
  106. if (x, y) in self.obs_add:
  107. self.obs_add.remove((x, y))
  108. if self.count_env_change >= 15:
  109. self.count_env_change = 0
  110. self.eps += 2.0
  111. for s in self.obs_add:
  112. self.g[(x, y)] = float("inf")
  113. self.rhs[(x, y)] = float("inf")
  114. for sn in self.get_neighbor(s):
  115. self.UpdateState(sn)
  116. for s in self.obs_remove:
  117. for sn in self.get_neighbor(s):
  118. self.UpdateState(sn)
  119. self.UpdateState(s)
  120. while True:
  121. if self.eps <= 1.0:
  122. break
  123. self.eps -= 0.5
  124. self.OPEN.update(self.INCONS)
  125. for s in self.OPEN:
  126. self.OPEN[s] = self.Key(s)
  127. self.CLOSED = set()
  128. self.ComputeOrImprovePath()
  129. self.plot_visited()
  130. self.plot_path(self.extract_path())
  131. plt.title(self.title)
  132. self.visited = set()
  133. plt.pause(0.5)
  134. self.fig.canvas.draw_idle()
  135. def ComputeOrImprovePath(self):
  136. while True:
  137. s, v = self.TopKey()
  138. if v >= self.Key(self.s_start) and \
  139. self.rhs[self.s_start] == self.g[self.s_start]:
  140. break
  141. self.OPEN.pop(s)
  142. self.visited.add(s)
  143. if self.g[s] > self.rhs[s]:
  144. self.g[s] = self.rhs[s]
  145. self.CLOSED.add(s)
  146. for sn in self.get_neighbor(s):
  147. self.UpdateState(sn)
  148. else:
  149. self.g[s] = float("inf")
  150. for sn in self.get_neighbor(s):
  151. self.UpdateState(sn)
  152. self.UpdateState(s)
  153. def UpdateState(self, s):
  154. if s != self.s_goal:
  155. self.rhs[s] = float("inf")
  156. for x in self.get_neighbor(s):
  157. self.rhs[s] = min(self.rhs[s], self.g[x] + self.cost(s, x))
  158. if s in self.OPEN:
  159. self.OPEN.pop(s)
  160. if self.g[s] != self.rhs[s]:
  161. if s not in self.CLOSED:
  162. self.OPEN[s] = self.Key(s)
  163. else:
  164. self.INCONS[s] = 0
  165. def Key(self, s):
  166. if self.g[s] > self.rhs[s]:
  167. return [self.rhs[s] + self.eps * self.h(self.s_start, s), self.rhs[s]]
  168. else:
  169. return [self.g[s] + self.h(self.s_start, s), self.g[s]]
  170. def TopKey(self):
  171. """
  172. :return: return the min key and its value.
  173. """
  174. s = min(self.OPEN, key=self.OPEN.get)
  175. return s, self.OPEN[s]
  176. def h(self, s_start, s_goal):
  177. heuristic_type = self.heuristic_type # heuristic type
  178. if heuristic_type == "manhattan":
  179. return abs(s_goal[0] - s_start[0]) + abs(s_goal[1] - s_start[1])
  180. else:
  181. return math.hypot(s_goal[0] - s_start[0], s_goal[1] - s_start[1])
  182. def cost(self, s_start, s_goal):
  183. """
  184. Calculate cost for this motion
  185. :param s_start: starting node
  186. :param s_goal: end node
  187. :return: cost for this motion
  188. :note: cost function could be more complicate!
  189. """
  190. if self.is_collision(s_start, s_goal):
  191. return float("inf")
  192. return math.hypot(s_goal[0] - s_start[0], s_goal[1] - s_start[1])
  193. def is_collision(self, s_start, s_end):
  194. if s_start in self.obs or s_end in self.obs:
  195. return True
  196. if s_start[0] != s_end[0] and s_start[1] != s_end[1]:
  197. if s_end[0] - s_start[0] == s_start[1] - s_end[1]:
  198. s1 = (min(s_start[0], s_end[0]), min(s_start[1], s_end[1]))
  199. s2 = (max(s_start[0], s_end[0]), max(s_start[1], s_end[1]))
  200. else:
  201. s1 = (min(s_start[0], s_end[0]), max(s_start[1], s_end[1]))
  202. s2 = (max(s_start[0], s_end[0]), min(s_start[1], s_end[1]))
  203. if s1 in self.obs or s2 in self.obs:
  204. return True
  205. return False
  206. def get_neighbor(self, s):
  207. nei_list = set()
  208. for u in self.u_set:
  209. s_next = tuple([s[i] + u[i] for i in range(2)])
  210. if s_next not in self.obs:
  211. nei_list.add(s_next)
  212. return nei_list
  213. def extract_path(self):
  214. """
  215. Extract the path based on the PARENT set.
  216. :return: The planning path
  217. """
  218. path = [self.s_start]
  219. s = self.s_start
  220. for k in range(100):
  221. g_list = {}
  222. for x in self.get_neighbor(s):
  223. if not self.is_collision(s, x):
  224. g_list[x] = self.g[x]
  225. s = min(g_list, key=g_list.get)
  226. path.append(s)
  227. if s == self.s_goal:
  228. break
  229. return list(path)
  230. def plot_path(self, path):
  231. px = [x[0] for x in path]
  232. py = [x[1] for x in path]
  233. plt.plot(px, py, linewidth=2)
  234. plt.plot(self.s_start[0], self.s_start[1], "bs")
  235. plt.plot(self.s_goal[0], self.s_goal[1], "gs")
  236. def plot_visited(self):
  237. self.count += 1
  238. color = ['gainsboro', 'lightgray', 'silver', 'darkgray',
  239. 'bisque', 'navajowhite', 'moccasin', 'wheat',
  240. 'powderblue', 'skyblue', 'lightskyblue', 'cornflowerblue']
  241. if self.count >= len(color) - 1:
  242. self.count = 0
  243. for x in self.visited:
  244. plt.plot(x[0], x[1], marker='s', color=color[self.count])
  245. def main():
  246. s_start = (5, 5)
  247. s_goal = (45, 25)
  248. dstar = ADStar(s_start, s_goal, 2.5, "euclidean")
  249. dstar.run()
  250. if __name__ == '__main__':
  251. main()