DstarLite3D.py 9.8 KB

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