Spaces:
Runtime error

Energetic26 commited on
Commit
da15f1f
·
1 Parent(s): 4b87938

uploading the gym itself

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. app.py +15 -31
  2. gym/__init__.py +18 -0
  3. gym/__pycache__/__init__.cpython-39.pyc +0 -0
  4. gym/__pycache__/core.cpython-39.pyc +0 -0
  5. gym/__pycache__/error.cpython-39.pyc +0 -0
  6. gym/__pycache__/logger.cpython-39.pyc +0 -0
  7. gym/__pycache__/version.cpython-39.pyc +0 -0
  8. gym/core.py +357 -0
  9. gym/envs/__init__.py +646 -0
  10. gym/envs/__pycache__/__init__.cpython-39.pyc +0 -0
  11. gym/envs/__pycache__/registration.cpython-39.pyc +0 -0
  12. gym/envs/atari/__init__.py +1 -0
  13. gym/envs/atari/__pycache__/__init__.cpython-39.pyc +0 -0
  14. gym/envs/atari/__pycache__/environment.cpython-39.pyc +0 -0
  15. gym/envs/atari/environment.py +403 -0
  16. gym/envs/box2d/__init__.py +8 -0
  17. gym/envs/box2d/__pycache__/__init__.cpython-39.pyc +0 -0
  18. gym/envs/box2d/__pycache__/bipedal_walker.cpython-39.pyc +0 -0
  19. gym/envs/box2d/__pycache__/car_dynamics.cpython-39.pyc +0 -0
  20. gym/envs/box2d/__pycache__/car_racing.cpython-39.pyc +0 -0
  21. gym/envs/box2d/__pycache__/lunar_lander.cpython-39.pyc +0 -0
  22. gym/envs/box2d/bipedal_walker.py +658 -0
  23. gym/envs/box2d/car_dynamics.py +313 -0
  24. gym/envs/box2d/car_racing.py +652 -0
  25. gym/envs/box2d/lunar_lander.py +534 -0
  26. gym/envs/classic_control/__init__.py +5 -0
  27. gym/envs/classic_control/__pycache__/__init__.cpython-39.pyc +0 -0
  28. gym/envs/classic_control/__pycache__/acrobot.cpython-39.pyc +0 -0
  29. gym/envs/classic_control/__pycache__/cartpole.cpython-39.pyc +0 -0
  30. gym/envs/classic_control/__pycache__/continuous_mountain_car.cpython-39.pyc +0 -0
  31. gym/envs/classic_control/__pycache__/mountain_car.cpython-39.pyc +0 -0
  32. gym/envs/classic_control/__pycache__/pendulum.cpython-39.pyc +0 -0
  33. gym/envs/classic_control/__pycache__/rendering.cpython-39.pyc +0 -0
  34. gym/envs/classic_control/acrobot.py +323 -0
  35. gym/envs/classic_control/assets/clockwise.png +0 -0
  36. gym/envs/classic_control/cartpole.py +234 -0
  37. gym/envs/classic_control/continuous_mountain_car.py +195 -0
  38. gym/envs/classic_control/mountain_car.py +177 -0
  39. gym/envs/classic_control/pendulum.py +94 -0
  40. gym/envs/classic_control/rendering.py +458 -0
  41. gym/envs/mujoco/__init__.py +17 -0
  42. gym/envs/mujoco/__pycache__/__init__.cpython-39.pyc +0 -0
  43. gym/envs/mujoco/__pycache__/ant.cpython-39.pyc +0 -0
  44. gym/envs/mujoco/__pycache__/ant_v3.cpython-39.pyc +0 -0
  45. gym/envs/mujoco/__pycache__/half_cheetah.cpython-39.pyc +0 -0
  46. gym/envs/mujoco/__pycache__/half_cheetah_v3.cpython-39.pyc +0 -0
  47. gym/envs/mujoco/__pycache__/hopper.cpython-39.pyc +0 -0
  48. gym/envs/mujoco/__pycache__/hopper_v3.cpython-39.pyc +0 -0
  49. gym/envs/mujoco/__pycache__/humanoid.cpython-39.pyc +0 -0
  50. gym/envs/mujoco/__pycache__/humanoid_v3.cpython-39.pyc +0 -0
app.py CHANGED
@@ -1,9 +1,12 @@
 
1
  import glob
2
  import gym
3
  import time
4
  import streamlit as st
5
  from stable_baselines3 import PPO
6
- import cv2
 
 
7
 
8
  st.write(gym.__version__)
9
 
@@ -11,43 +14,24 @@ env = gym.make('BipedalWalker-v3')
11
  model = PPO.load("bipedalwalker_ppo")
12
 
13
  video_every = 1
14
-
15
- # Define a custom video recording wrapper
16
- class VideoRecorder(gym.Wrapper):
17
- def __init__(self, env):
18
- super().__init__(env)
19
- self.frames = []
20
-
21
- def reset(self, **kwargs):
22
- self.frames = []
23
- return self.env.reset(**kwargs)
24
-
25
- def step(self, action):
26
- obs, reward, done, info = self.env.step(action)
27
- frame = self.env.render(mode='rgb_array')
28
- self.frames.append(frame)
29
- if done:
30
- self.save_video()
31
- return obs, reward, done, info
32
-
33
- def save_video(self):
34
- fourcc = cv2.VideoWriter_fourcc(*'mp4v')
35
- out = cv2.VideoWriter('video.mp4', fourcc, self.env.metadata['video.frames_per_second'], (self.frames[0].shape[1], self.frames[0].shape[0]))
36
- for frame in self.frames:
37
- out.write(frame)
38
- out.release()
39
-
40
- env = VideoRecorder(env) # Wrap the environment with the custom video recording wrapper
41
 
42
  obs = env.reset()
43
-
44
- for i in range(1000):
45
  action, _ = model.predict(obs, deterministic=True)
46
- obs, reward, done, info = env.step(action)
47
  if done :
48
  env.reset()
49
  env.close()
50
 
 
 
 
 
 
 
 
 
51
  video_file = open("video.mp4", 'rb')
52
  video_bytes = video_file.read()
53
  st.video(video_bytes, format='mp4')
 
1
+ import os
2
  import glob
3
  import gym
4
  import time
5
  import streamlit as st
6
  from stable_baselines3 import PPO
7
+
8
+ if os.path.exists("video.mp4"):
9
+ os.remove(".video.mp4")
10
 
11
  st.write(gym.__version__)
12
 
 
14
  model = PPO.load("bipedalwalker_ppo")
15
 
16
  video_every = 1
17
+ env = gym.wrappers.RecordVideo(env, 'video.mp4')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  obs = env.reset()
20
+ for i in range(100):
 
21
  action, _ = model.predict(obs, deterministic=True)
22
+ obs,reward,done,info =env.step(action)
23
  if done :
24
  env.reset()
25
  env.close()
26
 
27
+ # Change the current working directory to the 'video' folder
28
+ # os.chdir('./video')
29
+
30
+ # Find the mp4 file in the directory
31
+ # mp4_files = glob.glob("*.mp4")
32
+
33
+ # Check if the file exists
34
+
35
  video_file = open("video.mp4", 'rb')
36
  video_bytes = video_file.read()
37
  st.video(video_bytes, format='mp4')
gym/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from gym import error
2
+ from gym.version import VERSION as __version__
3
+
4
+ from gym.core import (
5
+ Env,
6
+ GoalEnv,
7
+ Wrapper,
8
+ ObservationWrapper,
9
+ ActionWrapper,
10
+ RewardWrapper,
11
+ )
12
+ from gym.spaces import Space
13
+ from gym.envs import make, spec, register
14
+ from gym import logger
15
+ from gym import vector
16
+ from gym import wrappers
17
+
18
+ __all__ = ["Env", "Space", "Wrapper", "make", "spec", "register"]
gym/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (638 Bytes). View file
 
gym/__pycache__/core.cpython-39.pyc ADDED
Binary file (14.1 kB). View file
 
gym/__pycache__/error.cpython-39.pyc ADDED
Binary file (6.62 kB). View file
 
gym/__pycache__/logger.cpython-39.pyc ADDED
Binary file (1.49 kB). View file
 
gym/__pycache__/version.cpython-39.pyc ADDED
Binary file (166 Bytes). View file
 
gym/core.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import abstractmethod
2
+
3
+ import gym
4
+ from gym import error
5
+ from gym.utils import closer
6
+
7
+
8
+ class Env(object):
9
+ """The main OpenAI Gym class. It encapsulates an environment with
10
+ arbitrary behind-the-scenes dynamics. An environment can be
11
+ partially or fully observed.
12
+
13
+ The main API methods that users of this class need to know are:
14
+
15
+ step
16
+ reset
17
+ render
18
+ close
19
+ seed
20
+
21
+ And set the following attributes:
22
+
23
+ action_space: The Space object corresponding to valid actions
24
+ observation_space: The Space object corresponding to valid observations
25
+ reward_range: A tuple corresponding to the min and max possible rewards
26
+
27
+ Note: a default reward range set to [-inf,+inf] already exists. Set it if you want a narrower range.
28
+
29
+ The methods are accessed publicly as "step", "reset", etc...
30
+ """
31
+
32
+ # Set this in SOME subclasses
33
+ metadata = {"render.modes": []}
34
+ reward_range = (-float("inf"), float("inf"))
35
+ spec = None
36
+
37
+ # Set these in ALL subclasses
38
+ action_space = None
39
+ observation_space = None
40
+
41
+ @abstractmethod
42
+ def step(self, action):
43
+ """Run one timestep of the environment's dynamics. When end of
44
+ episode is reached, you are responsible for calling `reset()`
45
+ to reset this environment's state.
46
+
47
+ Accepts an action and returns a tuple (observation, reward, done, info).
48
+
49
+ Args:
50
+ action (object): an action provided by the agent
51
+
52
+ Returns:
53
+ observation (object): agent's observation of the current environment
54
+ reward (float) : amount of reward returned after previous action
55
+ done (bool): whether the episode has ended, in which case further step() calls will return undefined results
56
+ info (dict): contains auxiliary diagnostic information (helpful for debugging, and sometimes learning)
57
+ """
58
+ raise NotImplementedError
59
+
60
+ @abstractmethod
61
+ def reset(self):
62
+ """Resets the environment to an initial state and returns an initial
63
+ observation.
64
+
65
+ Note that this function should not reset the environment's random
66
+ number generator(s); random variables in the environment's state should
67
+ be sampled independently between multiple calls to `reset()`. In other
68
+ words, each call of `reset()` should yield an environment suitable for
69
+ a new episode, independent of previous episodes.
70
+
71
+ Returns:
72
+ observation (object): the initial observation.
73
+ """
74
+ raise NotImplementedError
75
+
76
+ @abstractmethod
77
+ def render(self, mode="human"):
78
+ """Renders the environment.
79
+
80
+ The set of supported modes varies per environment. (And some
81
+ environments do not support rendering at all.) By convention,
82
+ if mode is:
83
+
84
+ - human: render to the current display or terminal and
85
+ return nothing. Usually for human consumption.
86
+ - rgb_array: Return an numpy.ndarray with shape (x, y, 3),
87
+ representing RGB values for an x-by-y pixel image, suitable
88
+ for turning into a video.
89
+ - ansi: Return a string (str) or StringIO.StringIO containing a
90
+ terminal-style text representation. The text can include newlines
91
+ and ANSI escape sequences (e.g. for colors).
92
+
93
+ Note:
94
+ Make sure that your class's metadata 'render.modes' key includes
95
+ the list of supported modes. It's recommended to call super()
96
+ in implementations to use the functionality of this method.
97
+
98
+ Args:
99
+ mode (str): the mode to render with
100
+
101
+ Example:
102
+
103
+ class MyEnv(Env):
104
+ metadata = {'render.modes': ['human', 'rgb_array']}
105
+
106
+ def render(self, mode='human'):
107
+ if mode == 'rgb_array':
108
+ return np.array(...) # return RGB frame suitable for video
109
+ elif mode == 'human':
110
+ ... # pop up a window and render
111
+ else:
112
+ super(MyEnv, self).render(mode=mode) # just raise an exception
113
+ """
114
+ raise NotImplementedError
115
+
116
+ def close(self):
117
+ """Override close in your subclass to perform any necessary cleanup.
118
+
119
+ Environments will automatically close() themselves when
120
+ garbage collected or when the program exits.
121
+ """
122
+ pass
123
+
124
+ def seed(self, seed=None):
125
+ """Sets the seed for this env's random number generator(s).
126
+
127
+ Note:
128
+ Some environments use multiple pseudorandom number generators.
129
+ We want to capture all such seeds used in order to ensure that
130
+ there aren't accidental correlations between multiple generators.
131
+
132
+ Returns:
133
+ list<bigint>: Returns the list of seeds used in this env's random
134
+ number generators. The first value in the list should be the
135
+ "main" seed, or the value which a reproducer should pass to
136
+ 'seed'. Often, the main seed equals the provided 'seed', but
137
+ this won't be true if seed=None, for example.
138
+ """
139
+ return
140
+
141
+ @property
142
+ def unwrapped(self):
143
+ """Completely unwrap this env.
144
+
145
+ Returns:
146
+ gym.Env: The base non-wrapped gym.Env instance
147
+ """
148
+ return self
149
+
150
+ def __str__(self):
151
+ if self.spec is None:
152
+ return "<{} instance>".format(type(self).__name__)
153
+ else:
154
+ return "<{}<{}>>".format(type(self).__name__, self.spec.id)
155
+
156
+ def __enter__(self):
157
+ """Support with-statement for the environment."""
158
+ return self
159
+
160
+ def __exit__(self, *args):
161
+ """Support with-statement for the environment."""
162
+ self.close()
163
+ # propagate exception
164
+ return False
165
+
166
+
167
+ class GoalEnv(Env):
168
+ """A goal-based environment. It functions just as any regular OpenAI Gym environment but it
169
+ imposes a required structure on the observation_space. More concretely, the observation
170
+ space is required to contain at least three elements, namely `observation`, `desired_goal`, and
171
+ `achieved_goal`. Here, `desired_goal` specifies the goal that the agent should attempt to achieve.
172
+ `achieved_goal` is the goal that it currently achieved instead. `observation` contains the
173
+ actual observations of the environment as per usual.
174
+ """
175
+
176
+ def reset(self):
177
+ # Enforce that each GoalEnv uses a Goal-compatible observation space.
178
+ if not isinstance(self.observation_space, gym.spaces.Dict):
179
+ raise error.Error(
180
+ "GoalEnv requires an observation space of type gym.spaces.Dict"
181
+ )
182
+ for key in ["observation", "achieved_goal", "desired_goal"]:
183
+ if key not in self.observation_space.spaces:
184
+ raise error.Error(
185
+ 'GoalEnv requires the "{}" key to be part of the observation dictionary.'.format(
186
+ key
187
+ )
188
+ )
189
+
190
+ @abstractmethod
191
+ def compute_reward(self, achieved_goal, desired_goal, info):
192
+ """Compute the step reward. This externalizes the reward function and makes
193
+ it dependent on a desired goal and the one that was achieved. If you wish to include
194
+ additional rewards that are independent of the goal, you can include the necessary values
195
+ to derive it in 'info' and compute it accordingly.
196
+
197
+ Args:
198
+ achieved_goal (object): the goal that was achieved during execution
199
+ desired_goal (object): the desired goal that we asked the agent to attempt to achieve
200
+ info (dict): an info dictionary with additional information
201
+
202
+ Returns:
203
+ float: The reward that corresponds to the provided achieved goal w.r.t. to the desired
204
+ goal. Note that the following should always hold true:
205
+
206
+ ob, reward, done, info = env.step()
207
+ assert reward == env.compute_reward(ob['achieved_goal'], ob['desired_goal'], info)
208
+ """
209
+ raise NotImplementedError
210
+
211
+
212
+ class Wrapper(Env):
213
+ """Wraps the environment to allow a modular transformation.
214
+
215
+ This class is the base class for all wrappers. The subclass could override
216
+ some methods to change the behavior of the original environment without touching the
217
+ original code.
218
+
219
+ .. note::
220
+
221
+ Don't forget to call ``super().__init__(env)`` if the subclass overrides :meth:`__init__`.
222
+
223
+ """
224
+
225
+ def __init__(self, env):
226
+ self.env = env
227
+
228
+ self._action_space = None
229
+ self._observation_space = None
230
+ self._reward_range = None
231
+ self._metadata = None
232
+
233
+ def __getattr__(self, name):
234
+ if name.startswith("_"):
235
+ raise AttributeError(
236
+ "attempted to get missing private attribute '{}'".format(name)
237
+ )
238
+ return getattr(self.env, name)
239
+
240
+ @property
241
+ def spec(self):
242
+ return self.env.spec
243
+
244
+ @classmethod
245
+ def class_name(cls):
246
+ return cls.__name__
247
+
248
+ @property
249
+ def action_space(self):
250
+ if self._action_space is None:
251
+ return self.env.action_space
252
+ return self._action_space
253
+
254
+ @action_space.setter
255
+ def action_space(self, space):
256
+ self._action_space = space
257
+
258
+ @property
259
+ def observation_space(self):
260
+ if self._observation_space is None:
261
+ return self.env.observation_space
262
+ return self._observation_space
263
+
264
+ @observation_space.setter
265
+ def observation_space(self, space):
266
+ self._observation_space = space
267
+
268
+ @property
269
+ def reward_range(self):
270
+ if self._reward_range is None:
271
+ return self.env.reward_range
272
+ return self._reward_range
273
+
274
+ @reward_range.setter
275
+ def reward_range(self, value):
276
+ self._reward_range = value
277
+
278
+ @property
279
+ def metadata(self):
280
+ if self._metadata is None:
281
+ return self.env.metadata
282
+ return self._metadata
283
+
284
+ @metadata.setter
285
+ def metadata(self, value):
286
+ self._metadata = value
287
+
288
+ def step(self, action):
289
+ return self.env.step(action)
290
+
291
+ def reset(self, **kwargs):
292
+ return self.env.reset(**kwargs)
293
+
294
+ def render(self, mode="human", **kwargs):
295
+ return self.env.render(mode, **kwargs)
296
+
297
+ def close(self):
298
+ return self.env.close()
299
+
300
+ def seed(self, seed=None):
301
+ return self.env.seed(seed)
302
+
303
+ def compute_reward(self, achieved_goal, desired_goal, info):
304
+ return self.env.compute_reward(achieved_goal, desired_goal, info)
305
+
306
+ def __str__(self):
307
+ return "<{}{}>".format(type(self).__name__, self.env)
308
+
309
+ def __repr__(self):
310
+ return str(self)
311
+
312
+ @property
313
+ def unwrapped(self):
314
+ return self.env.unwrapped
315
+
316
+
317
+ class ObservationWrapper(Wrapper):
318
+ def reset(self, **kwargs):
319
+ observation = self.env.reset(**kwargs)
320
+ return self.observation(observation)
321
+
322
+ def step(self, action):
323
+ observation, reward, done, info = self.env.step(action)
324
+ return self.observation(observation), reward, done, info
325
+
326
+ @abstractmethod
327
+ def observation(self, observation):
328
+ raise NotImplementedError
329
+
330
+
331
+ class RewardWrapper(Wrapper):
332
+ def reset(self, **kwargs):
333
+ return self.env.reset(**kwargs)
334
+
335
+ def step(self, action):
336
+ observation, reward, done, info = self.env.step(action)
337
+ return observation, self.reward(reward), done, info
338
+
339
+ @abstractmethod
340
+ def reward(self, reward):
341
+ raise NotImplementedError
342
+
343
+
344
+ class ActionWrapper(Wrapper):
345
+ def reset(self, **kwargs):
346
+ return self.env.reset(**kwargs)
347
+
348
+ def step(self, action):
349
+ return self.env.step(self.action(action))
350
+
351
+ @abstractmethod
352
+ def action(self, action):
353
+ raise NotImplementedError
354
+
355
+ @abstractmethod
356
+ def reverse_action(self, action):
357
+ raise NotImplementedError
gym/envs/__init__.py ADDED
@@ -0,0 +1,646 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from gym.envs.registration import (
2
+ registry,
3
+ register,
4
+ make,
5
+ spec,
6
+ load_env_plugins as _load_env_plugins,
7
+ )
8
+
9
+ # Hook to load plugins from entry points
10
+ _load_env_plugins()
11
+
12
+
13
+ # Classic
14
+ # ----------------------------------------
15
+
16
+ register(
17
+ id="CartPole-v0",
18
+ entry_point="gym.envs.classic_control:CartPoleEnv",
19
+ max_episode_steps=200,
20
+ reward_threshold=195.0,
21
+ )
22
+
23
+ register(
24
+ id="CartPole-v1",
25
+ entry_point="gym.envs.classic_control:CartPoleEnv",
26
+ max_episode_steps=500,
27
+ reward_threshold=475.0,
28
+ )
29
+
30
+ register(
31
+ id="MountainCar-v0",
32
+ entry_point="gym.envs.classic_control:MountainCarEnv",
33
+ max_episode_steps=200,
34
+ reward_threshold=-110.0,
35
+ )
36
+
37
+ register(
38
+ id="MountainCarContinuous-v0",
39
+ entry_point="gym.envs.classic_control:Continuous_MountainCarEnv",
40
+ max_episode_steps=999,
41
+ reward_threshold=90.0,
42
+ )
43
+
44
+ register(
45
+ id="Pendulum-v1",
46
+ entry_point="gym.envs.classic_control:PendulumEnv",
47
+ max_episode_steps=200,
48
+ )
49
+
50
+ register(
51
+ id="Acrobot-v1",
52
+ entry_point="gym.envs.classic_control:AcrobotEnv",
53
+ reward_threshold=-100.0,
54
+ max_episode_steps=500,
55
+ )
56
+
57
+ # Box2d
58
+ # ----------------------------------------
59
+
60
+ register(
61
+ id="LunarLander-v2",
62
+ entry_point="gym.envs.box2d:LunarLander",
63
+ max_episode_steps=1000,
64
+ reward_threshold=200,
65
+ )
66
+
67
+ register(
68
+ id="LunarLanderContinuous-v2",
69
+ entry_point="gym.envs.box2d:LunarLanderContinuous",
70
+ max_episode_steps=1000,
71
+ reward_threshold=200,
72
+ )
73
+
74
+ register(
75
+ id="BipedalWalker-v3",
76
+ entry_point="gym.envs.box2d:BipedalWalker",
77
+ max_episode_steps=1600,
78
+ reward_threshold=300,
79
+ )
80
+
81
+ register(
82
+ id="BipedalWalkerHardcore-v3",
83
+ entry_point="gym.envs.box2d:BipedalWalkerHardcore",
84
+ max_episode_steps=2000,
85
+ reward_threshold=300,
86
+ )
87
+
88
+ register(
89
+ id="CarRacing-v0",
90
+ entry_point="gym.envs.box2d:CarRacing",
91
+ max_episode_steps=1000,
92
+ reward_threshold=900,
93
+ )
94
+
95
+ # Toy Text
96
+ # ----------------------------------------
97
+
98
+ register(
99
+ id="Blackjack-v1",
100
+ entry_point="gym.envs.toy_text:BlackjackEnv",
101
+ kwargs={"sab": True, "natural": False},
102
+ )
103
+
104
+ register(
105
+ id="FrozenLake-v1",
106
+ entry_point="gym.envs.toy_text:FrozenLakeEnv",
107
+ kwargs={"map_name": "4x4"},
108
+ max_episode_steps=100,
109
+ reward_threshold=0.70, # optimum = 0.74
110
+ )
111
+
112
+ register(
113
+ id="FrozenLake8x8-v1",
114
+ entry_point="gym.envs.toy_text:FrozenLakeEnv",
115
+ kwargs={"map_name": "8x8"},
116
+ max_episode_steps=200,
117
+ reward_threshold=0.85, # optimum = 0.91
118
+ )
119
+
120
+ register(
121
+ id="CliffWalking-v0",
122
+ entry_point="gym.envs.toy_text:CliffWalkingEnv",
123
+ )
124
+
125
+ register(
126
+ id="Taxi-v3",
127
+ entry_point="gym.envs.toy_text:TaxiEnv",
128
+ reward_threshold=8, # optimum = 8.46
129
+ max_episode_steps=200,
130
+ )
131
+
132
+ # Mujoco
133
+ # ----------------------------------------
134
+
135
+ # 2D
136
+
137
+ register(
138
+ id="Reacher-v2",
139
+ entry_point="gym.envs.mujoco:ReacherEnv",
140
+ max_episode_steps=50,
141
+ reward_threshold=-3.75,
142
+ )
143
+
144
+ register(
145
+ id="Pusher-v2",
146
+ entry_point="gym.envs.mujoco:PusherEnv",
147
+ max_episode_steps=100,
148
+ reward_threshold=0.0,
149
+ )
150
+
151
+ register(
152
+ id="Thrower-v2",
153
+ entry_point="gym.envs.mujoco:ThrowerEnv",
154
+ max_episode_steps=100,
155
+ reward_threshold=0.0,
156
+ )
157
+
158
+ register(
159
+ id="Striker-v2",
160
+ entry_point="gym.envs.mujoco:StrikerEnv",
161
+ max_episode_steps=100,
162
+ reward_threshold=0.0,
163
+ )
164
+
165
+ register(
166
+ id="InvertedPendulum-v2",
167
+ entry_point="gym.envs.mujoco:InvertedPendulumEnv",
168
+ max_episode_steps=1000,
169
+ reward_threshold=950.0,
170
+ )
171
+
172
+ register(
173
+ id="InvertedDoublePendulum-v2",
174
+ entry_point="gym.envs.mujoco:InvertedDoublePendulumEnv",
175
+ max_episode_steps=1000,
176
+ reward_threshold=9100.0,
177
+ )
178
+
179
+ register(
180
+ id="HalfCheetah-v2",
181
+ entry_point="gym.envs.mujoco:HalfCheetahEnv",
182
+ max_episode_steps=1000,
183
+ reward_threshold=4800.0,
184
+ )
185
+
186
+ register(
187
+ id="HalfCheetah-v3",
188
+ entry_point="gym.envs.mujoco.half_cheetah_v3:HalfCheetahEnv",
189
+ max_episode_steps=1000,
190
+ reward_threshold=4800.0,
191
+ )
192
+
193
+ register(
194
+ id="Hopper-v2",
195
+ entry_point="gym.envs.mujoco:HopperEnv",
196
+ max_episode_steps=1000,
197
+ reward_threshold=3800.0,
198
+ )
199
+
200
+ register(
201
+ id="Hopper-v3",
202
+ entry_point="gym.envs.mujoco.hopper_v3:HopperEnv",
203
+ max_episode_steps=1000,
204
+ reward_threshold=3800.0,
205
+ )
206
+
207
+ register(
208
+ id="Swimmer-v2",
209
+ entry_point="gym.envs.mujoco:SwimmerEnv",
210
+ max_episode_steps=1000,
211
+ reward_threshold=360.0,
212
+ )
213
+
214
+ register(
215
+ id="Swimmer-v3",
216
+ entry_point="gym.envs.mujoco.swimmer_v3:SwimmerEnv",
217
+ max_episode_steps=1000,
218
+ reward_threshold=360.0,
219
+ )
220
+
221
+ register(
222
+ id="Walker2d-v2",
223
+ max_episode_steps=1000,
224
+ entry_point="gym.envs.mujoco:Walker2dEnv",
225
+ )
226
+
227
+ register(
228
+ id="Walker2d-v3",
229
+ max_episode_steps=1000,
230
+ entry_point="gym.envs.mujoco.walker2d_v3:Walker2dEnv",
231
+ )
232
+
233
+ register(
234
+ id="Ant-v2",
235
+ entry_point="gym.envs.mujoco:AntEnv",
236
+ max_episode_steps=1000,
237
+ reward_threshold=6000.0,
238
+ )
239
+
240
+ register(
241
+ id="Ant-v3",
242
+ entry_point="gym.envs.mujoco.ant_v3:AntEnv",
243
+ max_episode_steps=1000,
244
+ reward_threshold=6000.0,
245
+ )
246
+
247
+ register(
248
+ id="Humanoid-v2",
249
+ entry_point="gym.envs.mujoco:HumanoidEnv",
250
+ max_episode_steps=1000,
251
+ )
252
+
253
+ register(
254
+ id="Humanoid-v3",
255
+ entry_point="gym.envs.mujoco.humanoid_v3:HumanoidEnv",
256
+ max_episode_steps=1000,
257
+ )
258
+
259
+ register(
260
+ id="HumanoidStandup-v2",
261
+ entry_point="gym.envs.mujoco:HumanoidStandupEnv",
262
+ max_episode_steps=1000,
263
+ )
264
+
265
+ # Robotics
266
+ # ----------------------------------------
267
+
268
+
269
+ def _merge(a, b):
270
+ a.update(b)
271
+ return a
272
+
273
+
274
+ for reward_type in ["sparse", "dense"]:
275
+ suffix = "Dense" if reward_type == "dense" else ""
276
+ kwargs = {
277
+ "reward_type": reward_type,
278
+ }
279
+
280
+ # Fetch
281
+ register(
282
+ id="FetchSlide{}-v1".format(suffix),
283
+ entry_point="gym.envs.robotics:FetchSlideEnv",
284
+ kwargs=kwargs,
285
+ max_episode_steps=50,
286
+ )
287
+
288
+ register(
289
+ id="FetchPickAndPlace{}-v1".format(suffix),
290
+ entry_point="gym.envs.robotics:FetchPickAndPlaceEnv",
291
+ kwargs=kwargs,
292
+ max_episode_steps=50,
293
+ )
294
+
295
+ register(
296
+ id="FetchReach{}-v1".format(suffix),
297
+ entry_point="gym.envs.robotics:FetchReachEnv",
298
+ kwargs=kwargs,
299
+ max_episode_steps=50,
300
+ )
301
+
302
+ register(
303
+ id="FetchPush{}-v1".format(suffix),
304
+ entry_point="gym.envs.robotics:FetchPushEnv",
305
+ kwargs=kwargs,
306
+ max_episode_steps=50,
307
+ )
308
+
309
+ # Hand
310
+ register(
311
+ id="HandReach{}-v0".format(suffix),
312
+ entry_point="gym.envs.robotics:HandReachEnv",
313
+ kwargs=kwargs,
314
+ max_episode_steps=50,
315
+ )
316
+
317
+ register(
318
+ id="HandManipulateBlockRotateZ{}-v0".format(suffix),
319
+ entry_point="gym.envs.robotics:HandBlockEnv",
320
+ kwargs=_merge({"target_position": "ignore", "target_rotation": "z"}, kwargs),
321
+ max_episode_steps=100,
322
+ )
323
+
324
+ register(
325
+ id="HandManipulateBlockRotateZTouchSensors{}-v0".format(suffix),
326
+ entry_point="gym.envs.robotics:HandBlockTouchSensorsEnv",
327
+ kwargs=_merge(
328
+ {
329
+ "target_position": "ignore",
330
+ "target_rotation": "z",
331
+ "touch_get_obs": "boolean",
332
+ },
333
+ kwargs,
334
+ ),
335
+ max_episode_steps=100,
336
+ )
337
+
338
+ register(
339
+ id="HandManipulateBlockRotateZTouchSensors{}-v1".format(suffix),
340
+ entry_point="gym.envs.robotics:HandBlockTouchSensorsEnv",
341
+ kwargs=_merge(
342
+ {
343
+ "target_position": "ignore",
344
+ "target_rotation": "z",
345
+ "touch_get_obs": "sensordata",
346
+ },
347
+ kwargs,
348
+ ),
349
+ max_episode_steps=100,
350
+ )
351
+
352
+ register(
353
+ id="HandManipulateBlockRotateParallel{}-v0".format(suffix),
354
+ entry_point="gym.envs.robotics:HandBlockEnv",
355
+ kwargs=_merge(
356
+ {"target_position": "ignore", "target_rotation": "parallel"}, kwargs
357
+ ),
358
+ max_episode_steps=100,
359
+ )
360
+
361
+ register(
362
+ id="HandManipulateBlockRotateParallelTouchSensors{}-v0".format(suffix),
363
+ entry_point="gym.envs.robotics:HandBlockTouchSensorsEnv",
364
+ kwargs=_merge(
365
+ {
366
+ "target_position": "ignore",
367
+ "target_rotation": "parallel",
368
+ "touch_get_obs": "boolean",
369
+ },
370
+ kwargs,
371
+ ),
372
+ max_episode_steps=100,
373
+ )
374
+
375
+ register(
376
+ id="HandManipulateBlockRotateParallelTouchSensors{}-v1".format(suffix),
377
+ entry_point="gym.envs.robotics:HandBlockTouchSensorsEnv",
378
+ kwargs=_merge(
379
+ {
380
+ "target_position": "ignore",
381
+ "target_rotation": "parallel",
382
+ "touch_get_obs": "sensordata",
383
+ },
384
+ kwargs,
385
+ ),
386
+ max_episode_steps=100,
387
+ )
388
+
389
+ register(
390
+ id="HandManipulateBlockRotateXYZ{}-v0".format(suffix),
391
+ entry_point="gym.envs.robotics:HandBlockEnv",
392
+ kwargs=_merge({"target_position": "ignore", "target_rotation": "xyz"}, kwargs),
393
+ max_episode_steps=100,
394
+ )
395
+
396
+ register(
397
+ id="HandManipulateBlockRotateXYZTouchSensors{}-v0".format(suffix),
398
+ entry_point="gym.envs.robotics:HandBlockTouchSensorsEnv",
399
+ kwargs=_merge(
400
+ {
401
+ "target_position": "ignore",
402
+ "target_rotation": "xyz",
403
+ "touch_get_obs": "boolean",
404
+ },
405
+ kwargs,
406
+ ),
407
+ max_episode_steps=100,
408
+ )
409
+
410
+ register(
411
+ id="HandManipulateBlockRotateXYZTouchSensors{}-v1".format(suffix),
412
+ entry_point="gym.envs.robotics:HandBlockTouchSensorsEnv",
413
+ kwargs=_merge(
414
+ {
415
+ "target_position": "ignore",
416
+ "target_rotation": "xyz",
417
+ "touch_get_obs": "sensordata",
418
+ },
419
+ kwargs,
420
+ ),
421
+ max_episode_steps=100,
422
+ )
423
+
424
+ register(
425
+ id="HandManipulateBlockFull{}-v0".format(suffix),
426
+ entry_point="gym.envs.robotics:HandBlockEnv",
427
+ kwargs=_merge({"target_position": "random", "target_rotation": "xyz"}, kwargs),
428
+ max_episode_steps=100,
429
+ )
430
+
431
+ # Alias for "Full"
432
+ register(
433
+ id="HandManipulateBlock{}-v0".format(suffix),
434
+ entry_point="gym.envs.robotics:HandBlockEnv",
435
+ kwargs=_merge({"target_position": "random", "target_rotation": "xyz"}, kwargs),
436
+ max_episode_steps=100,
437
+ )
438
+
439
+ register(
440
+ id="HandManipulateBlockTouchSensors{}-v0".format(suffix),
441
+ entry_point="gym.envs.robotics:HandBlockTouchSensorsEnv",
442
+ kwargs=_merge(
443
+ {
444
+ "target_position": "random",
445
+ "target_rotation": "xyz",
446
+ "touch_get_obs": "boolean",
447
+ },
448
+ kwargs,
449
+ ),
450
+ max_episode_steps=100,
451
+ )
452
+
453
+ register(
454
+ id="HandManipulateBlockTouchSensors{}-v1".format(suffix),
455
+ entry_point="gym.envs.robotics:HandBlockTouchSensorsEnv",
456
+ kwargs=_merge(
457
+ {
458
+ "target_position": "random",
459
+ "target_rotation": "xyz",
460
+ "touch_get_obs": "sensordata",
461
+ },
462
+ kwargs,
463
+ ),
464
+ max_episode_steps=100,
465
+ )
466
+
467
+ register(
468
+ id="HandManipulateEggRotate{}-v0".format(suffix),
469
+ entry_point="gym.envs.robotics:HandEggEnv",
470
+ kwargs=_merge({"target_position": "ignore", "target_rotation": "xyz"}, kwargs),
471
+ max_episode_steps=100,
472
+ )
473
+
474
+ register(
475
+ id="HandManipulateEggRotateTouchSensors{}-v0".format(suffix),
476
+ entry_point="gym.envs.robotics:HandEggTouchSensorsEnv",
477
+ kwargs=_merge(
478
+ {
479
+ "target_position": "ignore",
480
+ "target_rotation": "xyz",
481
+ "touch_get_obs": "boolean",
482
+ },
483
+ kwargs,
484
+ ),
485
+ max_episode_steps=100,
486
+ )
487
+
488
+ register(
489
+ id="HandManipulateEggRotateTouchSensors{}-v1".format(suffix),
490
+ entry_point="gym.envs.robotics:HandEggTouchSensorsEnv",
491
+ kwargs=_merge(
492
+ {
493
+ "target_position": "ignore",
494
+ "target_rotation": "xyz",
495
+ "touch_get_obs": "sensordata",
496
+ },
497
+ kwargs,
498
+ ),
499
+ max_episode_steps=100,
500
+ )
501
+
502
+ register(
503
+ id="HandManipulateEggFull{}-v0".format(suffix),
504
+ entry_point="gym.envs.robotics:HandEggEnv",
505
+ kwargs=_merge({"target_position": "random", "target_rotation": "xyz"}, kwargs),
506
+ max_episode_steps=100,
507
+ )
508
+
509
+ # Alias for "Full"
510
+ register(
511
+ id="HandManipulateEgg{}-v0".format(suffix),
512
+ entry_point="gym.envs.robotics:HandEggEnv",
513
+ kwargs=_merge({"target_position": "random", "target_rotation": "xyz"}, kwargs),
514
+ max_episode_steps=100,
515
+ )
516
+
517
+ register(
518
+ id="HandManipulateEggTouchSensors{}-v0".format(suffix),
519
+ entry_point="gym.envs.robotics:HandEggTouchSensorsEnv",
520
+ kwargs=_merge(
521
+ {
522
+ "target_position": "random",
523
+ "target_rotation": "xyz",
524
+ "touch_get_obs": "boolean",
525
+ },
526
+ kwargs,
527
+ ),
528
+ max_episode_steps=100,
529
+ )
530
+
531
+ register(
532
+ id="HandManipulateEggTouchSensors{}-v1".format(suffix),
533
+ entry_point="gym.envs.robotics:HandEggTouchSensorsEnv",
534
+ kwargs=_merge(
535
+ {
536
+ "target_position": "random",
537
+ "target_rotation": "xyz",
538
+ "touch_get_obs": "sensordata",
539
+ },
540
+ kwargs,
541
+ ),
542
+ max_episode_steps=100,
543
+ )
544
+
545
+ register(
546
+ id="HandManipulatePenRotate{}-v0".format(suffix),
547
+ entry_point="gym.envs.robotics:HandPenEnv",
548
+ kwargs=_merge({"target_position": "ignore", "target_rotation": "xyz"}, kwargs),
549
+ max_episode_steps=100,
550
+ )
551
+
552
+ register(
553
+ id="HandManipulatePenRotateTouchSensors{}-v0".format(suffix),
554
+ entry_point="gym.envs.robotics:HandPenTouchSensorsEnv",
555
+ kwargs=_merge(
556
+ {
557
+ "target_position": "ignore",
558
+ "target_rotation": "xyz",
559
+ "touch_get_obs": "boolean",
560
+ },
561
+ kwargs,
562
+ ),
563
+ max_episode_steps=100,
564
+ )
565
+
566
+ register(
567
+ id="HandManipulatePenRotateTouchSensors{}-v1".format(suffix),
568
+ entry_point="gym.envs.robotics:HandPenTouchSensorsEnv",
569
+ kwargs=_merge(
570
+ {
571
+ "target_position": "ignore",
572
+ "target_rotation": "xyz",
573
+ "touch_get_obs": "sensordata",
574
+ },
575
+ kwargs,
576
+ ),
577
+ max_episode_steps=100,
578
+ )
579
+
580
+ register(
581
+ id="HandManipulatePenFull{}-v0".format(suffix),
582
+ entry_point="gym.envs.robotics:HandPenEnv",
583
+ kwargs=_merge({"target_position": "random", "target_rotation": "xyz"}, kwargs),
584
+ max_episode_steps=100,
585
+ )
586
+
587
+ # Alias for "Full"
588
+ register(
589
+ id="HandManipulatePen{}-v0".format(suffix),
590
+ entry_point="gym.envs.robotics:HandPenEnv",
591
+ kwargs=_merge({"target_position": "random", "target_rotation": "xyz"}, kwargs),
592
+ max_episode_steps=100,
593
+ )
594
+
595
+ register(
596
+ id="HandManipulatePenTouchSensors{}-v0".format(suffix),
597
+ entry_point="gym.envs.robotics:HandPenTouchSensorsEnv",
598
+ kwargs=_merge(
599
+ {
600
+ "target_position": "random",
601
+ "target_rotation": "xyz",
602
+ "touch_get_obs": "boolean",
603
+ },
604
+ kwargs,
605
+ ),
606
+ max_episode_steps=100,
607
+ )
608
+
609
+ register(
610
+ id="HandManipulatePenTouchSensors{}-v1".format(suffix),
611
+ entry_point="gym.envs.robotics:HandPenTouchSensorsEnv",
612
+ kwargs=_merge(
613
+ {
614
+ "target_position": "random",
615
+ "target_rotation": "xyz",
616
+ "touch_get_obs": "sensordata",
617
+ },
618
+ kwargs,
619
+ ),
620
+ max_episode_steps=100,
621
+ )
622
+
623
+ # Unit test
624
+ # ---------
625
+
626
+ register(
627
+ id="CubeCrash-v0",
628
+ entry_point="gym.envs.unittest:CubeCrash",
629
+ reward_threshold=0.9,
630
+ )
631
+ register(
632
+ id="CubeCrashSparse-v0",
633
+ entry_point="gym.envs.unittest:CubeCrashSparse",
634
+ reward_threshold=0.9,
635
+ )
636
+ register(
637
+ id="CubeCrashScreenBecomesBlack-v0",
638
+ entry_point="gym.envs.unittest:CubeCrashScreenBecomesBlack",
639
+ reward_threshold=0.9,
640
+ )
641
+
642
+ register(
643
+ id="MemorizeDigits-v0",
644
+ entry_point="gym.envs.unittest:MemorizeDigits",
645
+ reward_threshold=20,
646
+ )
gym/envs/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (7.19 kB). View file
 
