tools.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @author: huiming zhou
  5. """
  6. import matplotlib.pyplot as plt
  7. def extract_path(xI, xG, parent, actions):
  8. """
  9. Extract the path based on the relationship of nodes.
  10. :param xI: Starting node
  11. :param xG: Goal node
  12. :param parent: Relationship between nodes
  13. :param actions: Action needed for transfer between two nodes
  14. :return: The planning path
  15. """
  16. path_back = [xG]
  17. acts_back = [actions[xG]]
  18. x_current = xG
  19. while True:
  20. x_current = parent[x_current]
  21. path_back.append(x_current)
  22. acts_back.append(actions[x_current])
  23. if x_current == xI: break
  24. return list(reversed(path_back)), list(reversed(acts_back))
  25. def showPath(xI, xG, path):
  26. """
  27. Plot the path.
  28. :param xI: Starting node
  29. :param xG: Goal node
  30. :param path: Planning path
  31. :return: A plot
  32. """
  33. path.remove(xI)
  34. path.remove(xG)
  35. path_x = [path[i][0] for i in range(len(path))]
  36. path_y = [path[i][1] for i in range(len(path))]
  37. plt.plot(path_x, path_y, linewidth='5', color='r', linestyle='-')
  38. plt.pause(0.001)
  39. plt.show()
  40. def show_map(xI, xG, obs_map, lose_map, name):
  41. """
  42. Plot the background you designed.
  43. :param xI: starting state
  44. :param xG: goal states
  45. :param obs_map: positions of obstacles
  46. :param lose_map: positions of losing state
  47. :param name: name of this figure
  48. :return: a figure
  49. """
  50. obs_x = [obs_map[i][0] for i in range(len(obs_map))]
  51. obs_y = [obs_map[i][1] for i in range(len(obs_map))]
  52. lose_x = [lose_map[i][0] for i in range(len(lose_map))]
  53. lose_y = [lose_map[i][1] for i in range(len(lose_map))]
  54. plt.plot(xI[0], xI[1], "bs") # plot starting state (blue)
  55. for x in xG:
  56. plt.plot(x[0], x[1], "gs") # plot goal states (green)
  57. plt.plot(obs_x, obs_y, "sk") # plot obstacles (black)
  58. plt.plot(lose_x, lose_y, marker = 's', color = '#A52A2A') # plot losing states (grown)
  59. plt.title(name, fontdict=None)
  60. plt.axis("equal")
  61. def plot_dots(x):
  62. """
  63. Plot state x for animation
  64. :param x: current node
  65. :return: a plot
  66. """
  67. plt.plot(x[0], x[1], linewidth='3', color='#808080', marker='o') # plot dots for animation
  68. plt.gcf().canvas.mpl_connect('key_release_event',
  69. lambda event: [exit(0) if event.key == 'escape' else None])
  70. plt.pause(0.001)