tools.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @author: huiming zhou
  5. """
  6. import matplotlib.pyplot as plt
  7. import environment
  8. def obs_detect(x, u, obs_map):
  9. """
  10. Detect if the next state is in obstacles using this input.
  11. :param x: current state
  12. :param u: input
  13. :param obs_map: map of obstacles
  14. :return: in obstacles: True / not in obstacles: False
  15. """
  16. x_next = [x[0] + u[0], x[1] + u[1]] # next state using input 'u'
  17. if u not in environment.motions or \
  18. obs_map[x_next[0]][x_next[1]] == 1: # if 'u' is feasible and next state is not in obstacles
  19. return True
  20. return False
  21. def extract_path(xI, xG, parent, actions):
  22. """
  23. Extract the path based on the relationship of nodes.
  24. :param xI: Starting node
  25. :param xG: Goal node
  26. :param parent: Relationship between nodes
  27. :param actions: Action needed for transfer between two nodes
  28. :return: The planning path
  29. """
  30. path_back = [xG]
  31. acts_back = [actions[xG]]
  32. x_current = xG
  33. while True:
  34. x_current = parent[x_current]
  35. path_back.append(x_current)
  36. acts_back.append(actions[x_current])
  37. if x_current == xI: break
  38. return list(reversed(path_back)), list(reversed(acts_back))
  39. def showPath(xI, xG, path, visited, name):
  40. """
  41. Plot the path.
  42. :param xI: Starting node
  43. :param xG: Goal node
  44. :param path: Planning path
  45. :param visited: Visited nodes
  46. :param name: Name of this figure
  47. :return: A plot
  48. """
  49. background = environment.obstacles()
  50. fig, ax = plt.subplots()
  51. for k in range(len(visited)):
  52. background[visited[k][1]][visited[k][0]] = [.5, .5, .5] # visited nodes: gray color
  53. for k in range(len(path)):
  54. background[path[k][1]][path[k][0]] = [1., 0., 0.] # path: red color
  55. background[xI[1]][xI[0]] = [0., 0., 1.] # starting node: blue color
  56. background[xG[1]][xG[0]] = [0., 1., .5] # goal node: green color
  57. ax.imshow(background)
  58. ax.invert_yaxis() # put origin of coordinate to left-bottom
  59. plt.title(name, fontdict=None)
  60. plt.show()