gym/envs/__pycache__/registration.cpython-39.pyc ADDED
Binary file (8.02 kB). View file
 
gym/envs/atari/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from gym.envs.atari.environment import AtariEnv
gym/envs/atari/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (219 Bytes). View file
 
gym/envs/atari/__pycache__/environment.cpython-39.pyc ADDED
Binary file (12.7 kB). View file
 
gym/envs/atari/environment.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import gym
3
+ import gym.logger as logger
4
+
5
+ from gym import error, spaces
6
+ from gym import utils
7
+ from gym.utils import seeding
8
+
9
+ from typing import Optional, Union, Tuple, Dict, Any, List
10
+
11
+ import ale_py.roms as roms
12
+ from ale_py._ale_py import ALEInterface, ALEState, Action, LoggerMode
13
+ from ale_py.roms.utils import rom_id_to_name
14
+
15
+
16
+ class AtariEnv(gym.Env, utils.EzPickle):
17
+ """
18
+ (A)rcade (L)earning (Gym) (Env)ironment.
19
+ A Gym wrapper around the Arcade Learning Environment (ALE).
20
+ """
21
+
22
+ # No render modes
23
+ metadata = {"render.modes": ["human", "rgb_array"]}
24
+
25
+ def __init__(
26
+ self,
27
+ game: str = "pong",
28
+ mode: Optional[int] = None,
29
+ difficulty: Optional[int] = None,
30
+ obs_type: str = "rgb",
31
+ frameskip: Union[Tuple[int, int], int] = 4,
32
+ repeat_action_probability: float = 0.25,
33
+ full_action_space: bool = False,
34
+ render_mode: str = None,
35
+ ) -> None:
36
+ """
37
+ Initialize the ALE for Gym.
38
+ Default parameters are taken from Machado et al., 2018.
39
+
40
+ Args:
41
+ game: str => Game to initialize env with.
42
+ mode: Optional[int] => Game mode, see Machado et al., 2018
43
+ difficulty: Optional[int] => Game difficulty,see Machado et al., 2018
44
+ obs_type: str => Observation type in { 'rgb', 'grayscale', 'ram' }
45
+ frameskip: Union[Tuple[int, int], int] =>
46
+ Stochastic frameskip as tuple or fixed.
47
+ repeat_action_probability: int =>
48
+ Probability to repeat actions, see Machado et al., 2018
49
+ full_action_space: bool => Use full action space?
50
+ render_mode: str => One of { 'human', 'rgb_array' }.
51
+ If `human` we'll interactively display the screen and enable
52
+ game sounds. This will lock emulation to the ROMs specified FPS
53
+ If `rgb_array` we'll return the `rgb` key in step metadata with
54
+ the current environment RGB frame.
55
+
56
+ Note:
57
+ - The game must be installed, see ale-import-roms, or ale-py-roms.
58
+ - Frameskip values of (low, high) will enable stochastic frame skip
59
+ which will sample a random frameskip uniformly each action.
60
+ - It is recommended to enable full action space.
61
+ See Machado et al., 2018 for more details.
62
+
63
+ References:
64
+ `Revisiting the Arcade Learning Environment: Evaluation Protocols
65
+ and Open Problems for General Agents`, Machado et al., 2018, JAIR
66
+ URL: https://jair.org/index.php/jair/article/view/11182
67
+ """
68
+ if obs_type == "image":
69
+ logger.warn(
70
+ 'obs_type "image" should be replaced with the image type, one of: rgb, grayscale'
71
+ )
72
+ obs_type = "rgb"
73
+ if obs_type not in {"rgb", "grayscale", "ram"}:
74
+ raise error.Error(
75
+ f"Invalid observation type: {obs_type}. Expecting: rgb, grayscale, ram."
76
+ )
77
+ if not (
78
+ isinstance(frameskip, int)
79
+ or (isinstance(frameskip, tuple) and len(frameskip) == 2)
80
+ ):
81
+ raise error.Error(f"Invalid frameskip type: {frameskip}")
82
+ if render_mode is not None and render_mode not in {"rgb_array", "human"}:
83
+ raise error.Error(
84
+ f"Render mode {render_mode} not supported (rgb_array, human)."
85
+ )
86
+
87
+ utils.EzPickle.__init__(
88
+ self,
89
+ game,
90
+ mode,
91
+ difficulty,
92
+ obs_type,
93
+ frameskip,
94
+ repeat_action_probability,
95
+ full_action_space,
96
+ render_mode,
97
+ )
98
+
99
+ # Initialize ALE
100
+ self.ale = ALEInterface()
101
+ self.viewer = None
102
+
103
+ self._game = rom_id_to_name(game)
104
+
105
+ self._game_mode = mode
106
+ self._game_difficulty = difficulty
107
+
108
+ self._frameskip = frameskip
109
+ self._obs_type = obs_type
110
+ self._render_mode = render_mode
111
+
112
+ # Set logger mode to error only
113
+ self.ale.setLoggerMode(LoggerMode.Error)
114
+ # Config sticky action prob.
115
+ self.ale.setFloat("repeat_action_probability", repeat_action_probability)
116
+
117
+ # If render mode is human we can display screen and sound
118
+ if render_mode == "human":
119
+ self.ale.setBool("display_screen", True)
120
+ self.ale.setBool("sound", True)
121
+
122
+ # Seed + Load
123
+ self.seed()
124
+
125
+ self._action_set = (
126
+ self.ale.getLegalActionSet()
127
+ if full_action_space
128
+ else self.ale.getMinimalActionSet()
129
+ )
130
+ self._action_space = spaces.Discrete(len(self._action_set))
131
+
132
+ # Initialize observation type
133
+ if self._obs_type == "ram":
134
+ self._obs_space = spaces.Box(
135
+ low=0, high=255, dtype=np.uint8, shape=(self.ale.getRAMSize(),)
136
+ )
137
+ elif self._obs_type == "rgb" or self._obs_type == "grayscale":
138
+ (screen_height, screen_width) = self.ale.getScreenDims()
139
+ image_shape = (
140
+ screen_height,
141
+ screen_width,
142
+ )
143
+ if self._obs_type == "rgb":
144
+ image_shape += (3,)
145
+ self._obs_space = spaces.Box(
146
+ low=0, high=255, dtype=np.uint8, shape=image_shape
147
+ )
148
+ else:
149
+ raise error.Error(f"Unrecognized observation type: {self._obs_type}")
150
+
151
+ def seed(self, seed: Optional[int] = None) -> Tuple[int, int]:
152
+ """
153
+ Seeds both the internal numpy rng for stochastic frame skip
154
+ as well as the ALE RNG.
155
+
156
+ This function must also initialize the ROM and set the corresponding
157
+ mode and difficulty. `seed` may be called to initialize the environment
158
+ during deserialization by Gym so these side-effects must reside here.
159
+
160
+ Args:
161
+ seed: int => Manually set the seed for RNG.
162
+ Returns:
163
+ tuple[int, int] => (np seed, ALE seed)
164
+ """
165
+ self.np_random, seed1 = seeding.np_random(seed)
166
+ seed2 = seeding.hash_seed(seed1 + 1) % 2 ** 31
167
+
168
+ self.ale.setInt("random_seed", seed2)
169
+
170
+ if not hasattr(roms, self._game):
171
+ raise error.Error(
172
+ f'We\'re Unable to find the game "{self._game}". Note: Gym no longer distributes ROMs. '
173
+ f"If you own a license to use the necessary ROMs for research purposes you can download them "
174
+ f'via `pip install gym[accept-rom-license]`. Otherwise, you should try importing "{self._game}" '
175
+ f'via the command `ale-import-roms`. If you believe this is a mistake perhaps your copy of "{self._game}" '
176
+ "is unsupported. To check if this is the case try providing the environment variable "
177
+ "`PYTHONWARNINGS=default::ImportWarning:ale_py.roms`. For more information see: "
178
+ "https://github.com/mgbellemare/Arcade-Learning-Environment#rom-management"
179
+ )
180
+ self.ale.loadROM(getattr(roms, self._game))
181
+
182
+ if self._game_mode is not None:
183
+ self.ale.setMode(self._game_mode)
184
+ if self._game_difficulty is not None:
185
+ self.ale.setDifficulty(self._game_difficulty)
186
+
187
+ return (
188
+ seed1,
189
+ seed2,
190
+ )
191
+
192
+ def step(self, action_ind: int) -> Tuple[np.ndarray, float, bool, Dict[str, Any]]:
193
+ """
194
+ Perform one agent step, i.e., repeats `action` frameskip # of steps.
195
+
196
+ Args:
197
+ action_ind: int => Action index to execute
198
+
199
+ Returns:
200
+ Tuple[np.ndarray, float, bool, Dict[str, Any]] =>
201
+ observation, reward, terminal, metadata
202
+
203
+ Note: `metadata` contains the keys "lives" and "rgb" if
204
+ render_mode == 'rgb_array'.
205
+ """
206
+ # Get action enum, terminal bool, metadata
207
+ action = self._action_set[action_ind]
208
+ terminal = self.ale.game_over()
209
+
210
+ # If frameskip is a length 2 tuple then it's stochastic
211
+ # frameskip between [frameskip[0], frameskip[1]] uniformly.
212
+ if isinstance(self._frameskip, int):
213
+ frameskip = self._frameskip
214
+ elif isinstance(self._frameskip, tuple):
215
+ frameskip = self.np_random.randint(*self._frameskip)
216
+ else:
217
+ raise error.Error(f"Invalid frameskip type: {self._frameskip}")
218
+
219
+ # Frameskip
220
+ reward = 0.0
221
+ for _ in range(frameskip):
222
+ reward += self.ale.act(action)
223
+
224
+ return self._get_obs(), reward, terminal, self._get_info()
225
+
226
+ def reset(
227
+ self, *, seed: Optional[int] = None, return_info: bool = False
228
+ ) -> Union[Tuple[np.ndarray, Dict[str, Any]], np.ndarray]:
229
+ """
230
+ Resets environment and returns initial observation.
231
+ """
232
+ # Gym's new seeding API seeds on reset.
233
+ # This will cause the console to be recreated
234
+ # and loose all previous state, e.g., statistics, etc.
235
+ seeded_with = None
236
+ if seed is not None:
237
+ seeded_with = self.seed(seed)
238
+
239
+ self.ale.reset_game()
240
+ obs = self._get_obs()
241
+
242
+ if return_info:
243
+ info = self._get_info()
244
+ if seeded_with is not None:
245
+ info["seeds"] = seeded_with
246
+ return obs, info
247
+ else:
248
+ return obs
249
+
250
+ def render(self, mode: str) -> None:
251
+ """
252
+ Render is not supported by ALE. We use a paradigm similar to
253
+ Gym3 which allows you to specify `render_mode` during construction.
254
+
255
+ For example,
256
+ gym.make("ale-py:Pong-v0", render_mode="human")
257
+ will display the ALE and maintain the proper interval to match the
258
+ FPS target set by the ROM.
259
+ """
260
+ img = self.ale.getScreenRGB()
261
+ if mode == "rgb_array":
262
+ return img
263
+ elif mode == "human":
264
+ from gym.envs.classic_control import rendering
265
+
266
+ if self.viewer is None:
267
+ logger.warn(
268
+ (
269
+ "We strongly suggest supplying `render_mode` when "
270
+ "constructing your environment, e.g., gym.make(ID, render_mode='human'). "
271
+ "Using `render_mode` provides access to proper scaling, audio support, "
272
+ "and proper framerates."
273
+ )
274
+ )
275
+ self.viewer = rendering.SimpleImageViewer()
276
+ self.viewer.imshow(img)
277
+ return self.viewer.isopen
278
+
279
+ def close(self) -> None:
280
+ """
281
+ Cleanup any leftovers by the environment
282
+ """
283
+ if self.viewer is not None:
284
+ self.viewer.close()
285
+ self.viewer = None
286
+
287
+ def _get_obs(self) -> np.ndarray:
288
+ """
289
+ Retreives the current observation.
290
+ This is dependent on `self._obs_type`.
291
+ """
292
+ if self._obs_type == "ram":
293
+ return self.ale.getRAM()
294
+ elif self._obs_type == "rgb":
295
+ return self.ale.getScreenRGB()
296
+ elif self._obs_type == "grayscale":
297
+ return self.ale.getScreenGrayscale()
298
+ else:
299
+ raise error.Error(f"Unrecognized observation type: {self._obs_type}")
300
+
301
+ def _get_info(self) -> Dict[str, Any]:
302
+ info = {
303
+ "lives": self.ale.lives(),
304
+ "episode_frame_number": self.ale.getEpisodeFrameNumber(),
305
+ "frame_number": self.ale.getFrameNumber(),
306
+ }
307
+
308
+ if self._render_mode == "rgb_array":
309
+ info["rgb"] = self.ale.getScreenRGB()
310
+
311
+ return info
312
+
313
+ def get_keys_to_action(self) -> Dict[Tuple[int], Action]:
314
+ """
315
+ Return keymapping -> actions for human play.
316
+ """
317
+ UP = ord("w")
318
+ LEFT = ord("a")
319
+ RIGHT = ord("d")
320
+ DOWN = ord("s")
321
+ FIRE = ord(" ")
322
+
323
+ mapping = {
324
+ Action.NOOP: (None,),
325
+ Action.UP: (UP,),
326
+ Action.FIRE: (FIRE,),
327
+ Action.DOWN: (DOWN,),
328
+ Action.LEFT: (LEFT,),
329
+ Action.RIGHT: (RIGHT,),
330
+ Action.UPFIRE: (UP, FIRE),
331
+ Action.DOWNFIRE: (DOWN, FIRE),
332
+ Action.LEFTFIRE: (LEFT, FIRE),
333
+ Action.RIGHTFIRE: (RIGHT, FIRE),
334
+ Action.UPLEFT: (UP, LEFT),
335
+ Action.UPRIGHT: (UP, RIGHT),
336
+ Action.DOWNLEFT: (DOWN, LEFT),
337
+ Action.DOWNRIGHT: (DOWN, RIGHT),
338
+ Action.UPLEFTFIRE: (UP, LEFT, FIRE),
339
+ Action.UPRIGHTFIRE: (UP, RIGHT, FIRE),
340
+ Action.DOWNLEFTFIRE: (DOWN, LEFT, FIRE),
341
+ Action.DOWNRIGHTFIRE: (DOWN, RIGHT, FIRE),
342
+ }
343
+
344
+ # Map
345
+ # (key, key, ...) -> action_idx
346
+ # where action_idx is the integer value of the action enum
347
+ #
348
+ actions = self._action_set
349
+ return dict(
350
+ zip(
351
+ map(lambda action: tuple(sorted(mapping[action])), actions),
352
+ range(len(actions)),
353
+ )
354
+ )
355
+
356
+ def get_action_meanings(self) -> List[str]:
357
+ """
358
+ Return the meaning of each integer action.
359
+ """
360
+ keys = Action.__members__.values()
361
+ values = Action.__members__.keys()
362
+ mapping = dict(zip(keys, values))
363
+ return [mapping[action] for action in self._action_set]
364
+
365
+ def clone_state(self, include_rng=False) -> ALEState:
366
+ """Clone emulator state w/o system state. Restoring this state will
367
+ *not* give an identical environment. For complete cloning and restoring
368
+ of the full state, see `{clone,restore}_full_state()`."""
369
+ return self.ale.cloneState(include_rng=include_rng)
370
+
371
+ def restore_state(self, state: ALEState) -> None:
372
+ """Restore emulator state w/o system state."""
373
+ self.ale.restoreState(state)
374
+
375
+ def clone_full_state(self) -> ALEState:
376
+ """Deprecated method which would clone the emulator and system state."""
377
+ logger.warn(
378
+ "`clone_full_state()` is deprecated and will be removed in a future release of `ale-py`. "
379
+ "Please use `clone_state(include_rng=True)` which is equivalent to `clone_full_state`. "
380
+ )
381
+ return self.ale.cloneSystemState()
382
+
383
+ def restore_full_state(self, state: ALEState) -> None:
384
+ """Restore emulator state w/ system state including pseudorandomness."""
385
+ logger.warn(
386
+ "restore_full_state() is deprecated and will be removed in a future release of `ale-py`. "
387
+ "Please use `restore_state(state)` which will restore the state regardless of being a full or partial state. "
388
+ )
389
+ self.ale.restoreSystemState(state)
390
+
391
+ @property
392
+ def action_space(self) -> spaces.Discrete:
393
+ """
394
+ Return Gym's action space.
395
+ """
396
+ return self._action_space
397
+
398
+ @property
399
+ def observation_space(self) -> spaces.Box:
400
+ """
401
+ Return Gym's observation space.
402
+ """
403
+ return self._obs_space
gym/envs/box2d/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ try:
2
+ import Box2D
3
+ from gym.envs.box2d.lunar_lander import LunarLander
4
+ from gym.envs.box2d.lunar_lander import LunarLanderContinuous
5
+ from gym.envs.box2d.bipedal_walker import BipedalWalker, BipedalWalkerHardcore
6
+ from gym.envs.box2d.car_racing import CarRacing
7
+ except ImportError:
8
+ Box2D = None
gym/envs/box2d/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (489 Bytes). View file
 
