dijkstra.py 3.0 KB

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