LRT_Astar3D.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # this is the three dimensional N>1 LRTA* algo
  2. # !/usr/bin/env python3
  3. # -*- coding: utf-8 -*-
  4. """
  5. @author: yue qi
  6. """
  7. import numpy as np
  8. import matplotlib.pyplot as plt
  9. import os
  10. import sys
  11. sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../../Search-based Planning/")
  12. from Search_3D.env3D import env
  13. from Search_3D import Astar3D
  14. from Search_3D.utils3D import getDist, getRay, g_Space, Heuristic, getNearest, isCollide, \
  15. cost, obstacleFree, children
  16. from Search_3D.plot_util3D import visualization
  17. import queue
  18. class LRT_A_star2:
  19. def __init__(self, resolution=0.5, N=7):
  20. self.N = N
  21. self.Astar = Astar3D.Weighted_A_star(resolution=resolution)
  22. self.path = []
  23. def updateHeuristic(self):
  24. # Initialize hvalues at infinity
  25. for xi in self.Astar.CLOSED:
  26. self.Astar.h[xi] = np.inf
  27. Diff = True
  28. while Diff: # repeat DP until converge
  29. hvals, lasthvals = [], []
  30. for xi in self.Astar.CLOSED:
  31. lasthvals.append(self.Astar.h[xi])
  32. # update h values if they are smaller
  33. Children = children(self.Astar,xi)
  34. minfval = min([cost(self.Astar,xi, xj, settings=0) + self.Astar.h[xj] for xj in Children])
  35. # h(s) = h(s') if h(s) > c(s,s') + h(s')
  36. if self.Astar.h[xi] >= minfval:
  37. self.Astar.h[xi] = minfval
  38. hvals.append(self.Astar.h[xi])
  39. if lasthvals == hvals: Diff = False
  40. def move(self):
  41. st = self.Astar.x0
  42. ind = 0
  43. # find the lowest path down hill
  44. while st in self.Astar.CLOSED: # when minchild in CLOSED then continue, when minchild in OPEN, stop
  45. Children = children(self.Astar,st)
  46. minh, minchild = np.inf, None
  47. for child in Children:
  48. # check collision here, not a supper efficient
  49. collide, _ = isCollide(self.Astar,st, child)
  50. if collide:
  51. continue
  52. h = self.Astar.h[child]
  53. if h <= minh:
  54. minh, minchild = h, child
  55. self.path.append([st, minchild])
  56. st = minchild
  57. for (_, p) in self.Astar.OPEN.enumerate():
  58. if p == st:
  59. break
  60. ind += 1
  61. if ind > 1000:
  62. break
  63. self.Astar.reset(st)
  64. def run(self):
  65. while True:
  66. if self.Astar.run(N=self.N):
  67. self.Astar.Path = self.Astar.Path + self.path
  68. self.Astar.done = True
  69. visualization(self.Astar)
  70. plt.show()
  71. break
  72. self.updateHeuristic()
  73. self.move()
  74. if __name__ == '__main__':
  75. T = LRT_A_star2(resolution=0.5, N=100)
  76. T.run()