Autonomous Racing  1
f1tenth Project Group of Technical University Dortmund, Germany
plot_path.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 import rospy
4 from gazebo_msgs.msg import ModelStates
5 from std_msgs.msg import Empty
6 import time
7 import numpy as np
8 from matplotlib import pyplot as plt
9 import os
10 
11 from track_geometry import OUTER_WALLS, INNER_WALLS
12 
13 DISTANCE_THRESHOLD = 1
14 MARGIN = 0.1
15 
16 current_position = None
17 crashes = []
18 spawns = []
19 paths = []
20 current_path = []
21 
22 
23 def model_state_callback(message):
24  global current_path, current_position
25  current_position = np.array([
26  message.pose[1].position.x,
27  message.pose[1].position.y
28  ])
29 
30  if len(current_path) > 0:
31  distance = np.linalg.norm(current_position - current_path[-1]).item()
32  if distance > DISTANCE_THRESHOLD:
33  path = np.stack(current_path)
34  paths.append(path)
35  current_path = []
36 
37  if len(current_path) == 0:
38  spawns.append(current_position)
39 
40  current_path.append(current_position)
41 
42 
43 def crash_callback(message):
44  if current_position is not None:
45  crashes.append(current_position)
46 
47 
48 rospy.init_node('plot_path', anonymous=True)
49 rospy.Subscriber("/gazebo/model_states", ModelStates, model_state_callback)
50 rospy.Subscriber("/crash", Empty, crash_callback)
51 
52 print("Recording path... Press CTRL+C to stop recording and create a plot.")
53 
54 while not rospy.is_shutdown():
55  time.sleep(0.1)
56 
57 if len(current_path) > 0:
58  paths.append(np.stack(current_path))
59 
60 x_limits = (np.min(OUTER_WALLS[:, 0]) - MARGIN,
61  np.max(OUTER_WALLS[:, 0]) + MARGIN)
62 y_limits = (np.min(OUTER_WALLS[:, 1]) - MARGIN,
63  np.max(OUTER_WALLS[:, 1]) + MARGIN)
64 size = (x_limits[1] - x_limits[0], y_limits[1] - y_limits[0])
65 
66 fig = plt.figure(figsize=(size[0] * 0.22, size[1] * 0.22))
67 plt.axis('off')
68 plt.xlim(*x_limits)
69 plt.ylim(*y_limits)
70 
71 for path in paths:
72  plt.plot(path[:, 0], path[:, 1], color='blue', linewidth=0.6)
73 
74 if len(crashes) != 0:
75  crashes = np.stack(crashes)
76  plt.plot(crashes[:, 0], crashes[:, 1], 'rx', markersize=6)
77 
78 if len(spawns) > 1:
79  spawns = np.stack(spawns)
80  plt.plot(spawns[:, 0], spawns[:, 1], 'go', markersize=2)
81 
82 plt.plot(INNER_WALLS[:, 0], INNER_WALLS[:, 1], color='gray', linewidth=0.6)
83 plt.plot(OUTER_WALLS[:, 0], OUTER_WALLS[:, 1], color='gray', linewidth=0.6)
84 
85 file_index = 0
86 filename = None
87 while filename is None or os.path.isfile(filename):
88  filename = 'path-{:03d}.pdf'.format(file_index)
89  file_index += 1
90 
91 extent = plt.gca().get_window_extent().transformed(fig.dpi_scale_trans.inverted())
92 plt.savefig(filename, bbox_inches=extent)
93 print('\nPlot saved to {:s}'.format(os.path.abspath(filename)))
def crash_callback(message)
Definition: plot_path.py:43
def model_state_callback(message)
Definition: plot_path.py:23