Anytime_Dstar3D.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. # check paper of
  2. # [Likhachev2005]
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. import os
  6. import sys
  7. from collections import defaultdict
  8. sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../../Search-based Planning/")
  9. from Search_3D.env3D import env
  10. from Search_3D.utils3D import getDist, heuristic_fun, getNearest, isinbound, \
  11. cost, children, StateSpace
  12. from Search_3D.plot_util3D import visualization
  13. from Search_3D import queue
  14. import time
  15. class Anytime_Dstar(object):
  16. def __init__(self, resolution=1):
  17. self.Alldirec = {(1, 0, 0): 1, (0, 1, 0): 1, (0, 0, 1): 1, \
  18. (-1, 0, 0): 1, (0, -1, 0): 1, (0, 0, -1): 1, \
  19. (1, 1, 0): np.sqrt(2), (1, 0, 1): np.sqrt(2), (0, 1, 1): np.sqrt(2), \
  20. (-1, -1, 0): np.sqrt(2), (-1, 0, -1): np.sqrt(2), (0, -1, -1): np.sqrt(2), \
  21. (1, -1, 0): np.sqrt(2), (-1, 1, 0): np.sqrt(2), (1, 0, -1): np.sqrt(2), \
  22. (-1, 0, 1): np.sqrt(2), (0, 1, -1): np.sqrt(2), (0, -1, 1): np.sqrt(2), \
  23. (1, 1, 1): np.sqrt(3), (-1, -1, -1) : np.sqrt(3), \
  24. (1, -1, -1): np.sqrt(3), (-1, 1, -1): np.sqrt(3), (-1, -1, 1): np.sqrt(3), \
  25. (1, 1, -1): np.sqrt(3), (1, -1, 1): np.sqrt(3), (-1, 1, 1): np.sqrt(3)}
  26. self.env = env(resolution=resolution)
  27. self.settings = 'CollisionChecking' # for collision checking
  28. self.x0, self.xt = tuple(self.env.start), tuple(self.env.goal)
  29. self.OPEN = queue.MinheapPQ()
  30. self.g = {} # all g initialized at inf
  31. self.h = {}
  32. self.rhs = {self.xt:0} # rhs(x0) = 0
  33. self.OPEN.put(self.xt, self.key(self.xt))
  34. self.INCONS = set()
  35. self.CLOSED = set()
  36. # init children set:
  37. self.CHILDREN = {}
  38. # init cost set
  39. self.COST = defaultdict(lambda: defaultdict(dict))
  40. # for visualization
  41. self.V = set() # vertice in closed
  42. self.ind = 0
  43. self.Path = []
  44. self.done = False
  45. # epsilon in the key caculation
  46. self.epsilon = 1
  47. self.increment = 0.1
  48. self.decrement = 0.2
  49. def getcost(self, xi, xj):
  50. # use a LUT for getting the costd
  51. if xi not in self.COST:
  52. for (xj,xjcost) in children(self, xi, settings=1):
  53. self.COST[xi][xj] = cost(self, xi, xj, xjcost)
  54. # this might happen when there is a node changed.
  55. if xj not in self.COST[xi]:
  56. self.COST[xi][xj] = cost(self, xi, xj)
  57. return self.COST[xi][xj]
  58. def getchildren(self, xi):
  59. if xi not in self.CHILDREN:
  60. allchild = children(self, xi)
  61. self.CHILDREN[xi] = set(allchild)
  62. return self.CHILDREN[xi]
  63. def geth(self, xi):
  64. # when the heurisitic is first calculated
  65. if xi not in self.h:
  66. self.h[xi] = heuristic_fun(self, xi, self.x0)
  67. return self.h[xi]
  68. def getg(self, xi):
  69. if xi not in self.g:
  70. self.g[xi] = np.inf
  71. return self.g[xi]
  72. def getrhs(self, xi):
  73. if xi not in self.rhs:
  74. self.rhs[xi] = np.inf
  75. return self.rhs[xi]
  76. def updatecost(self,range_changed=None, new=None, old=None, mode=False):
  77. # scan graph for changed cost, if cost is changed update it
  78. CHANGED = set()
  79. for xi in self.CLOSED:
  80. if xi in self.CHILDREN:
  81. oldchildren = self.CHILDREN[xi]# A
  82. if isinbound(old, xi, mode) or isinbound(new, xi, mode):
  83. newchildren = set(children(self,xi))# B
  84. removed = oldchildren.difference(newchildren)
  85. intersection = oldchildren.intersection(newchildren)
  86. added = newchildren.difference(oldchildren)
  87. for xj in removed:
  88. self.COST[xi][xj] = cost(self, xi, xj)
  89. for xj in intersection.union(added):
  90. self.COST[xi][xj] = cost(self, xi, xj)
  91. CHANGED.add(xi)
  92. else:
  93. if isinbound(old, xi, mode) or isinbound(new, xi, mode):
  94. CHANGED.add(xi)
  95. children_added = set(children(self,xi))
  96. self.CHILDREN[xi] = children_added
  97. for xj in children_added:
  98. self.COST[xi][xj] = cost(self, xi, xj)
  99. return CHANGED
  100. #--------------main functions for Anytime D star
  101. def key(self, s, epsilon=1):
  102. if self.getg(s) > self.getrhs(s):
  103. return [self.rhs[s] + epsilon * heuristic_fun(self, s, self.x0), self.rhs[s]]
  104. else:
  105. return [self.getg(s) + heuristic_fun(self, s, self.x0), self.getg(s)]
  106. def UpdateState(self, s):
  107. if s not in self.CLOSED:
  108. # TODO if s is not visited before
  109. self.g[s] = np.inf
  110. if s != self.xt:
  111. self.rhs[s] = min([self.getcost(s, s_p) + self.getg(s_p) for s_p in self.getchildren(s)])
  112. self.OPEN.check_remove(s)
  113. if self.getg(s) != self.getrhs(s):
  114. if s not in self.CLOSED:
  115. self.OPEN.put(s, self.key(s))
  116. else:
  117. self.INCONS.add(s)
  118. def ComputeorImprovePath(self):
  119. while self.OPEN.top_key() < self.key(self.x0,self.epsilon) or self.rhs[self.x0] != self.g[self.x0]:
  120. s = self.OPEN.get()
  121. if getDist(s, tuple(self.env.start)) < self.env.resolution:
  122. break
  123. if self.g[s] > self.rhs[s]:
  124. self.g[s] = self.rhs[s]
  125. self.CLOSED.add(s)
  126. self.V.add(s)
  127. for s_p in self.getchildren(s):
  128. self.UpdateState(s_p)
  129. else:
  130. self.g[s] = np.inf
  131. self.UpdateState(s)
  132. for s_p in self.getchildren(s):
  133. self.UpdateState(s_p)
  134. self.ind += 1
  135. def Main(self):
  136. ischanged = False
  137. islargelychanged = False
  138. t = 0
  139. self.ComputeorImprovePath()
  140. #TODO publish current epsilon sub-optimal solution
  141. self.done = True
  142. self.ind = 0
  143. self.Path = self.path()
  144. visualization(self)
  145. while True:
  146. visualization(self)
  147. if t == 20:
  148. break
  149. # change environment
  150. # new2,old2 = self.env.move_block(theta = [0,0,0.1*t], mode='rotation')
  151. new2,old2 = self.env.move_block(a = [0,0,-0.2], mode='translation')
  152. ischanged = True
  153. # islargelychanged = True
  154. self.Path = []
  155. # update cost with changed environment
  156. if ischanged:
  157. # CHANGED = self.updatecost(True, new2, old2, mode='obb')
  158. CHANGED = self.updatecost(True, new2, old2)
  159. for u in CHANGED:
  160. self.UpdateState(u)
  161. self.ComputeorImprovePath()
  162. ischanged = False
  163. if islargelychanged:
  164. self.epsilon += self.increment # or replan from scratch
  165. elif self.epsilon > 1:
  166. self.epsilon -= self.decrement
  167. # move states from the INCONS to OPEN
  168. # update priorities in OPEN
  169. Allnodes = self.INCONS.union(self.OPEN.allnodes())
  170. for node in Allnodes:
  171. self.OPEN.put(node, self.key(node, self.epsilon))
  172. self.INCONS = set()
  173. self.CLOSED = set()
  174. self.ComputeorImprovePath()
  175. #TODO publish current epsilon sub optimal solution
  176. self.Path = self.path()
  177. # if epsilon == 1:
  178. # wait for change to occur
  179. t += 1
  180. def path(self, s_start=None):
  181. '''After ComputeShortestPath()
  182. returns, one can then follow a shortest path from s_start to
  183. s_goal by always moving from the current vertex s, starting
  184. at s_start. , to any successor s' that minimizes c(s,s') + g(s')
  185. until s_goal is reached (ties can be broken arbitrarily).'''
  186. path = []
  187. s_goal = self.xt
  188. s = self.x0
  189. ind = 0
  190. while getDist(s, s_goal) > self.env.resolution:
  191. if s == self.x0:
  192. children = [i for i in self.CLOSED if getDist(s, i) <= self.env.resolution*np.sqrt(3)]
  193. else:
  194. children = list(self.CHILDREN[s])
  195. snext = children[np.argmin([self.getcost(s,s_p) + self.getg(s_p) for s_p in children])]
  196. path.append([s, snext])
  197. s = snext
  198. if ind > 100:
  199. break
  200. ind += 1
  201. return path
  202. if __name__ == '__main__':
  203. AD = Anytime_Dstar(resolution = 1)
  204. AD.Main()