-
Notifications
You must be signed in to change notification settings - Fork 10
/
metaworld_env.py
235 lines (207 loc) · 7.79 KB
/
metaworld_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
import os
import gym
import numpy as np
from dm_env import StepType, specs
import dm_env
import numpy as np
from gym import spaces
from typing import Any, NamedTuple
from collections import deque
class MetaWorld:
def __init__(
self,
name,
seed=None,
action_repeat=1,
size=(64, 64),
camera=None,
):
import metaworld
from metaworld.envs import (
ALL_V2_ENVIRONMENTS_GOAL_OBSERVABLE,
ALL_V2_ENVIRONMENTS_GOAL_HIDDEN,
)
os.environ["MUJOCO_GL"] = "egl"
task = f"{name}-v2-goal-observable"
env_cls = ALL_V2_ENVIRONMENTS_GOAL_OBSERVABLE[task]
self._env = env_cls(seed=seed)
self._env._freeze_rand_vec = False
self._size = size
self._action_repeat = action_repeat
self._camera = camera
@property
def obs_space(self):
spaces = {
"image": gym.spaces.Box(0, 255, self._size + (3,), dtype=np.uint8),
"reward": gym.spaces.Box(-np.inf, np.inf, (), dtype=np.float32),
"is_first": gym.spaces.Box(0, 1, (), dtype=bool),
"is_last": gym.spaces.Box(0, 1, (), dtype=bool),
"is_terminal": gym.spaces.Box(0, 1, (), dtype=bool),
"state": self._env.observation_space,
"success": gym.spaces.Box(0, 1, (), dtype=bool),
}
return spaces
@property
def act_space(self):
action = self._env.action_space
return {"action": action}
def step(self, action):
assert np.isfinite(action["action"]).all(), action["action"]
reward = 0.0
success = 0.0
for _ in range(self._action_repeat):
state, rew, done, info = self._env.step(action["action"])
success += float(info["success"])
reward += rew or 0.0
success = min(success, 1.0)
assert success in [0.0, 1.0]
obs = {
"reward": reward,
"is_first": False,
"is_last": False, # will be handled by timelimit wrapper
"is_terminal": False, # will be handled by per_episode function
"image": self._env.sim.render(
*self._size, mode="offscreen", camera_name=self._camera
),
"state": state,
"success": success,
}
return obs
def reset(self):
if self._camera == "corner2":
self._env.model.cam_pos[2][:] = [0.75, 0.075, 0.7]
state = self._env.reset()
obs = {
"reward": 0.0,
"is_first": True,
"is_last": False,
"is_terminal": False,
"image": self._env.sim.render(
*self._size, mode="offscreen", camera_name=self._camera
),
"state": state,
"success": False,
}
return obs
class NormalizeAction:
def __init__(self, env, key="action"):
self._env = env
self._key = key
space = env.act_space[key]
self._mask = np.isfinite(space.low) & np.isfinite(space.high)
self._low = np.where(self._mask, space.low, -1)
self._high = np.where(self._mask, space.high, 1)
def __getattr__(self, name):
if name.startswith("__"):
raise AttributeError(name)
try:
return getattr(self._env, name)
except AttributeError:
raise ValueError(name)
@property
def act_space(self):
low = np.where(self._mask, -np.ones_like(self._low), self._low)
high = np.where(self._mask, np.ones_like(self._low), self._high)
space = gym.spaces.Box(low, high, dtype=np.float32)
return {**self._env.act_space, self._key: space}
def step(self, action):
orig = (action[self._key] + 1) / 2 * (self._high - self._low) + self._low
orig = np.where(self._mask, orig, action[self._key])
return self._env.step({**action, self._key: orig})
class TimeLimit:
def __init__(self, env, duration):
self._env = env
self._duration = duration
self._step = None
def __getattr__(self, name):
if name.startswith("__"):
raise AttributeError(name)
try:
return getattr(self._env, name)
except AttributeError:
raise ValueError(name)
def step(self, action):
assert self._step is not None, "Must reset environment."
obs = self._env.step(action)
self._step += 1
if self._duration and self._step >= self._duration:
obs["is_last"] = True
self._step = None
return obs
def reset(self):
self._step = 0
return self._env.reset()
class ExtendedTimeStep(NamedTuple):
step_type: Any
reward: Any
discount: Any
observation: Any
action: Any
success: Any
def first(self):
return self.step_type == StepType.FIRST
def mid(self):
return self.step_type == StepType.MID
def last(self):
return self.step_type == StepType.LAST
def __getitem__(self, attr):
if isinstance(attr, str):
return getattr(self, attr)
else:
return tuple.__getitem__(self, attr)
class metaworld_wrapper():
def __init__(self, env, nstack=3):
self._env = env
self.nstack = 3
wos = env.obs_space['image'] # wrapped ob space
low = np.repeat(wos.low, self.nstack, axis=-1)
high = np.repeat(wos.high, self.nstack, axis=-1)
self.stackedobs = np.zeros(low.shape, low.dtype)
self.observation_space = spaces.Box(low=np.transpose(low, (2, 0, 1)), high=np.transpose(high, (2, 0, 1)), dtype=np.uint8)
def observation_spec(self):
return specs.BoundedArray(self.observation_space.shape,
np.uint8,
0,
255,
name='observation')
def action_spec(self):
return specs.BoundedArray(self._env.act_space['action'].shape,
np.float32,
self._env.act_space['action'].low,
self._env.act_space['action'].high,
'action')
def reset(self):
time_step = self._env.reset()
obs = time_step['image']
self.stackedobs[...] = 0
self.stackedobs[..., -obs.shape[-1]:] = obs
return ExtendedTimeStep(observation=np.transpose(self.stackedobs, (2, 0, 1)),
step_type=StepType.FIRST,
action=np.zeros(self.action_spec().shape, dtype=self.action_spec().dtype),
reward=0.0,
discount=1.0,
success = time_step['success'])
def step(self, action):
action = {'action':action}
time_step = self._env.step(action)
obs = time_step['image']
self.stackedobs = np.roll(self.stackedobs, shift=-obs.shape[-1], axis=-1) #
self.stackedobs[..., -obs.shape[-1]:] = obs
if time_step['is_first']:
step_type = StepType.FIRST
elif time_step['is_last']:
step_type = StepType.LAST
else:
step_type = StepType.MID
return ExtendedTimeStep(observation=np.transpose(self.stackedobs, (2, 0, 1)),
step_type=step_type,
action=action['action'],
reward=time_step['reward'],
discount=1.0,
success = time_step['success'])
def make(name, frame_stack, action_repeat, seed):
env = MetaWorld(name, seed,action_repeat, (84,84), 'corner2')
env = NormalizeAction(env)
env = TimeLimit(env, 250)
env = metaworld_wrapper(env, frame_stack)
return env