sr_right_hand_partial_traj_advanced.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # Copyright 2019 Shadow Robot Company Ltd.
3 #
4 # This program is free software: you can redistribute it and/or modify it
5 # under the terms of the GNU General Public License as published by the Free
6 # Software Foundation version 2 of the License.
7 #
8 # This program is distributed in the hope that it will be useful, but WITHOUT
9 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
11 # more details.
12 #
13 # You should have received a copy of the GNU General Public License along
14 # with this program. If not, see <http://www.gnu.org/licenses/>.
15 
16 # This example gives a more advanced use case for sending partial trajectories.
17 # A plot is generated to show the output of the desired and achieved positions and velocities.
18 
19 import numpy as np
20 
21 import rospy
22 from control_msgs.msg import JointTrajectoryControllerState,\
23  FollowJointTrajectoryActionResult, FollowJointTrajectoryActionGoal
24 import matplotlib.pyplot as plt
25 from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
26 
27 from sr_robot_commander.sr_hand_commander import SrHandCommander
28 from sr_utilities.hand_finder import HandFinder
29 
30 
32 
33  def __init__(self):
34  self.start_time_goals = []
36  self.goal_joint_names = []
37  self.trajectories = []
38  self.start_goals = False
39  self.finish_goals = False
40 
41  self.joints_time = []
42  self.ffj3_actual = []
43  self.ffj3_desired = []
44  self.ffj3_error = []
45  self.rfj3_actual = []
46  self.rfj3_desired = []
47  self.rfj3_error = []
48  self.ffj3_vel_actual = []
49  self.rfj3_vel_actual = []
50  self.ffj3_vel_desired = []
51  self.rfj3_vel_desired = []
52  self.ffj3_vel_error = []
53  self.rfj3_vel_error = []
54 
55  rospy.Subscriber("/rh_trajectory_controller/state",
56  JointTrajectoryControllerState, self.callback)
57  rospy.Subscriber(
58  "/rh_trajectory_controller/follow_joint_trajectory/result",
59  FollowJointTrajectoryActionResult, self.callback_result)
60  rospy.Subscriber(
61  "/rh_trajectory_controller/follow_joint_trajectory/goal",
62  FollowJointTrajectoryActionGoal, self.callback_goal)
63 
64  def callback(self, state):
65  self.joint_names = state.joint_names
66  self.ffj3_index = self.joint_names.index("rh_FFJ3")
67  self.rfj3_index = self.joint_names.index("rh_RFJ3")
68 
69  if self.start_goals and not self.finish_goals:
70  self.joints_time.append(state.header.stamp.to_sec())
71  self.ffj3_actual.append(state.actual.positions[self.ffj3_index])
72  self.ffj3_desired.append(state.desired.positions[self.ffj3_index])
73  self.ffj3_error.append(state.error.positions[self.ffj3_index])
74  self.rfj3_actual.append(state.actual.positions[self.rfj3_index])
75  self.rfj3_desired.append(state.desired.positions[self.rfj3_index])
76  self.rfj3_error.append(state.error.positions[self.rfj3_index])
77 
78  self.ffj3_vel_actual.append(state.actual.velocities[self.ffj3_index])
79  self.rfj3_vel_actual.append(state.actual.velocities[self.rfj3_index])
80  self.ffj3_vel_desired.append(state.desired.velocities[self.ffj3_index])
81  self.rfj3_vel_desired.append(state.desired.velocities[self.rfj3_index])
82  self.ffj3_vel_error.append(state.error.velocities[self.ffj3_index])
83  self.rfj3_vel_error.append(state.error.velocities[self.rfj3_index])
84 
85  def callback_result(self, result):
86  print ("Trajectory Goal: " + result.status.goal_id.id +
87  " finished with status: " + str(result.status.status))
88 
89  def callback_goal(self, goal):
90  self.start_goals = True
91  self.goal_joint_names.append(goal.goal.trajectory.joint_names)
92  self.start_time_goals.append(goal.header.stamp.to_sec())
93  self.start_time_goals_trajectory.append(goal.goal.trajectory.header.stamp.to_sec())
94  self.trajectories.append(goal.goal.trajectory.points)
95 
96  def plot_settings(self, plt):
97  ax = plt.gca()
98  plt.grid(which='both', axis='both')
99  plt.setp(ax.get_xticklabels(), fontsize=8)
100  plt.setp(ax.get_yticklabels(), fontsize=8)
101  plt.xlabel('Time (s)')
102  ax.xaxis.label.set_size(10)
103  ax.yaxis.label.set_size(10)
104 
105  def graph(self):
106  time_zero = self.joints_time[0]
107  time = np.array(self.joints_time) - time_zero
108 
109  plt.figure()
110 
111  # Plot goal trajectories waypoints
112  time_ffj3_traj = []
113  angle_ffj3_traj = []
114  time_rfj3_traj = []
115  angle_rfj3_traj = []
116  for i, traj in enumerate(self.trajectories):
117  ffj3_goal_index = self.goal_joint_names[i].index("rh_FFJ3") if "rh_FFJ3" in self.goal_joint_names[i] else -1
118  rfj3_goal_index = self.goal_joint_names[i].index("rh_RFJ3") if "rh_RFJ3" in self.goal_joint_names[i] else -1
119 
120  for point in traj:
121  if ffj3_goal_index > -1:
122  time_ffj3_traj.append(point.time_from_start.to_sec() +
124  time_zero)
125  angle_ffj3_traj.append(point.positions[ffj3_goal_index])
126  if rfj3_goal_index > -1:
127  time_rfj3_traj.append(point.time_from_start.to_sec() +
129  time_zero)
130  angle_rfj3_traj.append(point.positions[rfj3_goal_index])
131 
132  if ffj3_goal_index > -1:
133  plt.subplot(3, 2, 1)
134  plt.plot(time_ffj3_traj, angle_ffj3_traj, 'o',
135  label="Traj " + str(i + 1))
136 
137  if rfj3_goal_index > -1:
138  plt.subplot(3, 2, 2)
139  plt.plot(time_rfj3_traj, angle_rfj3_traj, 'o',
140  label="Traj " + str(i + 1))
141 
142  time_ffj3_traj = []
143  angle_ffj3_traj = []
144  time_rfj3_traj = []
145  angle_rfj3_traj = []
146 
147  # Plot trajectories
148  plt.subplot(3, 2, 1)
149  plt.plot(time, self.ffj3_actual, 'black', label="Actual traj")
150  plt.plot(time, self.ffj3_desired, 'green', label="Desired traj")
151  plt.ylabel('FFJ3 Actual position (rad)')
152  self.plot_settings(plt)
153  plt.ylim(ymax=2.2, ymin=-0.1)
154  plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=5,
155  mode="expand", borderaxespad=0., prop={'size': 8})
156 
157  plt.subplot(3, 2, 2)
158  plt.plot(time, self.rfj3_actual, 'black', label="Actual traj")
159  plt.plot(time, self.rfj3_desired, 'green', label="Desired traj")
160  plt.ylabel('RFJ3 Actual position (rad)')
161  self.plot_settings(plt)
162  plt.ylim(ymax=2.2, ymin=-0.1)
163  plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=4,
164  mode="expand", borderaxespad=0., prop={'size': 8})
165 
166  plt.subplot(3, 2, 3)
167  plt.plot(time, self.ffj3_vel_actual, 'black', label="Actual traj")
168  plt.plot(time, self.ffj3_vel_desired, 'green', label="Desired traj")
169  plt.ylabel('FFJ3 Actual velocity')
170  plt.xlim(xmax=16, xmin=0)
171  self.plot_settings(plt)
172  plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=4,
173  mode="expand", borderaxespad=0., prop={'size': 8})
174 
175  plt.subplot(3, 2, 4)
176  plt.plot(time, self.rfj3_vel_actual, 'black', label="Actual traj")
177  plt.plot(time, self.rfj3_vel_desired, 'green', label="Desired traj")
178  plt.ylabel('RFJ3 Actual velocity')
179  plt.xlim(xmax=16, xmin=0)
180  self.plot_settings(plt)
181  plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=4,
182  mode="expand", borderaxespad=0., prop={'size': 8})
183 
184  plt.subplot(3, 2, 5)
185  plt.plot(time, self.ffj3_vel_error, 'red', label="Error traj")
186  plt.ylabel('FFJ3 Velocity Error')
187  plt.xlim(xmax=16, xmin=0)
188  self.plot_settings(plt)
189 
190  plt.subplot(3, 2, 6)
191  plt.plot(time, self.rfj3_vel_error, 'red', label="Error traj")
192  plt.ylabel('RFJ3 Velocity Error')
193  plt.xlim(xmax=16, xmin=0)
194  self.plot_settings(plt)
195 
196  plt.subplots_adjust(left=0.07, right=0.96, bottom=0.083, top=0.90)
197  plt.show()
198 
199 
200 def construct_trajectory_point(posture, duration):
201  trajectory_point = JointTrajectoryPoint()
202  trajectory_point.time_from_start = rospy.Duration.from_sec(float(duration))
203  for key in joint_trajectory.joint_names:
204  trajectory_point.positions.append(posture[key])
205  return trajectory_point
206 
207 # 6 position goals are specified
208 open_hand = {'rh_FFJ1': 0.0, 'rh_FFJ2': 0.0, 'rh_FFJ3': 0.0, 'rh_FFJ4': 0.0,
209  'rh_MFJ1': 0.0, 'rh_MFJ2': 0.0, 'rh_MFJ3': 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.0, 'rh_THJ3': 0.0,
248  'rh_THJ4': 0.0, 'rh_THJ5': 0.0}
249 
250 # Two partial trajectories are defined here for joint rh_FFJ3
251 grasp_partial_1 = {'rh_FFJ3': 1.06}
252 grasp_partial_2 = {'rh_FFJ3': 1.2}
253 
254 if __name__ == '__main__':
255  rospy.init_node("partial_traj_example_advanced", anonymous=True)
256  rospy.sleep(1) # Do not start at time zero
257 
258  listener = PartialTrajListener()
259  hand_finder = HandFinder()
260 
261  hand_parameters = hand_finder.get_hand_parameters()
262  hand_serial = hand_parameters.mapping.keys()[0]
263 
264  hand_commander = SrHandCommander(hand_parameters=hand_parameters,
265  hand_serial=hand_serial)
266 
267  hand_mapping = hand_parameters.mapping[hand_serial]
268 
269  # Hand joints are detected
270  joints = hand_finder.get_hand_joints()[hand_mapping]
271 
272  # Adjust poses according to the hand loaded
273  open_hand_current = dict([(i, open_hand[i]) for i in joints if i in open_hand])
274  grasp1_current = dict([(i, grasp1[i]) for i in joints if i in grasp1])
275  grasp2_current = dict([(i, grasp2[i]) for i in joints if i in grasp2])
276  grasp3_current = dict([(i, grasp3[i]) for i in joints if i in grasp3])
277  grasp4_current = dict([(i, grasp4[i]) for i in joints if i in grasp4])
278  grasp5_current = dict([(i, grasp5[i]) for i in joints if i in grasp5])
279 
280  start_time = rospy.Time.now()
281 
282  # Opening hand
283  rospy.loginfo("Moving hand to open position")
284  trajectory_start_time = 1.0
285  joint_trajectory = JointTrajectory()
286  joint_trajectory.header.stamp = start_time + rospy.Duration.from_sec(float(trajectory_start_time))
287  joint_trajectory.joint_names = list(open_hand_current.keys())
288  joint_trajectory.points = []
289  trajectory_point = construct_trajectory_point(open_hand_current, 1.0)
290  joint_trajectory.points.append(trajectory_point)
291  hand_commander.run_joint_trajectory_unsafe(joint_trajectory, True)
292 
293  # Closing index and middle fingers. Trajectories are generated from grasp1 - grasp5 and run with hand_commander
294  rospy.loginfo("Closing index and ring fingers")
295  trajectory_start_time = 4.0
296  joint_trajectory = JointTrajectory()
297  joint_trajectory.header.stamp = start_time + rospy.Duration.from_sec(float(trajectory_start_time))
298  joint_trajectory.joint_names = list(grasp1_current.keys())
299  joint_trajectory.points = []
300  trajectory_point = construct_trajectory_point(grasp1_current, 1.0)
301  joint_trajectory.points.append(trajectory_point)
302  trajectory_point = construct_trajectory_point(grasp2_current, 4.0)
303  joint_trajectory.points.append(trajectory_point)
304  trajectory_point = construct_trajectory_point(grasp3_current, 6.0)
305  joint_trajectory.points.append(trajectory_point)
306  trajectory_point = construct_trajectory_point(grasp4_current, 8.0)
307  joint_trajectory.points.append(trajectory_point)
308  trajectory_point = construct_trajectory_point(grasp5_current, 10.0)
309  joint_trajectory.points.append(trajectory_point)
310  hand_commander.run_joint_trajectory_unsafe(joint_trajectory, False)
311 
312  # Interrupting trajectory of index using two partial trajectories
313  rospy.loginfo("Moving index finger to partial trajectory goals")
314  rospy.sleep(2)
315  trajectory_start_time = 8.0
316  joint_trajectory = JointTrajectory()
317  joint_trajectory.header.stamp = start_time + rospy.Duration.from_sec(float(trajectory_start_time))
318  joint_trajectory.joint_names = list(grasp_partial_1.keys())
319  joint_trajectory.points = []
320  trajectory_point = construct_trajectory_point(grasp_partial_1, 1.0)
321  joint_trajectory.points.append(trajectory_point)
322  trajectory_point = construct_trajectory_point(grasp_partial_2, 3.0)
323  joint_trajectory.points.append(trajectory_point)
324  hand_commander.run_joint_trajectory_unsafe(joint_trajectory, False)
325 
326  graphs_finished = False
327 
328  rate = rospy.Rate(10)
329 
330  # Do not exit until graphs closed
331  while not rospy.is_shutdown():
332  if len(listener.joints_time) > 5 and\
333  (listener.joints_time[-1] - listener.joints_time[0]) > 15 and\
334  not graphs_finished:
335  listener.finish_goals = True
336  listener.graph()
337  graphs_finished = True
338  break
339  rate.sleep()


sr_example
Author(s): Ugo Cupcic
autogenerated on Wed Oct 14 2020 04:05:12