astar.py 5.2 KB

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