astar.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @author: Huiming Zhou
  5. """
  6. import numpy as np
  7. import matplotlib.pyplot as plt
  8. from matplotlib import colors
  9. from queue import *
  10. from mazemods import *
  11. from environment import *
  12. def aStarSearch(xI, xG, n, m, O, heuristic_type):
  13. q_astar = QueuePrior()
  14. q_astar.put(xI, 0)
  15. parent = {xI: xI}
  16. actions = {xI: (0, 0)}
  17. rec_cost = {xI: 0}
  18. u_set = {(-1, 0), (1, 0), (0, 1), (0, -1)}
  19. while not q_astar.empty():
  20. x_current = q_astar.get()
  21. if x_current == xG:
  22. break
  23. for u_next in u_set:
  24. x_next = tuple([x_current[i] + u_next[i] for i in range(len(x_current))])
  25. if 0 <= x_next[0] < n and 0 <= x_next[1] < m \
  26. and not collisionCheck(x_current, u_next, O):
  27. new_cost = rec_cost[x_current] + 1
  28. if x_next not in rec_cost or new_cost < rec_cost[x_next]:
  29. rec_cost[x_next] = new_cost
  30. priority = new_cost + Heuristic(x_next, xG, heuristic_type)
  31. q_astar.put(x_next, priority)
  32. parent[x_next] = x_current
  33. actions[x_next] = u_next
  34. [path_astar, actions_astar] = extractpath(xI, xG, parent, actions)
  35. [simple_cost, west_cost, east_cost] = cost_calculation(xI, actions_astar, O)
  36. return path_astar, actions_astar, len(parent), simple_cost, west_cost, east_cost
  37. # Heuristic function used in A* algorithm
  38. def Heuristic(state, goal, heuristic_type):
  39. if heuristic_type == "manhattanHeuristic":
  40. return abs(goal[0] - state[0]) + abs(goal[1] - state[1])
  41. elif heuristic_type == "euclideanHeuristic":
  42. return ((goal[0] - state[0]) ** 2 + (goal[1] - state[1]) ** 2) ** (1 / 2)
  43. else:
  44. print("Please choose right heuristic type!")