DstarLite3D.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import os
  4. import sys
  5. from collections import defaultdict
  6. sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../../Search-based Planning/")
  7. from Search_3D.env3D import env
  8. from Search_3D.utils3D import getDist, heuristic_fun, getNearest, isinbound, \
  9. cost, children, StateSpace
  10. from Search_3D.plot_util3D import visualization
  11. from Search_3D import queue
  12. import time
  13. class D_star_Lite(object):
  14. # Original version of the D*lite
  15. def __init__(self, resolution = 1):
  16. self.Alldirec = {(1, 0, 0): 1, (0, 1, 0): 1, (0, 0, 1): 1, \
  17. (-1, 0, 0): 1, (0, -1, 0): 1, (0, 0, -1): 1, \
  18. (1, 1, 0): np.sqrt(2), (1, 0, 1): np.sqrt(2), (0, 1, 1): np.sqrt(2), \
  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, 1, 0): np.sqrt(2), (1, 0, -1): np.sqrt(2), \
  21. (-1, 0, 1): np.sqrt(2), (0, 1, -1): np.sqrt(2), (0, -1, 1): np.sqrt(2), \
  22. (1, 1, 1): np.sqrt(3), (-1, -1, -1) : np.sqrt(3), \
  23. (1, -1, -1): np.sqrt(3), (-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. self.env = env(resolution=resolution)
  26. #self.X = StateSpace(self.env)
  27. #self.x0, self.xt = getNearest(self.X, self.env.start), getNearest(self.X, self.env.goal)
  28. self.settings = 'CollisionChecking' # for collision checking
  29. self.x0, self.xt = tuple(self.env.start), tuple(self.env.goal)
  30. # self.OPEN = queue.QueuePrior()
  31. self.OPEN = queue.MinheapPQ()
  32. self.km = 0
  33. self.g = {} # all g initialized at inf
  34. self.rhs = {self.xt:0} # rhs(x0) = 0
  35. self.h = {}
  36. self.OPEN.put(self.xt, self.CalculateKey(self.xt))
  37. self.CLOSED = set()
  38. # init children set:
  39. self.CHILDREN = {}
  40. # init cost set
  41. self.COST = defaultdict(lambda: defaultdict(dict))
  42. # for visualization
  43. self.V = set() # vertice in closed
  44. self.ind = 0
  45. self.Path = []
  46. self.done = False
  47. def updatecost(self,range_changed=None, new=None, old=None, mode=False):
  48. # scan graph for changed cost, if cost is changed update it
  49. CHANGED = set()
  50. for xi in self.CLOSED:
  51. if xi in self.CHILDREN:
  52. oldchildren = self.CHILDREN[xi]# A
  53. if isinbound(old, xi, mode) or isinbound(new, xi, mode):
  54. newchildren = set(children(self,xi))# B
  55. removed = oldchildren.difference(newchildren)
  56. intersection = oldchildren.intersection(newchildren)
  57. added = newchildren.difference(oldchildren)
  58. for xj in removed:
  59. self.COST[xi][xj] = cost(self, xi, xj)
  60. for xj in intersection.union(added):
  61. self.COST[xi][xj] = cost(self, xi, xj)
  62. CHANGED.add(xi)
  63. else:
  64. if isinbound(old, xi, mode) or isinbound(new, xi, mode):
  65. CHANGED.add(xi)
  66. children_added = set(children(self,xi))
  67. self.CHILDREN[xi] = children_added
  68. for xj in children_added:
  69. self.COST[xi][xj] = cost(self, xi, xj)
  70. return CHANGED
  71. def getcost(self, xi, xj):
  72. # use a LUT for getting the costd
  73. if xi not in self.COST:
  74. for (xj,xjcost) in children(self, xi, settings=1):
  75. self.COST[xi][xj] = cost(self, xi, xj, xjcost)
  76. # this might happen when there is a node changed.
  77. if xj not in self.COST[xi]:
  78. self.COST[xi][xj] = cost(self, xi, xj)
  79. return self.COST[xi][xj]
  80. def getchildren(self, xi):
  81. if xi not in self.CHILDREN:
  82. allchild = children(self, xi)
  83. self.CHILDREN[xi] = set(allchild)
  84. return self.CHILDREN[xi]
  85. def geth(self, xi):
  86. # when the heurisitic is first calculated
  87. if xi not in self.h:
  88. self.h[xi] = heuristic_fun(self, xi, self.x0)
  89. return self.h[xi]
  90. def getg(self, xi):
  91. if xi not in self.g:
  92. self.g[xi] = np.inf
  93. return self.g[xi]
  94. def getrhs(self, xi):
  95. if xi not in self.rhs:
  96. self.rhs[xi] = np.inf
  97. return self.rhs[xi]
  98. #-------------main functions for D*Lite-------------
  99. def CalculateKey(self, s, epsilion = 1):
  100. return [min(self.getg(s), self.getrhs(s)) + epsilion * self.geth(s) + self.km, min(self.getg(s), self.getrhs(s))]
  101. def UpdateVertex(self, u):
  102. # if still in the hunt
  103. if not getDist(self.xt, u) <= self.env.resolution: # originally: u != s_goal
  104. if u in self.CHILDREN and len(self.CHILDREN[u]) == 0:
  105. self.rhs[u] = np.inf
  106. else:
  107. self.rhs[u] = min([self.getcost(s, u) + self.getg(s) for s in self.getchildren(u)])
  108. # if u is in OPEN, remove it
  109. self.OPEN.check_remove(u)
  110. # if rhs(u) not equal to g(u)
  111. if self.getg(u) != self.getrhs(u):
  112. self.OPEN.put(u, self.CalculateKey(u))
  113. def ComputeShortestPath(self):
  114. while self.OPEN.top_key() < self.CalculateKey(self.x0) or self.getrhs(self.x0) != self.getg(self.x0) :
  115. kold = self.OPEN.top_key()
  116. u = self.OPEN.get()
  117. self.V.add(u)
  118. self.CLOSED.add(u)
  119. if not self.done: # first time running, we need to stop on this condition
  120. if getDist(self.x0,u) < 1*self.env.resolution:
  121. self.x0 = u
  122. break
  123. if kold < self.CalculateKey(u):
  124. self.OPEN.put(u, self.CalculateKey(u))
  125. if self.getg(u) > self.getrhs(u):
  126. self.g[u] = self.rhs[u]
  127. else:
  128. self.g[u] = np.inf
  129. self.UpdateVertex(u)
  130. for s in self.getchildren(u):
  131. self.UpdateVertex(s)
  132. # visualization(self)
  133. self.ind += 1
  134. def main(self):
  135. s_last = self.x0
  136. print('first run ...')
  137. self.ComputeShortestPath()
  138. self.Path = self.path()
  139. self.done = True
  140. visualization(self)
  141. plt.pause(0.5)
  142. # plt.show()
  143. print('running with map update ...')
  144. t = 0 # count time
  145. ischanged = False
  146. self.V = set()
  147. while getDist(self.x0, self.xt) > 2*self.env.resolution:
  148. #---------------------------------- at specific times, the environment is changed and cost is updated
  149. if t % 2 == 0:
  150. new0,old0 = self.env.move_block(a=[-0.1, 0, -0.2], s=0.5, block_to_move=1, mode='translation')
  151. new1,old1 = self.env.move_block(a=[0, 0, -0.2], s=0.5, block_to_move=0, mode='translation')
  152. new2,old2 = self.env.move_block(theta = [0,0,0.1*t], mode='rotation')
  153. #new2,old2 = self.env.move_block(a=[-0.3, 0, -0.1], s=0.5, block_to_move=1, mode='translation')
  154. ischanged = True
  155. self.Path = []
  156. #----------------------------------- traverse the route as originally planned
  157. if t == 0:
  158. children_new = [i for i in self.CLOSED if getDist(self.x0, i) <= self.env.resolution*np.sqrt(3)]
  159. else:
  160. children_new = list(children(self,self.x0))
  161. self.x0 = children_new[np.argmin([self.getcost(self.x0,s_p) + self.getg(s_p) for s_p in children_new])]
  162. # TODO add the moving robot position codes
  163. self.env.start = self.x0
  164. # ---------------------------------- if any cost changed, update km, reset slast,
  165. # for all directed edgees (u,v) with chaged edge costs,
  166. # update the edge cost c(u,v) and update vertex u. then replan
  167. if ischanged:
  168. self.km += heuristic_fun(self, self.x0, s_last)
  169. s_last = self.x0
  170. CHANGED = self.updatecost(True, new0, old0)
  171. CHANGED1 = self.updatecost(True, new1, old1)
  172. CHANGED2 = self.updatecost(True, new2, old2, mode='obb')
  173. CHANGED = CHANGED.union(CHANGED1, CHANGED2)
  174. # self.V = set()
  175. for u in CHANGED:
  176. self.UpdateVertex(u)
  177. self.ComputeShortestPath()
  178. ischanged = False
  179. self.Path = self.path(self.x0)
  180. visualization(self)
  181. t += 1
  182. plt.show()
  183. def path(self, s_start=None):
  184. '''After ComputeShortestPath()
  185. returns, one can then follow a shortest path from s_start to
  186. s_goal by always moving from the current vertex s, starting
  187. at s_start. , to any successor s' that minimizes c(s,s') + g(s')
  188. until s_goal is reached (ties can be broken arbitrarily).'''
  189. path = []
  190. s_goal = self.xt
  191. if not s_start:
  192. s = self.x0
  193. else:
  194. s= s_start
  195. ind = 0
  196. while s != s_goal:
  197. if s == self.x0:
  198. children = [i for i in self.CLOSED if getDist(s, i) <= self.env.resolution*np.sqrt(3)]
  199. else:
  200. children = list(self.CHILDREN[s])
  201. snext = children[np.argmin([self.getcost(s,s_p) + self.getg(s_p) for s_p in children])]
  202. path.append([s, snext])
  203. s = snext
  204. if ind > 100:
  205. break
  206. ind += 1
  207. return path
  208. if __name__ == '__main__':
  209. D_lite = D_star_Lite(1)
  210. a = time.time()
  211. D_lite.main()
  212. print('used time (s) is ' + str(time.time() - a))