-
Notifications
You must be signed in to change notification settings - Fork 18
/
openai_gym_compatibility.py
325 lines (258 loc) · 10.1 KB
/
openai_gym_compatibility.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
"""Compatibility wrappers for OpenAI gym V22 and V26."""
# pyright: reportGeneralTypeIssues=false, reportPrivateImportUsage=false
from __future__ import annotations
import sys
from typing import Any
import gymnasium
from gymnasium import error
from gymnasium.core import ActType, ObsType
from gymnasium.error import MissingArgument
from gymnasium.spaces import (
Box,
Dict,
Discrete,
Graph,
MultiBinary,
MultiDiscrete,
Sequence,
Text,
Tuple,
)
from gymnasium.utils.step_api_compatibility import (
convert_to_terminated_truncated_step_api,
)
if sys.version_info >= (3, 8):
from typing import Protocol, runtime_checkable
else:
from typing_extensions import Protocol, runtime_checkable
try:
import gym
import gym.wrappers
except ImportError as e:
GYM_IMPORT_ERROR = e
else:
GYM_IMPORT_ERROR = None
class GymV26CompatibilityV0(gymnasium.Env[ObsType, ActType]):
"""Converts a Gym v26 environment to a Gymnasium environment."""
def __init__(
self,
env_id: str | None = None,
make_kwargs: dict[str, Any] | None = None,
env: gym.Env | None = None,
):
"""Converts a gym v26 environment to a gymnasium environment.
Either `env_id` or `env` must be passed as arguments.
Args:
env_id: The environment id to use in `gym.make`
make_kwargs: Additional keyword arguments for make
env: An gym environment to wrap.
"""
if GYM_IMPORT_ERROR is not None:
raise error.DependencyNotInstalled(
f"{GYM_IMPORT_ERROR} (Hint: You need to install gym with `pip install gym` to use gym environments"
)
if make_kwargs is None:
make_kwargs = {}
if env is not None:
self.gym_env = env
elif env_id is not None:
self.gym_env = gym.make(env_id, **make_kwargs)
else:
raise MissingArgument(
"Either env_id or env must be provided to create a legacy gym environment."
)
self.gym_env = _strip_default_wrappers(self.gym_env)
self.observation_space = _convert_space(self.gym_env.observation_space)
self.action_space = _convert_space(self.gym_env.action_space)
self.metadata = getattr(self.gym_env, "metadata", {"render_modes": []})
self.render_mode = self.gym_env.render_mode
self.reward_range = getattr(self.gym_env, "reward_range", None)
self.spec = getattr(self.gym_env, "spec", None)
def __getattr__(self, item: str):
"""Gets an attribute that only exists in the base environments."""
return getattr(self.gym_env, item)
def reset(
self, seed: int | None = None, options: dict | None = None
) -> tuple[ObsType, dict]:
"""Resets the environment.
Args:
seed: the seed to reset the environment with
options: the options to reset the environment with
Returns:
(observation, info)
"""
super().reset(seed=seed)
# Options are ignored
return self.gym_env.reset(seed=seed, options=options)
def step(self, action: ActType) -> tuple[ObsType, float, bool, bool, dict]:
"""Steps through the environment.
Args:
action: action to step through the environment with
Returns:
(observation, reward, terminated, truncated, info)
"""
return self.gym_env.step(action)
def render(self):
"""Renders the environment.
Returns:
The rendering of the environment, depending on the render mode
"""
return self.gym_env.render()
def close(self):
"""Closes the environment."""
self.gym_env.close()
@runtime_checkable
class LegacyV22Env(Protocol):
"""A protocol for openai gym v22 environment."""
observation_space: gym.Space
action_space: gym.Space
def reset(self) -> Any:
"""Reset the environment and return the initial observation."""
...
def step(self, action: Any) -> tuple[Any, float, bool, dict]:
"""Run one timestep of the environment's dynamics."""
...
def render(self, mode: str | None = "human") -> Any:
"""Render the environment."""
...
def close(self):
"""Close the environment."""
...
def seed(self, seed: int | None = None):
"""Set the seed for this env's random number generator(s)."""
...
class GymV22CompatibilityV0(gymnasium.Env[ObsType, ActType]):
r"""A wrapper which can transform an environment from the old API to the new API.
Old step API refers to step() method returning (observation, reward, done, info), and reset() only retuning the observation.
New step API refers to step() method returning (observation, reward, terminated, truncated, info) and reset() returning (observation, info).
(Refer to docs for details on the API change)
Known limitations:
- Environments that use `self.np_random` might not work as expected.
"""
def __init__(
self,
env_id: str | None = None,
make_kwargs: dict | None = None,
env: gym.Env | None = None,
render_mode: str | None = None,
):
"""A wrapper which converts old-style envs to valid modern envs.
Some information may be lost in the conversion, so we recommend updating your environment.
"""
if GYM_IMPORT_ERROR is not None:
raise error.DependencyNotInstalled(
f"{GYM_IMPORT_ERROR} (Hint: You need to install gym with `pip install gym` to use gym environments"
)
if make_kwargs is None:
make_kwargs = {}
if env is not None:
gym_env = env
elif env_id is not None:
gym_env = gym.make(env_id, **make_kwargs)
else:
raise MissingArgument(
"Either env_id or env must be provided to create a legacy gym environment."
)
self.observation_space = _convert_space(gym_env.observation_space)
self.action_space = _convert_space(gym_env.action_space)
gym_env = _strip_default_wrappers(gym_env)
self.metadata = getattr(gym_env, "metadata", {"render_modes": []})
self.render_mode = render_mode
self.reward_range = getattr(gym_env, "reward_range", None)
self.spec = getattr(gym_env, "spec", None)
self.gym_env: LegacyV22Env = gym_env
def __getattr__(self, item: str):
"""Gets an attribute that only exists in the base environments."""
return getattr(self.gym_env, item)
def reset(
self, seed: int | None = None, options: dict | None = None
) -> tuple[ObsType, dict]:
"""Resets the environment.
Args:
seed: the seed to reset the environment with
options: the options to reset the environment with
Returns:
(observation, info)
"""
if seed is not None:
self.gym_env.seed(seed)
# Options are ignored
if self.render_mode == "human":
self.render()
return self.gym_env.reset(), {}
def step(self, action: ActType) -> tuple[Any, float, bool, bool, dict]:
"""Steps through the environment.
Args:
action: action to step through the environment with
Returns:
(observation, reward, terminated, truncated, info)
"""
obs, reward, done, info = self.gym_env.step(action)
if self.render_mode == "human":
self.render()
return convert_to_terminated_truncated_step_api((obs, reward, done, info))
def render(self) -> Any:
"""Renders the environment.
Returns:
The rendering of the environment, depending on the render mode
"""
return self.gym_env.render(mode=self.render_mode)
def close(self):
"""Closes the environment."""
self.gym_env.close()
def __str__(self):
"""Returns the wrapper name and the unwrapped environment string."""
return f"<{type(self).__name__}{self.gym_env}>"
def __repr__(self):
"""Returns the string representation of the wrapper."""
return str(self)
def _strip_default_wrappers(env: gym.Env) -> gym.Env:
"""Strips builtin wrappers from the environment.
Args:
env: the environment to strip builtin wrappers from
Returns:
The environment without builtin wrappers
"""
default_wrappers = (
gym.wrappers.render_collection.RenderCollection,
gym.wrappers.human_rendering.HumanRendering,
)
while isinstance(env, default_wrappers):
env = env.env
return env
def _convert_space(space: gym.Space) -> gymnasium.Space:
"""Converts a gym space to a gymnasium space.
Args:
space: the space to convert
Returns:
The converted space
"""
if isinstance(space, gym.spaces.Discrete):
return Discrete(n=space.n)
elif isinstance(space, gym.spaces.Box):
return Box(low=space.low, high=space.high, shape=space.shape, dtype=space.dtype)
elif isinstance(space, gym.spaces.MultiDiscrete):
return MultiDiscrete(nvec=space.nvec)
elif isinstance(space, gym.spaces.MultiBinary):
return MultiBinary(n=space.n)
elif isinstance(space, gym.spaces.Tuple):
return Tuple(spaces=tuple(map(_convert_space, space.spaces)))
elif isinstance(space, gym.spaces.Dict):
return Dict(spaces={k: _convert_space(v) for k, v in space.spaces.items()})
elif isinstance(space, gym.spaces.Sequence):
return Sequence(space=_convert_space(space.feature_space))
elif isinstance(space, gym.spaces.Graph):
return Graph(
node_space=_convert_space(space.node_space), # type: ignore
edge_space=_convert_space(space.edge_space), # type: ignore
)
elif isinstance(space, gym.spaces.Text):
return Text(
max_length=space.max_length,
min_length=space.min_length,
charset=space._char_str,
)
else:
raise NotImplementedError(
f"Cannot convert space of type {space}. Please upgrade your code to gymnasium."
)