Field_D_star.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. """
  2. Field D* 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 FieldDStar:
  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.parent = {}
  25. for i in range(self.Env.x_range):
  26. for j in range(self.Env.y_range):
  27. self.rhs[(i, j)] = float("inf")
  28. self.g[(i, j)] = float("inf")
  29. self.parent[(i, j)] = (0, 0)
  30. self.rhs[self.s_goal] = 0.0
  31. self.U[self.s_goal] = self.CalculateKey(self.s_goal)
  32. self.visited = set()
  33. self.count = 0
  34. self.fig = plt.figure()
  35. def run(self):
  36. self.Plot.plot_grid("Field D*")
  37. self.ComputeShortestPath()
  38. self.plot_path(self.extract_path())
  39. self.fig.canvas.mpl_connect('button_press_event', self.on_press)
  40. plt.show()
  41. def on_press(self, event):
  42. x, y = event.xdata, event.ydata
  43. if x < 0 or x > self.x - 1 or y < 0 or y > self.y - 1:
  44. print("Please choose right area!")
  45. else:
  46. x, y = int(x), int(y)
  47. print("Change position: x =", x, ",", "y =", y)
  48. self.visited = set()
  49. self.count += 1
  50. if (x, y) not in self.obs:
  51. self.obs.add((x, y))
  52. plt.plot(x, y, 'sk')
  53. else:
  54. self.obs.remove((x, y))
  55. plt.plot(x, y, marker='s', color='white')
  56. self.UpdateVertex((x, y))
  57. for s_n in self.get_neighbor((x, y)):
  58. self.UpdateVertex(s_n)
  59. self.ComputeShortestPath()
  60. self.plot_visited(self.visited)
  61. self.plot_path(self.extract_path())
  62. self.fig.canvas.draw_idle()
  63. def ComputeShortestPath(self):
  64. while True:
  65. s, v = self.TopKey()
  66. if v >= self.CalculateKey(self.s_start) and \
  67. self.rhs[self.s_start] == self.g[self.s_start]:
  68. break
  69. k_old = v
  70. self.U.pop(s)
  71. self.visited.add(s)
  72. if k_old < self.CalculateKey(s):
  73. self.U[s] = self.CalculateKey(s)
  74. elif self.g[s] > self.rhs[s]:
  75. self.g[s] = self.rhs[s]
  76. for x in self.get_neighbor(s):
  77. self.UpdateVertex(x)
  78. else:
  79. self.g[s] = float("inf")
  80. self.UpdateVertex(s)
  81. for x in self.get_neighbor(s):
  82. self.UpdateVertex(x)
  83. def UpdateVertex(self, s):
  84. if s != self.s_goal:
  85. value = []
  86. s_plist = []
  87. sn_list = self.get_neighbor_pure(s)
  88. sn_list.append(sn_list[0])
  89. for k in range(8):
  90. v, sp = self.ComputeCost(s, sn_list[k], sn_list[k + 1])
  91. value.append(v)
  92. s_plist.append(sp)
  93. self.rhs[s] = min(value)
  94. self.parent[s] = s_plist[value.index(min(value))]
  95. if s in self.U:
  96. self.U.pop(s)
  97. if self.g[s] != self.rhs[s]:
  98. self.U[s] = self.CalculateKey(s)
  99. def get_neighbor_pure(self, s):
  100. s_list = []
  101. for u in self.u_set:
  102. s_next = tuple([s[i] + u[i] for i in range(2)])
  103. s_list.append(s_next)
  104. return s_list
  105. def CalculateKey(self, s):
  106. return [min(self.g[s], self.rhs[s]) + self.h(self.s_start, s),
  107. min(self.g[s], self.rhs[s])]
  108. def ComputeCost(self, s, sa, sb):
  109. if sa[0] != s[0] and sa[1] != s[1]:
  110. s1, s2 = sb, sa
  111. else:
  112. s1, s2 = sa, sb
  113. c = self.cost(s, s2)
  114. b = self.cost(s, s1)
  115. y = 0
  116. if min(c, b) == float("inf"):
  117. vs = float("inf")
  118. elif self.g[s1] <= self.g[s2]:
  119. vs = min(c, b) + self.g[s1]
  120. else:
  121. f = self.g[s1] - self.g[s2]
  122. if f <= b:
  123. if c <= f:
  124. vs = math.sqrt(2) * c + self.g[s2]
  125. else:
  126. y = min(f / (math.sqrt(c ** 2 - f ** 2)), 1)
  127. vs = c * math.sqrt(1 + y ** 2) + f * (1 - y) + self.g[s2]
  128. else:
  129. if c <= b:
  130. vs = math.sqrt(2) * c + self.g[s2]
  131. else:
  132. x = 1 - min(b / (math.sqrt(c ** 2 - b ** 2)), 1)
  133. vs = c * math.sqrt(1 + (1 - x) ** 2) + b * x + self.g[s2]
  134. ss = (y * s1[0] + (1 - y) * s2[0], y * s1[1] + (1 - y) * s2[1])
  135. return vs, ss
  136. def TopKey(self):
  137. """
  138. :return: return the min key and its value.
  139. """
  140. s = min(self.U, key=self.U.get)
  141. return s, self.U[s]
  142. def h(self, s_start, s_goal):
  143. heuristic_type = self.heuristic_type # heuristic type
  144. if heuristic_type == "manhattan":
  145. return abs(s_goal[0] - s_start[0]) + abs(s_goal[1] - s_start[1])
  146. else:
  147. return math.hypot(s_goal[0] - s_start[0], s_goal[1] - s_start[1])
  148. def cost(self, s_start, s_goal):
  149. """
  150. Calculate cost for this motion
  151. :param s_start: starting node
  152. :param s_goal: end node
  153. :return: cost for this motion
  154. :note: cost function could be more complicate!
  155. """
  156. if self.is_collision(s_start, s_goal):
  157. return float("inf")
  158. return math.hypot(s_goal[0] - s_start[0], s_goal[1] - s_start[1])
  159. def is_collision(self, s_start, s_end):
  160. if s_start in self.obs or s_end in self.obs:
  161. return True
  162. if s_start[0] != s_end[0] and s_start[1] != s_end[1]:
  163. if s_end[0] - s_start[0] == s_start[1] - s_end[1]:
  164. s1 = (min(s_start[0], s_end[0]), min(s_start[1], s_end[1]))
  165. s2 = (max(s_start[0], s_end[0]), max(s_start[1], s_end[1]))
  166. else:
  167. s1 = (min(s_start[0], s_end[0]), max(s_start[1], s_end[1]))
  168. s2 = (max(s_start[0], s_end[0]), min(s_start[1], s_end[1]))
  169. if s1 in self.obs or s2 in self.obs:
  170. return True
  171. return False
  172. def get_neighbor(self, s):
  173. s_list = []
  174. for u in self.u_set:
  175. s_next = tuple([s[i] + u[i] for i in range(2)])
  176. if s_next not in self.obs:
  177. s_list.append(s_next)
  178. return s_list
  179. def extract_path(self):
  180. path = [self.s_start]
  181. s = self.s_start
  182. count = 0
  183. while True:
  184. count += 1
  185. g_list = {}
  186. for x in self.get_neighbor(s):
  187. if not self.is_collision(s, x):
  188. g_list[x] = self.g[x]
  189. ss = self.parent[s]
  190. s = min(g_list, key=g_list.get)
  191. path.append(s)
  192. if s == self.s_goal or count > 100:
  193. return list(reversed(path))
  194. def plot_path(self, path):
  195. px = [x[0] for x in path]
  196. py = [x[1] for x in path]
  197. plt.plot(px, py, linewidth=2)
  198. plt.plot(self.s_start[0], self.s_start[1], "bs")
  199. plt.plot(self.s_goal[0], self.s_goal[1], "gs")
  200. def plot_visited(self, visited):
  201. color = ['gainsboro', 'lightgray', 'silver', 'darkgray',
  202. 'bisque', 'navajowhite', 'moccasin', 'wheat',
  203. 'powderblue', 'skyblue', 'lightskyblue', 'cornflowerblue']
  204. if self.count >= len(color) - 1:
  205. self.count = 0
  206. for x in visited:
  207. plt.plot(x[0], x[1], marker='s', color=color[self.count])
  208. def main():
  209. s_start = (5, 5)
  210. s_goal = (45, 25)
  211. fielddstar = FieldDStar(s_start, s_goal, "euclidean")
  212. fielddstar.run()
  213. if __name__ == '__main__':
  214. main()