gym/envs/box2d/__pycache__/bipedal_walker.cpython-39.pyc ADDED
Binary file (15.5 kB). View file
 
gym/envs/box2d/__pycache__/car_dynamics.cpython-39.pyc ADDED
Binary file (7.66 kB). View file
 
gym/envs/box2d/__pycache__/car_racing.cpython-39.pyc ADDED
Binary file (14.9 kB). View file
 
gym/envs/box2d/__pycache__/lunar_lander.cpython-39.pyc ADDED
Binary file (13.5 kB). View file
 
gym/envs/box2d/bipedal_walker.py ADDED
@@ -0,0 +1,658 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import math
3
+
4
+ import numpy as np
5
+ import Box2D
6
+ from Box2D.b2 import (
7
+ edgeShape,
8
+ circleShape,
9
+ fixtureDef,
10
+ polygonShape,
11
+ revoluteJointDef,
12
+ contactListener,
13
+ )
14
+
15
+ import gym
16
+ from gym import spaces
17
+ from gym.utils import colorize, seeding, EzPickle
18
+
19
+ # This is simple 4-joints walker robot environment.
20
+ #
21
+ # There are two versions:
22
+ #
23
+ # - Normal, with slightly uneven terrain.
24
+ #
25
+ # - Hardcore with ladders, stumps, pitfalls.
26
+ #
27
+ # Reward is given for moving forward, total 300+ points up to the far end. If the robot falls,
28
+ # it gets -100. Applying motor torque costs a small amount of points, more optimal agent
29
+ # will get better score.
30
+ #
31
+ # Heuristic is provided for testing, it's also useful to get demonstrations to
32
+ # learn from. To run heuristic:
33
+ #
34
+ # python gym/envs/box2d/bipedal_walker.py
35
+ #
36
+ # State consists of hull angle speed, angular velocity, horizontal speed, vertical speed,
37
+ # position of joints and joints angular speed, legs contact with ground, and 10 lidar
38
+ # rangefinder measurements to help to deal with the hardcore version. There's no coordinates
39
+ # in the state vector. Lidar is less useful in normal version, but it works.
40
+ #
41
+ # To solve the game you need to get 300 points in 1600 time steps.
42
+ #
43
+ # To solve hardcore version you need 300 points in 2000 time steps.
44
+ #
45
+ # Created by Oleg Klimov. Licensed on the same terms as the rest of OpenAI Gym.
46
+
47
+ FPS = 50
48
+ SCALE = 30.0 # affects how fast-paced the game is, forces should be adjusted as well
49
+
50
+ MOTORS_TORQUE = 80
51
+ SPEED_HIP = 4
52
+ SPEED_KNEE = 6
53
+ LIDAR_RANGE = 160 / SCALE
54
+
55
+ INITIAL_RANDOM = 5
56
+
57
+ HULL_POLY = [(-30, +9), (+6, +9), (+34, +1), (+34, -8), (-30, -8)]
58
+ LEG_DOWN = -8 / SCALE
59
+ LEG_W, LEG_H = 8 / SCALE, 34 / SCALE
60
+
61
+ VIEWPORT_W = 600
62
+ VIEWPORT_H = 400
63
+
64
+ TERRAIN_STEP = 14 / SCALE
65
+ TERRAIN_LENGTH = 200 # in steps
66
+ TERRAIN_HEIGHT = VIEWPORT_H / SCALE / 4
67
+ TERRAIN_GRASS = 10 # low long are grass spots, in steps
68
+ TERRAIN_STARTPAD = 20 # in steps
69
+ FRICTION = 2.5
70
+
71
+ HULL_FD = fixtureDef(
72
+ shape=polygonShape(vertices=[(x / SCALE, y / SCALE) for x, y in HULL_POLY]),
73
+ density=5.0,
74
+ friction=0.1,
75
+ categoryBits=0x0020,
76
+ maskBits=0x001, # collide only with ground
77
+ restitution=0.0,
78
+ ) # 0.99 bouncy
79
+
80
+ LEG_FD = fixtureDef(
81
+ shape=polygonShape(box=(LEG_W / 2, LEG_H / 2)),
82
+ density=1.0,
83
+ restitution=0.0,
84
+ categoryBits=0x0020,
85
+ maskBits=0x001,
86
+ )
87
+
88
+ LOWER_FD = fixtureDef(
89
+ shape=polygonShape(box=(0.8 * LEG_W / 2, LEG_H / 2)),
90
+ density=1.0,
91
+ restitution=0.0,
92
+ categoryBits=0x0020,
93
+ maskBits=0x001,
94
+ )
95
+
96
+
97
+ class ContactDetector(contactListener):
98
+ def __init__(self, env):
99
+ contactListener.__init__(self)
100
+ self.env = env
101
+
102
+ def BeginContact(self, contact):
103
+ if (
104
+ self.env.hull == contact.fixtureA.body
105
+ or self.env.hull == contact.fixtureB.body
106
+ ):
107
+ self.env.game_over = True
108
+ for leg in [self.env.legs[1], self.env.legs[3]]:
109
+ if leg in [contact.fixtureA.body, contact.fixtureB.body]:
110
+ leg.ground_contact = True
111
+
112
+ def EndContact(self, contact):
113
+ for leg in [self.env.legs[1], self.env.legs[3]]:
114
+ if leg in [contact.fixtureA.body, contact.fixtureB.body]:
115
+ leg.ground_contact = False
116
+
117
+
118
+ class BipedalWalker(gym.Env, EzPickle):
119
+ metadata = {"render.modes": ["human", "rgb_array"], "video.frames_per_second": FPS}
120
+
121
+ hardcore = False
122
+
123
+ def __init__(self):
124
+ EzPickle.__init__(self)
125
+ self.seed()
126
+ self.viewer = None
127
+
128
+ self.world = Box2D.b2World()
129
+ self.terrain = None
130
+ self.hull = None
131
+
132
+ self.prev_shaping = None
133
+
134
+ self.fd_polygon = fixtureDef(
135
+ shape=polygonShape(vertices=[(0, 0), (1, 0), (1, -1), (0, -1)]),
136
+ friction=FRICTION,
137
+ )
138
+
139
+ self.fd_edge = fixtureDef(
140
+ shape=edgeShape(vertices=[(0, 0), (1, 1)]),
141
+ friction=FRICTION,
142
+ categoryBits=0x0001,
143
+ )
144
+
145
+ high = np.array([np.inf] * 24).astype(np.float32)
146
+ self.action_space = spaces.Box(
147
+ np.array([-1, -1, -1, -1]).astype(np.float32),
148
+ np.array([1, 1, 1, 1]).astype(np.float32),
149
+ )
150
+ self.observation_space = spaces.Box(-high, high)
151
+
152
+ def seed(self, seed=None):
153
+ self.np_random, seed = seeding.np_random(seed)
154
+ return [seed]
155
+
156
+ def _destroy(self):
157
+ if not self.terrain:
158
+ return
159
+ self.world.contactListener = None
160
+ for t in self.terrain:
161
+ self.world.DestroyBody(t)
162
+ self.terrain = []
163
+ self.world.DestroyBody(self.hull)
164
+ self.hull = None
165
+ for leg in self.legs:
166
+ self.world.DestroyBody(leg)
167
+ self.legs = []
168
+ self.joints = []
169
+
170
+ def _generate_terrain(self, hardcore):
171
+ GRASS, STUMP, STAIRS, PIT, _STATES_ = range(5)
172
+ state = GRASS
173
+ velocity = 0.0
174
+ y = TERRAIN_HEIGHT
175
+ counter = TERRAIN_STARTPAD
176
+ oneshot = False
177
+ self.terrain = []
178
+ self.terrain_x = []
179
+ self.terrain_y = []
180
+ for i in range(TERRAIN_LENGTH):
181
+ x = i * TERRAIN_STEP
182
+ self.terrain_x.append(x)
183
+
184
+ if state == GRASS and not oneshot:
185
+ velocity = 0.8 * velocity + 0.01 * np.sign(TERRAIN_HEIGHT - y)
186
+ if i > TERRAIN_STARTPAD:
187
+ velocity += self.np_random.uniform(-1, 1) / SCALE # 1
188
+ y += velocity
189
+
190
+ elif state == PIT and oneshot:
191
+ counter = self.np_random.randint(3, 5)
192
+ poly = [
193
+ (x, y),
194
+ (x + TERRAIN_STEP, y),
195
+ (x + TERRAIN_STEP, y - 4 * TERRAIN_STEP),
196
+ (x, y - 4 * TERRAIN_STEP),
197
+ ]
198
+ self.fd_polygon.shape.vertices = poly
199
+ t = self.world.CreateStaticBody(fixtures=self.fd_polygon)
200
+ t.color1, t.color2 = (1, 1, 1), (0.6, 0.6, 0.6)
201
+ self.terrain.append(t)
202
+
203
+ self.fd_polygon.shape.vertices = [
204
+ (p[0] + TERRAIN_STEP * counter, p[1]) for p in poly
205
+ ]
206
+ t = self.world.CreateStaticBody(fixtures=self.fd_polygon)
207
+ t.color1, t.color2 = (1, 1, 1), (0.6, 0.6, 0.6)
208
+ self.terrain.append(t)
209
+ counter += 2
210
+ original_y = y
211
+
212
+ elif state == PIT and not oneshot:
213
+ y = original_y
214
+ if counter > 1:
215
+ y -= 4 * TERRAIN_STEP
216
+
217
+ elif state == STUMP and oneshot:
218
+ counter = self.np_random.randint(1, 3)
219
+ poly = [
220
+ (x, y),
221
+ (x + counter * TERRAIN_STEP, y),
222
+ (x + counter * TERRAIN_STEP, y + counter * TERRAIN_STEP),
223
+ (x, y + counter * TERRAIN_STEP),
224
+ ]
225
+ self.fd_polygon.shape.vertices = poly
226
+ t = self.world.CreateStaticBody(fixtures=self.fd_polygon)
227
+ t.color1, t.color2 = (1, 1, 1), (0.6, 0.6, 0.6)
228
+ self.terrain.append(t)
229
+
230
+ elif state == STAIRS and oneshot:
231
+ stair_height = +1 if self.np_random.rand() > 0.5 else -1
232
+ stair_width = self.np_random.randint(4, 5)
233
+ stair_steps = self.np_random.randint(3, 5)
234
+ original_y = y
235
+ for s in range(stair_steps):
236
+ poly = [
237
+ (
238
+ x + (s * stair_width) * TERRAIN_STEP,
239
+ y + (s * stair_height) * TERRAIN_STEP,
240
+ ),
241
+ (
242
+ x + ((1 + s) * stair_width) * TERRAIN_STEP,
243
+ y + (s * stair_height) * TERRAIN_STEP,
244
+ ),
245
+ (
246
+ x + ((1 + s) * stair_width) * TERRAIN_STEP,
247
+ y + (-1 + s * stair_height) * TERRAIN_STEP,
248
+ ),
249
+ (
250
+ x + (s * stair_width) * TERRAIN_STEP,
251
+ y + (-1 + s * stair_height) * TERRAIN_STEP,
252
+ ),
253
+ ]
254
+ self.fd_polygon.shape.vertices = poly
255
+ t = self.world.CreateStaticBody(fixtures=self.fd_polygon)
256
+ t.color1, t.color2 = (1, 1, 1), (0.6, 0.6, 0.6)
257
+ self.terrain.append(t)
258
+ counter = stair_steps * stair_width
259
+
260
+ elif state == STAIRS and not oneshot:
261
+ s = stair_steps * stair_width - counter - stair_height
262
+ n = s / stair_width
263
+ y = original_y + (n * stair_height) * TERRAIN_STEP
264
+
265
+ oneshot = False
266
+ self.terrain_y.append(y)
267
+ counter -= 1
268
+ if counter == 0:
269
+ counter = self.np_random.randint(TERRAIN_GRASS / 2, TERRAIN_GRASS)
270
+ if state == GRASS and hardcore:
271
+ state = self.np_random.randint(1, _STATES_)
272
+ oneshot = True
273
+ else:
274
+ state = GRASS
275
+ oneshot = True
276
+
277
+ self.terrain_poly = []
278
+ for i in range(TERRAIN_LENGTH - 1):
279
+ poly = [
280
+ (self.terrain_x[i], self.terrain_y[i]),
281
+ (self.terrain_x[i + 1], self.terrain_y[i + 1]),
282
+ ]
283
+ self.fd_edge.shape.vertices = poly
284
+ t = self.world.CreateStaticBody(fixtures=self.fd_edge)
285
+ color = (0.3, 1.0 if i % 2 == 0 else 0.8, 0.3)
286
+ t.color1 = color
287
+ t.color2 = color
288
+ self.terrain.append(t)
289
+ color = (0.4, 0.6, 0.3)
290
+ poly += [(poly[1][0], 0), (poly[0][0], 0)]
291
+ self.terrain_poly.append((poly, color))
292
+ self.terrain.reverse()
293
+
294
+ def _generate_clouds(self):
295
+ # Sorry for the clouds, couldn't resist
296
+ self.cloud_poly = []
297
+ for i in range(TERRAIN_LENGTH // 20):
298
+ x = self.np_random.uniform(0, TERRAIN_LENGTH) * TERRAIN_STEP
299
+ y = VIEWPORT_H / SCALE * 3 / 4
300
+ poly = [
301
+ (
302
+ x
303
+ + 15 * TERRAIN_STEP * math.sin(3.14 * 2 * a / 5)
304
+ + self.np_random.uniform(0, 5 * TERRAIN_STEP),
305
+ y
306
+ + 5 * TERRAIN_STEP * math.cos(3.14 * 2 * a / 5)
307
+ + self.np_random.uniform(0, 5 * TERRAIN_STEP),
308
+ )
309
+ for a in range(5)
310
+ ]
311
+ x1 = min([p[0] for p in poly])
312
+ x2 = max([p[0] for p in poly])
313
+ self.cloud_poly.append((poly, x1, x2))
314
+
315
+ def reset(self):
316
+ self._destroy()
317
+ self.world.contactListener_bug_workaround = ContactDetector(self)
318
+ self.world.contactListener = self.world.contactListener_bug_workaround
319
+ self.game_over = False
320
+ self.prev_shaping = None
321
+ self.scroll = 0.0
322
+ self.lidar_render = 0
323
+
324
+ W = VIEWPORT_W / SCALE
325
+ H = VIEWPORT_H / SCALE
326
+
327
+ self._generate_terrain(self.hardcore)
328
+ self._generate_clouds()
329
+
330
+ init_x = TERRAIN_STEP * TERRAIN_STARTPAD / 2
331
+ init_y = TERRAIN_HEIGHT + 2 * LEG_H
332
+ self.hull = self.world.CreateDynamicBody(
333
+ position=(init_x, init_y), fixtures=HULL_FD
334
+ )
335
+ self.hull.color1 = (0.5, 0.4, 0.9)
336
+ self.hull.color2 = (0.3, 0.3, 0.5)
337
+ self.hull.ApplyForceToCenter(
338
+ (self.np_random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM), 0), True
339
+ )
340
+
341
+ self.legs = []
342
+ self.joints = []
343
+ for i in [-1, +1]:
344
+ leg = self.world.CreateDynamicBody(
345
+ position=(init_x, init_y - LEG_H / 2 - LEG_DOWN),
346
+ angle=(i * 0.05),
347
+ fixtures=LEG_FD,
348
+ )
349
+ leg.color1 = (0.6 - i / 10.0, 0.3 - i / 10.0, 0.5 - i / 10.0)
350
+ leg.color2 = (0.4 - i / 10.0, 0.2 - i / 10.0, 0.3 - i / 10.0)
351
+ rjd = revoluteJointDef(
352
+ bodyA=self.hull,
353
+ bodyB=leg,
354
+ localAnchorA=(0, LEG_DOWN),
355
+ localAnchorB=(0, LEG_H / 2),
356
+ enableMotor=True,
357
+ enableLimit=True,
358
+ maxMotorTorque=MOTORS_TORQUE,
359
+ motorSpeed=i,
360
+ lowerAngle=-0.8,
361
+ upperAngle=1.1,
362
+ )
363
+ self.legs.append(leg)
364
+ self.joints.append(self.world.CreateJoint(rjd))
365
+
366
+ lower = self.world.CreateDynamicBody(
367
+ position=(init_x, init_y - LEG_H * 3 / 2 - LEG_DOWN),
368
+ angle=(i * 0.05),
369
+ fixtures=LOWER_FD,
370
+ )
371
+ lower.color1 = (0.6 - i / 10.0, 0.3 - i / 10.0, 0.5 - i / 10.0)
372
+ lower.color2 = (0.4 - i / 10.0, 0.2 - i / 10.0, 0.3 - i / 10.0)
373
+ rjd = revoluteJointDef(
374
+ bodyA=leg,
375
+ bodyB=lower,
376
+ localAnchorA=(0, -LEG_H / 2),
377
+ localAnchorB=(0, LEG_H / 2),
378
+ enableMotor=True,
379
+ enableLimit=True,
380
+ maxMotorTorque=MOTORS_TORQUE,
381
+ motorSpeed=1,
382
+ lowerAngle=-1.6,
383
+ upperAngle=-0.1,
384
+ )
385
+ lower.ground_contact = False
386
+ self.legs.append(lower)
387
+ self.joints.append(self.world.CreateJoint(rjd))
388
+
389
+ self.drawlist = self.terrain + self.legs + [self.hull]
390
+
391
+ class LidarCallback(Box2D.b2.rayCastCallback):
392
+ def ReportFixture(self, fixture, point, normal, fraction):
393
+ if (fixture.filterData.categoryBits & 1) == 0:
394
+ return -1
395
+ self.p2 = point
396
+ self.fraction = fraction
397
+ return fraction
398
+
399
+ self.lidar = [LidarCallback() for _ in range(10)]
400
+
401
+ return self.step(np.array([0, 0, 0, 0]))[0]
402
+
403
+ def step(self, action):
404
+ # self.hull.ApplyForceToCenter((0, 20), True) -- Uncomment this to receive a bit of stability help
405
+ control_speed = False # Should be easier as well
406
+ if control_speed:
407
+ self.joints[0].motorSpeed = float(SPEED_HIP * np.clip(action[0], -1, 1))
408
+ self.joints[1].motorSpeed = float(SPEED_KNEE * np.clip(action[1], -1, 1))
409
+ self.joints[2].motorSpeed = float(SPEED_HIP * np.clip(action[2], -1, 1))
410
+ self.joints[3].motorSpeed = float(SPEED_KNEE * np.clip(action[3], -1, 1))
411
+ else:
412
+ self.joints[0].motorSpeed = float(SPEED_HIP * np.sign(action[0]))
413
+ self.joints[0].maxMotorTorque = float(
414
+ MOTORS_TORQUE * np.clip(np.abs(action[0]), 0, 1)
415
+ )
416
+ self.joints[1].motorSpeed = float(SPEED_KNEE * np.sign(action[1]))
417
+ self.joints[1].maxMotorTorque = float(
418
+ MOTORS_TORQUE * np.clip(np.abs(action[1]), 0, 1)
419
+ )
420
+ self.joints[2].motorSpeed = float(SPEED_HIP * np.sign(action[2]))
421
+ self.joints[2].maxMotorTorque = float(
422
+ MOTORS_TORQUE * np.clip(np.abs(action[2]), 0, 1)
423
+ )
424
+ self.joints[3].motorSpeed = float(SPEED_KNEE * np.sign(action[3]))
425
+ self.joints[3].maxMotorTorque = float(
426
+ MOTORS_TORQUE * np.clip(np.abs(action[3]), 0, 1)
427
+ )
428
+
429
+ self.world.Step(1.0 / FPS, 6 * 30, 2 * 30)
430
+
431
+ pos = self.hull.position
432
+ vel = self.hull.linearVelocity
433
+
434
+ for i in range(10):
435
+ self.lidar[i].fraction = 1.0
436
+ self.lidar[i].p1 = pos
437
+ self.lidar[i].p2 = (
438
+ pos[0] + math.sin(1.5 * i / 10.0) * LIDAR_RANGE,
439
+ pos[1] - math.cos(1.5 * i / 10.0) * LIDAR_RANGE,
440
+ )
441
+ self.world.RayCast(self.lidar[i], self.lidar[i].p1, self.lidar[i].p2)
442
+
443
+ state = [
444
+ self.hull.angle, # Normal angles up to 0.5 here, but sure more is possible.
445
+ 2.0 * self.hull.angularVelocity / FPS,
446
+ 0.3 * vel.x * (VIEWPORT_W / SCALE) / FPS, # Normalized to get -1..1 range
447
+ 0.3 * vel.y * (VIEWPORT_H / SCALE) / FPS,
448
+ self.joints[
449
+ 0
450
+ ].angle, # This will give 1.1 on high up, but it's still OK (and there should be spikes on hiting the ground, that's normal too)
451
+ self.joints[0].speed / SPEED_HIP,
452
+ self.joints[1].angle + 1.0,
453
+ self.joints[1].speed / SPEED_KNEE,
454
+ 1.0 if self.legs[1].ground_contact else 0.0,
455
+ self.joints[2].angle,
456
+ self.joints[2].speed / SPEED_HIP,
457
+ self.joints[3].angle + 1.0,
458
+ self.joints[3].speed / SPEED_KNEE,
459
+ 1.0 if self.legs[3].ground_contact else 0.0,
460
+ ]
461
+ state += [l.fraction for l in self.lidar]
462
+ assert len(state) == 24
463
+
464
+ self.scroll = pos.x - VIEWPORT_W / SCALE / 5
465
+
466
+ shaping = (
467
+ 130 * pos[0] / SCALE
468
+ ) # moving forward is a way to receive reward (normalized to get 300 on completion)
469
+ shaping -= 5.0 * abs(
470
+ state[0]
471
+ ) # keep head straight, other than that and falling, any behavior is unpunished
472
+
473
+ reward = 0
474
+ if self.prev_shaping is not None:
475
+ reward = shaping - self.prev_shaping
476
+ self.prev_shaping = shaping
477
+
478
+ for a in action:
479
+ reward -= 0.00035 * MOTORS_TORQUE * np.clip(np.abs(a), 0, 1)
480
+ # normalized to about -50.0 using heuristic, more optimal agent should spend less
481
+
482
+ done = False
483
+ if self.game_over or pos[0] < 0:
484
+ reward = -100
485
+ done = True
486
+ if pos[0] > (TERRAIN_LENGTH - TERRAIN_GRASS) * TERRAIN_STEP:
487
+ done = True
488
+ return np.array(state, dtype=np.float32), reward, done, {}
489
+
490
+ def render(self, mode="human"):
491
+ from gym.envs.classic_control import rendering
492
+
493
+ if self.viewer is None:
494
+ self.viewer = rendering.Viewer(VIEWPORT_W, VIEWPORT_H)
495
+ self.viewer.set_bounds(
496
+ self.scroll, VIEWPORT_W / SCALE + self.scroll, 0, VIEWPORT_H / SCALE
497
+ )
498
+
499
+ self.viewer.draw_polygon(
500
+ [
501
+ (self.scroll, 0),
502
+ (self.scroll + VIEWPORT_W / SCALE, 0),
503
+ (self.scroll + VIEWPORT_W / SCALE, VIEWPORT_H / SCALE),
504
+ (self.scroll, VIEWPORT_H / SCALE),
505
+ ],
506
+ color=(0.9, 0.9, 1.0),
507
+ )
508
+ for poly, x1, x2 in self.cloud_poly:
509
+ if x2 < self.scroll / 2:
510
+ continue
511
+ if x1 > self.scroll / 2 + VIEWPORT_W / SCALE:
512
+ continue
513
+ self.viewer.draw_polygon(
514
+ [(p[0] + self.scroll / 2, p[1]) for p in poly], color=(1, 1, 1)
515
+ )
516
+ for poly, color in self.terrain_poly:
517
+ if poly[1][0] < self.scroll:
518
+ continue
519
+ if poly[0][0] > self.scroll + VIEWPORT_W / SCALE:
520
+ continue
521
+ self.viewer.draw_polygon(poly, color=color)
522
+
523
+ self.lidar_render = (self.lidar_render + 1) % 100
524
+ i = self.lidar_render
525
+ if i < 2 * len(self.lidar):
526
+ l = (
527
+ self.lidar[i]
528
+ if i < len(self.lidar)
529
+ else self.lidar[len(self.lidar) - i - 1]
530
+ )
531
+ self.viewer.draw_polyline([l.p1, l.p2], color=(1, 0, 0), linewidth=1)
532
+
533
+ for obj in self.drawlist:
534
+ for f in obj.fixtures:
535
+ trans = f.body.transform
536
+ if type(f.shape) is circleShape:
537
+ t = rendering.Transform(translation=trans * f.shape.pos)
538
+ self.viewer.draw_circle(
539
+ f.shape.radius, 30, color=obj.color1
540
+ ).add_attr(t)
541
+ self.viewer.draw_circle(
542
+ f.shape.radius, 30, color=obj.color2, filled=False, linewidth=2
543
+ ).add_attr(t)
544
+ else:
545
+ path = [trans * v for v in f.shape.vertices]
546
+ self.viewer.draw_polygon(path, color=obj.color1)
547
+ path.append(path[0])
548
+ self.viewer.draw_polyline(path, color=obj.color2, linewidth=2)
549
+
550
+ flagy1 = TERRAIN_HEIGHT
551
+ flagy2 = flagy1 + 50 / SCALE
552
+ x = TERRAIN_STEP * 3
553
+ self.viewer.draw_polyline(
554
+ [(x, flagy1), (x, flagy2)], color=(0, 0, 0), linewidth=2
555
+ )
556
+ f = [
557
+ (x, flagy2),
558
+ (x, flagy2 - 10 / SCALE),
559
+ (x + 25 / SCALE, flagy2 - 5 / SCALE),
560
+ ]
561
+ self.viewer.draw_polygon(f, color=(0.9, 0.2, 0))
562
+ self.viewer.draw_polyline(f + [f[0]], color=(0, 0, 0), linewidth=2)
563
+
564
+ return self.viewer.render(return_rgb_array=mode == "rgb_array")
565
+
566
+ def close(self):
567
+ if self.viewer is not None:
568
+ self.viewer.close()
569
+ self.viewer = None
570
+
571
+
572
+ class BipedalWalkerHardcore(BipedalWalker):
573
+ hardcore = True
574
+
575
+
576
+ if __name__ == "__main__":
577
+ # Heurisic: suboptimal, have no notion of balance.
578
+ env = BipedalWalker()
579
+ env.reset()
580
+ steps = 0
581
+ total_reward = 0
582
+ a = np.array([0.0, 0.0, 0.0, 0.0])
583
+ STAY_ON_ONE_LEG, PUT_OTHER_DOWN, PUSH_OFF = 1, 2, 3
584
+ SPEED = 0.29 # Will fall forward on higher speed
585
+ state = STAY_ON_ONE_LEG
586
+ moving_leg = 0
587
+ supporting_leg = 1 - moving_leg
588
+ SUPPORT_KNEE_ANGLE = +0.1
589
+ supporting_knee_angle = SUPPORT_KNEE_ANGLE
590
+ while True:
591
+ s, r, done, info = env.step(a)
592
+ total_reward += r
593
+ if steps % 20 == 0 or done:
594
+ print("\naction " + str(["{:+0.2f}".format(x) for x in a]))
595
+ print("step {} total_reward {:+0.2f}".format(steps, total_reward))
596
+ print("hull " + str(["{:+0.2f}".format(x) for x in s[0:4]]))
597
+ print("leg0 " + str(["{:+0.2f}".format(x) for x in s[4:9]]))
598
+ print("leg1 " + str(["{:+0.2f}".format(x) for x in s[9:14]]))
599
+ steps += 1
600
+
601
+ contact0 = s[8]
602
+ contact1 = s[13]
603
+ moving_s_base = 4 + 5 * moving_leg
604
+ supporting_s_base = 4 + 5 * supporting_leg
605
+
606
+ hip_targ = [None, None] # -0.8 .. +1.1
607
+ knee_targ = [None, None] # -0.6 .. +0.9
608
+ hip_todo = [0.0, 0.0]
609
+ knee_todo = [0.0, 0.0]
610
+
611
+ if state == STAY_ON_ONE_LEG:
612
+ hip_targ[moving_leg] = 1.1
613
+ knee_targ[moving_leg] = -0.6
614
+ supporting_knee_angle += 0.03
615
+ if s[2] > SPEED:
616
+ supporting_knee_angle += 0.03
617
+ supporting_knee_angle = min(supporting_knee_angle, SUPPORT_KNEE_ANGLE)
618
+ knee_targ[supporting_leg] = supporting_knee_angle
619
+ if s[supporting_s_base + 0] < 0.10: # supporting leg is behind
620
+ state = PUT_OTHER_DOWN
621
+ if state == PUT_OTHER_DOWN:
622
+ hip_targ[moving_leg] = +0.1
623
+ knee_targ[moving_leg] = SUPPORT_KNEE_ANGLE
624
+ knee_targ[supporting_leg] = supporting_knee_angle
625
+ if s[moving_s_base + 4]:
626
+ state = PUSH_OFF
627
+ supporting_knee_angle = min(s[moving_s_base + 2], SUPPORT_KNEE_ANGLE)
628
+ if state == PUSH_OFF:
629
+ knee_targ[moving_leg] = supporting_knee_angle
630
+ knee_targ[supporting_leg] = +1.0
631
+ if s[supporting_s_base + 2] > 0.88 or s[2] > 1.2 * SPEED:
632
+ state = STAY_ON_ONE_LEG
633
+ moving_leg = 1 - moving_leg
634
+ supporting_leg = 1 - moving_leg
635
+
636
+ if hip_targ[0]:
637
+ hip_todo[0] = 0.9 * (hip_targ[0] - s[4]) - 0.25 * s[5]
638
+ if hip_targ[1]:
639
+ hip_todo[1] = 0.9 * (hip_targ[1] - s[9]) - 0.25 * s[10]
640
+ if knee_targ[0]:
641
+ knee_todo[0] = 4.0 * (knee_targ[0] - s[6]) - 0.25 * s[7]
642
+ if knee_targ[1]:
643
+ knee_todo[1] = 4.0 * (knee_targ[1] - s[11]) - 0.25 * s[12]
644
+
645
+ hip_todo[0] -= 0.9 * (0 - s[0]) - 1.5 * s[1] # PID to keep head strait
646
+ hip_todo[1] -= 0.9 * (0 - s[0]) - 1.5 * s[1]
647
+ knee_todo[0] -= 15.0 * s[3] # vertical speed, to damp oscillations
648
+ knee_todo[1] -= 15.0 * s[3]
649
+
650
+ a[0] = hip_todo[0]
651
+ a[1] = knee_todo[0]
652
+ a[2] = hip_todo[1]
653
+ a[3] = knee_todo[1]
654
+ a = np.clip(0.5 * a, -1.0, 1.0)
655
+
656
+ env.render()
657
+ if done:
658
+ break
gym/envs/box2d/car_dynamics.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Top-down car dynamics simulation.
3
+
4
+ Some ideas are taken from this great tutorial http://www.iforce2d.net/b2dtut/top-down-car by Chris Campbell.
5
+ This simulation is a bit more detailed, with wheels rotation.
6
+
7
+ Created by Oleg Klimov. Licensed on the same terms as the rest of OpenAI Gym.
8
+ """
9
+
10
+ import numpy as np
11
+ import math
12
+ import Box2D
13
+ from Box2D.b2 import (
14
+ edgeShape,
15
+ circleShape,
16
+ fixtureDef,
17
+ polygonShape,
18
+ revoluteJointDef,
19
+ contactListener,
20
+ shape,
21
+ )
22
+
23
+ SIZE = 0.02
24
+ ENGINE_POWER = 100000000 * SIZE * SIZE
25
+ WHEEL_MOMENT_OF_INERTIA = 4000 * SIZE * SIZE
26
+ FRICTION_LIMIT = (
27
+ 1000000 * SIZE * SIZE
28
+ ) # friction ~= mass ~= size^2 (calculated implicitly using density)
29
+ WHEEL_R = 27
30
+ WHEEL_W = 14
31
+ WHEELPOS = [(-55, +80), (+55, +80), (-55, -82), (+55, -82)]
32
+ HULL_POLY1 = [(-60, +130), (+60, +130), (+60, +110), (-60, +110)]
33
+ HULL_POLY2 = [(-15, +120), (+15, +120), (+20, +20), (-20, 20)]
34
+ HULL_POLY3 = [
35
+ (+25, +20),
36
+ (+50, -10),
37
+ (+50, -40),
38
+ (+20, -90),
39
+ (-20, -90),
40
+ (-50, -40),
41
+ (-50, -10),
42
+ (-25, +20),
43
+ ]
44
+ HULL_POLY4 = [(-50, -120), (+50, -120), (+50, -90), (-50, -90)]
45
+ WHEEL_COLOR = (0.0, 0.0, 0.0)
46
+ WHEEL_WHITE = (0.3, 0.3, 0.3)
47
+ MUD_COLOR = (0.4, 0.4, 0.0)
48
+
49
+
50
+ class Car:
51
+ def __init__(self, world, init_angle, init_x, init_y):
52
+ self.world = world
53
+ self.hull = self.world.CreateDynamicBody(
54
+ position=(init_x, init_y),
55
+ angle=init_angle,
56
+ fixtures=[
57
+ fixtureDef(
58
+ shape=polygonShape(
59
+ vertices=[(x * SIZE, y * SIZE) for x, y in HULL_POLY1]
60
+ ),
61
+ density=1.0,
62
+ ),
63
+ fixtureDef(
64
+ shape=polygonShape(
65
+ vertices=[(x * SIZE, y * SIZE) for x, y in HULL_POLY2]
66
+ ),
67
+ density=1.0,
68
+ ),
69
+ fixtureDef(
70
+ shape=polygonShape(
71
+ vertices=[(x * SIZE, y * SIZE) for x, y in HULL_POLY3]
72
+ ),
73
+ density=1.0,
74
+ ),
75
+ fixtureDef(
76
+ shape=polygonShape(
77
+ vertices=[(x * SIZE, y * SIZE) for x, y in HULL_POLY4]
78
+ ),
79
+ density=1.0,
80
+ ),
81
+ ],
82
+ )
83
+ self.hull.color = (0.8, 0.0, 0.0)
84
+ self.wheels = []
85
+ self.fuel_spent = 0.0
86
+ WHEEL_POLY = [
87
+ (-WHEEL_W, +WHEEL_R),
88
+ (+WHEEL_W, +WHEEL_R),
89
+ (+WHEEL_W, -WHEEL_R),
90
+ (-WHEEL_W, -WHEEL_R),
91
+ ]
92
+ for wx, wy in WHEELPOS:
93
+ front_k = 1.0 if wy > 0 else 1.0
94
+ w = self.world.CreateDynamicBody(
95
+ position=(init_x + wx * SIZE, init_y + wy * SIZE),
96
+ angle=init_angle,
97
+ fixtures=fixtureDef(
98
+ shape=polygonShape(
99
+ vertices=[
100
+ (x * front_k * SIZE, y * front_k * SIZE)
101
+ for x, y in WHEEL_POLY
102
+ ]
103
+ ),
104
+ density=0.1,
105
+ categoryBits=0x0020,
106
+ maskBits=0x001,
107
+ restitution=0.0,
108
+ ),
109
+ )
110
+ w.wheel_rad = front_k * WHEEL_R * SIZE
111
+ w.color = WHEEL_COLOR
112
+ w.gas = 0.0
113
+ w.brake = 0.0
114
+ w.steer = 0.0
115
+ w.phase = 0.0 # wheel angle
116
+ w.omega = 0.0 # angular velocity
117
+ w.skid_start = None
118
+ w.skid_particle = None
119
+ rjd = revoluteJointDef(
120
+ bodyA=self.hull,
121
+ bodyB=w,
122
+ localAnchorA=(wx * SIZE, wy * SIZE),
123
+ localAnchorB=(0, 0),
124
+ enableMotor=True,
125
+ enableLimit=True,
126
+ maxMotorTorque=180 * 900 * SIZE * SIZE,
127
+ motorSpeed=0,
128
+ lowerAngle=-0.4,
129
+ upperAngle=+0.4,
130
+ )
131
+ w.joint = self.world.CreateJoint(rjd)
132
+ w.tiles = set()
133
+ w.userData = w
134
+ self.wheels.append(w)
135
+ self.drawlist = self.wheels + [self.hull]
136
+ self.particles = []
137
+
138
+ def gas(self, gas):
139
+ """control: rear wheel drive
140
+
141
+ Args:
142
+ gas (float): How much gas gets applied. Gets clipped between 0 and 1.
143
+ """
144
+ gas = np.clip(gas, 0, 1)
145
+ for w in self.wheels[2:4]:
146
+ diff = gas - w.gas
147
+ if diff > 0.1:
148
+ diff = 0.1 # gradually increase, but stop immediately
149
+ w.gas += diff
150
+
151
+ def brake(self, b):
152
+ """control: brake
153
+
154
+ Args:
155
+ b (0..1): Degree to which the brakes are applied. More than 0.9 blocks the wheels to zero rotation"""
156
+ for w in self.wheels:
157
+ w.brake = b
158
+
159
+ def steer(self, s):
160
+ """control: steer
161
+
162
+ Args:
163
+ s (-1..1): target position, it takes time to rotate steering wheel from side-to-side"""
164
+ self.wheels[0].steer = s
165
+ self.wheels[1].steer = s
166
+
167
+ def step(self, dt):
168
+ for w in self.wheels:
169
+ # Steer each wheel
170
+ dir = np.sign(w.steer - w.joint.angle)
171
+ val = abs(w.steer - w.joint.angle)
172
+ w.joint.motorSpeed = dir * min(50.0 * val, 3.0)
173
+
174
+ # Position => friction_limit
175
+ grass = True
176
+ friction_limit = FRICTION_LIMIT * 0.6 # Grass friction if no tile
177
+ for tile in w.tiles:
178
+ friction_limit = max(
179
+ friction_limit, FRICTION_LIMIT * tile.road_friction
180
+ )
181
+ grass = False
182
+
183
+ # Force
184
+ forw = w.GetWorldVector((0, 1))
185
+ side = w.GetWorldVector((1, 0))
186
+ v = w.linearVelocity
187
+ vf = forw[0] * v[0] + forw[1] * v[1] # forward speed
188
+ vs = side[0] * v[0] + side[1] * v[1] # side speed
189
+
190
+ # WHEEL_MOMENT_OF_INERTIA*np.square(w.omega)/2 = E -- energy
191
+ # WHEEL_MOMENT_OF_INERTIA*w.omega * domega/dt = dE/dt = W -- power
192
+ # domega = dt*W/WHEEL_MOMENT_OF_INERTIA/w.omega
193
+
194
+ # add small coef not to divide by zero
195
+ w.omega += (
196
+ dt
197
+ * ENGINE_POWER
198
+ * w.gas
199
+ / WHEEL_MOMENT_OF_INERTIA
200
+ / (abs(w.omega) + 5.0)
201
+ )
202
+ self.fuel_spent += dt * ENGINE_POWER * w.gas
203
+
204
+ if w.brake >= 0.9:
205
+ w.omega = 0
206
+ elif w.brake > 0:
207
+ BRAKE_FORCE = 15 # radians per second
208
+ dir = -np.sign(w.omega)
209
+ val = BRAKE_FORCE * w.brake
210
+ if abs(val) > abs(w.omega):
211
+ val = abs(w.omega) # low speed => same as = 0
212
+ w.omega += dir * val
213
+ w.phase += w.omega * dt
214
+
215
+ vr = w.omega * w.wheel_rad # rotating wheel speed
216
+ f_force = -vf + vr # force direction is direction of speed difference
217
+ p_force = -vs
218
+
219
+ # Physically correct is to always apply friction_limit until speed is equal.
220
+ # But dt is finite, that will lead to oscillations if difference is already near zero.
221
+
222
+ # Random coefficient to cut oscillations in few steps (have no effect on friction_limit)
223
+ f_force *= 205000 * SIZE * SIZE
224
+ p_force *= 205000 * SIZE * SIZE
225
+ force = np.sqrt(np.square(f_force) + np.square(p_force))
226
+
227
+ # Skid trace
228
+ if abs(force) > 2.0 * friction_limit:
229
+ if (
230
+ w.skid_particle
231
+ and w.skid_particle.grass == grass
232
+ and len(w.skid_particle.poly) < 30
233
+ ):
234
+ w.skid_particle.poly.append((w.position[0], w.position[1]))
235
+ elif w.skid_start is None:
236
+ w.skid_start = w.position
237
+ else:
238
+ w.skid_particle = self._create_particle(
239
+ w.skid_start, w.position, grass
240
+ )
241
+ w.skid_start = None
242
+ else:
243
+ w.skid_start = None
244
+ w.skid_particle = None
245
+
246
+ if abs(force) > friction_limit:
247
+ f_force /= force
248
+ p_force /= force
249
+ force = friction_limit # Correct physics here
250
+ f_force *= force
251
+ p_force *= force
252
+
253
+ w.omega -= dt * f_force * w.wheel_rad / WHEEL_MOMENT_OF_INERTIA
254
+
255
+ w.ApplyForceToCenter(
256
+ (
257
+ p_force * side[0] + f_force * forw[0],
258
+ p_force * side[1] + f_force * forw[1],
259
+ ),
260
+ True,
261
+ )
262
+
263
+ def draw(self, viewer, draw_particles=True):
264
+ if draw_particles:
265
+ for p in self.particles:
266
+ viewer.draw_polyline(p.poly, color=p.color, linewidth=5)
267
+ for obj in self.drawlist:
268
+ for f in obj.fixtures:
269
+ trans = f.body.transform
270
+ path = [trans * v for v in f.shape.vertices]
271
+ viewer.draw_polygon(path, color=obj.color)
272
+ if "phase" not in obj.__dict__:
273
+ continue
274
+ a1 = obj.phase
275
+ a2 = obj.phase + 1.2 # radians
276
+ s1 = math.sin(a1)
277
+ s2 = math.sin(a2)
278
+ c1 = math.cos(a1)
279
+ c2 = math.cos(a2)
280
+ if s1 > 0 and s2 > 0:
281
+ continue
282
+ if s1 > 0:
283
+ c1 = np.sign(c1)
284
+ if s2 > 0:
285
+ c2 = np.sign(c2)
286
+ white_poly = [
287
+ (-WHEEL_W * SIZE, +WHEEL_R * c1 * SIZE),
288
+ (+WHEEL_W * SIZE, +WHEEL_R * c1 * SIZE),
289
+ (+WHEEL_W * SIZE, +WHEEL_R * c2 * SIZE),
290
+ (-WHEEL_W * SIZE, +WHEEL_R * c2 * SIZE),
291
+ ]
292
+ viewer.draw_polygon([trans * v for v in white_poly], color=WHEEL_WHITE)
293
+
294
+ def _create_particle(self, point1, point2, grass):
295
+ class Particle:
296
+ pass
297
+
298
+ p = Particle()
299
+ p.color = WHEEL_COLOR if not grass else MUD_COLOR
300
+ p.ttl = 1
301
+ p.poly = [(point1[0], point1[1]), (point2[0], point2[1])]
302
+ p.grass = grass
303
+ self.particles.append(p)
304
+ while len(self.particles) > 30:
305
+ self.particles.pop(0)
306
+ return p
307
+
308
+ def destroy(self):
309
+ self.world.DestroyBody(self.hull)
310
+ self.hull = None
311
+ for w in self.wheels:
312
+ self.world.DestroyBody(w)
313
+ self.wheels = []
gym/envs/box2d/car_racing.py ADDED
@@ -0,0 +1,652 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Easiest continuous control task to learn from pixels, a top-down racing
3
+ environment.
4
+ Discrete control is reasonable in this environment as well, on/off
5
+ discretization is fine.
6
+
7
+ State consists of STATE_W x STATE_H pixels.
8
+
9
+ The reward is -0.1 every frame and +1000/N for every track tile visited, where
10
+ N is the total number of tiles visited in the track. For example, if you have
11
+ finished in 732 frames, your reward is 1000 - 0.1*732 = 926.8 points.
12
+
13
+ The game is solved when the agent consistently gets 900+ points. The generated
14
+ track is random every episode.
15
+
16
+ The episode finishes when all the tiles are visited. The car also can go
17
+ outside of the PLAYFIELD - that is far off the track, then it will get -100
18
+ and die.
19
+
20
+ Some indicators are shown at the bottom of the window along with the state RGB
21
+ buffer. From left to right: the true speed, four ABS sensors, the steering
22
+ wheel position and gyroscope.
23
+
24
+ To play yourself (it's rather fast for humans), type:
25
+
26
+ python gym/envs/box2d/car_racing.py
27
+
28
+ Remember it's a powerful rear-wheel drive car - don't press the accelerator
29
+ and turn at the same time.
30
+
31
+ Created by Oleg Klimov. Licensed on the same terms as the rest of OpenAI Gym.
32
+ """
33
+ import sys
34
+ import math
35
+ import numpy as np
36
+
37
+ import Box2D
38
+ from Box2D.b2 import fixtureDef
39
+ from Box2D.b2 import polygonShape
40
+ from Box2D.b2 import contactListener
41
+
42
+ import gym
43
+ from gym import spaces
44
+ from gym.envs.box2d.car_dynamics import Car
45
+ from gym.utils import seeding, EzPickle
46
+
47
+ import pyglet
48
+
49
+ pyglet.options["debug_gl"] = False
50
+ from pyglet import gl
51
+
52
+ STATE_W = 96 # less than Atari 160x192
53
+ STATE_H = 96
54
+ VIDEO_W = 600
55
+ VIDEO_H = 400
56
+ WINDOW_W = 1000
57
+ WINDOW_H = 800
58
+
59
+ SCALE = 6.0 # Track scale
60
+ TRACK_RAD = 900 / SCALE # Track is heavily morphed circle with this radius
61
+ PLAYFIELD = 2000 / SCALE # Game over boundary
62
+ FPS = 50 # Frames per second
63
+ ZOOM = 2.7 # Camera zoom
64
+ ZOOM_FOLLOW = True # Set to False for fixed view (don't use zoom)
65
+
66
+
67
+ TRACK_DETAIL_STEP = 21 / SCALE
68
+ TRACK_TURN_RATE = 0.31
69
+ TRACK_WIDTH = 40 / SCALE
70
+ BORDER = 8 / SCALE
71
+ BORDER_MIN_COUNT = 4
72
+
73
+ ROAD_COLOR = [0.4, 0.4, 0.4]
74
+
75
+
76
+ class FrictionDetector(contactListener):
77
+ def __init__(self, env):
78
+ contactListener.__init__(self)
79
+ self.env = env
80
+
81
+ def BeginContact(self, contact):
82
+ self._contact(contact, True)
83
+
84
+ def EndContact(self, contact):
85
+ self._contact(contact, False)
86
+
87
+ def _contact(self, contact, begin):
88
+ tile = None
89
+ obj = None
90
+ u1 = contact.fixtureA.body.userData
91
+ u2 = contact.fixtureB.body.userData
92
+ if u1 and "road_friction" in u1.__dict__:
93
+ tile = u1
94
+ obj = u2
95
+ if u2 and "road_friction" in u2.__dict__:
96
+ tile = u2
97
+ obj = u1
98
+ if not tile:
99
+ return
100
+
101
+ tile.color[0] = ROAD_COLOR[0]
102
+ tile.color[1] = ROAD_COLOR[1]
103
+ tile.color[2] = ROAD_COLOR[2]
104
+ if not obj or "tiles" not in obj.__dict__:
105
+ return
106
+ if begin:
107
+ obj.tiles.add(tile)
108
+ if not tile.road_visited:
109
+ tile.road_visited = True
110
+ self.env.reward += 1000.0 / len(self.env.track)
111
+ self.env.tile_visited_count += 1
112
+ else:
113
+ obj.tiles.remove(tile)
114
+
115
+
116
+ class CarRacing(gym.Env, EzPickle):
117
+ metadata = {
118
+ "render.modes": ["human", "rgb_array", "state_pixels"],
119
+ "video.frames_per_second": FPS,
120
+ }
121
+
122
+ def __init__(self, verbose=1):
123
+ EzPickle.__init__(self)
124
+ self.seed()
125
+ self.contactListener_keepref = FrictionDetector(self)
126
+ self.world = Box2D.b2World((0, 0), contactListener=self.contactListener_keepref)
127
+ self.viewer = None
128
+ self.invisible_state_window = None
129
+ self.invisible_video_window = None
130
+ self.road = None
131
+ self.car = None
132
+ self.reward = 0.0
133
+ self.prev_reward = 0.0
134
+ self.verbose = verbose
135
+ self.fd_tile = fixtureDef(
136
+ shape=polygonShape(vertices=[(0, 0), (1, 0), (1, -1), (0, -1)])
137
+ )
138
+
139
+ self.action_space = spaces.Box(
140
+ np.array([-1, 0, 0]).astype(np.float32),
141
+ np.array([+1, +1, +1]).astype(np.float32),
142
+ ) # steer, gas, brake
143
+
144
+ self.observation_space = spaces.Box(
145
+ low=0, high=255, shape=(STATE_H, STATE_W, 3), dtype=np.uint8
146
+ )
147
+
148
+ def seed(self, seed=None):
149
+ self.np_random, seed = seeding.np_random(seed)
150
+ return [seed]
151
+
152
+ def _destroy(self):
153
+ if not self.road:
154
+ return
155
+ for t in self.road:
156
+ self.world.DestroyBody(t)
157
+ self.road = []
158
+ self.car.destroy()
159
+
160
+ def _create_track(self):
161
+ CHECKPOINTS = 12
162
+
163
+ # Create checkpoints
164
+ checkpoints = []
165
+ for c in range(CHECKPOINTS):
166
+ noise = self.np_random.uniform(0, 2 * math.pi * 1 / CHECKPOINTS)
167
+ alpha = 2 * math.pi * c / CHECKPOINTS + noise
168
+ rad = self.np_random.uniform(TRACK_RAD / 3, TRACK_RAD)
169
+
170
+ if c == 0:
171
+ alpha = 0
172
+ rad = 1.5 * TRACK_RAD
173
+ if c == CHECKPOINTS - 1:
174
+ alpha = 2 * math.pi * c / CHECKPOINTS
175
+ self.start_alpha = 2 * math.pi * (-0.5) / CHECKPOINTS
176
+ rad = 1.5 * TRACK_RAD
177
+
178
+ checkpoints.append((alpha, rad * math.cos(alpha), rad * math.sin(alpha)))
179
+ self.road = []
180
+
181
+ # Go from one checkpoint to another to create track
182
+ x, y, beta = 1.5 * TRACK_RAD, 0, 0
183
+ dest_i = 0
184
+ laps = 0
185
+ track = []
186
+ no_freeze = 2500
187
+ visited_other_side = False
188
+ while True:
189
+ alpha = math.atan2(y, x)
190
+ if visited_other_side and alpha > 0:
191
+ laps += 1
192
+ visited_other_side = False
193
+ if alpha < 0:
194
+ visited_other_side = True
195
+ alpha += 2 * math.pi
196
+
197
+ while True: # Find destination from checkpoints
198
+ failed = True
199
+
200
+ while True:
201
+ dest_alpha, dest_x, dest_y = checkpoints[dest_i % len(checkpoints)]
202
+ if alpha <= dest_alpha:
203
+ failed = False
204
+ break
205
+ dest_i += 1
206
+ if dest_i % len(checkpoints) == 0:
207
+ break
208
+
209
+ if not failed:
210
+ break
211
+
212
+ alpha -= 2 * math.pi
213
+ continue
214
+
215
+ r1x = math.cos(beta)
216
+ r1y = math.sin(beta)
217
+ p1x = -r1y
218
+ p1y = r1x
219
+ dest_dx = dest_x - x # vector towards destination
220
+ dest_dy = dest_y - y
221
+ # destination vector projected on rad:
222
+ proj = r1x * dest_dx + r1y * dest_dy
223
+ while beta - alpha > 1.5 * math.pi:
224
+ beta -= 2 * math.pi
225
+ while beta - alpha < -1.5 * math.pi:
226
+ beta += 2 * math.pi
227
+ prev_beta = beta
228
+ proj *= SCALE
229
+ if proj > 0.3:
230
+ beta -= min(TRACK_TURN_RATE, abs(0.001 * proj))
231
+ if proj < -0.3:
232
+ beta += min(TRACK_TURN_RATE, abs(0.001 * proj))
233
+ x += p1x * TRACK_DETAIL_STEP
234
+ y += p1y * TRACK_DETAIL_STEP
235
+ track.append((alpha, prev_beta * 0.5 + beta * 0.5, x, y))
236
+ if laps > 4:
237
+ break
238
+ no_freeze -= 1
239
+ if no_freeze == 0:
240
+ break
241
+
242
+ # Find closed loop range i1..i2, first loop should be ignored, second is OK
243
+ i1, i2 = -1, -1
244
+ i = len(track)
245
+ while True:
246
+ i -= 1
247
+ if i == 0:
248
+ return False # Failed
249
+ pass_through_start = (
250
+ track[i][0] > self.start_alpha and track[i - 1][0] <= self.start_alpha
251
+ )
252
+ if pass_through_start and i2 == -1:
253
+ i2 = i
254
+ elif pass_through_start and i1 == -1:
255
+ i1 = i
256
+ break
257
+ if self.verbose == 1:
258
+ print("Track generation: %i..%i -> %i-tiles track" % (i1, i2, i2 - i1))
259
+ assert i1 != -1
260
+ assert i2 != -1
261
+
262
+ track = track[i1 : i2 - 1]
263
+
264
+ first_beta = track[0][1]
265
+ first_perp_x = math.cos(first_beta)
266
+ first_perp_y = math.sin(first_beta)
267
+ # Length of perpendicular jump to put together head and tail
268
+ well_glued_together = np.sqrt(
269
+ np.square(first_perp_x * (track[0][2] - track[-1][2]))
270
+ + np.square(first_perp_y * (track[0][3] - track[-1][3]))
271
+ )
272
+ if well_glued_together > TRACK_DETAIL_STEP:
273
+ return False
274
+
275
+ # Red-white border on hard turns
276
+ border = [False] * len(track)
277
+ for i in range(len(track)):
278
+ good = True
279
+ oneside = 0
280
+ for neg in range(BORDER_MIN_COUNT):
281
+ beta1 = track[i - neg - 0][1]
282
+ beta2 = track[i - neg - 1][1]
283
+ good &= abs(beta1 - beta2) > TRACK_TURN_RATE * 0.2
284
+ oneside += np.sign(beta1 - beta2)
285
+ good &= abs(oneside) == BORDER_MIN_COUNT
286
+ border[i] = good
287
+ for i in range(len(track)):
288
+ for neg in range(BORDER_MIN_COUNT):
289
+ border[i - neg] |= border[i]
290
+
291
+ # Create tiles
292
+ for i in range(len(track)):
293
+ alpha1, beta1, x1, y1 = track[i]
294
+ alpha2, beta2, x2, y2 = track[i - 1]
295
+ road1_l = (
296
+ x1 - TRACK_WIDTH * math.cos(beta1),
297
+ y1 - TRACK_WIDTH * math.sin(beta1),
298
+ )
299
+ road1_r = (
300
+ x1 + TRACK_WIDTH * math.cos(beta1),
301
+ y1 + TRACK_WIDTH * math.sin(beta1),
302
+ )
303
+ road2_l = (
304
+ x2 - TRACK_WIDTH * math.cos(beta2),
305
+ y2 - TRACK_WIDTH * math.sin(beta2),
306
+ )
307
+ road2_r = (
308
+ x2 + TRACK_WIDTH * math.cos(beta2),
309
+ y2 + TRACK_WIDTH * math.sin(beta2),
310
+ )
311
+ vertices = [road1_l, road1_r, road2_r, road2_l]
312
+ self.fd_tile.shape.vertices = vertices
313
+ t = self.world.CreateStaticBody(fixtures=self.fd_tile)
314
+ t.userData = t
315
+ c = 0.01 * (i % 3)
316
+ t.color = [ROAD_COLOR[0] + c, ROAD_COLOR[1] + c, ROAD_COLOR[2] + c]
317
+ t.road_visited = False
318
+ t.road_friction = 1.0
319
+ t.fixtures[0].sensor = True
320
+ self.road_poly.append(([road1_l, road1_r, road2_r, road2_l], t.color))
321
+ self.road.append(t)
322
+ if border[i]:
323
+ side = np.sign(beta2 - beta1)
324
+ b1_l = (
325
+ x1 + side * TRACK_WIDTH * math.cos(beta1),
326
+ y1 + side * TRACK_WIDTH * math.sin(beta1),
327
+ )
328
+ b1_r = (
329
+ x1 + side * (TRACK_WIDTH + BORDER) * math.cos(beta1),
330
+ y1 + side * (TRACK_WIDTH + BORDER) * math.sin(beta1),
331
+ )
332
+ b2_l = (
333
+ x2 + side * TRACK_WIDTH * math.cos(beta2),
334
+ y2 + side * TRACK_WIDTH * math.sin(beta2),
335
+ )
336
+ b2_r = (
337
+ x2 + side * (TRACK_WIDTH + BORDER) * math.cos(beta2),
338
+ y2 + side * (TRACK_WIDTH + BORDER) * math.sin(beta2),
339
+ )
340
+ self.road_poly.append(
341
+ ([b1_l, b1_r, b2_r, b2_l], (1, 1, 1) if i % 2 == 0 else (1, 0, 0))
342
+ )
343
+ self.track = track
344
+ return True
345
+
346
+ def reset(self):
347
+ self._destroy()
348
+ self.reward = 0.0
349
+ self.prev_reward = 0.0
350
+ self.tile_visited_count = 0
351
+ self.t = 0.0
352
+ self.road_poly = []
353
+
354
+ while True:
355
+ success = self._create_track()
356
+ if success:
357
+ break
358
+ if self.verbose == 1:
359
+ print(
360
+ "retry to generate track (normal if there are not many"
361
+ "instances of this message)"
362
+ )
363
+ self.car = Car(self.world, *self.track[0][1:4])
364
+
365
+ return self.step(None)[0]
366
+
367
+ def step(self, action):
368
+ if action is not None:
369
+ self.car.steer(-action[0])
370
+ self.car.gas(action[1])
371
+ self.car.brake(action[2])
372
+
373
+ self.car.step(1.0 / FPS)
374
+ self.world.Step(1.0 / FPS, 6 * 30, 2 * 30)
375
+ self.t += 1.0 / FPS
376
+
377
+ self.state = self.render("state_pixels")
378
+
379
+ step_reward = 0
380
+ done = False
381
+ if action is not None: # First step without action, called from reset()
382
+ self.reward -= 0.1
383
+ # We actually don't want to count fuel spent, we want car to be faster.
384
+ # self.reward -= 10 * self.car.fuel_spent / ENGINE_POWER
385
+ self.car.fuel_spent = 0.0
386
+ step_reward = self.reward - self.prev_reward
387
+ self.prev_reward = self.reward
388
+ if self.tile_visited_count == len(self.track):
389
+ done = True
390
+ x, y = self.car.hull.position
391
+ if abs(x) > PLAYFIELD or abs(y) > PLAYFIELD:
392
+ done = True
393
+ step_reward = -100
394
+
395
+ return self.state, step_reward, done, {}
396
+
397
+ def render(self, mode="human"):
398
+ assert mode in ["human", "state_pixels", "rgb_array"]
399
+ if self.viewer is None:
400
+ from gym.envs.classic_control import rendering
401
+
402
+ self.viewer = rendering.Viewer(WINDOW_W, WINDOW_H)
403
+ self.score_label = pyglet.text.Label(
404
+ "0000",
405
+ font_size=36,
406
+ x=20,
407
+ y=WINDOW_H * 2.5 / 40.00,
408
+ anchor_x="left",
409
+ anchor_y="center",
410
+ color=(255, 255, 255, 255),
411
+ )
412
+ self.transform = rendering.Transform()
413
+
414
+ if "t" not in self.__dict__:
415
+ return # reset() not called yet
416
+
417
+ # Animate zoom first second:
418
+ zoom = 0.1 * SCALE * max(1 - self.t, 0) + ZOOM * SCALE * min(self.t, 1)
419
+ scroll_x = self.car.hull.position[0]
420
+ scroll_y = self.car.hull.position[1]
421
+ angle = -self.car.hull.angle
422
+ vel = self.car.hull.linearVelocity
423
+ if np.linalg.norm(vel) > 0.5:
424
+ angle = math.atan2(vel[0], vel[1])
425
+ self.transform.set_scale(zoom, zoom)
426
+ self.transform.set_translation(
427
+ WINDOW_W / 2
428
+ - (scroll_x * zoom * math.cos(angle) - scroll_y * zoom * math.sin(angle)),
429
+ WINDOW_H / 4
430
+ - (scroll_x * zoom * math.sin(angle) + scroll_y * zoom * math.cos(angle)),
431
+ )
432
+ self.transform.set_rotation(angle)
433
+
434
+ self.car.draw(self.viewer, mode != "state_pixels")
435
+
436
+ arr = None
437
+ win = self.viewer.window
438
+ win.switch_to()
439
+ win.dispatch_events()
440
+
441
+ win.clear()
442
+ t = self.transform
443
+ if mode == "rgb_array":
444
+ VP_W = VIDEO_W
445
+ VP_H = VIDEO_H
446
+ elif mode == "state_pixels":
447
+ VP_W = STATE_W
448
+ VP_H = STATE_H
449
+ else:
450
+ pixel_scale = 1
451
+ if hasattr(win.context, "_nscontext"):
452
+ pixel_scale = (
453
+ win.context._nscontext.view().backingScaleFactor()
454
+ ) # pylint: disable=protected-access
455
+ VP_W = int(pixel_scale * WINDOW_W)
456
+ VP_H = int(pixel_scale * WINDOW_H)
457
+
458
+ gl.glViewport(0, 0, VP_W, VP_H)
459
+ t.enable()
460
+ self.render_road()
461
+ for geom in self.viewer.onetime_geoms:
462
+ geom.render()
463
+ self.viewer.onetime_geoms = []
464
+ t.disable()
465
+ self.render_indicators(WINDOW_W, WINDOW_H)
466
+
467
+ if mode == "human":
468
+ win.flip()
469
+ return self.viewer.isopen
470
+
471
+ image_data = (
472
+ pyglet.image.get_buffer_manager().get_color_buffer().get_image_data()
473
+ )
474
+ arr = np.fromstring(image_data.get_data(), dtype=np.uint8, sep="")
475
+ arr = arr.reshape(VP_H, VP_W, 4)
476
+ arr = arr[::-1, :, 0:3]
477
+
478
+ return arr
479
+
480
+ def close(self):
481
+ if self.viewer is not None:
482
+ self.viewer.close()
483
+ self.viewer = None
484
+
485
+ def render_road(self):
486
+ colors = [0.4, 0.8, 0.4, 1.0] * 4
487
+ polygons_ = [
488
+ +PLAYFIELD,
489
+ +PLAYFIELD,
490
+ 0,
491
+ +PLAYFIELD,
492
+ -PLAYFIELD,
493
+ 0,
494
+ -PLAYFIELD,
495
+ -PLAYFIELD,
496
+ 0,
497
+ -PLAYFIELD,
498
+ +PLAYFIELD,
499
+ 0,
500
+ ]
501
+
502
+ k = PLAYFIELD / 20.0
503
+ colors.extend([0.4, 0.9, 0.4, 1.0] * 4 * 20 * 20)
504
+ for x in range(-20, 20, 2):
505
+ for y in range(-20, 20, 2):
506
+ polygons_.extend(
507
+ [
508
+ k * x + k,
509
+ k * y + 0,
510
+ 0,
511
+ k * x + 0,
512
+ k * y + 0,
513
+ 0,
514
+ k * x + 0,
515
+ k * y + k,
516
+ 0,
517
+ k * x + k,
518
+ k * y + k,
519
+ 0,
520
+ ]
521
+ )
522
+
523
+ for poly, color in self.road_poly:
524
+ colors.extend([color[0], color[1], color[2], 1] * len(poly))
525
+ for p in poly:
526
+ polygons_.extend([p[0], p[1], 0])
527
+
528
+ vl = pyglet.graphics.vertex_list(
529
+ len(polygons_) // 3, ("v3f", polygons_), ("c4f", colors)
530
+ ) # gl.GL_QUADS,
531
+ vl.draw(gl.GL_QUADS)
532
+ vl.delete()
533
+
534
+ def render_indicators(self, W, H):
535
+ s = W / 40.0
536
+ h = H / 40.0
537
+ colors = [0, 0, 0, 1] * 4
538
+ polygons = [W, 0, 0, W, 5 * h, 0, 0, 5 * h, 0, 0, 0, 0]
539
+
540
+ def vertical_ind(place, val, color):
541
+ colors.extend([color[0], color[1], color[2], 1] * 4)
542
+ polygons.extend(
543
+ [
544
+ place * s,
545
+ h + h * val,
546
+ 0,
547
+ (place + 1) * s,
548
+ h + h * val,
549
+ 0,
550
+ (place + 1) * s,
551
+ h,
552
+ 0,
553
+ (place + 0) * s,
554
+ h,
555
+ 0,
556
+ ]
557
+ )
558
+
559
+ def horiz_ind(place, val, color):
560
+ colors.extend([color[0], color[1], color[2], 1] * 4)
561
+ polygons.extend(
562
+ [
563
+ (place + 0) * s,
564
+ 4 * h,
565
+ 0,
566
+ (place + val) * s,
567
+ 4 * h,
568
+ 0,
569
+ (place + val) * s,
570
+ 2 * h,
571
+ 0,
572
+ (place + 0) * s,
573
+ 2 * h,
574
+ 0,
575
+ ]
576
+ )
577
+
578
+ true_speed = np.sqrt(
579
+ np.square(self.car.hull.linearVelocity[0])
580
+ + np.square(self.car.hull.linearVelocity[1])
581
+ )
582
+
583
+ vertical_ind(5, 0.02 * true_speed, (1, 1, 1))
584
+ vertical_ind(7, 0.01 * self.car.wheels[0].omega, (0.0, 0, 1)) # ABS sensors
585
+ vertical_ind(8, 0.01 * self.car.wheels[1].omega, (0.0, 0, 1))
586
+ vertical_ind(9, 0.01 * self.car.wheels[2].omega, (0.2, 0, 1))
587
+ vertical_ind(10, 0.01 * self.car.wheels[3].omega, (0.2, 0, 1))
588
+ horiz_ind(20, -10.0 * self.car.wheels[0].joint.angle, (0, 1, 0))
589
+ horiz_ind(30, -0.8 * self.car.hull.angularVelocity, (1, 0, 0))
590
+ vl = pyglet.graphics.vertex_list(
591
+ len(polygons) // 3, ("v3f", polygons), ("c4f", colors)
592
+ ) # gl.GL_QUADS,
593
+ vl.draw(gl.GL_QUADS)
594
+ vl.delete()
595
+ self.score_label.text = "%04i" % self.reward
596
+ self.score_label.draw()
597
+
598
+
599
+ if __name__ == "__main__":
600
+ from pyglet.window import key
601
+
602
+ a = np.array([0.0, 0.0, 0.0])
603
+
604
+ def key_press(k, mod):
605
+ global restart
606
+ if k == 0xFF0D:
607
+ restart = True
608
+ if k == key.LEFT:
609
+ a[0] = -1.0
610
+ if k == key.RIGHT:
611
+ a[0] = +1.0
612
+ if k == key.UP:
613
+ a[1] = +1.0
614
+ if k == key.DOWN:
615
+ a[2] = +0.8 # set 1.0 for wheels to block to zero rotation
616
+
617
+ def key_release(k, mod):
618
+ if k == key.LEFT and a[0] == -1.0:
619
+ a[0] = 0
620
+ if k == key.RIGHT and a[0] == +1.0:
621
+ a[0] = 0
622
+ if k == key.UP:
623
+ a[1] = 0
624
+ if k == key.DOWN:
625
+ a[2] = 0
626
+
627
+ env = CarRacing()
628
+ env.render()
629
+ env.viewer.window.on_key_press = key_press
630
+ env.viewer.window.on_key_release = key_release
631
+ record_video = False
632
+ if record_video:
633
+ from gym.wrappers.monitor import Monitor
634
+
635
+ env = Monitor(env, "/tmp/video-test", force=True)
636
+ isopen = True
637
+ while isopen:
638
+ env.reset()
639
+ total_reward = 0.0
640
+ steps = 0
641
+ restart = False
642
+ while True:
643
+ s, r, done, info = env.step(a)
644
+ total_reward += r
645
+ if steps % 200 == 0 or done:
646
+ print("\naction " + str(["{:+0.2f}".format(x) for x in a]))
647
+ print("step {} total_reward {:+0.2f}".format(steps, total_reward))
648
+ steps += 1
649
+ isopen = env.render()
650
+ if done or restart or isopen == False:
651
+ break
652
+ env.close()
gym/envs/box2d/lunar_lander.py ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Rocket trajectory optimization is a classic topic in Optimal Control.
3
+
4
+ According to Pontryagin's maximum principle it's optimal to fire engine full throttle or
5
+ turn it off. That's the reason this environment is OK to have discreet actions (engine on or off).
6
+
7
+ The landing pad is always at coordinates (0,0). The coordinates are the first two numbers in the state vector.
8
+ Reward for moving from the top of the screen to the landing pad and zero speed is about 100..140 points.
9
+ If the lander moves away from the landing pad it loses reward. The episode finishes if the lander crashes or
10
+ comes to rest, receiving an additional -100 or +100 points. Each leg with ground contact is +10 points.
11
+ Firing the main engine is -0.3 points each frame. Firing the side engine is -0.03 points each frame.
12
+ Solved is 200 points.
13
+
14
+ Landing outside the landing pad is possible. Fuel is infinite, so an agent can learn to fly and then land
15
+ on its first attempt. Please see the source code for details.
16
+
17
+ To see a heuristic landing, run:
18
+
19
+ python gym/envs/box2d/lunar_lander.py
20
+
21
+ To play yourself, run:
22
+
23
+ python examples/agents/keyboard_agent.py LunarLander-v2
24
+
25
+ Created by Oleg Klimov. Licensed on the same terms as the rest of OpenAI Gym.
26
+ """
27
+
28
+
29
+ import math
30
+ import sys
31
+ import numpy as np
32
+
33
+ import Box2D
34
+ from Box2D.b2 import (
35
+ edgeShape,
36
+ circleShape,
37
+ fixtureDef,
38
+ polygonShape,
39
+ revoluteJointDef,
40
+ contactListener,
41
+ )
42
+
43
+ import gym
44
+ from gym import spaces
45
+ from gym.utils import seeding, EzPickle
46
+
47
+ FPS = 50
48
+ SCALE = 30.0 # affects how fast-paced the game is, forces should be adjusted as well
49
+
50
+ MAIN_ENGINE_POWER = 13.0
51
+ SIDE_ENGINE_POWER = 0.6
52
+
53
+ INITIAL_RANDOM = 1000.0 # Set 1500 to make game harder
54
+
55
+ LANDER_POLY = [(-14, +17), (-17, 0), (-17, -10), (+17, -10), (+17, 0), (+14, +17)]
56
+ LEG_AWAY = 20
57
+ LEG_DOWN = 18
58
+ LEG_W, LEG_H = 2, 8
59
+ LEG_SPRING_TORQUE = 40
60
+
61
+ SIDE_ENGINE_HEIGHT = 14.0
62
+ SIDE_ENGINE_AWAY = 12.0
63
+
64
+ VIEWPORT_W = 600
65
+ VIEWPORT_H = 400
66
+
67
+
68
+ class ContactDetector(contactListener):
69
+ def __init__(self, env):
70
+ contactListener.__init__(self)
71
+ self.env = env
72
+
73
+ def BeginContact(self, contact):
74
+ if (
75
+ self.env.lander == contact.fixtureA.body
76
+ or self.env.lander == contact.fixtureB.body
77
+ ):
78
+ self.env.game_over = True
79
+ for i in range(2):
80
+ if self.env.legs[i] in [contact.fixtureA.body, contact.fixtureB.body]:
81
+ self.env.legs[i].ground_contact = True
82
+
83
+ def EndContact(self, contact):
84
+ for i in range(2):
85
+ if self.env.legs[i] in [contact.fixtureA.body, contact.fixtureB.body]:
86
+ self.env.legs[i].ground_contact = False
87
+
88
+
89
+ class LunarLander(gym.Env, EzPickle):
90
+ metadata = {"render.modes": ["human", "rgb_array"], "video.frames_per_second": FPS}
91
+
92
+ continuous = False
93
+
94
+ def __init__(self):
95
+ EzPickle.__init__(self)
96
+ self.seed()
97
+ self.viewer = None
98
+
99
+ self.world = Box2D.b2World()
100
+ self.moon = None
101
+ self.lander = None
102
+ self.particles = []
103
+
104
+ self.prev_reward = None
105
+
106
+ # useful range is -1 .. +1, but spikes can be higher
107
+ self.observation_space = spaces.Box(
108
+ -np.inf, np.inf, shape=(8,), dtype=np.float32
109
+ )
110
+
111
+ if self.continuous:
112
+ # Action is two floats [main engine, left-right engines].
113
+ # Main engine: -1..0 off, 0..+1 throttle from 50% to 100% power. Engine can't work with less than 50% power.
114
+ # Left-right: -1.0..-0.5 fire left engine, +0.5..+1.0 fire right engine, -0.5..0.5 off
115
+ self.action_space = spaces.Box(-1, +1, (2,), dtype=np.float32)
116
+ else:
117
+ # Nop, fire left engine, main engine, right engine
118
+ self.action_space = spaces.Discrete(4)
119
+
120
+ def seed(self, seed=None):
121
+ self.np_random, seed = seeding.np_random(seed)
122
+ return [seed]
123
+
124
+ def _destroy(self):
125
+ if not self.moon:
126
+ return
127
+ self.world.contactListener = None
128
+ self._clean_particles(True)
129
+ self.world.DestroyBody(self.moon)
130
+ self.moon = None
131
+ self.world.DestroyBody(self.lander)
132
+ self.lander = None
133
+ self.world.DestroyBody(self.legs[0])
134
+ self.world.DestroyBody(self.legs[1])
135
+
136
+ def reset(self):
137
+ self._destroy()
138
+ self.world.contactListener_keepref = ContactDetector(self)
139
+ self.world.contactListener = self.world.contactListener_keepref
140
+ self.game_over = False
141
+ self.prev_shaping = None
142
+
143
+ W = VIEWPORT_W / SCALE
144
+ H = VIEWPORT_H / SCALE
145
+
146
+ # terrain
147
+ CHUNKS = 11
148
+ height = self.np_random.uniform(0, H / 2, size=(CHUNKS + 1,))
149
+ chunk_x = [W / (CHUNKS - 1) * i for i in range(CHUNKS)]
150
+ self.helipad_x1 = chunk_x[CHUNKS // 2 - 1]
151
+ self.helipad_x2 = chunk_x[CHUNKS // 2 + 1]
152
+ self.helipad_y = H / 4
153
+ height[CHUNKS // 2 - 2] = self.helipad_y
154
+ height[CHUNKS // 2 - 1] = self.helipad_y
155
+ height[CHUNKS // 2 + 0] = self.helipad_y
156
+ height[CHUNKS // 2 + 1] = self.helipad_y
157
+ height[CHUNKS // 2 + 2] = self.helipad_y
158
+ smooth_y = [
159
+ 0.33 * (height[i - 1] + height[i + 0] + height[i + 1])
160
+ for i in range(CHUNKS)
161
+ ]
162
+
163
+ self.moon = self.world.CreateStaticBody(
164
+ shapes=edgeShape(vertices=[(0, 0), (W, 0)])
165
+ )
166
+ self.sky_polys = []
167
+ for i in range(CHUNKS - 1):
168
+ p1 = (chunk_x[i], smooth_y[i])
169
+ p2 = (chunk_x[i + 1], smooth_y[i + 1])
170
+ self.moon.CreateEdgeFixture(vertices=[p1, p2], density=0, friction=0.1)
171
+ self.sky_polys.append([p1, p2, (p2[0], H), (p1[0], H)])
172
+
173
+ self.moon.color1 = (0.0, 0.0, 0.0)
174
+ self.moon.color2 = (0.0, 0.0, 0.0)
175
+
176
+ initial_y = VIEWPORT_H / SCALE
177
+ self.lander = self.world.CreateDynamicBody(
178
+ position=(VIEWPORT_W / SCALE / 2, initial_y),
179
+ angle=0.0,
180
+ fixtures=fixtureDef(
181
+ shape=polygonShape(
182
+ vertices=[(x / SCALE, y / SCALE) for x, y in LANDER_POLY]
183
+ ),
184
+ density=5.0,
185
+ friction=0.1,
186
+ categoryBits=0x0010,
187
+ maskBits=0x001, # collide only with ground
188
+ restitution=0.0,
189
+ ), # 0.99 bouncy
190
+ )
191
+ self.lander.color1 = (0.5, 0.4, 0.9)
192
+ self.lander.color2 = (0.3, 0.3, 0.5)
193
+ self.lander.ApplyForceToCenter(
194
+ (
195
+ self.np_random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM),
196
+ self.np_random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM),
197
+ ),
198
+ True,
199
+ )
200
+
201
+ self.legs = []
202
+ for i in [-1, +1]:
203
+ leg = self.world.CreateDynamicBody(
204
+ position=(VIEWPORT_W / SCALE / 2 - i * LEG_AWAY / SCALE, initial_y),
205
+ angle=(i * 0.05),
206
+ fixtures=fixtureDef(
207
+ shape=polygonShape(box=(LEG_W / SCALE, LEG_H / SCALE)),
208
+ density=1.0,
209
+ restitution=0.0,
210
+ categoryBits=0x0020,
211
+ maskBits=0x001,
212
+ ),
213
+ )
214
+ leg.ground_contact = False
215
+ leg.color1 = (0.5, 0.4, 0.9)
216
+ leg.color2 = (0.3, 0.3, 0.5)
217
+ rjd = revoluteJointDef(
218
+ bodyA=self.lander,
219
+ bodyB=leg,
220
+ localAnchorA=(0, 0),
221
+ localAnchorB=(i * LEG_AWAY / SCALE, LEG_DOWN / SCALE),
222
+ enableMotor=True,
223
+ enableLimit=True,
224
+ maxMotorTorque=LEG_SPRING_TORQUE,
225
+ motorSpeed=+0.3 * i, # low enough not to jump back into the sky
226
+ )
227
+ if i == -1:
228
+ rjd.lowerAngle = (
229
+ +0.9 - 0.5
230
+ ) # The most esoteric numbers here, angled legs have freedom to travel within
231
+ rjd.upperAngle = +0.9
232
+ else:
233
+ rjd.lowerAngle = -0.9
234
+ rjd.upperAngle = -0.9 + 0.5
235
+ leg.joint = self.world.CreateJoint(rjd)
236
+ self.legs.append(leg)
237
+
238
+ self.drawlist = [self.lander] + self.legs
239
+
240
+ return self.step(np.array([0, 0]) if self.continuous else 0)[0]
241
+
242
+ def _create_particle(self, mass, x, y, ttl):
243
+ p = self.world.CreateDynamicBody(
244
+ position=(x, y),
245
+ angle=0.0,
246
+ fixtures=fixtureDef(
247
+ shape=circleShape(radius=2 / SCALE, pos=(0, 0)),
248
+ density=mass,
249
+ friction=0.1,
250
+ categoryBits=0x0100,
251
+ maskBits=0x001, # collide only with ground
252
+ restitution=0.3,
253
+ ),
254
+ )
255
+ p.ttl = ttl
256
+ self.particles.append(p)
257
+ self._clean_particles(False)
258
+ return p
259
+
260
+ def _clean_particles(self, all):
261
+ while self.particles and (all or self.particles[0].ttl < 0):
262
+ self.world.DestroyBody(self.particles.pop(0))
263
+
264
+ def step(self, action):
265
+ if self.continuous:
266
+ action = np.clip(action, -1, +1).astype(np.float32)
267
+ else:
268
+ assert self.action_space.contains(action), "%r (%s) invalid " % (
269
+ action,
270
+ type(action),
271
+ )
272
+
273
+ # Engines
274
+ tip = (math.sin(self.lander.angle), math.cos(self.lander.angle))
275
+ side = (-tip[1], tip[0])
276
+ dispersion = [self.np_random.uniform(-1.0, +1.0) / SCALE for _ in range(2)]
277
+
278
+ m_power = 0.0
279
+ if (self.continuous and action[0] > 0.0) or (
280
+ not self.continuous and action == 2
281
+ ):
282
+ # Main engine
283
+ if self.continuous:
284
+ m_power = (np.clip(action[0], 0.0, 1.0) + 1.0) * 0.5 # 0.5..1.0
285
+ assert m_power >= 0.5 and m_power <= 1.0
286
+ else:
287
+ m_power = 1.0
288
+ ox = (
289
+ tip[0] * (4 / SCALE + 2 * dispersion[0]) + side[0] * dispersion[1]
290
+ ) # 4 is move a bit downwards, +-2 for randomness
291
+ oy = -tip[1] * (4 / SCALE + 2 * dispersion[0]) - side[1] * dispersion[1]
292
+ impulse_pos = (self.lander.position[0] + ox, self.lander.position[1] + oy)
293
+ p = self._create_particle(
294
+ 3.5, # 3.5 is here to make particle speed adequate
295
+ impulse_pos[0],
296
+ impulse_pos[1],
297
+ m_power,
298
+ ) # particles are just a decoration
299
+ p.ApplyLinearImpulse(
300
+ (ox * MAIN_ENGINE_POWER * m_power, oy * MAIN_ENGINE_POWER * m_power),
301
+ impulse_pos,
302
+ True,
303
+ )
304
+ self.lander.ApplyLinearImpulse(
305
+ (-ox * MAIN_ENGINE_POWER * m_power, -oy * MAIN_ENGINE_POWER * m_power),
306
+ impulse_pos,
307
+ True,
308
+ )
309
+
310
+ s_power = 0.0
311
+ if (self.continuous and np.abs(action[1]) > 0.5) or (
312
+ not self.continuous and action in [1, 3]
313
+ ):
314
+ # Orientation engines
315
+ if self.continuous:
316
+ direction = np.sign(action[1])
317
+ s_power = np.clip(np.abs(action[1]), 0.5, 1.0)
318
+ assert s_power >= 0.5 and s_power <= 1.0
319
+ else:
320
+ direction = action - 2
321
+ s_power = 1.0
322
+ ox = tip[0] * dispersion[0] + side[0] * (
323
+ 3 * dispersion[1] + direction * SIDE_ENGINE_AWAY / SCALE
324
+ )
325
+ oy = -tip[1] * dispersion[0] - side[1] * (
326
+ 3 * dispersion[1] + direction * SIDE_ENGINE_AWAY / SCALE
327
+ )
328
+ impulse_pos = (
329
+ self.lander.position[0] + ox - tip[0] * 17 / SCALE,
330
+ self.lander.position[1] + oy + tip[1] * SIDE_ENGINE_HEIGHT / SCALE,
331
+ )
332
+ p = self._create_particle(0.7, impulse_pos[0], impulse_pos[1], s_power)
333
+ p.ApplyLinearImpulse(
334
+ (ox * SIDE_ENGINE_POWER * s_power, oy * SIDE_ENGINE_POWER * s_power),
335
+ impulse_pos,
336
+ True,
337
+ )
338
+ self.lander.ApplyLinearImpulse(
339
+ (-ox * SIDE_ENGINE_POWER * s_power, -oy * SIDE_ENGINE_POWER * s_power),
340
+ impulse_pos,
341
+ True,
342
+ )
343
+
344
+ self.world.Step(1.0 / FPS, 6 * 30, 2 * 30)
345
+
346
+ pos = self.lander.position
347
+ vel = self.lander.linearVelocity
348
+ state = [
349
+ (pos.x - VIEWPORT_W / SCALE / 2) / (VIEWPORT_W / SCALE / 2),
350
+ (pos.y - (self.helipad_y + LEG_DOWN / SCALE)) / (VIEWPORT_H / SCALE / 2),
351
+ vel.x * (VIEWPORT_W / SCALE / 2) / FPS,
352
+ vel.y * (VIEWPORT_H / SCALE / 2) / FPS,
353
+ self.lander.angle,
354
+ 20.0 * self.lander.angularVelocity / FPS,
355
+ 1.0 if self.legs[0].ground_contact else 0.0,
356
+ 1.0 if self.legs[1].ground_contact else 0.0,
357
+ ]
358
+ assert len(state) == 8
359
+
360
+ reward = 0
361
+ shaping = (
362
+ -100 * np.sqrt(state[0] * state[0] + state[1] * state[1])
363
+ - 100 * np.sqrt(state[2] * state[2] + state[3] * state[3])
364
+ - 100 * abs(state[4])
365
+ + 10 * state[6]
366
+ + 10 * state[7]
367
+ ) # And ten points for legs contact, the idea is if you
368
+ # lose contact again after landing, you get negative reward
369
+ if self.prev_shaping is not None:
370
+ reward = shaping - self.prev_shaping
371
+ self.prev_shaping = shaping
372
+
373
+ reward -= (
374
+ m_power * 0.30
375
+ ) # less fuel spent is better, about -30 for heuristic landing
376
+ reward -= s_power * 0.03
377
+
378
+ done = False
379
+ if self.game_over or abs(state[0]) >= 1.0:
380
+ done = True
381
+ reward = -100
382
+ if not self.lander.awake:
383
+ done = True
384
+ reward = +100
385
+ return np.array(state, dtype=np.float32), reward, done, {}
386
+
387
+ def render(self, mode="human"):
388
+ from gym.envs.classic_control import rendering
389
+
390
+ if self.viewer is None:
391
+ self.viewer = rendering.Viewer(VIEWPORT_W, VIEWPORT_H)
392
+ self.viewer.set_bounds(0, VIEWPORT_W / SCALE, 0, VIEWPORT_H / SCALE)
393
+
394
+ for obj in self.particles:
395
+ obj.ttl -= 0.15
396
+ obj.color1 = (
397
+ max(0.2, 0.2 + obj.ttl),
398
+ max(0.2, 0.5 * obj.ttl),
399
+ max(0.2, 0.5 * obj.ttl),
400
+ )
401
+ obj.color2 = (
402
+ max(0.2, 0.2 + obj.ttl),
403
+ max(0.2, 0.5 * obj.ttl),
404
+ max(0.2, 0.5 * obj.ttl),
405
+ )
406
+
407
+ self._clean_particles(False)
408
+
409
+ for p in self.sky_polys:
410
+ self.viewer.draw_polygon(p, color=(0, 0, 0))
411
+
412
+ for obj in self.particles + self.drawlist:
413
+ for f in obj.fixtures:
414
+ trans = f.body.transform
415
+ if type(f.shape) is circleShape:
416
+ t = rendering.Transform(translation=trans * f.shape.pos)
417
+ self.viewer.draw_circle(
418
+ f.shape.radius, 20, color=obj.color1
419
+ ).add_attr(t)
420
+ self.viewer.draw_circle(
421
+ f.shape.radius, 20, color=obj.color2, filled=False, linewidth=2
422
+ ).add_attr(t)
423
+ else:
424
+ path = [trans * v for v in f.shape.vertices]
425
+ self.viewer.draw_polygon(path, color=obj.color1)
426
+ path.append(path[0])
427
+ self.viewer.draw_polyline(path, color=obj.color2, linewidth=2)
428
+
429
+ for x in [self.helipad_x1, self.helipad_x2]:
430
+ flagy1 = self.helipad_y
431
+ flagy2 = flagy1 + 50 / SCALE
432
+ self.viewer.draw_polyline([(x, flagy1), (x, flagy2)], color=(1, 1, 1))
433
+ self.viewer.draw_polygon(
434
+ [
435
+ (x, flagy2),
436
+ (x, flagy2 - 10 / SCALE),
437
+ (x + 25 / SCALE, flagy2 - 5 / SCALE),
438
+ ],
439
+ color=(0.8, 0.8, 0),
440
+ )
441
+
442
+ return self.viewer.render(return_rgb_array=mode == "rgb_array")
443
+
444
+ def close(self):
445
+ if self.viewer is not None:
446
+ self.viewer.close()
447
+ self.viewer = None
448
+
449
+
450
+ class LunarLanderContinuous(LunarLander):
451
+ continuous = True
452
+
453
+
454
+ def heuristic(env, s):
455
+ """
456
+ The heuristic for
457
+ 1. Testing
458
+ 2. Demonstration rollout.
459
+
460
+ Args:
461
+ env: The environment
462
+ s (list): The state. Attributes:
463
+ s[0] is the horizontal coordinate
464
+ s[1] is the vertical coordinate
465
+ s[2] is the horizontal speed
466
+ s[3] is the vertical speed
467
+ s[4] is the angle
468
+ s[5] is the angular speed
469
+ s[6] 1 if first leg has contact, else 0
470
+ s[7] 1 if second leg has contact, else 0
471
+ returns:
472
+ a: The heuristic to be fed into the step function defined above to determine the next step and reward.
473
+ """
474
+
475
+ angle_targ = s[0] * 0.5 + s[2] * 1.0 # angle should point towards center
476
+ if angle_targ > 0.4:
477
+ angle_targ = 0.4 # more than 0.4 radians (22 degrees) is bad
478
+ if angle_targ < -0.4:
479
+ angle_targ = -0.4
480
+ hover_targ = 0.55 * np.abs(
481
+ s[0]
482
+ ) # target y should be proportional to horizontal offset
483
+
484
+ angle_todo = (angle_targ - s[4]) * 0.5 - (s[5]) * 1.0
485
+ hover_todo = (hover_targ - s[1]) * 0.5 - (s[3]) * 0.5
486
+
487
+ if s[6] or s[7]: # legs have contact
488
+ angle_todo = 0
489
+ hover_todo = (
490
+ -(s[3]) * 0.5
491
+ ) # override to reduce fall speed, that's all we need after contact
492
+
493
+ if env.continuous:
494
+ a = np.array([hover_todo * 20 - 1, -angle_todo * 20])
495
+ a = np.clip(a, -1, +1)
496
+ else:
497
+ a = 0
498
+ if hover_todo > np.abs(angle_todo) and hover_todo > 0.05:
499
+ a = 2
500
+ elif angle_todo < -0.05:
501
+ a = 3
502
+ elif angle_todo > +0.05:
503
+ a = 1
504
+ return a
505
+
506
+
507
+ def demo_heuristic_lander(env, seed=None, render=False):
508
+ env.seed(seed)
509
+ total_reward = 0
510
+ steps = 0
511
+ s = env.reset()
512
+ while True:
513
+ a = heuristic(env, s)
514
+ s, r, done, info = env.step(a)
515
+ total_reward += r
516
+
517
+ if render:
518
+ still_open = env.render()
519
+ if still_open == False:
520
+ break
521
+
522
+ if steps % 20 == 0 or done:
523
+ print("observations:", " ".join(["{:+0.2f}".format(x) for x in s]))
524
+ print("step {} total_reward {:+0.2f}".format(steps, total_reward))
525
+ steps += 1
526
+ if done:
527
+ break
528
+ if render:
529
+ env.close()
530
+ return total_reward
531
+
532
+
533
+ if __name__ == "__main__":
534
+ demo_heuristic_lander(LunarLander(), render=True)
gym/envs/classic_control/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from gym.envs.classic_control.cartpole import CartPoleEnv
2
+ from gym.envs.classic_control.mountain_car import MountainCarEnv
3
+ from gym.envs.classic_control.continuous_mountain_car import Continuous_MountainCarEnv
4
+ from gym.envs.classic_control.pendulum import PendulumEnv
5
+ from gym.envs.classic_control.acrobot import AcrobotEnv
gym/envs/classic_control/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (549 Bytes). View file
 
gym/envs/classic_control/__pycache__/acrobot.cpython-39.pyc ADDED
Binary file (9.76 kB). View file
 
gym/envs/classic_control/__pycache__/cartpole.cpython-39.pyc ADDED
Binary file (6.42 kB). View file
 
gym/envs/classic_control/__pycache__/continuous_mountain_car.cpython-39.pyc ADDED
Binary file (5.76 kB). View file
 
gym/envs/classic_control/__pycache__/mountain_car.cpython-39.pyc ADDED
Binary file (5.5 kB). View file
 
gym/envs/classic_control/__pycache__/pendulum.cpython-39.pyc ADDED
Binary file (3.38 kB). View file
 
gym/envs/classic_control/__pycache__/rendering.cpython-39.pyc ADDED
Binary file (15.8 kB). View file
 
gym/envs/classic_control/acrobot.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """classic Acrobot task"""
2
+ import numpy as np
3
+ from numpy import sin, cos, pi
4
+
5
+ from gym import core, spaces
6
+ from gym.utils import seeding
7
+
8
+ __copyright__ = "Copyright 2013, RLPy http://acl.mit.edu/RLPy"
9
+ __credits__ = [
10
+ "Alborz Geramifard",
11
+ "Robert H. Klein",
12
+ "Christoph Dann",
13
+ "William Dabney",
14
+ "Jonathan P. How",
15
+ ]
16
+ __license__ = "BSD 3-Clause"
17
+ __author__ = "Christoph Dann <cdann@cdann.de>"
18
+
19
+ # SOURCE:
20
+ # https://github.com/rlpy/rlpy/blob/master/rlpy/Domains/Acrobot.py
21
+
22
+
23
+ class AcrobotEnv(core.Env):
24
+
25
+ """
26
+ Acrobot is a 2-link pendulum with only the second joint actuated.
27
+ Initially, both links point downwards. The goal is to swing the
28
+ end-effector at a height at least the length of one link above the base.
29
+ Both links can swing freely and can pass by each other, i.e., they don't
30
+ collide when they have the same angle.
31
+ **STATE:**
32
+ The state consists of the sin() and cos() of the two rotational joint
33
+ angles and the joint angular velocities :
34
+ [cos(theta1) sin(theta1) cos(theta2) sin(theta2) thetaDot1 thetaDot2].
35
+ For the first link, an angle of 0 corresponds to the link pointing downwards.
36
+ The angle of the second link is relative to the angle of the first link.
37
+ An angle of 0 corresponds to having the same angle between the two links.
38
+ A state of [1, 0, 1, 0, ..., ...] means that both links point downwards.
39
+ **ACTIONS:**
40
+ The action is either applying +1, 0 or -1 torque on the joint between
41
+ the two pendulum links.
42
+ .. note::
43
+ The dynamics equations were missing some terms in the NIPS paper which
44
+ are present in the book. R. Sutton confirmed in personal correspondence
45
+ that the experimental results shown in the paper and the book were
46
+ generated with the equations shown in the book.
47
+ However, there is the option to run the domain with the paper equations
48
+ by setting book_or_nips = 'nips'
49
+ **REFERENCE:**
50
+ .. seealso::
51
+ R. Sutton: Generalization in Reinforcement Learning:
52
+ Successful Examples Using Sparse Coarse Coding (NIPS 1996)
53
+ .. seealso::
54
+ R. Sutton and A. G. Barto:
55
+ Reinforcement learning: An introduction.
56
+ Cambridge: MIT press, 1998.
57
+ .. warning::
58
+ This version of the domain uses the Runge-Kutta method for integrating
59
+ the system dynamics and is more realistic, but also considerably harder
60
+ than the original version which employs Euler integration,
61
+ see the AcrobotLegacy class.
62
+ """
63
+
64
+ metadata = {"render.modes": ["human", "rgb_array"], "video.frames_per_second": 15}
65
+
66
+ dt = 0.2
67
+
68
+ LINK_LENGTH_1 = 1.0 # [m]
69
+ LINK_LENGTH_2 = 1.0 # [m]
70
+ LINK_MASS_1 = 1.0 #: [kg] mass of link 1
71
+ LINK_MASS_2 = 1.0 #: [kg] mass of link 2
72
+ LINK_COM_POS_1 = 0.5 #: [m] position of the center of mass of link 1
73
+ LINK_COM_POS_2 = 0.5 #: [m] position of the center of mass of link 2
74
+ LINK_MOI = 1.0 #: moments of inertia for both links
75
+
76
+ MAX_VEL_1 = 4 * pi
77
+ MAX_VEL_2 = 9 * pi
78
+
79
+ AVAIL_TORQUE = [-1.0, 0.0, +1]
80
+
81
+ torque_noise_max = 0.0
82
+
83
+ #: use dynamics equations from the nips paper or the book
84
+ book_or_nips = "book"
85
+ action_arrow = None
86
+ domain_fig = None
87
+ actions_num = 3
88
+
89
+ def __init__(self):
90
+ self.viewer = None
91
+ high = np.array(
92
+ [1.0, 1.0, 1.0, 1.0, self.MAX_VEL_1, self.MAX_VEL_2], dtype=np.float32
93
+ )
94
+ low = -high
95
+ self.observation_space = spaces.Box(low=low, high=high, dtype=np.float32)
96
+ self.action_space = spaces.Discrete(3)
97
+ self.state = None
98
+ self.seed()
99
+
100
+ def seed(self, seed=None):
101
+ self.np_random, seed = seeding.np_random(seed)
102
+ return [seed]
103
+
104
+ def reset(self):
105
+ self.state = self.np_random.uniform(low=-0.1, high=0.1, size=(4,)).astype(
106
+ np.float32
107
+ )
108
+ return self._get_ob()
109
+
110
+ def step(self, a):
111
+ s = self.state
112
+ torque = self.AVAIL_TORQUE[a]
113
+
114
+ # Add noise to the force action
115
+ if self.torque_noise_max > 0:
116
+ torque += self.np_random.uniform(
117
+ -self.torque_noise_max, self.torque_noise_max
118
+ )
119
+
120
+ # Now, augment the state with our force action so it can be passed to
121
+ # _dsdt
122
+ s_augmented = np.append(s, torque)
123
+
124
+ ns = rk4(self._dsdt, s_augmented, [0, self.dt])
125
+
126
+ ns[0] = wrap(ns[0], -pi, pi)
127
+ ns[1] = wrap(ns[1], -pi, pi)
128
+ ns[2] = bound(ns[2], -self.MAX_VEL_1, self.MAX_VEL_1)
129
+ ns[3] = bound(ns[3], -self.MAX_VEL_2, self.MAX_VEL_2)
130
+ self.state = ns
131
+ terminal = self._terminal()
132
+ reward = -1.0 if not terminal else 0.0
133
+ return (self._get_ob(), reward, terminal, {})
134
+
135
+ def _get_ob(self):
136
+ s = self.state
137
+ return np.array(
138
+ [cos(s[0]), sin(s[0]), cos(s[1]), sin(s[1]), s[2], s[3]], dtype=np.float32
139
+ )
140
+
141
+ def _terminal(self):
142
+ s = self.state
143
+ return bool(-cos(s[0]) - cos(s[1] + s[0]) > 1.0)
144
+
145
+ def _dsdt(self, s_augmented):
146
+ m1 = self.LINK_MASS_1
147
+ m2 = self.LINK_MASS_2
148
+ l1 = self.LINK_LENGTH_1
149
+ lc1 = self.LINK_COM_POS_1
150
+ lc2 = self.LINK_COM_POS_2
151
+ I1 = self.LINK_MOI
152
+ I2 = self.LINK_MOI
153
+ g = 9.8
154
+ a = s_augmented[-1]
155
+ s = s_augmented[:-1]
156
+ theta1 = s[0]
157
+ theta2 = s[1]
158
+ dtheta1 = s[2]
159
+ dtheta2 = s[3]
160
+ d1 = (
161
+ m1 * lc1 ** 2
162
+ + m2 * (l1 ** 2 + lc2 ** 2 + 2 * l1 * lc2 * cos(theta2))
163
+ + I1
164
+ + I2
165
+ )
166
+ d2 = m2 * (lc2 ** 2 + l1 * lc2 * cos(theta2)) + I2
167
+ phi2 = m2 * lc2 * g * cos(theta1 + theta2 - pi / 2.0)
168
+ phi1 = (
169
+ -m2 * l1 * lc2 * dtheta2 ** 2 * sin(theta2)
170
+ - 2 * m2 * l1 * lc2 * dtheta2 * dtheta1 * sin(theta2)
171
+ + (m1 * lc1 + m2 * l1) * g * cos(theta1 - pi / 2)
172
+ + phi2
173
+ )
174
+ if self.book_or_nips == "nips":
175
+ # the following line is consistent with the description in the
176
+ # paper
177
+ ddtheta2 = (a + d2 / d1 * phi1 - phi2) / (m2 * lc2 ** 2 + I2 - d2 ** 2 / d1)
178
+ else:
179
+ # the following line is consistent with the java implementation and the
180
+ # book
181
+ ddtheta2 = (
182
+ a + d2 / d1 * phi1 - m2 * l1 * lc2 * dtheta1 ** 2 * sin(theta2) - phi2
183
+ ) / (m2 * lc2 ** 2 + I2 - d2 ** 2 / d1)
184
+ ddtheta1 = -(d2 * ddtheta2 + phi1) / d1
185
+ return (dtheta1, dtheta2, ddtheta1, ddtheta2, 0.0)
186
+
187
+ def render(self, mode="human"):
188
+ from gym.envs.classic_control import rendering
189
+
190
+ s = self.state
191
+
192
+ if self.viewer is None:
193
+ self.viewer = rendering.Viewer(500, 500)
194
+ bound = self.LINK_LENGTH_1 + self.LINK_LENGTH_2 + 0.2 # 2.2 for default
195
+ self.viewer.set_bounds(-bound, bound, -bound, bound)
196
+
197
+ if s is None:
198
+ return None
199
+
200
+ p1 = [-self.LINK_LENGTH_1 * cos(s[0]), self.LINK_LENGTH_1 * sin(s[0])]
201
+
202
+ p2 = [
203
+ p1[0] - self.LINK_LENGTH_2 * cos(s[0] + s[1]),
204
+ p1[1] + self.LINK_LENGTH_2 * sin(s[0] + s[1]),
205
+ ]
206
+
207
+ xys = np.array([[0, 0], p1, p2])[:, ::-1]
208
+ thetas = [s[0] - pi / 2, s[0] + s[1] - pi / 2]
209
+ link_lengths = [self.LINK_LENGTH_1, self.LINK_LENGTH_2]
210
+
211
+ self.viewer.draw_line((-2.2, 1), (2.2, 1))
212
+ for ((x, y), th, llen) in zip(xys, thetas, link_lengths):
213
+ l, r, t, b = 0, llen, 0.1, -0.1
214
+ jtransform = rendering.Transform(rotation=th, translation=(x, y))
215
+ link = self.viewer.draw_polygon([(l, b), (l, t), (r, t), (r, b)])
216
+ link.add_attr(jtransform)
217
+ link.set_color(0, 0.8, 0.8)
218
+ circ = self.viewer.draw_circle(0.1)
219
+ circ.set_color(0.8, 0.8, 0)
220
+ circ.add_attr(jtransform)
221
+
222
+ return self.viewer.render(return_rgb_array=mode == "rgb_array")
223
+
224
+ def close(self):
225
+ if self.viewer:
226
+ self.viewer.close()
227
+ self.viewer = None
228
+
229
+
230
+ def wrap(x, m, M):
231
+ """Wraps ``x`` so m <= x <= M; but unlike ``bound()`` which
232
+ truncates, ``wrap()`` wraps x around the coordinate system defined by m,M.\n
233
+ For example, m = -180, M = 180 (degrees), x = 360 --> returns 0.
234
+
235
+ Args:
236
+ x: a scalar
237
+ m: minimum possible value in range
238
+ M: maximum possible value in range
239
+
240
+ Returns:
241
+ x: a scalar, wrapped
242
+ """
243
+ diff = M - m
244
+ while x > M:
245
+ x = x - diff
246
+ while x < m:
247
+ x = x + diff
248
+ return x
249
+
250
+
251
+ def bound(x, m, M=None):
252
+ """Either have m as scalar, so bound(x,m,M) which returns m <= x <= M *OR*
253
+ have m as length 2 vector, bound(x,m, <IGNORED>) returns m[0] <= x <= m[1].
254
+
255
+ Args:
256
+ x: scalar
257
+
258
+ Returns:
259
+ x: scalar, bound between min (m) and Max (M)
260
+ """
261
+ if M is None:
262
+ M = m[1]
263
+ m = m[0]
264
+ # bound x between min (m) and Max (M)
265
+ return min(max(x, m), M)
266
+
267
+
268
+ def rk4(derivs, y0, t):
269
+ """
270
+ Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta.
271
+ This is a toy implementation which may be useful if you find
272
+ yourself stranded on a system w/o scipy. Otherwise use
273
+ :func:`scipy.integrate`.
274
+
275
+ Args:
276
+ derivs: the derivative of the system and has the signature ``dy = derivs(yi)``
277
+ y0: initial state vector
278
+ t: sample times
279
+ args: additional arguments passed to the derivative function
280
+ kwargs: additional keyword arguments passed to the derivative function
281
+
282
+ Example 1 ::
283
+ ## 2D system
284
+ def derivs(x):
285
+ d1 = x[0] + 2*x[1]
286
+ d2 = -3*x[0] + 4*x[1]
287
+ return (d1, d2)
288
+ dt = 0.0005
289
+ t = arange(0.0, 2.0, dt)
290
+ y0 = (1,2)
291
+ yout = rk4(derivs6, y0, t)
292
+
293
+ If you have access to scipy, you should probably be using the
294
+ scipy.integrate tools rather than this function.
295
+ This would then require re-adding the time variable to the signature of derivs.
296
+
297
+ Returns:
298
+ yout: Runge-Kutta approximation of the ODE
299
+ """
300
+
301
+ try:
302
+ Ny = len(y0)
303
+ except TypeError:
304
+ yout = np.zeros((len(t),), np.float_)
305
+ else:
306
+ yout = np.zeros((len(t), Ny), np.float_)
307
+
308
+ yout[0] = y0
309
+
310
+ for i in np.arange(len(t) - 1):
311
+
312
+ thist = t[i]
313
+ dt = t[i + 1] - thist
314
+ dt2 = dt / 2.0
315
+ y0 = yout[i]
316
+
317
+ k1 = np.asarray(derivs(y0))
318
+ k2 = np.asarray(derivs(y0 + dt2 * k1))
319
+ k3 = np.asarray(derivs(y0 + dt2 * k2))
320
+ k4 = np.asarray(derivs(y0 + dt * k3))
321
+ yout[i + 1] = y0 + dt / 6.0 * (k1 + 2 * k2 + 2 * k3 + k4)
322
+ # We only care about the final timestep and we cleave off action value which will be zero
323
+ return yout[-1][:4]
gym/envs/classic_control/assets/clockwise.png ADDED
gym/envs/classic_control/cartpole.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Classic cart-pole system implemented by Rich Sutton et al.
3
+ Copied from http://incompleteideas.net/sutton/book/code/pole.c
4
+ permalink: https://perma.cc/C9ZM-652R
5
+ """
6
+
7
+ import math
8
+ import gym
9
+ from gym import spaces, logger
10
+ from gym.utils import seeding
11
+ import numpy as np
12
+
13
+
14
+ class CartPoleEnv(gym.Env):
15
+ """
16
+ Description:
17
+ A pole is attached by an un-actuated joint to a cart, which moves along
18
+ a frictionless track. The pendulum starts upright, and the goal is to
19
+ prevent it from falling over by increasing and reducing the cart's
20
+ velocity.
21
+
22
+ Source:
23
+ This environment corresponds to the version of the cart-pole problem
24
+ described by Barto, Sutton, and Anderson
25
+
26
+ Observation:
27
+ Type: Box(4)
28
+ Num Observation Min Max
29
+ 0 Cart Position -4.8 4.8
30
+ 1 Cart Velocity -Inf Inf
31
+ 2 Pole Angle -0.418 rad (-24 deg) 0.418 rad (24 deg)
32
+ 3 Pole Angular Velocity -Inf Inf
33
+
34
+ Actions:
35
+ Type: Discrete(2)
36
+ Num Action
37
+ 0 Push cart to the left
38
+ 1 Push cart to the right
39
+
40
+ Note: The amount the velocity that is reduced or increased is not
41
+ fixed; it depends on the angle the pole is pointing. This is because
42
+ the center of gravity of the pole increases the amount of energy needed
43
+ to move the cart underneath it
44
+
45
+ Reward:
46
+ Reward is 1 for every step taken, including the termination step
47
+
48
+ Starting State:
49
+ All observations are assigned a uniform random value in [-0.05..0.05]
50
+
51
+ Episode Termination:
52
+ Pole Angle is more than 12 degrees.
53
+ Cart Position is more than 2.4 (center of the cart reaches the edge of
54
+ the display).
55
+ Episode length is greater than 200.
56
+ Solved Requirements:
57
+ Considered solved when the average return is greater than or equal to
58
+ 195.0 over 100 consecutive trials.
59
+ """
60
+
61
+ metadata = {"render.modes": ["human", "rgb_array"], "video.frames_per_second": 50}
62
+
63
+ def __init__(self):
64
+ self.gravity = 9.8
65
+ self.masscart = 1.0
66
+ self.masspole = 0.1
67
+ self.total_mass = self.masspole + self.masscart
68
+ self.length = 0.5 # actually half the pole's length
69
+ self.polemass_length = self.masspole * self.length
70
+ self.force_mag = 10.0
71
+ self.tau = 0.02 # seconds between state updates
72
+ self.kinematics_integrator = "euler"
73
+
74
+ # Angle at which to fail the episode
75
+ self.theta_threshold_radians = 12 * 2 * math.pi / 360
76
+ self.x_threshold = 2.4
77
+
78
+ # Angle limit set to 2 * theta_threshold_radians so failing observation
79
+ # is still within bounds.
80
+ high = np.array(
81
+ [
82
+ self.x_threshold * 2,
83
+ np.finfo(np.float32).max,
84
+ self.theta_threshold_radians * 2,
85
+ np.finfo(np.float32).max,
86
+ ],
87
+ dtype=np.float32,
88
+ )
89
+
90
+ self.action_space = spaces.Discrete(2)
91
+ self.observation_space = spaces.Box(-high, high, dtype=np.float32)
92
+
93
+ self.seed()
94
+ self.viewer = None
95
+ self.state = None
96
+
97
+ self.steps_beyond_done = None
98
+
99
+ def seed(self, seed=None):
100
+ self.np_random, seed = seeding.np_random(seed)
101
+ return [seed]
102
+
103
+ def step(self, action):
104
+ err_msg = "%r (%s) invalid" % (action, type(action))
105
+ assert self.action_space.contains(action), err_msg
106
+
107
+ x, x_dot, theta, theta_dot = self.state
108
+ force = self.force_mag if action == 1 else -self.force_mag
109
+ costheta = math.cos(theta)
110
+ sintheta = math.sin(theta)
111
+
112
+ # For the interested reader:
113
+ # https://coneural.org/florian/papers/05_cart_pole.pdf
114
+ temp = (
115
+ force + self.polemass_length * theta_dot ** 2 * sintheta
116
+ ) / self.total_mass
117
+ thetaacc = (self.gravity * sintheta - costheta * temp) / (
118
+ self.length * (4.0 / 3.0 - self.masspole * costheta ** 2 / self.total_mass)
119
+ )
120
+ xacc = temp - self.polemass_length * thetaacc * costheta / self.total_mass
121
+
122
+ if self.kinematics_integrator == "euler":
123
+ x = x + self.tau * x_dot
124
+ x_dot = x_dot + self.tau * xacc
125
+ theta = theta + self.tau * theta_dot
126
+ theta_dot = theta_dot + self.tau * thetaacc
127
+ else: # semi-implicit euler
128
+ x_dot = x_dot + self.tau * xacc
129
+ x = x + self.tau * x_dot
130
+ theta_dot = theta_dot + self.tau * thetaacc
131
+ theta = theta + self.tau * theta_dot
132
+
133
+ self.state = (x, x_dot, theta, theta_dot)
134
+
135
+ done = bool(
136
+ x < -self.x_threshold
137
+ or x > self.x_threshold
138
+ or theta < -self.theta_threshold_radians
139
+ or theta > self.theta_threshold_radians
140
+ )
141
+
142
+ if not done:
143
+ reward = 1.0
144
+ elif self.steps_beyond_done is None:
145
+ # Pole just fell!
146
+ self.steps_beyond_done = 0
147
+ reward = 1.0
148
+ else:
149
+ if self.steps_beyond_done == 0:
150
+ logger.warn(
151
+ "You are calling 'step()' even though this "
152
+ "environment has already returned done = True. You "
153
+ "should always call 'reset()' once you receive 'done = "
154
+ "True' -- any further steps are undefined behavior."
155
+ )
156
+ self.steps_beyond_done += 1
157
+ reward = 0.0
158
+
159
+ return np.array(self.state, dtype=np.float32), reward, done, {}
160
+
161
+ def reset(self):
162
+ self.state = self.np_random.uniform(low=-0.05, high=0.05, size=(4,))
163
+ self.steps_beyond_done = None
164
+ return np.array(self.state, dtype=np.float32)
165
+
166
+ def render(self, mode="human"):
167
+ screen_width = 600
168
+ screen_height = 400
169
+
170
+ world_width = self.x_threshold * 2
171
+ scale = screen_width / world_width
172
+ carty = 100 # TOP OF CART
173
+ polewidth = 10.0
174
+ polelen = scale * (2 * self.length)
175
+ cartwidth = 50.0
176
+ cartheight = 30.0
177
+
178
+ if self.viewer is None:
179
+ from gym.envs.classic_control import rendering
180
+
181
+ self.viewer = rendering.Viewer(screen_width, screen_height)
182
+ l, r, t, b = -cartwidth / 2, cartwidth / 2, cartheight / 2, -cartheight / 2
183
+ axleoffset = cartheight / 4.0
184
+ cart = rendering.FilledPolygon([(l, b), (l, t), (r, t), (r, b)])
185
+ self.carttrans = rendering.Transform()
186
+ cart.add_attr(self.carttrans)
187
+ self.viewer.add_geom(cart)
188
+ l, r, t, b = (
189
+ -polewidth / 2,
190
+ polewidth / 2,
191
+ polelen - polewidth / 2,
192
+ -polewidth / 2,
193
+ )
194
+ pole = rendering.FilledPolygon([(l, b), (l, t), (r, t), (r, b)])
195
+ pole.set_color(0.8, 0.6, 0.4)
196
+ self.poletrans = rendering.Transform(translation=(0, axleoffset))
197
+ pole.add_attr(self.poletrans)
198
+ pole.add_attr(self.carttrans)
199
+ self.viewer.add_geom(pole)
200
+ self.axle = rendering.make_circle(polewidth / 2)
201
+ self.axle.add_attr(self.poletrans)
202
+ self.axle.add_attr(self.carttrans)
203
+ self.axle.set_color(0.5, 0.5, 0.8)
204
+ self.viewer.add_geom(self.axle)
205
+ self.track = rendering.Line((0, carty), (screen_width, carty))
206
+ self.track.set_color(0, 0, 0)
207
+ self.viewer.add_geom(self.track)
208
+
209
+ self._pole_geom = pole
210
+
211
+ if self.state is None:
212
+ return None
213
+
214
+ # Edit the pole polygon vertex
215
+ pole = self._pole_geom
216
+ l, r, t, b = (
217
+ -polewidth / 2,
218
+ polewidth / 2,
219
+ polelen - polewidth / 2,
220
+ -polewidth / 2,
221
+ )
222
+ pole.v = [(l, b), (l, t), (r, t), (r, b)]
223
+
224
+ x = self.state
225
+ cartx = x[0] * scale + screen_width / 2.0 # MIDDLE OF CART
226
+ self.carttrans.set_translation(cartx, carty)
227
+ self.poletrans.set_rotation(-x[2])
228
+
229
+ return self.viewer.render(return_rgb_array=mode == "rgb_array")
230
+
231
+ def close(self):
232
+ if self.viewer:
233
+ self.viewer.close()
234
+ self.viewer = None
gym/envs/classic_control/continuous_mountain_car.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ @author: Olivier Sigaud
4
+
5
+ A merge between two sources:
6
+
7
+ * Adaptation of the MountainCar Environment from the "FAReinforcement" library
8
+ of Jose Antonio Martin H. (version 1.0), adapted by 'Tom Schaul, tom@idsia.ch'
9
+ and then modified by Arnaud de Broissia
10
+
11
+ * the OpenAI/gym MountainCar environment
12
+ itself from
13
+ http://incompleteideas.net/sutton/MountainCar/MountainCar1.cp
14
+ permalink: https://perma.cc/6Z2N-PFWC
15
+ """
16
+
17
+ import math
18
+
19
+ import numpy as np
20
+
21
+ import gym
22
+ from gym import spaces
23
+ from gym.utils import seeding
24
+
25
+
26
+ class Continuous_MountainCarEnv(gym.Env):
27
+ """
28
+ Description:
29
+ The agent (a car) is started at the bottom of a valley. For any given
30
+ state the agent may choose to accelerate to the left, right or cease
31
+ any acceleration.
32
+ Observation:
33
+ Type: Box(2)
34
+ Num Observation Min Max
35
+ 0 Car Position -1.2 0.6
36
+ 1 Car Velocity -0.07 0.07
37
+ Actions:
38
+ Type: Box(1)
39
+ Num Action Min Max
40
+ 0 the power coef -1.0 1.0
41
+ Note: actual driving force is calculated by multipling the power coef by power (0.0015)
42
+
43
+ Reward:
44
+ Reward of 100 is awarded if the agent reached the flag (position = 0.45) on top of the mountain.
45
+ Reward is decrease based on amount of energy consumed each step.
46
+
47
+ Starting State:
48
+ The position of the car is assigned a uniform random value in
49
+ [-0.6 , -0.4].
50
+ The starting velocity of the car is always assigned to 0.
51
+
52
+ Episode Termination:
53
+ The car position is more than 0.45
54
+ Episode length is greater than 200
55
+ """
56
+
57
+ metadata = {"render.modes": ["human", "rgb_array"], "video.frames_per_second": 30}
58
+
59
+ def __init__(self, goal_velocity=0):
60
+ self.min_action = -1.0
61
+ self.max_action = 1.0
62
+ self.min_position = -1.2
63
+ self.max_position = 0.6
64
+ self.max_speed = 0.07
65
+ self.goal_position = (
66
+ 0.45 # was 0.5 in gym, 0.45 in Arnaud de Broissia's version
67
+ )
68
+ self.goal_velocity = goal_velocity
69
+ self.power = 0.0015
70
+
71
+ self.low_state = np.array(
72
+ [self.min_position, -self.max_speed], dtype=np.float32
73
+ )
74
+ self.high_state = np.array(
75
+ [self.max_position, self.max_speed], dtype=np.float32
76
+ )
77
+
78
+ self.viewer = None
79
+
80
+ self.action_space = spaces.Box(
81
+ low=self.min_action, high=self.max_action, shape=(1,), dtype=np.float32
82
+ )
83
+ self.observation_space = spaces.Box(
84
+ low=self.low_state, high=self.high_state, dtype=np.float32
85
+ )
86
+
87
+ self.seed()
88
+
89
+ def seed(self, seed=None):
90
+ self.np_random, seed = seeding.np_random(seed)
91
+ return [seed]
92
+
93
+ def step(self, action):
94
+
95
+ position = self.state[0]
96
+ velocity = self.state[1]
97
+ force = min(max(action[0], self.min_action), self.max_action)
98
+
99
+ velocity += force * self.power - 0.0025 * math.cos(3 * position)
100
+ if velocity > self.max_speed:
101
+ velocity = self.max_speed
102
+ if velocity < -self.max_speed:
103
+ velocity = -self.max_speed
104
+ position += velocity
105
+ if position > self.max_position:
106
+ position = self.max_position
107
+ if position < self.min_position:
108
+ position = self.min_position
109
+ if position == self.min_position and velocity < 0:
110
+ velocity = 0
111
+
112
+ # Convert a possible numpy bool to a Python bool.
113
+ done = bool(position >= self.goal_position and velocity >= self.goal_velocity)
114
+
115
+ reward = 0
116
+ if done:
117
+ reward = 100.0
118
+ reward -= math.pow(action[0], 2) * 0.1
119
+
120
+ self.state = np.array([position, velocity], dtype=np.float32)
121
+ return self.state, reward, done, {}
122
+
123
+ def reset(self):
124
+ self.state = np.array([self.np_random.uniform(low=-0.6, high=-0.4), 0])
125
+ return np.array(self.state, dtype=np.float32)
126
+
127
+ def _height(self, xs):
128
+ return np.sin(3 * xs) * 0.45 + 0.55
129
+
130
+ def render(self, mode="human"):
131
+ screen_width = 600
132
+ screen_height = 400
133
+
134
+ world_width = self.max_position - self.min_position
135
+ scale = screen_width / world_width
136
+ carwidth = 40
137
+ carheight = 20
138
+
139
+ if self.viewer is None:
140
+ from gym.envs.classic_control import rendering
141
+
142
+ self.viewer = rendering.Viewer(screen_width, screen_height)
143
+ xs = np.linspace(self.min_position, self.max_position, 100)
144
+ ys = self._height(xs)
145
+ xys = list(zip((xs - self.min_position) * scale, ys * scale))
146
+
147
+ self.track = rendering.make_polyline(xys)
148
+ self.track.set_linewidth(4)
149
+ self.viewer.add_geom(self.track)
150
+
151
+ clearance = 10
152
+
153
+ l, r, t, b = -carwidth / 2, carwidth / 2, carheight, 0
154
+ car = rendering.FilledPolygon([(l, b), (l, t), (r, t), (r, b)])
155
+ car.add_attr(rendering.Transform(translation=(0, clearance)))
156
+ self.cartrans = rendering.Transform()
157
+ car.add_attr(self.cartrans)
158
+ self.viewer.add_geom(car)
159
+ frontwheel = rendering.make_circle(carheight / 2.5)
160
+ frontwheel.set_color(0.5, 0.5, 0.5)
161
+ frontwheel.add_attr(
162
+ rendering.Transform(translation=(carwidth / 4, clearance))
163
+ )
164
+ frontwheel.add_attr(self.cartrans)
165
+ self.viewer.add_geom(frontwheel)
166
+ backwheel = rendering.make_circle(carheight / 2.5)
167
+ backwheel.add_attr(
168
+ rendering.Transform(translation=(-carwidth / 4, clearance))
169
+ )
170
+ backwheel.add_attr(self.cartrans)
171
+ backwheel.set_color(0.5, 0.5, 0.5)
172
+ self.viewer.add_geom(backwheel)
173
+ flagx = (self.goal_position - self.min_position) * scale
174
+ flagy1 = self._height(self.goal_position) * scale
175
+ flagy2 = flagy1 + 50
176
+ flagpole = rendering.Line((flagx, flagy1), (flagx, flagy2))
177
+ self.viewer.add_geom(flagpole)
178
+ flag = rendering.FilledPolygon(
179
+ [(flagx, flagy2), (flagx, flagy2 - 10), (flagx + 25, flagy2 - 5)]
180
+ )
181
+ flag.set_color(0.8, 0.8, 0)
182
+ self.viewer.add_geom(flag)
183
+
184
+ pos = self.state[0]
185
+ self.cartrans.set_translation(
186
+ (pos - self.min_position) * scale, self._height(pos) * scale
187
+ )
188
+ self.cartrans.set_rotation(math.cos(3 * pos))
189
+
190
+ return self.viewer.render(return_rgb_array=mode == "rgb_array")
191
+
192
+ def close(self):
193
+ if self.viewer:
194
+ self.viewer.close()
195
+ self.viewer = None
gym/envs/classic_control/mountain_car.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ http://incompleteideas.net/MountainCar/MountainCar1.cp
3
+ permalink: https://perma.cc/6Z2N-PFWC
4
+ """
5
+ import math
6
+
7
+ import numpy as np
8
+
9
+ import gym
10
+ from gym import spaces
11
+ from gym.utils import seeding
12
+
13
+
14
+ class MountainCarEnv(gym.Env):
15
+ """
16
+ Description:
17
+ The agent (a car) is started at the bottom of a valley. For any given
18
+ state the agent may choose to accelerate to the left, right or cease
19
+ any acceleration.
20
+
21
+ Source:
22
+ The environment appeared first in Andrew Moore's PhD Thesis (1990).
23
+
24
+ Observation:
25
+ Type: Box(2)
26
+ Num Observation Min Max
27
+ 0 Car Position -1.2 0.6
28
+ 1 Car Velocity -0.07 0.07
29
+
30
+ Actions:
31
+ Type: Discrete(3)
32
+ Num Action
33
+ 0 Accelerate to the Left
34
+ 1 Don't accelerate
35
+ 2 Accelerate to the Right
36
+
37
+ Note: This does not affect the amount of velocity affected by the
38
+ gravitational pull acting on the car.
39
+
40
+ Reward:
41
+ Reward of 0 is awarded if the agent reached the flag (position = 0.5)
42
+ on top of the mountain.
43
+ Reward of -1 is awarded if the position of the agent is less than 0.5.
44
+
45
+ Starting State:
46
+ The position of the car is assigned a uniform random value in
47
+ [-0.6 , -0.4].
48
+ The starting velocity of the car is always assigned to 0.
49
+
50
+ Episode Termination:
51
+ The car position is more than 0.5
52
+ Episode length is greater than 200
53
+ """
54
+
55
+ metadata = {"render.modes": ["human", "rgb_array"], "video.frames_per_second": 30}
56
+
57
+ def __init__(self, goal_velocity=0):
58
+ self.min_position = -1.2
59
+ self.max_position = 0.6
60
+ self.max_speed = 0.07
61
+ self.goal_position = 0.5
62
+ self.goal_velocity = goal_velocity
63
+
64
+ self.force = 0.001
65
+ self.gravity = 0.0025
66
+
67
+ self.low = np.array([self.min_position, -self.max_speed], dtype=np.float32)
68
+ self.high = np.array([self.max_position, self.max_speed], dtype=np.float32)
69
+
70
+ self.viewer = None
71
+
72
+ self.action_space = spaces.Discrete(3)
73
+ self.observation_space = spaces.Box(self.low, self.high, dtype=np.float32)
74
+
75
+ self.seed()
76
+
77
+ def seed(self, seed=None):
78
+ self.np_random, seed = seeding.np_random(seed)
79
+ return [seed]
80
+
81
+ def step(self, action):
82
+ assert self.action_space.contains(action), "%r (%s) invalid" % (
83
+ action,
84
+ type(action),
85
+ )
86
+
87
+ position, velocity = self.state
88
+ velocity += (action - 1) * self.force + math.cos(3 * position) * (-self.gravity)
89
+ velocity = np.clip(velocity, -self.max_speed, self.max_speed)
90
+ position += velocity
91
+ position = np.clip(position, self.min_position, self.max_position)
92
+ if position == self.min_position and velocity < 0:
93
+ velocity = 0
94
+
95
+ done = bool(position >= self.goal_position and velocity >= self.goal_velocity)
96
+ reward = -1.0
97
+
98
+ self.state = (position, velocity)
99
+ return np.array(self.state, dtype=np.float32), reward, done, {}
100
+
101
+ def reset(self):
102
+ self.state = np.array([self.np_random.uniform(low=-0.6, high=-0.4), 0])
103
+ return np.array(self.state, dtype=np.float32)
104
+
105
+ def _height(self, xs):
106
+ return np.sin(3 * xs) * 0.45 + 0.55
107
+
108
+ def render(self, mode="human"):
109
+ screen_width = 600
110
+ screen_height = 400
111
+
112
+ world_width = self.max_position - self.min_position
113
+ scale = screen_width / world_width
114
+ carwidth = 40
115
+ carheight = 20
116
+
117
+ if self.viewer is None:
118
+ from gym.envs.classic_control import rendering
119
+
120
+ self.viewer = rendering.Viewer(screen_width, screen_height)
121
+ xs = np.linspace(self.min_position, self.max_position, 100)
122
+ ys = self._height(xs)
123
+ xys = list(zip((xs - self.min_position) * scale, ys * scale))
124
+
125
+ self.track = rendering.make_polyline(xys)
126
+ self.track.set_linewidth(4)
127
+ self.viewer.add_geom(self.track)
128
+
129
+ clearance = 10
130
+
131
+ l, r, t, b = -carwidth / 2, carwidth / 2, carheight, 0
132
+ car = rendering.FilledPolygon([(l, b), (l, t), (r, t), (r, b)])
133
+ car.add_attr(rendering.Transform(translation=(0, clearance)))
134
+ self.cartrans = rendering.Transform()
135
+ car.add_attr(self.cartrans)
136
+ self.viewer.add_geom(car)
137
+ frontwheel = rendering.make_circle(carheight / 2.5)
138
+ frontwheel.set_color(0.5, 0.5, 0.5)
139
+ frontwheel.add_attr(
140
+ rendering.Transform(translation=(carwidth / 4, clearance))
141
+ )
142
+ frontwheel.add_attr(self.cartrans)
143
+ self.viewer.add_geom(frontwheel)
144
+ backwheel = rendering.make_circle(carheight / 2.5)
145
+ backwheel.add_attr(
146
+ rendering.Transform(translation=(-carwidth / 4, clearance))
147
+ )
148
+ backwheel.add_attr(self.cartrans)
149
+ backwheel.set_color(0.5, 0.5, 0.5)
150
+ self.viewer.add_geom(backwheel)
151
+ flagx = (self.goal_position - self.min_position) * scale
152
+ flagy1 = self._height(self.goal_position) * scale
153
+ flagy2 = flagy1 + 50
154
+ flagpole = rendering.Line((flagx, flagy1), (flagx, flagy2))
155
+ self.viewer.add_geom(flagpole)
156
+ flag = rendering.FilledPolygon(
157
+ [(flagx, flagy2), (flagx, flagy2 - 10), (flagx + 25, flagy2 - 5)]
158
+ )
159
+ flag.set_color(0.8, 0.8, 0)
160
+ self.viewer.add_geom(flag)
161
+
162
+ pos = self.state[0]
163
+ self.cartrans.set_translation(
164
+ (pos - self.min_position) * scale, self._height(pos) * scale
165
+ )
166
+ self.cartrans.set_rotation(math.cos(3 * pos))
167
+
168
+ return self.viewer.render(return_rgb_array=mode == "rgb_array")
169
+
170
+ def get_keys_to_action(self):
171
+ # Control with left and right arrow keys.
172
+ return {(): 1, (276,): 0, (275,): 2, (275, 276): 1}
173
+
174
+ def close(self):
175
+ if self.viewer:
176
+ self.viewer.close()
177
+ self.viewer = None
gym/envs/classic_control/pendulum.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gym
2
+ from gym import spaces
3
+ from gym.utils import seeding
4
+ import numpy as np
5
+ from os import path
6
+
7
+
8
+ class PendulumEnv(gym.Env):
9
+ metadata = {"render.modes": ["human", "rgb_array"], "video.frames_per_second": 30}
10
+
11
+ def __init__(self, g=10.0):
12
+ self.max_speed = 8
13
+ self.max_torque = 2.0
14
+ self.dt = 0.05
15
+ self.g = g
16
+ self.m = 1.0
17
+ self.l = 1.0
18
+ self.viewer = None
19
+
20
+ high = np.array([1.0, 1.0, self.max_speed], dtype=np.float32)
21
+ self.action_space = spaces.Box(
22
+ low=-self.max_torque, high=self.max_torque, shape=(1,), dtype=np.float32
23
+ )
24
+ self.observation_space = spaces.Box(low=-high, high=high, dtype=np.float32)
25
+
26
+ self.seed()
27
+
28
+ def seed(self, seed=None):
29
+ self.np_random, seed = seeding.np_random(seed)
30
+ return [seed]
31
+
32
+ def step(self, u):
33
+ th, thdot = self.state # th := theta
34
+
35
+ g = self.g
36
+ m = self.m
37
+ l = self.l
38
+ dt = self.dt
39
+
40
+ u = np.clip(u, -self.max_torque, self.max_torque)[0]
41
+ self.last_u = u # for rendering
42
+ costs = angle_normalize(th) ** 2 + 0.1 * thdot ** 2 + 0.001 * (u ** 2)
43
+
44
+ newthdot = thdot + (3 * g / (2 * l) * np.sin(th) + 3.0 / (m * l ** 2) * u) * dt
45
+ newthdot = np.clip(newthdot, -self.max_speed, self.max_speed)
46
+ newth = th + newthdot * dt
47
+
48
+ self.state = np.array([newth, newthdot])
49
+ return self._get_obs(), -costs, False, {}
50
+
51
+ def reset(self):
52
+ high = np.array([np.pi, 1])
53
+ self.state = self.np_random.uniform(low=-high, high=high)
54
+ self.last_u = None
55
+ return self._get_obs()
56
+
57
+ def _get_obs(self):
58
+ theta, thetadot = self.state
59
+ return np.array([np.cos(theta), np.sin(theta), thetadot], dtype=np.float32)
60
+
61
+ def render(self, mode="human"):
62
+ if self.viewer is None:
63
+ from gym.envs.classic_control import rendering
64
+
65
+ self.viewer = rendering.Viewer(500, 500)
66
+ self.viewer.set_bounds(-2.2, 2.2, -2.2, 2.2)
67
+ rod = rendering.make_capsule(1, 0.2)
68
+ rod.set_color(0.8, 0.3, 0.3)
69
+ self.pole_transform = rendering.Transform()
70
+ rod.add_attr(self.pole_transform)
71
+ self.viewer.add_geom(rod)
72
+ axle = rendering.make_circle(0.05)
73
+ axle.set_color(0, 0, 0)
74
+ self.viewer.add_geom(axle)
75
+ fname = path.join(path.dirname(__file__), "assets/clockwise.png")
76
+ self.img = rendering.Image(fname, 1.0, 1.0)
77
+ self.imgtrans = rendering.Transform()
78
+ self.img.add_attr(self.imgtrans)
79
+
80
+ self.viewer.add_onetime(self.img)
81
+ self.pole_transform.set_rotation(self.state[0] + np.pi / 2)
82
+ if self.last_u is not None:
83
+ self.imgtrans.scale = (-self.last_u / 2, np.abs(self.last_u) / 2)
84
+
85
+ return self.viewer.render(return_rgb_array=mode == "rgb_array")
86
+
87
+ def close(self):
88
+ if self.viewer:
89
+ self.viewer.close()
90
+ self.viewer = None
91
+
92
+
93
+ def angle_normalize(x):
94
+ return ((x + np.pi) % (2 * np.pi)) - np.pi
gym/envs/classic_control/rendering.py ADDED
@@ -0,0 +1,458 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 2D rendering framework
3
+ """
4
+ import os
5
+ import sys
6
+
7
+ if "Apple" in sys.version:
8
+ if "DYLD_FALLBACK_LIBRARY_PATH" in os.environ:
9
+ os.environ["DYLD_FALLBACK_LIBRARY_PATH"] += ":/usr/lib"
10
+ # (JDS 2016/04/15): avoid bug on Anaconda 2.3.0 / Yosemite
11
+
12
+ from gym import error
13
+
14
+ try:
15
+ import pyglet
16
+ except ImportError as e:
17
+ raise ImportError(
18
+ """
19
+ Cannot import pyglet.
20
+ HINT: you can install pyglet directly via 'pip install pyglet'.
21
+ But if you really just want to install all Gym dependencies and not have to think about it,
22
+ 'pip install -e .[all]' or 'pip install gym[all]' will do it.
23
+ """
24
+ )
25
+
26
+ try:
27
+ from pyglet.gl import *
28
+ except ImportError as e:
29
+ raise ImportError(
30
+ """
31
+ Error occurred while running `from pyglet.gl import *`
32
+ HINT: make sure you have OpenGL installed. On Ubuntu, you can run 'apt-get install python-opengl'.
33
+ If you're running on a server, you may need a virtual frame buffer; something like this should work:
34
+ 'xvfb-run -s \"-screen 0 1400x900x24\" python <your_script.py>'
35
+ """
36
+ )
37
+
38
+ import math
39
+ import numpy as np
40
+
41
+ RAD2DEG = 57.29577951308232
42
+
43
+
44
+ def get_display(spec):
45
+ """Convert a display specification (such as :0) into an actual Display
46
+ object.
47
+
48
+ Pyglet only supports multiple Displays on Linux.
49
+ """
50
+ if spec is None:
51
+ return pyglet.canvas.get_display()
52
+ # returns already available pyglet_display,
53
+ # if there is no pyglet display available then it creates one
54
+ elif isinstance(spec, str):
55
+ return pyglet.canvas.Display(spec)
56
+ else:
57
+ raise error.Error(
58
+ "Invalid display specification: {}. (Must be a string like :0 or None.)".format(
59
+ spec
60
+ )
61
+ )
62
+
63
+
64
+ def get_window(width, height, display, **kwargs):
65
+ """
66
+ Will create a pyglet window from the display specification provided.
67
+ """
68
+ screen = display.get_screens() # available screens
69
+ config = screen[0].get_best_config() # selecting the first screen
70
+ context = config.create_context(None) # create GL context
71
+
72
+ return pyglet.window.Window(
73
+ width=width,
74
+ height=height,
75
+ display=display,
76
+ config=config,
77
+ context=context,
78
+ **kwargs
79
+ )
80
+
81
+
82
+ class Viewer(object):
83
+ def __init__(self, width, height, display=None):
84
+ display = get_display(display)
85
+
86
+ self.width = width
87
+ self.height = height
88
+ self.window = get_window(width=width, height=height, display=display)
89
+ self.window.on_close = self.window_closed_by_user
90
+ self.isopen = True
91
+ self.geoms = []
92
+ self.onetime_geoms = []
93
+ self.transform = Transform()
94
+
95
+ glEnable(GL_BLEND)
96
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
97
+
98
+ def close(self):
99
+ if self.isopen and sys.meta_path:
100
+ # ^^^ check sys.meta_path to avoid 'ImportError: sys.meta_path is None, Python is likely shutting down'
101
+ self.window.close()
102
+ self.isopen = False
103
+
104
+ def window_closed_by_user(self):
105
+ self.isopen = False
106
+
107
+ def set_bounds(self, left, right, bottom, top):
108
+ assert right > left and top > bottom
109
+ scalex = self.width / (right - left)
110
+ scaley = self.height / (top - bottom)
111
+ self.transform = Transform(
112
+ translation=(-left * scalex, -bottom * scaley), scale=(scalex, scaley)
113
+ )
114
+
115
+ def add_geom(self, geom):
116
+ self.geoms.append(geom)
117
+
118
+ def add_onetime(self, geom):
119
+ self.onetime_geoms.append(geom)
120
+
121
+ def render(self, return_rgb_array=False):
122
+ glClearColor(1, 1, 1, 1)
123
+ self.window.clear()
124
+ self.window.switch_to()
125
+ self.window.dispatch_events()
126
+ self.transform.enable()
127
+ for geom in self.geoms:
128
+ geom.render()
129
+ for geom in self.onetime_geoms:
130
+ geom.render()
131
+ self.transform.disable()
132
+ arr = None
133
+ if return_rgb_array:
134
+ buffer = pyglet.image.get_buffer_manager().get_color_buffer()
135
+ image_data = buffer.get_image_data()
136
+ arr = np.frombuffer(image_data.get_data(), dtype=np.uint8)
137
+ # In https://github.com/openai/gym-http-api/issues/2, we
138
+ # discovered that someone using Xmonad on Arch was having
139
+ # a window of size 598 x 398, though a 600 x 400 window
140
+ # was requested. (Guess Xmonad was preserving a pixel for
141
+ # the boundary.) So we use the buffer height/width rather
142
+ # than the requested one.
143
+ arr = arr.reshape(buffer.height, buffer.width, 4)
144
+ arr = arr[::-1, :, 0:3]
145
+ self.window.flip()
146
+ self.onetime_geoms = []
147
+ return arr if return_rgb_array else self.isopen
148
+
149
+ # Convenience
150
+ def draw_circle(self, radius=10, res=30, filled=True, **attrs):
151
+ geom = make_circle(radius=radius, res=res, filled=filled)
152
+ _add_attrs(geom, attrs)
153
+ self.add_onetime(geom)
154
+ return geom
155
+
156
+ def draw_polygon(self, v, filled=True, **attrs):
157
+ geom = make_polygon(v=v, filled=filled)
158
+ _add_attrs(geom, attrs)
159
+ self.add_onetime(geom)
160
+ return geom
161
+
162
+ def draw_polyline(self, v, **attrs):
163
+ geom = make_polyline(v=v)
164
+ _add_attrs(geom, attrs)
165
+ self.add_onetime(geom)
166
+ return geom
167
+
168
+ def draw_line(self, start, end, **attrs):
169
+ geom = Line(start, end)
170
+ _add_attrs(geom, attrs)
171
+ self.add_onetime(geom)
172
+ return geom
173
+
174
+ def get_array(self):
175
+ self.window.flip()
176
+ image_data = (
177
+ pyglet.image.get_buffer_manager().get_color_buffer().get_image_data()
178
+ )
179
+ self.window.flip()
180
+ arr = np.fromstring(image_data.get_data(), dtype=np.uint8, sep="")
181
+ arr = arr.reshape(self.height, self.width, 4)
182
+ return arr[::-1, :, 0:3]
183
+
184
+ def __del__(self):
185
+ self.close()
186
+
187
+
188
+ def _add_attrs(geom, attrs):
189
+ if "color" in attrs:
190
+ geom.set_color(*attrs["color"])
191
+ if "linewidth" in attrs:
192
+ geom.set_linewidth(attrs["linewidth"])
193
+
194
+
195
+ class Geom(object):
196
+ def __init__(self):
197
+ self._color = Color((0, 0, 0, 1.0))
198
+ self.attrs = [self._color]
199
+
200
+ def render(self):
201
+ for attr in reversed(self.attrs):
202
+ attr.enable()
203
+ self.render1()
204
+ for attr in self.attrs:
205
+ attr.disable()
206
+
207
+ def render1(self):
208
+ raise NotImplementedError
209
+
210
+ def add_attr(self, attr):
211
+ self.attrs.append(attr)
212
+
213
+ def set_color(self, r, g, b):
214
+ self._color.vec4 = (r, g, b, 1)
215
+
216
+
217
+ class Attr(object):
218
+ def enable(self):
219
+ raise NotImplementedError
220
+
221
+ def disable(self):
222
+ pass
223
+
224
+
225
+ class Transform(Attr):
226
+ def __init__(self, translation=(0.0, 0.0), rotation=0.0, scale=(1, 1)):
227
+ self.set_translation(*translation)
228
+ self.set_rotation(rotation)
229
+ self.set_scale(*scale)
230
+
231
+ def enable(self):
232
+ glPushMatrix()
233
+ glTranslatef(
234
+ self.translation[0], self.translation[1], 0
235
+ ) # translate to GL loc ppint
236
+ glRotatef(RAD2DEG * self.rotation, 0, 0, 1.0)
237
+ glScalef(self.scale[0], self.scale[1], 1)
238
+
239
+ def disable(self):
240
+ glPopMatrix()
241
+
242
+ def set_translation(self, newx, newy):
243
+ self.translation = (float(newx), float(newy))
244
+
245
+ def set_rotation(self, new):
246
+ self.rotation = float(new)
247
+
248
+ def set_scale(self, newx, newy):
249
+ self.scale = (float(newx), float(newy))
250
+
251
+
252
+ class Color(Attr):
253
+ def __init__(self, vec4):
254
+ self.vec4 = vec4
255
+
256
+ def enable(self):
257
+ glColor4f(*self.vec4)
258
+
259
+
260
+ class LineStyle(Attr):
261
+ def __init__(self, style):
262
+ self.style = style
263
+
264
+ def enable(self):
265
+ glEnable(GL_LINE_STIPPLE)
266
+ glLineStipple(1, self.style)
267
+
268
+ def disable(self):
269
+ glDisable(GL_LINE_STIPPLE)
270
+
271
+
272
+ class LineWidth(Attr):
273
+ def __init__(self, stroke):
274
+ self.stroke = stroke
275
+
276
+ def enable(self):
277
+ glLineWidth(self.stroke)
278
+
279
+
280
+ class Point(Geom):
281
+ def __init__(self):
282
+ Geom.__init__(self)
283
+
284
+ def render1(self):
285
+ glBegin(GL_POINTS) # draw point
286
+ glVertex3f(0.0, 0.0, 0.0)
287
+ glEnd()
288
+
289
+
290
+ class FilledPolygon(Geom):
291
+ def __init__(self, v):
292
+ Geom.__init__(self)
293
+ self.v = v
294
+
295
+ def render1(self):
296
+ if len(self.v) == 4:
297
+ glBegin(GL_QUADS)
298
+ elif len(self.v) > 4:
299
+ glBegin(GL_POLYGON)
300
+ else:
301
+ glBegin(GL_TRIANGLES)
302
+ for p in self.v:
303
+ glVertex3f(p[0], p[1], 0) # draw each vertex
304
+ glEnd()
305
+
306
+
307
+ def make_circle(radius=10, res=30, filled=True):
308
+ points = []
309
+ for i in range(res):
310
+ ang = 2 * math.pi * i / res
311
+ points.append((math.cos(ang) * radius, math.sin(ang) * radius))
312
+ if filled:
313
+ return FilledPolygon(points)
314
+ else:
315
+ return PolyLine(points, True)
316
+
317
+
318
+ def make_polygon(v, filled=True):
319
+ if filled:
320
+ return FilledPolygon(v)
321
+ else:
322
+ return PolyLine(v, True)
323
+
324
+
325
+ def make_polyline(v):
326
+ return PolyLine(v, False)
327
+
328
+
329
+ def make_capsule(length, width):
330
+ l, r, t, b = 0, length, width / 2, -width / 2
331
+ box = make_polygon([(l, b), (l, t), (r, t), (r, b)])
332
+ circ0 = make_circle(width / 2)
333
+ circ1 = make_circle(width / 2)
334
+ circ1.add_attr(Transform(translation=(length, 0)))
335
+ geom = Compound([box, circ0, circ1])
336
+ return geom
337
+
338
+
339
+ class Compound(Geom):
340
+ def __init__(self, gs):
341
+ Geom.__init__(self)
342
+ self.gs = gs
343
+ for g in self.gs:
344
+ g.attrs = [a for a in g.attrs if not isinstance(a, Color)]
345
+
346
+ def render1(self):
347
+ for g in self.gs:
348
+ g.render()
349
+
350
+
351
+ class PolyLine(Geom):
352
+ def __init__(self, v, close):
353
+ Geom.__init__(self)
354
+ self.v = v
355
+ self.close = close
356
+ self.linewidth = LineWidth(1)
357
+ self.add_attr(self.linewidth)
358
+
359
+ def render1(self):
360
+ glBegin(GL_LINE_LOOP if self.close else GL_LINE_STRIP)
361
+ for p in self.v:
362
+ glVertex3f(p[0], p[1], 0) # draw each vertex
363
+ glEnd()
364
+
365
+ def set_linewidth(self, x):
366
+ self.linewidth.stroke = x
367
+
368
+
369
+ class Line(Geom):
370
+ def __init__(self, start=(0.0, 0.0), end=(0.0, 0.0)):
371
+ Geom.__init__(self)
372
+ self.start = start
373
+ self.end = end
374
+ self.linewidth = LineWidth(1)
375
+ self.add_attr(self.linewidth)
376
+
377
+ def render1(self):
378
+ glBegin(GL_LINES)
379
+ glVertex2f(*self.start)
380
+ glVertex2f(*self.end)
381
+ glEnd()
382
+
383
+
384
+ class Image(Geom):
385
+ def __init__(self, fname, width, height):
386
+ Geom.__init__(self)
387
+ self.set_color(1.0, 1.0, 1.0)
388
+ self.width = width
389
+ self.height = height
390
+ img = pyglet.image.load(fname)
391
+ self.img = img
392
+ self.flip = False
393
+
394
+ def render1(self):
395
+ self.img.blit(
396
+ -self.width / 2, -self.height / 2, width=self.width, height=self.height
397
+ )
398
+
399
+
400
+ # ================================================================
401
+
402
+
403
+ class SimpleImageViewer(object):
404
+ def __init__(self, display=None, maxwidth=500):
405
+ self.window = None
406
+ self.isopen = False
407
+ self.display = get_display(display)
408
+ self.maxwidth = maxwidth
409
+
410
+ def imshow(self, arr):
411
+ if self.window is None:
412
+ height, width, _channels = arr.shape
413
+ if width > self.maxwidth:
414
+ scale = self.maxwidth / width
415
+ width = int(scale * width)
416
+ height = int(scale * height)
417
+ self.window = get_window(
418
+ width=width,
419
+ height=height,
420
+ display=self.display,
421
+ vsync=False,
422
+ resizable=True,
423
+ )
424
+ self.width = width
425
+ self.height = height
426
+ self.isopen = True
427
+
428
+ @self.window.event
429
+ def on_resize(width, height):
430
+ self.width = width
431
+ self.height = height
432
+
433
+ @self.window.event
434
+ def on_close():
435
+ self.isopen = False
436
+
437
+ assert len(arr.shape) == 3, "You passed in an image with the wrong number shape"
438
+ image = pyglet.image.ImageData(
439
+ arr.shape[1], arr.shape[0], "RGB", arr.tobytes(), pitch=arr.shape[1] * -3
440
+ )
441
+ texture = image.get_texture()
442
+ gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)
443
+ texture.width = self.width
444
+ texture.height = self.height
445
+ self.window.clear()
446
+ self.window.switch_to()
447
+ self.window.dispatch_events()
448
+ texture.blit(0, 0) # draw
449
+ self.window.flip()
450
+
451
+ def close(self):
452
+ if self.isopen and sys.meta_path:
453
+ # ^^^ check sys.meta_path to avoid 'ImportError: sys.meta_path is None, Python is likely shutting down'
454
+ self.window.close()
455
+ self.isopen = False
456
+
457
+ def __del__(self):
458
+ self.close()
gym/envs/mujoco/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from gym.envs.mujoco.mujoco_env import MujocoEnv
2
+
3
+ # ^^^^^ so that user gets the correct error
4
+ # message if mujoco is not installed correctly
5
+ from gym.envs.mujoco.ant import AntEnv
6
+ from gym.envs.mujoco.half_cheetah import HalfCheetahEnv
7
+ from gym.envs.mujoco.hopper import HopperEnv
8
+ from gym.envs.mujoco.walker2d import Walker2dEnv
9
+ from gym.envs.mujoco.humanoid import HumanoidEnv
10
+ from gym.envs.mujoco.inverted_pendulum import InvertedPendulumEnv
11
+ from gym.envs.mujoco.inverted_double_pendulum import InvertedDoublePendulumEnv
12
+ from gym.envs.mujoco.reacher import ReacherEnv
13
+ from gym.envs.mujoco.swimmer import SwimmerEnv
14
+ from gym.envs.mujoco.humanoidstandup import HumanoidStandupEnv
15
+ from gym.envs.mujoco.pusher import PusherEnv
16
+ from gym.envs.mujoco.thrower import ThrowerEnv
17
+ from gym.envs.mujoco.striker import StrikerEnv
gym/envs/mujoco/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (1.04 kB). View file
 
gym/envs/mujoco/__pycache__/ant.cpython-39.pyc ADDED
Binary file (2.12 kB). View file
 
gym/envs/mujoco/__pycache__/ant_v3.cpython-39.pyc ADDED
Binary file (4.23 kB). View file
 
gym/envs/mujoco/__pycache__/half_cheetah.cpython-39.pyc ADDED
Binary file (1.82 kB). View file
 
gym/envs/mujoco/__pycache__/half_cheetah_v3.cpython-39.pyc ADDED
Binary file (2.68 kB). View file
 
gym/envs/mujoco/__pycache__/hopper.cpython-39.pyc ADDED
Binary file (2.04 kB). View file
 
gym/envs/mujoco/__pycache__/hopper_v3.cpython-39.pyc ADDED
Binary file (3.94 kB). View file
 
gym/envs/mujoco/__pycache__/humanoid.cpython-39.pyc ADDED
Binary file (2.47 kB). View file
 
gym/envs/mujoco/__pycache__/humanoid_v3.cpython-39.pyc ADDED
Binary file (4.65 kB). View file