tools.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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", ms = 24) # plot starting state (blue)
  55. plt.plot(xG[0], xG[1], "gs", ms = 24) # plot goal states (green)
  56. plt.plot(obs_x, obs_y, "sk", ms = 24) # plot obstacles (black)
  57. plt.plot(lose_x, lose_y, marker = 's', color = '#A52A2A', ms = 24) # plot losing states (grown)
  58. plt.title(name, fontdict=None)
  59. plt.axis("equal")
  60. def plot_dots(x):
  61. """
  62. Plot state x for animation
  63. :param x: current node
  64. :return: a plot
  65. """
  66. plt.plot(x[0], x[1], linewidth='3', color='#808080', marker='o', ms = 23) # plot dots for animation
  67. plt.gcf().canvas.mpl_connect('key_release_event',
  68. lambda event: [exit(0) if event.key == 'escape' else None])
  69. plt.pause(0.1)