astar.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. """
  2. A_star 2D
  3. @author: huiming zhou
  4. """
  5. import os
  6. import sys
  7. sys.path.append(os.path.dirname(os.path.abspath(__file__)) +
  8. "/../../Search-based Planning/")
  9. from Search_2D import queue
  10. from Search_2D import plotting
  11. from Search_2D import env
  12. class Astar:
  13. def __init__(self, x_start, x_goal, e, heuristic_type):
  14. self.xI, self.xG = x_start, x_goal
  15. self.heuristic_type = heuristic_type
  16. self.Env = env.Env() # class Env
  17. self.e = e # weighted A*: e >= 1
  18. self.u_set = self.Env.motions # feasible input set
  19. self.obs = self.Env.obs # position of obstacles
  20. self.g = {self.xI: 0, self.xG: float("inf")} # cost to come
  21. self.OPEN = queue.QueuePrior() # priority queue / OPEN set
  22. self.OPEN.put(self.xI, self.fvalue(self.xI))
  23. self.CLOSED = [] # closed set & visited
  24. self.PARENT = {self.xI: self.xI} # relations
  25. def searching(self):
  26. """
  27. Searching using A_star.
  28. :return: path, order of visited nodes in the planning
  29. """
  30. while not self.OPEN.empty():
  31. s = self.OPEN.get()
  32. self.CLOSED.append(s)
  33. if s == self.xG: # stop condition
  34. break
  35. for u in self.u_set: # explore neighborhoods of current node
  36. s_next = tuple([s[i] + u[i] for i in range(2)])
  37. if s_next not in self.obs and s_next not in self.CLOSED:
  38. new_cost = self.g[s] + self.get_cost(s, u)
  39. if s_next not in self.g:
  40. self.g[s_next] = float("inf")
  41. if new_cost < self.g[s_next]: # conditions for updating cost
  42. self.g[s_next] = new_cost
  43. self.PARENT[s_next] = s
  44. self.OPEN.put(s_next, self.fvalue(s_next))
  45. return self.extract_path(self.PARENT), self.CLOSED
  46. def repeated_Searching(self, xI, xG, e):
  47. path, visited = [], []
  48. while e >= 1:
  49. p_k, v_k = self.repeated_Astar(xI, xG, e)
  50. path.append(p_k)
  51. visited.append(v_k)
  52. e -= 0.5
  53. return path, visited
  54. def repeated_Astar(self, xI, xG, e):
  55. g = {xI: 0, xG: float("inf")}
  56. OPEN = queue.QueuePrior()
  57. OPEN.put(xI, g[xI] + e * self.Heuristic(xI))
  58. CLOSED = set()
  59. PARENT = {xI: xI}
  60. VISITED = []
  61. while OPEN:
  62. s = OPEN.get()
  63. CLOSED.add(s)
  64. VISITED.append(s)
  65. if s == xG:
  66. break
  67. for u in self.u_set: # explore neighborhoods of current node
  68. s_next = tuple([s[i] + u[i] for i in range(2)])
  69. if s_next not in self.obs and s_next not in CLOSED:
  70. new_cost = g[s] + self.get_cost(s, u)
  71. if s_next not in g:
  72. g[s_next] = float("inf")
  73. if new_cost < g[s_next]: # conditions for updating cost
  74. g[s_next] = new_cost
  75. PARENT[s_next] = s
  76. OPEN.put(s_next, g[s_next] + e * self.Heuristic(s_next))
  77. return self.extract_path(PARENT), VISITED
  78. def fvalue(self, x, e=1):
  79. """
  80. f = g + h. (g: cost to come, h: heuristic function)
  81. :param x: current state
  82. :return: f
  83. """
  84. return self.g[x] + e * self.Heuristic(x)
  85. def extract_path(self, PARENT):
  86. """
  87. Extract the path based on the relationship of nodes.
  88. :return: The planning path
  89. """
  90. path_back = [self.xG]
  91. x_current = self.xG
  92. while True:
  93. x_current = PARENT[x_current]
  94. path_back.append(x_current)
  95. if x_current == self.xI:
  96. break
  97. return list(path_back)
  98. @staticmethod
  99. def get_cost(x, u):
  100. """
  101. Calculate cost for this motion
  102. :param x: current node
  103. :param u: current input
  104. :return: cost for this motion
  105. :note: cost function could be more complicate!
  106. """
  107. return 1
  108. def Heuristic(self, state):
  109. """
  110. Calculate heuristic.
  111. :param state: current node (state)
  112. :return: heuristic function value
  113. """
  114. heuristic_type = self.heuristic_type # heuristic type
  115. goal = self.xG # goal node
  116. if heuristic_type == "manhattan":
  117. return abs(goal[0] - state[0]) + abs(goal[1] - state[1])
  118. elif heuristic_type == "euclidean":
  119. return ((goal[0] - state[0]) ** 2 + (goal[1] - state[1]) ** 2) ** (1 / 2)
  120. else:
  121. print("Please choose right heuristic type!")
  122. def main():
  123. x_start = (5, 5)
  124. x_goal = (45, 25)
  125. astar = Astar(x_start, x_goal, 1, "manhattan") # weight e = 1
  126. plot = plotting.Plotting(x_start, x_goal) # class Plotting
  127. #
  128. # fig_name = "A*"
  129. # path, visited = astar.searching()
  130. # plot.animation(path, visited, fig_name) # animation generate
  131. fig_name = "Repeated A*"
  132. path, visited = astar.repeated_Searching(x_start, x_goal, 2.5)
  133. plot.animation_ara_star(path, visited, fig_name)
  134. if __name__ == '__main__':
  135. main()