DstarLite3D.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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 isinbound(old, xi, mode) or isinbound(new, xi, mode):
  52. newchildren = set(children(self, xi)) # B
  53. self.CHILDREN[xi] = newchildren
  54. for xj in newchildren:
  55. self.COST[xi][xj] = cost(self, xi, xj)
  56. CHANGED.add(xi)
  57. return CHANGED
  58. def getcost(self, xi, xj):
  59. # use a LUT for getting the costd
  60. if xi not in self.COST:
  61. for (xj,xjcost) in children(self, xi, settings=1):
  62. self.COST[xi][xj] = cost(self, xi, xj, xjcost)
  63. # this might happen when there is a node changed.
  64. if xj not in self.COST[xi]:
  65. self.COST[xi][xj] = cost(self, xi, xj)
  66. return self.COST[xi][xj]
  67. def getchildren(self, xi):
  68. if xi not in self.CHILDREN:
  69. allchild = children(self, xi)
  70. self.CHILDREN[xi] = set(allchild)
  71. return self.CHILDREN[xi]
  72. def geth(self, xi):
  73. # when the heurisitic is first calculated
  74. if xi not in self.h:
  75. self.h[xi] = heuristic_fun(self, xi, self.x0)
  76. return self.h[xi]
  77. def getg(self, xi):
  78. if xi not in self.g:
  79. self.g[xi] = np.inf
  80. return self.g[xi]
  81. def getrhs(self, xi):
  82. if xi not in self.rhs:
  83. self.rhs[xi] = np.inf
  84. return self.rhs[xi]
  85. #-------------main functions for D*Lite-------------
  86. def CalculateKey(self, s, epsilion = 1):
  87. return [min(self.getg(s), self.getrhs(s)) + epsilion * self.geth(s) + self.km, min(self.getg(s), self.getrhs(s))]
  88. def UpdateVertex(self, u):
  89. # if still in the hunt
  90. if not getDist(self.xt, u) <= self.env.resolution: # originally: u != x_goal
  91. if u in self.CHILDREN and len(self.CHILDREN[u]) == 0:
  92. self.rhs[u] = np.inf
  93. else:
  94. self.rhs[u] = min([self.getcost(s, u) + self.getg(s) for s in self.getchildren(u)])
  95. # if u is in OPEN, remove it
  96. self.OPEN.check_remove(u)
  97. # if rhs(u) not equal to g(u)
  98. if self.getg(u) != self.getrhs(u):
  99. self.OPEN.put(u, self.CalculateKey(u))
  100. def ComputeShortestPath(self):
  101. while self.OPEN.top_key() < self.CalculateKey(self.x0) or self.getrhs(self.x0) != self.getg(self.x0) :
  102. kold = self.OPEN.top_key()
  103. u = self.OPEN.get()
  104. self.V.add(u)
  105. self.CLOSED.add(u)
  106. if not self.done: # first time running, we need to stop on this condition
  107. if getDist(self.x0,u) < 1*self.env.resolution:
  108. self.x0 = u
  109. break
  110. if kold < self.CalculateKey(u):
  111. self.OPEN.put(u, self.CalculateKey(u))
  112. if self.getg(u) > self.getrhs(u):
  113. self.g[u] = self.rhs[u]
  114. else:
  115. self.g[u] = np.inf
  116. self.UpdateVertex(u)
  117. for s in self.getchildren(u):
  118. self.UpdateVertex(s)
  119. # visualization(self)
  120. self.ind += 1
  121. def main(self):
  122. s_last = self.x0
  123. print('first run ...')
  124. self.ComputeShortestPath()
  125. self.Path = self.path()
  126. self.done = True
  127. visualization(self)
  128. plt.pause(0.5)
  129. # plt.show()
  130. print('running with map update ...')
  131. t = 0 # count time
  132. ischanged = False
  133. self.V = set()
  134. while getDist(self.x0, self.xt) > 2*self.env.resolution:
  135. #---------------------------------- at specific times, the environment is changed and Cost is updated
  136. if t % 2 == 0:
  137. new0,old0 = self.env.move_block(a=[-0.1, 0, -0.2], s=0.5, block_to_move=1, mode='translation')
  138. new1,old1 = self.env.move_block(a=[0, 0, -0.2], s=0.5, block_to_move=0, mode='translation')
  139. new2,old2 = self.env.move_block(theta = [0,0,0.1*t], mode='rotation')
  140. #new2,old2 = self.env.move_block(a=[-0.3, 0, -0.1], s=0.5, block_to_move=1, mode='translation')
  141. ischanged = True
  142. self.Path = []
  143. #----------------------------------- traverse the route as originally planned
  144. if t == 0:
  145. children_new = [i for i in self.CLOSED if getDist(self.x0, i) <= self.env.resolution*np.sqrt(3)]
  146. else:
  147. children_new = list(children(self,self.x0))
  148. self.x0 = children_new[np.argmin([self.getcost(self.x0,s_p) + self.getg(s_p) for s_p in children_new])]
  149. # TODO add the moving robot position codes
  150. self.env.start = self.x0
  151. # ---------------------------------- if any Cost changed, update km, reset slast,
  152. # for all directed edgees (u,v) with chaged edge costs,
  153. # update the edge Cost c(u,v) and update vertex u. then replan
  154. if ischanged:
  155. self.km += heuristic_fun(self, self.x0, s_last)
  156. s_last = self.x0
  157. CHANGED = self.updatecost(True, new0, old0)
  158. CHANGED1 = self.updatecost(True, new1, old1)
  159. CHANGED2 = self.updatecost(True, new2, old2, mode='obb')
  160. CHANGED = CHANGED.union(CHANGED1, CHANGED2)
  161. # self.V = set()
  162. for u in CHANGED:
  163. self.UpdateVertex(u)
  164. self.ComputeShortestPath()
  165. ischanged = False
  166. self.Path = self.path(self.x0)
  167. visualization(self)
  168. t += 1
  169. plt.show()
  170. def path(self, s_start=None):
  171. '''After ComputeShortestPath()
  172. returns, one can then follow a shortest path from x_start to
  173. x_goal by always moving from the current vertex s, starting
  174. at x_start. , to any successor s' that minimizes c(s,s') + g(s')
  175. until x_goal is reached (ties can be broken arbitrarily).'''
  176. path = []
  177. s_goal = self.xt
  178. if not s_start:
  179. s = self.x0
  180. else:
  181. s= s_start
  182. ind = 0
  183. while s != s_goal:
  184. if s == self.x0:
  185. children = [i for i in self.CLOSED if getDist(s, i) <= self.env.resolution*np.sqrt(3)]
  186. else:
  187. children = list(self.CHILDREN[s])
  188. snext = children[np.argmin([self.getcost(s,s_p) + self.getg(s_p) for s_p in children])]
  189. path.append([s, snext])
  190. s = snext
  191. if ind > 100:
  192. break
  193. ind += 1
  194. return path
  195. if __name__ == '__main__':
  196. D_lite = D_star_Lite(1)
  197. a = time.time()
  198. D_lite.main()
  199. print('used time (s) is ' + str(time.time() - a))