dijkstra.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. """
  2. Dijkstra 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 Dijkstra:
  13. def __init__(self, x_start, x_goal):
  14. self.xI, self.xG = x_start, x_goal
  15. self.Env = env.Env()
  16. self.plotting = plotting.Plotting(self.xI, self.xG)
  17. self.u_set = self.Env.motions # feasible input set
  18. self.obs = self.Env.obs # position of obstacles
  19. self.g = {self.xI: 0, self.xG: float("inf")} # cost to come
  20. self.OPEN = queue.QueuePrior() # priority queue / U set
  21. self.OPEN.put(self.xI, 0)
  22. self.CLOSED = [] # closed set & visited
  23. self.PARENT = {self.xI: self.xI} # relations
  24. def searching(self):
  25. """
  26. Searching using Dijkstra.
  27. :return: path, order of visited nodes in the planning
  28. """
  29. while not self.OPEN.empty():
  30. s = self.OPEN.get()
  31. if s == self.xG: # stop condition
  32. break
  33. self.CLOSED.append(s)
  34. for u in self.u_set: # explore neighborhoods
  35. s_next = tuple([s[i] + u[i] for i in range(2)])
  36. if s_next not in self.obs: # node not visited and not in obstacles
  37. new_cost = self.g[s] + self.get_cost(s, u)
  38. if s_next not in self.g:
  39. self.g[s_next] = float("inf")
  40. if new_cost < self.g[s_next]:
  41. self.g[s_next] = new_cost
  42. self.OPEN.put(s_next, new_cost)
  43. self.PARENT[s_next] = s
  44. return self.extract_path(), self.CLOSED
  45. def extract_path(self):
  46. """
  47. Extract the path based on the relationship of nodes.
  48. :return: The planning path
  49. """
  50. path_back = [self.xG]
  51. x_current = self.xG
  52. while True:
  53. x_current = self.PARENT[x_current]
  54. path_back.append(x_current)
  55. if x_current == self.xI:
  56. break
  57. return list(path_back)
  58. @staticmethod
  59. def get_cost(x, u):
  60. """
  61. Calculate cost for this motion
  62. :param x: current node
  63. :param u: input
  64. :return: cost for this motion
  65. :note: cost function could be more complicate!
  66. """
  67. return 1
  68. def main():
  69. x_start = (5, 5)
  70. x_goal = (45, 25)
  71. dijkstra = Dijkstra(x_start, x_goal)
  72. plot = plotting.Plotting(x_start, x_goal) # class Plotting
  73. fig_name = "Dijkstra's"
  74. path, visited = dijkstra.searching()
  75. plot.animation(path, visited, fig_name) # animation generate
  76. if __name__ == '__main__':
  77. main()