-
Notifications
You must be signed in to change notification settings - Fork 1
/
grasping_env.py
355 lines (280 loc) · 11.6 KB
/
grasping_env.py
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
from dis import dis
from typing import Tuple, List, Optional, Dict, Callable
import math
import glob
import argparse
import torch
import torch.nn as nn
import numpy as np
import pybullet as pb
import pybullet_data
import gym
from gym.spaces.discrete import Discrete
import time
import h5py
import matplotlib.pyplot as plt
from scipy.spatial.transform import Rotation as R
import os
import nuro_arm
import nuro_arm.robot.robot_arm as robot
from curriculum import ObjectRoutine
# from augmentations import Preprocess
HOME_JPOS = [0, -1, 1.2, 1.4, 0]
TERMINAL_ERROR_MARGIN = 0.035
ROTATION_DELTA = 0.10
VERTICAL_DELTA = 0.02
DISTANCE_DELTA = 0.02
ROLL_DELTA = 0.04
# BACKGROUNDS_DIR = "/Users/tom/Documents/tiny-imagenet-200/val/images"
class HandoverArm(robot.RobotArm):
def __init__(self, controller_type='sim', headless=True, realtime=False, workspace=None, pb_client=None, serial_number=None):
super().__init__(controller_type, headless,
realtime, workspace, pb_client, serial_number)
self.end_effector_link_index = 11
self.camera_link_index = 12
self.open_gripper
if controller_type == 'sim':
self._id = self._sim.robot_id
self.arm_ready_jpos = HOME_JPOS
# self.base_rotation_radians = self.controller._to_radians(1, READY_JPOS[0])
# self.object_id
def ready(self, randomize=True):
'''
moves the arm to the 'ready' position (bent, pointing forward toward workspace)
'''
# self.open_gripper()
self.mp._teleport_gripper(1)
self.mp._teleport_arm(HOME_JPOS)
if randomize:
rot_off = np.random.randint(-4, 4)
z_off = np.random.randint(-4, 4)
self.execute_action(rot_off, z_off, 0, 0)
def execute_action(self,
rot_act: int,
z_act: int,
dist_act: int,
roll_act: int):
'''takes an action returned from policy neural network and moves joints accordingly.
Params
------
takes the four dimensions of the action space, all in {-1, 0, 1}
rot_act: base rotation
z_act: up/down on z axis
dist_act: forward/backward from center of robot
roll_act: gripper roll
Returns
-------
True if collision-free action was predicted
'''
start_jpos = self.get_arm_jpos()
# collide_list = self.mp.is_collision_free(start_jpos, False)[1]
# for collision in collide_list:
# print(collision.__str__())
# obj_collide = np.any(map(lambda x: x.other_body == self.object_id, collide_list))
# print('obj collide:', obj_collide)
# TODO add to valid_Action return, change definition of collission to object collision
(old_x, old_y, old_z), ee_quat = self.get_hand_pose()
old_roll, _, old_yaw = R.from_quat(ee_quat).as_euler('zyz')
# old_yaw = np.arctan2(old_y, old_x)
# print(old_yaw, R.from_quat(ee_quat).as_euler('zyz'))
old_radius = np.linalg.norm((old_x, old_y))
x = old_x + (dist_act * DISTANCE_DELTA) * np.cos(old_yaw)
y = old_y + (dist_act * DISTANCE_DELTA) * np.sin(old_yaw)
z = old_z + (z_act * VERTICAL_DELTA)
yaw = old_yaw + (rot_act * ROTATION_DELTA)
roll = old_roll + (roll_act * ROLL_DELTA)
new_pos = (x, y, z)
new_quat = R.from_euler('zyz', (roll, np.pi/2, yaw)).as_quat()
next_jpos, info = self.mp.calculate_ik(new_pos, new_quat)
valid_action = info['ik_pos_error'] < 0.05 and info['ik_rot_error'] < 0.2
valid_action = valid_action and self.mp.is_collision_free(next_jpos, False)[0]
# valid_action, collisions = self.mp.is_collision_free_trajectory(
# start_jpos, next_jpos, ignore_gripper=False, n_substeps=4)
if valid_action:
self.mp._teleport_arm(next_jpos)
return valid_action
# self.mp._teleport_arm(joint_pos)
# self.controller.power_off_servos()
def try_grasp(self) -> bool:
self.close_gripper()
self.self.controller.read_gripper_state()
class WristCamera:
def __init__(self, robot: HandoverArm, img_size: int) -> None:
'''Camera that is mounted to view workspace from above
Hint
----
For this camera setup, it may be easiest if you use the functions
`pybullet.computeViewMatrix` and `pybullet.computeProjectionMatrixFOV`.
cameraUpVector should be (0,1,0)
Parameters
----------
workspace
2d array describing extents of robot workspace that is to be viewed,
in the format: ((min_x,min_y), (max_x, max_y))
Attributes
----------
img_size : int
height, width of rendered image
view_mtx : List[float]
view matrix that is positioned to view center of workspace from above
proj_mtx : List[float]
proj matrix that set up to fully view workspace
'''
self.img_size = img_size
self.robot = robot
self.type = robot.controller_type
self.computeView()
def computeView(self):
"""
Computes the view matrix and projection matrix based on the position and orientation of the robot's end effector
"""
pos, quat = pb.getLinkState(
self.robot._id, self.robot.camera_link_index)[:2]
rotmat = R.from_quat(quat).as_matrix().T
pos = - np.dot(rotmat, pos)
self.view_mtx = np.eye(4)
self.view_mtx[:3, :3] = rotmat
self.view_mtx[:3, 3] = pos
self.view_mtx = np.ravel(self.view_mtx, order='F')
self.proj_mtx = pb.computeProjectionMatrixFOV(fov=90,
aspect=1,
nearVal=0.01,
farVal=10)
def get_image(self) -> Tuple[np.ndarray, np.ndarray]:
'''Takes rgb image
Returns
-------
np.ndarray
shape (H,W,3) with dtype=np.uint8
'''
rgba, _, mask = tuple(
pb.getCameraImage(width=self.img_size,
height=self.img_size,
viewMatrix=self.view_mtx,
projectionMatrix=self.proj_mtx,
renderer=pb.ER_TINY_RENDERER)[2:5])
return rgba[..., :3], mask
class HandoverGraspingEnv(gym.Env):
def __init__(self,
episode_length: int = 60,
sparse_reward: bool = True,
img_size: int = 64,
render: bool = False,
preprocess=False,
) -> None:
'''Pybullet simulator with robot that performs top down grasps of a
single object. A camera is positioned to take images of workspace
from above.
'''
# add robot
self.robot = HandoverArm(headless=not render)
pb.setGravity(0, 0, 0)
self.camera = WristCamera(self.robot, img_size)
self.img_size = img_size
self.prepro = preprocess
if preprocess:
self.prepro = Preprocess(augmentations=('brightness', 'blur'), bkrd_dir=BACKGROUNDS_DIR)
self.object_routine = ObjectRoutine(moving_mode='noise', moving_dimensions=['horizontal', 'vertical', 'roll'], random_start=False)
self.robot.object_id = self.object_routine._id
# add object
self.object_width = 0.02
self.t_step = 0
self.episode_length = episode_length
self.sparse = sparse_reward
self.observation_space = gym.spaces.Box(
0, 255, shape=(img_size, img_size, 3), dtype=np.float32)
# Four action spaces, each representing a positive, zero, or negative change
self.base_rotation_actions = Discrete(n=3, start=-1)
self.pitch_actions = Discrete(n=3, start=-1)
self.forward_actions = Discrete(n=3, start=-1)
self.wrist_rotation_actions = Discrete(n=3, start=-1)
# NOTE: if sampling, subtract 1
self.action_space = gym.spaces.MultiDiscrete([3, 3, 3, 3])
# self.action_space = gym.spaces.Discrete(81)
self.reset()
def reset(self) -> np.ndarray:
'''Resets environment by randomly placing object
'''
# self.object_routine.reset()
pos = np.random.uniform((0.15, -0.06, 0.1),(0.25, 0.06, 0.25))
quat = pb.getQuaternionFromEuler((0,np.pi/2, 0))
pb.resetBasePositionAndOrientation(self.object_routine._id, pos, quat)
self.robot.ready()
# self.reset_object_texture()
self.t_step = 0
return self.get_obs()
def step(self, action: np.ndarray):
'''
Takes one step in the environment.
Params
------
action: 4-vector with discrete values in {-1, 0, 1}
Returns
------
obs, reward, done, info
'''
self.action_space.contains(action)
# TODO maybe different reward schema?
# tmp = action
# action = []
# for i in range(4):
# action.append(tmp % 3 - 1)
# tmp = tmp // 3
if self.robot.execute_action(*action):
collided = False
else:
collided = True
self.t_step += 1
obs = self.get_obs()
reward, done = self.getReward(collided)
done = done or self.t_step >= self.episode_length# or collided
# diagnostic information, what should we put here?
info = {'success': self.canGrasp()}
# self.object_routine.step()
return obs, reward, done, info
def canGrasp(self) -> bool:
'''Determines if the current position of the gripper's is such that the object is within a small error margin of grasp point.
'''
# grip_pos = pb.getLinkState(
# self.robot._id, self.robot.end_effector_link_index, computeForwardKinematics=True)[0]
# obj_pos = pb.getBasePositionAndOrientation(self.object_id)[0]
# return np.allclose(grip_pos, obj_pos, atol=TERMINAL_ERROR_MARGIN, rtol=0)
return self.distToGrasp() < TERMINAL_ERROR_MARGIN
def distToGrasp(self) -> float:
''' Euclidian distance to the grasping object '''
grip_pos = pb.getLinkState(
self.robot._id, self.robot.end_effector_link_index, computeForwardKinematics=True)[0]
obj_pos = pb.getBasePositionAndOrientation(self.object_routine._id)[0]
return float(np.linalg.norm(np.subtract(grip_pos, obj_pos)))
def getReward(self, collided: bool) -> Tuple[float, bool]:
''' Defines the terminal states in the learning environment'''
# TODO: Issue penalty if runs into an obstacle
REWARD_SCALE = 1e-3
done = self.canGrasp()
if self.sparse:
# if collided:
# return -1, True
# else:
return int(done), done
else:
return REWARD_SCALE/self.distToGrasp(), done
def get_obs(self) -> dict:
'''Takes picture using camera, returns rgb and segmentation mask of image
Returns
-------
np.ndarray
rgb image of shape (H,W,3) and dtype of np.uint8
'''
self.camera.computeView()
rgb, mask = self.camera.get_image()
jpos = self.robot.get_arm_jpos()
if self.prepro:
rgb = self.prepro(rgb, mask)
return {'rgb': rgb, 'joints':jpos}
def plot_obs(self):
plt.imshow(self.get_obs())
plt.show()
if __name__ == "__main__":
env = HandoverGraspingEnv()
env.plot_obs()
exit()