dijkstra.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @author: Huiming Zhou
  5. """
  6. import numpy as np
  7. import matplotlib.pyplot as plt
  8. from matplotlib import colors
  9. from queue import *
  10. from mazemods import *
  11. def DijkstraSearch(xI, xG, n, m, O, cost_type):
  12. q_dijk = QueuePrior()
  13. q_dijk.put(xI, 0)
  14. parent = {xI: xI}
  15. actions = {xI: (0, 0)}
  16. rec_cost = {xI: 0}
  17. u_set = {(-1, 0), (1, 0), (0, 1), (0, -1)}
  18. while not q_dijk.empty():
  19. x_current = q_dijk.get()
  20. if x_current == xG:
  21. break
  22. for u_next in u_set:
  23. x_next = tuple([x_current[i] + u_next[i] for i in range(len(x_current))])
  24. if 0 <= x_next[0] < n and 0 <= x_next[1] < m \
  25. and not collisionCheck(x_current, u_next, O):
  26. cost_x = costfunc(x_current, x_next, O, cost_type)
  27. new_cost = rec_cost[x_current] + cost_x
  28. if x_next not in rec_cost or new_cost < rec_cost[x_next]:
  29. rec_cost[x_next] = new_cost
  30. priority = new_cost
  31. q_dijk.put(x_next, priority)
  32. parent[x_next] = x_current
  33. actions[x_next] = u_next
  34. [path_dijk, actions_dijk] = extractpath(xI, xG, parent, actions)
  35. [simple_cost, west_cost, east_cost] = cost_calculation(xI, actions_dijk, O)
  36. return path_dijk, actions_dijk, len(parent), simple_cost, west_cost, east_cost
  37. # Cost function used in Dijkstra's algorithm
  38. def costfunc(x_current, x_next, O, function_type):
  39. if function_type == "westcost":
  40. return x_next[0] ** 2
  41. elif function_type == "eastcost":
  42. maxX = 0
  43. for k in range(len(O)):
  44. westxO = O[k][1]
  45. if westxO > maxX:
  46. maxX = westxO
  47. return (maxX - x_next[0]) ** 2
  48. else:
  49. print("Please choose right cost function!")