Field_D_star.py 9.0 KB

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