-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrun_collection_manipulator_ros2.py
More file actions
397 lines (294 loc) · 15.7 KB
/
run_collection_manipulator_ros2.py
File metadata and controls
397 lines (294 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
# Description: This script is used to run the policy on the real robot
# Authors:
# Giulio Turrisi
import sys
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(dir_path+"/mujoco/")
sys.path.append(dir_path+"/../")
sys.path.append(dir_path+"/../scripts/rsl_rl")
dir_path = Path(__file__).resolve().parent
sys.path.append(str(dir_path / ".."))
ros_ws = dir_path / "ros2_ws"
setup_bash = ros_ws / "install" / "setup.bash"
if not setup_bash.exists():
print("Building the msgs first...")
subprocess.run(["colcon", "build"], cwd=ros_ws, check=True)
if os.environ.get("SIM2REAL_ROBOT_IDENTIFICATION_SOURCED") != "1":
print("Sourcing ROS2 workspace and restarting script...")
cmd = (
f"source {shlex.quote(str(setup_bash))} && "
"export SIM2REAL_ROBOT_IDENTIFICATION_SOURCED=1 && "
f"exec {shlex.quote(sys.executable)} "
+ " ".join(shlex.quote(arg) for arg in [str(Path(__file__).resolve()), *sys.argv[1:]])
)
os.execv("/bin/bash", ["bash", "-c", cmd])
import rclpy
from rclpy.node import Node
from dls2_interface.msg import ArmState, ArmTrajectoryGenerator
import time
import numpy as np
np.set_printoptions(precision=3, suppress=True)
import threading
import copy
import torch
import mujoco
import mujoco.viewer
import config
# Set the priority of the process
pid = os.getpid()
print("PID: ", pid)
os.system("renice -n -21 -p " + str(pid))
os.system("echo -20 > /proc/" + str(pid) + "/autogroup")
#for real time, launch it with chrt -r 99 python3 run_controller.py
USE_MUJOCO_RENDER = True
USE_MUJOCO_SIMULATION = True
CONTROL_FREQ = config.frequency_collection # Hz
def handle_parallel_gripper(array):
if(config.robot == "piper_l"):
return array[:-1]
else:
return array
class Data_Collection_Node(Node):
def __init__(self):
super().__init__('Data_Collection_Node')
# Subscribers and Publishers
self.subscription_arm_state = self.create_subscription(ArmState,"/arm_state", self.get_arm_blind_state_callback, 1)
self.publisher_arm_trajectory_generator = self.create_publisher(ArmTrajectoryGenerator,"/arm_trajectory_generator", 1)
self.timer = self.create_timer(1.0/CONTROL_FREQ, self.compute_control)
# Safety check to not do anything until a first base and blind state are received
self.first_message_joints_arrived = False
# Timing stuff
self.loop_time = 0.002
self.last_start_time = None
self.start_collection_time = None
# Base State
self.position = np.zeros(3)
self.orientation = np.zeros(4)
self.linear_velocity = np.zeros(3)
self.angular_velocity = np.zeros(3)
# Blind State
self.joint_positions = np.zeros(12)
self.joint_velocities = np.zeros(12)
self.feet_contact = np.zeros(4)
# Create the environment -----------------------------------------------------------
self.mjModel = mujoco.MjModel.from_xml_path(dir_path + "/robot_model/" + config.robot + "/scene_flat.xml")
self.mjData = mujoco.MjData(self.mjModel)
if(USE_MUJOCO_RENDER):
self.viewer = mujoco.viewer.launch_passive(
self.mjModel,
self.mjData,
show_left_ui=False,
show_right_ui=False,
)
self.last_render_time = time.time()
keyframe_home_id = mujoco.mj_name2id(self.mjModel, mujoco.mjtObj.mjOBJ_KEY, "home")
keyframe_sys_id_1 = mujoco.mj_name2id(self.mjModel, mujoco.mjtObj.mjOBJ_KEY, "sys_id_1")
keyframe_sys_id_2 = mujoco.mj_name2id(self.mjModel, mujoco.mjtObj.mjOBJ_KEY, "sys_id_2")
self.home_position = self.mjModel.key_qpos[keyframe_sys_id_1]
self.goal_position = self.mjModel.key_qpos[keyframe_sys_id_2]
# Handling parallel gripper - if present, otherwise
# the func will return the same array
self.home_position = handle_parallel_gripper(self.home_position)
self.goal_position = handle_parallel_gripper(self.goal_position)
self.Kp = config.Kp
self.Kd = config.Kd
self.calibration_reference_joint_positions = None
# Chirp Trajectory only variables
self.chirp_traj_time = 3.0
self.calibration_reference_trajectory = None
self.saved_actual_joints_position = None
self.saved_actual_joints_velocity = None
self.saved_desired_joints_position = None
self.saved_desired_joints_velocity = None
self.saved_commanded_joints_torque = None
self.num_traj_saved = 0
# Interactive Command Line ----------------------------
from console import Console
self.console = Console(controller_node=self)
thread_console = threading.Thread(target=self.console.interactive_command_line)
thread_console.daemon = True
thread_console.start()
def get_arm_blind_state_callback(self, msg):
self.arm_joints_position = np.array(msg.joints_position)
self.arm_joints_position = np.append(self.arm_joints_position, msg.gripper_position)
self.arm_joints_velocity = np.array(msg.joints_velocity)
self.arm_joints_velocity = np.append(self.arm_joints_velocity, msg.gripper_velocity)
self.first_message_joints_arrived = True
def _initialize_calibration_trajectory(self):
"""Initialize calibration trajectory with random values"""
print("Generating first a trajectory..")
# Generate a linear trajectory between actual joint positions and two setpoint
t = np.linspace(0, self.chirp_traj_time, num=100)
# Interpolate for each joint separately
self.calibration_reference_trajectory = np.zeros((100, len(self.home_position)))
for joint_idx in range(len(self.home_position)):
self.calibration_reference_trajectory[:, joint_idx] = np.interp(
t,
[0, self.chirp_traj_time/2, self.chirp_traj_time],
[self.home_position[joint_idx], self.goal_position[joint_idx], self.home_position[joint_idx]]
)
self.start_collection_time = time.time()
def _get_desired_positions_and_gains(self, ):
"""Get desired joint positions and control gains based on collection type"""
if self.console.setpoint_collection:
print("not implemented")
elif self.console.falling_collection:
print("not implemented")
elif self.console.trajectory_collection:
# Trajectory collection: follow the reference trajectory
Kp = self.Kp
Kd = self.Kd
time_traj = self.start_collection_time - time.time()
desired_joint_pos = self.calibration_reference_trajectory[int((time_traj/self.chirp_traj_time)*100)]
return desired_joint_pos, Kp, Kd
def _collect_trajectory_data(self, joints_pos, joints_vel, desired_joint_pos):
"""Collect trajectory data by concatenating and storing joint information"""
concatenated_actual_joints_position = joints_pos
concatenated_actual_joints_velocity = joints_vel
concatenated_desired_joints_position = desired_joint_pos
concatenated_desired_joints_velocity = desired_joint_pos*0.0
error_joints_pos = desired_joint_pos - joints_pos
concatenated_commanded_joints_torque = config.Kp * (error_joints_pos) - config.Kd * joints_vel
if self.saved_actual_joints_position is None:
self.saved_actual_joints_position = concatenated_actual_joints_position
self.saved_actual_joints_velocity = concatenated_actual_joints_velocity
self.saved_desired_joints_position = concatenated_desired_joints_position
self.saved_desired_joints_velocity = concatenated_desired_joints_velocity
self.saved_commanded_joints_torque = concatenated_commanded_joints_torque
else:
self.saved_actual_joints_position = np.vstack([self.saved_actual_joints_position, concatenated_actual_joints_position])
self.saved_actual_joints_velocity = np.vstack([self.saved_actual_joints_velocity, concatenated_actual_joints_velocity])
self.saved_desired_joints_position = np.vstack([self.saved_desired_joints_position, concatenated_desired_joints_position])
self.saved_desired_joints_velocity = np.vstack([self.saved_desired_joints_velocity, concatenated_desired_joints_velocity])
self.saved_commanded_joints_torque = np.vstack([self.saved_commanded_joints_torque, concatenated_commanded_joints_torque])
def _check_collection_complete(self, joints_pos, desired_joint_pos):
"""Check if data collection is complete based on collection type"""
if self.console.setpoint_collection:
# Complete when target is reached or timeout
print("not implemented")
return False
elif self.console.falling_collection:
# Complete after falling phase timeout
print("not implemented")
return False
elif self.console.trajectory_collection:
# Complete after trajectory duration
return time.time() - self.start_collection_time > self.chirp_traj_time
def _save_trajectory_data(self):
"""Save collected trajectory data to file"""
# HACK
num_steps = self.saved_actual_joints_position.shape[0]
duration = num_steps/CONTROL_FREQ
time_data = torch.linspace(0, duration, steps=num_steps, device="cpu")
dof_pos_buffer = torch.zeros(num_steps, 7, device="cpu")
dof_vel_buffer = torch.zeros(num_steps, 7, device="cpu")
dof_target_pos_buffer = torch.zeros(num_steps, 7, device="cpu")
dof_target_vel_buffer = torch.zeros(num_steps, 7, device="cpu")
dof_target_commanded_torque_buffer = torch.zeros(num_steps, 7, device="cpu")
dof_pos_buffer[:, :] = torch.from_numpy(self.saved_actual_joints_position)
dof_vel_buffer[:, :] = torch.from_numpy(self.saved_actual_joints_velocity)
dof_target_pos_buffer[:, :] = torch.from_numpy(self.saved_desired_joints_position)
#dof_target_vel_buffer[:, :] = torch.from_numpy(self.saved_desired_joints_velocity)
dof_target_commanded_torque_buffer[:, :] = torch.from_numpy(self.saved_commanded_joints_torque)
save_dir = "datasets/" + config.robot
os.makedirs(save_dir, exist_ok=True)
torch.save({
"time": time_data.cpu(),
"dof_pos": dof_pos_buffer.cpu(),
"dof_vel": dof_vel_buffer.cpu(),
"des_dof_pos": dof_target_pos_buffer.cpu(),
"des_dof_vel": dof_target_vel_buffer.cpu(),
"des_dof_torque": dof_target_commanded_torque_buffer.cpu(),
"kp": self.Kp,
"kd": self.Kd,
}, "datasets/" + config.robot + f"/traj_{self.num_traj_saved}.pt")
self.num_traj_saved += 1
self.saved_actual_joints_position = None
self.saved_actual_joints_velocity = None
self.saved_desired_joints_position = None
self.saved_desired_joints_velocity = None
self.saved_commanded_joints_torque = None
input("Press enter to continue.")
def compute_control(self):
# Update the loop time
start_time = time.perf_counter()
if(self.last_start_time is not None):
self.loop_time = (start_time - self.last_start_time)
self.last_start_time = start_time
simulation_dt = self.loop_time
# Safety check to not do anything until a first base and blind state are received
if(not USE_MUJOCO_SIMULATION and self.first_message_joints_arrived==False):
return
# Update the mujoco model
if(not USE_MUJOCO_SIMULATION):
self.mjData.qpos = copy.deepcopy(self.arm_joints_position)
self.mjData.qvel = copy.deepcopy(self.arm_joints_velocity)
mujoco.mj_forward(self.mjModel, self.mjData)
joints_pos = self.mjData.qpos
joints_vel = self.mjData.qvel
# Handling parallel gripper - if present, otherwise
# the func will return the same array
joints_pos = handle_parallel_gripper(joints_pos)
joints_vel = handle_parallel_gripper(joints_vel)
if(not self.console.isActivated):
desired_joint_pos = self.home_position
# Impedence Loop
Kp = self.Kp
Kd = self.Kd
elif(self.console.isActivated and (self.console.setpoint_collection or self.console.falling_collection)):
print("not implemented")
elif(self.console.isActivated and self.console.trajectory_collection):
# Initialize setpoint if needed
if self.calibration_reference_trajectory is None:
self._initialize_calibration_trajectory()
# Get desired joint positions and control gains based on collection type
desired_joint_pos, Kp, Kd = self._get_desired_positions_and_gains()
# Collect data
self._collect_trajectory_data(joints_pos, joints_vel, desired_joint_pos)
# Check if collection is complete
collection_complete = self._check_collection_complete(joints_pos, desired_joint_pos)
if collection_complete:
self.calibration_reference_trajectory = None
self.chirp_traj_time -= 0.2 # Reduce trajectory time for next trajectory
if(self.chirp_traj_time < 0.4):
self._save_trajectory_data()
self.console.trajectory_collection = False
print("Trajectory collection completed.")
else:
desired_joint_pos = self.home_position
# Impedence Loop
Kp = self.Kp*0.0
Kd = self.Kd*0.0
if USE_MUJOCO_SIMULATION:
error_joints_pos = desired_joint_pos - joints_pos
self.mjData.ctrl = Kp * (error_joints_pos) - Kd * joints_vel
mujoco.mj_step(self.mjModel, self.mjData)
# Publish the desired joint positions to the trajectory generator --------------------------------
arm_trajectory_generator_msg = ArmTrajectoryGenerator()
arm_trajectory_generator_msg.timestamp = float(self.get_clock().now().nanoseconds)
arm_trajectory_generator_msg.desired_arm_joints_position = desired_joint_pos[0:-1].flatten().tolist()
arm_trajectory_generator_msg.desired_arm_joints_velocity = np.zeros(6).tolist()
arm_trajectory_generator_msg.desired_arm_gripper_position = desired_joint_pos[-1]
arm_trajectory_generator_msg.desired_arm_gripper_velocity = 0.0
arm_trajectory_generator_msg.arm_kp = Kp[0:6].tolist()
arm_trajectory_generator_msg.arm_kd = Kd[0:6].tolist()
arm_trajectory_generator_msg.gripper_kp = Kp[6].tolist()
arm_trajectory_generator_msg.gripper_kd = Kd[6].tolist()
self.publisher_arm_trajectory_generator.publish(arm_trajectory_generator_msg)
# Render the simulation -----------------------------------------------------------------------------------
if USE_MUJOCO_RENDER:
RENDER_FREQ = 30
# Render only at a certain frequency -----------------------------------------------------------------
if time.time() - self.last_render_time > 1.0 / RENDER_FREQ:
self.viewer.sync()
#---------------------------
if __name__ == '__main__':
print('Hello from your lovely data_collection routine.')
rclpy.init()
data_collection_node = Data_Collection_Node()
rclpy.spin(data_collection_node)
data_collection_node.destroy_node()
rclpy.shutdown()
print("Data-Collection-Node is stopped")
exit(0)