LRT_Astar3D.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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
  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 = self.Astar.children(xi)
  34. minfval = min([cost(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 = [i for i in self.Astar.children(st)]
  46. minh, minchild = np.inf, None
  47. for child in Children:
  48. h = self.Astar.h[child]
  49. if h <= minh:
  50. minh, minchild = h, child
  51. self.path.append([st, minchild])
  52. st = minchild
  53. for (_, p) in self.Astar.OPEN.enumerate():
  54. if p == st:
  55. break
  56. ind += 1
  57. if ind > 1000:
  58. break
  59. self.Astar.reset(st)
  60. def run(self):
  61. while True:
  62. if self.Astar.run(N=self.N):
  63. self.Astar.Path = self.Astar.Path + self.path
  64. self.Astar.done = True
  65. visualization(self.Astar)
  66. plt.show()
  67. break
  68. self.updateHeuristic()
  69. self.move()
  70. if __name__ == '__main__':
  71. T = LRT_A_star2(resolution=0.5, N=150)
  72. T.run()