dijkstra.py 2.6 KB

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