dijkstra.py 2.7 KB

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