rrtstar3D.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. """
  2. This is rrt star code for 3D
  3. @author: yue qi
  4. """
  5. import numpy as np
  6. from numpy.matlib import repmat
  7. from collections import defaultdict
  8. import time
  9. import matplotlib.pyplot as plt
  10. import os
  11. import sys
  12. sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../../Sampling-based Planning/")
  13. from rrt_3D.env3D import env
  14. from rrt_3D.utils3D import getDist, sampleFree, nearest, steer, isCollide, near, visualization, cost, path, edgeset, hash3D, dehash
  15. class rrtstar():
  16. def __init__(self):
  17. self.env = env()
  18. self.Parent = {}
  19. self.E = edgeset()
  20. self.V = []
  21. self.i = 0
  22. self.maxiter = 10000 # at least 4000 in this env
  23. self.stepsize = 0.5
  24. self.gamma = 500
  25. self.eta = 2*self.stepsize
  26. self.Path = []
  27. self.done = False
  28. def wireup(self,x,y):
  29. self.E.add_edge([x,y]) # add edge
  30. self.Parent[hash3D(x)] = y
  31. def removewire(self,xnear):
  32. xparent = self.Parent[hash3D(xnear)]
  33. a = [xnear,xparent]
  34. self.E.remove_edge(a) # remove and replace old the connection
  35. def reached(self):
  36. self.done = True
  37. xn = near(self,self.env.goal)
  38. c = [cost(self,x) for x in xn]
  39. xncmin = xn[np.argmin(c)]
  40. self.wireup(self.env.goal,xncmin)
  41. self.V.append(self.env.goal)
  42. self.Path,self.D = path(self)
  43. def run(self):
  44. self.V.append(self.env.start)
  45. self.ind = 0
  46. xnew = self.env.start
  47. print('start rrt*... ')
  48. self.fig = plt.figure(figsize = (10,8))
  49. while self.ind < self.maxiter:
  50. xrand = sampleFree(self)
  51. xnearest = nearest(self,xrand)
  52. xnew = steer(self,xnearest,xrand)
  53. if not isCollide(self,xnearest,xnew):
  54. Xnear = near(self,xnew)
  55. self.V.append(xnew) # add point
  56. visualization(self)
  57. # minimal path and minimal cost
  58. xmin, cmin = xnearest, cost(self, xnearest) + getDist(xnearest, xnew)
  59. # connecting along minimal cost path
  60. for xnear in Xnear:
  61. c1 = cost(self, xnear) + getDist(xnew, xnear)
  62. if not isCollide(self, xnew, xnear) and c1 < cmin:
  63. xmin, cmin = xnear, c1
  64. self.wireup(xnew, xmin)
  65. # rewire
  66. for xnear in Xnear:
  67. c2 = cost(self, xnew) + getDist(xnew, xnear)
  68. if not isCollide(self, xnew, xnear) and c2 < cost(self, xnear):
  69. self.removewire(xnear)
  70. self.wireup(xnear, xnew)
  71. self.i += 1
  72. self.ind += 1
  73. # max sample reached
  74. self.reached()
  75. print('time used = ' + str(time.time()-starttime))
  76. print('Total distance = '+str(self.D))
  77. visualization(self)
  78. plt.show()
  79. if __name__ == '__main__':
  80. p = rrtstar()
  81. starttime = time.time()
  82. p.run()