-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmaniskill.py
374 lines (323 loc) · 12.7 KB
/
maniskill.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import glob
import gym
import numpy as np
import os
import random
import torch
from gym.spaces import Box
from dm_control.utils.rewards import tolerance
from sapien.core import Pose
from mani_skill2.envs.pick_and_place.pick_cube import (
PickCubeEnv,
LiftCubeEnv,
)
from mani_skill2.envs.misc.turn_faucet import TurnFaucetEnv
from mani_skill2.utils.common import flatten_dict_space_keys, flatten_state_dict
from mani_skill2.utils.registration import register_env
from mani_skill2.utils.sapien_utils import look_at
from transforms3d.euler import euler2quat
camera_poses = {
"PickCube": look_at([0.2, 0.4, 0.4], [0.0, 0.0, 0.3]),
"TurnFaucet": look_at([0.2, 0.4, 0.4], [0.0, 0.0, 0.3]),
"PushCubeMatterport": look_at([0.2, -0.4, 0.4], [0.0, 0.0, 0.3]),
"LiftCubeMatterport": look_at([0.2, -0.4, 0.4], [0.0, 0.0, 0.3]),
"PickCubeMatterport": look_at([0.2, -0.4, 0.4], [0.0, 0.0, 0.3]),
"TurnFaucetMatterport": look_at([0.2, -0.4, 0.4], [0.0, 0.0, 0.3]),
}
env_kwargs = {
"PickCube": {},
"TurnFaucet": {"model_ids": "5021"},
"PushCubeMatterport": {},
"LiftCubeMatterport": {},
"PickCubeMatterport": {},
"TurnFaucetMatterport": {"model_ids": "5021"},
}
QPOS_LOW = np.array(
[0.0, np.pi * 2 / 8, 0, -np.pi * 5 / 8, 0, np.pi * 7 / 8, np.pi / 4, 0.04, 0.04]
)
QPOS_HIGH = np.array(
[0.0, np.pi * 1 / 8, 0, -np.pi * 5 / 8, 0, np.pi * 6 / 8, np.pi / 4, 0.04, 0.04]
)
BASE_POSE = Pose([-0.615, 0, 0.05])
CUBE_HALF_SIZE = 0.02
xyz = np.hstack([0.0, 0.0, CUBE_HALF_SIZE])
quat = np.array([1.0, 0.0, 0.0, 0.0])
OBJ_INIT_POSE = Pose(xyz, quat)
def load_ReplicaCAD(builder):
paths = sorted(
list(
glob.glob(
os.path.join("./data/hab2_bench_assets/stages_uncompressed/*.glb")
)
)
)
path = random.choice(paths)
pose = Pose(q=[0.707, 0.707, 0, 0]) # y-axis up for Habitat scenes
builder.add_visual_from_file(path, pose)
arena = builder.build_static()
# Add offset to workspace
offset = np.array([-2.0, -3.0, 0.8])
arena.set_pose(Pose(-offset))
return arena
def load_Matterport(builder):
paths = sorted(list(glob.glob(os.path.join("./data/matterport3d/*.glb"))))
path = random.choice(paths)
pose = Pose(q=[0, 0, 0, 1]) # y-axis up for Matterport scenes
builder.add_visual_from_file(path, pose)
arena = builder.build_static()
# Add offset to workspace
offset = np.array([0, 0, 0.8])
arena.set_pose(Pose(-offset))
return arena
@register_env("PickCubeMatterport-v0", max_episode_steps=100, override=True)
class PickCubeMatterport(PickCubeEnv):
def _clear(self):
# Release cached resources
self._renderer.clear_cached_resources()
super()._clear()
def _initialize_task(self):
# Fix goal position
self.goal_pos = np.array([0.1, 0.0, 0.3])
self.goal_site.set_pose(Pose(self.goal_pos))
def _initialize_agent(self):
# Set ee to be near the object
self.agent.reset(QPOS_LOW)
self.agent_init_pose = BASE_POSE
self.agent.robot.set_pose(self.agent_init_pose)
def _initialize_actors(self):
self.obj_init_pose = OBJ_INIT_POSE
self.obj.set_pose(self.obj_init_pose)
def _load_actors(self):
# Load invisible ground
self._add_ground(render=False)
# Load cube
self.obj = self._build_cube(self.cube_half_size)
# Add goal indicator
self.goal_site = self._build_sphere_site(self.goal_thresh)
# Load arena
builder = self._scene.create_actor_builder()
self.arena = load_Matterport(builder)
def get_done(self, info, **kwargs):
# Disable done from task completion
return False
def compute_dense_reward(self, info, **kwargs):
_CUBE_HALF_SIZE = self.cube_half_size[0]
_GOAL_THRESH = self.goal_thresh
_LIFT_THRESH = 0.1
tcp_to_obj = np.linalg.norm(self.obj.pose.p - self.tcp.pose.p)
obj_to_goal_xy = np.linalg.norm(self.goal_pos[:2] - self.obj.pose.p[:2])
obj_to_goal_z = np.abs(self.goal_pos[2] - self.obj.pose.p[2])
gripper_dist = np.linalg.norm(
self.agent.finger1_link.pose.p - self.agent.finger2_link.pose.p
)
reaching_reward = tolerance(
tcp_to_obj,
bounds=(0, _CUBE_HALF_SIZE),
margin=np.linalg.norm(self.obj_init_pose.p - self.agent_init_pose.p),
sigmoid="long_tail",
)
reward = reaching_reward
# Only issue gripping reward if agent is close to object
if tcp_to_obj < _CUBE_HALF_SIZE:
# Encourage agent to close gripper
gripping_reward = tolerance(
gripper_dist,
bounds=(0, _CUBE_HALF_SIZE * 2),
margin=_CUBE_HALF_SIZE,
sigmoid="linear",
)
reward += 0.5 * gripping_reward
# Only issue placing reward if object is grasped
if self.agent.check_grasp(self.obj, max_angle=30):
# Add lifting reward
lifting_reward = tolerance(
obj_to_goal_z,
bounds=(0, _GOAL_THRESH),
margin=self.goal_pos[2] - self.obj_init_pose.p[2],
sigmoid="linear",
)
reward += 5 * lifting_reward
if np.abs(self.goal_pos[2] - self.obj.pose.p[2]) < _GOAL_THRESH:
# Add placing reward
placing_reward = tolerance(
obj_to_goal_xy,
bounds=(0, _GOAL_THRESH),
margin=np.linalg.norm(self.goal_pos[:2] - self.obj_init_pose.p[:2]),
sigmoid="linear",
)
reward += 5 * placing_reward
return reward
@register_env("PushCubeMatterport-v0", max_episode_steps=100, override=True)
class PushCubeMatterport(PickCubeMatterport):
def _initialize_task(self):
# Fix goal position
self.goal_pos = np.array([0.2, 0.2, 0.0])
self.goal_site.set_pose(Pose(self.goal_pos))
def compute_dense_reward(self, info, **kwargs):
_CUBE_HALF_SIZE = self.cube_half_size[0]
_GOAL_THRESH = self.goal_thresh
tcp_to_obj = np.linalg.norm(self.obj.pose.p - self.tcp.pose.p)
obj_to_goal = np.linalg.norm(self.goal_pos - self.obj.pose.p)
gripper_dist = np.linalg.norm(
self.agent.finger1_link.pose.p - self.agent.finger2_link.pose.p
)
reaching_reward = tolerance(
tcp_to_obj,
bounds=(0, _CUBE_HALF_SIZE),
margin=np.linalg.norm(self.obj_init_pose.p - self.agent_init_pose.p),
sigmoid="long_tail",
)
reward = reaching_reward
# Only issue gripping reward if agent is close to object
if tcp_to_obj < _CUBE_HALF_SIZE:
# Encourage agent to close gripper
gripping_reward = tolerance(
gripper_dist,
bounds=(0, _CUBE_HALF_SIZE * 2),
margin=_CUBE_HALF_SIZE,
sigmoid="linear",
)
reward += 0.5 * gripping_reward
# Only issue pushing reward if object is grasped
if self.agent.check_grasp(self.obj, max_angle=30):
# Add placing reward
pushing_reward = tolerance(
obj_to_goal,
bounds=(0, _GOAL_THRESH),
margin=np.linalg.norm(self.goal_pos - self.obj_init_pose.p),
sigmoid="linear",
)
reward += 5 * pushing_reward
return reward
@register_env("LiftCubeMatterport-v0", max_episode_steps=100, override=True)
class LiftCubeMatterport(LiftCubeEnv):
def _clear(self):
# Release cached resources
self._renderer.clear_cached_resources()
super()._clear()
def _initialize_task(self):
# Fix goal position
self.goal_pos = np.array([0.0, 0.0, 0.3])
self.goal_site.set_pose(Pose(self.goal_pos))
def _initialize_agent(self):
# Set ee to be near the object
self.agent.reset(QPOS_LOW)
self.agent_init_pose = BASE_POSE
self.agent.robot.set_pose(self.agent_init_pose)
def _initialize_actors(self):
self.obj_init_pose = OBJ_INIT_POSE
self.obj.set_pose(self.obj_init_pose)
def _load_actors(self):
# Load invisible ground
self._add_ground(render=False)
# Load cube
self.obj = self._build_cube(self.cube_half_size)
# Add goal indicator
self.goal_site = self._build_sphere_site(self.goal_thresh)
# Load arena
builder = self._scene.create_actor_builder()
self.arena = load_Matterport(builder)
def get_done(self, info, **kwargs):
# Disable done from task completion
return False
def compute_dense_reward(self, info, **kwargs):
_CUBE_HALF_SIZE = self.cube_half_size[0]
_GOAL_THRESH = self.goal_thresh
tcp_to_obj = np.linalg.norm(self.obj.pose.p - self.tcp.pose.p)
obj_to_goal_z = np.abs(self.goal_pos[2] - self.obj.pose.p[2])
gripper_dist = np.linalg.norm(
self.agent.finger1_link.pose.p - self.agent.finger2_link.pose.p
)
reaching_reward = tolerance(
tcp_to_obj,
bounds=(0, _CUBE_HALF_SIZE),
margin=np.linalg.norm(self.obj_init_pose.p - self.agent_init_pose.p),
sigmoid="long_tail",
)
reward = reaching_reward
# Only issue gripping reward if agent is close to object
if tcp_to_obj < _CUBE_HALF_SIZE:
# Encourage agent to close gripper
gripping_reward = tolerance(
gripper_dist,
bounds=(0, _CUBE_HALF_SIZE * 2),
margin=_CUBE_HALF_SIZE,
sigmoid="linear",
)
reward += 0.5 * gripping_reward
# Only issue placing reward if object is grasped
if self.agent.check_grasp(self.obj, max_angle=30):
# Add lifting reward
lifting_reward = tolerance(
obj_to_goal_z,
bounds=(0, _GOAL_THRESH),
margin=self.goal_pos[2] - self.obj_init_pose.p[2],
sigmoid="linear",
)
reward += 5 * lifting_reward
return reward
@register_env("TurnFaucetMatterport-v0", max_episode_steps=100, override=True)
class TurnFaucetMatterport(TurnFaucetEnv):
def _clear(self):
# Release cached resources
self._renderer.clear_cached_resources()
super()._clear()
def _initialize_agent(self):
# Set ee to be above the faucet
self.agent.reset(QPOS_HIGH)
self.agent_init_pose = BASE_POSE
self.agent.robot.set_pose(self.agent_init_pose)
def _initialize_articulations(self):
q = euler2quat(0, 0, 0)
p = np.array([0.1, 0.0, 0.0])
self.faucet.set_pose(Pose(p, q))
def _load_actors(self):
# Add invisible ground
self._add_ground(render=False)
# Load arena
builder = self._scene.create_actor_builder()
self.arena = load_Matterport(builder)
def get_done(self, info, **kwargs):
# Disable done from task completion
return False
class ManiSkillWrapper(gym.Wrapper):
def __init__(self, env, pixel_obs):
super().__init__(env)
assert env.obs_mode == "rgbd"
self._pixel_obs = pixel_obs
if pixel_obs:
self._observation_space = Box(
low=0, high=255, shape=(3, 64, 64), dtype=np.uint8
)
else:
# States include robot proprioception (agent) and task information (extra)
obs_space = self.env.observation_space
state_spaces = []
state_spaces.extend(
flatten_dict_space_keys(obs_space["agent"]).spaces.values()
)
state_spaces.extend(
flatten_dict_space_keys(obs_space["extra"]).spaces.values()
)
# Concatenate all the state spaces
state_size = sum([space.shape[0] for space in state_spaces])
self._observation_space = Box(-np.inf, np.inf, shape=(state_size,))
def observation(self, observation):
if self._pixel_obs:
obs = observation["image"]["base_camera"]["rgb"]
obs = obs.transpose(2, 0, 1).copy()
return obs
else:
# Concatenate all the states
state = np.hstack(
[
flatten_state_dict(observation["agent"]),
flatten_state_dict(observation["extra"]),
]
)
return state
def reset(self, **kwargs):
return self.observation(self.env.reset(reconfigure=True, **kwargs))
def step(self, action):
obs, reward, done, info = self.env.step(action)
return self.observation(obs), reward, done, info