dijkstra.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @author: huiming zhou
  5. """
  6. import queue
  7. import environment
  8. import tools
  9. class Dijkstra:
  10. def __init__(self, Start_State, Goal_State, n, m):
  11. self.xI = Start_State
  12. self.xG = Goal_State
  13. self.u_set = environment.motions # feasible input set
  14. self.obs_map = environment.map_obs() # position of obstacles
  15. self.n = n
  16. self.m = m
  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. actions = {self.xI: (0, 0)} # record actions of nodes
  26. cost = {self.xI: 0}
  27. visited = []
  28. while not q_dijk.empty():
  29. x_current = q_dijk.get()
  30. visited.append(x_current) # record visited nodes
  31. if x_current == self.xG: # stop condition
  32. break
  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 neighbor node is not in obstacles -> ...
  36. if 0 <= x_next[0] < self.n and 0 <= x_next[1] < self.m \
  37. and not tools.obs_detect(x_current, u_next, self.obs_map):
  38. new_cost = cost[x_current] + int(self.get_cost(x_current, u_next))
  39. if x_next not in cost or new_cost < cost[x_next]:
  40. cost[x_next] = new_cost
  41. priority = new_cost
  42. q_dijk.put(x_next, priority) # put node into queue using cost to come as priority
  43. parent[x_next] = x_current
  44. actions[x_next] = u_next
  45. [path_dijk, actions_dijk] = tools.extract_path(self.xI, self.xG, parent, actions)
  46. return path_dijk, actions_dijk, visited
  47. def get_cost(self, x, u):
  48. """
  49. Calculate cost for this motion
  50. :param x: current node
  51. :param u: input
  52. :return: cost for this motion
  53. :note: cost function could be more complicate!
  54. """
  55. return 1
  56. if __name__ == '__main__':
  57. x_Start = (15, 10) # Starting node
  58. x_Goal = (48, 15) # Goal node
  59. dijkstra = Dijkstra(x_Start, x_Goal, environment.col, environment.row)
  60. [path_dijk, actions_dijk, visited_dijk] = dijkstra.searching()
  61. tools.showPath(x_Start, x_Goal, path_dijk, visited_dijk, 'dijkstra_searching')