dijkstra.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @author: huiming zhou
  5. """
  6. import queue
  7. import env
  8. import tools
  9. class Dijkstra:
  10. def __init__(self, x_start, x_goal, x_range, y_range):
  11. self.u_set = env.motions # feasible input set
  12. self.xI, self.xG = x_start, x_goal
  13. self.x_range, self.y_range = x_range, y_range
  14. self.obs = env.obs_map(self.xI, self.xG, "dijkstra searching") # position of obstacles
  15. def searching(self):
  16. """
  17. Searching using Dijkstra.
  18. :return: planning path, action in each node, visited nodes in the planning process
  19. """
  20. q_dijk = queue.QueuePrior() # priority queue
  21. q_dijk.put(self.xI, 0)
  22. parent = {self.xI: self.xI} # record parents of nodes
  23. action = {self.xI: (0, 0)} # record actions of nodes
  24. cost = {self.xI: 0}
  25. while not q_dijk.empty():
  26. x_current = q_dijk.get()
  27. if x_current == self.xG: # stop condition
  28. break
  29. if x_current != self.xI:
  30. tools.plot_dots(x_current, len(parent))
  31. for u_next in self.u_set: # explore neighborhoods of current node
  32. x_next = tuple([x_current[i] + u_next[i] for i in range(len(x_current))])
  33. if x_next not in self.obs: # node not visited and not in obstacles
  34. new_cost = cost[x_current] + self.get_cost(x_current, u_next)
  35. if x_next not in cost or new_cost < cost[x_next]:
  36. cost[x_next] = new_cost
  37. priority = new_cost
  38. q_dijk.put(x_next, priority) # put node into queue using cost to come as priority
  39. parent[x_next] = x_current
  40. action[x_next] = u_next
  41. [path_dijk, action_dijk] = tools.extract_path(self.xI, self.xG, parent, action)
  42. return path_dijk, action_dijk
  43. def get_cost(self, x, u):
  44. """
  45. Calculate cost for this motion
  46. :param x: current node
  47. :param u: input
  48. :return: cost for this motion
  49. :note: cost function could be more complicate!
  50. """
  51. return 1
  52. if __name__ == '__main__':
  53. x_Start = (5, 5) # Starting node
  54. x_Goal = (49, 5) # Goal node
  55. dijkstra = Dijkstra(x_Start, x_Goal, env.x_range, env.y_range)
  56. [path_dijk, actions_dijk] = dijkstra.searching()
  57. tools.showPath(x_Start, x_Goal, path_dijk)