diff --git a/app.py b/app.py index c74e16dd0e6e618c6968102386af7f67c7f54f93..debd4921e74f76273b4ef03b7604171b527edcde 100644 --- a/app.py +++ b/app.py @@ -1,9 +1,12 @@ +import os import glob import gym import time import streamlit as st from stable_baselines3 import PPO -import cv2 + +if os.path.exists("video.mp4"): + os.remove(".video.mp4") st.write(gym.__version__) @@ -11,43 +14,24 @@ env = gym.make('BipedalWalker-v3') model = PPO.load("bipedalwalker_ppo") video_every = 1 - -# Define a custom video recording wrapper -class VideoRecorder(gym.Wrapper): - def __init__(self, env): - super().__init__(env) - self.frames = [] - - def reset(self, **kwargs): - self.frames = [] - return self.env.reset(**kwargs) - - def step(self, action): - obs, reward, done, info = self.env.step(action) - frame = self.env.render(mode='rgb_array') - self.frames.append(frame) - if done: - self.save_video() - return obs, reward, done, info - - def save_video(self): - fourcc = cv2.VideoWriter_fourcc(*'mp4v') - out = cv2.VideoWriter('video.mp4', fourcc, self.env.metadata['video.frames_per_second'], (self.frames[0].shape[1], self.frames[0].shape[0])) - for frame in self.frames: - out.write(frame) - out.release() - -env = VideoRecorder(env) # Wrap the environment with the custom video recording wrapper +env = gym.wrappers.RecordVideo(env, 'video.mp4') obs = env.reset() - -for i in range(1000): +for i in range(100): action, _ = model.predict(obs, deterministic=True) - obs, reward, done, info = env.step(action) + obs,reward,done,info =env.step(action) if done : env.reset() env.close() +# Change the current working directory to the 'video' folder +# os.chdir('./video') + +# Find the mp4 file in the directory +# mp4_files = glob.glob("*.mp4") + +# Check if the file exists + video_file = open("video.mp4", 'rb') video_bytes = video_file.read() st.video(video_bytes, format='mp4') diff --git a/gym/__init__.py b/gym/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ef30030057f3d805653b3d7b8dc9ae11169b1a42 --- /dev/null +++ b/gym/__init__.py @@ -0,0 +1,18 @@ +from gym import error +from gym.version import VERSION as __version__ + +from gym.core import ( + Env, + GoalEnv, + Wrapper, + ObservationWrapper, + ActionWrapper, + RewardWrapper, +) +from gym.spaces import Space +from gym.envs import make, spec, register +from gym import logger +from gym import vector +from gym import wrappers + +__all__ = ["Env", "Space", "Wrapper", "make", "spec", "register"] diff --git a/gym/__pycache__/__init__.cpython-39.pyc b/gym/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a91387b6169126e9269922355ebf20f9c004b1a1 Binary files /dev/null and b/gym/__pycache__/__init__.cpython-39.pyc differ diff --git a/gym/__pycache__/core.cpython-39.pyc b/gym/__pycache__/core.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69d501a8c8e4c735d66911c9307dcc2786f999c5 Binary files /dev/null and b/gym/__pycache__/core.cpython-39.pyc differ diff --git a/gym/__pycache__/error.cpython-39.pyc b/gym/__pycache__/error.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..045f635dd681093c3a94e2de0c266b68a7e54955 Binary files /dev/null and b/gym/__pycache__/error.cpython-39.pyc differ diff --git a/gym/__pycache__/logger.cpython-39.pyc b/gym/__pycache__/logger.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0f480ff82d8b61dc80c1ca0f4549186c595f9da Binary files /dev/null and b/gym/__pycache__/logger.cpython-39.pyc differ diff --git a/gym/__pycache__/version.cpython-39.pyc b/gym/__pycache__/version.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d862274d41a58c825ce3f7d9a5326ed68e8793ec Binary files /dev/null and b/gym/__pycache__/version.cpython-39.pyc differ diff --git a/gym/core.py b/gym/core.py new file mode 100644 index 0000000000000000000000000000000000000000..ae7b32c355714a1fc2b5ea2f0d4ee01f4845fcf0 --- /dev/null +++ b/gym/core.py @@ -0,0 +1,357 @@ +from abc import abstractmethod + +import gym +from gym import error +from gym.utils import closer + + +class Env(object): + """The main OpenAI Gym class. It encapsulates an environment with + arbitrary behind-the-scenes dynamics. An environment can be + partially or fully observed. + + The main API methods that users of this class need to know are: + + step + reset + render + close + seed + + And set the following attributes: + + action_space: The Space object corresponding to valid actions + observation_space: The Space object corresponding to valid observations + reward_range: A tuple corresponding to the min and max possible rewards + + Note: a default reward range set to [-inf,+inf] already exists. Set it if you want a narrower range. + + The methods are accessed publicly as "step", "reset", etc... + """ + + # Set this in SOME subclasses + metadata = {"render.modes": []} + reward_range = (-float("inf"), float("inf")) + spec = None + + # Set these in ALL subclasses + action_space = None + observation_space = None + + @abstractmethod + def step(self, action): + """Run one timestep of the environment's dynamics. When end of + episode is reached, you are responsible for calling `reset()` + to reset this environment's state. + + Accepts an action and returns a tuple (observation, reward, done, info). + + Args: + action (object): an action provided by the agent + + Returns: + observation (object): agent's observation of the current environment + reward (float) : amount of reward returned after previous action + done (bool): whether the episode has ended, in which case further step() calls will return undefined results + info (dict): contains auxiliary diagnostic information (helpful for debugging, and sometimes learning) + """ + raise NotImplementedError + + @abstractmethod + def reset(self): + """Resets the environment to an initial state and returns an initial + observation. + + Note that this function should not reset the environment's random + number generator(s); random variables in the environment's state should + be sampled independently between multiple calls to `reset()`. In other + words, each call of `reset()` should yield an environment suitable for + a new episode, independent of previous episodes. + + Returns: + observation (object): the initial observation. + """ + raise NotImplementedError + + @abstractmethod + def render(self, mode="human"): + """Renders the environment. + + The set of supported modes varies per environment. (And some + environments do not support rendering at all.) By convention, + if mode is: + + - human: render to the current display or terminal and + return nothing. Usually for human consumption. + - rgb_array: Return an numpy.ndarray with shape (x, y, 3), + representing RGB values for an x-by-y pixel image, suitable + for turning into a video. + - ansi: Return a string (str) or StringIO.StringIO containing a + terminal-style text representation. The text can include newlines + and ANSI escape sequences (e.g. for colors). + + Note: + Make sure that your class's metadata 'render.modes' key includes + the list of supported modes. It's recommended to call super() + in implementations to use the functionality of this method. + + Args: + mode (str): the mode to render with + + Example: + + class MyEnv(Env): + metadata = {'render.modes': ['human', 'rgb_array']} + + def render(self, mode='human'): + if mode == 'rgb_array': + return np.array(...) # return RGB frame suitable for video + elif mode == 'human': + ... # pop up a window and render + else: + super(MyEnv, self).render(mode=mode) # just raise an exception + """ + raise NotImplementedError + + def close(self): + """Override close in your subclass to perform any necessary cleanup. + + Environments will automatically close() themselves when + garbage collected or when the program exits. + """ + pass + + def seed(self, seed=None): + """Sets the seed for this env's random number generator(s). + + Note: + Some environments use multiple pseudorandom number generators. + We want to capture all such seeds used in order to ensure that + there aren't accidental correlations between multiple generators. + + Returns: + list: Returns the list of seeds used in this env's random + number generators. The first value in the list should be the + "main" seed, or the value which a reproducer should pass to + 'seed'. Often, the main seed equals the provided 'seed', but + this won't be true if seed=None, for example. + """ + return + + @property + def unwrapped(self): + """Completely unwrap this env. + + Returns: + gym.Env: The base non-wrapped gym.Env instance + """ + return self + + def __str__(self): + if self.spec is None: + return "<{} instance>".format(type(self).__name__) + else: + return "<{}<{}>>".format(type(self).__name__, self.spec.id) + + def __enter__(self): + """Support with-statement for the environment.""" + return self + + def __exit__(self, *args): + """Support with-statement for the environment.""" + self.close() + # propagate exception + return False + + +class GoalEnv(Env): + """A goal-based environment. It functions just as any regular OpenAI Gym environment but it + imposes a required structure on the observation_space. More concretely, the observation + space is required to contain at least three elements, namely `observation`, `desired_goal`, and + `achieved_goal`. Here, `desired_goal` specifies the goal that the agent should attempt to achieve. + `achieved_goal` is the goal that it currently achieved instead. `observation` contains the + actual observations of the environment as per usual. + """ + + def reset(self): + # Enforce that each GoalEnv uses a Goal-compatible observation space. + if not isinstance(self.observation_space, gym.spaces.Dict): + raise error.Error( + "GoalEnv requires an observation space of type gym.spaces.Dict" + ) + for key in ["observation", "achieved_goal", "desired_goal"]: + if key not in self.observation_space.spaces: + raise error.Error( + 'GoalEnv requires the "{}" key to be part of the observation dictionary.'.format( + key + ) + ) + + @abstractmethod + def compute_reward(self, achieved_goal, desired_goal, info): + """Compute the step reward. This externalizes the reward function and makes + it dependent on a desired goal and the one that was achieved. If you wish to include + additional rewards that are independent of the goal, you can include the necessary values + to derive it in 'info' and compute it accordingly. + + Args: + achieved_goal (object): the goal that was achieved during execution + desired_goal (object): the desired goal that we asked the agent to attempt to achieve + info (dict): an info dictionary with additional information + + Returns: + float: The reward that corresponds to the provided achieved goal w.r.t. to the desired + goal. Note that the following should always hold true: + + ob, reward, done, info = env.step() + assert reward == env.compute_reward(ob['achieved_goal'], ob['desired_goal'], info) + """ + raise NotImplementedError + + +class Wrapper(Env): + """Wraps the environment to allow a modular transformation. + + This class is the base class for all wrappers. The subclass could override + some methods to change the behavior of the original environment without touching the + original code. + + .. note:: + + Don't forget to call ``super().__init__(env)`` if the subclass overrides :meth:`__init__`. + + """ + + def __init__(self, env): + self.env = env + + self._action_space = None + self._observation_space = None + self._reward_range = None + self._metadata = None + + def __getattr__(self, name): + if name.startswith("_"): + raise AttributeError( + "attempted to get missing private attribute '{}'".format(name) + ) + return getattr(self.env, name) + + @property + def spec(self): + return self.env.spec + + @classmethod + def class_name(cls): + return cls.__name__ + + @property + def action_space(self): + if self._action_space is None: + return self.env.action_space + return self._action_space + + @action_space.setter + def action_space(self, space): + self._action_space = space + + @property + def observation_space(self): + if self._observation_space is None: + return self.env.observation_space + return self._observation_space + + @observation_space.setter + def observation_space(self, space): + self._observation_space = space + + @property + def reward_range(self): + if self._reward_range is None: + return self.env.reward_range + return self._reward_range + + @reward_range.setter + def reward_range(self, value): + self._reward_range = value + + @property + def metadata(self): + if self._metadata is None: + return self.env.metadata + return self._metadata + + @metadata.setter + def metadata(self, value): + self._metadata = value + + def step(self, action): + return self.env.step(action) + + def reset(self, **kwargs): + return self.env.reset(**kwargs) + + def render(self, mode="human", **kwargs): + return self.env.render(mode, **kwargs) + + def close(self): + return self.env.close() + + def seed(self, seed=None): + return self.env.seed(seed) + + def compute_reward(self, achieved_goal, desired_goal, info): + return self.env.compute_reward(achieved_goal, desired_goal, info) + + def __str__(self): + return "<{}{}>".format(type(self).__name__, self.env) + + def __repr__(self): + return str(self) + + @property + def unwrapped(self): + return self.env.unwrapped + + +class ObservationWrapper(Wrapper): + def reset(self, **kwargs): + observation = self.env.reset(**kwargs) + return self.observation(observation) + + def step(self, action): + observation, reward, done, info = self.env.step(action) + return self.observation(observation), reward, done, info + + @abstractmethod + def observation(self, observation): + raise NotImplementedError + + +class RewardWrapper(Wrapper): + def reset(self, **kwargs): + return self.env.reset(**kwargs) + + def step(self, action): + observation, reward, done, info = self.env.step(action) + return observation, self.reward(reward), done, info + + @abstractmethod + def reward(self, reward): + raise NotImplementedError + + +class ActionWrapper(Wrapper): + def reset(self, **kwargs): + return self.env.reset(**kwargs) + + def step(self, action): + return self.env.step(self.action(action)) + + @abstractmethod + def action(self, action): + raise NotImplementedError + + @abstractmethod + def reverse_action(self, action): + raise NotImplementedError diff --git a/gym/envs/__init__.py b/gym/envs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a90b0370730e74d783971a1a3f0771c5a2fb572e --- /dev/null +++ b/gym/envs/__init__.py @@ -0,0 +1,646 @@ +from gym.envs.registration import ( + registry, + register, + make, + spec, + load_env_plugins as _load_env_plugins, +) + +# Hook to load plugins from entry points +_load_env_plugins() + + +# Classic +# ---------------------------------------- + +register( + id="CartPole-v0", + entry_point="gym.envs.classic_control:CartPoleEnv", + max_episode_steps=200, + reward_threshold=195.0, +) + +register( + id="CartPole-v1", + entry_point="gym.envs.classic_control:CartPoleEnv", + max_episode_steps=500, + reward_threshold=475.0, +) + +register( + id="MountainCar-v0", + entry_point="gym.envs.classic_control:MountainCarEnv", + max_episode_steps=200, + reward_threshold=-110.0, +) + +register( + id="MountainCarContinuous-v0", + entry_point="gym.envs.classic_control:Continuous_MountainCarEnv", + max_episode_steps=999, + reward_threshold=90.0, +) + +register( + id="Pendulum-v1", + entry_point="gym.envs.classic_control:PendulumEnv", + max_episode_steps=200, +) + +register( + id="Acrobot-v1", + entry_point="gym.envs.classic_control:AcrobotEnv", + reward_threshold=-100.0, + max_episode_steps=500, +) + +# Box2d +# ---------------------------------------- + +register( + id="LunarLander-v2", + entry_point="gym.envs.box2d:LunarLander", + max_episode_steps=1000, + reward_threshold=200, +) + +register( + id="LunarLanderContinuous-v2", + entry_point="gym.envs.box2d:LunarLanderContinuous", + max_episode_steps=1000, + reward_threshold=200, +) + +register( + id="BipedalWalker-v3", + entry_point="gym.envs.box2d:BipedalWalker", + max_episode_steps=1600, + reward_threshold=300, +) + +register( + id="BipedalWalkerHardcore-v3", + entry_point="gym.envs.box2d:BipedalWalkerHardcore", + max_episode_steps=2000, + reward_threshold=300, +) + +register( + id="CarRacing-v0", + entry_point="gym.envs.box2d:CarRacing", + max_episode_steps=1000, + reward_threshold=900, +) + +# Toy Text +# ---------------------------------------- + +register( + id="Blackjack-v1", + entry_point="gym.envs.toy_text:BlackjackEnv", + kwargs={"sab": True, "natural": False}, +) + +register( + id="FrozenLake-v1", + entry_point="gym.envs.toy_text:FrozenLakeEnv", + kwargs={"map_name": "4x4"}, + max_episode_steps=100, + reward_threshold=0.70, # optimum = 0.74 +) + +register( + id="FrozenLake8x8-v1", + entry_point="gym.envs.toy_text:FrozenLakeEnv", + kwargs={"map_name": "8x8"}, + max_episode_steps=200, + reward_threshold=0.85, # optimum = 0.91 +) + +register( + id="CliffWalking-v0", + entry_point="gym.envs.toy_text:CliffWalkingEnv", +) + +register( + id="Taxi-v3", + entry_point="gym.envs.toy_text:TaxiEnv", + reward_threshold=8, # optimum = 8.46 + max_episode_steps=200, +) + +# Mujoco +# ---------------------------------------- + +# 2D + +register( + id="Reacher-v2", + entry_point="gym.envs.mujoco:ReacherEnv", + max_episode_steps=50, + reward_threshold=-3.75, +) + +register( + id="Pusher-v2", + entry_point="gym.envs.mujoco:PusherEnv", + max_episode_steps=100, + reward_threshold=0.0, +) + +register( + id="Thrower-v2", + entry_point="gym.envs.mujoco:ThrowerEnv", + max_episode_steps=100, + reward_threshold=0.0, +) + +register( + id="Striker-v2", + entry_point="gym.envs.mujoco:StrikerEnv", + max_episode_steps=100, + reward_threshold=0.0, +) + +register( + id="InvertedPendulum-v2", + entry_point="gym.envs.mujoco:InvertedPendulumEnv", + max_episode_steps=1000, + reward_threshold=950.0, +) + +register( + id="InvertedDoublePendulum-v2", + entry_point="gym.envs.mujoco:InvertedDoublePendulumEnv", + max_episode_steps=1000, + reward_threshold=9100.0, +) + +register( + id="HalfCheetah-v2", + entry_point="gym.envs.mujoco:HalfCheetahEnv", + max_episode_steps=1000, + reward_threshold=4800.0, +) + +register( + id="HalfCheetah-v3", + entry_point="gym.envs.mujoco.half_cheetah_v3:HalfCheetahEnv", + max_episode_steps=1000, + reward_threshold=4800.0, +) + +register( + id="Hopper-v2", + entry_point="gym.envs.mujoco:HopperEnv", + max_episode_steps=1000, + reward_threshold=3800.0, +) + +register( + id="Hopper-v3", + entry_point="gym.envs.mujoco.hopper_v3:HopperEnv", + max_episode_steps=1000, + reward_threshold=3800.0, +) + +register( + id="Swimmer-v2", + entry_point="gym.envs.mujoco:SwimmerEnv", + max_episode_steps=1000, + reward_threshold=360.0, +) + +register( + id="Swimmer-v3", + entry_point="gym.envs.mujoco.swimmer_v3:SwimmerEnv", + max_episode_steps=1000, + reward_threshold=360.0, +) + +register( + id="Walker2d-v2", + max_episode_steps=1000, + entry_point="gym.envs.mujoco:Walker2dEnv", +) + +register( + id="Walker2d-v3", + max_episode_steps=1000, + entry_point="gym.envs.mujoco.walker2d_v3:Walker2dEnv", +) + +register( + id="Ant-v2", + entry_point="gym.envs.mujoco:AntEnv", + max_episode_steps=1000, + reward_threshold=6000.0, +) + +register( + id="Ant-v3", + entry_point="gym.envs.mujoco.ant_v3:AntEnv", + max_episode_steps=1000, + reward_threshold=6000.0, +) + +register( + id="Humanoid-v2", + entry_point="gym.envs.mujoco:HumanoidEnv", + max_episode_steps=1000, +) + +register( + id="Humanoid-v3", + entry_point="gym.envs.mujoco.humanoid_v3:HumanoidEnv", + max_episode_steps=1000, +) + +register( + id="HumanoidStandup-v2", + entry_point="gym.envs.mujoco:HumanoidStandupEnv", + max_episode_steps=1000, +) + +# Robotics +# ---------------------------------------- + + +def _merge(a, b): + a.update(b) + return a + + +for reward_type in ["sparse", "dense"]: + suffix = "Dense" if reward_type == "dense" else "" + kwargs = { + "reward_type": reward_type, + } + + # Fetch + register( + id="FetchSlide{}-v1".format(suffix), + entry_point="gym.envs.robotics:FetchSlideEnv", + kwargs=kwargs, + max_episode_steps=50, + ) + + register( + id="FetchPickAndPlace{}-v1".format(suffix), + entry_point="gym.envs.robotics:FetchPickAndPlaceEnv", + kwargs=kwargs, + max_episode_steps=50, + ) + + register( + id="FetchReach{}-v1".format(suffix), + entry_point="gym.envs.robotics:FetchReachEnv", + kwargs=kwargs, + max_episode_steps=50, + ) + + register( + id="FetchPush{}-v1".format(suffix), + entry_point="gym.envs.robotics:FetchPushEnv", + kwargs=kwargs, + max_episode_steps=50, + ) + + # Hand + register( + id="HandReach{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandReachEnv", + kwargs=kwargs, + max_episode_steps=50, + ) + + register( + id="HandManipulateBlockRotateZ{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandBlockEnv", + kwargs=_merge({"target_position": "ignore", "target_rotation": "z"}, kwargs), + max_episode_steps=100, + ) + + register( + id="HandManipulateBlockRotateZTouchSensors{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandBlockTouchSensorsEnv", + kwargs=_merge( + { + "target_position": "ignore", + "target_rotation": "z", + "touch_get_obs": "boolean", + }, + kwargs, + ), + max_episode_steps=100, + ) + + register( + id="HandManipulateBlockRotateZTouchSensors{}-v1".format(suffix), + entry_point="gym.envs.robotics:HandBlockTouchSensorsEnv", + kwargs=_merge( + { + "target_position": "ignore", + "target_rotation": "z", + "touch_get_obs": "sensordata", + }, + kwargs, + ), + max_episode_steps=100, + ) + + register( + id="HandManipulateBlockRotateParallel{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandBlockEnv", + kwargs=_merge( + {"target_position": "ignore", "target_rotation": "parallel"}, kwargs + ), + max_episode_steps=100, + ) + + register( + id="HandManipulateBlockRotateParallelTouchSensors{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandBlockTouchSensorsEnv", + kwargs=_merge( + { + "target_position": "ignore", + "target_rotation": "parallel", + "touch_get_obs": "boolean", + }, + kwargs, + ), + max_episode_steps=100, + ) + + register( + id="HandManipulateBlockRotateParallelTouchSensors{}-v1".format(suffix), + entry_point="gym.envs.robotics:HandBlockTouchSensorsEnv", + kwargs=_merge( + { + "target_position": "ignore", + "target_rotation": "parallel", + "touch_get_obs": "sensordata", + }, + kwargs, + ), + max_episode_steps=100, + ) + + register( + id="HandManipulateBlockRotateXYZ{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandBlockEnv", + kwargs=_merge({"target_position": "ignore", "target_rotation": "xyz"}, kwargs), + max_episode_steps=100, + ) + + register( + id="HandManipulateBlockRotateXYZTouchSensors{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandBlockTouchSensorsEnv", + kwargs=_merge( + { + "target_position": "ignore", + "target_rotation": "xyz", + "touch_get_obs": "boolean", + }, + kwargs, + ), + max_episode_steps=100, + ) + + register( + id="HandManipulateBlockRotateXYZTouchSensors{}-v1".format(suffix), + entry_point="gym.envs.robotics:HandBlockTouchSensorsEnv", + kwargs=_merge( + { + "target_position": "ignore", + "target_rotation": "xyz", + "touch_get_obs": "sensordata", + }, + kwargs, + ), + max_episode_steps=100, + ) + + register( + id="HandManipulateBlockFull{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandBlockEnv", + kwargs=_merge({"target_position": "random", "target_rotation": "xyz"}, kwargs), + max_episode_steps=100, + ) + + # Alias for "Full" + register( + id="HandManipulateBlock{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandBlockEnv", + kwargs=_merge({"target_position": "random", "target_rotation": "xyz"}, kwargs), + max_episode_steps=100, + ) + + register( + id="HandManipulateBlockTouchSensors{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandBlockTouchSensorsEnv", + kwargs=_merge( + { + "target_position": "random", + "target_rotation": "xyz", + "touch_get_obs": "boolean", + }, + kwargs, + ), + max_episode_steps=100, + ) + + register( + id="HandManipulateBlockTouchSensors{}-v1".format(suffix), + entry_point="gym.envs.robotics:HandBlockTouchSensorsEnv", + kwargs=_merge( + { + "target_position": "random", + "target_rotation": "xyz", + "touch_get_obs": "sensordata", + }, + kwargs, + ), + max_episode_steps=100, + ) + + register( + id="HandManipulateEggRotate{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandEggEnv", + kwargs=_merge({"target_position": "ignore", "target_rotation": "xyz"}, kwargs), + max_episode_steps=100, + ) + + register( + id="HandManipulateEggRotateTouchSensors{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandEggTouchSensorsEnv", + kwargs=_merge( + { + "target_position": "ignore", + "target_rotation": "xyz", + "touch_get_obs": "boolean", + }, + kwargs, + ), + max_episode_steps=100, + ) + + register( + id="HandManipulateEggRotateTouchSensors{}-v1".format(suffix), + entry_point="gym.envs.robotics:HandEggTouchSensorsEnv", + kwargs=_merge( + { + "target_position": "ignore", + "target_rotation": "xyz", + "touch_get_obs": "sensordata", + }, + kwargs, + ), + max_episode_steps=100, + ) + + register( + id="HandManipulateEggFull{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandEggEnv", + kwargs=_merge({"target_position": "random", "target_rotation": "xyz"}, kwargs), + max_episode_steps=100, + ) + + # Alias for "Full" + register( + id="HandManipulateEgg{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandEggEnv", + kwargs=_merge({"target_position": "random", "target_rotation": "xyz"}, kwargs), + max_episode_steps=100, + ) + + register( + id="HandManipulateEggTouchSensors{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandEggTouchSensorsEnv", + kwargs=_merge( + { + "target_position": "random", + "target_rotation": "xyz", + "touch_get_obs": "boolean", + }, + kwargs, + ), + max_episode_steps=100, + ) + + register( + id="HandManipulateEggTouchSensors{}-v1".format(suffix), + entry_point="gym.envs.robotics:HandEggTouchSensorsEnv", + kwargs=_merge( + { + "target_position": "random", + "target_rotation": "xyz", + "touch_get_obs": "sensordata", + }, + kwargs, + ), + max_episode_steps=100, + ) + + register( + id="HandManipulatePenRotate{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandPenEnv", + kwargs=_merge({"target_position": "ignore", "target_rotation": "xyz"}, kwargs), + max_episode_steps=100, + ) + + register( + id="HandManipulatePenRotateTouchSensors{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandPenTouchSensorsEnv", + kwargs=_merge( + { + "target_position": "ignore", + "target_rotation": "xyz", + "touch_get_obs": "boolean", + }, + kwargs, + ), + max_episode_steps=100, + ) + + register( + id="HandManipulatePenRotateTouchSensors{}-v1".format(suffix), + entry_point="gym.envs.robotics:HandPenTouchSensorsEnv", + kwargs=_merge( + { + "target_position": "ignore", + "target_rotation": "xyz", + "touch_get_obs": "sensordata", + }, + kwargs, + ), + max_episode_steps=100, + ) + + register( + id="HandManipulatePenFull{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandPenEnv", + kwargs=_merge({"target_position": "random", "target_rotation": "xyz"}, kwargs), + max_episode_steps=100, + ) + + # Alias for "Full" + register( + id="HandManipulatePen{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandPenEnv", + kwargs=_merge({"target_position": "random", "target_rotation": "xyz"}, kwargs), + max_episode_steps=100, + ) + + register( + id="HandManipulatePenTouchSensors{}-v0".format(suffix), + entry_point="gym.envs.robotics:HandPenTouchSensorsEnv", + kwargs=_merge( + { + "target_position": "random", + "target_rotation": "xyz", + "touch_get_obs": "boolean", + }, + kwargs, + ), + max_episode_steps=100, + ) + + register( + id="HandManipulatePenTouchSensors{}-v1".format(suffix), + entry_point="gym.envs.robotics:HandPenTouchSensorsEnv", + kwargs=_merge( + { + "target_position": "random", + "target_rotation": "xyz", + "touch_get_obs": "sensordata", + }, + kwargs, + ), + max_episode_steps=100, + ) + +# Unit test +# --------- + +register( + id="CubeCrash-v0", + entry_point="gym.envs.unittest:CubeCrash", + reward_threshold=0.9, +) +register( + id="CubeCrashSparse-v0", + entry_point="gym.envs.unittest:CubeCrashSparse", + reward_threshold=0.9, +) +register( + id="CubeCrashScreenBecomesBlack-v0", + entry_point="gym.envs.unittest:CubeCrashScreenBecomesBlack", + reward_threshold=0.9, +) + +register( + id="MemorizeDigits-v0", + entry_point="gym.envs.unittest:MemorizeDigits", + reward_threshold=20, +) diff --git a/gym/envs/__pycache__/__init__.cpython-39.pyc b/gym/envs/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dbff8f05d3332deec7fca316de0d373093c9e40 Binary files /dev/null and b/gym/envs/__pycache__/__init__.cpython-39.pyc differ diff --git a/gym/envs/__pycache__/registration.cpython-39.pyc b/gym/envs/__pycache__/registration.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c026f52d3075df6b63fc51e02caeffa028003d7 Binary files /dev/null and b/gym/envs/__pycache__/registration.cpython-39.pyc differ diff --git a/gym/envs/atari/__init__.py b/gym/envs/atari/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1ea809788086fbfc1bc97fe4001d42d70d6ec2ec --- /dev/null +++ b/gym/envs/atari/__init__.py @@ -0,0 +1 @@ +from gym.envs.atari.environment import AtariEnv diff --git a/gym/envs/atari/__pycache__/__init__.cpython-39.pyc b/gym/envs/atari/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..524c2a203acd1bba618f67ffd3190141f5cfba02 Binary files /dev/null and b/gym/envs/atari/__pycache__/__init__.cpython-39.pyc differ diff --git a/gym/envs/atari/__pycache__/environment.cpython-39.pyc b/gym/envs/atari/__pycache__/environment.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4f101d3ab9536fd7321df4aaf5aa0988a991177 Binary files /dev/null and b/gym/envs/atari/__pycache__/environment.cpython-39.pyc differ diff --git a/gym/envs/atari/environment.py b/gym/envs/atari/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..dcb8cc39c135e42ad87d13fe196ce2d21d8adf8c --- /dev/null +++ b/gym/envs/atari/environment.py @@ -0,0 +1,403 @@ +import numpy as np +import gym +import gym.logger as logger + +from gym import error, spaces +from gym import utils +from gym.utils import seeding + +from typing import Optional, Union, Tuple, Dict, Any, List + +import ale_py.roms as roms +from ale_py._ale_py import ALEInterface, ALEState, Action, LoggerMode +from ale_py.roms.utils import rom_id_to_name + + +class AtariEnv(gym.Env, utils.EzPickle): + """ + (A)rcade (L)earning (Gym) (Env)ironment. + A Gym wrapper around the Arcade Learning Environment (ALE). + """ + + # No render modes + metadata = {"render.modes": ["human", "rgb_array"]} + + def __init__( + self, + game: str = "pong", + mode: Optional[int] = None, + difficulty: Optional[int] = None, + obs_type: str = "rgb", + frameskip: Union[Tuple[int, int], int] = 4, + repeat_action_probability: float = 0.25, + full_action_space: bool = False, + render_mode: str = None, + ) -> None: + """ + Initialize the ALE for Gym. + Default parameters are taken from Machado et al., 2018. + + Args: + game: str => Game to initialize env with. + mode: Optional[int] => Game mode, see Machado et al., 2018 + difficulty: Optional[int] => Game difficulty,see Machado et al., 2018 + obs_type: str => Observation type in { 'rgb', 'grayscale', 'ram' } + frameskip: Union[Tuple[int, int], int] => + Stochastic frameskip as tuple or fixed. + repeat_action_probability: int => + Probability to repeat actions, see Machado et al., 2018 + full_action_space: bool => Use full action space? + render_mode: str => One of { 'human', 'rgb_array' }. + If `human` we'll interactively display the screen and enable + game sounds. This will lock emulation to the ROMs specified FPS + If `rgb_array` we'll return the `rgb` key in step metadata with + the current environment RGB frame. + + Note: + - The game must be installed, see ale-import-roms, or ale-py-roms. + - Frameskip values of (low, high) will enable stochastic frame skip + which will sample a random frameskip uniformly each action. + - It is recommended to enable full action space. + See Machado et al., 2018 for more details. + + References: + `Revisiting the Arcade Learning Environment: Evaluation Protocols + and Open Problems for General Agents`, Machado et al., 2018, JAIR + URL: https://jair.org/index.php/jair/article/view/11182 + """ + if obs_type == "image": + logger.warn( + 'obs_type "image" should be replaced with the image type, one of: rgb, grayscale' + ) + obs_type = "rgb" + if obs_type not in {"rgb", "grayscale", "ram"}: + raise error.Error( + f"Invalid observation type: {obs_type}. Expecting: rgb, grayscale, ram." + ) + if not ( + isinstance(frameskip, int) + or (isinstance(frameskip, tuple) and len(frameskip) == 2) + ): + raise error.Error(f"Invalid frameskip type: {frameskip}") + if render_mode is not None and render_mode not in {"rgb_array", "human"}: + raise error.Error( + f"Render mode {render_mode} not supported (rgb_array, human)." + ) + + utils.EzPickle.__init__( + self, + game, + mode, + difficulty, + obs_type, + frameskip, + repeat_action_probability, + full_action_space, + render_mode, + ) + + # Initialize ALE + self.ale = ALEInterface() + self.viewer = None + + self._game = rom_id_to_name(game) + + self._game_mode = mode + self._game_difficulty = difficulty + + self._frameskip = frameskip + self._obs_type = obs_type + self._render_mode = render_mode + + # Set logger mode to error only + self.ale.setLoggerMode(LoggerMode.Error) + # Config sticky action prob. + self.ale.setFloat("repeat_action_probability", repeat_action_probability) + + # If render mode is human we can display screen and sound + if render_mode == "human": + self.ale.setBool("display_screen", True) + self.ale.setBool("sound", True) + + # Seed + Load + self.seed() + + self._action_set = ( + self.ale.getLegalActionSet() + if full_action_space + else self.ale.getMinimalActionSet() + ) + self._action_space = spaces.Discrete(len(self._action_set)) + + # Initialize observation type + if self._obs_type == "ram": + self._obs_space = spaces.Box( + low=0, high=255, dtype=np.uint8, shape=(self.ale.getRAMSize(),) + ) + elif self._obs_type == "rgb" or self._obs_type == "grayscale": + (screen_height, screen_width) = self.ale.getScreenDims() + image_shape = ( + screen_height, + screen_width, + ) + if self._obs_type == "rgb": + image_shape += (3,) + self._obs_space = spaces.Box( + low=0, high=255, dtype=np.uint8, shape=image_shape + ) + else: + raise error.Error(f"Unrecognized observation type: {self._obs_type}") + + def seed(self, seed: Optional[int] = None) -> Tuple[int, int]: + """ + Seeds both the internal numpy rng for stochastic frame skip + as well as the ALE RNG. + + This function must also initialize the ROM and set the corresponding + mode and difficulty. `seed` may be called to initialize the environment + during deserialization by Gym so these side-effects must reside here. + + Args: + seed: int => Manually set the seed for RNG. + Returns: + tuple[int, int] => (np seed, ALE seed) + """ + self.np_random, seed1 = seeding.np_random(seed) + seed2 = seeding.hash_seed(seed1 + 1) % 2 ** 31 + + self.ale.setInt("random_seed", seed2) + + if not hasattr(roms, self._game): + raise error.Error( + f'We\'re Unable to find the game "{self._game}". Note: Gym no longer distributes ROMs. ' + f"If you own a license to use the necessary ROMs for research purposes you can download them " + f'via `pip install gym[accept-rom-license]`. Otherwise, you should try importing "{self._game}" ' + f'via the command `ale-import-roms`. If you believe this is a mistake perhaps your copy of "{self._game}" ' + "is unsupported. To check if this is the case try providing the environment variable " + "`PYTHONWARNINGS=default::ImportWarning:ale_py.roms`. For more information see: " + "https://github.com/mgbellemare/Arcade-Learning-Environment#rom-management" + ) + self.ale.loadROM(getattr(roms, self._game)) + + if self._game_mode is not None: + self.ale.setMode(self._game_mode) + if self._game_difficulty is not None: + self.ale.setDifficulty(self._game_difficulty) + + return ( + seed1, + seed2, + ) + + def step(self, action_ind: int) -> Tuple[np.ndarray, float, bool, Dict[str, Any]]: + """ + Perform one agent step, i.e., repeats `action` frameskip # of steps. + + Args: + action_ind: int => Action index to execute + + Returns: + Tuple[np.ndarray, float, bool, Dict[str, Any]] => + observation, reward, terminal, metadata + + Note: `metadata` contains the keys "lives" and "rgb" if + render_mode == 'rgb_array'. + """ + # Get action enum, terminal bool, metadata + action = self._action_set[action_ind] + terminal = self.ale.game_over() + + # If frameskip is a length 2 tuple then it's stochastic + # frameskip between [frameskip[0], frameskip[1]] uniformly. + if isinstance(self._frameskip, int): + frameskip = self._frameskip + elif isinstance(self._frameskip, tuple): + frameskip = self.np_random.randint(*self._frameskip) + else: + raise error.Error(f"Invalid frameskip type: {self._frameskip}") + + # Frameskip + reward = 0.0 + for _ in range(frameskip): + reward += self.ale.act(action) + + return self._get_obs(), reward, terminal, self._get_info() + + def reset( + self, *, seed: Optional[int] = None, return_info: bool = False + ) -> Union[Tuple[np.ndarray, Dict[str, Any]], np.ndarray]: + """ + Resets environment and returns initial observation. + """ + # Gym's new seeding API seeds on reset. + # This will cause the console to be recreated + # and loose all previous state, e.g., statistics, etc. + seeded_with = None + if seed is not None: + seeded_with = self.seed(seed) + + self.ale.reset_game() + obs = self._get_obs() + + if return_info: + info = self._get_info() + if seeded_with is not None: + info["seeds"] = seeded_with + return obs, info + else: + return obs + + def render(self, mode: str) -> None: + """ + Render is not supported by ALE. We use a paradigm similar to + Gym3 which allows you to specify `render_mode` during construction. + + For example, + gym.make("ale-py:Pong-v0", render_mode="human") + will display the ALE and maintain the proper interval to match the + FPS target set by the ROM. + """ + img = self.ale.getScreenRGB() + if mode == "rgb_array": + return img + elif mode == "human": + from gym.envs.classic_control import rendering + + if self.viewer is None: + logger.warn( + ( + "We strongly suggest supplying `render_mode` when " + "constructing your environment, e.g., gym.make(ID, render_mode='human'). " + "Using `render_mode` provides access to proper scaling, audio support, " + "and proper framerates." + ) + ) + self.viewer = rendering.SimpleImageViewer() + self.viewer.imshow(img) + return self.viewer.isopen + + def close(self) -> None: + """ + Cleanup any leftovers by the environment + """ + if self.viewer is not None: + self.viewer.close() + self.viewer = None + + def _get_obs(self) -> np.ndarray: + """ + Retreives the current observation. + This is dependent on `self._obs_type`. + """ + if self._obs_type == "ram": + return self.ale.getRAM() + elif self._obs_type == "rgb": + return self.ale.getScreenRGB() + elif self._obs_type == "grayscale": + return self.ale.getScreenGrayscale() + else: + raise error.Error(f"Unrecognized observation type: {self._obs_type}") + + def _get_info(self) -> Dict[str, Any]: + info = { + "lives": self.ale.lives(), + "episode_frame_number": self.ale.getEpisodeFrameNumber(), + "frame_number": self.ale.getFrameNumber(), + } + + if self._render_mode == "rgb_array": + info["rgb"] = self.ale.getScreenRGB() + + return info + + def get_keys_to_action(self) -> Dict[Tuple[int], Action]: + """ + Return keymapping -> actions for human play. + """ + UP = ord("w") + LEFT = ord("a") + RIGHT = ord("d") + DOWN = ord("s") + FIRE = ord(" ") + + mapping = { + Action.NOOP: (None,), + Action.UP: (UP,), + Action.FIRE: (FIRE,), + Action.DOWN: (DOWN,), + Action.LEFT: (LEFT,), + Action.RIGHT: (RIGHT,), + Action.UPFIRE: (UP, FIRE), + Action.DOWNFIRE: (DOWN, FIRE), + Action.LEFTFIRE: (LEFT, FIRE), + Action.RIGHTFIRE: (RIGHT, FIRE), + Action.UPLEFT: (UP, LEFT), + Action.UPRIGHT: (UP, RIGHT), + Action.DOWNLEFT: (DOWN, LEFT), + Action.DOWNRIGHT: (DOWN, RIGHT), + Action.UPLEFTFIRE: (UP, LEFT, FIRE), + Action.UPRIGHTFIRE: (UP, RIGHT, FIRE), + Action.DOWNLEFTFIRE: (DOWN, LEFT, FIRE), + Action.DOWNRIGHTFIRE: (DOWN, RIGHT, FIRE), + } + + # Map + # (key, key, ...) -> action_idx + # where action_idx is the integer value of the action enum + # + actions = self._action_set + return dict( + zip( + map(lambda action: tuple(sorted(mapping[action])), actions), + range(len(actions)), + ) + ) + + def get_action_meanings(self) -> List[str]: + """ + Return the meaning of each integer action. + """ + keys = Action.__members__.values() + values = Action.__members__.keys() + mapping = dict(zip(keys, values)) + return [mapping[action] for action in self._action_set] + + def clone_state(self, include_rng=False) -> ALEState: + """Clone emulator state w/o system state. Restoring this state will + *not* give an identical environment. For complete cloning and restoring + of the full state, see `{clone,restore}_full_state()`.""" + return self.ale.cloneState(include_rng=include_rng) + + def restore_state(self, state: ALEState) -> None: + """Restore emulator state w/o system state.""" + self.ale.restoreState(state) + + def clone_full_state(self) -> ALEState: + """Deprecated method which would clone the emulator and system state.""" + logger.warn( + "`clone_full_state()` is deprecated and will be removed in a future release of `ale-py`. " + "Please use `clone_state(include_rng=True)` which is equivalent to `clone_full_state`. " + ) + return self.ale.cloneSystemState() + + def restore_full_state(self, state: ALEState) -> None: + """Restore emulator state w/ system state including pseudorandomness.""" + logger.warn( + "restore_full_state() is deprecated and will be removed in a future release of `ale-py`. " + "Please use `restore_state(state)` which will restore the state regardless of being a full or partial state. " + ) + self.ale.restoreSystemState(state) + + @property + def action_space(self) -> spaces.Discrete: + """ + Return Gym's action space. + """ + return self._action_space + + @property + def observation_space(self) -> spaces.Box: + """ + Return Gym's observation space. + """ + return self._obs_space diff --git a/gym/envs/box2d/__init__.py b/gym/envs/box2d/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..46cb91d389be2debf6f60cbfb79c77be2d13fa40 --- /dev/null +++ b/gym/envs/box2d/__init__.py @@ -0,0 +1,8 @@ +try: + import Box2D + from gym.envs.box2d.lunar_lander import LunarLander + from gym.envs.box2d.lunar_lander import LunarLanderContinuous + from gym.envs.box2d.bipedal_walker import BipedalWalker, BipedalWalkerHardcore + from gym.envs.box2d.car_racing import CarRacing +except ImportError: + Box2D = None diff --git a/gym/envs/box2d/__pycache__/__init__.cpython-39.pyc b/gym/envs/box2d/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f924334678e2e0f67689031da8d5fed6f8c4c9a6 Binary files /dev/null and b/gym/envs/box2d/__pycache__/__init__.cpython-39.pyc differ diff --git a/gym/envs/box2d/__pycache__/bipedal_walker.cpython-39.pyc b/gym/envs/box2d/__pycache__/bipedal_walker.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9b7edb83b8daa6d803f4bef8fe0df691b4db6f0 Binary files /dev/null and b/gym/envs/box2d/__pycache__/bipedal_walker.cpython-39.pyc differ diff --git a/gym/envs/box2d/__pycache__/car_dynamics.cpython-39.pyc b/gym/envs/box2d/__pycache__/car_dynamics.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0379d7b9fd705fb273bd2c56d07ea48d084a37ee Binary files /dev/null and b/gym/envs/box2d/__pycache__/car_dynamics.cpython-39.pyc differ diff --git a/gym/envs/box2d/__pycache__/car_racing.cpython-39.pyc b/gym/envs/box2d/__pycache__/car_racing.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..754729e61c92d83f6fbe21159b04d63157baa682 Binary files /dev/null and b/gym/envs/box2d/__pycache__/car_racing.cpython-39.pyc differ diff --git a/gym/envs/box2d/__pycache__/lunar_lander.cpython-39.pyc b/gym/envs/box2d/__pycache__/lunar_lander.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d32ddfd69d14642dfb7eecc991e5129337eb7942 Binary files /dev/null and b/gym/envs/box2d/__pycache__/lunar_lander.cpython-39.pyc differ diff --git a/gym/envs/box2d/bipedal_walker.py b/gym/envs/box2d/bipedal_walker.py new file mode 100644 index 0000000000000000000000000000000000000000..34b564f217c13d0b76138bc5eba021cdba3718d1 --- /dev/null +++ b/gym/envs/box2d/bipedal_walker.py @@ -0,0 +1,658 @@ +import sys +import math + +import numpy as np +import Box2D +from Box2D.b2 import ( + edgeShape, + circleShape, + fixtureDef, + polygonShape, + revoluteJointDef, + contactListener, +) + +import gym +from gym import spaces +from gym.utils import colorize, seeding, EzPickle + +# This is simple 4-joints walker robot environment. +# +# There are two versions: +# +# - Normal, with slightly uneven terrain. +# +# - Hardcore with ladders, stumps, pitfalls. +# +# Reward is given for moving forward, total 300+ points up to the far end. If the robot falls, +# it gets -100. Applying motor torque costs a small amount of points, more optimal agent +# will get better score. +# +# Heuristic is provided for testing, it's also useful to get demonstrations to +# learn from. To run heuristic: +# +# python gym/envs/box2d/bipedal_walker.py +# +# State consists of hull angle speed, angular velocity, horizontal speed, vertical speed, +# position of joints and joints angular speed, legs contact with ground, and 10 lidar +# rangefinder measurements to help to deal with the hardcore version. There's no coordinates +# in the state vector. Lidar is less useful in normal version, but it works. +# +# To solve the game you need to get 300 points in 1600 time steps. +# +# To solve hardcore version you need 300 points in 2000 time steps. +# +# Created by Oleg Klimov. Licensed on the same terms as the rest of OpenAI Gym. + +FPS = 50 +SCALE = 30.0 # affects how fast-paced the game is, forces should be adjusted as well + +MOTORS_TORQUE = 80 +SPEED_HIP = 4 +SPEED_KNEE = 6 +LIDAR_RANGE = 160 / SCALE + +INITIAL_RANDOM = 5 + +HULL_POLY = [(-30, +9), (+6, +9), (+34, +1), (+34, -8), (-30, -8)] +LEG_DOWN = -8 / SCALE +LEG_W, LEG_H = 8 / SCALE, 34 / SCALE + +VIEWPORT_W = 600 +VIEWPORT_H = 400 + +TERRAIN_STEP = 14 / SCALE +TERRAIN_LENGTH = 200 # in steps +TERRAIN_HEIGHT = VIEWPORT_H / SCALE / 4 +TERRAIN_GRASS = 10 # low long are grass spots, in steps +TERRAIN_STARTPAD = 20 # in steps +FRICTION = 2.5 + +HULL_FD = fixtureDef( + shape=polygonShape(vertices=[(x / SCALE, y / SCALE) for x, y in HULL_POLY]), + density=5.0, + friction=0.1, + categoryBits=0x0020, + maskBits=0x001, # collide only with ground + restitution=0.0, +) # 0.99 bouncy + +LEG_FD = fixtureDef( + shape=polygonShape(box=(LEG_W / 2, LEG_H / 2)), + density=1.0, + restitution=0.0, + categoryBits=0x0020, + maskBits=0x001, +) + +LOWER_FD = fixtureDef( + shape=polygonShape(box=(0.8 * LEG_W / 2, LEG_H / 2)), + density=1.0, + restitution=0.0, + categoryBits=0x0020, + maskBits=0x001, +) + + +class ContactDetector(contactListener): + def __init__(self, env): + contactListener.__init__(self) + self.env = env + + def BeginContact(self, contact): + if ( + self.env.hull == contact.fixtureA.body + or self.env.hull == contact.fixtureB.body + ): + self.env.game_over = True + for leg in [self.env.legs[1], self.env.legs[3]]: + if leg in [contact.fixtureA.body, contact.fixtureB.body]: + leg.ground_contact = True + + def EndContact(self, contact): + for leg in [self.env.legs[1], self.env.legs[3]]: + if leg in [contact.fixtureA.body, contact.fixtureB.body]: + leg.ground_contact = False + + +class BipedalWalker(gym.Env, EzPickle): + metadata = {"render.modes": ["human", "rgb_array"], "video.frames_per_second": FPS} + + hardcore = False + + def __init__(self): + EzPickle.__init__(self) + self.seed() + self.viewer = None + + self.world = Box2D.b2World() + self.terrain = None + self.hull = None + + self.prev_shaping = None + + self.fd_polygon = fixtureDef( + shape=polygonShape(vertices=[(0, 0), (1, 0), (1, -1), (0, -1)]), + friction=FRICTION, + ) + + self.fd_edge = fixtureDef( + shape=edgeShape(vertices=[(0, 0), (1, 1)]), + friction=FRICTION, + categoryBits=0x0001, + ) + + high = np.array([np.inf] * 24).astype(np.float32) + self.action_space = spaces.Box( + np.array([-1, -1, -1, -1]).astype(np.float32), + np.array([1, 1, 1, 1]).astype(np.float32), + ) + self.observation_space = spaces.Box(-high, high) + + def seed(self, seed=None): + self.np_random, seed = seeding.np_random(seed) + return [seed] + + def _destroy(self): + if not self.terrain: + return + self.world.contactListener = None + for t in self.terrain: + self.world.DestroyBody(t) + self.terrain = [] + self.world.DestroyBody(self.hull) + self.hull = None + for leg in self.legs: + self.world.DestroyBody(leg) + self.legs = [] + self.joints = [] + + def _generate_terrain(self, hardcore): + GRASS, STUMP, STAIRS, PIT, _STATES_ = range(5) + state = GRASS + velocity = 0.0 + y = TERRAIN_HEIGHT + counter = TERRAIN_STARTPAD + oneshot = False + self.terrain = [] + self.terrain_x = [] + self.terrain_y = [] + for i in range(TERRAIN_LENGTH): + x = i * TERRAIN_STEP + self.terrain_x.append(x) + + if state == GRASS and not oneshot: + velocity = 0.8 * velocity + 0.01 * np.sign(TERRAIN_HEIGHT - y) + if i > TERRAIN_STARTPAD: + velocity += self.np_random.uniform(-1, 1) / SCALE # 1 + y += velocity + + elif state == PIT and oneshot: + counter = self.np_random.randint(3, 5) + poly = [ + (x, y), + (x + TERRAIN_STEP, y), + (x + TERRAIN_STEP, y - 4 * TERRAIN_STEP), + (x, y - 4 * TERRAIN_STEP), + ] + self.fd_polygon.shape.vertices = poly + t = self.world.CreateStaticBody(fixtures=self.fd_polygon) + t.color1, t.color2 = (1, 1, 1), (0.6, 0.6, 0.6) + self.terrain.append(t) + + self.fd_polygon.shape.vertices = [ + (p[0] + TERRAIN_STEP * counter, p[1]) for p in poly + ] + t = self.world.CreateStaticBody(fixtures=self.fd_polygon) + t.color1, t.color2 = (1, 1, 1), (0.6, 0.6, 0.6) + self.terrain.append(t) + counter += 2 + original_y = y + + elif state == PIT and not oneshot: + y = original_y + if counter > 1: + y -= 4 * TERRAIN_STEP + + elif state == STUMP and oneshot: + counter = self.np_random.randint(1, 3) + poly = [ + (x, y), + (x + counter * TERRAIN_STEP, y), + (x + counter * TERRAIN_STEP, y + counter * TERRAIN_STEP), + (x, y + counter * TERRAIN_STEP), + ] + self.fd_polygon.shape.vertices = poly + t = self.world.CreateStaticBody(fixtures=self.fd_polygon) + t.color1, t.color2 = (1, 1, 1), (0.6, 0.6, 0.6) + self.terrain.append(t) + + elif state == STAIRS and oneshot: + stair_height = +1 if self.np_random.rand() > 0.5 else -1 + stair_width = self.np_random.randint(4, 5) + stair_steps = self.np_random.randint(3, 5) + original_y = y + for s in range(stair_steps): + poly = [ + ( + x + (s * stair_width) * TERRAIN_STEP, + y + (s * stair_height) * TERRAIN_STEP, + ), + ( + x + ((1 + s) * stair_width) * TERRAIN_STEP, + y + (s * stair_height) * TERRAIN_STEP, + ), + ( + x + ((1 + s) * stair_width) * TERRAIN_STEP, + y + (-1 + s * stair_height) * TERRAIN_STEP, + ), + ( + x + (s * stair_width) * TERRAIN_STEP, + y + (-1 + s * stair_height) * TERRAIN_STEP, + ), + ] + self.fd_polygon.shape.vertices = poly + t = self.world.CreateStaticBody(fixtures=self.fd_polygon) + t.color1, t.color2 = (1, 1, 1), (0.6, 0.6, 0.6) + self.terrain.append(t) + counter = stair_steps * stair_width + + elif state == STAIRS and not oneshot: + s = stair_steps * stair_width - counter - stair_height + n = s / stair_width + y = original_y + (n * stair_height) * TERRAIN_STEP + + oneshot = False + self.terrain_y.append(y) + counter -= 1 + if counter == 0: + counter = self.np_random.randint(TERRAIN_GRASS / 2, TERRAIN_GRASS) + if state == GRASS and hardcore: + state = self.np_random.randint(1, _STATES_) + oneshot = True + else: + state = GRASS + oneshot = True + + self.terrain_poly = [] + for i in range(TERRAIN_LENGTH - 1): + poly = [ + (self.terrain_x[i], self.terrain_y[i]), + (self.terrain_x[i + 1], self.terrain_y[i + 1]), + ] + self.fd_edge.shape.vertices = poly + t = self.world.CreateStaticBody(fixtures=self.fd_edge) + color = (0.3, 1.0 if i % 2 == 0 else 0.8, 0.3) + t.color1 = color + t.color2 = color + self.terrain.append(t) + color = (0.4, 0.6, 0.3) + poly += [(poly[1][0], 0), (poly[0][0], 0)] + self.terrain_poly.append((poly, color)) + self.terrain.reverse() + + def _generate_clouds(self): + # Sorry for the clouds, couldn't resist + self.cloud_poly = [] + for i in range(TERRAIN_LENGTH // 20): + x = self.np_random.uniform(0, TERRAIN_LENGTH) * TERRAIN_STEP + y = VIEWPORT_H / SCALE * 3 / 4 + poly = [ + ( + x + + 15 * TERRAIN_STEP * math.sin(3.14 * 2 * a / 5) + + self.np_random.uniform(0, 5 * TERRAIN_STEP), + y + + 5 * TERRAIN_STEP * math.cos(3.14 * 2 * a / 5) + + self.np_random.uniform(0, 5 * TERRAIN_STEP), + ) + for a in range(5) + ] + x1 = min([p[0] for p in poly]) + x2 = max([p[0] for p in poly]) + self.cloud_poly.append((poly, x1, x2)) + + def reset(self): + self._destroy() + self.world.contactListener_bug_workaround = ContactDetector(self) + self.world.contactListener = self.world.contactListener_bug_workaround + self.game_over = False + self.prev_shaping = None + self.scroll = 0.0 + self.lidar_render = 0 + + W = VIEWPORT_W / SCALE + H = VIEWPORT_H / SCALE + + self._generate_terrain(self.hardcore) + self._generate_clouds() + + init_x = TERRAIN_STEP * TERRAIN_STARTPAD / 2 + init_y = TERRAIN_HEIGHT + 2 * LEG_H + self.hull = self.world.CreateDynamicBody( + position=(init_x, init_y), fixtures=HULL_FD + ) + self.hull.color1 = (0.5, 0.4, 0.9) + self.hull.color2 = (0.3, 0.3, 0.5) + self.hull.ApplyForceToCenter( + (self.np_random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM), 0), True + ) + + self.legs = [] + self.joints = [] + for i in [-1, +1]: + leg = self.world.CreateDynamicBody( + position=(init_x, init_y - LEG_H / 2 - LEG_DOWN), + angle=(i * 0.05), + fixtures=LEG_FD, + ) + leg.color1 = (0.6 - i / 10.0, 0.3 - i / 10.0, 0.5 - i / 10.0) + leg.color2 = (0.4 - i / 10.0, 0.2 - i / 10.0, 0.3 - i / 10.0) + rjd = revoluteJointDef( + bodyA=self.hull, + bodyB=leg, + localAnchorA=(0, LEG_DOWN), + localAnchorB=(0, LEG_H / 2), + enableMotor=True, + enableLimit=True, + maxMotorTorque=MOTORS_TORQUE, + motorSpeed=i, + lowerAngle=-0.8, + upperAngle=1.1, + ) + self.legs.append(leg) + self.joints.append(self.world.CreateJoint(rjd)) + + lower = self.world.CreateDynamicBody( + position=(init_x, init_y - LEG_H * 3 / 2 - LEG_DOWN), + angle=(i * 0.05), + fixtures=LOWER_FD, + ) + lower.color1 = (0.6 - i / 10.0, 0.3 - i / 10.0, 0.5 - i / 10.0) + lower.color2 = (0.4 - i / 10.0, 0.2 - i / 10.0, 0.3 - i / 10.0) + rjd = revoluteJointDef( + bodyA=leg, + bodyB=lower, + localAnchorA=(0, -LEG_H / 2), + localAnchorB=(0, LEG_H / 2), + enableMotor=True, + enableLimit=True, + maxMotorTorque=MOTORS_TORQUE, + motorSpeed=1, + lowerAngle=-1.6, + upperAngle=-0.1, + ) + lower.ground_contact = False + self.legs.append(lower) + self.joints.append(self.world.CreateJoint(rjd)) + + self.drawlist = self.terrain + self.legs + [self.hull] + + class LidarCallback(Box2D.b2.rayCastCallback): + def ReportFixture(self, fixture, point, normal, fraction): + if (fixture.filterData.categoryBits & 1) == 0: + return -1 + self.p2 = point + self.fraction = fraction + return fraction + + self.lidar = [LidarCallback() for _ in range(10)] + + return self.step(np.array([0, 0, 0, 0]))[0] + + def step(self, action): + # self.hull.ApplyForceToCenter((0, 20), True) -- Uncomment this to receive a bit of stability help + control_speed = False # Should be easier as well + if control_speed: + self.joints[0].motorSpeed = float(SPEED_HIP * np.clip(action[0], -1, 1)) + self.joints[1].motorSpeed = float(SPEED_KNEE * np.clip(action[1], -1, 1)) + self.joints[2].motorSpeed = float(SPEED_HIP * np.clip(action[2], -1, 1)) + self.joints[3].motorSpeed = float(SPEED_KNEE * np.clip(action[3], -1, 1)) + else: + self.joints[0].motorSpeed = float(SPEED_HIP * np.sign(action[0])) + self.joints[0].maxMotorTorque = float( + MOTORS_TORQUE * np.clip(np.abs(action[0]), 0, 1) + ) + self.joints[1].motorSpeed = float(SPEED_KNEE * np.sign(action[1])) + self.joints[1].maxMotorTorque = float( + MOTORS_TORQUE * np.clip(np.abs(action[1]), 0, 1) + ) + self.joints[2].motorSpeed = float(SPEED_HIP * np.sign(action[2])) + self.joints[2].maxMotorTorque = float( + MOTORS_TORQUE * np.clip(np.abs(action[2]), 0, 1) + ) + self.joints[3].motorSpeed = float(SPEED_KNEE * np.sign(action[3])) + self.joints[3].maxMotorTorque = float( + MOTORS_TORQUE * np.clip(np.abs(action[3]), 0, 1) + ) + + self.world.Step(1.0 / FPS, 6 * 30, 2 * 30) + + pos = self.hull.position + vel = self.hull.linearVelocity + + for i in range(10): + self.lidar[i].fraction = 1.0 + self.lidar[i].p1 = pos + self.lidar[i].p2 = ( + pos[0] + math.sin(1.5 * i / 10.0) * LIDAR_RANGE, + pos[1] - math.cos(1.5 * i / 10.0) * LIDAR_RANGE, + ) + self.world.RayCast(self.lidar[i], self.lidar[i].p1, self.lidar[i].p2) + + state = [ + self.hull.angle, # Normal angles up to 0.5 here, but sure more is possible. + 2.0 * self.hull.angularVelocity / FPS, + 0.3 * vel.x * (VIEWPORT_W / SCALE) / FPS, # Normalized to get -1..1 range + 0.3 * vel.y * (VIEWPORT_H / SCALE) / FPS, + self.joints[ + 0 + ].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) + self.joints[0].speed / SPEED_HIP, + self.joints[1].angle + 1.0, + self.joints[1].speed / SPEED_KNEE, + 1.0 if self.legs[1].ground_contact else 0.0, + self.joints[2].angle, + self.joints[2].speed / SPEED_HIP, + self.joints[3].angle + 1.0, + self.joints[3].speed / SPEED_KNEE, + 1.0 if self.legs[3].ground_contact else 0.0, + ] + state += [l.fraction for l in self.lidar] + assert len(state) == 24 + + self.scroll = pos.x - VIEWPORT_W / SCALE / 5 + + shaping = ( + 130 * pos[0] / SCALE + ) # moving forward is a way to receive reward (normalized to get 300 on completion) + shaping -= 5.0 * abs( + state[0] + ) # keep head straight, other than that and falling, any behavior is unpunished + + reward = 0 + if self.prev_shaping is not None: + reward = shaping - self.prev_shaping + self.prev_shaping = shaping + + for a in action: + reward -= 0.00035 * MOTORS_TORQUE * np.clip(np.abs(a), 0, 1) + # normalized to about -50.0 using heuristic, more optimal agent should spend less + + done = False + if self.game_over or pos[0] < 0: + reward = -100 + done = True + if pos[0] > (TERRAIN_LENGTH - TERRAIN_GRASS) * TERRAIN_STEP: + done = True + return np.array(state, dtype=np.float32), reward, done, {} + + def render(self, mode="human"): + from gym.envs.classic_control import rendering + + if self.viewer is None: + self.viewer = rendering.Viewer(VIEWPORT_W, VIEWPORT_H) + self.viewer.set_bounds( + self.scroll, VIEWPORT_W / SCALE + self.scroll, 0, VIEWPORT_H / SCALE + ) + + self.viewer.draw_polygon( + [ + (self.scroll, 0), + (self.scroll + VIEWPORT_W / SCALE, 0), + (self.scroll + VIEWPORT_W / SCALE, VIEWPORT_H / SCALE), + (self.scroll, VIEWPORT_H / SCALE), + ], + color=(0.9, 0.9, 1.0), + ) + for poly, x1, x2 in self.cloud_poly: + if x2 < self.scroll / 2: + continue + if x1 > self.scroll / 2 + VIEWPORT_W / SCALE: + continue + self.viewer.draw_polygon( + [(p[0] + self.scroll / 2, p[1]) for p in poly], color=(1, 1, 1) + ) + for poly, color in self.terrain_poly: + if poly[1][0] < self.scroll: + continue + if poly[0][0] > self.scroll + VIEWPORT_W / SCALE: + continue + self.viewer.draw_polygon(poly, color=color) + + self.lidar_render = (self.lidar_render + 1) % 100 + i = self.lidar_render + if i < 2 * len(self.lidar): + l = ( + self.lidar[i] + if i < len(self.lidar) + else self.lidar[len(self.lidar) - i - 1] + ) + self.viewer.draw_polyline([l.p1, l.p2], color=(1, 0, 0), linewidth=1) + + for obj in self.drawlist: + for f in obj.fixtures: + trans = f.body.transform + if type(f.shape) is circleShape: + t = rendering.Transform(translation=trans * f.shape.pos) + self.viewer.draw_circle( + f.shape.radius, 30, color=obj.color1 + ).add_attr(t) + self.viewer.draw_circle( + f.shape.radius, 30, color=obj.color2, filled=False, linewidth=2 + ).add_attr(t) + else: + path = [trans * v for v in f.shape.vertices] + self.viewer.draw_polygon(path, color=obj.color1) + path.append(path[0]) + self.viewer.draw_polyline(path, color=obj.color2, linewidth=2) + + flagy1 = TERRAIN_HEIGHT + flagy2 = flagy1 + 50 / SCALE + x = TERRAIN_STEP * 3 + self.viewer.draw_polyline( + [(x, flagy1), (x, flagy2)], color=(0, 0, 0), linewidth=2 + ) + f = [ + (x, flagy2), + (x, flagy2 - 10 / SCALE), + (x + 25 / SCALE, flagy2 - 5 / SCALE), + ] + self.viewer.draw_polygon(f, color=(0.9, 0.2, 0)) + self.viewer.draw_polyline(f + [f[0]], color=(0, 0, 0), linewidth=2) + + return self.viewer.render(return_rgb_array=mode == "rgb_array") + + def close(self): + if self.viewer is not None: + self.viewer.close() + self.viewer = None + + +class BipedalWalkerHardcore(BipedalWalker): + hardcore = True + + +if __name__ == "__main__": + # Heurisic: suboptimal, have no notion of balance. + env = BipedalWalker() + env.reset() + steps = 0 + total_reward = 0 + a = np.array([0.0, 0.0, 0.0, 0.0]) + STAY_ON_ONE_LEG, PUT_OTHER_DOWN, PUSH_OFF = 1, 2, 3 + SPEED = 0.29 # Will fall forward on higher speed + state = STAY_ON_ONE_LEG + moving_leg = 0 + supporting_leg = 1 - moving_leg + SUPPORT_KNEE_ANGLE = +0.1 + supporting_knee_angle = SUPPORT_KNEE_ANGLE + while True: + s, r, done, info = env.step(a) + total_reward += r + if steps % 20 == 0 or done: + print("\naction " + str(["{:+0.2f}".format(x) for x in a])) + print("step {} total_reward {:+0.2f}".format(steps, total_reward)) + print("hull " + str(["{:+0.2f}".format(x) for x in s[0:4]])) + print("leg0 " + str(["{:+0.2f}".format(x) for x in s[4:9]])) + print("leg1 " + str(["{:+0.2f}".format(x) for x in s[9:14]])) + steps += 1 + + contact0 = s[8] + contact1 = s[13] + moving_s_base = 4 + 5 * moving_leg + supporting_s_base = 4 + 5 * supporting_leg + + hip_targ = [None, None] # -0.8 .. +1.1 + knee_targ = [None, None] # -0.6 .. +0.9 + hip_todo = [0.0, 0.0] + knee_todo = [0.0, 0.0] + + if state == STAY_ON_ONE_LEG: + hip_targ[moving_leg] = 1.1 + knee_targ[moving_leg] = -0.6 + supporting_knee_angle += 0.03 + if s[2] > SPEED: + supporting_knee_angle += 0.03 + supporting_knee_angle = min(supporting_knee_angle, SUPPORT_KNEE_ANGLE) + knee_targ[supporting_leg] = supporting_knee_angle + if s[supporting_s_base + 0] < 0.10: # supporting leg is behind + state = PUT_OTHER_DOWN + if state == PUT_OTHER_DOWN: + hip_targ[moving_leg] = +0.1 + knee_targ[moving_leg] = SUPPORT_KNEE_ANGLE + knee_targ[supporting_leg] = supporting_knee_angle + if s[moving_s_base + 4]: + state = PUSH_OFF + supporting_knee_angle = min(s[moving_s_base + 2], SUPPORT_KNEE_ANGLE) + if state == PUSH_OFF: + knee_targ[moving_leg] = supporting_knee_angle + knee_targ[supporting_leg] = +1.0 + if s[supporting_s_base + 2] > 0.88 or s[2] > 1.2 * SPEED: + state = STAY_ON_ONE_LEG + moving_leg = 1 - moving_leg + supporting_leg = 1 - moving_leg + + if hip_targ[0]: + hip_todo[0] = 0.9 * (hip_targ[0] - s[4]) - 0.25 * s[5] + if hip_targ[1]: + hip_todo[1] = 0.9 * (hip_targ[1] - s[9]) - 0.25 * s[10] + if knee_targ[0]: + knee_todo[0] = 4.0 * (knee_targ[0] - s[6]) - 0.25 * s[7] + if knee_targ[1]: + knee_todo[1] = 4.0 * (knee_targ[1] - s[11]) - 0.25 * s[12] + + hip_todo[0] -= 0.9 * (0 - s[0]) - 1.5 * s[1] # PID to keep head strait + hip_todo[1] -= 0.9 * (0 - s[0]) - 1.5 * s[1] + knee_todo[0] -= 15.0 * s[3] # vertical speed, to damp oscillations + knee_todo[1] -= 15.0 * s[3] + + a[0] = hip_todo[0] + a[1] = knee_todo[0] + a[2] = hip_todo[1] + a[3] = knee_todo[1] + a = np.clip(0.5 * a, -1.0, 1.0) + + env.render() + if done: + break diff --git a/gym/envs/box2d/car_dynamics.py b/gym/envs/box2d/car_dynamics.py new file mode 100644 index 0000000000000000000000000000000000000000..756e1e179eb623d9ccae0f9bf12007a51b609bd9 --- /dev/null +++ b/gym/envs/box2d/car_dynamics.py @@ -0,0 +1,313 @@ +""" +Top-down car dynamics simulation. + +Some ideas are taken from this great tutorial http://www.iforce2d.net/b2dtut/top-down-car by Chris Campbell. +This simulation is a bit more detailed, with wheels rotation. + +Created by Oleg Klimov. Licensed on the same terms as the rest of OpenAI Gym. +""" + +import numpy as np +import math +import Box2D +from Box2D.b2 import ( + edgeShape, + circleShape, + fixtureDef, + polygonShape, + revoluteJointDef, + contactListener, + shape, +) + +SIZE = 0.02 +ENGINE_POWER = 100000000 * SIZE * SIZE +WHEEL_MOMENT_OF_INERTIA = 4000 * SIZE * SIZE +FRICTION_LIMIT = ( + 1000000 * SIZE * SIZE +) # friction ~= mass ~= size^2 (calculated implicitly using density) +WHEEL_R = 27 +WHEEL_W = 14 +WHEELPOS = [(-55, +80), (+55, +80), (-55, -82), (+55, -82)] +HULL_POLY1 = [(-60, +130), (+60, +130), (+60, +110), (-60, +110)] +HULL_POLY2 = [(-15, +120), (+15, +120), (+20, +20), (-20, 20)] +HULL_POLY3 = [ + (+25, +20), + (+50, -10), + (+50, -40), + (+20, -90), + (-20, -90), + (-50, -40), + (-50, -10), + (-25, +20), +] +HULL_POLY4 = [(-50, -120), (+50, -120), (+50, -90), (-50, -90)] +WHEEL_COLOR = (0.0, 0.0, 0.0) +WHEEL_WHITE = (0.3, 0.3, 0.3) +MUD_COLOR = (0.4, 0.4, 0.0) + + +class Car: + def __init__(self, world, init_angle, init_x, init_y): + self.world = world + self.hull = self.world.CreateDynamicBody( + position=(init_x, init_y), + angle=init_angle, + fixtures=[ + fixtureDef( + shape=polygonShape( + vertices=[(x * SIZE, y * SIZE) for x, y in HULL_POLY1] + ), + density=1.0, + ), + fixtureDef( + shape=polygonShape( + vertices=[(x * SIZE, y * SIZE) for x, y in HULL_POLY2] + ), + density=1.0, + ), + fixtureDef( + shape=polygonShape( + vertices=[(x * SIZE, y * SIZE) for x, y in HULL_POLY3] + ), + density=1.0, + ), + fixtureDef( + shape=polygonShape( + vertices=[(x * SIZE, y * SIZE) for x, y in HULL_POLY4] + ), + density=1.0, + ), + ], + ) + self.hull.color = (0.8, 0.0, 0.0) + self.wheels = [] + self.fuel_spent = 0.0 + WHEEL_POLY = [ + (-WHEEL_W, +WHEEL_R), + (+WHEEL_W, +WHEEL_R), + (+WHEEL_W, -WHEEL_R), + (-WHEEL_W, -WHEEL_R), + ] + for wx, wy in WHEELPOS: + front_k = 1.0 if wy > 0 else 1.0 + w = self.world.CreateDynamicBody( + position=(init_x + wx * SIZE, init_y + wy * SIZE), + angle=init_angle, + fixtures=fixtureDef( + shape=polygonShape( + vertices=[ + (x * front_k * SIZE, y * front_k * SIZE) + for x, y in WHEEL_POLY + ] + ), + density=0.1, + categoryBits=0x0020, + maskBits=0x001, + restitution=0.0, + ), + ) + w.wheel_rad = front_k * WHEEL_R * SIZE + w.color = WHEEL_COLOR + w.gas = 0.0 + w.brake = 0.0 + w.steer = 0.0 + w.phase = 0.0 # wheel angle + w.omega = 0.0 # angular velocity + w.skid_start = None + w.skid_particle = None + rjd = revoluteJointDef( + bodyA=self.hull, + bodyB=w, + localAnchorA=(wx * SIZE, wy * SIZE), + localAnchorB=(0, 0), + enableMotor=True, + enableLimit=True, + maxMotorTorque=180 * 900 * SIZE * SIZE, + motorSpeed=0, + lowerAngle=-0.4, + upperAngle=+0.4, + ) + w.joint = self.world.CreateJoint(rjd) + w.tiles = set() + w.userData = w + self.wheels.append(w) + self.drawlist = self.wheels + [self.hull] + self.particles = [] + + def gas(self, gas): + """control: rear wheel drive + + Args: + gas (float): How much gas gets applied. Gets clipped between 0 and 1. + """ + gas = np.clip(gas, 0, 1) + for w in self.wheels[2:4]: + diff = gas - w.gas + if diff > 0.1: + diff = 0.1 # gradually increase, but stop immediately + w.gas += diff + + def brake(self, b): + """control: brake + + Args: + b (0..1): Degree to which the brakes are applied. More than 0.9 blocks the wheels to zero rotation""" + for w in self.wheels: + w.brake = b + + def steer(self, s): + """control: steer + + Args: + s (-1..1): target position, it takes time to rotate steering wheel from side-to-side""" + self.wheels[0].steer = s + self.wheels[1].steer = s + + def step(self, dt): + for w in self.wheels: + # Steer each wheel + dir = np.sign(w.steer - w.joint.angle) + val = abs(w.steer - w.joint.angle) + w.joint.motorSpeed = dir * min(50.0 * val, 3.0) + + # Position => friction_limit + grass = True + friction_limit = FRICTION_LIMIT * 0.6 # Grass friction if no tile + for tile in w.tiles: + friction_limit = max( + friction_limit, FRICTION_LIMIT * tile.road_friction + ) + grass = False + + # Force + forw = w.GetWorldVector((0, 1)) + side = w.GetWorldVector((1, 0)) + v = w.linearVelocity + vf = forw[0] * v[0] + forw[1] * v[1] # forward speed + vs = side[0] * v[0] + side[1] * v[1] # side speed + + # WHEEL_MOMENT_OF_INERTIA*np.square(w.omega)/2 = E -- energy + # WHEEL_MOMENT_OF_INERTIA*w.omega * domega/dt = dE/dt = W -- power + # domega = dt*W/WHEEL_MOMENT_OF_INERTIA/w.omega + + # add small coef not to divide by zero + w.omega += ( + dt + * ENGINE_POWER + * w.gas + / WHEEL_MOMENT_OF_INERTIA + / (abs(w.omega) + 5.0) + ) + self.fuel_spent += dt * ENGINE_POWER * w.gas + + if w.brake >= 0.9: + w.omega = 0 + elif w.brake > 0: + BRAKE_FORCE = 15 # radians per second + dir = -np.sign(w.omega) + val = BRAKE_FORCE * w.brake + if abs(val) > abs(w.omega): + val = abs(w.omega) # low speed => same as = 0 + w.omega += dir * val + w.phase += w.omega * dt + + vr = w.omega * w.wheel_rad # rotating wheel speed + f_force = -vf + vr # force direction is direction of speed difference + p_force = -vs + + # Physically correct is to always apply friction_limit until speed is equal. + # But dt is finite, that will lead to oscillations if difference is already near zero. + + # Random coefficient to cut oscillations in few steps (have no effect on friction_limit) + f_force *= 205000 * SIZE * SIZE + p_force *= 205000 * SIZE * SIZE + force = np.sqrt(np.square(f_force) + np.square(p_force)) + + # Skid trace + if abs(force) > 2.0 * friction_limit: + if ( + w.skid_particle + and w.skid_particle.grass == grass + and len(w.skid_particle.poly) < 30 + ): + w.skid_particle.poly.append((w.position[0], w.position[1])) + elif w.skid_start is None: + w.skid_start = w.position + else: + w.skid_particle = self._create_particle( + w.skid_start, w.position, grass + ) + w.skid_start = None + else: + w.skid_start = None + w.skid_particle = None + + if abs(force) > friction_limit: + f_force /= force + p_force /= force + force = friction_limit # Correct physics here + f_force *= force + p_force *= force + + w.omega -= dt * f_force * w.wheel_rad / WHEEL_MOMENT_OF_INERTIA + + w.ApplyForceToCenter( + ( + p_force * side[0] + f_force * forw[0], + p_force * side[1] + f_force * forw[1], + ), + True, + ) + + def draw(self, viewer, draw_particles=True): + if draw_particles: + for p in self.particles: + viewer.draw_polyline(p.poly, color=p.color, linewidth=5) + for obj in self.drawlist: + for f in obj.fixtures: + trans = f.body.transform + path = [trans * v for v in f.shape.vertices] + viewer.draw_polygon(path, color=obj.color) + if "phase" not in obj.__dict__: + continue + a1 = obj.phase + a2 = obj.phase + 1.2 # radians + s1 = math.sin(a1) + s2 = math.sin(a2) + c1 = math.cos(a1) + c2 = math.cos(a2) + if s1 > 0 and s2 > 0: + continue + if s1 > 0: + c1 = np.sign(c1) + if s2 > 0: + c2 = np.sign(c2) + white_poly = [ + (-WHEEL_W * SIZE, +WHEEL_R * c1 * SIZE), + (+WHEEL_W * SIZE, +WHEEL_R * c1 * SIZE), + (+WHEEL_W * SIZE, +WHEEL_R * c2 * SIZE), + (-WHEEL_W * SIZE, +WHEEL_R * c2 * SIZE), + ] + viewer.draw_polygon([trans * v for v in white_poly], color=WHEEL_WHITE) + + def _create_particle(self, point1, point2, grass): + class Particle: + pass + + p = Particle() + p.color = WHEEL_COLOR if not grass else MUD_COLOR + p.ttl = 1 + p.poly = [(point1[0], point1[1]), (point2[0], point2[1])] + p.grass = grass + self.particles.append(p) + while len(self.particles) > 30: + self.particles.pop(0) + return p + + def destroy(self): + self.world.DestroyBody(self.hull) + self.hull = None + for w in self.wheels: + self.world.DestroyBody(w) + self.wheels = [] diff --git a/gym/envs/box2d/car_racing.py b/gym/envs/box2d/car_racing.py new file mode 100644 index 0000000000000000000000000000000000000000..1867cd7009b7ee3a61df9fab3e7c402658cb454a --- /dev/null +++ b/gym/envs/box2d/car_racing.py @@ -0,0 +1,652 @@ +""" +Easiest continuous control task to learn from pixels, a top-down racing +environment. +Discrete control is reasonable in this environment as well, on/off +discretization is fine. + +State consists of STATE_W x STATE_H pixels. + +The reward is -0.1 every frame and +1000/N for every track tile visited, where +N is the total number of tiles visited in the track. For example, if you have +finished in 732 frames, your reward is 1000 - 0.1*732 = 926.8 points. + +The game is solved when the agent consistently gets 900+ points. The generated +track is random every episode. + +The episode finishes when all the tiles are visited. The car also can go +outside of the PLAYFIELD - that is far off the track, then it will get -100 +and die. + +Some indicators are shown at the bottom of the window along with the state RGB +buffer. From left to right: the true speed, four ABS sensors, the steering +wheel position and gyroscope. + +To play yourself (it's rather fast for humans), type: + +python gym/envs/box2d/car_racing.py + +Remember it's a powerful rear-wheel drive car - don't press the accelerator +and turn at the same time. + +Created by Oleg Klimov. Licensed on the same terms as the rest of OpenAI Gym. +""" +import sys +import math +import numpy as np + +import Box2D +from Box2D.b2 import fixtureDef +from Box2D.b2 import polygonShape +from Box2D.b2 import contactListener + +import gym +from gym import spaces +from gym.envs.box2d.car_dynamics import Car +from gym.utils import seeding, EzPickle + +import pyglet + +pyglet.options["debug_gl"] = False +from pyglet import gl + +STATE_W = 96 # less than Atari 160x192 +STATE_H = 96 +VIDEO_W = 600 +VIDEO_H = 400 +WINDOW_W = 1000 +WINDOW_H = 800 + +SCALE = 6.0 # Track scale +TRACK_RAD = 900 / SCALE # Track is heavily morphed circle with this radius +PLAYFIELD = 2000 / SCALE # Game over boundary +FPS = 50 # Frames per second +ZOOM = 2.7 # Camera zoom +ZOOM_FOLLOW = True # Set to False for fixed view (don't use zoom) + + +TRACK_DETAIL_STEP = 21 / SCALE +TRACK_TURN_RATE = 0.31 +TRACK_WIDTH = 40 / SCALE +BORDER = 8 / SCALE +BORDER_MIN_COUNT = 4 + +ROAD_COLOR = [0.4, 0.4, 0.4] + + +class FrictionDetector(contactListener): + def __init__(self, env): + contactListener.__init__(self) + self.env = env + + def BeginContact(self, contact): + self._contact(contact, True) + + def EndContact(self, contact): + self._contact(contact, False) + + def _contact(self, contact, begin): + tile = None + obj = None + u1 = contact.fixtureA.body.userData + u2 = contact.fixtureB.body.userData + if u1 and "road_friction" in u1.__dict__: + tile = u1 + obj = u2 + if u2 and "road_friction" in u2.__dict__: + tile = u2 + obj = u1 + if not tile: + return + + tile.color[0] = ROAD_COLOR[0] + tile.color[1] = ROAD_COLOR[1] + tile.color[2] = ROAD_COLOR[2] + if not obj or "tiles" not in obj.__dict__: + return + if begin: + obj.tiles.add(tile) + if not tile.road_visited: + tile.road_visited = True + self.env.reward += 1000.0 / len(self.env.track) + self.env.tile_visited_count += 1 + else: + obj.tiles.remove(tile) + + +class CarRacing(gym.Env, EzPickle): + metadata = { + "render.modes": ["human", "rgb_array", "state_pixels"], + "video.frames_per_second": FPS, + } + + def __init__(self, verbose=1): + EzPickle.__init__(self) + self.seed() + self.contactListener_keepref = FrictionDetector(self) + self.world = Box2D.b2World((0, 0), contactListener=self.contactListener_keepref) + self.viewer = None + self.invisible_state_window = None + self.invisible_video_window = None + self.road = None + self.car = None + self.reward = 0.0 + self.prev_reward = 0.0 + self.verbose = verbose + self.fd_tile = fixtureDef( + shape=polygonShape(vertices=[(0, 0), (1, 0), (1, -1), (0, -1)]) + ) + + self.action_space = spaces.Box( + np.array([-1, 0, 0]).astype(np.float32), + np.array([+1, +1, +1]).astype(np.float32), + ) # steer, gas, brake + + self.observation_space = spaces.Box( + low=0, high=255, shape=(STATE_H, STATE_W, 3), dtype=np.uint8 + ) + + def seed(self, seed=None): + self.np_random, seed = seeding.np_random(seed) + return [seed] + + def _destroy(self): + if not self.road: + return + for t in self.road: + self.world.DestroyBody(t) + self.road = [] + self.car.destroy() + + def _create_track(self): + CHECKPOINTS = 12 + + # Create checkpoints + checkpoints = [] + for c in range(CHECKPOINTS): + noise = self.np_random.uniform(0, 2 * math.pi * 1 / CHECKPOINTS) + alpha = 2 * math.pi * c / CHECKPOINTS + noise + rad = self.np_random.uniform(TRACK_RAD / 3, TRACK_RAD) + + if c == 0: + alpha = 0 + rad = 1.5 * TRACK_RAD + if c == CHECKPOINTS - 1: + alpha = 2 * math.pi * c / CHECKPOINTS + self.start_alpha = 2 * math.pi * (-0.5) / CHECKPOINTS + rad = 1.5 * TRACK_RAD + + checkpoints.append((alpha, rad * math.cos(alpha), rad * math.sin(alpha))) + self.road = [] + + # Go from one checkpoint to another to create track + x, y, beta = 1.5 * TRACK_RAD, 0, 0 + dest_i = 0 + laps = 0 + track = [] + no_freeze = 2500 + visited_other_side = False + while True: + alpha = math.atan2(y, x) + if visited_other_side and alpha > 0: + laps += 1 + visited_other_side = False + if alpha < 0: + visited_other_side = True + alpha += 2 * math.pi + + while True: # Find destination from checkpoints + failed = True + + while True: + dest_alpha, dest_x, dest_y = checkpoints[dest_i % len(checkpoints)] + if alpha <= dest_alpha: + failed = False + break + dest_i += 1 + if dest_i % len(checkpoints) == 0: + break + + if not failed: + break + + alpha -= 2 * math.pi + continue + + r1x = math.cos(beta) + r1y = math.sin(beta) + p1x = -r1y + p1y = r1x + dest_dx = dest_x - x # vector towards destination + dest_dy = dest_y - y + # destination vector projected on rad: + proj = r1x * dest_dx + r1y * dest_dy + while beta - alpha > 1.5 * math.pi: + beta -= 2 * math.pi + while beta - alpha < -1.5 * math.pi: + beta += 2 * math.pi + prev_beta = beta + proj *= SCALE + if proj > 0.3: + beta -= min(TRACK_TURN_RATE, abs(0.001 * proj)) + if proj < -0.3: + beta += min(TRACK_TURN_RATE, abs(0.001 * proj)) + x += p1x * TRACK_DETAIL_STEP + y += p1y * TRACK_DETAIL_STEP + track.append((alpha, prev_beta * 0.5 + beta * 0.5, x, y)) + if laps > 4: + break + no_freeze -= 1 + if no_freeze == 0: + break + + # Find closed loop range i1..i2, first loop should be ignored, second is OK + i1, i2 = -1, -1 + i = len(track) + while True: + i -= 1 + if i == 0: + return False # Failed + pass_through_start = ( + track[i][0] > self.start_alpha and track[i - 1][0] <= self.start_alpha + ) + if pass_through_start and i2 == -1: + i2 = i + elif pass_through_start and i1 == -1: + i1 = i + break + if self.verbose == 1: + print("Track generation: %i..%i -> %i-tiles track" % (i1, i2, i2 - i1)) + assert i1 != -1 + assert i2 != -1 + + track = track[i1 : i2 - 1] + + first_beta = track[0][1] + first_perp_x = math.cos(first_beta) + first_perp_y = math.sin(first_beta) + # Length of perpendicular jump to put together head and tail + well_glued_together = np.sqrt( + np.square(first_perp_x * (track[0][2] - track[-1][2])) + + np.square(first_perp_y * (track[0][3] - track[-1][3])) + ) + if well_glued_together > TRACK_DETAIL_STEP: + return False + + # Red-white border on hard turns + border = [False] * len(track) + for i in range(len(track)): + good = True + oneside = 0 + for neg in range(BORDER_MIN_COUNT): + beta1 = track[i - neg - 0][1] + beta2 = track[i - neg - 1][1] + good &= abs(beta1 - beta2) > TRACK_TURN_RATE * 0.2 + oneside += np.sign(beta1 - beta2) + good &= abs(oneside) == BORDER_MIN_COUNT + border[i] = good + for i in range(len(track)): + for neg in range(BORDER_MIN_COUNT): + border[i - neg] |= border[i] + + # Create tiles + for i in range(len(track)): + alpha1, beta1, x1, y1 = track[i] + alpha2, beta2, x2, y2 = track[i - 1] + road1_l = ( + x1 - TRACK_WIDTH * math.cos(beta1), + y1 - TRACK_WIDTH * math.sin(beta1), + ) + road1_r = ( + x1 + TRACK_WIDTH * math.cos(beta1), + y1 + TRACK_WIDTH * math.sin(beta1), + ) + road2_l = ( + x2 - TRACK_WIDTH * math.cos(beta2), + y2 - TRACK_WIDTH * math.sin(beta2), + ) + road2_r = ( + x2 + TRACK_WIDTH * math.cos(beta2), + y2 + TRACK_WIDTH * math.sin(beta2), + ) + vertices = [road1_l, road1_r, road2_r, road2_l] + self.fd_tile.shape.vertices = vertices + t = self.world.CreateStaticBody(fixtures=self.fd_tile) + t.userData = t + c = 0.01 * (i % 3) + t.color = [ROAD_COLOR[0] + c, ROAD_COLOR[1] + c, ROAD_COLOR[2] + c] + t.road_visited = False + t.road_friction = 1.0 + t.fixtures[0].sensor = True + self.road_poly.append(([road1_l, road1_r, road2_r, road2_l], t.color)) + self.road.append(t) + if border[i]: + side = np.sign(beta2 - beta1) + b1_l = ( + x1 + side * TRACK_WIDTH * math.cos(beta1), + y1 + side * TRACK_WIDTH * math.sin(beta1), + ) + b1_r = ( + x1 + side * (TRACK_WIDTH + BORDER) * math.cos(beta1), + y1 + side * (TRACK_WIDTH + BORDER) * math.sin(beta1), + ) + b2_l = ( + x2 + side * TRACK_WIDTH * math.cos(beta2), + y2 + side * TRACK_WIDTH * math.sin(beta2), + ) + b2_r = ( + x2 + side * (TRACK_WIDTH + BORDER) * math.cos(beta2), + y2 + side * (TRACK_WIDTH + BORDER) * math.sin(beta2), + ) + self.road_poly.append( + ([b1_l, b1_r, b2_r, b2_l], (1, 1, 1) if i % 2 == 0 else (1, 0, 0)) + ) + self.track = track + return True + + def reset(self): + self._destroy() + self.reward = 0.0 + self.prev_reward = 0.0 + self.tile_visited_count = 0 + self.t = 0.0 + self.road_poly = [] + + while True: + success = self._create_track() + if success: + break + if self.verbose == 1: + print( + "retry to generate track (normal if there are not many" + "instances of this message)" + ) + self.car = Car(self.world, *self.track[0][1:4]) + + return self.step(None)[0] + + def step(self, action): + if action is not None: + self.car.steer(-action[0]) + self.car.gas(action[1]) + self.car.brake(action[2]) + + self.car.step(1.0 / FPS) + self.world.Step(1.0 / FPS, 6 * 30, 2 * 30) + self.t += 1.0 / FPS + + self.state = self.render("state_pixels") + + step_reward = 0 + done = False + if action is not None: # First step without action, called from reset() + self.reward -= 0.1 + # We actually don't want to count fuel spent, we want car to be faster. + # self.reward -= 10 * self.car.fuel_spent / ENGINE_POWER + self.car.fuel_spent = 0.0 + step_reward = self.reward - self.prev_reward + self.prev_reward = self.reward + if self.tile_visited_count == len(self.track): + done = True + x, y = self.car.hull.position + if abs(x) > PLAYFIELD or abs(y) > PLAYFIELD: + done = True + step_reward = -100 + + return self.state, step_reward, done, {} + + def render(self, mode="human"): + assert mode in ["human", "state_pixels", "rgb_array"] + if self.viewer is None: + from gym.envs.classic_control import rendering + + self.viewer = rendering.Viewer(WINDOW_W, WINDOW_H) + self.score_label = pyglet.text.Label( + "0000", + font_size=36, + x=20, + y=WINDOW_H * 2.5 / 40.00, + anchor_x="left", + anchor_y="center", + color=(255, 255, 255, 255), + ) + self.transform = rendering.Transform() + + if "t" not in self.__dict__: + return # reset() not called yet + + # Animate zoom first second: + zoom = 0.1 * SCALE * max(1 - self.t, 0) + ZOOM * SCALE * min(self.t, 1) + scroll_x = self.car.hull.position[0] + scroll_y = self.car.hull.position[1] + angle = -self.car.hull.angle + vel = self.car.hull.linearVelocity + if np.linalg.norm(vel) > 0.5: + angle = math.atan2(vel[0], vel[1]) + self.transform.set_scale(zoom, zoom) + self.transform.set_translation( + WINDOW_W / 2 + - (scroll_x * zoom * math.cos(angle) - scroll_y * zoom * math.sin(angle)), + WINDOW_H / 4 + - (scroll_x * zoom * math.sin(angle) + scroll_y * zoom * math.cos(angle)), + ) + self.transform.set_rotation(angle) + + self.car.draw(self.viewer, mode != "state_pixels") + + arr = None + win = self.viewer.window + win.switch_to() + win.dispatch_events() + + win.clear() + t = self.transform + if mode == "rgb_array": + VP_W = VIDEO_W + VP_H = VIDEO_H + elif mode == "state_pixels": + VP_W = STATE_W + VP_H = STATE_H + else: + pixel_scale = 1 + if hasattr(win.context, "_nscontext"): + pixel_scale = ( + win.context._nscontext.view().backingScaleFactor() + ) # pylint: disable=protected-access + VP_W = int(pixel_scale * WINDOW_W) + VP_H = int(pixel_scale * WINDOW_H) + + gl.glViewport(0, 0, VP_W, VP_H) + t.enable() + self.render_road() + for geom in self.viewer.onetime_geoms: + geom.render() + self.viewer.onetime_geoms = [] + t.disable() + self.render_indicators(WINDOW_W, WINDOW_H) + + if mode == "human": + win.flip() + return self.viewer.isopen + + image_data = ( + pyglet.image.get_buffer_manager().get_color_buffer().get_image_data() + ) + arr = np.fromstring(image_data.get_data(), dtype=np.uint8, sep="") + arr = arr.reshape(VP_H, VP_W, 4) + arr = arr[::-1, :, 0:3] + + return arr + + def close(self): + if self.viewer is not None: + self.viewer.close() + self.viewer = None + + def render_road(self): + colors = [0.4, 0.8, 0.4, 1.0] * 4 + polygons_ = [ + +PLAYFIELD, + +PLAYFIELD, + 0, + +PLAYFIELD, + -PLAYFIELD, + 0, + -PLAYFIELD, + -PLAYFIELD, + 0, + -PLAYFIELD, + +PLAYFIELD, + 0, + ] + + k = PLAYFIELD / 20.0 + colors.extend([0.4, 0.9, 0.4, 1.0] * 4 * 20 * 20) + for x in range(-20, 20, 2): + for y in range(-20, 20, 2): + polygons_.extend( + [ + k * x + k, + k * y + 0, + 0, + k * x + 0, + k * y + 0, + 0, + k * x + 0, + k * y + k, + 0, + k * x + k, + k * y + k, + 0, + ] + ) + + for poly, color in self.road_poly: + colors.extend([color[0], color[1], color[2], 1] * len(poly)) + for p in poly: + polygons_.extend([p[0], p[1], 0]) + + vl = pyglet.graphics.vertex_list( + len(polygons_) // 3, ("v3f", polygons_), ("c4f", colors) + ) # gl.GL_QUADS, + vl.draw(gl.GL_QUADS) + vl.delete() + + def render_indicators(self, W, H): + s = W / 40.0 + h = H / 40.0 + colors = [0, 0, 0, 1] * 4 + polygons = [W, 0, 0, W, 5 * h, 0, 0, 5 * h, 0, 0, 0, 0] + + def vertical_ind(place, val, color): + colors.extend([color[0], color[1], color[2], 1] * 4) + polygons.extend( + [ + place * s, + h + h * val, + 0, + (place + 1) * s, + h + h * val, + 0, + (place + 1) * s, + h, + 0, + (place + 0) * s, + h, + 0, + ] + ) + + def horiz_ind(place, val, color): + colors.extend([color[0], color[1], color[2], 1] * 4) + polygons.extend( + [ + (place + 0) * s, + 4 * h, + 0, + (place + val) * s, + 4 * h, + 0, + (place + val) * s, + 2 * h, + 0, + (place + 0) * s, + 2 * h, + 0, + ] + ) + + true_speed = np.sqrt( + np.square(self.car.hull.linearVelocity[0]) + + np.square(self.car.hull.linearVelocity[1]) + ) + + vertical_ind(5, 0.02 * true_speed, (1, 1, 1)) + vertical_ind(7, 0.01 * self.car.wheels[0].omega, (0.0, 0, 1)) # ABS sensors + vertical_ind(8, 0.01 * self.car.wheels[1].omega, (0.0, 0, 1)) + vertical_ind(9, 0.01 * self.car.wheels[2].omega, (0.2, 0, 1)) + vertical_ind(10, 0.01 * self.car.wheels[3].omega, (0.2, 0, 1)) + horiz_ind(20, -10.0 * self.car.wheels[0].joint.angle, (0, 1, 0)) + horiz_ind(30, -0.8 * self.car.hull.angularVelocity, (1, 0, 0)) + vl = pyglet.graphics.vertex_list( + len(polygons) // 3, ("v3f", polygons), ("c4f", colors) + ) # gl.GL_QUADS, + vl.draw(gl.GL_QUADS) + vl.delete() + self.score_label.text = "%04i" % self.reward + self.score_label.draw() + + +if __name__ == "__main__": + from pyglet.window import key + + a = np.array([0.0, 0.0, 0.0]) + + def key_press(k, mod): + global restart + if k == 0xFF0D: + restart = True + if k == key.LEFT: + a[0] = -1.0 + if k == key.RIGHT: + a[0] = +1.0 + if k == key.UP: + a[1] = +1.0 + if k == key.DOWN: + a[2] = +0.8 # set 1.0 for wheels to block to zero rotation + + def key_release(k, mod): + if k == key.LEFT and a[0] == -1.0: + a[0] = 0 + if k == key.RIGHT and a[0] == +1.0: + a[0] = 0 + if k == key.UP: + a[1] = 0 + if k == key.DOWN: + a[2] = 0 + + env = CarRacing() + env.render() + env.viewer.window.on_key_press = key_press + env.viewer.window.on_key_release = key_release + record_video = False + if record_video: + from gym.wrappers.monitor import Monitor + + env = Monitor(env, "/tmp/video-test", force=True) + isopen = True + while isopen: + env.reset() + total_reward = 0.0 + steps = 0 + restart = False + while True: + s, r, done, info = env.step(a) + total_reward += r + if steps % 200 == 0 or done: + print("\naction " + str(["{:+0.2f}".format(x) for x in a])) + print("step {} total_reward {:+0.2f}".format(steps, total_reward)) + steps += 1 + isopen = env.render() + if done or restart or isopen == False: + break + env.close() diff --git a/gym/envs/box2d/lunar_lander.py b/gym/envs/box2d/lunar_lander.py new file mode 100644 index 0000000000000000000000000000000000000000..57dbbaec6f71a05ea7bc87d481a891d34b85e89d --- /dev/null +++ b/gym/envs/box2d/lunar_lander.py @@ -0,0 +1,534 @@ +""" +Rocket trajectory optimization is a classic topic in Optimal Control. + +According to Pontryagin's maximum principle it's optimal to fire engine full throttle or +turn it off. That's the reason this environment is OK to have discreet actions (engine on or off). + +The landing pad is always at coordinates (0,0). The coordinates are the first two numbers in the state vector. +Reward for moving from the top of the screen to the landing pad and zero speed is about 100..140 points. +If the lander moves away from the landing pad it loses reward. The episode finishes if the lander crashes or +comes to rest, receiving an additional -100 or +100 points. Each leg with ground contact is +10 points. +Firing the main engine is -0.3 points each frame. Firing the side engine is -0.03 points each frame. +Solved is 200 points. + +Landing outside the landing pad is possible. Fuel is infinite, so an agent can learn to fly and then land +on its first attempt. Please see the source code for details. + +To see a heuristic landing, run: + +python gym/envs/box2d/lunar_lander.py + +To play yourself, run: + +python examples/agents/keyboard_agent.py LunarLander-v2 + +Created by Oleg Klimov. Licensed on the same terms as the rest of OpenAI Gym. +""" + + +import math +import sys +import numpy as np + +import Box2D +from Box2D.b2 import ( + edgeShape, + circleShape, + fixtureDef, + polygonShape, + revoluteJointDef, + contactListener, +) + +import gym +from gym import spaces +from gym.utils import seeding, EzPickle + +FPS = 50 +SCALE = 30.0 # affects how fast-paced the game is, forces should be adjusted as well + +MAIN_ENGINE_POWER = 13.0 +SIDE_ENGINE_POWER = 0.6 + +INITIAL_RANDOM = 1000.0 # Set 1500 to make game harder + +LANDER_POLY = [(-14, +17), (-17, 0), (-17, -10), (+17, -10), (+17, 0), (+14, +17)] +LEG_AWAY = 20 +LEG_DOWN = 18 +LEG_W, LEG_H = 2, 8 +LEG_SPRING_TORQUE = 40 + +SIDE_ENGINE_HEIGHT = 14.0 +SIDE_ENGINE_AWAY = 12.0 + +VIEWPORT_W = 600 +VIEWPORT_H = 400 + + +class ContactDetector(contactListener): + def __init__(self, env): + contactListener.__init__(self) + self.env = env + + def BeginContact(self, contact): + if ( + self.env.lander == contact.fixtureA.body + or self.env.lander == contact.fixtureB.body + ): + self.env.game_over = True + for i in range(2): + if self.env.legs[i] in [contact.fixtureA.body, contact.fixtureB.body]: + self.env.legs[i].ground_contact = True + + def EndContact(self, contact): + for i in range(2): + if self.env.legs[i] in [contact.fixtureA.body, contact.fixtureB.body]: + self.env.legs[i].ground_contact = False + + +class LunarLander(gym.Env, EzPickle): + metadata = {"render.modes": ["human", "rgb_array"], "video.frames_per_second": FPS} + + continuous = False + + def __init__(self): + EzPickle.__init__(self) + self.seed() + self.viewer = None + + self.world = Box2D.b2World() + self.moon = None + self.lander = None + self.particles = [] + + self.prev_reward = None + + # useful range is -1 .. +1, but spikes can be higher + self.observation_space = spaces.Box( + -np.inf, np.inf, shape=(8,), dtype=np.float32 + ) + + if self.continuous: + # Action is two floats [main engine, left-right engines]. + # Main engine: -1..0 off, 0..+1 throttle from 50% to 100% power. Engine can't work with less than 50% power. + # Left-right: -1.0..-0.5 fire left engine, +0.5..+1.0 fire right engine, -0.5..0.5 off + self.action_space = spaces.Box(-1, +1, (2,), dtype=np.float32) + else: + # Nop, fire left engine, main engine, right engine + self.action_space = spaces.Discrete(4) + + def seed(self, seed=None): + self.np_random, seed = seeding.np_random(seed) + return [seed] + + def _destroy(self): + if not self.moon: + return + self.world.contactListener = None + self._clean_particles(True) + self.world.DestroyBody(self.moon) + self.moon = None + self.world.DestroyBody(self.lander) + self.lander = None + self.world.DestroyBody(self.legs[0]) + self.world.DestroyBody(self.legs[1]) + + def reset(self): + self._destroy() + self.world.contactListener_keepref = ContactDetector(self) + self.world.contactListener = self.world.contactListener_keepref + self.game_over = False + self.prev_shaping = None + + W = VIEWPORT_W / SCALE + H = VIEWPORT_H / SCALE + + # terrain + CHUNKS = 11 + height = self.np_random.uniform(0, H / 2, size=(CHUNKS + 1,)) + chunk_x = [W / (CHUNKS - 1) * i for i in range(CHUNKS)] + self.helipad_x1 = chunk_x[CHUNKS // 2 - 1] + self.helipad_x2 = chunk_x[CHUNKS // 2 + 1] + self.helipad_y = H / 4 + height[CHUNKS // 2 - 2] = self.helipad_y + height[CHUNKS // 2 - 1] = self.helipad_y + height[CHUNKS // 2 + 0] = self.helipad_y + height[CHUNKS // 2 + 1] = self.helipad_y + height[CHUNKS // 2 + 2] = self.helipad_y + smooth_y = [ + 0.33 * (height[i - 1] + height[i + 0] + height[i + 1]) + for i in range(CHUNKS) + ] + + self.moon = self.world.CreateStaticBody( + shapes=edgeShape(vertices=[(0, 0), (W, 0)]) + ) + self.sky_polys = [] + for i in range(CHUNKS - 1): + p1 = (chunk_x[i], smooth_y[i]) + p2 = (chunk_x[i + 1], smooth_y[i + 1]) + self.moon.CreateEdgeFixture(vertices=[p1, p2], density=0, friction=0.1) + self.sky_polys.append([p1, p2, (p2[0], H), (p1[0], H)]) + + self.moon.color1 = (0.0, 0.0, 0.0) + self.moon.color2 = (0.0, 0.0, 0.0) + + initial_y = VIEWPORT_H / SCALE + self.lander = self.world.CreateDynamicBody( + position=(VIEWPORT_W / SCALE / 2, initial_y), + angle=0.0, + fixtures=fixtureDef( + shape=polygonShape( + vertices=[(x / SCALE, y / SCALE) for x, y in LANDER_POLY] + ), + density=5.0, + friction=0.1, + categoryBits=0x0010, + maskBits=0x001, # collide only with ground + restitution=0.0, + ), # 0.99 bouncy + ) + self.lander.color1 = (0.5, 0.4, 0.9) + self.lander.color2 = (0.3, 0.3, 0.5) + self.lander.ApplyForceToCenter( + ( + self.np_random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM), + self.np_random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM), + ), + True, + ) + + self.legs = [] + for i in [-1, +1]: + leg = self.world.CreateDynamicBody( + position=(VIEWPORT_W / SCALE / 2 - i * LEG_AWAY / SCALE, initial_y), + angle=(i * 0.05), + fixtures=fixtureDef( + shape=polygonShape(box=(LEG_W / SCALE, LEG_H / SCALE)), + density=1.0, + restitution=0.0, + categoryBits=0x0020, + maskBits=0x001, + ), + ) + leg.ground_contact = False + leg.color1 = (0.5, 0.4, 0.9) + leg.color2 = (0.3, 0.3, 0.5) + rjd = revoluteJointDef( + bodyA=self.lander, + bodyB=leg, + localAnchorA=(0, 0), + localAnchorB=(i * LEG_AWAY / SCALE, LEG_DOWN / SCALE), + enableMotor=True, + enableLimit=True, + maxMotorTorque=LEG_SPRING_TORQUE, + motorSpeed=+0.3 * i, # low enough not to jump back into the sky + ) + if i == -1: + rjd.lowerAngle = ( + +0.9 - 0.5 + ) # The most esoteric numbers here, angled legs have freedom to travel within + rjd.upperAngle = +0.9 + else: + rjd.lowerAngle = -0.9 + rjd.upperAngle = -0.9 + 0.5 + leg.joint = self.world.CreateJoint(rjd) + self.legs.append(leg) + + self.drawlist = [self.lander] + self.legs + + return self.step(np.array([0, 0]) if self.continuous else 0)[0] + + def _create_particle(self, mass, x, y, ttl): + p = self.world.CreateDynamicBody( + position=(x, y), + angle=0.0, + fixtures=fixtureDef( + shape=circleShape(radius=2 / SCALE, pos=(0, 0)), + density=mass, + friction=0.1, + categoryBits=0x0100, + maskBits=0x001, # collide only with ground + restitution=0.3, + ), + ) + p.ttl = ttl + self.particles.append(p) + self._clean_particles(False) + return p + + def _clean_particles(self, all): + while self.particles and (all or self.particles[0].ttl < 0): + self.world.DestroyBody(self.particles.pop(0)) + + def step(self, action): + if self.continuous: + action = np.clip(action, -1, +1).astype(np.float32) + else: + assert self.action_space.contains(action), "%r (%s) invalid " % ( + action, + type(action), + ) + + # Engines + tip = (math.sin(self.lander.angle), math.cos(self.lander.angle)) + side = (-tip[1], tip[0]) + dispersion = [self.np_random.uniform(-1.0, +1.0) / SCALE for _ in range(2)] + + m_power = 0.0 + if (self.continuous and action[0] > 0.0) or ( + not self.continuous and action == 2 + ): + # Main engine + if self.continuous: + m_power = (np.clip(action[0], 0.0, 1.0) + 1.0) * 0.5 # 0.5..1.0 + assert m_power >= 0.5 and m_power <= 1.0 + else: + m_power = 1.0 + ox = ( + tip[0] * (4 / SCALE + 2 * dispersion[0]) + side[0] * dispersion[1] + ) # 4 is move a bit downwards, +-2 for randomness + oy = -tip[1] * (4 / SCALE + 2 * dispersion[0]) - side[1] * dispersion[1] + impulse_pos = (self.lander.position[0] + ox, self.lander.position[1] + oy) + p = self._create_particle( + 3.5, # 3.5 is here to make particle speed adequate + impulse_pos[0], + impulse_pos[1], + m_power, + ) # particles are just a decoration + p.ApplyLinearImpulse( + (ox * MAIN_ENGINE_POWER * m_power, oy * MAIN_ENGINE_POWER * m_power), + impulse_pos, + True, + ) + self.lander.ApplyLinearImpulse( + (-ox * MAIN_ENGINE_POWER * m_power, -oy * MAIN_ENGINE_POWER * m_power), + impulse_pos, + True, + ) + + s_power = 0.0 + if (self.continuous and np.abs(action[1]) > 0.5) or ( + not self.continuous and action in [1, 3] + ): + # Orientation engines + if self.continuous: + direction = np.sign(action[1]) + s_power = np.clip(np.abs(action[1]), 0.5, 1.0) + assert s_power >= 0.5 and s_power <= 1.0 + else: + direction = action - 2 + s_power = 1.0 + ox = tip[0] * dispersion[0] + side[0] * ( + 3 * dispersion[1] + direction * SIDE_ENGINE_AWAY / SCALE + ) + oy = -tip[1] * dispersion[0] - side[1] * ( + 3 * dispersion[1] + direction * SIDE_ENGINE_AWAY / SCALE + ) + impulse_pos = ( + self.lander.position[0] + ox - tip[0] * 17 / SCALE, + self.lander.position[1] + oy + tip[1] * SIDE_ENGINE_HEIGHT / SCALE, + ) + p = self._create_particle(0.7, impulse_pos[0], impulse_pos[1], s_power) + p.ApplyLinearImpulse( + (ox * SIDE_ENGINE_POWER * s_power, oy * SIDE_ENGINE_POWER * s_power), + impulse_pos, + True, + ) + self.lander.ApplyLinearImpulse( + (-ox * SIDE_ENGINE_POWER * s_power, -oy * SIDE_ENGINE_POWER * s_power), + impulse_pos, + True, + ) + + self.world.Step(1.0 / FPS, 6 * 30, 2 * 30) + + pos = self.lander.position + vel = self.lander.linearVelocity + state = [ + (pos.x - VIEWPORT_W / SCALE / 2) / (VIEWPORT_W / SCALE / 2), + (pos.y - (self.helipad_y + LEG_DOWN / SCALE)) / (VIEWPORT_H / SCALE / 2), + vel.x * (VIEWPORT_W / SCALE / 2) / FPS, + vel.y * (VIEWPORT_H / SCALE / 2) / FPS, + self.lander.angle, + 20.0 * self.lander.angularVelocity / FPS, + 1.0 if self.legs[0].ground_contact else 0.0, + 1.0 if self.legs[1].ground_contact else 0.0, + ] + assert len(state) == 8 + + reward = 0 + shaping = ( + -100 * np.sqrt(state[0] * state[0] + state[1] * state[1]) + - 100 * np.sqrt(state[2] * state[2] + state[3] * state[3]) + - 100 * abs(state[4]) + + 10 * state[6] + + 10 * state[7] + ) # And ten points for legs contact, the idea is if you + # lose contact again after landing, you get negative reward + if self.prev_shaping is not None: + reward = shaping - self.prev_shaping + self.prev_shaping = shaping + + reward -= ( + m_power * 0.30 + ) # less fuel spent is better, about -30 for heuristic landing + reward -= s_power * 0.03 + + done = False + if self.game_over or abs(state[0]) >= 1.0: + done = True + reward = -100 + if not self.lander.awake: + done = True + reward = +100 + return np.array(state, dtype=np.float32), reward, done, {} + + def render(self, mode="human"): + from gym.envs.classic_control import rendering + + if self.viewer is None: + self.viewer = rendering.Viewer(VIEWPORT_W, VIEWPORT_H) + self.viewer.set_bounds(0, VIEWPORT_W / SCALE, 0, VIEWPORT_H / SCALE) + + for obj in self.particles: + obj.ttl -= 0.15 + obj.color1 = ( + max(0.2, 0.2 + obj.ttl), + max(0.2, 0.5 * obj.ttl), + max(0.2, 0.5 * obj.ttl), + ) + obj.color2 = ( + max(0.2, 0.2 + obj.ttl), + max(0.2, 0.5 * obj.ttl), + max(0.2, 0.5 * obj.ttl), + ) + + self._clean_particles(False) + + for p in self.sky_polys: + self.viewer.draw_polygon(p, color=(0, 0, 0)) + + for obj in self.particles + self.drawlist: + for f in obj.fixtures: + trans = f.body.transform + if type(f.shape) is circleShape: + t = rendering.Transform(translation=trans * f.shape.pos) + self.viewer.draw_circle( + f.shape.radius, 20, color=obj.color1 + ).add_attr(t) + self.viewer.draw_circle( + f.shape.radius, 20, color=obj.color2, filled=False, linewidth=2 + ).add_attr(t) + else: + path = [trans * v for v in f.shape.vertices] + self.viewer.draw_polygon(path, color=obj.color1) + path.append(path[0]) + self.viewer.draw_polyline(path, color=obj.color2, linewidth=2) + + for x in [self.helipad_x1, self.helipad_x2]: + flagy1 = self.helipad_y + flagy2 = flagy1 + 50 / SCALE + self.viewer.draw_polyline([(x, flagy1), (x, flagy2)], color=(1, 1, 1)) + self.viewer.draw_polygon( + [ + (x, flagy2), + (x, flagy2 - 10 / SCALE), + (x + 25 / SCALE, flagy2 - 5 / SCALE), + ], + color=(0.8, 0.8, 0), + ) + + return self.viewer.render(return_rgb_array=mode == "rgb_array") + + def close(self): + if self.viewer is not None: + self.viewer.close() + self.viewer = None + + +class LunarLanderContinuous(LunarLander): + continuous = True + + +def heuristic(env, s): + """ + The heuristic for + 1. Testing + 2. Demonstration rollout. + + Args: + env: The environment + s (list): The state. Attributes: + s[0] is the horizontal coordinate + s[1] is the vertical coordinate + s[2] is the horizontal speed + s[3] is the vertical speed + s[4] is the angle + s[5] is the angular speed + s[6] 1 if first leg has contact, else 0 + s[7] 1 if second leg has contact, else 0 + returns: + a: The heuristic to be fed into the step function defined above to determine the next step and reward. + """ + + angle_targ = s[0] * 0.5 + s[2] * 1.0 # angle should point towards center + if angle_targ > 0.4: + angle_targ = 0.4 # more than 0.4 radians (22 degrees) is bad + if angle_targ < -0.4: + angle_targ = -0.4 + hover_targ = 0.55 * np.abs( + s[0] + ) # target y should be proportional to horizontal offset + + angle_todo = (angle_targ - s[4]) * 0.5 - (s[5]) * 1.0 + hover_todo = (hover_targ - s[1]) * 0.5 - (s[3]) * 0.5 + + if s[6] or s[7]: # legs have contact + angle_todo = 0 + hover_todo = ( + -(s[3]) * 0.5 + ) # override to reduce fall speed, that's all we need after contact + + if env.continuous: + a = np.array([hover_todo * 20 - 1, -angle_todo * 20]) + a = np.clip(a, -1, +1) + else: + a = 0 + if hover_todo > np.abs(angle_todo) and hover_todo > 0.05: + a = 2 + elif angle_todo < -0.05: + a = 3 + elif angle_todo > +0.05: + a = 1 + return a + + +def demo_heuristic_lander(env, seed=None, render=False): + env.seed(seed) + total_reward = 0 + steps = 0 + s = env.reset() + while True: + a = heuristic(env, s) + s, r, done, info = env.step(a) + total_reward += r + + if render: + still_open = env.render() + if still_open == False: + break + + if steps % 20 == 0 or done: + print("observations:", " ".join(["{:+0.2f}".format(x) for x in s])) + print("step {} total_reward {:+0.2f}".format(steps, total_reward)) + steps += 1 + if done: + break + if render: + env.close() + return total_reward + + +if __name__ == "__main__": + demo_heuristic_lander(LunarLander(), render=True) diff --git a/gym/envs/classic_control/__init__.py b/gym/envs/classic_control/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a94cb47b2bea09a588e9e57c5b5da68eaa39c7b3 --- /dev/null +++ b/gym/envs/classic_control/__init__.py @@ -0,0 +1,5 @@ +from gym.envs.classic_control.cartpole import CartPoleEnv +from gym.envs.classic_control.mountain_car import MountainCarEnv +from gym.envs.classic_control.continuous_mountain_car import Continuous_MountainCarEnv +from gym.envs.classic_control.pendulum import PendulumEnv +from gym.envs.classic_control.acrobot import AcrobotEnv diff --git a/gym/envs/classic_control/__pycache__/__init__.cpython-39.pyc b/gym/envs/classic_control/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..837e1288acc5a73bce413f76f68aadc9a07a8db2 Binary files /dev/null and b/gym/envs/classic_control/__pycache__/__init__.cpython-39.pyc differ diff --git a/gym/envs/classic_control/__pycache__/acrobot.cpython-39.pyc b/gym/envs/classic_control/__pycache__/acrobot.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a82ca86995a672ca9eb83951d782bd48244931c3 Binary files /dev/null and b/gym/envs/classic_control/__pycache__/acrobot.cpython-39.pyc differ diff --git a/gym/envs/classic_control/__pycache__/cartpole.cpython-39.pyc b/gym/envs/classic_control/__pycache__/cartpole.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85f455788c77c695c1399e558167e749d01e8b46 Binary files /dev/null and b/gym/envs/classic_control/__pycache__/cartpole.cpython-39.pyc differ diff --git a/gym/envs/classic_control/__pycache__/continuous_mountain_car.cpython-39.pyc b/gym/envs/classic_control/__pycache__/continuous_mountain_car.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c260b653e76c24b6a9c0cc9d025b3c2e7a94d5a5 Binary files /dev/null and b/gym/envs/classic_control/__pycache__/continuous_mountain_car.cpython-39.pyc differ diff --git a/gym/envs/classic_control/__pycache__/mountain_car.cpython-39.pyc b/gym/envs/classic_control/__pycache__/mountain_car.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c3ca1beae81773eef60f4cadca3eb5223f402a7 Binary files /dev/null and b/gym/envs/classic_control/__pycache__/mountain_car.cpython-39.pyc differ diff --git a/gym/envs/classic_control/__pycache__/pendulum.cpython-39.pyc b/gym/envs/classic_control/__pycache__/pendulum.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bc95896c45a6edf84a766badc701c8261158e39 Binary files /dev/null and b/gym/envs/classic_control/__pycache__/pendulum.cpython-39.pyc differ diff --git a/gym/envs/classic_control/__pycache__/rendering.cpython-39.pyc b/gym/envs/classic_control/__pycache__/rendering.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b9163759c0c0564bc5917c29e5dcc5e7616b99a Binary files /dev/null and b/gym/envs/classic_control/__pycache__/rendering.cpython-39.pyc differ diff --git a/gym/envs/classic_control/acrobot.py b/gym/envs/classic_control/acrobot.py new file mode 100644 index 0000000000000000000000000000000000000000..17e26d67d83def2c3e3985c450659cf8fc47f20e --- /dev/null +++ b/gym/envs/classic_control/acrobot.py @@ -0,0 +1,323 @@ +"""classic Acrobot task""" +import numpy as np +from numpy import sin, cos, pi + +from gym import core, spaces +from gym.utils import seeding + +__copyright__ = "Copyright 2013, RLPy http://acl.mit.edu/RLPy" +__credits__ = [ + "Alborz Geramifard", + "Robert H. Klein", + "Christoph Dann", + "William Dabney", + "Jonathan P. How", +] +__license__ = "BSD 3-Clause" +__author__ = "Christoph Dann " + +# SOURCE: +# https://github.com/rlpy/rlpy/blob/master/rlpy/Domains/Acrobot.py + + +class AcrobotEnv(core.Env): + + """ + Acrobot is a 2-link pendulum with only the second joint actuated. + Initially, both links point downwards. The goal is to swing the + end-effector at a height at least the length of one link above the base. + Both links can swing freely and can pass by each other, i.e., they don't + collide when they have the same angle. + **STATE:** + The state consists of the sin() and cos() of the two rotational joint + angles and the joint angular velocities : + [cos(theta1) sin(theta1) cos(theta2) sin(theta2) thetaDot1 thetaDot2]. + For the first link, an angle of 0 corresponds to the link pointing downwards. + The angle of the second link is relative to the angle of the first link. + An angle of 0 corresponds to having the same angle between the two links. + A state of [1, 0, 1, 0, ..., ...] means that both links point downwards. + **ACTIONS:** + The action is either applying +1, 0 or -1 torque on the joint between + the two pendulum links. + .. note:: + The dynamics equations were missing some terms in the NIPS paper which + are present in the book. R. Sutton confirmed in personal correspondence + that the experimental results shown in the paper and the book were + generated with the equations shown in the book. + However, there is the option to run the domain with the paper equations + by setting book_or_nips = 'nips' + **REFERENCE:** + .. seealso:: + R. Sutton: Generalization in Reinforcement Learning: + Successful Examples Using Sparse Coarse Coding (NIPS 1996) + .. seealso:: + R. Sutton and A. G. Barto: + Reinforcement learning: An introduction. + Cambridge: MIT press, 1998. + .. warning:: + This version of the domain uses the Runge-Kutta method for integrating + the system dynamics and is more realistic, but also considerably harder + than the original version which employs Euler integration, + see the AcrobotLegacy class. + """ + + metadata = {"render.modes": ["human", "rgb_array"], "video.frames_per_second": 15} + + dt = 0.2 + + LINK_LENGTH_1 = 1.0 # [m] + LINK_LENGTH_2 = 1.0 # [m] + LINK_MASS_1 = 1.0 #: [kg] mass of link 1 + LINK_MASS_2 = 1.0 #: [kg] mass of link 2 + LINK_COM_POS_1 = 0.5 #: [m] position of the center of mass of link 1 + LINK_COM_POS_2 = 0.5 #: [m] position of the center of mass of link 2 + LINK_MOI = 1.0 #: moments of inertia for both links + + MAX_VEL_1 = 4 * pi + MAX_VEL_2 = 9 * pi + + AVAIL_TORQUE = [-1.0, 0.0, +1] + + torque_noise_max = 0.0 + + #: use dynamics equations from the nips paper or the book + book_or_nips = "book" + action_arrow = None + domain_fig = None + actions_num = 3 + + def __init__(self): + self.viewer = None + high = np.array( + [1.0, 1.0, 1.0, 1.0, self.MAX_VEL_1, self.MAX_VEL_2], dtype=np.float32 + ) + low = -high + self.observation_space = spaces.Box(low=low, high=high, dtype=np.float32) + self.action_space = spaces.Discrete(3) + self.state = None + self.seed() + + def seed(self, seed=None): + self.np_random, seed = seeding.np_random(seed) + return [seed] + + def reset(self): + self.state = self.np_random.uniform(low=-0.1, high=0.1, size=(4,)).astype( + np.float32 + ) + return self._get_ob() + + def step(self, a): + s = self.state + torque = self.AVAIL_TORQUE[a] + + # Add noise to the force action + if self.torque_noise_max > 0: + torque += self.np_random.uniform( + -self.torque_noise_max, self.torque_noise_max + ) + + # Now, augment the state with our force action so it can be passed to + # _dsdt + s_augmented = np.append(s, torque) + + ns = rk4(self._dsdt, s_augmented, [0, self.dt]) + + ns[0] = wrap(ns[0], -pi, pi) + ns[1] = wrap(ns[1], -pi, pi) + ns[2] = bound(ns[2], -self.MAX_VEL_1, self.MAX_VEL_1) + ns[3] = bound(ns[3], -self.MAX_VEL_2, self.MAX_VEL_2) + self.state = ns + terminal = self._terminal() + reward = -1.0 if not terminal else 0.0 + return (self._get_ob(), reward, terminal, {}) + + def _get_ob(self): + s = self.state + return np.array( + [cos(s[0]), sin(s[0]), cos(s[1]), sin(s[1]), s[2], s[3]], dtype=np.float32 + ) + + def _terminal(self): + s = self.state + return bool(-cos(s[0]) - cos(s[1] + s[0]) > 1.0) + + def _dsdt(self, s_augmented): + m1 = self.LINK_MASS_1 + m2 = self.LINK_MASS_2 + l1 = self.LINK_LENGTH_1 + lc1 = self.LINK_COM_POS_1 + lc2 = self.LINK_COM_POS_2 + I1 = self.LINK_MOI + I2 = self.LINK_MOI + g = 9.8 + a = s_augmented[-1] + s = s_augmented[:-1] + theta1 = s[0] + theta2 = s[1] + dtheta1 = s[2] + dtheta2 = s[3] + d1 = ( + m1 * lc1 ** 2 + + m2 * (l1 ** 2 + lc2 ** 2 + 2 * l1 * lc2 * cos(theta2)) + + I1 + + I2 + ) + d2 = m2 * (lc2 ** 2 + l1 * lc2 * cos(theta2)) + I2 + phi2 = m2 * lc2 * g * cos(theta1 + theta2 - pi / 2.0) + phi1 = ( + -m2 * l1 * lc2 * dtheta2 ** 2 * sin(theta2) + - 2 * m2 * l1 * lc2 * dtheta2 * dtheta1 * sin(theta2) + + (m1 * lc1 + m2 * l1) * g * cos(theta1 - pi / 2) + + phi2 + ) + if self.book_or_nips == "nips": + # the following line is consistent with the description in the + # paper + ddtheta2 = (a + d2 / d1 * phi1 - phi2) / (m2 * lc2 ** 2 + I2 - d2 ** 2 / d1) + else: + # the following line is consistent with the java implementation and the + # book + ddtheta2 = ( + a + d2 / d1 * phi1 - m2 * l1 * lc2 * dtheta1 ** 2 * sin(theta2) - phi2 + ) / (m2 * lc2 ** 2 + I2 - d2 ** 2 / d1) + ddtheta1 = -(d2 * ddtheta2 + phi1) / d1 + return (dtheta1, dtheta2, ddtheta1, ddtheta2, 0.0) + + def render(self, mode="human"): + from gym.envs.classic_control import rendering + + s = self.state + + if self.viewer is None: + self.viewer = rendering.Viewer(500, 500) + bound = self.LINK_LENGTH_1 + self.LINK_LENGTH_2 + 0.2 # 2.2 for default + self.viewer.set_bounds(-bound, bound, -bound, bound) + + if s is None: + return None + + p1 = [-self.LINK_LENGTH_1 * cos(s[0]), self.LINK_LENGTH_1 * sin(s[0])] + + p2 = [ + p1[0] - self.LINK_LENGTH_2 * cos(s[0] + s[1]), + p1[1] + self.LINK_LENGTH_2 * sin(s[0] + s[1]), + ] + + xys = np.array([[0, 0], p1, p2])[:, ::-1] + thetas = [s[0] - pi / 2, s[0] + s[1] - pi / 2] + link_lengths = [self.LINK_LENGTH_1, self.LINK_LENGTH_2] + + self.viewer.draw_line((-2.2, 1), (2.2, 1)) + for ((x, y), th, llen) in zip(xys, thetas, link_lengths): + l, r, t, b = 0, llen, 0.1, -0.1 + jtransform = rendering.Transform(rotation=th, translation=(x, y)) + link = self.viewer.draw_polygon([(l, b), (l, t), (r, t), (r, b)]) + link.add_attr(jtransform) + link.set_color(0, 0.8, 0.8) + circ = self.viewer.draw_circle(0.1) + circ.set_color(0.8, 0.8, 0) + circ.add_attr(jtransform) + + return self.viewer.render(return_rgb_array=mode == "rgb_array") + + def close(self): + if self.viewer: + self.viewer.close() + self.viewer = None + + +def wrap(x, m, M): + """Wraps ``x`` so m <= x <= M; but unlike ``bound()`` which + truncates, ``wrap()`` wraps x around the coordinate system defined by m,M.\n + For example, m = -180, M = 180 (degrees), x = 360 --> returns 0. + + Args: + x: a scalar + m: minimum possible value in range + M: maximum possible value in range + + Returns: + x: a scalar, wrapped + """ + diff = M - m + while x > M: + x = x - diff + while x < m: + x = x + diff + return x + + +def bound(x, m, M=None): + """Either have m as scalar, so bound(x,m,M) which returns m <= x <= M *OR* + have m as length 2 vector, bound(x,m, ) returns m[0] <= x <= m[1]. + + Args: + x: scalar + + Returns: + x: scalar, bound between min (m) and Max (M) + """ + if M is None: + M = m[1] + m = m[0] + # bound x between min (m) and Max (M) + return min(max(x, m), M) + + +def rk4(derivs, y0, t): + """ + Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta. + This is a toy implementation which may be useful if you find + yourself stranded on a system w/o scipy. Otherwise use + :func:`scipy.integrate`. + + Args: + derivs: the derivative of the system and has the signature ``dy = derivs(yi)`` + y0: initial state vector + t: sample times + args: additional arguments passed to the derivative function + kwargs: additional keyword arguments passed to the derivative function + + Example 1 :: + ## 2D system + def derivs(x): + d1 = x[0] + 2*x[1] + d2 = -3*x[0] + 4*x[1] + return (d1, d2) + dt = 0.0005 + t = arange(0.0, 2.0, dt) + y0 = (1,2) + yout = rk4(derivs6, y0, t) + + If you have access to scipy, you should probably be using the + scipy.integrate tools rather than this function. + This would then require re-adding the time variable to the signature of derivs. + + Returns: + yout: Runge-Kutta approximation of the ODE + """ + + try: + Ny = len(y0) + except TypeError: + yout = np.zeros((len(t),), np.float_) + else: + yout = np.zeros((len(t), Ny), np.float_) + + yout[0] = y0 + + for i in np.arange(len(t) - 1): + + thist = t[i] + dt = t[i + 1] - thist + dt2 = dt / 2.0 + y0 = yout[i] + + k1 = np.asarray(derivs(y0)) + k2 = np.asarray(derivs(y0 + dt2 * k1)) + k3 = np.asarray(derivs(y0 + dt2 * k2)) + k4 = np.asarray(derivs(y0 + dt * k3)) + yout[i + 1] = y0 + dt / 6.0 * (k1 + 2 * k2 + 2 * k3 + k4) + # We only care about the final timestep and we cleave off action value which will be zero + return yout[-1][:4] diff --git a/gym/envs/classic_control/assets/clockwise.png b/gym/envs/classic_control/assets/clockwise.png new file mode 100644 index 0000000000000000000000000000000000000000..1aa423652b279e6bf31cd1f06bed6a9c421f9323 Binary files /dev/null and b/gym/envs/classic_control/assets/clockwise.png differ diff --git a/gym/envs/classic_control/cartpole.py b/gym/envs/classic_control/cartpole.py new file mode 100644 index 0000000000000000000000000000000000000000..e11adcba6f413017e8661e8990dde668a63a129c --- /dev/null +++ b/gym/envs/classic_control/cartpole.py @@ -0,0 +1,234 @@ +""" +Classic cart-pole system implemented by Rich Sutton et al. +Copied from http://incompleteideas.net/sutton/book/code/pole.c +permalink: https://perma.cc/C9ZM-652R +""" + +import math +import gym +from gym import spaces, logger +from gym.utils import seeding +import numpy as np + + +class CartPoleEnv(gym.Env): + """ + Description: + A pole is attached by an un-actuated joint to a cart, which moves along + a frictionless track. The pendulum starts upright, and the goal is to + prevent it from falling over by increasing and reducing the cart's + velocity. + + Source: + This environment corresponds to the version of the cart-pole problem + described by Barto, Sutton, and Anderson + + Observation: + Type: Box(4) + Num Observation Min Max + 0 Cart Position -4.8 4.8 + 1 Cart Velocity -Inf Inf + 2 Pole Angle -0.418 rad (-24 deg) 0.418 rad (24 deg) + 3 Pole Angular Velocity -Inf Inf + + Actions: + Type: Discrete(2) + Num Action + 0 Push cart to the left + 1 Push cart to the right + + Note: The amount the velocity that is reduced or increased is not + fixed; it depends on the angle the pole is pointing. This is because + the center of gravity of the pole increases the amount of energy needed + to move the cart underneath it + + Reward: + Reward is 1 for every step taken, including the termination step + + Starting State: + All observations are assigned a uniform random value in [-0.05..0.05] + + Episode Termination: + Pole Angle is more than 12 degrees. + Cart Position is more than 2.4 (center of the cart reaches the edge of + the display). + Episode length is greater than 200. + Solved Requirements: + Considered solved when the average return is greater than or equal to + 195.0 over 100 consecutive trials. + """ + + metadata = {"render.modes": ["human", "rgb_array"], "video.frames_per_second": 50} + + def __init__(self): + self.gravity = 9.8 + self.masscart = 1.0 + self.masspole = 0.1 + self.total_mass = self.masspole + self.masscart + self.length = 0.5 # actually half the pole's length + self.polemass_length = self.masspole * self.length + self.force_mag = 10.0 + self.tau = 0.02 # seconds between state updates + self.kinematics_integrator = "euler" + + # Angle at which to fail the episode + self.theta_threshold_radians = 12 * 2 * math.pi / 360 + self.x_threshold = 2.4 + + # Angle limit set to 2 * theta_threshold_radians so failing observation + # is still within bounds. + high = np.array( + [ + self.x_threshold * 2, + np.finfo(np.float32).max, + self.theta_threshold_radians * 2, + np.finfo(np.float32).max, + ], + dtype=np.float32, + ) + + self.action_space = spaces.Discrete(2) + self.observation_space = spaces.Box(-high, high, dtype=np.float32) + + self.seed() + self.viewer = None + self.state = None + + self.steps_beyond_done = None + + def seed(self, seed=None): + self.np_random, seed = seeding.np_random(seed) + return [seed] + + def step(self, action): + err_msg = "%r (%s) invalid" % (action, type(action)) + assert self.action_space.contains(action), err_msg + + x, x_dot, theta, theta_dot = self.state + force = self.force_mag if action == 1 else -self.force_mag + costheta = math.cos(theta) + sintheta = math.sin(theta) + + # For the interested reader: + # https://coneural.org/florian/papers/05_cart_pole.pdf + temp = ( + force + self.polemass_length * theta_dot ** 2 * sintheta + ) / self.total_mass + thetaacc = (self.gravity * sintheta - costheta * temp) / ( + self.length * (4.0 / 3.0 - self.masspole * costheta ** 2 / self.total_mass) + ) + xacc = temp - self.polemass_length * thetaacc * costheta / self.total_mass + + if self.kinematics_integrator == "euler": + x = x + self.tau * x_dot + x_dot = x_dot + self.tau * xacc + theta = theta + self.tau * theta_dot + theta_dot = theta_dot + self.tau * thetaacc + else: # semi-implicit euler + x_dot = x_dot + self.tau * xacc + x = x + self.tau * x_dot + theta_dot = theta_dot + self.tau * thetaacc + theta = theta + self.tau * theta_dot + + self.state = (x, x_dot, theta, theta_dot) + + done = bool( + x < -self.x_threshold + or x > self.x_threshold + or theta < -self.theta_threshold_radians + or theta > self.theta_threshold_radians + ) + + if not done: + reward = 1.0 + elif self.steps_beyond_done is None: + # Pole just fell! + self.steps_beyond_done = 0 + reward = 1.0 + else: + if self.steps_beyond_done == 0: + logger.warn( + "You are calling 'step()' even though this " + "environment has already returned done = True. You " + "should always call 'reset()' once you receive 'done = " + "True' -- any further steps are undefined behavior." + ) + self.steps_beyond_done += 1 + reward = 0.0 + + return np.array(self.state, dtype=np.float32), reward, done, {} + + def reset(self): + self.state = self.np_random.uniform(low=-0.05, high=0.05, size=(4,)) + self.steps_beyond_done = None + return np.array(self.state, dtype=np.float32) + + def render(self, mode="human"): + screen_width = 600 + screen_height = 400 + + world_width = self.x_threshold * 2 + scale = screen_width / world_width + carty = 100 # TOP OF CART + polewidth = 10.0 + polelen = scale * (2 * self.length) + cartwidth = 50.0 + cartheight = 30.0 + + if self.viewer is None: + from gym.envs.classic_control import rendering + + self.viewer = rendering.Viewer(screen_width, screen_height) + l, r, t, b = -cartwidth / 2, cartwidth / 2, cartheight / 2, -cartheight / 2 + axleoffset = cartheight / 4.0 + cart = rendering.FilledPolygon([(l, b), (l, t), (r, t), (r, b)]) + self.carttrans = rendering.Transform() + cart.add_attr(self.carttrans) + self.viewer.add_geom(cart) + l, r, t, b = ( + -polewidth / 2, + polewidth / 2, + polelen - polewidth / 2, + -polewidth / 2, + ) + pole = rendering.FilledPolygon([(l, b), (l, t), (r, t), (r, b)]) + pole.set_color(0.8, 0.6, 0.4) + self.poletrans = rendering.Transform(translation=(0, axleoffset)) + pole.add_attr(self.poletrans) + pole.add_attr(self.carttrans) + self.viewer.add_geom(pole) + self.axle = rendering.make_circle(polewidth / 2) + self.axle.add_attr(self.poletrans) + self.axle.add_attr(self.carttrans) + self.axle.set_color(0.5, 0.5, 0.8) + self.viewer.add_geom(self.axle) + self.track = rendering.Line((0, carty), (screen_width, carty)) + self.track.set_color(0, 0, 0) + self.viewer.add_geom(self.track) + + self._pole_geom = pole + + if self.state is None: + return None + + # Edit the pole polygon vertex + pole = self._pole_geom + l, r, t, b = ( + -polewidth / 2, + polewidth / 2, + polelen - polewidth / 2, + -polewidth / 2, + ) + pole.v = [(l, b), (l, t), (r, t), (r, b)] + + x = self.state + cartx = x[0] * scale + screen_width / 2.0 # MIDDLE OF CART + self.carttrans.set_translation(cartx, carty) + self.poletrans.set_rotation(-x[2]) + + return self.viewer.render(return_rgb_array=mode == "rgb_array") + + def close(self): + if self.viewer: + self.viewer.close() + self.viewer = None diff --git a/gym/envs/classic_control/continuous_mountain_car.py b/gym/envs/classic_control/continuous_mountain_car.py new file mode 100644 index 0000000000000000000000000000000000000000..65314444fc953ef32c3980b5bf9400925e9c1608 --- /dev/null +++ b/gym/envs/classic_control/continuous_mountain_car.py @@ -0,0 +1,195 @@ +# -*- coding: utf-8 -*- +""" +@author: Olivier Sigaud + +A merge between two sources: + +* Adaptation of the MountainCar Environment from the "FAReinforcement" library +of Jose Antonio Martin H. (version 1.0), adapted by 'Tom Schaul, tom@idsia.ch' +and then modified by Arnaud de Broissia + +* the OpenAI/gym MountainCar environment +itself from +http://incompleteideas.net/sutton/MountainCar/MountainCar1.cp +permalink: https://perma.cc/6Z2N-PFWC +""" + +import math + +import numpy as np + +import gym +from gym import spaces +from gym.utils import seeding + + +class Continuous_MountainCarEnv(gym.Env): + """ + Description: + The agent (a car) is started at the bottom of a valley. For any given + state the agent may choose to accelerate to the left, right or cease + any acceleration. + Observation: + Type: Box(2) + Num Observation Min Max + 0 Car Position -1.2 0.6 + 1 Car Velocity -0.07 0.07 + Actions: + Type: Box(1) + Num Action Min Max + 0 the power coef -1.0 1.0 + Note: actual driving force is calculated by multipling the power coef by power (0.0015) + + Reward: + Reward of 100 is awarded if the agent reached the flag (position = 0.45) on top of the mountain. + Reward is decrease based on amount of energy consumed each step. + + Starting State: + The position of the car is assigned a uniform random value in + [-0.6 , -0.4]. + The starting velocity of the car is always assigned to 0. + + Episode Termination: + The car position is more than 0.45 + Episode length is greater than 200 + """ + + metadata = {"render.modes": ["human", "rgb_array"], "video.frames_per_second": 30} + + def __init__(self, goal_velocity=0): + self.min_action = -1.0 + self.max_action = 1.0 + self.min_position = -1.2 + self.max_position = 0.6 + self.max_speed = 0.07 + self.goal_position = ( + 0.45 # was 0.5 in gym, 0.45 in Arnaud de Broissia's version + ) + self.goal_velocity = goal_velocity + self.power = 0.0015 + + self.low_state = np.array( + [self.min_position, -self.max_speed], dtype=np.float32 + ) + self.high_state = np.array( + [self.max_position, self.max_speed], dtype=np.float32 + ) + + self.viewer = None + + self.action_space = spaces.Box( + low=self.min_action, high=self.max_action, shape=(1,), dtype=np.float32 + ) + self.observation_space = spaces.Box( + low=self.low_state, high=self.high_state, dtype=np.float32 + ) + + self.seed() + + def seed(self, seed=None): + self.np_random, seed = seeding.np_random(seed) + return [seed] + + def step(self, action): + + position = self.state[0] + velocity = self.state[1] + force = min(max(action[0], self.min_action), self.max_action) + + velocity += force * self.power - 0.0025 * math.cos(3 * position) + if velocity > self.max_speed: + velocity = self.max_speed + if velocity < -self.max_speed: + velocity = -self.max_speed + position += velocity + if position > self.max_position: + position = self.max_position + if position < self.min_position: + position = self.min_position + if position == self.min_position and velocity < 0: + velocity = 0 + + # Convert a possible numpy bool to a Python bool. + done = bool(position >= self.goal_position and velocity >= self.goal_velocity) + + reward = 0 + if done: + reward = 100.0 + reward -= math.pow(action[0], 2) * 0.1 + + self.state = np.array([position, velocity], dtype=np.float32) + return self.state, reward, done, {} + + def reset(self): + self.state = np.array([self.np_random.uniform(low=-0.6, high=-0.4), 0]) + return np.array(self.state, dtype=np.float32) + + def _height(self, xs): + return np.sin(3 * xs) * 0.45 + 0.55 + + def render(self, mode="human"): + screen_width = 600 + screen_height = 400 + + world_width = self.max_position - self.min_position + scale = screen_width / world_width + carwidth = 40 + carheight = 20 + + if self.viewer is None: + from gym.envs.classic_control import rendering + + self.viewer = rendering.Viewer(screen_width, screen_height) + xs = np.linspace(self.min_position, self.max_position, 100) + ys = self._height(xs) + xys = list(zip((xs - self.min_position) * scale, ys * scale)) + + self.track = rendering.make_polyline(xys) + self.track.set_linewidth(4) + self.viewer.add_geom(self.track) + + clearance = 10 + + l, r, t, b = -carwidth / 2, carwidth / 2, carheight, 0 + car = rendering.FilledPolygon([(l, b), (l, t), (r, t), (r, b)]) + car.add_attr(rendering.Transform(translation=(0, clearance))) + self.cartrans = rendering.Transform() + car.add_attr(self.cartrans) + self.viewer.add_geom(car) + frontwheel = rendering.make_circle(carheight / 2.5) + frontwheel.set_color(0.5, 0.5, 0.5) + frontwheel.add_attr( + rendering.Transform(translation=(carwidth / 4, clearance)) + ) + frontwheel.add_attr(self.cartrans) + self.viewer.add_geom(frontwheel) + backwheel = rendering.make_circle(carheight / 2.5) + backwheel.add_attr( + rendering.Transform(translation=(-carwidth / 4, clearance)) + ) + backwheel.add_attr(self.cartrans) + backwheel.set_color(0.5, 0.5, 0.5) + self.viewer.add_geom(backwheel) + flagx = (self.goal_position - self.min_position) * scale + flagy1 = self._height(self.goal_position) * scale + flagy2 = flagy1 + 50 + flagpole = rendering.Line((flagx, flagy1), (flagx, flagy2)) + self.viewer.add_geom(flagpole) + flag = rendering.FilledPolygon( + [(flagx, flagy2), (flagx, flagy2 - 10), (flagx + 25, flagy2 - 5)] + ) + flag.set_color(0.8, 0.8, 0) + self.viewer.add_geom(flag) + + pos = self.state[0] + self.cartrans.set_translation( + (pos - self.min_position) * scale, self._height(pos) * scale + ) + self.cartrans.set_rotation(math.cos(3 * pos)) + + return self.viewer.render(return_rgb_array=mode == "rgb_array") + + def close(self): + if self.viewer: + self.viewer.close() + self.viewer = None diff --git a/gym/envs/classic_control/mountain_car.py b/gym/envs/classic_control/mountain_car.py new file mode 100644 index 0000000000000000000000000000000000000000..e096774b00cf316451db524a3c223609f992cf66 --- /dev/null +++ b/gym/envs/classic_control/mountain_car.py @@ -0,0 +1,177 @@ +""" +http://incompleteideas.net/MountainCar/MountainCar1.cp +permalink: https://perma.cc/6Z2N-PFWC +""" +import math + +import numpy as np + +import gym +from gym import spaces +from gym.utils import seeding + + +class MountainCarEnv(gym.Env): + """ + Description: + The agent (a car) is started at the bottom of a valley. For any given + state the agent may choose to accelerate to the left, right or cease + any acceleration. + + Source: + The environment appeared first in Andrew Moore's PhD Thesis (1990). + + Observation: + Type: Box(2) + Num Observation Min Max + 0 Car Position -1.2 0.6 + 1 Car Velocity -0.07 0.07 + + Actions: + Type: Discrete(3) + Num Action + 0 Accelerate to the Left + 1 Don't accelerate + 2 Accelerate to the Right + + Note: This does not affect the amount of velocity affected by the + gravitational pull acting on the car. + + Reward: + Reward of 0 is awarded if the agent reached the flag (position = 0.5) + on top of the mountain. + Reward of -1 is awarded if the position of the agent is less than 0.5. + + Starting State: + The position of the car is assigned a uniform random value in + [-0.6 , -0.4]. + The starting velocity of the car is always assigned to 0. + + Episode Termination: + The car position is more than 0.5 + Episode length is greater than 200 + """ + + metadata = {"render.modes": ["human", "rgb_array"], "video.frames_per_second": 30} + + def __init__(self, goal_velocity=0): + self.min_position = -1.2 + self.max_position = 0.6 + self.max_speed = 0.07 + self.goal_position = 0.5 + self.goal_velocity = goal_velocity + + self.force = 0.001 + self.gravity = 0.0025 + + self.low = np.array([self.min_position, -self.max_speed], dtype=np.float32) + self.high = np.array([self.max_position, self.max_speed], dtype=np.float32) + + self.viewer = None + + self.action_space = spaces.Discrete(3) + self.observation_space = spaces.Box(self.low, self.high, dtype=np.float32) + + self.seed() + + def seed(self, seed=None): + self.np_random, seed = seeding.np_random(seed) + return [seed] + + def step(self, action): + assert self.action_space.contains(action), "%r (%s) invalid" % ( + action, + type(action), + ) + + position, velocity = self.state + velocity += (action - 1) * self.force + math.cos(3 * position) * (-self.gravity) + velocity = np.clip(velocity, -self.max_speed, self.max_speed) + position += velocity + position = np.clip(position, self.min_position, self.max_position) + if position == self.min_position and velocity < 0: + velocity = 0 + + done = bool(position >= self.goal_position and velocity >= self.goal_velocity) + reward = -1.0 + + self.state = (position, velocity) + return np.array(self.state, dtype=np.float32), reward, done, {} + + def reset(self): + self.state = np.array([self.np_random.uniform(low=-0.6, high=-0.4), 0]) + return np.array(self.state, dtype=np.float32) + + def _height(self, xs): + return np.sin(3 * xs) * 0.45 + 0.55 + + def render(self, mode="human"): + screen_width = 600 + screen_height = 400 + + world_width = self.max_position - self.min_position + scale = screen_width / world_width + carwidth = 40 + carheight = 20 + + if self.viewer is None: + from gym.envs.classic_control import rendering + + self.viewer = rendering.Viewer(screen_width, screen_height) + xs = np.linspace(self.min_position, self.max_position, 100) + ys = self._height(xs) + xys = list(zip((xs - self.min_position) * scale, ys * scale)) + + self.track = rendering.make_polyline(xys) + self.track.set_linewidth(4) + self.viewer.add_geom(self.track) + + clearance = 10 + + l, r, t, b = -carwidth / 2, carwidth / 2, carheight, 0 + car = rendering.FilledPolygon([(l, b), (l, t), (r, t), (r, b)]) + car.add_attr(rendering.Transform(translation=(0, clearance))) + self.cartrans = rendering.Transform() + car.add_attr(self.cartrans) + self.viewer.add_geom(car) + frontwheel = rendering.make_circle(carheight / 2.5) + frontwheel.set_color(0.5, 0.5, 0.5) + frontwheel.add_attr( + rendering.Transform(translation=(carwidth / 4, clearance)) + ) + frontwheel.add_attr(self.cartrans) + self.viewer.add_geom(frontwheel) + backwheel = rendering.make_circle(carheight / 2.5) + backwheel.add_attr( + rendering.Transform(translation=(-carwidth / 4, clearance)) + ) + backwheel.add_attr(self.cartrans) + backwheel.set_color(0.5, 0.5, 0.5) + self.viewer.add_geom(backwheel) + flagx = (self.goal_position - self.min_position) * scale + flagy1 = self._height(self.goal_position) * scale + flagy2 = flagy1 + 50 + flagpole = rendering.Line((flagx, flagy1), (flagx, flagy2)) + self.viewer.add_geom(flagpole) + flag = rendering.FilledPolygon( + [(flagx, flagy2), (flagx, flagy2 - 10), (flagx + 25, flagy2 - 5)] + ) + flag.set_color(0.8, 0.8, 0) + self.viewer.add_geom(flag) + + pos = self.state[0] + self.cartrans.set_translation( + (pos - self.min_position) * scale, self._height(pos) * scale + ) + self.cartrans.set_rotation(math.cos(3 * pos)) + + return self.viewer.render(return_rgb_array=mode == "rgb_array") + + def get_keys_to_action(self): + # Control with left and right arrow keys. + return {(): 1, (276,): 0, (275,): 2, (275, 276): 1} + + def close(self): + if self.viewer: + self.viewer.close() + self.viewer = None diff --git a/gym/envs/classic_control/pendulum.py b/gym/envs/classic_control/pendulum.py new file mode 100644 index 0000000000000000000000000000000000000000..10ced4d43d218fbf0bb344b3bbc006fcaa7f8362 --- /dev/null +++ b/gym/envs/classic_control/pendulum.py @@ -0,0 +1,94 @@ +import gym +from gym import spaces +from gym.utils import seeding +import numpy as np +from os import path + + +class PendulumEnv(gym.Env): + metadata = {"render.modes": ["human", "rgb_array"], "video.frames_per_second": 30} + + def __init__(self, g=10.0): + self.max_speed = 8 + self.max_torque = 2.0 + self.dt = 0.05 + self.g = g + self.m = 1.0 + self.l = 1.0 + self.viewer = None + + high = np.array([1.0, 1.0, self.max_speed], dtype=np.float32) + self.action_space = spaces.Box( + low=-self.max_torque, high=self.max_torque, shape=(1,), dtype=np.float32 + ) + self.observation_space = spaces.Box(low=-high, high=high, dtype=np.float32) + + self.seed() + + def seed(self, seed=None): + self.np_random, seed = seeding.np_random(seed) + return [seed] + + def step(self, u): + th, thdot = self.state # th := theta + + g = self.g + m = self.m + l = self.l + dt = self.dt + + u = np.clip(u, -self.max_torque, self.max_torque)[0] + self.last_u = u # for rendering + costs = angle_normalize(th) ** 2 + 0.1 * thdot ** 2 + 0.001 * (u ** 2) + + newthdot = thdot + (3 * g / (2 * l) * np.sin(th) + 3.0 / (m * l ** 2) * u) * dt + newthdot = np.clip(newthdot, -self.max_speed, self.max_speed) + newth = th + newthdot * dt + + self.state = np.array([newth, newthdot]) + return self._get_obs(), -costs, False, {} + + def reset(self): + high = np.array([np.pi, 1]) + self.state = self.np_random.uniform(low=-high, high=high) + self.last_u = None + return self._get_obs() + + def _get_obs(self): + theta, thetadot = self.state + return np.array([np.cos(theta), np.sin(theta), thetadot], dtype=np.float32) + + def render(self, mode="human"): + if self.viewer is None: + from gym.envs.classic_control import rendering + + self.viewer = rendering.Viewer(500, 500) + self.viewer.set_bounds(-2.2, 2.2, -2.2, 2.2) + rod = rendering.make_capsule(1, 0.2) + rod.set_color(0.8, 0.3, 0.3) + self.pole_transform = rendering.Transform() + rod.add_attr(self.pole_transform) + self.viewer.add_geom(rod) + axle = rendering.make_circle(0.05) + axle.set_color(0, 0, 0) + self.viewer.add_geom(axle) + fname = path.join(path.dirname(__file__), "assets/clockwise.png") + self.img = rendering.Image(fname, 1.0, 1.0) + self.imgtrans = rendering.Transform() + self.img.add_attr(self.imgtrans) + + self.viewer.add_onetime(self.img) + self.pole_transform.set_rotation(self.state[0] + np.pi / 2) + if self.last_u is not None: + self.imgtrans.scale = (-self.last_u / 2, np.abs(self.last_u) / 2) + + return self.viewer.render(return_rgb_array=mode == "rgb_array") + + def close(self): + if self.viewer: + self.viewer.close() + self.viewer = None + + +def angle_normalize(x): + return ((x + np.pi) % (2 * np.pi)) - np.pi diff --git a/gym/envs/classic_control/rendering.py b/gym/envs/classic_control/rendering.py new file mode 100644 index 0000000000000000000000000000000000000000..cf64db90070db8f8c16043ddc0f7bcbb89be2b3f --- /dev/null +++ b/gym/envs/classic_control/rendering.py @@ -0,0 +1,458 @@ +""" +2D rendering framework +""" +import os +import sys + +if "Apple" in sys.version: + if "DYLD_FALLBACK_LIBRARY_PATH" in os.environ: + os.environ["DYLD_FALLBACK_LIBRARY_PATH"] += ":/usr/lib" + # (JDS 2016/04/15): avoid bug on Anaconda 2.3.0 / Yosemite + +from gym import error + +try: + import pyglet +except ImportError as e: + raise ImportError( + """ + Cannot import pyglet. + HINT: you can install pyglet directly via 'pip install pyglet'. + But if you really just want to install all Gym dependencies and not have to think about it, + 'pip install -e .[all]' or 'pip install gym[all]' will do it. + """ + ) + +try: + from pyglet.gl import * +except ImportError as e: + raise ImportError( + """ + Error occurred while running `from pyglet.gl import *` + HINT: make sure you have OpenGL installed. On Ubuntu, you can run 'apt-get install python-opengl'. + If you're running on a server, you may need a virtual frame buffer; something like this should work: + 'xvfb-run -s \"-screen 0 1400x900x24\" python ' + """ + ) + +import math +import numpy as np + +RAD2DEG = 57.29577951308232 + + +def get_display(spec): + """Convert a display specification (such as :0) into an actual Display + object. + + Pyglet only supports multiple Displays on Linux. + """ + if spec is None: + return pyglet.canvas.get_display() + # returns already available pyglet_display, + # if there is no pyglet display available then it creates one + elif isinstance(spec, str): + return pyglet.canvas.Display(spec) + else: + raise error.Error( + "Invalid display specification: {}. (Must be a string like :0 or None.)".format( + spec + ) + ) + + +def get_window(width, height, display, **kwargs): + """ + Will create a pyglet window from the display specification provided. + """ + screen = display.get_screens() # available screens + config = screen[0].get_best_config() # selecting the first screen + context = config.create_context(None) # create GL context + + return pyglet.window.Window( + width=width, + height=height, + display=display, + config=config, + context=context, + **kwargs + ) + + +class Viewer(object): + def __init__(self, width, height, display=None): + display = get_display(display) + + self.width = width + self.height = height + self.window = get_window(width=width, height=height, display=display) + self.window.on_close = self.window_closed_by_user + self.isopen = True + self.geoms = [] + self.onetime_geoms = [] + self.transform = Transform() + + glEnable(GL_BLEND) + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) + + def close(self): + if self.isopen and sys.meta_path: + # ^^^ check sys.meta_path to avoid 'ImportError: sys.meta_path is None, Python is likely shutting down' + self.window.close() + self.isopen = False + + def window_closed_by_user(self): + self.isopen = False + + def set_bounds(self, left, right, bottom, top): + assert right > left and top > bottom + scalex = self.width / (right - left) + scaley = self.height / (top - bottom) + self.transform = Transform( + translation=(-left * scalex, -bottom * scaley), scale=(scalex, scaley) + ) + + def add_geom(self, geom): + self.geoms.append(geom) + + def add_onetime(self, geom): + self.onetime_geoms.append(geom) + + def render(self, return_rgb_array=False): + glClearColor(1, 1, 1, 1) + self.window.clear() + self.window.switch_to() + self.window.dispatch_events() + self.transform.enable() + for geom in self.geoms: + geom.render() + for geom in self.onetime_geoms: + geom.render() + self.transform.disable() + arr = None + if return_rgb_array: + buffer = pyglet.image.get_buffer_manager().get_color_buffer() + image_data = buffer.get_image_data() + arr = np.frombuffer(image_data.get_data(), dtype=np.uint8) + # In https://github.com/openai/gym-http-api/issues/2, we + # discovered that someone using Xmonad on Arch was having + # a window of size 598 x 398, though a 600 x 400 window + # was requested. (Guess Xmonad was preserving a pixel for + # the boundary.) So we use the buffer height/width rather + # than the requested one. + arr = arr.reshape(buffer.height, buffer.width, 4) + arr = arr[::-1, :, 0:3] + self.window.flip() + self.onetime_geoms = [] + return arr if return_rgb_array else self.isopen + + # Convenience + def draw_circle(self, radius=10, res=30, filled=True, **attrs): + geom = make_circle(radius=radius, res=res, filled=filled) + _add_attrs(geom, attrs) + self.add_onetime(geom) + return geom + + def draw_polygon(self, v, filled=True, **attrs): + geom = make_polygon(v=v, filled=filled) + _add_attrs(geom, attrs) + self.add_onetime(geom) + return geom + + def draw_polyline(self, v, **attrs): + geom = make_polyline(v=v) + _add_attrs(geom, attrs) + self.add_onetime(geom) + return geom + + def draw_line(self, start, end, **attrs): + geom = Line(start, end) + _add_attrs(geom, attrs) + self.add_onetime(geom) + return geom + + def get_array(self): + self.window.flip() + image_data = ( + pyglet.image.get_buffer_manager().get_color_buffer().get_image_data() + ) + self.window.flip() + arr = np.fromstring(image_data.get_data(), dtype=np.uint8, sep="") + arr = arr.reshape(self.height, self.width, 4) + return arr[::-1, :, 0:3] + + def __del__(self): + self.close() + + +def _add_attrs(geom, attrs): + if "color" in attrs: + geom.set_color(*attrs["color"]) + if "linewidth" in attrs: + geom.set_linewidth(attrs["linewidth"]) + + +class Geom(object): + def __init__(self): + self._color = Color((0, 0, 0, 1.0)) + self.attrs = [self._color] + + def render(self): + for attr in reversed(self.attrs): + attr.enable() + self.render1() + for attr in self.attrs: + attr.disable() + + def render1(self): + raise NotImplementedError + + def add_attr(self, attr): + self.attrs.append(attr) + + def set_color(self, r, g, b): + self._color.vec4 = (r, g, b, 1) + + +class Attr(object): + def enable(self): + raise NotImplementedError + + def disable(self): + pass + + +class Transform(Attr): + def __init__(self, translation=(0.0, 0.0), rotation=0.0, scale=(1, 1)): + self.set_translation(*translation) + self.set_rotation(rotation) + self.set_scale(*scale) + + def enable(self): + glPushMatrix() + glTranslatef( + self.translation[0], self.translation[1], 0 + ) # translate to GL loc ppint + glRotatef(RAD2DEG * self.rotation, 0, 0, 1.0) + glScalef(self.scale[0], self.scale[1], 1) + + def disable(self): + glPopMatrix() + + def set_translation(self, newx, newy): + self.translation = (float(newx), float(newy)) + + def set_rotation(self, new): + self.rotation = float(new) + + def set_scale(self, newx, newy): + self.scale = (float(newx), float(newy)) + + +class Color(Attr): + def __init__(self, vec4): + self.vec4 = vec4 + + def enable(self): + glColor4f(*self.vec4) + + +class LineStyle(Attr): + def __init__(self, style): + self.style = style + + def enable(self): + glEnable(GL_LINE_STIPPLE) + glLineStipple(1, self.style) + + def disable(self): + glDisable(GL_LINE_STIPPLE) + + +class LineWidth(Attr): + def __init__(self, stroke): + self.stroke = stroke + + def enable(self): + glLineWidth(self.stroke) + + +class Point(Geom): + def __init__(self): + Geom.__init__(self) + + def render1(self): + glBegin(GL_POINTS) # draw point + glVertex3f(0.0, 0.0, 0.0) + glEnd() + + +class FilledPolygon(Geom): + def __init__(self, v): + Geom.__init__(self) + self.v = v + + def render1(self): + if len(self.v) == 4: + glBegin(GL_QUADS) + elif len(self.v) > 4: + glBegin(GL_POLYGON) + else: + glBegin(GL_TRIANGLES) + for p in self.v: + glVertex3f(p[0], p[1], 0) # draw each vertex + glEnd() + + +def make_circle(radius=10, res=30, filled=True): + points = [] + for i in range(res): + ang = 2 * math.pi * i / res + points.append((math.cos(ang) * radius, math.sin(ang) * radius)) + if filled: + return FilledPolygon(points) + else: + return PolyLine(points, True) + + +def make_polygon(v, filled=True): + if filled: + return FilledPolygon(v) + else: + return PolyLine(v, True) + + +def make_polyline(v): + return PolyLine(v, False) + + +def make_capsule(length, width): + l, r, t, b = 0, length, width / 2, -width / 2 + box = make_polygon([(l, b), (l, t), (r, t), (r, b)]) + circ0 = make_circle(width / 2) + circ1 = make_circle(width / 2) + circ1.add_attr(Transform(translation=(length, 0))) + geom = Compound([box, circ0, circ1]) + return geom + + +class Compound(Geom): + def __init__(self, gs): + Geom.__init__(self) + self.gs = gs + for g in self.gs: + g.attrs = [a for a in g.attrs if not isinstance(a, Color)] + + def render1(self): + for g in self.gs: + g.render() + + +class PolyLine(Geom): + def __init__(self, v, close): + Geom.__init__(self) + self.v = v + self.close = close + self.linewidth = LineWidth(1) + self.add_attr(self.linewidth) + + def render1(self): + glBegin(GL_LINE_LOOP if self.close else GL_LINE_STRIP) + for p in self.v: + glVertex3f(p[0], p[1], 0) # draw each vertex + glEnd() + + def set_linewidth(self, x): + self.linewidth.stroke = x + + +class Line(Geom): + def __init__(self, start=(0.0, 0.0), end=(0.0, 0.0)): + Geom.__init__(self) + self.start = start + self.end = end + self.linewidth = LineWidth(1) + self.add_attr(self.linewidth) + + def render1(self): + glBegin(GL_LINES) + glVertex2f(*self.start) + glVertex2f(*self.end) + glEnd() + + +class Image(Geom): + def __init__(self, fname, width, height): + Geom.__init__(self) + self.set_color(1.0, 1.0, 1.0) + self.width = width + self.height = height + img = pyglet.image.load(fname) + self.img = img + self.flip = False + + def render1(self): + self.img.blit( + -self.width / 2, -self.height / 2, width=self.width, height=self.height + ) + + +# ================================================================ + + +class SimpleImageViewer(object): + def __init__(self, display=None, maxwidth=500): + self.window = None + self.isopen = False + self.display = get_display(display) + self.maxwidth = maxwidth + + def imshow(self, arr): + if self.window is None: + height, width, _channels = arr.shape + if width > self.maxwidth: + scale = self.maxwidth / width + width = int(scale * width) + height = int(scale * height) + self.window = get_window( + width=width, + height=height, + display=self.display, + vsync=False, + resizable=True, + ) + self.width = width + self.height = height + self.isopen = True + + @self.window.event + def on_resize(width, height): + self.width = width + self.height = height + + @self.window.event + def on_close(): + self.isopen = False + + assert len(arr.shape) == 3, "You passed in an image with the wrong number shape" + image = pyglet.image.ImageData( + arr.shape[1], arr.shape[0], "RGB", arr.tobytes(), pitch=arr.shape[1] * -3 + ) + texture = image.get_texture() + gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) + texture.width = self.width + texture.height = self.height + self.window.clear() + self.window.switch_to() + self.window.dispatch_events() + texture.blit(0, 0) # draw + self.window.flip() + + def close(self): + if self.isopen and sys.meta_path: + # ^^^ check sys.meta_path to avoid 'ImportError: sys.meta_path is None, Python is likely shutting down' + self.window.close() + self.isopen = False + + def __del__(self): + self.close() diff --git a/gym/envs/mujoco/__init__.py b/gym/envs/mujoco/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..277aec80dfe105481344a4310eb5606dc2b29c04 --- /dev/null +++ b/gym/envs/mujoco/__init__.py @@ -0,0 +1,17 @@ +from gym.envs.mujoco.mujoco_env import MujocoEnv + +# ^^^^^ so that user gets the correct error +# message if mujoco is not installed correctly +from gym.envs.mujoco.ant import AntEnv +from gym.envs.mujoco.half_cheetah import HalfCheetahEnv +from gym.envs.mujoco.hopper import HopperEnv +from gym.envs.mujoco.walker2d import Walker2dEnv +from gym.envs.mujoco.humanoid import HumanoidEnv +from gym.envs.mujoco.inverted_pendulum import InvertedPendulumEnv +from gym.envs.mujoco.inverted_double_pendulum import InvertedDoublePendulumEnv +from gym.envs.mujoco.reacher import ReacherEnv +from gym.envs.mujoco.swimmer import SwimmerEnv +from gym.envs.mujoco.humanoidstandup import HumanoidStandupEnv +from gym.envs.mujoco.pusher import PusherEnv +from gym.envs.mujoco.thrower import ThrowerEnv +from gym.envs.mujoco.striker import StrikerEnv diff --git a/gym/envs/mujoco/__pycache__/__init__.cpython-39.pyc b/gym/envs/mujoco/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32d7c8a0526001cacf793cdc57fe8c80793a022f Binary files /dev/null and b/gym/envs/mujoco/__pycache__/__init__.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/ant.cpython-39.pyc b/gym/envs/mujoco/__pycache__/ant.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4debd714380bf09b4dae39b8398b79f199e2293f Binary files /dev/null and b/gym/envs/mujoco/__pycache__/ant.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/ant_v3.cpython-39.pyc b/gym/envs/mujoco/__pycache__/ant_v3.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34b3359af6faad9e6906b75c9aabe4c698d73bbe Binary files /dev/null and b/gym/envs/mujoco/__pycache__/ant_v3.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/half_cheetah.cpython-39.pyc b/gym/envs/mujoco/__pycache__/half_cheetah.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70f4e7799efa966ce39d790ec85347791333b969 Binary files /dev/null and b/gym/envs/mujoco/__pycache__/half_cheetah.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/half_cheetah_v3.cpython-39.pyc b/gym/envs/mujoco/__pycache__/half_cheetah_v3.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0d0a4730f31e1e2266ffee5318d8e8ced357d7f Binary files /dev/null and b/gym/envs/mujoco/__pycache__/half_cheetah_v3.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/hopper.cpython-39.pyc b/gym/envs/mujoco/__pycache__/hopper.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2434342ee069837d5c918a6d9dd176a4e45b93c5 Binary files /dev/null and b/gym/envs/mujoco/__pycache__/hopper.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/hopper_v3.cpython-39.pyc b/gym/envs/mujoco/__pycache__/hopper_v3.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f52ebdd66f00aa5c4db7ee7c335e6c491735ea0c Binary files /dev/null and b/gym/envs/mujoco/__pycache__/hopper_v3.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/humanoid.cpython-39.pyc b/gym/envs/mujoco/__pycache__/humanoid.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40c4559b936de77324c1804c67956171ac4635a9 Binary files /dev/null and b/gym/envs/mujoco/__pycache__/humanoid.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/humanoid_v3.cpython-39.pyc b/gym/envs/mujoco/__pycache__/humanoid_v3.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c5a06274ec1f438253f880148278512b4e32d7e Binary files /dev/null and b/gym/envs/mujoco/__pycache__/humanoid_v3.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/humanoidstandup.cpython-39.pyc b/gym/envs/mujoco/__pycache__/humanoidstandup.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bf0d179db23e895f9ca149dae37512fb0b44bc7 Binary files /dev/null and b/gym/envs/mujoco/__pycache__/humanoidstandup.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/inverted_double_pendulum.cpython-39.pyc b/gym/envs/mujoco/__pycache__/inverted_double_pendulum.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aebc6ca4952058b3ceaeeb56742f0e4642fb5286 Binary files /dev/null and b/gym/envs/mujoco/__pycache__/inverted_double_pendulum.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/inverted_pendulum.cpython-39.pyc b/gym/envs/mujoco/__pycache__/inverted_pendulum.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8721d5c70433c4e759e4d38c5914c9bc8baf030 Binary files /dev/null and b/gym/envs/mujoco/__pycache__/inverted_pendulum.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/mujoco_env.cpython-39.pyc b/gym/envs/mujoco/__pycache__/mujoco_env.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbb587c718389620808acd9328d8fb71c792397d Binary files /dev/null and b/gym/envs/mujoco/__pycache__/mujoco_env.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/pusher.cpython-39.pyc b/gym/envs/mujoco/__pycache__/pusher.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e7c754377be985363cc771bf3b2f676913863a0 Binary files /dev/null and b/gym/envs/mujoco/__pycache__/pusher.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/reacher.cpython-39.pyc b/gym/envs/mujoco/__pycache__/reacher.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab3c68fa312f4a75f7092c9752f281284f49fcd8 Binary files /dev/null and b/gym/envs/mujoco/__pycache__/reacher.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/striker.cpython-39.pyc b/gym/envs/mujoco/__pycache__/striker.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b63fea67379869d80f1855cacb6f006d8e41200e Binary files /dev/null and b/gym/envs/mujoco/__pycache__/striker.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/swimmer.cpython-39.pyc b/gym/envs/mujoco/__pycache__/swimmer.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea14331251787d2caa8a25aaea656410496a7db6 Binary files /dev/null and b/gym/envs/mujoco/__pycache__/swimmer.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/swimmer_v3.cpython-39.pyc b/gym/envs/mujoco/__pycache__/swimmer_v3.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4c8360b49a21d58a32977515d0d2a96bd8b76a4 Binary files /dev/null and b/gym/envs/mujoco/__pycache__/swimmer_v3.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/thrower.cpython-39.pyc b/gym/envs/mujoco/__pycache__/thrower.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9fdf77a8bfa0906a630242e2f415c2fbf42e2ce0 Binary files /dev/null and b/gym/envs/mujoco/__pycache__/thrower.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/walker2d.cpython-39.pyc b/gym/envs/mujoco/__pycache__/walker2d.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cb334fd2568620245fa08d385dd7b23b8c21b5c Binary files /dev/null and b/gym/envs/mujoco/__pycache__/walker2d.cpython-39.pyc differ diff --git a/gym/envs/mujoco/__pycache__/walker2d_v3.cpython-39.pyc b/gym/envs/mujoco/__pycache__/walker2d_v3.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5aa31e85f5b587b2073460e0a835b1aa2c5e7636 Binary files /dev/null and b/gym/envs/mujoco/__pycache__/walker2d_v3.cpython-39.pyc differ diff --git a/gym/envs/mujoco/ant.py b/gym/envs/mujoco/ant.py new file mode 100644 index 0000000000000000000000000000000000000000..ae0a2f8dcf9846d6c28ced183e99bab1789f7014 --- /dev/null +++ b/gym/envs/mujoco/ant.py @@ -0,0 +1,56 @@ +import numpy as np +from gym import utils +from gym.envs.mujoco import mujoco_env + + +class AntEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__(self): + mujoco_env.MujocoEnv.__init__(self, "ant.xml", 5) + utils.EzPickle.__init__(self) + + def step(self, a): + xposbefore = self.get_body_com("torso")[0] + self.do_simulation(a, self.frame_skip) + xposafter = self.get_body_com("torso")[0] + forward_reward = (xposafter - xposbefore) / self.dt + ctrl_cost = 0.5 * np.square(a).sum() + contact_cost = ( + 0.5 * 1e-3 * np.sum(np.square(np.clip(self.sim.data.cfrc_ext, -1, 1))) + ) + survive_reward = 1.0 + reward = forward_reward - ctrl_cost - contact_cost + survive_reward + state = self.state_vector() + notdone = np.isfinite(state).all() and state[2] >= 0.2 and state[2] <= 1.0 + done = not notdone + ob = self._get_obs() + return ( + ob, + reward, + done, + dict( + reward_forward=forward_reward, + reward_ctrl=-ctrl_cost, + reward_contact=-contact_cost, + reward_survive=survive_reward, + ), + ) + + def _get_obs(self): + return np.concatenate( + [ + self.sim.data.qpos.flat[2:], + self.sim.data.qvel.flat, + np.clip(self.sim.data.cfrc_ext, -1, 1).flat, + ] + ) + + def reset_model(self): + qpos = self.init_qpos + self.np_random.uniform( + size=self.model.nq, low=-0.1, high=0.1 + ) + qvel = self.init_qvel + self.np_random.randn(self.model.nv) * 0.1 + self.set_state(qpos, qvel) + return self._get_obs() + + def viewer_setup(self): + self.viewer.cam.distance = self.model.stat.extent * 0.5 diff --git a/gym/envs/mujoco/ant_v3.py b/gym/envs/mujoco/ant_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..473f85daada5929482718169313bb1cbb33ae55c --- /dev/null +++ b/gym/envs/mujoco/ant_v3.py @@ -0,0 +1,148 @@ +import numpy as np +from gym import utils +from gym.envs.mujoco import mujoco_env + + +DEFAULT_CAMERA_CONFIG = { + "distance": 4.0, +} + + +class AntEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__( + self, + xml_file="ant.xml", + ctrl_cost_weight=0.5, + contact_cost_weight=5e-4, + healthy_reward=1.0, + terminate_when_unhealthy=True, + healthy_z_range=(0.2, 1.0), + contact_force_range=(-1.0, 1.0), + reset_noise_scale=0.1, + exclude_current_positions_from_observation=True, + ): + utils.EzPickle.__init__(**locals()) + + self._ctrl_cost_weight = ctrl_cost_weight + self._contact_cost_weight = contact_cost_weight + + self._healthy_reward = healthy_reward + self._terminate_when_unhealthy = terminate_when_unhealthy + self._healthy_z_range = healthy_z_range + + self._contact_force_range = contact_force_range + + self._reset_noise_scale = reset_noise_scale + + self._exclude_current_positions_from_observation = ( + exclude_current_positions_from_observation + ) + + mujoco_env.MujocoEnv.__init__(self, xml_file, 5) + + @property + def healthy_reward(self): + return ( + float(self.is_healthy or self._terminate_when_unhealthy) + * self._healthy_reward + ) + + def control_cost(self, action): + control_cost = self._ctrl_cost_weight * np.sum(np.square(action)) + return control_cost + + @property + def contact_forces(self): + raw_contact_forces = self.sim.data.cfrc_ext + min_value, max_value = self._contact_force_range + contact_forces = np.clip(raw_contact_forces, min_value, max_value) + return contact_forces + + @property + def contact_cost(self): + contact_cost = self._contact_cost_weight * np.sum( + np.square(self.contact_forces) + ) + return contact_cost + + @property + def is_healthy(self): + state = self.state_vector() + min_z, max_z = self._healthy_z_range + is_healthy = np.isfinite(state).all() and min_z <= state[2] <= max_z + return is_healthy + + @property + def done(self): + done = not self.is_healthy if self._terminate_when_unhealthy else False + return done + + def step(self, action): + xy_position_before = self.get_body_com("torso")[:2].copy() + self.do_simulation(action, self.frame_skip) + xy_position_after = self.get_body_com("torso")[:2].copy() + + xy_velocity = (xy_position_after - xy_position_before) / self.dt + x_velocity, y_velocity = xy_velocity + + ctrl_cost = self.control_cost(action) + contact_cost = self.contact_cost + + forward_reward = x_velocity + healthy_reward = self.healthy_reward + + rewards = forward_reward + healthy_reward + costs = ctrl_cost + contact_cost + + reward = rewards - costs + done = self.done + observation = self._get_obs() + info = { + "reward_forward": forward_reward, + "reward_ctrl": -ctrl_cost, + "reward_contact": -contact_cost, + "reward_survive": healthy_reward, + "x_position": xy_position_after[0], + "y_position": xy_position_after[1], + "distance_from_origin": np.linalg.norm(xy_position_after, ord=2), + "x_velocity": x_velocity, + "y_velocity": y_velocity, + "forward_reward": forward_reward, + } + + return observation, reward, done, info + + def _get_obs(self): + position = self.sim.data.qpos.flat.copy() + velocity = self.sim.data.qvel.flat.copy() + contact_force = self.contact_forces.flat.copy() + + if self._exclude_current_positions_from_observation: + position = position[2:] + + observations = np.concatenate((position, velocity, contact_force)) + + return observations + + def reset_model(self): + noise_low = -self._reset_noise_scale + noise_high = self._reset_noise_scale + + qpos = self.init_qpos + self.np_random.uniform( + low=noise_low, high=noise_high, size=self.model.nq + ) + qvel = self.init_qvel + self._reset_noise_scale * self.np_random.randn( + self.model.nv + ) + self.set_state(qpos, qvel) + + observation = self._get_obs() + + return observation + + def viewer_setup(self): + for key, value in DEFAULT_CAMERA_CONFIG.items(): + if isinstance(value, np.ndarray): + getattr(self.viewer.cam, key)[:] = value + else: + setattr(self.viewer.cam, key, value) diff --git a/gym/envs/mujoco/assets/ant.xml b/gym/envs/mujoco/assets/ant.xml new file mode 100644 index 0000000000000000000000000000000000000000..ee4d679981c136b949ce278f39ddbd16e42e5de3 --- /dev/null +++ b/gym/envs/mujoco/assets/ant.xml @@ -0,0 +1,81 @@ + + + diff --git a/gym/envs/mujoco/assets/half_cheetah.xml b/gym/envs/mujoco/assets/half_cheetah.xml new file mode 100644 index 0000000000000000000000000000000000000000..338c2e87a705c425ab7c2ff733d5c40c96fcc918 --- /dev/null +++ b/gym/envs/mujoco/assets/half_cheetah.xml @@ -0,0 +1,96 @@ + + + + + + + + + + diff --git a/gym/envs/mujoco/assets/hopper.xml b/gym/envs/mujoco/assets/hopper.xml new file mode 100644 index 0000000000000000000000000000000000000000..f18bc46994c5a725d31fb68c40342ce6be9846bc --- /dev/null +++ b/gym/envs/mujoco/assets/hopper.xml @@ -0,0 +1,48 @@ + + + + + + + + diff --git a/gym/envs/mujoco/assets/humanoid.xml b/gym/envs/mujoco/assets/humanoid.xml new file mode 100644 index 0000000000000000000000000000000000000000..a263bdbcf54f95b449486b18281d9dc0c24a0102 --- /dev/null +++ b/gym/envs/mujoco/assets/humanoid.xml @@ -0,0 +1,121 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/mujoco/assets/humanoidstandup.xml b/gym/envs/mujoco/assets/humanoidstandup.xml new file mode 100644 index 0000000000000000000000000000000000000000..854dbc91c1968478a6218b9dfaa9cef22d7067ba --- /dev/null +++ b/gym/envs/mujoco/assets/humanoidstandup.xml @@ -0,0 +1,121 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/mujoco/assets/inverted_double_pendulum.xml b/gym/envs/mujoco/assets/inverted_double_pendulum.xml new file mode 100644 index 0000000000000000000000000000000000000000..a274e8c5d5b7e13127c52d7cb1dcdff80fbe2222 --- /dev/null +++ b/gym/envs/mujoco/assets/inverted_double_pendulum.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/gym/envs/mujoco/assets/inverted_pendulum.xml b/gym/envs/mujoco/assets/inverted_pendulum.xml new file mode 100644 index 0000000000000000000000000000000000000000..b778ba0071693c16edce04058ca02d1aa1572c2f --- /dev/null +++ b/gym/envs/mujoco/assets/inverted_pendulum.xml @@ -0,0 +1,27 @@ + + + + + + + + + \ No newline at end of file diff --git a/gym/envs/mujoco/assets/point.xml b/gym/envs/mujoco/assets/point.xml new file mode 100644 index 0000000000000000000000000000000000000000..e35ef3de807585cf5dc586990b608ec1ef30c056 --- /dev/null +++ b/gym/envs/mujoco/assets/point.xml @@ -0,0 +1,31 @@ + + + diff --git a/gym/envs/mujoco/assets/pusher.xml b/gym/envs/mujoco/assets/pusher.xml new file mode 100644 index 0000000000000000000000000000000000000000..31a5ef706065f42c6fa62201edf800cc005b50e7 --- /dev/null +++ b/gym/envs/mujoco/assets/pusher.xml @@ -0,0 +1,91 @@ + + + diff --git a/gym/envs/mujoco/assets/reacher.xml b/gym/envs/mujoco/assets/reacher.xml new file mode 100644 index 0000000000000000000000000000000000000000..28ebd67124c15d7efe608207ca06552e7f8c7ccc --- /dev/null +++ b/gym/envs/mujoco/assets/reacher.xml @@ -0,0 +1,39 @@ + + + + + + + \ No newline at end of file diff --git a/gym/envs/mujoco/assets/striker.xml b/gym/envs/mujoco/assets/striker.xml new file mode 100644 index 0000000000000000000000000000000000000000..f66f8080646c3d586316e71173b1a3eac87286c4 --- /dev/null +++ b/gym/envs/mujoco/assets/striker.xml @@ -0,0 +1,101 @@ + + + diff --git a/gym/envs/mujoco/assets/swimmer.xml b/gym/envs/mujoco/assets/swimmer.xml new file mode 100644 index 0000000000000000000000000000000000000000..2ab6cbdd667255cfcc6ea8ad30b86f3d67c07c50 --- /dev/null +++ b/gym/envs/mujoco/assets/swimmer.xml @@ -0,0 +1,39 @@ + + + diff --git a/gym/envs/mujoco/assets/thrower.xml b/gym/envs/mujoco/assets/thrower.xml new file mode 100644 index 0000000000000000000000000000000000000000..b68f256054915f4df2a9318bf5db721062aa072e --- /dev/null +++ b/gym/envs/mujoco/assets/thrower.xml @@ -0,0 +1,127 @@ + + + diff --git a/gym/envs/mujoco/assets/walker2d.xml b/gym/envs/mujoco/assets/walker2d.xml new file mode 100644 index 0000000000000000000000000000000000000000..3342571666db0d2db1bfa6e58829b0cc4f36a60e --- /dev/null +++ b/gym/envs/mujoco/assets/walker2d.xml @@ -0,0 +1,62 @@ + + + + + + + diff --git a/gym/envs/mujoco/half_cheetah.py b/gym/envs/mujoco/half_cheetah.py new file mode 100644 index 0000000000000000000000000000000000000000..7044e94597b2213783dac24f75b54590bafea2aa --- /dev/null +++ b/gym/envs/mujoco/half_cheetah.py @@ -0,0 +1,39 @@ +import numpy as np +from gym import utils +from gym.envs.mujoco import mujoco_env + + +class HalfCheetahEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__(self): + mujoco_env.MujocoEnv.__init__(self, "half_cheetah.xml", 5) + utils.EzPickle.__init__(self) + + def step(self, action): + xposbefore = self.sim.data.qpos[0] + self.do_simulation(action, self.frame_skip) + xposafter = self.sim.data.qpos[0] + ob = self._get_obs() + reward_ctrl = -0.1 * np.square(action).sum() + reward_run = (xposafter - xposbefore) / self.dt + reward = reward_ctrl + reward_run + done = False + return ob, reward, done, dict(reward_run=reward_run, reward_ctrl=reward_ctrl) + + def _get_obs(self): + return np.concatenate( + [ + self.sim.data.qpos.flat[1:], + self.sim.data.qvel.flat, + ] + ) + + def reset_model(self): + qpos = self.init_qpos + self.np_random.uniform( + low=-0.1, high=0.1, size=self.model.nq + ) + qvel = self.init_qvel + self.np_random.randn(self.model.nv) * 0.1 + self.set_state(qpos, qvel) + return self._get_obs() + + def viewer_setup(self): + self.viewer.cam.distance = self.model.stat.extent * 0.5 diff --git a/gym/envs/mujoco/half_cheetah_v3.py b/gym/envs/mujoco/half_cheetah_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..84f69b2bdcdb0aec3ae67f4af972943b8806021d --- /dev/null +++ b/gym/envs/mujoco/half_cheetah_v3.py @@ -0,0 +1,91 @@ +import numpy as np +from gym import utils +from gym.envs.mujoco import mujoco_env + + +DEFAULT_CAMERA_CONFIG = { + "distance": 4.0, +} + + +class HalfCheetahEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__( + self, + xml_file="half_cheetah.xml", + forward_reward_weight=1.0, + ctrl_cost_weight=0.1, + reset_noise_scale=0.1, + exclude_current_positions_from_observation=True, + ): + utils.EzPickle.__init__(**locals()) + + self._forward_reward_weight = forward_reward_weight + + self._ctrl_cost_weight = ctrl_cost_weight + + self._reset_noise_scale = reset_noise_scale + + self._exclude_current_positions_from_observation = ( + exclude_current_positions_from_observation + ) + + mujoco_env.MujocoEnv.__init__(self, xml_file, 5) + + def control_cost(self, action): + control_cost = self._ctrl_cost_weight * np.sum(np.square(action)) + return control_cost + + def step(self, action): + x_position_before = self.sim.data.qpos[0] + self.do_simulation(action, self.frame_skip) + x_position_after = self.sim.data.qpos[0] + x_velocity = (x_position_after - x_position_before) / self.dt + + ctrl_cost = self.control_cost(action) + + forward_reward = self._forward_reward_weight * x_velocity + + observation = self._get_obs() + reward = forward_reward - ctrl_cost + done = False + info = { + "x_position": x_position_after, + "x_velocity": x_velocity, + "reward_run": forward_reward, + "reward_ctrl": -ctrl_cost, + } + + return observation, reward, done, info + + def _get_obs(self): + position = self.sim.data.qpos.flat.copy() + velocity = self.sim.data.qvel.flat.copy() + + if self._exclude_current_positions_from_observation: + position = position[1:] + + observation = np.concatenate((position, velocity)).ravel() + return observation + + def reset_model(self): + noise_low = -self._reset_noise_scale + noise_high = self._reset_noise_scale + + qpos = self.init_qpos + self.np_random.uniform( + low=noise_low, high=noise_high, size=self.model.nq + ) + qvel = self.init_qvel + self._reset_noise_scale * self.np_random.randn( + self.model.nv + ) + + self.set_state(qpos, qvel) + + observation = self._get_obs() + return observation + + def viewer_setup(self): + for key, value in DEFAULT_CAMERA_CONFIG.items(): + if isinstance(value, np.ndarray): + getattr(self.viewer.cam, key)[:] = value + else: + setattr(self.viewer.cam, key, value) diff --git a/gym/envs/mujoco/hopper.py b/gym/envs/mujoco/hopper.py new file mode 100644 index 0000000000000000000000000000000000000000..46bf0a7f5d9968b84ab31d94f2688ce4ede1f101 --- /dev/null +++ b/gym/envs/mujoco/hopper.py @@ -0,0 +1,48 @@ +import numpy as np +from gym import utils +from gym.envs.mujoco import mujoco_env + + +class HopperEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__(self): + mujoco_env.MujocoEnv.__init__(self, "hopper.xml", 4) + utils.EzPickle.__init__(self) + + def step(self, a): + posbefore = self.sim.data.qpos[0] + self.do_simulation(a, self.frame_skip) + posafter, height, ang = self.sim.data.qpos[0:3] + alive_bonus = 1.0 + reward = (posafter - posbefore) / self.dt + reward += alive_bonus + reward -= 1e-3 * np.square(a).sum() + s = self.state_vector() + done = not ( + np.isfinite(s).all() + and (np.abs(s[2:]) < 100).all() + and (height > 0.7) + and (abs(ang) < 0.2) + ) + ob = self._get_obs() + return ob, reward, done, {} + + def _get_obs(self): + return np.concatenate( + [self.sim.data.qpos.flat[1:], np.clip(self.sim.data.qvel.flat, -10, 10)] + ) + + def reset_model(self): + qpos = self.init_qpos + self.np_random.uniform( + low=-0.005, high=0.005, size=self.model.nq + ) + qvel = self.init_qvel + self.np_random.uniform( + low=-0.005, high=0.005, size=self.model.nv + ) + self.set_state(qpos, qvel) + return self._get_obs() + + def viewer_setup(self): + self.viewer.cam.trackbodyid = 2 + self.viewer.cam.distance = self.model.stat.extent * 0.75 + self.viewer.cam.lookat[2] = 1.15 + self.viewer.cam.elevation = -20 diff --git a/gym/envs/mujoco/hopper_v3.py b/gym/envs/mujoco/hopper_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..8bb80024124daea23dbb5efbb0d80e5ea0f38418 --- /dev/null +++ b/gym/envs/mujoco/hopper_v3.py @@ -0,0 +1,137 @@ +import numpy as np +from gym.envs.mujoco import mujoco_env +from gym import utils + + +DEFAULT_CAMERA_CONFIG = { + "trackbodyid": 2, + "distance": 3.0, + "lookat": np.array((0.0, 0.0, 1.15)), + "elevation": -20.0, +} + + +class HopperEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__( + self, + xml_file="hopper.xml", + forward_reward_weight=1.0, + ctrl_cost_weight=1e-3, + healthy_reward=1.0, + terminate_when_unhealthy=True, + healthy_state_range=(-100.0, 100.0), + healthy_z_range=(0.7, float("inf")), + healthy_angle_range=(-0.2, 0.2), + reset_noise_scale=5e-3, + exclude_current_positions_from_observation=True, + ): + utils.EzPickle.__init__(**locals()) + + self._forward_reward_weight = forward_reward_weight + + self._ctrl_cost_weight = ctrl_cost_weight + + self._healthy_reward = healthy_reward + self._terminate_when_unhealthy = terminate_when_unhealthy + + self._healthy_state_range = healthy_state_range + self._healthy_z_range = healthy_z_range + self._healthy_angle_range = healthy_angle_range + + self._reset_noise_scale = reset_noise_scale + + self._exclude_current_positions_from_observation = ( + exclude_current_positions_from_observation + ) + + mujoco_env.MujocoEnv.__init__(self, xml_file, 4) + + @property + def healthy_reward(self): + return ( + float(self.is_healthy or self._terminate_when_unhealthy) + * self._healthy_reward + ) + + def control_cost(self, action): + control_cost = self._ctrl_cost_weight * np.sum(np.square(action)) + return control_cost + + @property + def is_healthy(self): + z, angle = self.sim.data.qpos[1:3] + state = self.state_vector()[2:] + + min_state, max_state = self._healthy_state_range + min_z, max_z = self._healthy_z_range + min_angle, max_angle = self._healthy_angle_range + + healthy_state = np.all(np.logical_and(min_state < state, state < max_state)) + healthy_z = min_z < z < max_z + healthy_angle = min_angle < angle < max_angle + + is_healthy = all((healthy_state, healthy_z, healthy_angle)) + + return is_healthy + + @property + def done(self): + done = not self.is_healthy if self._terminate_when_unhealthy else False + return done + + def _get_obs(self): + position = self.sim.data.qpos.flat.copy() + velocity = np.clip(self.sim.data.qvel.flat.copy(), -10, 10) + + if self._exclude_current_positions_from_observation: + position = position[1:] + + observation = np.concatenate((position, velocity)).ravel() + return observation + + def step(self, action): + x_position_before = self.sim.data.qpos[0] + self.do_simulation(action, self.frame_skip) + x_position_after = self.sim.data.qpos[0] + x_velocity = (x_position_after - x_position_before) / self.dt + + ctrl_cost = self.control_cost(action) + + forward_reward = self._forward_reward_weight * x_velocity + healthy_reward = self.healthy_reward + + rewards = forward_reward + healthy_reward + costs = ctrl_cost + + observation = self._get_obs() + reward = rewards - costs + done = self.done + info = { + "x_position": x_position_after, + "x_velocity": x_velocity, + } + + return observation, reward, done, info + + def reset_model(self): + noise_low = -self._reset_noise_scale + noise_high = self._reset_noise_scale + + qpos = self.init_qpos + self.np_random.uniform( + low=noise_low, high=noise_high, size=self.model.nq + ) + qvel = self.init_qvel + self.np_random.uniform( + low=noise_low, high=noise_high, size=self.model.nv + ) + + self.set_state(qpos, qvel) + + observation = self._get_obs() + return observation + + def viewer_setup(self): + for key, value in DEFAULT_CAMERA_CONFIG.items(): + if isinstance(value, np.ndarray): + getattr(self.viewer.cam, key)[:] = value + else: + setattr(self.viewer.cam, key, value) diff --git a/gym/envs/mujoco/humanoid.py b/gym/envs/mujoco/humanoid.py new file mode 100644 index 0000000000000000000000000000000000000000..ae8f1eaee21945f7e2e5ac2515d1dee0cd74c089 --- /dev/null +++ b/gym/envs/mujoco/humanoid.py @@ -0,0 +1,72 @@ +import numpy as np +from gym.envs.mujoco import mujoco_env +from gym import utils + + +def mass_center(model, sim): + mass = np.expand_dims(model.body_mass, 1) + xpos = sim.data.xipos + return (np.sum(mass * xpos, 0) / np.sum(mass))[0] + + +class HumanoidEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__(self): + mujoco_env.MujocoEnv.__init__(self, "humanoid.xml", 5) + utils.EzPickle.__init__(self) + + def _get_obs(self): + data = self.sim.data + return np.concatenate( + [ + data.qpos.flat[2:], + data.qvel.flat, + data.cinert.flat, + data.cvel.flat, + data.qfrc_actuator.flat, + data.cfrc_ext.flat, + ] + ) + + def step(self, a): + pos_before = mass_center(self.model, self.sim) + self.do_simulation(a, self.frame_skip) + pos_after = mass_center(self.model, self.sim) + alive_bonus = 5.0 + data = self.sim.data + lin_vel_cost = 1.25 * (pos_after - pos_before) / self.dt + quad_ctrl_cost = 0.1 * np.square(data.ctrl).sum() + quad_impact_cost = 0.5e-6 * np.square(data.cfrc_ext).sum() + quad_impact_cost = min(quad_impact_cost, 10) + reward = lin_vel_cost - quad_ctrl_cost - quad_impact_cost + alive_bonus + qpos = self.sim.data.qpos + done = bool((qpos[2] < 1.0) or (qpos[2] > 2.0)) + return ( + self._get_obs(), + reward, + done, + dict( + reward_linvel=lin_vel_cost, + reward_quadctrl=-quad_ctrl_cost, + reward_alive=alive_bonus, + reward_impact=-quad_impact_cost, + ), + ) + + def reset_model(self): + c = 0.01 + self.set_state( + self.init_qpos + self.np_random.uniform(low=-c, high=c, size=self.model.nq), + self.init_qvel + + self.np_random.uniform( + low=-c, + high=c, + size=self.model.nv, + ), + ) + return self._get_obs() + + def viewer_setup(self): + self.viewer.cam.trackbodyid = 1 + self.viewer.cam.distance = self.model.stat.extent * 1.0 + self.viewer.cam.lookat[2] = 2.0 + self.viewer.cam.elevation = -20 diff --git a/gym/envs/mujoco/humanoid_v3.py b/gym/envs/mujoco/humanoid_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..94a809d3ee9bd6d5270bec1186d7811ca59183e5 --- /dev/null +++ b/gym/envs/mujoco/humanoid_v3.py @@ -0,0 +1,162 @@ +import numpy as np +from gym.envs.mujoco import mujoco_env +from gym import utils + + +DEFAULT_CAMERA_CONFIG = { + "trackbodyid": 1, + "distance": 4.0, + "lookat": np.array((0.0, 0.0, 2.0)), + "elevation": -20.0, +} + + +def mass_center(model, sim): + mass = np.expand_dims(model.body_mass, axis=1) + xpos = sim.data.xipos + return (np.sum(mass * xpos, axis=0) / np.sum(mass))[0:2].copy() + + +class HumanoidEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__( + self, + xml_file="humanoid.xml", + forward_reward_weight=1.25, + ctrl_cost_weight=0.1, + contact_cost_weight=5e-7, + contact_cost_range=(-np.inf, 10.0), + healthy_reward=5.0, + terminate_when_unhealthy=True, + healthy_z_range=(1.0, 2.0), + reset_noise_scale=1e-2, + exclude_current_positions_from_observation=True, + ): + utils.EzPickle.__init__(**locals()) + + self._forward_reward_weight = forward_reward_weight + self._ctrl_cost_weight = ctrl_cost_weight + self._contact_cost_weight = contact_cost_weight + self._contact_cost_range = contact_cost_range + self._healthy_reward = healthy_reward + self._terminate_when_unhealthy = terminate_when_unhealthy + self._healthy_z_range = healthy_z_range + + self._reset_noise_scale = reset_noise_scale + + self._exclude_current_positions_from_observation = ( + exclude_current_positions_from_observation + ) + + mujoco_env.MujocoEnv.__init__(self, xml_file, 5) + + @property + def healthy_reward(self): + return ( + float(self.is_healthy or self._terminate_when_unhealthy) + * self._healthy_reward + ) + + def control_cost(self, action): + control_cost = self._ctrl_cost_weight * np.sum(np.square(self.sim.data.ctrl)) + return control_cost + + @property + def contact_cost(self): + contact_forces = self.sim.data.cfrc_ext + contact_cost = self._contact_cost_weight * np.sum(np.square(contact_forces)) + min_cost, max_cost = self._contact_cost_range + contact_cost = np.clip(contact_cost, min_cost, max_cost) + return contact_cost + + @property + def is_healthy(self): + min_z, max_z = self._healthy_z_range + is_healthy = min_z < self.sim.data.qpos[2] < max_z + + return is_healthy + + @property + def done(self): + done = (not self.is_healthy) if self._terminate_when_unhealthy else False + return done + + def _get_obs(self): + position = self.sim.data.qpos.flat.copy() + velocity = self.sim.data.qvel.flat.copy() + + com_inertia = self.sim.data.cinert.flat.copy() + com_velocity = self.sim.data.cvel.flat.copy() + + actuator_forces = self.sim.data.qfrc_actuator.flat.copy() + external_contact_forces = self.sim.data.cfrc_ext.flat.copy() + + if self._exclude_current_positions_from_observation: + position = position[2:] + + return np.concatenate( + ( + position, + velocity, + com_inertia, + com_velocity, + actuator_forces, + external_contact_forces, + ) + ) + + def step(self, action): + xy_position_before = mass_center(self.model, self.sim) + self.do_simulation(action, self.frame_skip) + xy_position_after = mass_center(self.model, self.sim) + + xy_velocity = (xy_position_after - xy_position_before) / self.dt + x_velocity, y_velocity = xy_velocity + + ctrl_cost = self.control_cost(action) + contact_cost = self.contact_cost + + forward_reward = self._forward_reward_weight * x_velocity + healthy_reward = self.healthy_reward + + rewards = forward_reward + healthy_reward + costs = ctrl_cost + contact_cost + + observation = self._get_obs() + reward = rewards - costs + done = self.done + info = { + "reward_linvel": forward_reward, + "reward_quadctrl": -ctrl_cost, + "reward_alive": healthy_reward, + "reward_impact": -contact_cost, + "x_position": xy_position_after[0], + "y_position": xy_position_after[1], + "distance_from_origin": np.linalg.norm(xy_position_after, ord=2), + "x_velocity": x_velocity, + "y_velocity": y_velocity, + "forward_reward": forward_reward, + } + + return observation, reward, done, info + + def reset_model(self): + noise_low = -self._reset_noise_scale + noise_high = self._reset_noise_scale + + qpos = self.init_qpos + self.np_random.uniform( + low=noise_low, high=noise_high, size=self.model.nq + ) + qvel = self.init_qvel + self.np_random.uniform( + low=noise_low, high=noise_high, size=self.model.nv + ) + self.set_state(qpos, qvel) + + observation = self._get_obs() + return observation + + def viewer_setup(self): + for key, value in DEFAULT_CAMERA_CONFIG.items(): + if isinstance(value, np.ndarray): + getattr(self.viewer.cam, key)[:] = value + else: + setattr(self.viewer.cam, key, value) diff --git a/gym/envs/mujoco/humanoidstandup.py b/gym/envs/mujoco/humanoidstandup.py new file mode 100644 index 0000000000000000000000000000000000000000..7117ab79124d78691ae3d96b83878e148d52468a --- /dev/null +++ b/gym/envs/mujoco/humanoidstandup.py @@ -0,0 +1,64 @@ +from gym.envs.mujoco import mujoco_env +from gym import utils +import numpy as np + + +class HumanoidStandupEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__(self): + mujoco_env.MujocoEnv.__init__(self, "humanoidstandup.xml", 5) + utils.EzPickle.__init__(self) + + def _get_obs(self): + data = self.sim.data + return np.concatenate( + [ + data.qpos.flat[2:], + data.qvel.flat, + data.cinert.flat, + data.cvel.flat, + data.qfrc_actuator.flat, + data.cfrc_ext.flat, + ] + ) + + def step(self, a): + self.do_simulation(a, self.frame_skip) + pos_after = self.sim.data.qpos[2] + data = self.sim.data + uph_cost = (pos_after - 0) / self.model.opt.timestep + + quad_ctrl_cost = 0.1 * np.square(data.ctrl).sum() + quad_impact_cost = 0.5e-6 * np.square(data.cfrc_ext).sum() + quad_impact_cost = min(quad_impact_cost, 10) + reward = uph_cost - quad_ctrl_cost - quad_impact_cost + 1 + + done = bool(False) + return ( + self._get_obs(), + reward, + done, + dict( + reward_linup=uph_cost, + reward_quadctrl=-quad_ctrl_cost, + reward_impact=-quad_impact_cost, + ), + ) + + def reset_model(self): + c = 0.01 + self.set_state( + self.init_qpos + self.np_random.uniform(low=-c, high=c, size=self.model.nq), + self.init_qvel + + self.np_random.uniform( + low=-c, + high=c, + size=self.model.nv, + ), + ) + return self._get_obs() + + def viewer_setup(self): + self.viewer.cam.trackbodyid = 1 + self.viewer.cam.distance = self.model.stat.extent * 1.0 + self.viewer.cam.lookat[2] = 0.8925 + self.viewer.cam.elevation = -20 diff --git a/gym/envs/mujoco/inverted_double_pendulum.py b/gym/envs/mujoco/inverted_double_pendulum.py new file mode 100644 index 0000000000000000000000000000000000000000..81dd3c5610b2fb04bce840bf9f65ebec7d6f9b50 --- /dev/null +++ b/gym/envs/mujoco/inverted_double_pendulum.py @@ -0,0 +1,46 @@ +import numpy as np +from gym import utils +from gym.envs.mujoco import mujoco_env + + +class InvertedDoublePendulumEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__(self): + mujoco_env.MujocoEnv.__init__(self, "inverted_double_pendulum.xml", 5) + utils.EzPickle.__init__(self) + + def step(self, action): + self.do_simulation(action, self.frame_skip) + ob = self._get_obs() + x, _, y = self.sim.data.site_xpos[0] + dist_penalty = 0.01 * x ** 2 + (y - 2) ** 2 + v1, v2 = self.sim.data.qvel[1:3] + vel_penalty = 1e-3 * v1 ** 2 + 5e-3 * v2 ** 2 + alive_bonus = 10 + r = alive_bonus - dist_penalty - vel_penalty + done = bool(y <= 1) + return ob, r, done, {} + + def _get_obs(self): + return np.concatenate( + [ + self.sim.data.qpos[:1], # cart x pos + np.sin(self.sim.data.qpos[1:]), # link angles + np.cos(self.sim.data.qpos[1:]), + np.clip(self.sim.data.qvel, -10, 10), + np.clip(self.sim.data.qfrc_constraint, -10, 10), + ] + ).ravel() + + def reset_model(self): + self.set_state( + self.init_qpos + + self.np_random.uniform(low=-0.1, high=0.1, size=self.model.nq), + self.init_qvel + self.np_random.randn(self.model.nv) * 0.1, + ) + return self._get_obs() + + def viewer_setup(self): + v = self.viewer + v.cam.trackbodyid = 0 + v.cam.distance = self.model.stat.extent * 0.5 + v.cam.lookat[2] = 0.12250000000000005 # v.model.stat.center[2] diff --git a/gym/envs/mujoco/inverted_pendulum.py b/gym/envs/mujoco/inverted_pendulum.py new file mode 100644 index 0000000000000000000000000000000000000000..b87ec498bcd18036491cbbf696f84f3040666079 --- /dev/null +++ b/gym/envs/mujoco/inverted_pendulum.py @@ -0,0 +1,35 @@ +import numpy as np +from gym import utils +from gym.envs.mujoco import mujoco_env + + +class InvertedPendulumEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__(self): + utils.EzPickle.__init__(self) + mujoco_env.MujocoEnv.__init__(self, "inverted_pendulum.xml", 2) + + def step(self, a): + reward = 1.0 + self.do_simulation(a, self.frame_skip) + ob = self._get_obs() + notdone = np.isfinite(ob).all() and (np.abs(ob[1]) <= 0.2) + done = not notdone + return ob, reward, done, {} + + def reset_model(self): + qpos = self.init_qpos + self.np_random.uniform( + size=self.model.nq, low=-0.01, high=0.01 + ) + qvel = self.init_qvel + self.np_random.uniform( + size=self.model.nv, low=-0.01, high=0.01 + ) + self.set_state(qpos, qvel) + return self._get_obs() + + def _get_obs(self): + return np.concatenate([self.sim.data.qpos, self.sim.data.qvel]).ravel() + + def viewer_setup(self): + v = self.viewer + v.cam.trackbodyid = 0 + v.cam.distance = self.model.stat.extent diff --git a/gym/envs/mujoco/mujoco_env.py b/gym/envs/mujoco/mujoco_env.py new file mode 100644 index 0000000000000000000000000000000000000000..4d0fe8865c82565e84c867f29048968cca65e0ab --- /dev/null +++ b/gym/envs/mujoco/mujoco_env.py @@ -0,0 +1,196 @@ +from collections import OrderedDict +import os + + +from gym import error, spaces +from gym.utils import seeding +import numpy as np +from os import path +import gym + +try: + import mujoco_py +except ImportError as e: + raise error.DependencyNotInstalled( + "{}. (HINT: you need to install mujoco_py, and also perform the setup instructions here: https://github.com/openai/mujoco-py/.)".format( + e + ) + ) + +DEFAULT_SIZE = 500 + + +def convert_observation_to_space(observation): + if isinstance(observation, dict): + space = spaces.Dict( + OrderedDict( + [ + (key, convert_observation_to_space(value)) + for key, value in observation.items() + ] + ) + ) + elif isinstance(observation, np.ndarray): + low = np.full(observation.shape, -float("inf"), dtype=np.float32) + high = np.full(observation.shape, float("inf"), dtype=np.float32) + space = spaces.Box(low, high, dtype=observation.dtype) + else: + raise NotImplementedError(type(observation), observation) + + return space + + +class MujocoEnv(gym.Env): + """Superclass for all MuJoCo environments.""" + + def __init__(self, model_path, frame_skip): + if model_path.startswith("/"): + fullpath = model_path + else: + fullpath = os.path.join(os.path.dirname(__file__), "assets", model_path) + if not path.exists(fullpath): + raise IOError("File %s does not exist" % fullpath) + self.frame_skip = frame_skip + self.model = mujoco_py.load_model_from_path(fullpath) + self.sim = mujoco_py.MjSim(self.model) + self.data = self.sim.data + self.viewer = None + self._viewers = {} + + self.metadata = { + "render.modes": ["human", "rgb_array", "depth_array"], + "video.frames_per_second": int(np.round(1.0 / self.dt)), + } + + self.init_qpos = self.sim.data.qpos.ravel().copy() + self.init_qvel = self.sim.data.qvel.ravel().copy() + + self._set_action_space() + + action = self.action_space.sample() + observation, _reward, done, _info = self.step(action) + assert not done + + self._set_observation_space(observation) + + self.seed() + + def _set_action_space(self): + bounds = self.model.actuator_ctrlrange.copy().astype(np.float32) + low, high = bounds.T + self.action_space = spaces.Box(low=low, high=high, dtype=np.float32) + return self.action_space + + def _set_observation_space(self, observation): + self.observation_space = convert_observation_to_space(observation) + return self.observation_space + + def seed(self, seed=None): + self.np_random, seed = seeding.np_random(seed) + return [seed] + + # methods to override: + # ---------------------------- + + def reset_model(self): + """ + Reset the robot degrees of freedom (qpos and qvel). + Implement this in each subclass. + """ + raise NotImplementedError + + def viewer_setup(self): + """ + This method is called when the viewer is initialized. + Optionally implement this method, if you need to tinker with camera position + and so forth. + """ + pass + + # ----------------------------- + + def reset(self): + self.sim.reset() + ob = self.reset_model() + return ob + + def set_state(self, qpos, qvel): + assert qpos.shape == (self.model.nq,) and qvel.shape == (self.model.nv,) + old_state = self.sim.get_state() + new_state = mujoco_py.MjSimState( + old_state.time, qpos, qvel, old_state.act, old_state.udd_state + ) + self.sim.set_state(new_state) + self.sim.forward() + + @property + def dt(self): + return self.model.opt.timestep * self.frame_skip + + def do_simulation(self, ctrl, n_frames): + self.sim.data.ctrl[:] = ctrl + for _ in range(n_frames): + self.sim.step() + + def render( + self, + mode="human", + width=DEFAULT_SIZE, + height=DEFAULT_SIZE, + camera_id=None, + camera_name=None, + ): + if mode == "rgb_array" or mode == "depth_array": + if camera_id is not None and camera_name is not None: + raise ValueError( + "Both `camera_id` and `camera_name` cannot be" + " specified at the same time." + ) + + no_camera_specified = camera_name is None and camera_id is None + if no_camera_specified: + camera_name = "track" + + if camera_id is None and camera_name in self.model._camera_name2id: + camera_id = self.model.camera_name2id(camera_name) + + self._get_viewer(mode).render(width, height, camera_id=camera_id) + + if mode == "rgb_array": + # window size used for old mujoco-py: + data = self._get_viewer(mode).read_pixels(width, height, depth=False) + # original image is upside-down, so flip it + return data[::-1, :, :] + elif mode == "depth_array": + self._get_viewer(mode).render(width, height) + # window size used for old mujoco-py: + # Extract depth part of the read_pixels() tuple + data = self._get_viewer(mode).read_pixels(width, height, depth=True)[1] + # original image is upside-down, so flip it + return data[::-1, :] + elif mode == "human": + self._get_viewer(mode).render() + + def close(self): + if self.viewer is not None: + # self.viewer.finish() + self.viewer = None + self._viewers = {} + + def _get_viewer(self, mode): + self.viewer = self._viewers.get(mode) + if self.viewer is None: + if mode == "human": + self.viewer = mujoco_py.MjViewer(self.sim) + elif mode == "rgb_array" or mode == "depth_array": + self.viewer = mujoco_py.MjRenderContextOffscreen(self.sim, -1) + + self.viewer_setup() + self._viewers[mode] = self.viewer + return self.viewer + + def get_body_com(self, body_name): + return self.data.get_body_xpos(body_name) + + def state_vector(self): + return np.concatenate([self.sim.data.qpos.flat, self.sim.data.qvel.flat]) diff --git a/gym/envs/mujoco/pusher.py b/gym/envs/mujoco/pusher.py new file mode 100644 index 0000000000000000000000000000000000000000..e82adc6634bcad40e02ca9e0ce70ecd2b71041d2 --- /dev/null +++ b/gym/envs/mujoco/pusher.py @@ -0,0 +1,63 @@ +import numpy as np +from gym import utils +from gym.envs.mujoco import mujoco_env + +import mujoco_py + + +class PusherEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__(self): + utils.EzPickle.__init__(self) + mujoco_env.MujocoEnv.__init__(self, "pusher.xml", 5) + + def step(self, a): + vec_1 = self.get_body_com("object") - self.get_body_com("tips_arm") + vec_2 = self.get_body_com("object") - self.get_body_com("goal") + + reward_near = -np.linalg.norm(vec_1) + reward_dist = -np.linalg.norm(vec_2) + reward_ctrl = -np.square(a).sum() + reward = reward_dist + 0.1 * reward_ctrl + 0.5 * reward_near + + self.do_simulation(a, self.frame_skip) + ob = self._get_obs() + done = False + return ob, reward, done, dict(reward_dist=reward_dist, reward_ctrl=reward_ctrl) + + def viewer_setup(self): + self.viewer.cam.trackbodyid = -1 + self.viewer.cam.distance = 4.0 + + def reset_model(self): + qpos = self.init_qpos + + self.goal_pos = np.asarray([0, 0]) + while True: + self.cylinder_pos = np.concatenate( + [ + self.np_random.uniform(low=-0.3, high=0, size=1), + self.np_random.uniform(low=-0.2, high=0.2, size=1), + ] + ) + if np.linalg.norm(self.cylinder_pos - self.goal_pos) > 0.17: + break + + qpos[-4:-2] = self.cylinder_pos + qpos[-2:] = self.goal_pos + qvel = self.init_qvel + self.np_random.uniform( + low=-0.005, high=0.005, size=self.model.nv + ) + qvel[-4:] = 0 + self.set_state(qpos, qvel) + return self._get_obs() + + def _get_obs(self): + return np.concatenate( + [ + self.sim.data.qpos.flat[:7], + self.sim.data.qvel.flat[:7], + self.get_body_com("tips_arm"), + self.get_body_com("object"), + self.get_body_com("goal"), + ] + ) diff --git a/gym/envs/mujoco/reacher.py b/gym/envs/mujoco/reacher.py new file mode 100644 index 0000000000000000000000000000000000000000..3cc1f30e0d35b0bc07ee1acb3d67ebea29dc8d4f --- /dev/null +++ b/gym/envs/mujoco/reacher.py @@ -0,0 +1,51 @@ +import numpy as np +from gym import utils +from gym.envs.mujoco import mujoco_env + + +class ReacherEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__(self): + utils.EzPickle.__init__(self) + mujoco_env.MujocoEnv.__init__(self, "reacher.xml", 2) + + def step(self, a): + vec = self.get_body_com("fingertip") - self.get_body_com("target") + reward_dist = -np.linalg.norm(vec) + reward_ctrl = -np.square(a).sum() + reward = reward_dist + reward_ctrl + self.do_simulation(a, self.frame_skip) + ob = self._get_obs() + done = False + return ob, reward, done, dict(reward_dist=reward_dist, reward_ctrl=reward_ctrl) + + def viewer_setup(self): + self.viewer.cam.trackbodyid = 0 + + def reset_model(self): + qpos = ( + self.np_random.uniform(low=-0.1, high=0.1, size=self.model.nq) + + self.init_qpos + ) + while True: + self.goal = self.np_random.uniform(low=-0.2, high=0.2, size=2) + if np.linalg.norm(self.goal) < 0.2: + break + qpos[-2:] = self.goal + qvel = self.init_qvel + self.np_random.uniform( + low=-0.005, high=0.005, size=self.model.nv + ) + qvel[-2:] = 0 + self.set_state(qpos, qvel) + return self._get_obs() + + def _get_obs(self): + theta = self.sim.data.qpos.flat[:2] + return np.concatenate( + [ + np.cos(theta), + np.sin(theta), + self.sim.data.qpos.flat[2:], + self.sim.data.qvel.flat[:2], + self.get_body_com("fingertip") - self.get_body_com("target"), + ] + ) diff --git a/gym/envs/mujoco/striker.py b/gym/envs/mujoco/striker.py new file mode 100644 index 0000000000000000000000000000000000000000..186f9d7fe6b37b976a0ef0e13259478acb0c9445 --- /dev/null +++ b/gym/envs/mujoco/striker.py @@ -0,0 +1,81 @@ +import numpy as np +from gym import utils +from gym.envs.mujoco import mujoco_env + + +class StrikerEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__(self): + utils.EzPickle.__init__(self) + self._striked = False + self._min_strike_dist = np.inf + self.strike_threshold = 0.1 + mujoco_env.MujocoEnv.__init__(self, "striker.xml", 5) + + def step(self, a): + vec_1 = self.get_body_com("object") - self.get_body_com("tips_arm") + vec_2 = self.get_body_com("object") - self.get_body_com("goal") + self._min_strike_dist = min(self._min_strike_dist, np.linalg.norm(vec_2)) + + if np.linalg.norm(vec_1) < self.strike_threshold: + self._striked = True + self._strike_pos = self.get_body_com("tips_arm") + + if self._striked: + vec_3 = self.get_body_com("object") - self._strike_pos + reward_near = -np.linalg.norm(vec_3) + else: + reward_near = -np.linalg.norm(vec_1) + + reward_dist = -np.linalg.norm(self._min_strike_dist) + reward_ctrl = -np.square(a).sum() + reward = 3 * reward_dist + 0.1 * reward_ctrl + 0.5 * reward_near + + self.do_simulation(a, self.frame_skip) + ob = self._get_obs() + done = False + return ob, reward, done, dict(reward_dist=reward_dist, reward_ctrl=reward_ctrl) + + def viewer_setup(self): + self.viewer.cam.trackbodyid = 0 + self.viewer.cam.distance = 4.0 + + def reset_model(self): + self._min_strike_dist = np.inf + self._striked = False + self._strike_pos = None + + qpos = self.init_qpos + + self.ball = np.array([0.5, -0.175]) + while True: + self.goal = np.concatenate( + [ + self.np_random.uniform(low=0.15, high=0.7, size=1), + self.np_random.uniform(low=0.1, high=1.0, size=1), + ] + ) + if np.linalg.norm(self.ball - self.goal) > 0.17: + break + + qpos[-9:-7] = [self.ball[1], self.ball[0]] + qpos[-7:-5] = self.goal + diff = self.ball - self.goal + angle = -np.arctan(diff[0] / (diff[1] + 1e-8)) + qpos[-1] = angle / 3.14 + qvel = self.init_qvel + self.np_random.uniform( + low=-0.1, high=0.1, size=self.model.nv + ) + qvel[7:] = 0 + self.set_state(qpos, qvel) + return self._get_obs() + + def _get_obs(self): + return np.concatenate( + [ + self.sim.data.qpos.flat[:7], + self.sim.data.qvel.flat[:7], + self.get_body_com("tips_arm"), + self.get_body_com("object"), + self.get_body_com("goal"), + ] + ) diff --git a/gym/envs/mujoco/swimmer.py b/gym/envs/mujoco/swimmer.py new file mode 100644 index 0000000000000000000000000000000000000000..f903184daa2902f0cd3b290341f1b9974972c3e5 --- /dev/null +++ b/gym/envs/mujoco/swimmer.py @@ -0,0 +1,34 @@ +import numpy as np +from gym import utils +from gym.envs.mujoco import mujoco_env + + +class SwimmerEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__(self): + mujoco_env.MujocoEnv.__init__(self, "swimmer.xml", 4) + utils.EzPickle.__init__(self) + + def step(self, a): + ctrl_cost_coeff = 0.0001 + xposbefore = self.sim.data.qpos[0] + self.do_simulation(a, self.frame_skip) + xposafter = self.sim.data.qpos[0] + reward_fwd = (xposafter - xposbefore) / self.dt + reward_ctrl = -ctrl_cost_coeff * np.square(a).sum() + reward = reward_fwd + reward_ctrl + ob = self._get_obs() + return ob, reward, False, dict(reward_fwd=reward_fwd, reward_ctrl=reward_ctrl) + + def _get_obs(self): + qpos = self.sim.data.qpos + qvel = self.sim.data.qvel + return np.concatenate([qpos.flat[2:], qvel.flat]) + + def reset_model(self): + self.set_state( + self.init_qpos + + self.np_random.uniform(low=-0.1, high=0.1, size=self.model.nq), + self.init_qvel + + self.np_random.uniform(low=-0.1, high=0.1, size=self.model.nv), + ) + return self._get_obs() diff --git a/gym/envs/mujoco/swimmer_v3.py b/gym/envs/mujoco/swimmer_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..8cf794d4791b28d72891a597a06f5fa0f4786c9a --- /dev/null +++ b/gym/envs/mujoco/swimmer_v3.py @@ -0,0 +1,94 @@ +import numpy as np +from gym.envs.mujoco import mujoco_env +from gym import utils + + +DEFAULT_CAMERA_CONFIG = {} + + +class SwimmerEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__( + self, + xml_file="swimmer.xml", + forward_reward_weight=1.0, + ctrl_cost_weight=1e-4, + reset_noise_scale=0.1, + exclude_current_positions_from_observation=True, + ): + utils.EzPickle.__init__(**locals()) + + self._forward_reward_weight = forward_reward_weight + self._ctrl_cost_weight = ctrl_cost_weight + + self._reset_noise_scale = reset_noise_scale + + self._exclude_current_positions_from_observation = ( + exclude_current_positions_from_observation + ) + + mujoco_env.MujocoEnv.__init__(self, xml_file, 4) + + def control_cost(self, action): + control_cost = self._ctrl_cost_weight * np.sum(np.square(action)) + return control_cost + + def step(self, action): + xy_position_before = self.sim.data.qpos[0:2].copy() + self.do_simulation(action, self.frame_skip) + xy_position_after = self.sim.data.qpos[0:2].copy() + + xy_velocity = (xy_position_after - xy_position_before) / self.dt + x_velocity, y_velocity = xy_velocity + + forward_reward = self._forward_reward_weight * x_velocity + + ctrl_cost = self.control_cost(action) + + observation = self._get_obs() + reward = forward_reward - ctrl_cost + done = False + info = { + "reward_fwd": forward_reward, + "reward_ctrl": -ctrl_cost, + "x_position": xy_position_after[0], + "y_position": xy_position_after[1], + "distance_from_origin": np.linalg.norm(xy_position_after, ord=2), + "x_velocity": x_velocity, + "y_velocity": y_velocity, + "forward_reward": forward_reward, + } + + return observation, reward, done, info + + def _get_obs(self): + position = self.sim.data.qpos.flat.copy() + velocity = self.sim.data.qvel.flat.copy() + + if self._exclude_current_positions_from_observation: + position = position[2:] + + observation = np.concatenate([position, velocity]).ravel() + return observation + + def reset_model(self): + noise_low = -self._reset_noise_scale + noise_high = self._reset_noise_scale + + qpos = self.init_qpos + self.np_random.uniform( + low=noise_low, high=noise_high, size=self.model.nq + ) + qvel = self.init_qvel + self.np_random.uniform( + low=noise_low, high=noise_high, size=self.model.nv + ) + + self.set_state(qpos, qvel) + + observation = self._get_obs() + return observation + + def viewer_setup(self): + for key, value in DEFAULT_CAMERA_CONFIG.items(): + if isinstance(value, np.ndarray): + getattr(self.viewer.cam, key)[:] = value + else: + setattr(self.viewer.cam, key, value) diff --git a/gym/envs/mujoco/thrower.py b/gym/envs/mujoco/thrower.py new file mode 100644 index 0000000000000000000000000000000000000000..b8b21a22abf123e743cb8542eefbf7dfcc39fec5 --- /dev/null +++ b/gym/envs/mujoco/thrower.py @@ -0,0 +1,67 @@ +import numpy as np +from gym import utils +from gym.envs.mujoco import mujoco_env + + +class ThrowerEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__(self): + utils.EzPickle.__init__(self) + self._ball_hit_ground = False + self._ball_hit_location = None + mujoco_env.MujocoEnv.__init__(self, "thrower.xml", 5) + + def step(self, a): + ball_xy = self.get_body_com("ball")[:2] + goal_xy = self.get_body_com("goal")[:2] + + if not self._ball_hit_ground and self.get_body_com("ball")[2] < -0.25: + self._ball_hit_ground = True + self._ball_hit_location = self.get_body_com("ball") + + if self._ball_hit_ground: + ball_hit_xy = self._ball_hit_location[:2] + reward_dist = -np.linalg.norm(ball_hit_xy - goal_xy) + else: + reward_dist = -np.linalg.norm(ball_xy - goal_xy) + reward_ctrl = -np.square(a).sum() + + reward = reward_dist + 0.002 * reward_ctrl + self.do_simulation(a, self.frame_skip) + ob = self._get_obs() + done = False + return ob, reward, done, dict(reward_dist=reward_dist, reward_ctrl=reward_ctrl) + + def viewer_setup(self): + self.viewer.cam.trackbodyid = 0 + self.viewer.cam.distance = 4.0 + + def reset_model(self): + self._ball_hit_ground = False + self._ball_hit_location = None + + qpos = self.init_qpos + self.goal = np.array( + [ + self.np_random.uniform(low=-0.3, high=0.3), + self.np_random.uniform(low=-0.3, high=0.3), + ] + ) + + qpos[-9:-7] = self.goal + qvel = self.init_qvel + self.np_random.uniform( + low=-0.005, high=0.005, size=self.model.nv + ) + qvel[7:] = 0 + self.set_state(qpos, qvel) + return self._get_obs() + + def _get_obs(self): + return np.concatenate( + [ + self.sim.data.qpos.flat[:7], + self.sim.data.qvel.flat[:7], + self.get_body_com("r_wrist_roll_link"), + self.get_body_com("ball"), + self.get_body_com("goal"), + ] + ) diff --git a/gym/envs/mujoco/walker2d.py b/gym/envs/mujoco/walker2d.py new file mode 100644 index 0000000000000000000000000000000000000000..5f49b4bf2eab32c76d6ff8484693515f6441f208 --- /dev/null +++ b/gym/envs/mujoco/walker2d.py @@ -0,0 +1,41 @@ +import numpy as np +from gym import utils +from gym.envs.mujoco import mujoco_env + + +class Walker2dEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__(self): + mujoco_env.MujocoEnv.__init__(self, "walker2d.xml", 4) + utils.EzPickle.__init__(self) + + def step(self, a): + posbefore = self.sim.data.qpos[0] + self.do_simulation(a, self.frame_skip) + posafter, height, ang = self.sim.data.qpos[0:3] + alive_bonus = 1.0 + reward = (posafter - posbefore) / self.dt + reward += alive_bonus + reward -= 1e-3 * np.square(a).sum() + done = not (height > 0.8 and height < 2.0 and ang > -1.0 and ang < 1.0) + ob = self._get_obs() + return ob, reward, done, {} + + def _get_obs(self): + qpos = self.sim.data.qpos + qvel = self.sim.data.qvel + return np.concatenate([qpos[1:], np.clip(qvel, -10, 10)]).ravel() + + def reset_model(self): + self.set_state( + self.init_qpos + + self.np_random.uniform(low=-0.005, high=0.005, size=self.model.nq), + self.init_qvel + + self.np_random.uniform(low=-0.005, high=0.005, size=self.model.nv), + ) + return self._get_obs() + + def viewer_setup(self): + self.viewer.cam.trackbodyid = 2 + self.viewer.cam.distance = self.model.stat.extent * 0.5 + self.viewer.cam.lookat[2] = 1.15 + self.viewer.cam.elevation = -20 diff --git a/gym/envs/mujoco/walker2d_v3.py b/gym/envs/mujoco/walker2d_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..eee6bb7d4ffdbbd4774d705e65c97fd11453e7f2 --- /dev/null +++ b/gym/envs/mujoco/walker2d_v3.py @@ -0,0 +1,130 @@ +import numpy as np +from gym.envs.mujoco import mujoco_env +from gym import utils + + +DEFAULT_CAMERA_CONFIG = { + "trackbodyid": 2, + "distance": 4.0, + "lookat": np.array((0.0, 0.0, 1.15)), + "elevation": -20.0, +} + + +class Walker2dEnv(mujoco_env.MujocoEnv, utils.EzPickle): + def __init__( + self, + xml_file="walker2d.xml", + forward_reward_weight=1.0, + ctrl_cost_weight=1e-3, + healthy_reward=1.0, + terminate_when_unhealthy=True, + healthy_z_range=(0.8, 2.0), + healthy_angle_range=(-1.0, 1.0), + reset_noise_scale=5e-3, + exclude_current_positions_from_observation=True, + ): + utils.EzPickle.__init__(**locals()) + + self._forward_reward_weight = forward_reward_weight + self._ctrl_cost_weight = ctrl_cost_weight + + self._healthy_reward = healthy_reward + self._terminate_when_unhealthy = terminate_when_unhealthy + + self._healthy_z_range = healthy_z_range + self._healthy_angle_range = healthy_angle_range + + self._reset_noise_scale = reset_noise_scale + + self._exclude_current_positions_from_observation = ( + exclude_current_positions_from_observation + ) + + mujoco_env.MujocoEnv.__init__(self, xml_file, 4) + + @property + def healthy_reward(self): + return ( + float(self.is_healthy or self._terminate_when_unhealthy) + * self._healthy_reward + ) + + def control_cost(self, action): + control_cost = self._ctrl_cost_weight * np.sum(np.square(action)) + return control_cost + + @property + def is_healthy(self): + z, angle = self.sim.data.qpos[1:3] + + min_z, max_z = self._healthy_z_range + min_angle, max_angle = self._healthy_angle_range + + healthy_z = min_z < z < max_z + healthy_angle = min_angle < angle < max_angle + is_healthy = healthy_z and healthy_angle + + return is_healthy + + @property + def done(self): + done = not self.is_healthy if self._terminate_when_unhealthy else False + return done + + def _get_obs(self): + position = self.sim.data.qpos.flat.copy() + velocity = np.clip(self.sim.data.qvel.flat.copy(), -10, 10) + + if self._exclude_current_positions_from_observation: + position = position[1:] + + observation = np.concatenate((position, velocity)).ravel() + return observation + + def step(self, action): + x_position_before = self.sim.data.qpos[0] + self.do_simulation(action, self.frame_skip) + x_position_after = self.sim.data.qpos[0] + x_velocity = (x_position_after - x_position_before) / self.dt + + ctrl_cost = self.control_cost(action) + + forward_reward = self._forward_reward_weight * x_velocity + healthy_reward = self.healthy_reward + + rewards = forward_reward + healthy_reward + costs = ctrl_cost + + observation = self._get_obs() + reward = rewards - costs + done = self.done + info = { + "x_position": x_position_after, + "x_velocity": x_velocity, + } + + return observation, reward, done, info + + def reset_model(self): + noise_low = -self._reset_noise_scale + noise_high = self._reset_noise_scale + + qpos = self.init_qpos + self.np_random.uniform( + low=noise_low, high=noise_high, size=self.model.nq + ) + qvel = self.init_qvel + self.np_random.uniform( + low=noise_low, high=noise_high, size=self.model.nv + ) + + self.set_state(qpos, qvel) + + observation = self._get_obs() + return observation + + def viewer_setup(self): + for key, value in DEFAULT_CAMERA_CONFIG.items(): + if isinstance(value, np.ndarray): + getattr(self.viewer.cam, key)[:] = value + else: + setattr(self.viewer.cam, key, value) diff --git a/gym/envs/registration.py b/gym/envs/registration.py new file mode 100644 index 0000000000000000000000000000000000000000..8af22cceb729362c165a10d1acf62527d563c94e --- /dev/null +++ b/gym/envs/registration.py @@ -0,0 +1,280 @@ +import re +import sys +import copy +import importlib +import contextlib + +if sys.version_info < (3, 8): + import importlib_metadata as metadata +else: + import importlib.metadata as metadata + +from gym import error, logger + +# This format is true today, but it's *not* an official spec. +# [username/](env-name)-v(version) env-name is group 1, version is group 2 +# +# 2016-10-31: We're experimentally expanding the environment ID format +# to include an optional username. +env_id_re = re.compile(r"^(?:[\w:-]+\/)?([\w:.-]+)-v(\d+)$") + +# Whitelist of plugins which can hook into the `gym.envs.internal` entry point. +plugin_internal_whitelist = {"ale_py.gym"} + + +def load(name): + mod_name, attr_name = name.split(":") + mod = importlib.import_module(mod_name) + fn = getattr(mod, attr_name) + return fn + + +class EnvSpec(object): + """A specification for a particular instance of the environment. Used + to register the parameters for official evaluations. + + Args: + id (str): The official environment ID + entry_point (Optional[str]): The Python entrypoint of the environment class (e.g. module.name:Class) + reward_threshold (Optional[int]): The reward threshold before the task is considered solved + nondeterministic (bool): Whether this environment is non-deterministic even after seeding + max_episode_steps (Optional[int]): The maximum number of steps that an episode can consist of + order_enforce (Optional[int]): Whether to wrap the environment in an orderEnforcing wrapper + kwargs (dict): The kwargs to pass to the environment class + + """ + + def __init__( + self, + id, + entry_point=None, + reward_threshold=None, + nondeterministic=False, + max_episode_steps=None, + order_enforce=True, + kwargs=None, + ): + self.id = id + self.entry_point = entry_point + self.reward_threshold = reward_threshold + self.nondeterministic = nondeterministic + self.max_episode_steps = max_episode_steps + self.order_enforce = order_enforce + self._kwargs = {} if kwargs is None else kwargs + + match = env_id_re.search(id) + if not match: + raise error.Error( + "Attempted to register malformed environment ID: {}. (Currently all IDs must be of the form {}.)".format( + id, env_id_re.pattern + ) + ) + self._env_name = match.group(1) + + def make(self, **kwargs): + """Instantiates an instance of the environment with appropriate kwargs""" + if self.entry_point is None: + raise error.Error( + "Attempting to make deprecated env {}. (HINT: is there a newer registered version of this env?)".format( + self.id + ) + ) + + _kwargs = self._kwargs.copy() + _kwargs.update(kwargs) + + if callable(self.entry_point): + env = self.entry_point(**_kwargs) + else: + cls = load(self.entry_point) + env = cls(**_kwargs) + + # Make the environment aware of which spec it came from. + spec = copy.deepcopy(self) + spec._kwargs = _kwargs + env.unwrapped.spec = spec + if env.spec.max_episode_steps is not None: + from gym.wrappers.time_limit import TimeLimit + + env = TimeLimit(env, max_episode_steps=env.spec.max_episode_steps) + else: + if self.order_enforce: + from gym.wrappers.order_enforcing import OrderEnforcing + + env = OrderEnforcing(env) + return env + + def __repr__(self): + return "EnvSpec({})".format(self.id) + + +class EnvRegistry(object): + """Register an env by ID. IDs remain stable over time and are + guaranteed to resolve to the same environment dynamics (or be + desupported). The goal is that results on a particular environment + should always be comparable, and not depend on the version of the + code that was running. + """ + + def __init__(self): + self.env_specs = {} + self._ns = None + + def make(self, path, **kwargs): + if len(kwargs) > 0: + logger.info("Making new env: %s (%s)", path, kwargs) + else: + logger.info("Making new env: %s", path) + spec = self.spec(path) + env = spec.make(**kwargs) + return env + + def all(self): + return self.env_specs.values() + + def spec(self, path): + if ":" in path: + mod_name, _, id = path.partition(":") + try: + importlib.import_module(mod_name) + except ModuleNotFoundError: + raise error.Error( + "A module ({}) was specified for the environment but was not found, make sure the package is installed with `pip install` before calling `gym.make()`".format( + mod_name + ) + ) + else: + id = path + + match = env_id_re.search(id) + if not match: + raise error.Error( + "Attempted to look up malformed environment ID: {}. (Currently all IDs must be of the form {}.)".format( + id.encode("utf-8"), env_id_re.pattern + ) + ) + + try: + return self.env_specs[id] + except KeyError: + # Parse the env name and check to see if it matches the non-version + # part of a valid env (could also check the exact number here) + env_name = match.group(1) + matching_envs = [ + valid_env_name + for valid_env_name, valid_env_spec in self.env_specs.items() + if env_name == valid_env_spec._env_name + ] + algorithmic_envs = [ + "Copy", + "RepeatCopy", + "DuplicatedInput", + "Reverse", + "ReversedAdiiton", + "ReversedAddition3", + ] + toytext_envs = [ + "KellyCoinflip", + "KellyCoinflipGeneralized", + "NChain", + "Roulette", + "GuessingGame", + "HotterColder", + ] + if matching_envs: + raise error.DeprecatedEnv( + "Env {} not found (valid versions include {})".format( + id, matching_envs + ) + ) + elif env_name in algorithmic_envs: + raise error.UnregisteredEnv( + "Algorithmic environment {} has been moved out of Gym. Install it via `pip install gym-algorithmic` and add `import gym_algorithmic` before using it.".format( + id + ) + ) + elif env_name in toytext_envs: + raise error.UnregisteredEnv( + "Toytext environment {} has been moved out of Gym. Install it via `pip install gym-legacy-toytext` and add `import gym_toytext` before using it.".format( + id + ) + ) + else: + raise error.UnregisteredEnv("No registered env with id: {}".format(id)) + + def register(self, id, **kwargs): + if self._ns is not None: + if "/" in id: + namespace, id = id.split("/") + logger.warn( + f"Custom namespace '{namespace}' is being overrode by namespace '{self._ns}'. " + "If you are developing a plugin you shouldn't specify a namespace in `register` calls. " + "The namespace is specified through the entry point key." + ) + id = f"{self._ns}/{id}" + if id in self.env_specs: + logger.warn("Overriding environment {}".format(id)) + self.env_specs[id] = EnvSpec(id, **kwargs) + + @contextlib.contextmanager + def namespace(self, ns): + self._ns = ns + yield + self._ns = None + + +# Have a global registry +registry = EnvRegistry() + + +def register(id, **kwargs): + return registry.register(id, **kwargs) + + +def make(id, **kwargs): + return registry.make(id, **kwargs) + + +def spec(id): + return registry.spec(id) + + +@contextlib.contextmanager +def namespace(ns): + with registry.namespace(ns): + yield + + +def load_env_plugins(entry_point="gym.envs"): + # Load third-party environments + for plugin in metadata.entry_points().get(entry_point, []): + # Python 3.8 doesn't support plugin.module, plugin.attr + # So we'll have to try and parse this ourselves + try: + module, attr = plugin.module, plugin.attr + except AttributeError: + if ":" in plugin.value: + module, attr = plugin.value.split(":", maxsplit=1) + else: + module, attr = plugin.value, None + finally: + if attr is None: + raise error.Error( + f"Gym environment plugin `{module}` must specify a function to execute, not a root module" + ) + + context = namespace(plugin.name) + if plugin.name == "__internal__": + if module in plugin_internal_whitelist: + context = contextlib.nullcontext() + else: + logger.warn( + f"Trying to register an internal environment when `{module}` is not in the whitelist" + ) + + with context: + fn = plugin.load() + try: + fn() + except Exception as e: + logger.warn(str(e)) diff --git a/gym/envs/robotics/__init__.py b/gym/envs/robotics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8ff166314aba399f33753297288a3028447cdea3 --- /dev/null +++ b/gym/envs/robotics/__init__.py @@ -0,0 +1,14 @@ +from gym.envs.robotics.fetch_env import FetchEnv +from gym.envs.robotics.fetch.slide import FetchSlideEnv +from gym.envs.robotics.fetch.pick_and_place import FetchPickAndPlaceEnv +from gym.envs.robotics.fetch.push import FetchPushEnv +from gym.envs.robotics.fetch.reach import FetchReachEnv + +from gym.envs.robotics.hand.reach import HandReachEnv +from gym.envs.robotics.hand.manipulate import HandBlockEnv +from gym.envs.robotics.hand.manipulate import HandEggEnv +from gym.envs.robotics.hand.manipulate import HandPenEnv + +from gym.envs.robotics.hand.manipulate_touch_sensors import HandBlockTouchSensorsEnv +from gym.envs.robotics.hand.manipulate_touch_sensors import HandEggTouchSensorsEnv +from gym.envs.robotics.hand.manipulate_touch_sensors import HandPenTouchSensorsEnv diff --git a/gym/envs/robotics/__pycache__/__init__.cpython-39.pyc b/gym/envs/robotics/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e875f134e973edbb63851e2e74dfff509fc09b8 Binary files /dev/null and b/gym/envs/robotics/__pycache__/__init__.cpython-39.pyc differ diff --git a/gym/envs/robotics/__pycache__/fetch_env.cpython-39.pyc b/gym/envs/robotics/__pycache__/fetch_env.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8fb3dc97fa6966d9e1e177eb2a142b50a3a6b38 Binary files /dev/null and b/gym/envs/robotics/__pycache__/fetch_env.cpython-39.pyc differ diff --git a/gym/envs/robotics/__pycache__/hand_env.cpython-39.pyc b/gym/envs/robotics/__pycache__/hand_env.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3165b10a678cdb24eb2f2b0bfbf6024ca9cd4e24 Binary files /dev/null and b/gym/envs/robotics/__pycache__/hand_env.cpython-39.pyc differ diff --git a/gym/envs/robotics/__pycache__/robot_env.cpython-39.pyc b/gym/envs/robotics/__pycache__/robot_env.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c65cb4c25900f73b01a89c0621117fece82d895 Binary files /dev/null and b/gym/envs/robotics/__pycache__/robot_env.cpython-39.pyc differ diff --git a/gym/envs/robotics/__pycache__/rotations.cpython-39.pyc b/gym/envs/robotics/__pycache__/rotations.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..187c35e202c96f5bd3d0591aaa737f51e413bb52 Binary files /dev/null and b/gym/envs/robotics/__pycache__/rotations.cpython-39.pyc differ diff --git a/gym/envs/robotics/__pycache__/utils.cpython-39.pyc b/gym/envs/robotics/__pycache__/utils.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db8072bfe13176a9210c686e9a6a8199de703df8 Binary files /dev/null and b/gym/envs/robotics/__pycache__/utils.cpython-39.pyc differ diff --git a/gym/envs/robotics/assets/LICENSE.md b/gym/envs/robotics/assets/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..22ce9010d0b834098905c5b631e780723def824f --- /dev/null +++ b/gym/envs/robotics/assets/LICENSE.md @@ -0,0 +1,222 @@ +# Fetch Robotics +The model of the [Fetch](http://fetchrobotics.com/platforms-research-development/) is based on [models provided by Fetch](https://github.com/fetchrobotics/fetch_ros/tree/indigo-devel/fetch_description). It was adapted and refined by OpenAI. + +# ShadowHand +The model of the [ShadowHand](https://www.shadowrobot.com/products/dexterous-hand/) is based on [models provided by ShadowRobot](https://github.com/shadow-robot/sr_common/tree/kinetic-devel/sr_description/hand/model), and on code used under the following license: + +(C) Vikash Kumar, CSE, UW. Licensed under Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Additional license notices: + + Sources : 1) Manipulator and Manipulation in High Dimensional Spaces. Vikash Kumar, Ph.D. Thesis, CSE, Univ. of Washington. 2016. + + Mujoco :: Advanced physics simulation engine + Source : www.roboti.us + Version : 1.40 + Released : 17Jan'17 + + Author :: Vikash Kumar + Contacts : vikash@openai.com + Last edits : 3Apr'17 diff --git a/gym/envs/robotics/assets/fetch/pick_and_place.xml b/gym/envs/robotics/assets/fetch/pick_and_place.xml new file mode 100644 index 0000000000000000000000000000000000000000..337032a8329bcbbd21231fe063c0df39e4ee95b4 --- /dev/null +++ b/gym/envs/robotics/assets/fetch/pick_and_place.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/robotics/assets/fetch/push.xml b/gym/envs/robotics/assets/fetch/push.xml new file mode 100644 index 0000000000000000000000000000000000000000..8e12db248c10708362338126f9eb6bcae1cdd9da --- /dev/null +++ b/gym/envs/robotics/assets/fetch/push.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/gym/envs/robotics/assets/fetch/reach.xml b/gym/envs/robotics/assets/fetch/reach.xml new file mode 100644 index 0000000000000000000000000000000000000000..c73d6249f3d809336c91798ee10dd57df73de4df --- /dev/null +++ b/gym/envs/robotics/assets/fetch/reach.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/robotics/assets/fetch/robot.xml b/gym/envs/robotics/assets/fetch/robot.xml new file mode 100644 index 0000000000000000000000000000000000000000..b627d4925d52565feb41ce9bb53d745ec5eb2e6c --- /dev/null +++ b/gym/envs/robotics/assets/fetch/robot.xml @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/robotics/assets/fetch/shared.xml b/gym/envs/robotics/assets/fetch/shared.xml new file mode 100644 index 0000000000000000000000000000000000000000..5d61fef70dd10b018a216b73c023f958abaf8234 --- /dev/null +++ b/gym/envs/robotics/assets/fetch/shared.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/robotics/assets/fetch/slide.xml b/gym/envs/robotics/assets/fetch/slide.xml new file mode 100644 index 0000000000000000000000000000000000000000..efbfb51bd06b34257d27afd107df0d7c15619fdf --- /dev/null +++ b/gym/envs/robotics/assets/fetch/slide.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/robotics/assets/hand/manipulate_block.xml b/gym/envs/robotics/assets/hand/manipulate_block.xml new file mode 100644 index 0000000000000000000000000000000000000000..83a6517e6cf6ecc618060346e2fb8da66b6e76ae --- /dev/null +++ b/gym/envs/robotics/assets/hand/manipulate_block.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/robotics/assets/hand/manipulate_block_touch_sensors.xml b/gym/envs/robotics/assets/hand/manipulate_block_touch_sensors.xml new file mode 100644 index 0000000000000000000000000000000000000000..b649f102917eb404c7278c5e7588eea6f878a364 --- /dev/null +++ b/gym/envs/robotics/assets/hand/manipulate_block_touch_sensors.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/robotics/assets/hand/manipulate_egg.xml b/gym/envs/robotics/assets/hand/manipulate_egg.xml new file mode 100644 index 0000000000000000000000000000000000000000..d60217f761fb63a73efb8ef47906c813f3fcadba --- /dev/null +++ b/gym/envs/robotics/assets/hand/manipulate_egg.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/robotics/assets/hand/manipulate_egg_touch_sensors.xml b/gym/envs/robotics/assets/hand/manipulate_egg_touch_sensors.xml new file mode 100644 index 0000000000000000000000000000000000000000..73af83c0f5d485daac380ab60370b2b7fe361dbe --- /dev/null +++ b/gym/envs/robotics/assets/hand/manipulate_egg_touch_sensors.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/robotics/assets/hand/manipulate_pen.xml b/gym/envs/robotics/assets/hand/manipulate_pen.xml new file mode 100644 index 0000000000000000000000000000000000000000..20a6fb5e06d745a45435c673c488eb516f6af4fa --- /dev/null +++ b/gym/envs/robotics/assets/hand/manipulate_pen.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/robotics/assets/hand/manipulate_pen_touch_sensors.xml b/gym/envs/robotics/assets/hand/manipulate_pen_touch_sensors.xml new file mode 100644 index 0000000000000000000000000000000000000000..758839bfcb24c930dc11fe6ddb5bb72758115d07 --- /dev/null +++ b/gym/envs/robotics/assets/hand/manipulate_pen_touch_sensors.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/robotics/assets/hand/reach.xml b/gym/envs/robotics/assets/hand/reach.xml new file mode 100644 index 0000000000000000000000000000000000000000..71f6dfe621860e86569f00895bb1e73286f4558f --- /dev/null +++ b/gym/envs/robotics/assets/hand/reach.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/robotics/assets/hand/robot.xml b/gym/envs/robotics/assets/hand/robot.xml new file mode 100644 index 0000000000000000000000000000000000000000..dbb9e43448e267d3c6198c94570c4e6ef5e1f2d1 --- /dev/null +++ b/gym/envs/robotics/assets/hand/robot.xml @@ -0,0 +1,160 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/robotics/assets/hand/robot_touch_sensors_92.xml b/gym/envs/robotics/assets/hand/robot_touch_sensors_92.xml new file mode 100644 index 0000000000000000000000000000000000000000..fa6d41c0a85266036fd78dfdf1b4d374ed2df36d --- /dev/null +++ b/gym/envs/robotics/assets/hand/robot_touch_sensors_92.xml @@ -0,0 +1,252 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/robotics/assets/hand/shared.xml b/gym/envs/robotics/assets/hand/shared.xml new file mode 100644 index 0000000000000000000000000000000000000000..f27f265551c741c4eab32d238869d5c43357cb84 --- /dev/null +++ b/gym/envs/robotics/assets/hand/shared.xml @@ -0,0 +1,254 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/robotics/assets/hand/shared_asset.xml b/gym/envs/robotics/assets/hand/shared_asset.xml new file mode 100644 index 0000000000000000000000000000000000000000..ec9a0b08b641fa520e4b09e8d8ff3772c2962ac7 --- /dev/null +++ b/gym/envs/robotics/assets/hand/shared_asset.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/robotics/assets/hand/shared_touch_sensors_92.xml b/gym/envs/robotics/assets/hand/shared_touch_sensors_92.xml new file mode 100644 index 0000000000000000000000000000000000000000..472c84ccb7c3b1858aa6d83b67f764aadf1cdf0c --- /dev/null +++ b/gym/envs/robotics/assets/hand/shared_touch_sensors_92.xml @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gym/envs/robotics/assets/stls/fetch/base_link_collision.stl b/gym/envs/robotics/assets/stls/fetch/base_link_collision.stl new file mode 100644 index 0000000000000000000000000000000000000000..1ef459fd5bb63e2e5391b6166bc3231b37d07170 Binary files /dev/null and b/gym/envs/robotics/assets/stls/fetch/base_link_collision.stl differ diff --git a/gym/envs/robotics/assets/stls/fetch/bellows_link_collision.stl b/gym/envs/robotics/assets/stls/fetch/bellows_link_collision.stl new file mode 100644 index 0000000000000000000000000000000000000000..a7e5ab75ca42d597fc49d7913446ab7e6c2388f3 Binary files /dev/null and b/gym/envs/robotics/assets/stls/fetch/bellows_link_collision.stl differ diff --git a/gym/envs/robotics/assets/stls/fetch/elbow_flex_link_collision.stl b/gym/envs/robotics/assets/stls/fetch/elbow_flex_link_collision.stl new file mode 100644 index 0000000000000000000000000000000000000000..b0eea0777a10b5aad2e9237c888883944492c42e Binary files /dev/null and b/gym/envs/robotics/assets/stls/fetch/elbow_flex_link_collision.stl differ diff --git a/gym/envs/robotics/assets/stls/fetch/estop_link.stl b/gym/envs/robotics/assets/stls/fetch/estop_link.stl new file mode 100644 index 0000000000000000000000000000000000000000..f6d1c72e85f9b028b8a6026278a1d99f1035f353 Binary files /dev/null and b/gym/envs/robotics/assets/stls/fetch/estop_link.stl differ diff --git a/gym/envs/robotics/assets/stls/fetch/forearm_roll_link_collision.stl b/gym/envs/robotics/assets/stls/fetch/forearm_roll_link_collision.stl new file mode 100644 index 0000000000000000000000000000000000000000..fe468c540639d27015b8859a235bc10ce931ab8e Binary files /dev/null and b/gym/envs/robotics/assets/stls/fetch/forearm_roll_link_collision.stl differ diff --git a/gym/envs/robotics/assets/stls/fetch/gripper_link.stl b/gym/envs/robotics/assets/stls/fetch/gripper_link.stl new file mode 100644 index 0000000000000000000000000000000000000000..8a1487401a6b3f85edd115fd76419851d0001a6f Binary files /dev/null and b/gym/envs/robotics/assets/stls/fetch/gripper_link.stl differ diff --git a/gym/envs/robotics/assets/stls/fetch/head_pan_link_collision.stl b/gym/envs/robotics/assets/stls/fetch/head_pan_link_collision.stl new file mode 100644 index 0000000000000000000000000000000000000000..c77b5b187257f0ca97da05b5222d6115e01eff09 Binary files /dev/null and b/gym/envs/robotics/assets/stls/fetch/head_pan_link_collision.stl differ diff --git a/gym/envs/robotics/assets/stls/fetch/head_tilt_link_collision.stl b/gym/envs/robotics/assets/stls/fetch/head_tilt_link_collision.stl new file mode 100644 index 0000000000000000000000000000000000000000..53c2ddc58c1d342df4f30deb56137bda68aedeed Binary files /dev/null and b/gym/envs/robotics/assets/stls/fetch/head_tilt_link_collision.stl differ diff --git a/gym/envs/robotics/assets/stls/fetch/l_wheel_link_collision.stl b/gym/envs/robotics/assets/stls/fetch/l_wheel_link_collision.stl new file mode 100644 index 0000000000000000000000000000000000000000..5c1752487efc163453d32996e667e63713a6a398 Binary files /dev/null and b/gym/envs/robotics/assets/stls/fetch/l_wheel_link_collision.stl differ diff --git a/gym/envs/robotics/assets/stls/fetch/laser_link.stl b/gym/envs/robotics/assets/stls/fetch/laser_link.stl new file mode 100644 index 0000000000000000000000000000000000000000..fa4882fc9830423e8f0b623636c325f9154feba9 Binary files /dev/null and b/gym/envs/robotics/assets/stls/fetch/laser_link.stl differ diff --git a/gym/envs/robotics/assets/stls/fetch/r_wheel_link_collision.stl b/gym/envs/robotics/assets/stls/fetch/r_wheel_link_collision.stl new file mode 100644 index 0000000000000000000000000000000000000000..3742b24694f3bcf542254754f452eb316006b35b Binary files /dev/null and b/gym/envs/robotics/assets/stls/fetch/r_wheel_link_collision.stl differ diff --git a/gym/envs/robotics/assets/stls/fetch/shoulder_lift_link_collision.stl b/gym/envs/robotics/assets/stls/fetch/shoulder_lift_link_collision.stl new file mode 100644 index 0000000000000000000000000000000000000000..c9aff0dda920b09c76639d737fbb6a3d83c29d10 Binary files /dev/null and b/gym/envs/robotics/assets/stls/fetch/shoulder_lift_link_collision.stl differ diff --git a/gym/envs/robotics/assets/stls/fetch/shoulder_pan_link_collision.stl b/gym/envs/robotics/assets/stls/fetch/shoulder_pan_link_collision.stl new file mode 100644 index 0000000000000000000000000000000000000000..ac17a943757561c9d0d5b381af2cbc24b8b8b4c4 Binary files /dev/null and b/gym/envs/robotics/assets/stls/fetch/shoulder_pan_link_collision.stl differ diff --git a/gym/envs/robotics/assets/stls/fetch/torso_fixed_link.stl b/gym/envs/robotics/assets/stls/fetch/torso_fixed_link.stl new file mode 100644 index 0000000000000000000000000000000000000000..7cf7fc147ebeae583d537a0a9842398921f8495f Binary files /dev/null and b/gym/envs/robotics/assets/stls/fetch/torso_fixed_link.stl differ diff --git a/gym/envs/robotics/assets/stls/fetch/torso_lift_link_collision.stl b/gym/envs/robotics/assets/stls/fetch/torso_lift_link_collision.stl new file mode 100644 index 0000000000000000000000000000000000000000..4ce5fcf9c58c885b37dc012f6a539f3e89776006 Binary files /dev/null and b/gym/envs/robotics/assets/stls/fetch/torso_lift_link_collision.stl differ diff --git a/gym/envs/robotics/assets/stls/fetch/upperarm_roll_link_collision.stl b/gym/envs/robotics/assets/stls/fetch/upperarm_roll_link_collision.stl new file mode 100644 index 0000000000000000000000000000000000000000..120793232e41601320be52e298be450de59e3b5f Binary files /dev/null and b/gym/envs/robotics/assets/stls/fetch/upperarm_roll_link_collision.stl differ diff --git a/gym/envs/robotics/assets/stls/fetch/wrist_flex_link_collision.stl b/gym/envs/robotics/assets/stls/fetch/wrist_flex_link_collision.stl new file mode 100644 index 0000000000000000000000000000000000000000..3215d2e1de0f271dfdfc8abb2c00c47cafaabe45 Binary files /dev/null and b/gym/envs/robotics/assets/stls/fetch/wrist_flex_link_collision.stl differ diff --git a/gym/envs/robotics/assets/stls/fetch/wrist_roll_link_collision.stl b/gym/envs/robotics/assets/stls/fetch/wrist_roll_link_collision.stl new file mode 100644 index 0000000000000000000000000000000000000000..742bdd9197a34dadf2092b6062ebd18cf7ff9ab8 Binary files /dev/null and b/gym/envs/robotics/assets/stls/fetch/wrist_roll_link_collision.stl differ diff --git a/gym/envs/robotics/assets/stls/hand/F1.stl b/gym/envs/robotics/assets/stls/hand/F1.stl new file mode 100644 index 0000000000000000000000000000000000000000..515d3c90169fb7b7a5ecb344bb63267d5352ad8c Binary files /dev/null and b/gym/envs/robotics/assets/stls/hand/F1.stl differ diff --git a/gym/envs/robotics/assets/stls/hand/F2.stl b/gym/envs/robotics/assets/stls/hand/F2.stl new file mode 100644 index 0000000000000000000000000000000000000000..7bc5e20e0687f593401d369224d6f36d78f37534 Binary files /dev/null and b/gym/envs/robotics/assets/stls/hand/F2.stl differ diff --git a/gym/envs/robotics/assets/stls/hand/F3.stl b/gym/envs/robotics/assets/stls/hand/F3.stl new file mode 100644 index 0000000000000000000000000000000000000000..223f06f5bfb8af17e33c6fee5f0fa3d65c76d6bf Binary files /dev/null and b/gym/envs/robotics/assets/stls/hand/F3.stl differ diff --git a/gym/envs/robotics/assets/stls/hand/TH1_z.stl b/gym/envs/robotics/assets/stls/hand/TH1_z.stl new file mode 100644 index 0000000000000000000000000000000000000000..400ee2d62567af07045150511539919e758c05eb Binary files /dev/null and b/gym/envs/robotics/assets/stls/hand/TH1_z.stl differ diff --git a/gym/envs/robotics/assets/stls/hand/TH2_z.stl b/gym/envs/robotics/assets/stls/hand/TH2_z.stl new file mode 100644 index 0000000000000000000000000000000000000000..5ace8388b9fad8fc9f4a30d25a00592a312864f1 Binary files /dev/null and b/gym/envs/robotics/assets/stls/hand/TH2_z.stl differ diff --git a/gym/envs/robotics/assets/stls/hand/TH3_z.stl b/gym/envs/robotics/assets/stls/hand/TH3_z.stl new file mode 100644 index 0000000000000000000000000000000000000000..23485abc720951ef1ae56a72aa965e30c3ab8442 Binary files /dev/null and b/gym/envs/robotics/assets/stls/hand/TH3_z.stl differ diff --git a/gym/envs/robotics/assets/stls/hand/forearm_electric.stl b/gym/envs/robotics/assets/stls/hand/forearm_electric.stl new file mode 100644 index 0000000000000000000000000000000000000000..80f6f3da18910adf264507190fbb4d074a9da32f Binary files /dev/null and b/gym/envs/robotics/assets/stls/hand/forearm_electric.stl differ diff --git a/gym/envs/robotics/assets/stls/hand/forearm_electric_cvx.stl b/gym/envs/robotics/assets/stls/hand/forearm_electric_cvx.stl new file mode 100644 index 0000000000000000000000000000000000000000..3c30f57eaa99ae884a8c69d37401c8875ad3b712 Binary files /dev/null and b/gym/envs/robotics/assets/stls/hand/forearm_electric_cvx.stl differ diff --git a/gym/envs/robotics/assets/stls/hand/knuckle.stl b/gym/envs/robotics/assets/stls/hand/knuckle.stl new file mode 100644 index 0000000000000000000000000000000000000000..4faedd75409416ac79c8481c067bddff06eac19c Binary files /dev/null and b/gym/envs/robotics/assets/stls/hand/knuckle.stl differ diff --git a/gym/envs/robotics/assets/stls/hand/lfmetacarpal.stl b/gym/envs/robotics/assets/stls/hand/lfmetacarpal.stl new file mode 100644 index 0000000000000000000000000000000000000000..535cf4dbca59590f813c6dcc8abbd10bc7810a3a Binary files /dev/null and b/gym/envs/robotics/assets/stls/hand/lfmetacarpal.stl differ diff --git a/gym/envs/robotics/assets/stls/hand/palm.stl b/gym/envs/robotics/assets/stls/hand/palm.stl new file mode 100644 index 0000000000000000000000000000000000000000..65e47eb65dad73dee839c05a7b1b2c285541defb Binary files /dev/null and b/gym/envs/robotics/assets/stls/hand/palm.stl differ diff --git a/gym/envs/robotics/assets/stls/hand/wrist.stl b/gym/envs/robotics/assets/stls/hand/wrist.stl new file mode 100644 index 0000000000000000000000000000000000000000..420d5f9c678de1f13ace2fb50a9ba3531ab90194 Binary files /dev/null and b/gym/envs/robotics/assets/stls/hand/wrist.stl differ diff --git a/gym/envs/robotics/assets/textures/block.png b/gym/envs/robotics/assets/textures/block.png new file mode 100644 index 0000000000000000000000000000000000000000..0243b8f33123749b1811b3ae03eeb202d0279db6 Binary files /dev/null and b/gym/envs/robotics/assets/textures/block.png differ diff --git a/gym/envs/robotics/assets/textures/block_hidden.png b/gym/envs/robotics/assets/textures/block_hidden.png new file mode 100644 index 0000000000000000000000000000000000000000..e08b8613c4dfede9786e5ed841dc6dd529fef92e Binary files /dev/null and b/gym/envs/robotics/assets/textures/block_hidden.png differ diff --git a/gym/envs/robotics/fetch/__init__.py b/gym/envs/robotics/fetch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gym/envs/robotics/fetch/__pycache__/__init__.cpython-39.pyc b/gym/envs/robotics/fetch/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56b5524afd965ac8708321c9c4fb106ac2939bbb Binary files /dev/null and b/gym/envs/robotics/fetch/__pycache__/__init__.cpython-39.pyc differ diff --git a/gym/envs/robotics/fetch/__pycache__/pick_and_place.cpython-39.pyc b/gym/envs/robotics/fetch/__pycache__/pick_and_place.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b88a67f8c25fb7215d41fb09793dd09a5fd7905e Binary files /dev/null and b/gym/envs/robotics/fetch/__pycache__/pick_and_place.cpython-39.pyc differ diff --git a/gym/envs/robotics/fetch/__pycache__/push.cpython-39.pyc b/gym/envs/robotics/fetch/__pycache__/push.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdd54db2e3fa9947a20939e11e4205b8233a5d06 Binary files /dev/null and b/gym/envs/robotics/fetch/__pycache__/push.cpython-39.pyc differ diff --git a/gym/envs/robotics/fetch/__pycache__/reach.cpython-39.pyc b/gym/envs/robotics/fetch/__pycache__/reach.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..970da7ff6edeb613897bb266c7da6534cd9b9c71 Binary files /dev/null and b/gym/envs/robotics/fetch/__pycache__/reach.cpython-39.pyc differ diff --git a/gym/envs/robotics/fetch/__pycache__/slide.cpython-39.pyc b/gym/envs/robotics/fetch/__pycache__/slide.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a9f4e4e7471ffce259a64df7c62e7f3225f6ffc Binary files /dev/null and b/gym/envs/robotics/fetch/__pycache__/slide.cpython-39.pyc differ diff --git a/gym/envs/robotics/fetch/pick_and_place.py b/gym/envs/robotics/fetch/pick_and_place.py new file mode 100644 index 0000000000000000000000000000000000000000..4e1a6d5313b14286a2f867d40411b1dad0cdb776 --- /dev/null +++ b/gym/envs/robotics/fetch/pick_and_place.py @@ -0,0 +1,33 @@ +import os +from gym import utils +from gym.envs.robotics import fetch_env + + +# Ensure we get the path separator correct on windows +MODEL_XML_PATH = os.path.join("fetch", "pick_and_place.xml") + + +class FetchPickAndPlaceEnv(fetch_env.FetchEnv, utils.EzPickle): + def __init__(self, reward_type="sparse"): + initial_qpos = { + "robot0:slide0": 0.405, + "robot0:slide1": 0.48, + "robot0:slide2": 0.0, + "object0:joint": [1.25, 0.53, 0.4, 1.0, 0.0, 0.0, 0.0], + } + fetch_env.FetchEnv.__init__( + self, + MODEL_XML_PATH, + has_object=True, + block_gripper=False, + n_substeps=20, + gripper_extra_height=0.2, + target_in_the_air=True, + target_offset=0.0, + obj_range=0.15, + target_range=0.15, + distance_threshold=0.05, + initial_qpos=initial_qpos, + reward_type=reward_type, + ) + utils.EzPickle.__init__(self, reward_type=reward_type) diff --git a/gym/envs/robotics/fetch/push.py b/gym/envs/robotics/fetch/push.py new file mode 100644 index 0000000000000000000000000000000000000000..3227374e8ccba1fff4dcbf8ee2684d781f7970da --- /dev/null +++ b/gym/envs/robotics/fetch/push.py @@ -0,0 +1,33 @@ +import os +from gym import utils +from gym.envs.robotics import fetch_env + + +# Ensure we get the path separator correct on windows +MODEL_XML_PATH = os.path.join("fetch", "push.xml") + + +class FetchPushEnv(fetch_env.FetchEnv, utils.EzPickle): + def __init__(self, reward_type="sparse"): + initial_qpos = { + "robot0:slide0": 0.405, + "robot0:slide1": 0.48, + "robot0:slide2": 0.0, + "object0:joint": [1.25, 0.53, 0.4, 1.0, 0.0, 0.0, 0.0], + } + fetch_env.FetchEnv.__init__( + self, + MODEL_XML_PATH, + has_object=True, + block_gripper=True, + n_substeps=20, + gripper_extra_height=0.0, + target_in_the_air=False, + target_offset=0.0, + obj_range=0.15, + target_range=0.15, + distance_threshold=0.05, + initial_qpos=initial_qpos, + reward_type=reward_type, + ) + utils.EzPickle.__init__(self, reward_type=reward_type) diff --git a/gym/envs/robotics/fetch/reach.py b/gym/envs/robotics/fetch/reach.py new file mode 100644 index 0000000000000000000000000000000000000000..67520b95064cb675a2430d7b035a4fd8dd9b89c7 --- /dev/null +++ b/gym/envs/robotics/fetch/reach.py @@ -0,0 +1,32 @@ +import os +from gym import utils +from gym.envs.robotics import fetch_env + + +# Ensure we get the path separator correct on windows +MODEL_XML_PATH = os.path.join("fetch", "reach.xml") + + +class FetchReachEnv(fetch_env.FetchEnv, utils.EzPickle): + def __init__(self, reward_type="sparse"): + initial_qpos = { + "robot0:slide0": 0.4049, + "robot0:slide1": 0.48, + "robot0:slide2": 0.0, + } + fetch_env.FetchEnv.__init__( + self, + MODEL_XML_PATH, + has_object=False, + block_gripper=True, + n_substeps=20, + gripper_extra_height=0.2, + target_in_the_air=True, + target_offset=0.0, + obj_range=0.15, + target_range=0.15, + distance_threshold=0.05, + initial_qpos=initial_qpos, + reward_type=reward_type, + ) + utils.EzPickle.__init__(self, reward_type=reward_type) diff --git a/gym/envs/robotics/fetch/slide.py b/gym/envs/robotics/fetch/slide.py new file mode 100644 index 0000000000000000000000000000000000000000..ab47db7ff52780c10066f6e78482c7ab7a00a676 --- /dev/null +++ b/gym/envs/robotics/fetch/slide.py @@ -0,0 +1,35 @@ +import os +import numpy as np + +from gym import utils +from gym.envs.robotics import fetch_env + + +# Ensure we get the path separator correct on windows +MODEL_XML_PATH = os.path.join("fetch", "slide.xml") + + +class FetchSlideEnv(fetch_env.FetchEnv, utils.EzPickle): + def __init__(self, reward_type="sparse"): + initial_qpos = { + "robot0:slide0": 0.05, + "robot0:slide1": 0.48, + "robot0:slide2": 0.0, + "object0:joint": [1.7, 1.1, 0.41, 1.0, 0.0, 0.0, 0.0], + } + fetch_env.FetchEnv.__init__( + self, + MODEL_XML_PATH, + has_object=True, + block_gripper=True, + n_substeps=20, + gripper_extra_height=-0.02, + target_in_the_air=False, + target_offset=np.array([0.4, 0.0, 0.0]), + obj_range=0.1, + target_range=0.3, + distance_threshold=0.05, + initial_qpos=initial_qpos, + reward_type=reward_type, + ) + utils.EzPickle.__init__(self, reward_type=reward_type) diff --git a/gym/envs/robotics/fetch_env.py b/gym/envs/robotics/fetch_env.py new file mode 100644 index 0000000000000000000000000000000000000000..8142acab0f55fa7ee644c379afcb35e1f38acb43 --- /dev/null +++ b/gym/envs/robotics/fetch_env.py @@ -0,0 +1,230 @@ +import numpy as np + +from gym.envs.robotics import rotations, robot_env, utils + + +def goal_distance(goal_a, goal_b): + assert goal_a.shape == goal_b.shape + return np.linalg.norm(goal_a - goal_b, axis=-1) + + +class FetchEnv(robot_env.RobotEnv): + """Superclass for all Fetch environments.""" + + def __init__( + self, + model_path, + n_substeps, + gripper_extra_height, + block_gripper, + has_object, + target_in_the_air, + target_offset, + obj_range, + target_range, + distance_threshold, + initial_qpos, + reward_type, + ): + """Initializes a new Fetch environment. + + Args: + model_path (string): path to the environments XML file + n_substeps (int): number of substeps the simulation runs on every call to step + gripper_extra_height (float): additional height above the table when positioning the gripper + block_gripper (boolean): whether or not the gripper is blocked (i.e. not movable) or not + has_object (boolean): whether or not the environment has an object + target_in_the_air (boolean): whether or not the target should be in the air above the table or on the table surface + target_offset (float or array with 3 elements): offset of the target + obj_range (float): range of a uniform distribution for sampling initial object positions + target_range (float): range of a uniform distribution for sampling a target + distance_threshold (float): the threshold after which a goal is considered achieved + initial_qpos (dict): a dictionary of joint names and values that define the initial configuration + reward_type ('sparse' or 'dense'): the reward type, i.e. sparse or dense + """ + self.gripper_extra_height = gripper_extra_height + self.block_gripper = block_gripper + self.has_object = has_object + self.target_in_the_air = target_in_the_air + self.target_offset = target_offset + self.obj_range = obj_range + self.target_range = target_range + self.distance_threshold = distance_threshold + self.reward_type = reward_type + + super(FetchEnv, self).__init__( + model_path=model_path, + n_substeps=n_substeps, + n_actions=4, + initial_qpos=initial_qpos, + ) + + # GoalEnv methods + # ---------------------------- + + def compute_reward(self, achieved_goal, goal, info): + # Compute distance between goal and the achieved goal. + d = goal_distance(achieved_goal, goal) + if self.reward_type == "sparse": + return -(d > self.distance_threshold).astype(np.float32) + else: + return -d + + # RobotEnv methods + # ---------------------------- + + def _step_callback(self): + if self.block_gripper: + self.sim.data.set_joint_qpos("robot0:l_gripper_finger_joint", 0.0) + self.sim.data.set_joint_qpos("robot0:r_gripper_finger_joint", 0.0) + self.sim.forward() + + def _set_action(self, action): + assert action.shape == (4,) + action = ( + action.copy() + ) # ensure that we don't change the action outside of this scope + pos_ctrl, gripper_ctrl = action[:3], action[3] + + pos_ctrl *= 0.05 # limit maximum change in position + rot_ctrl = [ + 1.0, + 0.0, + 1.0, + 0.0, + ] # fixed rotation of the end effector, expressed as a quaternion + gripper_ctrl = np.array([gripper_ctrl, gripper_ctrl]) + assert gripper_ctrl.shape == (2,) + if self.block_gripper: + gripper_ctrl = np.zeros_like(gripper_ctrl) + action = np.concatenate([pos_ctrl, rot_ctrl, gripper_ctrl]) + + # Apply action to simulation. + utils.ctrl_set_action(self.sim, action) + utils.mocap_set_action(self.sim, action) + + def _get_obs(self): + # positions + grip_pos = self.sim.data.get_site_xpos("robot0:grip") + dt = self.sim.nsubsteps * self.sim.model.opt.timestep + grip_velp = self.sim.data.get_site_xvelp("robot0:grip") * dt + robot_qpos, robot_qvel = utils.robot_get_obs(self.sim) + if self.has_object: + object_pos = self.sim.data.get_site_xpos("object0") + # rotations + object_rot = rotations.mat2euler(self.sim.data.get_site_xmat("object0")) + # velocities + object_velp = self.sim.data.get_site_xvelp("object0") * dt + object_velr = self.sim.data.get_site_xvelr("object0") * dt + # gripper state + object_rel_pos = object_pos - grip_pos + object_velp -= grip_velp + else: + object_pos = ( + object_rot + ) = object_velp = object_velr = object_rel_pos = np.zeros(0) + gripper_state = robot_qpos[-2:] + gripper_vel = ( + robot_qvel[-2:] * dt + ) # change to a scalar if the gripper is made symmetric + + if not self.has_object: + achieved_goal = grip_pos.copy() + else: + achieved_goal = np.squeeze(object_pos.copy()) + obs = np.concatenate( + [ + grip_pos, + object_pos.ravel(), + object_rel_pos.ravel(), + gripper_state, + object_rot.ravel(), + object_velp.ravel(), + object_velr.ravel(), + grip_velp, + gripper_vel, + ] + ) + + return { + "observation": obs.copy(), + "achieved_goal": achieved_goal.copy(), + "desired_goal": self.goal.copy(), + } + + def _viewer_setup(self): + body_id = self.sim.model.body_name2id("robot0:gripper_link") + lookat = self.sim.data.body_xpos[body_id] + for idx, value in enumerate(lookat): + self.viewer.cam.lookat[idx] = value + self.viewer.cam.distance = 2.5 + self.viewer.cam.azimuth = 132.0 + self.viewer.cam.elevation = -14.0 + + def _render_callback(self): + # Visualize target. + sites_offset = (self.sim.data.site_xpos - self.sim.model.site_pos).copy() + site_id = self.sim.model.site_name2id("target0") + self.sim.model.site_pos[site_id] = self.goal - sites_offset[0] + self.sim.forward() + + def _reset_sim(self): + self.sim.set_state(self.initial_state) + + # Randomize start position of object. + if self.has_object: + object_xpos = self.initial_gripper_xpos[:2] + while np.linalg.norm(object_xpos - self.initial_gripper_xpos[:2]) < 0.1: + object_xpos = self.initial_gripper_xpos[:2] + self.np_random.uniform( + -self.obj_range, self.obj_range, size=2 + ) + object_qpos = self.sim.data.get_joint_qpos("object0:joint") + assert object_qpos.shape == (7,) + object_qpos[:2] = object_xpos + self.sim.data.set_joint_qpos("object0:joint", object_qpos) + + self.sim.forward() + return True + + def _sample_goal(self): + if self.has_object: + goal = self.initial_gripper_xpos[:3] + self.np_random.uniform( + -self.target_range, self.target_range, size=3 + ) + goal += self.target_offset + goal[2] = self.height_offset + if self.target_in_the_air and self.np_random.uniform() < 0.5: + goal[2] += self.np_random.uniform(0, 0.45) + else: + goal = self.initial_gripper_xpos[:3] + self.np_random.uniform( + -self.target_range, self.target_range, size=3 + ) + return goal.copy() + + def _is_success(self, achieved_goal, desired_goal): + d = goal_distance(achieved_goal, desired_goal) + return (d < self.distance_threshold).astype(np.float32) + + def _env_setup(self, initial_qpos): + for name, value in initial_qpos.items(): + self.sim.data.set_joint_qpos(name, value) + utils.reset_mocap_welds(self.sim) + self.sim.forward() + + # Move end effector into position. + gripper_target = np.array( + [-0.498, 0.005, -0.431 + self.gripper_extra_height] + ) + self.sim.data.get_site_xpos("robot0:grip") + gripper_rotation = np.array([1.0, 0.0, 1.0, 0.0]) + self.sim.data.set_mocap_pos("robot0:mocap", gripper_target) + self.sim.data.set_mocap_quat("robot0:mocap", gripper_rotation) + for _ in range(10): + self.sim.step() + + # Extract information for sampling goals. + self.initial_gripper_xpos = self.sim.data.get_site_xpos("robot0:grip").copy() + if self.has_object: + self.height_offset = self.sim.data.get_site_xpos("object0")[2] + + def render(self, mode="human", width=500, height=500): + return super(FetchEnv, self).render(mode, width, height) diff --git a/gym/envs/robotics/hand/__init__.py b/gym/envs/robotics/hand/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gym/envs/robotics/hand/__pycache__/__init__.cpython-39.pyc b/gym/envs/robotics/hand/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8324789b028a30cf695625217c8c0e0cb703718 Binary files /dev/null and b/gym/envs/robotics/hand/__pycache__/__init__.cpython-39.pyc differ diff --git a/gym/envs/robotics/hand/__pycache__/manipulate.cpython-39.pyc b/gym/envs/robotics/hand/__pycache__/manipulate.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b42996a84f78e2290d1437a263f7d753b278105 Binary files /dev/null and b/gym/envs/robotics/hand/__pycache__/manipulate.cpython-39.pyc differ diff --git a/gym/envs/robotics/hand/__pycache__/manipulate_touch_sensors.cpython-39.pyc b/gym/envs/robotics/hand/__pycache__/manipulate_touch_sensors.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f09d35c023ef19c062bf0e737e9a5a76dbf19508 Binary files /dev/null and b/gym/envs/robotics/hand/__pycache__/manipulate_touch_sensors.cpython-39.pyc differ diff --git a/gym/envs/robotics/hand/__pycache__/reach.cpython-39.pyc b/gym/envs/robotics/hand/__pycache__/reach.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..541361bd3ab9b37dd33ba29e90d510ea5cc9fd67 Binary files /dev/null and b/gym/envs/robotics/hand/__pycache__/reach.cpython-39.pyc differ diff --git a/gym/envs/robotics/hand/manipulate.py b/gym/envs/robotics/hand/manipulate.py new file mode 100644 index 0000000000000000000000000000000000000000..e3eca062d8b96b9a1dc1afbae74de0d8cdcb6fde --- /dev/null +++ b/gym/envs/robotics/hand/manipulate.py @@ -0,0 +1,354 @@ +import os +import numpy as np + +from gym import utils, error +from gym.envs.robotics import rotations, hand_env +from gym.envs.robotics.utils import robot_get_obs + +try: + import mujoco_py +except ImportError as e: + raise error.DependencyNotInstalled( + "{}. (HINT: you need to install mujoco_py, and also perform the setup instructions here: https://github.com/openai/mujoco-py/.)".format( + e + ) + ) + + +def quat_from_angle_and_axis(angle, axis): + assert axis.shape == (3,) + axis /= np.linalg.norm(axis) + quat = np.concatenate([[np.cos(angle / 2.0)], np.sin(angle / 2.0) * axis]) + quat /= np.linalg.norm(quat) + return quat + + +# Ensure we get the path separator correct on windows +MANIPULATE_BLOCK_XML = os.path.join("hand", "manipulate_block.xml") +MANIPULATE_EGG_XML = os.path.join("hand", "manipulate_egg.xml") +MANIPULATE_PEN_XML = os.path.join("hand", "manipulate_pen.xml") + + +class ManipulateEnv(hand_env.HandEnv): + def __init__( + self, + model_path, + target_position, + target_rotation, + target_position_range, + reward_type, + initial_qpos=None, + randomize_initial_position=True, + randomize_initial_rotation=True, + distance_threshold=0.01, + rotation_threshold=0.1, + n_substeps=20, + relative_control=False, + ignore_z_target_rotation=False, + ): + """Initializes a new Hand manipulation environment. + + Args: + model_path (string): path to the environments XML file + target_position (string): the type of target position: + - ignore: target position is fully ignored, i.e. the object can be positioned arbitrarily + - fixed: target position is set to the initial position of the object + - random: target position is fully randomized according to target_position_range + target_rotation (string): the type of target rotation: + - ignore: target rotation is fully ignored, i.e. the object can be rotated arbitrarily + - fixed: target rotation is set to the initial rotation of the object + - xyz: fully randomized target rotation around the X, Y and Z axis + - z: fully randomized target rotation around the Z axis + - parallel: fully randomized target rotation around Z and axis-aligned rotation around X, Y + ignore_z_target_rotation (boolean): whether or not the Z axis of the target rotation is ignored + target_position_range (np.array of shape (3, 2)): range of the target_position randomization + reward_type ('sparse' or 'dense'): the reward type, i.e. sparse or dense + initial_qpos (dict): a dictionary of joint names and values that define the initial configuration + randomize_initial_position (boolean): whether or not to randomize the initial position of the object + randomize_initial_rotation (boolean): whether or not to randomize the initial rotation of the object + distance_threshold (float, in meters): the threshold after which the position of a goal is considered achieved + rotation_threshold (float, in radians): the threshold after which the rotation of a goal is considered achieved + n_substeps (int): number of substeps the simulation runs on every call to step + relative_control (boolean): whether or not the hand is actuated in absolute joint positions or relative to the current state + """ + self.target_position = target_position + self.target_rotation = target_rotation + self.target_position_range = target_position_range + self.parallel_quats = [ + rotations.euler2quat(r) for r in rotations.get_parallel_rotations() + ] + self.randomize_initial_rotation = randomize_initial_rotation + self.randomize_initial_position = randomize_initial_position + self.distance_threshold = distance_threshold + self.rotation_threshold = rotation_threshold + self.reward_type = reward_type + self.ignore_z_target_rotation = ignore_z_target_rotation + + assert self.target_position in ["ignore", "fixed", "random"] + assert self.target_rotation in ["ignore", "fixed", "xyz", "z", "parallel"] + initial_qpos = initial_qpos or {} + + hand_env.HandEnv.__init__( + self, + model_path, + n_substeps=n_substeps, + initial_qpos=initial_qpos, + relative_control=relative_control, + ) + + def _get_achieved_goal(self): + # Object position and rotation. + object_qpos = self.sim.data.get_joint_qpos("object:joint") + assert object_qpos.shape == (7,) + return object_qpos + + def _goal_distance(self, goal_a, goal_b): + assert goal_a.shape == goal_b.shape + assert goal_a.shape[-1] == 7 + + d_pos = np.zeros_like(goal_a[..., 0]) + d_rot = np.zeros_like(goal_b[..., 0]) + if self.target_position != "ignore": + delta_pos = goal_a[..., :3] - goal_b[..., :3] + d_pos = np.linalg.norm(delta_pos, axis=-1) + + if self.target_rotation != "ignore": + quat_a, quat_b = goal_a[..., 3:], goal_b[..., 3:] + + if self.ignore_z_target_rotation: + # Special case: We want to ignore the Z component of the rotation. + # This code here assumes Euler angles with xyz convention. We first transform + # to euler, then set the Z component to be equal between the two, and finally + # transform back into quaternions. + euler_a = rotations.quat2euler(quat_a) + euler_b = rotations.quat2euler(quat_b) + euler_a[2] = euler_b[2] + quat_a = rotations.euler2quat(euler_a) + + # Subtract quaternions and extract angle between them. + quat_diff = rotations.quat_mul(quat_a, rotations.quat_conjugate(quat_b)) + angle_diff = 2 * np.arccos(np.clip(quat_diff[..., 0], -1.0, 1.0)) + d_rot = angle_diff + assert d_pos.shape == d_rot.shape + return d_pos, d_rot + + # GoalEnv methods + # ---------------------------- + + def compute_reward(self, achieved_goal, goal, info): + if self.reward_type == "sparse": + success = self._is_success(achieved_goal, goal).astype(np.float32) + return success - 1.0 + else: + d_pos, d_rot = self._goal_distance(achieved_goal, goal) + # We weigh the difference in position to avoid that `d_pos` (in meters) is completely + # dominated by `d_rot` (in radians). + return -(10.0 * d_pos + d_rot) + + # RobotEnv methods + # ---------------------------- + + def _is_success(self, achieved_goal, desired_goal): + d_pos, d_rot = self._goal_distance(achieved_goal, desired_goal) + achieved_pos = (d_pos < self.distance_threshold).astype(np.float32) + achieved_rot = (d_rot < self.rotation_threshold).astype(np.float32) + achieved_both = achieved_pos * achieved_rot + return achieved_both + + def _env_setup(self, initial_qpos): + for name, value in initial_qpos.items(): + self.sim.data.set_joint_qpos(name, value) + self.sim.forward() + + def _reset_sim(self): + self.sim.set_state(self.initial_state) + self.sim.forward() + + initial_qpos = self.sim.data.get_joint_qpos("object:joint").copy() + initial_pos, initial_quat = initial_qpos[:3], initial_qpos[3:] + assert initial_qpos.shape == (7,) + assert initial_pos.shape == (3,) + assert initial_quat.shape == (4,) + initial_qpos = None + + # Randomization initial rotation. + if self.randomize_initial_rotation: + if self.target_rotation == "z": + angle = self.np_random.uniform(-np.pi, np.pi) + axis = np.array([0.0, 0.0, 1.0]) + offset_quat = quat_from_angle_and_axis(angle, axis) + initial_quat = rotations.quat_mul(initial_quat, offset_quat) + elif self.target_rotation == "parallel": + angle = self.np_random.uniform(-np.pi, np.pi) + axis = np.array([0.0, 0.0, 1.0]) + z_quat = quat_from_angle_and_axis(angle, axis) + parallel_quat = self.parallel_quats[ + self.np_random.randint(len(self.parallel_quats)) + ] + offset_quat = rotations.quat_mul(z_quat, parallel_quat) + initial_quat = rotations.quat_mul(initial_quat, offset_quat) + elif self.target_rotation in ["xyz", "ignore"]: + angle = self.np_random.uniform(-np.pi, np.pi) + axis = self.np_random.uniform(-1.0, 1.0, size=3) + offset_quat = quat_from_angle_and_axis(angle, axis) + initial_quat = rotations.quat_mul(initial_quat, offset_quat) + elif self.target_rotation == "fixed": + pass + else: + raise error.Error( + 'Unknown target_rotation option "{}".'.format(self.target_rotation) + ) + + # Randomize initial position. + if self.randomize_initial_position: + if self.target_position != "fixed": + initial_pos += self.np_random.normal(size=3, scale=0.005) + + initial_quat /= np.linalg.norm(initial_quat) + initial_qpos = np.concatenate([initial_pos, initial_quat]) + self.sim.data.set_joint_qpos("object:joint", initial_qpos) + + def is_on_palm(): + self.sim.forward() + cube_middle_idx = self.sim.model.site_name2id("object:center") + cube_middle_pos = self.sim.data.site_xpos[cube_middle_idx] + is_on_palm = cube_middle_pos[2] > 0.04 + return is_on_palm + + # Run the simulation for a bunch of timesteps to let everything settle in. + for _ in range(10): + self._set_action(np.zeros(20)) + try: + self.sim.step() + except mujoco_py.MujocoException: + return False + return is_on_palm() + + def _sample_goal(self): + # Select a goal for the object position. + target_pos = None + if self.target_position == "random": + assert self.target_position_range.shape == (3, 2) + offset = self.np_random.uniform( + self.target_position_range[:, 0], self.target_position_range[:, 1] + ) + assert offset.shape == (3,) + target_pos = self.sim.data.get_joint_qpos("object:joint")[:3] + offset + elif self.target_position in ["ignore", "fixed"]: + target_pos = self.sim.data.get_joint_qpos("object:joint")[:3] + else: + raise error.Error( + 'Unknown target_position option "{}".'.format(self.target_position) + ) + assert target_pos is not None + assert target_pos.shape == (3,) + + # Select a goal for the object rotation. + target_quat = None + if self.target_rotation == "z": + angle = self.np_random.uniform(-np.pi, np.pi) + axis = np.array([0.0, 0.0, 1.0]) + target_quat = quat_from_angle_and_axis(angle, axis) + elif self.target_rotation == "parallel": + angle = self.np_random.uniform(-np.pi, np.pi) + axis = np.array([0.0, 0.0, 1.0]) + target_quat = quat_from_angle_and_axis(angle, axis) + parallel_quat = self.parallel_quats[ + self.np_random.randint(len(self.parallel_quats)) + ] + target_quat = rotations.quat_mul(target_quat, parallel_quat) + elif self.target_rotation == "xyz": + angle = self.np_random.uniform(-np.pi, np.pi) + axis = self.np_random.uniform(-1.0, 1.0, size=3) + target_quat = quat_from_angle_and_axis(angle, axis) + elif self.target_rotation in ["ignore", "fixed"]: + target_quat = self.sim.data.get_joint_qpos("object:joint") + else: + raise error.Error( + 'Unknown target_rotation option "{}".'.format(self.target_rotation) + ) + assert target_quat is not None + assert target_quat.shape == (4,) + + target_quat /= np.linalg.norm(target_quat) # normalized quaternion + goal = np.concatenate([target_pos, target_quat]) + return goal + + def _render_callback(self): + # Assign current state to target object but offset a bit so that the actual object + # is not obscured. + goal = self.goal.copy() + assert goal.shape == (7,) + if self.target_position == "ignore": + # Move the object to the side since we do not care about it's position. + goal[0] += 0.15 + self.sim.data.set_joint_qpos("target:joint", goal) + self.sim.data.set_joint_qvel("target:joint", np.zeros(6)) + + if "object_hidden" in self.sim.model.geom_names: + hidden_id = self.sim.model.geom_name2id("object_hidden") + self.sim.model.geom_rgba[hidden_id, 3] = 1.0 + self.sim.forward() + + def _get_obs(self): + robot_qpos, robot_qvel = robot_get_obs(self.sim) + object_qvel = self.sim.data.get_joint_qvel("object:joint") + achieved_goal = ( + self._get_achieved_goal().ravel() + ) # this contains the object position + rotation + observation = np.concatenate( + [robot_qpos, robot_qvel, object_qvel, achieved_goal] + ) + return { + "observation": observation.copy(), + "achieved_goal": achieved_goal.copy(), + "desired_goal": self.goal.ravel().copy(), + } + + +class HandBlockEnv(ManipulateEnv, utils.EzPickle): + def __init__( + self, target_position="random", target_rotation="xyz", reward_type="sparse" + ): + utils.EzPickle.__init__(self, target_position, target_rotation, reward_type) + ManipulateEnv.__init__( + self, + model_path=MANIPULATE_BLOCK_XML, + target_position=target_position, + target_rotation=target_rotation, + target_position_range=np.array([(-0.04, 0.04), (-0.06, 0.02), (0.0, 0.06)]), + reward_type=reward_type, + ) + + +class HandEggEnv(ManipulateEnv, utils.EzPickle): + def __init__( + self, target_position="random", target_rotation="xyz", reward_type="sparse" + ): + utils.EzPickle.__init__(self, target_position, target_rotation, reward_type) + ManipulateEnv.__init__( + self, + model_path=MANIPULATE_EGG_XML, + target_position=target_position, + target_rotation=target_rotation, + target_position_range=np.array([(-0.04, 0.04), (-0.06, 0.02), (0.0, 0.06)]), + reward_type=reward_type, + ) + + +class HandPenEnv(ManipulateEnv, utils.EzPickle): + def __init__( + self, target_position="random", target_rotation="xyz", reward_type="sparse" + ): + utils.EzPickle.__init__(self, target_position, target_rotation, reward_type) + ManipulateEnv.__init__( + self, + model_path=MANIPULATE_PEN_XML, + target_position=target_position, + target_rotation=target_rotation, + target_position_range=np.array([(-0.04, 0.04), (-0.06, 0.02), (0.0, 0.06)]), + randomize_initial_rotation=False, + reward_type=reward_type, + ignore_z_target_rotation=True, + distance_threshold=0.05, + ) diff --git a/gym/envs/robotics/hand/manipulate_touch_sensors.py b/gym/envs/robotics/hand/manipulate_touch_sensors.py new file mode 100644 index 0000000000000000000000000000000000000000..63d49c95a003deb7c945fdde8669af543751ca8b --- /dev/null +++ b/gym/envs/robotics/hand/manipulate_touch_sensors.py @@ -0,0 +1,207 @@ +import os +import numpy as np + +from gym import utils, error, spaces +from gym.envs.robotics.hand import manipulate + +# Ensure we get the path separator correct on windows +MANIPULATE_BLOCK_XML = os.path.join("hand", "manipulate_block_touch_sensors.xml") +MANIPULATE_EGG_XML = os.path.join("hand", "manipulate_egg_touch_sensors.xml") +MANIPULATE_PEN_XML = os.path.join("hand", "manipulate_pen_touch_sensors.xml") + + +class ManipulateTouchSensorsEnv(manipulate.ManipulateEnv): + def __init__( + self, + model_path, + target_position, + target_rotation, + target_position_range, + reward_type, + initial_qpos={}, + randomize_initial_position=True, + randomize_initial_rotation=True, + distance_threshold=0.01, + rotation_threshold=0.1, + n_substeps=20, + relative_control=False, + ignore_z_target_rotation=False, + touch_visualisation="on_touch", + touch_get_obs="sensordata", + ): + """Initializes a new Hand manipulation environment with touch sensors. + + Args: + touch_visualisation (string): how touch sensor sites are visualised + - "on_touch": shows touch sensor sites only when touch values > 0 + - "always": always shows touch sensor sites + - "off" or else: does not show touch sensor sites + touch_get_obs (string): touch sensor readings + - "boolean": returns 1 if touch sensor reading != 0.0 else 0 + - "sensordata": returns original touch sensor readings from self.sim.data.sensordata[id] + - "log": returns log(x+1) touch sensor readings from self.sim.data.sensordata[id] + - "off" or else: does not add touch sensor readings to the observation + + """ + self.touch_visualisation = touch_visualisation + self.touch_get_obs = touch_get_obs + self._touch_sensor_id_site_id = [] + self._touch_sensor_id = [] + self.touch_color = [1, 0, 0, 0.5] + self.notouch_color = [0, 0.5, 0, 0.2] + + manipulate.ManipulateEnv.__init__( + self, + model_path, + target_position, + target_rotation, + target_position_range, + reward_type, + initial_qpos=initial_qpos, + randomize_initial_position=randomize_initial_position, + randomize_initial_rotation=randomize_initial_rotation, + distance_threshold=distance_threshold, + rotation_threshold=rotation_threshold, + n_substeps=n_substeps, + relative_control=relative_control, + ignore_z_target_rotation=ignore_z_target_rotation, + ) + + for ( + k, + v, + ) in ( + self.sim.model._sensor_name2id.items() + ): # get touch sensor site names and their ids + if "robot0:TS_" in k: + self._touch_sensor_id_site_id.append( + ( + v, + self.sim.model._site_name2id[ + k.replace("robot0:TS_", "robot0:T_") + ], + ) + ) + self._touch_sensor_id.append(v) + + if self.touch_visualisation == "off": # set touch sensors rgba values + for _, site_id in self._touch_sensor_id_site_id: + self.sim.model.site_rgba[site_id][3] = 0.0 + elif self.touch_visualisation == "always": + pass + + obs = self._get_obs() + self.observation_space = spaces.Dict( + dict( + desired_goal=spaces.Box( + -np.inf, np.inf, shape=obs["achieved_goal"].shape, dtype="float32" + ), + achieved_goal=spaces.Box( + -np.inf, np.inf, shape=obs["achieved_goal"].shape, dtype="float32" + ), + observation=spaces.Box( + -np.inf, np.inf, shape=obs["observation"].shape, dtype="float32" + ), + ) + ) + + def _render_callback(self): + super(ManipulateTouchSensorsEnv, self)._render_callback() + if self.touch_visualisation == "on_touch": + for touch_sensor_id, site_id in self._touch_sensor_id_site_id: + if self.sim.data.sensordata[touch_sensor_id] != 0.0: + self.sim.model.site_rgba[site_id] = self.touch_color + else: + self.sim.model.site_rgba[site_id] = self.notouch_color + + def _get_obs(self): + robot_qpos, robot_qvel = manipulate.robot_get_obs(self.sim) + object_qvel = self.sim.data.get_joint_qvel("object:joint") + achieved_goal = ( + self._get_achieved_goal().ravel() + ) # this contains the object position + rotation + touch_values = [] # get touch sensor readings. if there is one, set value to 1 + if self.touch_get_obs == "sensordata": + touch_values = self.sim.data.sensordata[self._touch_sensor_id] + elif self.touch_get_obs == "boolean": + touch_values = self.sim.data.sensordata[self._touch_sensor_id] > 0.0 + elif self.touch_get_obs == "log": + touch_values = np.log(self.sim.data.sensordata[self._touch_sensor_id] + 1.0) + observation = np.concatenate( + [robot_qpos, robot_qvel, object_qvel, touch_values, achieved_goal] + ) + + return { + "observation": observation.copy(), + "achieved_goal": achieved_goal.copy(), + "desired_goal": self.goal.ravel().copy(), + } + + +class HandBlockTouchSensorsEnv(ManipulateTouchSensorsEnv, utils.EzPickle): + def __init__( + self, + target_position="random", + target_rotation="xyz", + touch_get_obs="sensordata", + reward_type="sparse", + ): + utils.EzPickle.__init__( + self, target_position, target_rotation, touch_get_obs, reward_type + ) + ManipulateTouchSensorsEnv.__init__( + self, + model_path=MANIPULATE_BLOCK_XML, + touch_get_obs=touch_get_obs, + target_rotation=target_rotation, + target_position=target_position, + target_position_range=np.array([(-0.04, 0.04), (-0.06, 0.02), (0.0, 0.06)]), + reward_type=reward_type, + ) + + +class HandEggTouchSensorsEnv(ManipulateTouchSensorsEnv, utils.EzPickle): + def __init__( + self, + target_position="random", + target_rotation="xyz", + touch_get_obs="sensordata", + reward_type="sparse", + ): + utils.EzPickle.__init__( + self, target_position, target_rotation, touch_get_obs, reward_type + ) + ManipulateTouchSensorsEnv.__init__( + self, + model_path=MANIPULATE_EGG_XML, + touch_get_obs=touch_get_obs, + target_rotation=target_rotation, + target_position=target_position, + target_position_range=np.array([(-0.04, 0.04), (-0.06, 0.02), (0.0, 0.06)]), + reward_type=reward_type, + ) + + +class HandPenTouchSensorsEnv(ManipulateTouchSensorsEnv, utils.EzPickle): + def __init__( + self, + target_position="random", + target_rotation="xyz", + touch_get_obs="sensordata", + reward_type="sparse", + ): + utils.EzPickle.__init__( + self, target_position, target_rotation, touch_get_obs, reward_type + ) + ManipulateTouchSensorsEnv.__init__( + self, + model_path=MANIPULATE_PEN_XML, + touch_get_obs=touch_get_obs, + target_rotation=target_rotation, + target_position=target_position, + target_position_range=np.array([(-0.04, 0.04), (-0.06, 0.02), (0.0, 0.06)]), + randomize_initial_rotation=False, + reward_type=reward_type, + ignore_z_target_rotation=True, + distance_threshold=0.05, + ) diff --git a/gym/envs/robotics/hand/reach.py b/gym/envs/robotics/hand/reach.py new file mode 100644 index 0000000000000000000000000000000000000000..f09e1673b04b6dbff1a226af12493f35e0f0db39 --- /dev/null +++ b/gym/envs/robotics/hand/reach.py @@ -0,0 +1,161 @@ +import os +import numpy as np + +from gym import utils +from gym.envs.robotics import hand_env +from gym.envs.robotics.utils import robot_get_obs + + +FINGERTIP_SITE_NAMES = [ + "robot0:S_fftip", + "robot0:S_mftip", + "robot0:S_rftip", + "robot0:S_lftip", + "robot0:S_thtip", +] + + +DEFAULT_INITIAL_QPOS = { + "robot0:WRJ1": -0.16514339750464327, + "robot0:WRJ0": -0.31973286565062153, + "robot0:FFJ3": 0.14340512546557435, + "robot0:FFJ2": 0.32028208333591573, + "robot0:FFJ1": 0.7126053607727917, + "robot0:FFJ0": 0.6705281001412586, + "robot0:MFJ3": 0.000246444303701037, + "robot0:MFJ2": 0.3152655251085491, + "robot0:MFJ1": 0.7659800313729842, + "robot0:MFJ0": 0.7323156897425923, + "robot0:RFJ3": 0.00038520700007378114, + "robot0:RFJ2": 0.36743546201985233, + "robot0:RFJ1": 0.7119514095008576, + "robot0:RFJ0": 0.6699446327514138, + "robot0:LFJ4": 0.0525442258033891, + "robot0:LFJ3": -0.13615534724474673, + "robot0:LFJ2": 0.39872030433433003, + "robot0:LFJ1": 0.7415570009679252, + "robot0:LFJ0": 0.704096378652974, + "robot0:THJ4": 0.003673823825070126, + "robot0:THJ3": 0.5506291436028695, + "robot0:THJ2": -0.014515151997119306, + "robot0:THJ1": -0.0015229223564485414, + "robot0:THJ0": -0.7894883021600622, +} + + +# Ensure we get the path separator correct on windows +MODEL_XML_PATH = os.path.join("hand", "reach.xml") + + +def goal_distance(goal_a, goal_b): + assert goal_a.shape == goal_b.shape + return np.linalg.norm(goal_a - goal_b, axis=-1) + + +class HandReachEnv(hand_env.HandEnv, utils.EzPickle): + def __init__( + self, + distance_threshold=0.01, + n_substeps=20, + relative_control=False, + initial_qpos=DEFAULT_INITIAL_QPOS, + reward_type="sparse", + ): + utils.EzPickle.__init__(**locals()) + self.distance_threshold = distance_threshold + self.reward_type = reward_type + + hand_env.HandEnv.__init__( + self, + MODEL_XML_PATH, + n_substeps=n_substeps, + initial_qpos=initial_qpos, + relative_control=relative_control, + ) + + def _get_achieved_goal(self): + goal = [self.sim.data.get_site_xpos(name) for name in FINGERTIP_SITE_NAMES] + return np.array(goal).flatten() + + # GoalEnv methods + # ---------------------------- + + def compute_reward(self, achieved_goal, goal, info): + d = goal_distance(achieved_goal, goal) + if self.reward_type == "sparse": + return -(d > self.distance_threshold).astype(np.float32) + else: + return -d + + # RobotEnv methods + # ---------------------------- + + def _env_setup(self, initial_qpos): + for name, value in initial_qpos.items(): + self.sim.data.set_joint_qpos(name, value) + self.sim.forward() + + self.initial_goal = self._get_achieved_goal().copy() + self.palm_xpos = self.sim.data.body_xpos[ + self.sim.model.body_name2id("robot0:palm") + ].copy() + + def _get_obs(self): + robot_qpos, robot_qvel = robot_get_obs(self.sim) + achieved_goal = self._get_achieved_goal().ravel() + observation = np.concatenate([robot_qpos, robot_qvel, achieved_goal]) + return { + "observation": observation.copy(), + "achieved_goal": achieved_goal.copy(), + "desired_goal": self.goal.copy(), + } + + def _sample_goal(self): + thumb_name = "robot0:S_thtip" + finger_names = [name for name in FINGERTIP_SITE_NAMES if name != thumb_name] + finger_name = self.np_random.choice(finger_names) + + thumb_idx = FINGERTIP_SITE_NAMES.index(thumb_name) + finger_idx = FINGERTIP_SITE_NAMES.index(finger_name) + assert thumb_idx != finger_idx + + # Pick a meeting point above the hand. + meeting_pos = self.palm_xpos + np.array([0.0, -0.09, 0.05]) + meeting_pos += self.np_random.normal(scale=0.005, size=meeting_pos.shape) + + # Slightly move meeting goal towards the respective finger to avoid that they + # overlap. + goal = self.initial_goal.copy().reshape(-1, 3) + for idx in [thumb_idx, finger_idx]: + offset_direction = meeting_pos - goal[idx] + offset_direction /= np.linalg.norm(offset_direction) + goal[idx] = meeting_pos - 0.005 * offset_direction + + if self.np_random.uniform() < 0.1: + # With some probability, ask all fingers to move back to the origin. + # This avoids that the thumb constantly stays near the goal position already. + goal = self.initial_goal.copy() + return goal.flatten() + + def _is_success(self, achieved_goal, desired_goal): + d = goal_distance(achieved_goal, desired_goal) + return (d < self.distance_threshold).astype(np.float32) + + def _render_callback(self): + # Visualize targets. + sites_offset = (self.sim.data.site_xpos - self.sim.model.site_pos).copy() + goal = self.goal.reshape(5, 3) + for finger_idx in range(5): + site_name = "target{}".format(finger_idx) + site_id = self.sim.model.site_name2id(site_name) + self.sim.model.site_pos[site_id] = goal[finger_idx] - sites_offset[site_id] + + # Visualize finger positions. + achieved_goal = self._get_achieved_goal().reshape(5, 3) + for finger_idx in range(5): + site_name = "finger{}".format(finger_idx) + site_id = self.sim.model.site_name2id(site_name) + self.sim.model.site_pos[site_id] = ( + achieved_goal[finger_idx] - sites_offset[site_id] + ) + self.sim.forward() diff --git a/gym/envs/robotics/hand_env.py b/gym/envs/robotics/hand_env.py new file mode 100644 index 0000000000000000000000000000000000000000..aaa0fec1d51fa097724f3e56a2738eb427e3f668 --- /dev/null +++ b/gym/envs/robotics/hand_env.py @@ -0,0 +1,60 @@ +import os +import copy +import numpy as np + +import gym +from gym import error, spaces +from gym.utils import seeding +from gym.envs.robotics import robot_env + + +class HandEnv(robot_env.RobotEnv): + def __init__(self, model_path, n_substeps, initial_qpos, relative_control): + self.relative_control = relative_control + + super(HandEnv, self).__init__( + model_path=model_path, + n_substeps=n_substeps, + n_actions=20, + initial_qpos=initial_qpos, + ) + + # RobotEnv methods + # ---------------------------- + + def _set_action(self, action): + assert action.shape == (20,) + + ctrlrange = self.sim.model.actuator_ctrlrange + actuation_range = (ctrlrange[:, 1] - ctrlrange[:, 0]) / 2.0 + if self.relative_control: + actuation_center = np.zeros_like(action) + for i in range(self.sim.data.ctrl.shape[0]): + actuation_center[i] = self.sim.data.get_joint_qpos( + self.sim.model.actuator_names[i].replace(":A_", ":") + ) + for joint_name in ["FF", "MF", "RF", "LF"]: + act_idx = self.sim.model.actuator_name2id( + "robot0:A_{}J1".format(joint_name) + ) + actuation_center[act_idx] += self.sim.data.get_joint_qpos( + "robot0:{}J0".format(joint_name) + ) + else: + actuation_center = (ctrlrange[:, 1] + ctrlrange[:, 0]) / 2.0 + self.sim.data.ctrl[:] = actuation_center + action * actuation_range + self.sim.data.ctrl[:] = np.clip( + self.sim.data.ctrl, ctrlrange[:, 0], ctrlrange[:, 1] + ) + + def _viewer_setup(self): + body_id = self.sim.model.body_name2id("robot0:palm") + lookat = self.sim.data.body_xpos[body_id] + for idx, value in enumerate(lookat): + self.viewer.cam.lookat[idx] = value + self.viewer.cam.distance = 0.5 + self.viewer.cam.azimuth = 55.0 + self.viewer.cam.elevation = -25.0 + + def render(self, mode="human", width=500, height=500): + return super(HandEnv, self).render(mode, width, height) diff --git a/gym/envs/robotics/robot_env.py b/gym/envs/robotics/robot_env.py new file mode 100644 index 0000000000000000000000000000000000000000..1fe6ca653e8d37d42abd01ecae6fc46548b3381e --- /dev/null +++ b/gym/envs/robotics/robot_env.py @@ -0,0 +1,179 @@ +import os +import copy +import numpy as np + +import gym +from gym import error, spaces +from gym.utils import seeding + +try: + import mujoco_py +except ImportError as e: + raise error.DependencyNotInstalled( + "{}. (HINT: you need to install mujoco_py, and also perform the setup instructions here: https://github.com/openai/mujoco-py/.)".format( + e + ) + ) + +DEFAULT_SIZE = 500 + + +class RobotEnv(gym.GoalEnv): + def __init__(self, model_path, initial_qpos, n_actions, n_substeps): + if model_path.startswith("/"): + fullpath = model_path + else: + fullpath = os.path.join(os.path.dirname(__file__), "assets", model_path) + if not os.path.exists(fullpath): + raise IOError("File {} does not exist".format(fullpath)) + + model = mujoco_py.load_model_from_path(fullpath) + self.sim = mujoco_py.MjSim(model, nsubsteps=n_substeps) + self.viewer = None + self._viewers = {} + + self.metadata = { + "render.modes": ["human", "rgb_array"], + "video.frames_per_second": int(np.round(1.0 / self.dt)), + } + + self.seed() + self._env_setup(initial_qpos=initial_qpos) + self.initial_state = copy.deepcopy(self.sim.get_state()) + + self.goal = self._sample_goal() + obs = self._get_obs() + self.action_space = spaces.Box(-1.0, 1.0, shape=(n_actions,), dtype="float32") + self.observation_space = spaces.Dict( + dict( + desired_goal=spaces.Box( + -np.inf, np.inf, shape=obs["achieved_goal"].shape, dtype="float32" + ), + achieved_goal=spaces.Box( + -np.inf, np.inf, shape=obs["achieved_goal"].shape, dtype="float32" + ), + observation=spaces.Box( + -np.inf, np.inf, shape=obs["observation"].shape, dtype="float32" + ), + ) + ) + + @property + def dt(self): + return self.sim.model.opt.timestep * self.sim.nsubsteps + + # Env methods + # ---------------------------- + + def seed(self, seed=None): + self.np_random, seed = seeding.np_random(seed) + return [seed] + + def step(self, action): + action = np.clip(action, self.action_space.low, self.action_space.high) + self._set_action(action) + self.sim.step() + self._step_callback() + obs = self._get_obs() + + done = False + info = { + "is_success": self._is_success(obs["achieved_goal"], self.goal), + } + reward = self.compute_reward(obs["achieved_goal"], self.goal, info) + return obs, reward, done, info + + def reset(self): + # Attempt to reset the simulator. Since we randomize initial conditions, it + # is possible to get into a state with numerical issues (e.g. due to penetration or + # Gimbel lock) or we may not achieve an initial condition (e.g. an object is within the hand). + # In this case, we just keep randomizing until we eventually achieve a valid initial + # configuration. + super(RobotEnv, self).reset() + did_reset_sim = False + while not did_reset_sim: + did_reset_sim = self._reset_sim() + self.goal = self._sample_goal().copy() + obs = self._get_obs() + return obs + + def close(self): + if self.viewer is not None: + # self.viewer.finish() + self.viewer = None + self._viewers = {} + + def render(self, mode="human", width=DEFAULT_SIZE, height=DEFAULT_SIZE): + self._render_callback() + if mode == "rgb_array": + self._get_viewer(mode).render(width, height) + # window size used for old mujoco-py: + data = self._get_viewer(mode).read_pixels(width, height, depth=False) + # original image is upside-down, so flip it + return data[::-1, :, :] + elif mode == "human": + self._get_viewer(mode).render() + + def _get_viewer(self, mode): + self.viewer = self._viewers.get(mode) + if self.viewer is None: + if mode == "human": + self.viewer = mujoco_py.MjViewer(self.sim) + elif mode == "rgb_array": + self.viewer = mujoco_py.MjRenderContextOffscreen(self.sim, device_id=-1) + self._viewer_setup() + self._viewers[mode] = self.viewer + return self.viewer + + # Extension methods + # ---------------------------- + + def _reset_sim(self): + """Resets a simulation and indicates whether or not it was successful. + If a reset was unsuccessful (e.g. if a randomized state caused an error in the + simulation), this method should indicate such a failure by returning False. + In such a case, this method will be called again to attempt a the reset again. + """ + self.sim.set_state(self.initial_state) + self.sim.forward() + return True + + def _get_obs(self): + """Returns the observation.""" + raise NotImplementedError() + + def _set_action(self, action): + """Applies the given action to the simulation.""" + raise NotImplementedError() + + def _is_success(self, achieved_goal, desired_goal): + """Indicates whether or not the achieved goal successfully achieved the desired goal.""" + raise NotImplementedError() + + def _sample_goal(self): + """Samples a new goal and returns it.""" + raise NotImplementedError() + + def _env_setup(self, initial_qpos): + """Initial configuration of the environment. Can be used to configure initial state + and extract information from the simulation. + """ + pass + + def _viewer_setup(self): + """Initial configuration of the viewer. Can be used to set the camera position, + for example. + """ + pass + + def _render_callback(self): + """A custom callback that is called before rendering. Can be used + to implement custom visualizations. + """ + pass + + def _step_callback(self): + """A custom callback that is called after stepping the simulation. Can be used + to enforce additional constraints on the simulation state. + """ + pass diff --git a/gym/envs/robotics/rotations.py b/gym/envs/robotics/rotations.py new file mode 100644 index 0000000000000000000000000000000000000000..fe241a10885716ab7caaf4a5ecaaa690f416ed54 --- /dev/null +++ b/gym/envs/robotics/rotations.py @@ -0,0 +1,387 @@ +# Copyright (c) 2009-2017, Matthew Brett and Christoph Gohlke +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# Many methods borrow heavily or entirely from transforms3d: +# https://github.com/matthew-brett/transforms3d +# They have mostly been modified to support batched operations. + +import numpy as np +import itertools + +""" +Rotations +========= + +Note: these have caused many subtle bugs in the past. +Be careful while updating these methods and while using them in clever ways. + +See MuJoCo documentation here: http://mujoco.org/book/modeling.html#COrientation + +Conventions +----------- + - All functions accept batches as well as individual rotations + - All rotation conventions match respective MuJoCo defaults + - All angles are in radians + - Matricies follow LR convention + - Euler Angles are all relative with 'xyz' axes ordering + - See specific representation for more information + +Representations +--------------- + +Euler + There are many euler angle frames -- here we will strive to use the default + in MuJoCo, which is eulerseq='xyz'. + This frame is a relative rotating frame, about x, y, and z axes in order. + Relative rotating means that after we rotate about x, then we use the + new (rotated) y, and the same for z. + +Quaternions + These are defined in terms of rotation (angle) about a unit vector (x, y, z) + We use the following convention: + q0 = cos(angle / 2) + q1 = sin(angle / 2) * x + q2 = sin(angle / 2) * y + q3 = sin(angle / 2) * z + This is also sometimes called qw, qx, qy, qz. + Note that quaternions are ambiguous, because we can represent a rotation by + angle about vector and -angle about vector <-x, -y, -z>. + To choose between these, we pick "first nonzero positive", where we + make the first nonzero element of the quaternion positive. + This can result in mismatches if you're converting an quaternion that is not + "first nonzero positive" to a different representation and back. + +Axis Angle + (Not currently implemented) + These are very straightforward. Rotation is angle about a unit vector. + +XY Axes + (Not currently implemented) + We are given x axis and y axis, and z axis is cross product of x and y. + +Z Axis + This is NOT RECOMMENDED. Defines a unit vector for the Z axis, + but rotation about this axis is not well defined. + Instead pick a fixed reference direction for another axis (e.g. X) + and calculate the other (e.g. Y = Z cross-product X), + then use XY Axes rotation instead. + +SO3 + (Not currently implemented) + While not supported by MuJoCo, this representation has a lot of nice features. + We expect to add support for these in the future. + +TODO / Missing +-------------- + - Rotation integration or derivatives (e.g. velocity conversions) + - More representations (SO3, etc) + - Random sampling (e.g. sample uniform random rotation) + - Performance benchmarks/measurements + - (Maybe) define everything as to/from matricies, for simplicity +""" + +# For testing whether a number is close to zero +_FLOAT_EPS = np.finfo(np.float64).eps +_EPS4 = _FLOAT_EPS * 4.0 + + +def euler2mat(euler): + """Convert Euler Angles to Rotation Matrix. See rotation.py for notes""" + euler = np.asarray(euler, dtype=np.float64) + assert euler.shape[-1] == 3, "Invalid shaped euler {}".format(euler) + + ai, aj, ak = -euler[..., 2], -euler[..., 1], -euler[..., 0] + si, sj, sk = np.sin(ai), np.sin(aj), np.sin(ak) + ci, cj, ck = np.cos(ai), np.cos(aj), np.cos(ak) + cc, cs = ci * ck, ci * sk + sc, ss = si * ck, si * sk + + mat = np.empty(euler.shape[:-1] + (3, 3), dtype=np.float64) + mat[..., 2, 2] = cj * ck + mat[..., 2, 1] = sj * sc - cs + mat[..., 2, 0] = sj * cc + ss + mat[..., 1, 2] = cj * sk + mat[..., 1, 1] = sj * ss + cc + mat[..., 1, 0] = sj * cs - sc + mat[..., 0, 2] = -sj + mat[..., 0, 1] = cj * si + mat[..., 0, 0] = cj * ci + return mat + + +def euler2quat(euler): + """Convert Euler Angles to Quaternions. See rotation.py for notes""" + euler = np.asarray(euler, dtype=np.float64) + assert euler.shape[-1] == 3, "Invalid shape euler {}".format(euler) + + ai, aj, ak = euler[..., 2] / 2, -euler[..., 1] / 2, euler[..., 0] / 2 + si, sj, sk = np.sin(ai), np.sin(aj), np.sin(ak) + ci, cj, ck = np.cos(ai), np.cos(aj), np.cos(ak) + cc, cs = ci * ck, ci * sk + sc, ss = si * ck, si * sk + + quat = np.empty(euler.shape[:-1] + (4,), dtype=np.float64) + quat[..., 0] = cj * cc + sj * ss + quat[..., 3] = cj * sc - sj * cs + quat[..., 2] = -(cj * ss + sj * cc) + quat[..., 1] = cj * cs - sj * sc + return quat + + +def mat2euler(mat): + """Convert Rotation Matrix to Euler Angles. See rotation.py for notes""" + mat = np.asarray(mat, dtype=np.float64) + assert mat.shape[-2:] == (3, 3), "Invalid shape matrix {}".format(mat) + + cy = np.sqrt(mat[..., 2, 2] * mat[..., 2, 2] + mat[..., 1, 2] * mat[..., 1, 2]) + condition = cy > _EPS4 + euler = np.empty(mat.shape[:-1], dtype=np.float64) + euler[..., 2] = np.where( + condition, + -np.arctan2(mat[..., 0, 1], mat[..., 0, 0]), + -np.arctan2(-mat[..., 1, 0], mat[..., 1, 1]), + ) + euler[..., 1] = np.where( + condition, -np.arctan2(-mat[..., 0, 2], cy), -np.arctan2(-mat[..., 0, 2], cy) + ) + euler[..., 0] = np.where( + condition, -np.arctan2(mat[..., 1, 2], mat[..., 2, 2]), 0.0 + ) + return euler + + +def mat2quat(mat): + """Convert Rotation Matrix to Quaternion. See rotation.py for notes""" + mat = np.asarray(mat, dtype=np.float64) + assert mat.shape[-2:] == (3, 3), "Invalid shape matrix {}".format(mat) + + Qxx, Qyx, Qzx = mat[..., 0, 0], mat[..., 0, 1], mat[..., 0, 2] + Qxy, Qyy, Qzy = mat[..., 1, 0], mat[..., 1, 1], mat[..., 1, 2] + Qxz, Qyz, Qzz = mat[..., 2, 0], mat[..., 2, 1], mat[..., 2, 2] + # Fill only lower half of symmetric matrix + K = np.zeros(mat.shape[:-2] + (4, 4), dtype=np.float64) + K[..., 0, 0] = Qxx - Qyy - Qzz + K[..., 1, 0] = Qyx + Qxy + K[..., 1, 1] = Qyy - Qxx - Qzz + K[..., 2, 0] = Qzx + Qxz + K[..., 2, 1] = Qzy + Qyz + K[..., 2, 2] = Qzz - Qxx - Qyy + K[..., 3, 0] = Qyz - Qzy + K[..., 3, 1] = Qzx - Qxz + K[..., 3, 2] = Qxy - Qyx + K[..., 3, 3] = Qxx + Qyy + Qzz + K /= 3.0 + # TODO: vectorize this -- probably could be made faster + q = np.empty(K.shape[:-2] + (4,)) + it = np.nditer(q[..., 0], flags=["multi_index"]) + while not it.finished: + # Use Hermitian eigenvectors, values for speed + vals, vecs = np.linalg.eigh(K[it.multi_index]) + # Select largest eigenvector, reorder to w,x,y,z quaternion + q[it.multi_index] = vecs[[3, 0, 1, 2], np.argmax(vals)] + # Prefer quaternion with positive w + # (q * -1 corresponds to same rotation as q) + if q[it.multi_index][0] < 0: + q[it.multi_index] *= -1 + it.iternext() + return q + + +def quat2euler(quat): + """Convert Quaternion to Euler Angles. See rotation.py for notes""" + return mat2euler(quat2mat(quat)) + + +def subtract_euler(e1, e2): + assert e1.shape == e2.shape + assert e1.shape[-1] == 3 + q1 = euler2quat(e1) + q2 = euler2quat(e2) + q_diff = quat_mul(q1, quat_conjugate(q2)) + return quat2euler(q_diff) + + +def quat2mat(quat): + """Convert Quaternion to Euler Angles. See rotation.py for notes""" + quat = np.asarray(quat, dtype=np.float64) + assert quat.shape[-1] == 4, "Invalid shape quat {}".format(quat) + + w, x, y, z = quat[..., 0], quat[..., 1], quat[..., 2], quat[..., 3] + Nq = np.sum(quat * quat, axis=-1) + s = 2.0 / Nq + X, Y, Z = x * s, y * s, z * s + wX, wY, wZ = w * X, w * Y, w * Z + xX, xY, xZ = x * X, x * Y, x * Z + yY, yZ, zZ = y * Y, y * Z, z * Z + + mat = np.empty(quat.shape[:-1] + (3, 3), dtype=np.float64) + mat[..., 0, 0] = 1.0 - (yY + zZ) + mat[..., 0, 1] = xY - wZ + mat[..., 0, 2] = xZ + wY + mat[..., 1, 0] = xY + wZ + mat[..., 1, 1] = 1.0 - (xX + zZ) + mat[..., 1, 2] = yZ - wX + mat[..., 2, 0] = xZ - wY + mat[..., 2, 1] = yZ + wX + mat[..., 2, 2] = 1.0 - (xX + yY) + return np.where((Nq > _FLOAT_EPS)[..., np.newaxis, np.newaxis], mat, np.eye(3)) + + +def quat_conjugate(q): + inv_q = -q + inv_q[..., 0] *= -1 + return inv_q + + +def quat_mul(q0, q1): + assert q0.shape == q1.shape + assert q0.shape[-1] == 4 + assert q1.shape[-1] == 4 + + w0 = q0[..., 0] + x0 = q0[..., 1] + y0 = q0[..., 2] + z0 = q0[..., 3] + + w1 = q1[..., 0] + x1 = q1[..., 1] + y1 = q1[..., 2] + z1 = q1[..., 3] + + w = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1 + x = w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1 + y = w0 * y1 + y0 * w1 + z0 * x1 - x0 * z1 + z = w0 * z1 + z0 * w1 + x0 * y1 - y0 * x1 + q = np.array([w, x, y, z]) + if q.ndim == 2: + q = q.swapaxes(0, 1) + assert q.shape == q0.shape + return q + + +def quat_rot_vec(q, v0): + q_v0 = np.array([0, v0[0], v0[1], v0[2]]) + q_v = quat_mul(q, quat_mul(q_v0, quat_conjugate(q))) + v = q_v[1:] + return v + + +def quat_identity(): + return np.array([1, 0, 0, 0]) + + +def quat2axisangle(quat): + theta = 0 + axis = np.array([0, 0, 1]) + sin_theta = np.linalg.norm(quat[1:]) + + if sin_theta > 0.0001: + theta = 2 * np.arcsin(sin_theta) + theta *= 1 if quat[0] >= 0 else -1 + axis = quat[1:] / sin_theta + + return axis, theta + + +def euler2point_euler(euler): + _euler = euler.copy() + if len(_euler.shape) < 2: + _euler = np.expand_dims(_euler, 0) + assert _euler.shape[1] == 3 + _euler_sin = np.sin(_euler) + _euler_cos = np.cos(_euler) + return np.concatenate([_euler_sin, _euler_cos], axis=-1) + + +def point_euler2euler(euler): + _euler = euler.copy() + if len(_euler.shape) < 2: + _euler = np.expand_dims(_euler, 0) + assert _euler.shape[1] == 6 + angle = np.arctan(_euler[..., :3] / _euler[..., 3:]) + angle[_euler[..., 3:] < 0] += np.pi + return angle + + +def quat2point_quat(quat): + # Should be in qw, qx, qy, qz + _quat = quat.copy() + if len(_quat.shape) < 2: + _quat = np.expand_dims(_quat, 0) + assert _quat.shape[1] == 4 + angle = np.arccos(_quat[:, [0]]) * 2 + xyz = _quat[:, 1:] + xyz[np.squeeze(np.abs(np.sin(angle / 2))) >= 1e-5] = (xyz / np.sin(angle / 2))[ + np.squeeze(np.abs(np.sin(angle / 2))) >= 1e-5 + ] + return np.concatenate([np.sin(angle), np.cos(angle), xyz], axis=-1) + + +def point_quat2quat(quat): + _quat = quat.copy() + if len(_quat.shape) < 2: + _quat = np.expand_dims(_quat, 0) + assert _quat.shape[1] == 5 + angle = np.arctan(_quat[:, [0]] / _quat[:, [1]]) + qw = np.cos(angle / 2) + + qxyz = _quat[:, 2:] + qxyz[np.squeeze(np.abs(np.sin(angle / 2))) >= 1e-5] = (qxyz * np.sin(angle / 2))[ + np.squeeze(np.abs(np.sin(angle / 2))) >= 1e-5 + ] + return np.concatenate([qw, qxyz], axis=-1) + + +def normalize_angles(angles): + """Puts angles in [-pi, pi] range.""" + angles = angles.copy() + if angles.size > 0: + angles = (angles + np.pi) % (2 * np.pi) - np.pi + assert -np.pi - 1e-6 <= angles.min() and angles.max() <= np.pi + 1e-6 + return angles + + +def round_to_straight_angles(angles): + """Returns closest angle modulo 90 degrees""" + angles = np.round(angles / (np.pi / 2)) * (np.pi / 2) + return normalize_angles(angles) + + +def get_parallel_rotations(): + mult90 = [0, np.pi / 2, -np.pi / 2, np.pi] + parallel_rotations = [] + for euler in itertools.product(mult90, repeat=3): + canonical = mat2euler(euler2mat(euler)) + canonical = np.round(canonical / (np.pi / 2)) + if canonical[0] == -2: + canonical[0] = 2 + if canonical[2] == -2: + canonical[2] = 2 + canonical *= np.pi / 2 + if all([(canonical != rot).any() for rot in parallel_rotations]): + parallel_rotations += [canonical] + assert len(parallel_rotations) == 24 + return parallel_rotations diff --git a/gym/envs/robotics/utils.py b/gym/envs/robotics/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..baa767200066b21c5998e42fe0a2ce4e5993da31 --- /dev/null +++ b/gym/envs/robotics/utils.py @@ -0,0 +1,101 @@ +import numpy as np + +from gym import error + +try: + import mujoco_py +except ImportError as e: + raise error.DependencyNotInstalled( + "{}. (HINT: you need to install mujoco_py, and also perform the setup instructions here: https://github.com/openai/mujoco-py/.)".format( + e + ) + ) + + +def robot_get_obs(sim): + """Returns all joint positions and velocities associated with + a robot. + """ + if sim.data.qpos is not None and sim.model.joint_names: + names = [n for n in sim.model.joint_names if n.startswith("robot")] + return ( + np.array([sim.data.get_joint_qpos(name) for name in names]), + np.array([sim.data.get_joint_qvel(name) for name in names]), + ) + return np.zeros(0), np.zeros(0) + + +def ctrl_set_action(sim, action): + """For torque actuators it copies the action into mujoco ctrl field. + For position actuators it sets the target relative to the current qpos. + """ + if sim.model.nmocap > 0: + _, action = np.split(action, (sim.model.nmocap * 7,)) + if sim.data.ctrl is not None: + for i in range(action.shape[0]): + if sim.model.actuator_biastype[i] == 0: + sim.data.ctrl[i] = action[i] + else: + idx = sim.model.jnt_qposadr[sim.model.actuator_trnid[i, 0]] + sim.data.ctrl[i] = sim.data.qpos[idx] + action[i] + + +def mocap_set_action(sim, action): + """The action controls the robot using mocaps. Specifically, bodies + on the robot (for example the gripper wrist) is controlled with + mocap bodies. In this case the action is the desired difference + in position and orientation (quaternion), in world coordinates, + of the of the target body. The mocap is positioned relative to + the target body according to the delta, and the MuJoCo equality + constraint optimizer tries to center the welded body on the mocap. + """ + if sim.model.nmocap > 0: + action, _ = np.split(action, (sim.model.nmocap * 7,)) + action = action.reshape(sim.model.nmocap, 7) + + pos_delta = action[:, :3] + quat_delta = action[:, 3:] + + reset_mocap2body_xpos(sim) + sim.data.mocap_pos[:] = sim.data.mocap_pos + pos_delta + sim.data.mocap_quat[:] = sim.data.mocap_quat + quat_delta + + +def reset_mocap_welds(sim): + """Resets the mocap welds that we use for actuation.""" + if sim.model.nmocap > 0 and sim.model.eq_data is not None: + for i in range(sim.model.eq_data.shape[0]): + if sim.model.eq_type[i] == mujoco_py.const.EQ_WELD: + sim.model.eq_data[i, :] = np.array([0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]) + sim.forward() + + +def reset_mocap2body_xpos(sim): + """Resets the position and orientation of the mocap bodies to the same + values as the bodies they're welded to. + """ + + if ( + sim.model.eq_type is None + or sim.model.eq_obj1id is None + or sim.model.eq_obj2id is None + ): + return + for eq_type, obj1_id, obj2_id in zip( + sim.model.eq_type, sim.model.eq_obj1id, sim.model.eq_obj2id + ): + if eq_type != mujoco_py.const.EQ_WELD: + continue + + mocap_id = sim.model.body_mocapid[obj1_id] + if mocap_id != -1: + # obj1 is the mocap, obj2 is the welded body + body_idx = obj2_id + else: + # obj2 is the mocap, obj1 is the welded body + mocap_id = sim.model.body_mocapid[obj2_id] + body_idx = obj1_id + + assert mocap_id != -1 + sim.data.mocap_pos[mocap_id][:] = sim.data.body_xpos[body_idx] + sim.data.mocap_quat[mocap_id][:] = sim.data.body_xquat[body_idx] diff --git a/gym/envs/toy_text/__init__.py b/gym/envs/toy_text/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8adeb2abef0a2ee2b052464f9071540c4ca1a8df --- /dev/null +++ b/gym/envs/toy_text/__init__.py @@ -0,0 +1,4 @@ +from gym.envs.toy_text.blackjack import BlackjackEnv +from gym.envs.toy_text.frozen_lake import FrozenLakeEnv +from gym.envs.toy_text.cliffwalking import CliffWalkingEnv +from gym.envs.toy_text.taxi import TaxiEnv diff --git a/gym/envs/toy_text/__pycache__/__init__.cpython-39.pyc b/gym/envs/toy_text/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ef4f1be3e519cdb1ff95cba1312fab0ee4c757e Binary files /dev/null and b/gym/envs/toy_text/__pycache__/__init__.cpython-39.pyc differ diff --git a/gym/envs/toy_text/__pycache__/blackjack.cpython-39.pyc b/gym/envs/toy_text/__pycache__/blackjack.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b2781833e570262b6d5c083a41417901df0e85a Binary files /dev/null and b/gym/envs/toy_text/__pycache__/blackjack.cpython-39.pyc differ diff --git a/gym/envs/toy_text/__pycache__/cliffwalking.cpython-39.pyc b/gym/envs/toy_text/__pycache__/cliffwalking.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1852476c7783fae77165d550eeec7352a62a4eff Binary files /dev/null and b/gym/envs/toy_text/__pycache__/cliffwalking.cpython-39.pyc differ diff --git a/gym/envs/toy_text/__pycache__/discrete.cpython-39.pyc b/gym/envs/toy_text/__pycache__/discrete.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..690dbe35e2fbf24dea4307901ab849870ea968e7 Binary files /dev/null and b/gym/envs/toy_text/__pycache__/discrete.cpython-39.pyc differ diff --git a/gym/envs/toy_text/__pycache__/frozen_lake.cpython-39.pyc b/gym/envs/toy_text/__pycache__/frozen_lake.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f2c81e6af34d8a08731c76449a619a58ab6b13c Binary files /dev/null and b/gym/envs/toy_text/__pycache__/frozen_lake.cpython-39.pyc differ diff --git a/gym/envs/toy_text/__pycache__/taxi.cpython-39.pyc b/gym/envs/toy_text/__pycache__/taxi.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdcc81f8a205ae3da68afb7292eba2adc92d41a6 Binary files /dev/null and b/gym/envs/toy_text/__pycache__/taxi.cpython-39.pyc differ diff --git a/gym/envs/toy_text/blackjack.py b/gym/envs/toy_text/blackjack.py new file mode 100644 index 0000000000000000000000000000000000000000..fdbf149f42fc2685dc4a2df1af6025aba11f9b54 --- /dev/null +++ b/gym/envs/toy_text/blackjack.py @@ -0,0 +1,128 @@ +import gym +from gym import spaces +from gym.utils import seeding + + +def cmp(a, b): + return float(a > b) - float(a < b) + + +# 1 = Ace, 2-10 = Number cards, Jack/Queen/King = 10 +deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] + + +def draw_card(np_random): + return int(np_random.choice(deck)) + + +def draw_hand(np_random): + return [draw_card(np_random), draw_card(np_random)] + + +def usable_ace(hand): # Does this hand have a usable ace? + return 1 in hand and sum(hand) + 10 <= 21 + + +def sum_hand(hand): # Return current hand total + if usable_ace(hand): + return sum(hand) + 10 + return sum(hand) + + +def is_bust(hand): # Is this hand a bust? + return sum_hand(hand) > 21 + + +def score(hand): # What is the score of this hand (0 if bust) + return 0 if is_bust(hand) else sum_hand(hand) + + +def is_natural(hand): # Is this hand a natural blackjack? + return sorted(hand) == [1, 10] + + +class BlackjackEnv(gym.Env): + """Simple blackjack environment + + Blackjack is a card game where the goal is to obtain cards that sum to as + near as possible to 21 without going over. They're playing against a fixed + dealer. + Face cards (Jack, Queen, King) have point value 10. + Aces can either count as 11 or 1, and it's called 'usable' at 11. + This game is placed with an infinite deck (or with replacement). + The game starts with dealer having one face up and one face down card, while + player having two face up cards. (Virtually for all Blackjack games today). + + The player can request additional cards (hit=1) until they decide to stop + (stick=0) or exceed 21 (bust). + + After the player sticks, the dealer reveals their facedown card, and draws + until their sum is 17 or greater. If the dealer goes bust the player wins. + + If neither player nor dealer busts, the outcome (win, lose, draw) is + decided by whose sum is closer to 21. The reward for winning is +1, + drawing is 0, and losing is -1. + + The observation of a 3-tuple of: the players current sum, + the dealer's one showing card (1-10 where 1 is ace), + and whether or not the player holds a usable ace (0 or 1). + + This environment corresponds to the version of the blackjack problem + described in Example 5.1 in Reinforcement Learning: An Introduction + by Sutton and Barto. + http://incompleteideas.net/book/the-book-2nd.html + """ + + def __init__(self, natural=False, sab=False): + self.action_space = spaces.Discrete(2) + self.observation_space = spaces.Tuple( + (spaces.Discrete(32), spaces.Discrete(11), spaces.Discrete(2)) + ) + self.seed() + + # Flag to payout 1.5 on a "natural" blackjack win, like casino rules + # Ref: http://www.bicyclecards.com/how-to-play/blackjack/ + self.natural = natural + + # Flag for full agreement with the (Sutton and Barto, 2018) definition. Overrides self.natural + self.sab = sab + + def seed(self, seed=None): + self.np_random, seed = seeding.np_random(seed) + return [seed] + + def step(self, action): + assert self.action_space.contains(action) + if action: # hit: add a card to players hand and return + self.player.append(draw_card(self.np_random)) + if is_bust(self.player): + done = True + reward = -1.0 + else: + done = False + reward = 0.0 + else: # stick: play out the dealers hand, and score + done = True + while sum_hand(self.dealer) < 17: + self.dealer.append(draw_card(self.np_random)) + reward = cmp(score(self.player), score(self.dealer)) + if self.sab and is_natural(self.player) and not is_natural(self.dealer): + # Player automatically wins. Rules consistent with S&B + reward = 1.0 + elif ( + not self.sab + and self.natural + and is_natural(self.player) + and reward == 1.0 + ): + # Natural gives extra points, but doesn't autowin. Legacy implementation + reward = 1.5 + return self._get_obs(), reward, done, {} + + def _get_obs(self): + return (sum_hand(self.player), self.dealer[0], usable_ace(self.player)) + + def reset(self): + self.dealer = draw_hand(self.np_random) + self.player = draw_hand(self.np_random) + return self._get_obs() diff --git a/gym/envs/toy_text/cliffwalking.py b/gym/envs/toy_text/cliffwalking.py new file mode 100644 index 0000000000000000000000000000000000000000..8898297fcd3ede49b1633762f3e406880dc6cf48 --- /dev/null +++ b/gym/envs/toy_text/cliffwalking.py @@ -0,0 +1,120 @@ +import numpy as np +import sys +from contextlib import closing +from io import StringIO +from gym.envs.toy_text import discrete + +UP = 0 +RIGHT = 1 +DOWN = 2 +LEFT = 3 + + +class CliffWalkingEnv(discrete.DiscreteEnv): + """ + This is a simple implementation of the Gridworld Cliff + reinforcement learning task. + + Adapted from Example 6.6 (page 106) from Reinforcement Learning: An Introduction + by Sutton and Barto: + http://incompleteideas.net/book/bookdraft2018jan1.pdf + + With inspiration from: + https://github.com/dennybritz/reinforcement-learning/blob/master/lib/envs/cliff_walking.py + + The board is a 4x12 matrix, with (using NumPy matrix indexing): + [3, 0] as the start at bottom-left + [3, 11] as the goal at bottom-right + [3, 1..10] as the cliff at bottom-center + + Each time step incurs -1 reward, and stepping into the cliff incurs -100 reward + and a reset to the start. An episode terminates when the agent reaches the goal. + """ + + metadata = {"render.modes": ["human", "ansi"]} + + def __init__(self): + self.shape = (4, 12) + self.start_state_index = np.ravel_multi_index((3, 0), self.shape) + + nS = np.prod(self.shape) + nA = 4 + + # Cliff Location + self._cliff = np.zeros(self.shape, dtype=np.bool) + self._cliff[3, 1:-1] = True + + # Calculate transition probabilities and rewards + P = {} + for s in range(nS): + position = np.unravel_index(s, self.shape) + P[s] = {a: [] for a in range(nA)} + P[s][UP] = self._calculate_transition_prob(position, [-1, 0]) + P[s][RIGHT] = self._calculate_transition_prob(position, [0, 1]) + P[s][DOWN] = self._calculate_transition_prob(position, [1, 0]) + P[s][LEFT] = self._calculate_transition_prob(position, [0, -1]) + + # Calculate initial state distribution + # We always start in state (3, 0) + isd = np.zeros(nS) + isd[self.start_state_index] = 1.0 + + super(CliffWalkingEnv, self).__init__(nS, nA, P, isd) + + def _limit_coordinates(self, coord): + """ + Prevent the agent from falling out of the grid world + :param coord: + :return: + """ + coord[0] = min(coord[0], self.shape[0] - 1) + coord[0] = max(coord[0], 0) + coord[1] = min(coord[1], self.shape[1] - 1) + coord[1] = max(coord[1], 0) + return coord + + def _calculate_transition_prob(self, current, delta): + """ + Determine the outcome for an action. Transition Prob is always 1.0. + :param current: Current position on the grid as (row, col) + :param delta: Change in position for transition + :return: (1.0, new_state, reward, done) + """ + new_position = np.array(current) + np.array(delta) + new_position = self._limit_coordinates(new_position).astype(int) + new_state = np.ravel_multi_index(tuple(new_position), self.shape) + if self._cliff[tuple(new_position)]: + return [(1.0, self.start_state_index, -100, False)] + + terminal_state = (self.shape[0] - 1, self.shape[1] - 1) + is_done = tuple(new_position) == terminal_state + return [(1.0, new_state, -1, is_done)] + + def render(self, mode="human"): + outfile = StringIO() if mode == "ansi" else sys.stdout + + for s in range(self.nS): + position = np.unravel_index(s, self.shape) + if self.s == s: + output = " x " + # Print terminal state + elif position == (3, 11): + output = " T " + elif self._cliff[position]: + output = " C " + else: + output = " o " + + if position[1] == 0: + output = output.lstrip() + if position[1] == self.shape[1] - 1: + output = output.rstrip() + output += "\n" + + outfile.write(output) + outfile.write("\n") + + # No need to return anything for human + if mode != "human": + with closing(outfile): + return outfile.getvalue() diff --git a/gym/envs/toy_text/discrete.py b/gym/envs/toy_text/discrete.py new file mode 100644 index 0000000000000000000000000000000000000000..a49263f0c6077ef893195f3ff20fc9d50de83656 --- /dev/null +++ b/gym/envs/toy_text/discrete.py @@ -0,0 +1,61 @@ +import numpy as np + +from gym import Env, spaces +from gym.utils import seeding + + +def categorical_sample(prob_n, np_random): + """ + Sample from categorical distribution + Each row specifies class probabilities + """ + prob_n = np.asarray(prob_n) + csprob_n = np.cumsum(prob_n) + return (csprob_n > np_random.rand()).argmax() + + +class DiscreteEnv(Env): + + """ + Has the following members + - nS: number of states + - nA: number of actions + - P: transitions (*) + - isd: initial state distribution (**) + + (*) dictionary of lists, where + P[s][a] == [(probability, nextstate, reward, done), ...] + (**) list or array of length nS + + + """ + + def __init__(self, nS, nA, P, isd): + self.P = P + self.isd = isd + self.lastaction = None # for rendering + self.nS = nS + self.nA = nA + + self.action_space = spaces.Discrete(self.nA) + self.observation_space = spaces.Discrete(self.nS) + + self.seed() + self.s = categorical_sample(self.isd, self.np_random) + + def seed(self, seed=None): + self.np_random, seed = seeding.np_random(seed) + return [seed] + + def reset(self): + self.s = categorical_sample(self.isd, self.np_random) + self.lastaction = None + return int(self.s) + + def step(self, a): + transitions = self.P[self.s][a] + i = categorical_sample([t[0] for t in transitions], self.np_random) + p, s, r, d = transitions[i] + self.s = s + self.lastaction = a + return (int(s), r, d, {"prob": p}) diff --git a/gym/envs/toy_text/frozen_lake.py b/gym/envs/toy_text/frozen_lake.py new file mode 100644 index 0000000000000000000000000000000000000000..1b6de59852d9fcf7c582d6d63be05cdcfd96d7aa --- /dev/null +++ b/gym/envs/toy_text/frozen_lake.py @@ -0,0 +1,169 @@ +import sys +from contextlib import closing + +import numpy as np +from io import StringIO + +from gym import utils +from gym.envs.toy_text import discrete + +LEFT = 0 +DOWN = 1 +RIGHT = 2 +UP = 3 + +MAPS = { + "4x4": ["SFFF", "FHFH", "FFFH", "HFFG"], + "8x8": [ + "SFFFFFFF", + "FFFFFFFF", + "FFFHFFFF", + "FFFFFHFF", + "FFFHFFFF", + "FHHFFFHF", + "FHFFHFHF", + "FFFHFFFG", + ], +} + + +def generate_random_map(size=8, p=0.8): + """Generates a random valid map (one that has a path from start to goal) + :param size: size of each side of the grid + :param p: probability that a tile is frozen + """ + valid = False + + # DFS to check that it's a valid path. + def is_valid(res): + frontier, discovered = [], set() + frontier.append((0, 0)) + while frontier: + r, c = frontier.pop() + if not (r, c) in discovered: + discovered.add((r, c)) + directions = [(1, 0), (0, 1), (-1, 0), (0, -1)] + for x, y in directions: + r_new = r + x + c_new = c + y + if r_new < 0 or r_new >= size or c_new < 0 or c_new >= size: + continue + if res[r_new][c_new] == "G": + return True + if res[r_new][c_new] != "H": + frontier.append((r_new, c_new)) + return False + + while not valid: + p = min(1, p) + res = np.random.choice(["F", "H"], (size, size), p=[p, 1 - p]) + res[0][0] = "S" + res[-1][-1] = "G" + valid = is_valid(res) + return ["".join(x) for x in res] + + +class FrozenLakeEnv(discrete.DiscreteEnv): + """ + Winter is here. You and your friends were tossing around a frisbee at the + park when you made a wild throw that left the frisbee out in the middle of + the lake. The water is mostly frozen, but there are a few holes where the + ice has melted. If you step into one of those holes, you'll fall into the + freezing water. At this time, there's an international frisbee shortage, so + it's absolutely imperative that you navigate across the lake and retrieve + the disc. However, the ice is slippery, so you won't always move in the + direction you intend. + The surface is described using a grid like the following + + SFFF + FHFH + FFFH + HFFG + + S : starting point, safe + F : frozen surface, safe + H : hole, fall to your doom + G : goal, where the frisbee is located + + The episode ends when you reach the goal or fall in a hole. + You receive a reward of 1 if you reach the goal, and zero otherwise. + """ + + metadata = {"render.modes": ["human", "ansi"]} + + def __init__(self, desc=None, map_name="4x4", is_slippery=True): + if desc is None and map_name is None: + desc = generate_random_map() + elif desc is None: + desc = MAPS[map_name] + self.desc = desc = np.asarray(desc, dtype="c") + self.nrow, self.ncol = nrow, ncol = desc.shape + self.reward_range = (0, 1) + + nA = 4 + nS = nrow * ncol + + isd = np.array(desc == b"S").astype("float64").ravel() + isd /= isd.sum() + + P = {s: {a: [] for a in range(nA)} for s in range(nS)} + + def to_s(row, col): + return row * ncol + col + + def inc(row, col, a): + if a == LEFT: + col = max(col - 1, 0) + elif a == DOWN: + row = min(row + 1, nrow - 1) + elif a == RIGHT: + col = min(col + 1, ncol - 1) + elif a == UP: + row = max(row - 1, 0) + return (row, col) + + def update_probability_matrix(row, col, action): + newrow, newcol = inc(row, col, action) + newstate = to_s(newrow, newcol) + newletter = desc[newrow, newcol] + done = bytes(newletter) in b"GH" + reward = float(newletter == b"G") + return newstate, reward, done + + for row in range(nrow): + for col in range(ncol): + s = to_s(row, col) + for a in range(4): + li = P[s][a] + letter = desc[row, col] + if letter in b"GH": + li.append((1.0, s, 0, True)) + else: + if is_slippery: + for b in [(a - 1) % 4, a, (a + 1) % 4]: + li.append( + (1.0 / 3.0, *update_probability_matrix(row, col, b)) + ) + else: + li.append((1.0, *update_probability_matrix(row, col, a))) + + super(FrozenLakeEnv, self).__init__(nS, nA, P, isd) + + def render(self, mode="human"): + outfile = StringIO() if mode == "ansi" else sys.stdout + + row, col = self.s // self.ncol, self.s % self.ncol + desc = self.desc.tolist() + desc = [[c.decode("utf-8") for c in line] for line in desc] + desc[row][col] = utils.colorize(desc[row][col], "red", highlight=True) + if self.lastaction is not None: + outfile.write( + " ({})\n".format(["Left", "Down", "Right", "Up"][self.lastaction]) + ) + else: + outfile.write("\n") + outfile.write("\n".join("".join(line) for line in desc) + "\n") + + if mode != "human": + with closing(outfile): + return outfile.getvalue() diff --git a/gym/envs/toy_text/taxi.py b/gym/envs/toy_text/taxi.py new file mode 100644 index 0000000000000000000000000000000000000000..47282f52d9cb3f5742e2e17a9459d31d9f7f63ed --- /dev/null +++ b/gym/envs/toy_text/taxi.py @@ -0,0 +1,200 @@ +import sys +from contextlib import closing +from io import StringIO +from gym import utils +from gym.envs.toy_text import discrete +import numpy as np + +MAP = [ + "+---------+", + "|R: | : :G|", + "| : | : : |", + "| : : : : |", + "| | : | : |", + "|Y| : |B: |", + "+---------+", +] + + +class TaxiEnv(discrete.DiscreteEnv): + """ + The Taxi Problem + from "Hierarchical Reinforcement Learning with the MAXQ Value Function Decomposition" + by Tom Dietterich + + Description: + There are four designated locations in the grid world indicated by R(ed), G(reen), Y(ellow), and B(lue). When the episode starts, the taxi starts off at a random square and the passenger is at a random location. The taxi drives to the passenger's location, picks up the passenger, drives to the passenger's destination (another one of the four specified locations), and then drops off the passenger. Once the passenger is dropped off, the episode ends. + + Observations: + There are 500 discrete states since there are 25 taxi positions, 5 possible locations of the passenger (including the case when the passenger is in the taxi), and 4 destination locations. + Note that there are 400 states that can actually be reached during an episode. The missing states correspond to situations in which the passenger is at the same location as their destination, as this typically signals the end of an episode. + Four additional states can be observed right after a successful episodes, when both the passenger and the taxi are at the destination. + This gives a total of 404 reachable discrete states. + + Passenger locations: + - 0: R(ed) + - 1: G(reen) + - 2: Y(ellow) + - 3: B(lue) + - 4: in taxi + + Destinations: + - 0: R(ed) + - 1: G(reen) + - 2: Y(ellow) + - 3: B(lue) + + Actions: + There are 6 discrete deterministic actions: + - 0: move south + - 1: move north + - 2: move east + - 3: move west + - 4: pickup passenger + - 5: drop off passenger + + Rewards: + There is a default per-step reward of -1, + except for delivering the passenger, which is +20, + or executing "pickup" and "drop-off" actions illegally, which is -10. + + Rendering: + - blue: passenger + - magenta: destination + - yellow: empty taxi + - green: full taxi + - other letters (R, G, Y and B): locations for passengers and destinations + + state space is represented by: + (taxi_row, taxi_col, passenger_location, destination) + """ + + metadata = {"render.modes": ["human", "ansi"]} + + def __init__(self): + self.desc = np.asarray(MAP, dtype="c") + + self.locs = locs = [(0, 0), (0, 4), (4, 0), (4, 3)] + + num_states = 500 + num_rows = 5 + num_columns = 5 + max_row = num_rows - 1 + max_col = num_columns - 1 + initial_state_distrib = np.zeros(num_states) + num_actions = 6 + P = { + state: {action: [] for action in range(num_actions)} + for state in range(num_states) + } + for row in range(num_rows): + for col in range(num_columns): + for pass_idx in range(len(locs) + 1): # +1 for being inside taxi + for dest_idx in range(len(locs)): + state = self.encode(row, col, pass_idx, dest_idx) + if pass_idx < 4 and pass_idx != dest_idx: + initial_state_distrib[state] += 1 + for action in range(num_actions): + # defaults + new_row, new_col, new_pass_idx = row, col, pass_idx + reward = ( + -1 + ) # default reward when there is no pickup/dropoff + done = False + taxi_loc = (row, col) + + if action == 0: + new_row = min(row + 1, max_row) + elif action == 1: + new_row = max(row - 1, 0) + if action == 2 and self.desc[1 + row, 2 * col + 2] == b":": + new_col = min(col + 1, max_col) + elif action == 3 and self.desc[1 + row, 2 * col] == b":": + new_col = max(col - 1, 0) + elif action == 4: # pickup + if pass_idx < 4 and taxi_loc == locs[pass_idx]: + new_pass_idx = 4 + else: # passenger not at location + reward = -10 + elif action == 5: # dropoff + if (taxi_loc == locs[dest_idx]) and pass_idx == 4: + new_pass_idx = dest_idx + done = True + reward = 20 + elif (taxi_loc in locs) and pass_idx == 4: + new_pass_idx = locs.index(taxi_loc) + else: # dropoff at wrong location + reward = -10 + new_state = self.encode( + new_row, new_col, new_pass_idx, dest_idx + ) + P[state][action].append((1.0, new_state, reward, done)) + initial_state_distrib /= initial_state_distrib.sum() + discrete.DiscreteEnv.__init__( + self, num_states, num_actions, P, initial_state_distrib + ) + + def encode(self, taxi_row, taxi_col, pass_loc, dest_idx): + # (5) 5, 5, 4 + i = taxi_row + i *= 5 + i += taxi_col + i *= 5 + i += pass_loc + i *= 4 + i += dest_idx + return i + + def decode(self, i): + out = [] + out.append(i % 4) + i = i // 4 + out.append(i % 5) + i = i // 5 + out.append(i % 5) + i = i // 5 + out.append(i) + assert 0 <= i < 5 + return reversed(out) + + def render(self, mode="human"): + outfile = StringIO() if mode == "ansi" else sys.stdout + + out = self.desc.copy().tolist() + out = [[c.decode("utf-8") for c in line] for line in out] + taxi_row, taxi_col, pass_idx, dest_idx = self.decode(self.s) + + def ul(x): + return "_" if x == " " else x + + if pass_idx < 4: + out[1 + taxi_row][2 * taxi_col + 1] = utils.colorize( + out[1 + taxi_row][2 * taxi_col + 1], "yellow", highlight=True + ) + pi, pj = self.locs[pass_idx] + out[1 + pi][2 * pj + 1] = utils.colorize( + out[1 + pi][2 * pj + 1], "blue", bold=True + ) + else: # passenger in taxi + out[1 + taxi_row][2 * taxi_col + 1] = utils.colorize( + ul(out[1 + taxi_row][2 * taxi_col + 1]), "green", highlight=True + ) + + di, dj = self.locs[dest_idx] + out[1 + di][2 * dj + 1] = utils.colorize(out[1 + di][2 * dj + 1], "magenta") + outfile.write("\n".join(["".join(row) for row in out]) + "\n") + if self.lastaction is not None: + outfile.write( + " ({})\n".format( + ["South", "North", "East", "West", "Pickup", "Dropoff"][ + self.lastaction + ] + ) + ) + else: + outfile.write("\n") + + # No need to return anything for human + if mode != "human": + with closing(outfile): + return outfile.getvalue() diff --git a/gym/envs/unittest/__init__.py b/gym/envs/unittest/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dbb50e8b0c7ab5202b84e12af308199c720d5a24 --- /dev/null +++ b/gym/envs/unittest/__init__.py @@ -0,0 +1,4 @@ +from gym.envs.unittest.cube_crash import CubeCrash +from gym.envs.unittest.cube_crash import CubeCrashSparse +from gym.envs.unittest.cube_crash import CubeCrashScreenBecomesBlack +from gym.envs.unittest.memorize_digits import MemorizeDigits diff --git a/gym/envs/unittest/__pycache__/__init__.cpython-39.pyc b/gym/envs/unittest/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..790b2be7a292270a4e346237aed00f6f767ca974 Binary files /dev/null and b/gym/envs/unittest/__pycache__/__init__.cpython-39.pyc differ diff --git a/gym/envs/unittest/__pycache__/cube_crash.cpython-39.pyc b/gym/envs/unittest/__pycache__/cube_crash.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0818a5f06cdc3b87f4ca103af323cd96cb7848b2 Binary files /dev/null and b/gym/envs/unittest/__pycache__/cube_crash.cpython-39.pyc differ diff --git a/gym/envs/unittest/__pycache__/memorize_digits.cpython-39.pyc b/gym/envs/unittest/__pycache__/memorize_digits.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..689cdae53a6b3bc62d3bd0f1d3c2e1404cb991a8 Binary files /dev/null and b/gym/envs/unittest/__pycache__/memorize_digits.cpython-39.pyc differ diff --git a/gym/envs/unittest/cube_crash.py b/gym/envs/unittest/cube_crash.py new file mode 100644 index 0000000000000000000000000000000000000000..61a7f531354a3c3961a6dc2320a9ec89af8074a2 --- /dev/null +++ b/gym/envs/unittest/cube_crash.py @@ -0,0 +1,173 @@ +import numpy as np +import gym +from gym import spaces +from gym.utils import seeding + +# Unit test environment for CNNs and CNN+RNN algorithms. +# Looks like this (RGB observations): +# +# --------------------------- +# | | +# | | +# | | +# | ** | +# | ** | +# | | +# | | +# | | +# | | +# | | +# ======== ============== +# +# Goal is to go through the hole at the bottom. Agent controls square using Left-Nop-Right actions. +# It falls down automatically, episode length is a bit less than FIELD_H +# +# CubeCrash-v0 # shaped reward +# CubeCrashSparse-v0 # reward 0 or 1 at the end +# CubeCrashScreenBecomesBlack-v0 # for RNNs +# +# To see how it works, run: +# +# python examples/agents/keyboard_agent.py CubeCrashScreen-v0 + +FIELD_W = 32 +FIELD_H = 40 +HOLE_WIDTH = 8 + +color_black = np.array((0, 0, 0)).astype("float32") +color_white = np.array((255, 255, 255)).astype("float32") +color_green = np.array((0, 255, 0)).astype("float32") + + +class CubeCrash(gym.Env): + metadata = { + "render.modes": ["human", "rgb_array"], + "video.frames_per_second": 60, + "video.res_w": FIELD_W, + "video.res_h": FIELD_H, + } + + use_shaped_reward = True + use_black_screen = False + use_random_colors = False # Makes env too hard + + def __init__(self): + self.seed() + self.viewer = None + + self.observation_space = spaces.Box( + 0, 255, (FIELD_H, FIELD_W, 3), dtype=np.uint8 + ) + self.action_space = spaces.Discrete(3) + + self.reset() + + def seed(self, seed=None): + self.np_random, seed = seeding.np_random(seed) + return [seed] + + def random_color(self): + return np.array( + [ + self.np_random.randint(low=0, high=255), + self.np_random.randint(low=0, high=255), + self.np_random.randint(low=0, high=255), + ] + ).astype("uint8") + + def reset(self): + self.cube_x = self.np_random.randint(low=3, high=FIELD_W - 3) + self.cube_y = self.np_random.randint(low=3, high=FIELD_H // 6) + self.hole_x = self.np_random.randint(low=HOLE_WIDTH, high=FIELD_W - HOLE_WIDTH) + self.bg_color = self.random_color() if self.use_random_colors else color_black + self.potential = None + self.step_n = 0 + while 1: + self.wall_color = ( + self.random_color() if self.use_random_colors else color_white + ) + self.cube_color = ( + self.random_color() if self.use_random_colors else color_green + ) + if ( + np.linalg.norm(self.wall_color - self.bg_color) < 50 + or np.linalg.norm(self.cube_color - self.bg_color) < 50 + ): + continue + break + return self.step(0)[0] + + def step(self, action): + if action == 0: + pass + elif action == 1: + self.cube_x -= 1 + elif action == 2: + self.cube_x += 1 + else: + assert 0, "Action %i is out of range" % action + self.cube_y += 1 + self.step_n += 1 + + obs = np.zeros((FIELD_H, FIELD_W, 3), dtype=np.uint8) + obs[:, :, :] = self.bg_color + obs[FIELD_H - 5 : FIELD_H, :, :] = self.wall_color + obs[ + FIELD_H - 5 : FIELD_H, + self.hole_x - HOLE_WIDTH // 2 : self.hole_x + HOLE_WIDTH // 2 + 1, + :, + ] = self.bg_color + obs[ + self.cube_y - 1 : self.cube_y + 2, self.cube_x - 1 : self.cube_x + 2, : + ] = self.cube_color + if self.use_black_screen and self.step_n > 4: + obs[:] = np.zeros((3,), dtype=np.uint8) + + done = False + reward = 0 + dist = np.abs(self.cube_x - self.hole_x) + if self.potential is not None and self.use_shaped_reward: + reward = (self.potential - dist) * 0.01 + self.potential = dist + + if self.cube_x - 1 < 0 or self.cube_x + 1 >= FIELD_W: + done = True + reward = -1 + elif self.cube_y + 1 >= FIELD_H - 5: + if dist >= HOLE_WIDTH // 2: + done = True + reward = -1 + elif self.cube_y == FIELD_H: + done = True + reward = +1 + self.last_obs = obs + return obs, reward, done, {} + + def render(self, mode="human"): + if mode == "rgb_array": + return self.last_obs + + elif mode == "human": + from gym.envs.classic_control import rendering + + if self.viewer is None: + self.viewer = rendering.SimpleImageViewer() + self.viewer.imshow(self.last_obs) + return self.viewer.isopen + + else: + assert 0, "Render mode '%s' is not supported" % mode + + def close(self): + if self.viewer is not None: + self.viewer.close() + self.viewer = None + + +class CubeCrashSparse(CubeCrash): + use_shaped_reward = False + + +class CubeCrashScreenBecomesBlack(CubeCrash): + use_shaped_reward = False + use_black_screen = True diff --git a/gym/envs/unittest/memorize_digits.py b/gym/envs/unittest/memorize_digits.py new file mode 100644 index 0000000000000000000000000000000000000000..6b48c9f5fc2cb6ff8b66c21898c02edec22e87aa --- /dev/null +++ b/gym/envs/unittest/memorize_digits.py @@ -0,0 +1,146 @@ +import numpy as np +import gym +from gym import spaces +from gym.utils import seeding + +# Unit test environment for CNNs. +# Looks like this (RGB observations): +# +# --------------------------- +# | | +# | ****** | +# | ****** | +# | ** ** | +# | ** ** | +# | ** | +# | ** | +# | **** | +# | **** | +# | **** | +# | **** | +# | ********** | +# | ********** | +# | | +# --------------------------- +# +# Agent should hit action 2 to gain reward. Catches off-by-one errors in your agent. +# +# To see how it works, run: +# +# python examples/agents/keyboard_agent.py MemorizeDigits-v0 + +FIELD_W = 32 +FIELD_H = 24 + +bogus_mnist = [ + [" **** ", "* *", "* *", "* *", "* *", " **** "], + [" ** ", " * * ", " * ", " * ", " * ", " *** "], + [" **** ", "* *", " *", " *** ", "** ", "******"], + [" **** ", "* *", " ** ", " *", "* *", " **** "], + [" * * ", " * * ", " * * ", " **** ", " * ", " * "], + [" **** ", " * ", " **** ", " * ", " * ", " **** "], + [" *** ", " * ", " **** ", " * * ", " * * ", " **** "], + [" **** ", " * ", " * ", " * ", " * ", " * "], + [" **** ", "* *", " **** ", "* *", "* *", " **** "], + [" **** ", "* *", "* *", " *****", " *", " **** "], +] + +color_black = np.array((0, 0, 0)).astype("float32") +color_white = np.array((255, 255, 255)).astype("float32") + + +class MemorizeDigits(gym.Env): + metadata = { + "render.modes": ["human", "rgb_array"], + "video.frames_per_second": 60, + "video.res_w": FIELD_W, + "video.res_h": FIELD_H, + } + + use_random_colors = False + + def __init__(self): + self.seed() + self.viewer = None + self.observation_space = spaces.Box( + 0, 255, (FIELD_H, FIELD_W, 3), dtype=np.uint8 + ) + self.action_space = spaces.Discrete(10) + self.bogus_mnist = np.zeros((10, 6, 6), dtype=np.uint8) + for digit in range(10): + for y in range(6): + self.bogus_mnist[digit, y, :] = [ + ord(char) for char in bogus_mnist[digit][y] + ] + self.reset() + + def seed(self, seed=None): + self.np_random, seed = seeding.np_random(seed) + return [seed] + + def random_color(self): + return np.array( + [ + self.np_random.randint(low=0, high=255), + self.np_random.randint(low=0, high=255), + self.np_random.randint(low=0, high=255), + ] + ).astype("uint8") + + def reset(self): + self.digit_x = self.np_random.randint(low=FIELD_W // 5, high=FIELD_W // 5 * 4) + self.digit_y = self.np_random.randint(low=FIELD_H // 5, high=FIELD_H // 5 * 4) + self.color_bg = self.random_color() if self.use_random_colors else color_black + self.step_n = 0 + while 1: + self.color_digit = ( + self.random_color() if self.use_random_colors else color_white + ) + if np.linalg.norm(self.color_digit - self.color_bg) < 50: + continue + break + self.digit = -1 + return self.step(0)[0] + + def step(self, action): + reward = -1 + done = False + self.step_n += 1 + if self.digit == -1: + pass + else: + if self.digit == action: + reward = +1 + done = self.step_n > 20 and 0 == self.np_random.randint(low=0, high=5) + self.digit = self.np_random.randint(low=0, high=10) + obs = np.zeros((FIELD_H, FIELD_W, 3), dtype=np.uint8) + obs[:, :, :] = self.color_bg + digit_img = np.zeros((6, 6, 3), dtype=np.uint8) + digit_img[:] = self.color_bg + xxx = self.bogus_mnist[self.digit] == 42 + digit_img[xxx] = self.color_digit + obs[ + self.digit_y - 3 : self.digit_y + 3, self.digit_x - 3 : self.digit_x + 3 + ] = digit_img + self.last_obs = obs + return obs, reward, done, {} + + def render(self, mode="human"): + if mode == "rgb_array": + return self.last_obs + + elif mode == "human": + from gym.envs.classic_control import rendering + + if self.viewer is None: + self.viewer = rendering.SimpleImageViewer() + self.viewer.imshow(self.last_obs) + return self.viewer.isopen + + else: + assert 0, "Render mode '%s' is not supported" % mode + + def close(self): + if self.viewer is not None: + self.viewer.close() + self.viewer = None diff --git a/gym/error.py b/gym/error.py new file mode 100644 index 0000000000000000000000000000000000000000..5884e5911b4e08118de6d3fcca630a4a77430639 --- /dev/null +++ b/gym/error.py @@ -0,0 +1,226 @@ +import sys + + +class Error(Exception): + pass + + +# Local errors + + +class Unregistered(Error): + """Raised when the user requests an item from the registry that does + not actually exist. + """ + + pass + + +class UnregisteredEnv(Unregistered): + """Raised when the user requests an env from the registry that does + not actually exist. + """ + + pass + + +class UnregisteredBenchmark(Unregistered): + """Raised when the user requests an env from the registry that does + not actually exist. + """ + + pass + + +class DeprecatedEnv(Error): + """Raised when the user requests an env from the registry with an + older version number than the latest env with the same name. + """ + + pass + + +class UnseedableEnv(Error): + """Raised when the user tries to seed an env that does not support + seeding. + """ + + pass + + +class DependencyNotInstalled(Error): + pass + + +class UnsupportedMode(Exception): + """Raised when the user requests a rendering mode not supported by the + environment. + """ + + pass + + +class ResetNeeded(Exception): + """When the monitor is active, raised when the user tries to step an + environment that's already done. + """ + + pass + + +class ResetNotAllowed(Exception): + """When the monitor is active, raised when the user tries to step an + environment that's not yet done. + """ + + pass + + +class InvalidAction(Exception): + """Raised when the user performs an action not contained within the + action space + """ + + pass + + +# API errors + + +class APIError(Error): + def __init__( + self, + message=None, + http_body=None, + http_status=None, + json_body=None, + headers=None, + ): + super(APIError, self).__init__(message) + + if http_body and hasattr(http_body, "decode"): + try: + http_body = http_body.decode("utf-8") + except: + http_body = ( + "" + ) + + self._message = message + self.http_body = http_body + self.http_status = http_status + self.json_body = json_body + self.headers = headers or {} + self.request_id = self.headers.get("request-id", None) + + def __unicode__(self): + if self.request_id is not None: + msg = self._message or "" + return u"Request {0}: {1}".format(self.request_id, msg) + else: + return self._message + + def __str__(self): + try: # Python 2 + return unicode(self).encode("utf-8") + except NameError: # Python 3 + return self.__unicode__() + + +class APIConnectionError(APIError): + pass + + +class InvalidRequestError(APIError): + def __init__( + self, + message, + param, + http_body=None, + http_status=None, + json_body=None, + headers=None, + ): + super(InvalidRequestError, self).__init__( + message, http_body, http_status, json_body, headers + ) + self.param = param + + +class AuthenticationError(APIError): + pass + + +class RateLimitError(APIError): + pass + + +# Video errors + + +class VideoRecorderError(Error): + pass + + +class InvalidFrame(Error): + pass + + +# Wrapper errors + + +class DoubleWrapperError(Error): + pass + + +class WrapAfterConfigureError(Error): + pass + + +class RetriesExceededError(Error): + pass + + +# Vectorized environments errors + + +class AlreadyPendingCallError(Exception): + """ + Raised when `reset`, or `step` is called asynchronously (e.g. with + `reset_async`, or `step_async` respectively), and `reset_async`, or + `step_async` (respectively) is called again (without a complete call to + `reset_wait`, or `step_wait` respectively). + """ + + def __init__(self, message, name): + super(AlreadyPendingCallError, self).__init__(message) + self.name = name + + +class NoAsyncCallError(Exception): + """ + Raised when an asynchronous `reset`, or `step` is not running, but + `reset_wait`, or `step_wait` (respectively) is called. + """ + + def __init__(self, message, name): + super(NoAsyncCallError, self).__init__(message) + self.name = name + + +class ClosedEnvironmentError(Exception): + """ + Trying to call `reset`, or `step`, while the environment is closed. + """ + + pass + + +class CustomSpaceError(Exception): + """ + The space is a custom gym.Space instance, and is not supported by + `AsyncVectorEnv` with `shared_memory=True`. + """ + + pass diff --git a/gym/logger.py b/gym/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..89ee21fe3f1d8610636fa55511064c4c18e21cec --- /dev/null +++ b/gym/logger.py @@ -0,0 +1,52 @@ +import sys +import warnings + +from gym.utils import colorize + +DEBUG = 10 +INFO = 20 +WARN = 30 +ERROR = 40 +DISABLED = 50 + +MIN_LEVEL = 30 + + +def set_level(level): + """ + Set logging threshold on current logger. + """ + global MIN_LEVEL + MIN_LEVEL = level + + +def debug(msg, *args): + if MIN_LEVEL <= DEBUG: + print("%s: %s" % ("DEBUG", msg % args), file=sys.stderr) + + +def info(msg, *args): + if MIN_LEVEL <= INFO: + print("%s: %s" % ("INFO", msg % args), file=sys.stderr) + + +def warn(msg, *args, category=None, stacklevel=1): + if MIN_LEVEL <= WARN: + warnings.warn( + colorize("%s: %s" % ("WARN", msg % args), "yellow"), + category=category, + stacklevel=stacklevel + 1, + ) + + +def deprecation(msg, *args): + warn(msg, *args, category=DeprecationWarning, stacklevel=2) + + +def error(msg, *args): + if MIN_LEVEL <= ERROR: + print(colorize("%s: %s" % ("ERROR", msg % args), "red"), file=sys.stderr) + + +# DEPRECATED: +setLevel = set_level diff --git a/gym/spaces/__init__.py b/gym/spaces/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..45f403d0e4c96e151194a9015199cc9cda526125 --- /dev/null +++ b/gym/spaces/__init__.py @@ -0,0 +1,26 @@ +from gym.spaces.space import Space +from gym.spaces.box import Box +from gym.spaces.discrete import Discrete +from gym.spaces.multi_discrete import MultiDiscrete +from gym.spaces.multi_binary import MultiBinary +from gym.spaces.tuple import Tuple +from gym.spaces.dict import Dict + +from gym.spaces.utils import flatdim +from gym.spaces.utils import flatten_space +from gym.spaces.utils import flatten +from gym.spaces.utils import unflatten + +__all__ = [ + "Space", + "Box", + "Discrete", + "MultiDiscrete", + "MultiBinary", + "Tuple", + "Dict", + "flatdim", + "flatten_space", + "flatten", + "unflatten", +] diff --git a/gym/spaces/__pycache__/__init__.cpython-39.pyc b/gym/spaces/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..494e8342e819231843825ee09845cf1035ced45e Binary files /dev/null and b/gym/spaces/__pycache__/__init__.cpython-39.pyc differ diff --git a/gym/spaces/__pycache__/box.cpython-39.pyc b/gym/spaces/__pycache__/box.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f40ab1d2d7161cdbdaece4c469b6baccefe9029 Binary files /dev/null and b/gym/spaces/__pycache__/box.cpython-39.pyc differ diff --git a/gym/spaces/__pycache__/dict.cpython-39.pyc b/gym/spaces/__pycache__/dict.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8a8cf6f34c75908bf5ef8bce1a279d94fe3f02b Binary files /dev/null and b/gym/spaces/__pycache__/dict.cpython-39.pyc differ diff --git a/gym/spaces/__pycache__/discrete.cpython-39.pyc b/gym/spaces/__pycache__/discrete.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43d30b317f098c5a931f29768677767b3c0bc576 Binary files /dev/null and b/gym/spaces/__pycache__/discrete.cpython-39.pyc differ diff --git a/gym/spaces/__pycache__/multi_binary.cpython-39.pyc b/gym/spaces/__pycache__/multi_binary.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1986f10d1ef51e67c266c49091391fce20ba100 Binary files /dev/null and b/gym/spaces/__pycache__/multi_binary.cpython-39.pyc differ diff --git a/gym/spaces/__pycache__/multi_discrete.cpython-39.pyc b/gym/spaces/__pycache__/multi_discrete.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..473e35b220f299c9504cabf5f10d260c1a97f168 Binary files /dev/null and b/gym/spaces/__pycache__/multi_discrete.cpython-39.pyc differ diff --git a/gym/spaces/__pycache__/space.cpython-39.pyc b/gym/spaces/__pycache__/space.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5a87046129bfdb80f2c56f51f6fc5a0071d2b9c Binary files /dev/null and b/gym/spaces/__pycache__/space.cpython-39.pyc differ diff --git a/gym/spaces/__pycache__/tuple.cpython-39.pyc b/gym/spaces/__pycache__/tuple.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7cac144913b54d20c7beabc535a773c1503ae74 Binary files /dev/null and b/gym/spaces/__pycache__/tuple.cpython-39.pyc differ diff --git a/gym/spaces/__pycache__/utils.cpython-39.pyc b/gym/spaces/__pycache__/utils.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1a1eb5d156fea4cd024f378f05b11992fa136e6 Binary files /dev/null and b/gym/spaces/__pycache__/utils.cpython-39.pyc differ diff --git a/gym/spaces/box.py b/gym/spaces/box.py new file mode 100644 index 0000000000000000000000000000000000000000..593d2a388fa4eb1fcc2999766c8e79c9e4f0f09f --- /dev/null +++ b/gym/spaces/box.py @@ -0,0 +1,167 @@ +import numpy as np + +from .space import Space +from gym import logger + + +class Box(Space): + """ + A (possibly unbounded) box in R^n. Specifically, a Box represents the + Cartesian product of n closed intervals. Each interval has the form of one + of [a, b], (-oo, b], [a, oo), or (-oo, oo). + + There are two common use cases: + + * Identical bound for each dimension:: + >>> Box(low=-1.0, high=2.0, shape=(3, 4), dtype=np.float32) + Box(3, 4) + + * Independent bound for each dimension:: + >>> Box(low=np.array([-1.0, -2.0]), high=np.array([2.0, 4.0]), dtype=np.float32) + Box(2,) + + """ + + def __init__(self, low, high, shape=None, dtype=np.float32, seed=None): + assert dtype is not None, "dtype must be explicitly provided. " + self.dtype = np.dtype(dtype) + + # determine shape if it isn't provided directly + if shape is not None: + shape = tuple(shape) + assert ( + np.isscalar(low) or low.shape == shape + ), "low.shape doesn't match provided shape" + assert ( + np.isscalar(high) or high.shape == shape + ), "high.shape doesn't match provided shape" + elif not np.isscalar(low): + shape = low.shape + assert ( + np.isscalar(high) or high.shape == shape + ), "high.shape doesn't match low.shape" + elif not np.isscalar(high): + shape = high.shape + assert ( + np.isscalar(low) or low.shape == shape + ), "low.shape doesn't match high.shape" + else: + raise ValueError( + "shape must be provided or inferred from the shapes of low or high" + ) + + if np.isscalar(low): + low = np.full(shape, low, dtype=dtype) + + if np.isscalar(high): + high = np.full(shape, high, dtype=dtype) + + self._shape = shape + self.low = low + self.high = high + + def _get_precision(dtype): + if np.issubdtype(dtype, np.floating): + return np.finfo(dtype).precision + else: + return np.inf + + low_precision = _get_precision(self.low.dtype) + high_precision = _get_precision(self.high.dtype) + dtype_precision = _get_precision(self.dtype) + if min(low_precision, high_precision) > dtype_precision: + logger.warn( + "Box bound precision lowered by casting to {}".format(self.dtype) + ) + self.low = self.low.astype(self.dtype) + self.high = self.high.astype(self.dtype) + + # Boolean arrays which indicate the interval type for each coordinate + self.bounded_below = -np.inf < self.low + self.bounded_above = np.inf > self.high + + super(Box, self).__init__(self.shape, self.dtype, seed) + + def is_bounded(self, manner="both"): + below = np.all(self.bounded_below) + above = np.all(self.bounded_above) + if manner == "both": + return below and above + elif manner == "below": + return below + elif manner == "above": + return above + else: + raise ValueError("manner is not in {'below', 'above', 'both'}") + + def sample(self): + """ + Generates a single random sample inside of the Box. + + In creating a sample of the box, each coordinate is sampled according to + the form of the interval: + + * [a, b] : uniform distribution + * [a, oo) : shifted exponential distribution + * (-oo, b] : shifted negative exponential distribution + * (-oo, oo) : normal distribution + """ + high = self.high if self.dtype.kind == "f" else self.high.astype("int64") + 1 + sample = np.empty(self.shape) + + # Masking arrays which classify the coordinates according to interval + # type + unbounded = ~self.bounded_below & ~self.bounded_above + upp_bounded = ~self.bounded_below & self.bounded_above + low_bounded = self.bounded_below & ~self.bounded_above + bounded = self.bounded_below & self.bounded_above + + # Vectorized sampling by interval type + sample[unbounded] = self.np_random.normal(size=unbounded[unbounded].shape) + + sample[low_bounded] = ( + self.np_random.exponential(size=low_bounded[low_bounded].shape) + + self.low[low_bounded] + ) + + sample[upp_bounded] = ( + -self.np_random.exponential(size=upp_bounded[upp_bounded].shape) + + self.high[upp_bounded] + ) + + sample[bounded] = self.np_random.uniform( + low=self.low[bounded], high=high[bounded], size=bounded[bounded].shape + ) + if self.dtype.kind == "i": + sample = np.floor(sample) + + return sample.astype(self.dtype) + + def contains(self, x): + if not isinstance(x, np.ndarray): + logger.warn("Casting input x to numpy array.") + x = np.asarray(x, dtype=self.dtype) + + return ( + np.can_cast(x.dtype, self.dtype) + and x.shape == self.shape + and np.all(x >= self.low) + and np.all(x <= self.high) + ) + + def to_jsonable(self, sample_n): + return np.array(sample_n).tolist() + + def from_jsonable(self, sample_n): + return [np.asarray(sample) for sample in sample_n] + + def __repr__(self): + return f"Box({self.low}, {self.high}, {self.shape}, {self.dtype})" + + def __eq__(self, other): + return ( + isinstance(other, Box) + and (self.shape == other.shape) + and np.allclose(self.low, other.low) + and np.allclose(self.high, other.high) + ) diff --git a/gym/spaces/dict.py b/gym/spaces/dict.py new file mode 100644 index 0000000000000000000000000000000000000000..b7b7389573bb88925cd03ad79f8d4c0ae6bef5be --- /dev/null +++ b/gym/spaces/dict.py @@ -0,0 +1,158 @@ +from collections import OrderedDict +import numpy as np +from .space import Space + + +class Dict(Space): + """ + A dictionary of simpler spaces. + + Example usage: + self.observation_space = spaces.Dict({"position": spaces.Discrete(2), "velocity": spaces.Discrete(3)}) + + Example usage [nested]: + self.nested_observation_space = spaces.Dict({ + 'sensors': spaces.Dict({ + 'position': spaces.Box(low=-100, high=100, shape=(3,)), + 'velocity': spaces.Box(low=-1, high=1, shape=(3,)), + 'front_cam': spaces.Tuple(( + spaces.Box(low=0, high=1, shape=(10, 10, 3)), + spaces.Box(low=0, high=1, shape=(10, 10, 3)) + )), + 'rear_cam': spaces.Box(low=0, high=1, shape=(10, 10, 3)), + }), + 'ext_controller': spaces.MultiDiscrete((5, 2, 2)), + 'inner_state':spaces.Dict({ + 'charge': spaces.Discrete(100), + 'system_checks': spaces.MultiBinary(10), + 'job_status': spaces.Dict({ + 'task': spaces.Discrete(5), + 'progress': spaces.Box(low=0, high=100, shape=()), + }) + }) + }) + """ + + def __init__(self, spaces=None, seed=None, **spaces_kwargs): + assert (spaces is None) or ( + not spaces_kwargs + ), "Use either Dict(spaces=dict(...)) or Dict(foo=x, bar=z)" + + if spaces is None: + spaces = spaces_kwargs + if isinstance(spaces, dict) and not isinstance(spaces, OrderedDict): + spaces = OrderedDict(sorted(list(spaces.items()))) + if isinstance(spaces, list): + spaces = OrderedDict(spaces) + self.spaces = spaces + for space in spaces.values(): + assert isinstance( + space, Space + ), "Values of the dict should be instances of gym.Space" + super(Dict, self).__init__( + None, None, seed + ) # None for shape and dtype, since it'll require special handling + + def seed(self, seed=None): + seeds = [] + if isinstance(seed, dict): + for key, seed_key in zip(self.spaces, seed): + assert key == seed_key, print( + "Key value", + seed_key, + "in passed seed dict did not match key value", + key, + "in spaces Dict.", + ) + seeds += self.spaces[key].seed(seed[seed_key]) + elif isinstance(seed, int): + seeds = super().seed(seed) + try: + subseeds = self.np_random.choice( + np.iinfo(int).max, + size=len(self.spaces), + replace=False, # unique subseed for each subspace + ) + except ValueError: + subseeds = self.np_random.choice( + np.iinfo(int).max, + size=len(self.spaces), + replace=True, # we get more than INT_MAX subspaces + ) + + for subspace, subseed in zip(self.spaces.values(), subseeds): + seeds.append(subspace.seed(int(subseed))[0]) + elif seed is None: + for space in self.spaces.values(): + seeds += space.seed(seed) + else: + raise TypeError("Passed seed not of an expected type: dict or int or None") + + return seeds + + def sample(self): + return OrderedDict([(k, space.sample()) for k, space in self.spaces.items()]) + + def contains(self, x): + if not isinstance(x, dict) or len(x) != len(self.spaces): + return False + for k, space in self.spaces.items(): + if k not in x: + return False + if not space.contains(x[k]): + return False + return True + + def __getitem__(self, key): + return self.spaces[key] + + def __setitem__(self, key, value): + self.spaces[key] = value + + def __iter__(self): + for key in self.spaces: + yield key + + def __len__(self): + return len(self.spaces) + + def __contains__(self, item): + return self.contains(item) + + def __repr__(self): + return ( + "Dict(" + + ", ".join([str(k) + ":" + str(s) for k, s in self.spaces.items()]) + + ")" + ) + + def to_jsonable(self, sample_n): + # serialize as dict-repr of vectors + return { + key: space.to_jsonable([sample[key] for sample in sample_n]) + for key, space in self.spaces.items() + } + + def from_jsonable(self, sample_n): + dict_of_list = {} + for key, space in self.spaces.items(): + dict_of_list[key] = space.from_jsonable(sample_n[key]) + ret = [] + for i, _ in enumerate(dict_of_list[key]): + entry = {} + for key, value in dict_of_list.items(): + entry[key] = value[i] + ret.append(entry) + return ret + + def __eq__(self, other): + return isinstance(other, Dict) and self.spaces == other.spaces + + def keys(self): + return self.spaces.keys() + + def values(self): + return self.spaces.values() + + def items(self): + return self.spaces.items() diff --git a/gym/spaces/discrete.py b/gym/spaces/discrete.py new file mode 100644 index 0000000000000000000000000000000000000000..eb358e6c1afda6dbf4751a2c83229c67bdbb45d2 --- /dev/null +++ b/gym/spaces/discrete.py @@ -0,0 +1,37 @@ +import numpy as np +from .space import Space + + +class Discrete(Space): + r"""A discrete space in :math:`\{ 0, 1, \\dots, n-1 \}`. + + Example:: + + >>> Discrete(2) + + """ + + def __init__(self, n, seed=None): + assert n >= 0 + self.n = n + super(Discrete, self).__init__((), np.int64, seed) + + def sample(self): + return self.np_random.randint(self.n) + + def contains(self, x): + if isinstance(x, int): + as_int = x + elif isinstance(x, (np.generic, np.ndarray)) and ( + x.dtype.char in np.typecodes["AllInteger"] and x.shape == () + ): + as_int = int(x) + else: + return False + return as_int >= 0 and as_int < self.n + + def __repr__(self): + return "Discrete(%d)" % self.n + + def __eq__(self, other): + return isinstance(other, Discrete) and self.n == other.n diff --git a/gym/spaces/multi_binary.py b/gym/spaces/multi_binary.py new file mode 100644 index 0000000000000000000000000000000000000000..d8b315a1c88789c5dcb2fe7fde53437acd15122b --- /dev/null +++ b/gym/spaces/multi_binary.py @@ -0,0 +1,57 @@ +import numpy as np +from .space import Space + + +class MultiBinary(Space): + """ + An n-shape binary space. + + The argument to MultiBinary defines n, which could be a number or a `list` of numbers. + + Example Usage: + + >> self.observation_space = spaces.MultiBinary(5) + + >> self.observation_space.sample() + + array([0,1,0,1,0], dtype =int8) + + >> self.observation_space = spaces.MultiBinary([3,2]) + + >> self.observation_space.sample() + + array([[0, 0], + [0, 1], + [1, 1]], dtype=int8) + + """ + + def __init__(self, n, seed=None): + self.n = n + if type(n) in [tuple, list, np.ndarray]: + input_n = n + else: + input_n = (n,) + super(MultiBinary, self).__init__(input_n, np.int8, seed) + + def sample(self): + return self.np_random.randint(low=0, high=2, size=self.n, dtype=self.dtype) + + def contains(self, x): + if isinstance(x, list) or isinstance(x, tuple): + x = np.array(x) # Promote list to array for contains check + if self.shape != x.shape: + return False + return ((x == 0) | (x == 1)).all() + + def to_jsonable(self, sample_n): + return np.array(sample_n).tolist() + + def from_jsonable(self, sample_n): + return [np.asarray(sample) for sample in sample_n] + + def __repr__(self): + return "MultiBinary({})".format(self.n) + + def __eq__(self, other): + return isinstance(other, MultiBinary) and self.n == other.n diff --git a/gym/spaces/multi_discrete.py b/gym/spaces/multi_discrete.py new file mode 100644 index 0000000000000000000000000000000000000000..4f163290d0a10846454e84a4c5244d9b6d86fd13 --- /dev/null +++ b/gym/spaces/multi_discrete.py @@ -0,0 +1,73 @@ +import numpy as np +from gym import logger +from .space import Space +from .discrete import Discrete + + +class MultiDiscrete(Space): + """ + - The multi-discrete action space consists of a series of discrete action spaces with different number of actions in each + - It is useful to represent game controllers or keyboards where each key can be represented as a discrete action space + - It is parametrized by passing an array of positive integers specifying number of actions for each discrete action space + + Note: Some environment wrappers assume a value of 0 always represents the NOOP action. + + e.g. Nintendo Game Controller + - Can be conceptualized as 3 discrete action spaces: + + 1) Arrow Keys: Discrete 5 - NOOP[0], UP[1], RIGHT[2], DOWN[3], LEFT[4] - params: min: 0, max: 4 + 2) Button A: Discrete 2 - NOOP[0], Pressed[1] - params: min: 0, max: 1 + 3) Button B: Discrete 2 - NOOP[0], Pressed[1] - params: min: 0, max: 1 + + - Can be initialized as + + MultiDiscrete([ 5, 2, 2 ]) + + """ + + def __init__(self, nvec, dtype=np.int64, seed=None): + """ + nvec: vector of counts of each categorical variable + """ + assert (np.array(nvec) > 0).all(), "nvec (counts) have to be positive" + self.nvec = np.asarray(nvec, dtype=dtype) + + super(MultiDiscrete, self).__init__(self.nvec.shape, dtype, seed) + + def sample(self): + return (self.np_random.random_sample(self.nvec.shape) * self.nvec).astype( + self.dtype + ) + + def contains(self, x): + if isinstance(x, list): + x = np.array(x) # Promote list to array for contains check + # if nvec is uint32 and space dtype is uint32, then 0 <= x < self.nvec guarantees that x + # is within correct bounds for space dtype (even though x does not have to be unsigned) + return x.shape == self.shape and (0 <= x).all() and (x < self.nvec).all() + + def to_jsonable(self, sample_n): + return [sample.tolist() for sample in sample_n] + + def from_jsonable(self, sample_n): + return np.array(sample_n) + + def __repr__(self): + return "MultiDiscrete({})".format(self.nvec) + + def __getitem__(self, index): + nvec = self.nvec[index] + if nvec.ndim == 0: + subspace = Discrete(nvec) + else: + subspace = MultiDiscrete(nvec, self.dtype) + subspace.np_random.set_state(self.np_random.get_state()) # for reproducibility + return subspace + + def __len__(self): + if self.nvec.ndim >= 2: + logger.warn("Get length of a multi-dimensional MultiDiscrete space.") + return len(self.nvec) + + def __eq__(self, other): + return isinstance(other, MultiDiscrete) and np.all(self.nvec == other.nvec) diff --git a/gym/spaces/space.py b/gym/spaces/space.py new file mode 100644 index 0000000000000000000000000000000000000000..4c077064390888285514524ad3c28d0bf901a987 --- /dev/null +++ b/gym/spaces/space.py @@ -0,0 +1,90 @@ +from gym.utils import seeding + + +class Space(object): + """Defines the observation and action spaces, so you can write generic + code that applies to any Env. For example, you can choose a random + action. + + WARNING - Custom observation & action spaces can inherit from the `Space` + class. However, most use-cases should be covered by the existing space + classes (e.g. `Box`, `Discrete`, etc...), and container classes (`Tuple` & + `Dict`). Note that parametrized probability distributions (through the + `sample()` method), and batching functions (in `gym.vector.VectorEnv`), are + only well-defined for instances of spaces provided in gym by default. + Moreover, some implementations of Reinforcement Learning algorithms might + not handle custom spaces properly. Use custom spaces with care. + """ + + def __init__(self, shape=None, dtype=None, seed=None): + import numpy as np # takes about 300-400ms to import, so we load lazily + + self._shape = None if shape is None else tuple(shape) + self.dtype = None if dtype is None else np.dtype(dtype) + self._np_random = None + if seed is not None: + self.seed(seed) + + @property + def np_random(self): + """Lazily seed the rng since this is expensive and only needed if + sampling from this space. + """ + if self._np_random is None: + self.seed() + + return self._np_random + + @property + def shape(self): + """Return the shape of the space as an immutable property""" + return self._shape + + def sample(self): + """Randomly sample an element of this space. Can be + uniform or non-uniform sampling based on boundedness of space.""" + raise NotImplementedError + + def seed(self, seed=None): + """Seed the PRNG of this space.""" + self._np_random, seed = seeding.np_random(seed) + return [seed] + + def contains(self, x): + """ + Return boolean specifying if x is a valid + member of this space + """ + raise NotImplementedError + + def __contains__(self, x): + return self.contains(x) + + def __setstate__(self, state): + # Don't mutate the original state + state = dict(state) + + # Allow for loading of legacy states. + # See: + # https://github.com/openai/gym/pull/2397 -- shape + # https://github.com/openai/gym/pull/1913 -- np_random + # + if "shape" in state: + state["_shape"] = state["shape"] + del state["shape"] + if "np_random" in state: + state["_np_random"] = state["np_random"] + del state["np_random"] + + # Update our state + self.__dict__.update(state) + + def to_jsonable(self, sample_n): + """Convert a batch of samples from this space to a JSONable data type.""" + # By default, assume identity is JSONable + return sample_n + + def from_jsonable(self, sample_n): + """Convert a JSONable data type to a batch of samples from this space.""" + # By default, assume identity is JSONable + return sample_n diff --git a/gym/spaces/tuple.py b/gym/spaces/tuple.py new file mode 100644 index 0000000000000000000000000000000000000000..bb3133a506329148a4d6c280982eb0f0d5276619 --- /dev/null +++ b/gym/spaces/tuple.py @@ -0,0 +1,92 @@ +import numpy as np +from .space import Space + + +class Tuple(Space): + """ + A tuple (i.e., product) of simpler spaces + + Example usage: + self.observation_space = spaces.Tuple((spaces.Discrete(2), spaces.Discrete(3))) + """ + + def __init__(self, spaces, seed=None): + self.spaces = spaces + for space in spaces: + assert isinstance( + space, Space + ), "Elements of the tuple must be instances of gym.Space" + super(Tuple, self).__init__(None, None, seed) + + def seed(self, seed=None): + seeds = [] + + if isinstance(seed, list): + for i, space in enumerate(self.spaces): + seeds += space.seed(seed[i]) + elif isinstance(seed, int): + seeds = super().seed(seed) + try: + subseeds = self.np_random.choice( + np.iinfo(int).max, + size=len(self.spaces), + replace=False, # unique subseed for each subspace + ) + except ValueError: + subseeds = self.np_random.choice( + np.iinfo(int).max, + size=len(self.spaces), + replace=True, # we get more than INT_MAX subspaces + ) + + for subspace, subseed in zip(self.spaces, subseeds): + seeds.append(subspace.seed(int(subseed))[0]) + elif seed is None: + for space in self.spaces: + seeds += space.seed(seed) + else: + raise TypeError("Passed seed not of an expected type: list or int or None") + + return seeds + + def sample(self): + return tuple([space.sample() for space in self.spaces]) + + def contains(self, x): + if isinstance(x, list): + x = tuple(x) # Promote list to tuple for contains check + return ( + isinstance(x, tuple) + and len(x) == len(self.spaces) + and all(space.contains(part) for (space, part) in zip(self.spaces, x)) + ) + + def __repr__(self): + return "Tuple(" + ", ".join([str(s) for s in self.spaces]) + ")" + + def to_jsonable(self, sample_n): + # serialize as list-repr of tuple of vectors + return [ + space.to_jsonable([sample[i] for sample in sample_n]) + for i, space in enumerate(self.spaces) + ] + + def from_jsonable(self, sample_n): + return [ + sample + for sample in zip( + *[ + space.from_jsonable(sample_n[i]) + for i, space in enumerate(self.spaces) + ] + ) + ] + + def __getitem__(self, index): + return self.spaces[index] + + def __len__(self): + return len(self.spaces) + + def __eq__(self, other): + return isinstance(other, Tuple) and self.spaces == other.spaces diff --git a/gym/spaces/utils.py b/gym/spaces/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ef5921753e556079c36a1c1a65632d487c4c4bbb --- /dev/null +++ b/gym/spaces/utils.py @@ -0,0 +1,224 @@ +from collections import OrderedDict +from functools import singledispatch, reduce +import numpy as np +import operator as op + +from gym.spaces import Box +from gym.spaces import Discrete +from gym.spaces import MultiDiscrete +from gym.spaces import MultiBinary +from gym.spaces import Tuple +from gym.spaces import Dict + + +@singledispatch +def flatdim(space): + """Return the number of dimensions a flattened equivalent of this space + would have. + + Accepts a space and returns an integer. Raises ``NotImplementedError`` if + the space is not defined in ``gym.spaces``. + """ + raise NotImplementedError(f"Unknown space: `{space}`") + + +@flatdim.register(Box) +@flatdim.register(MultiBinary) +def flatdim_box_multibinary(space): + return reduce(op.mul, space.shape, 1) + + +@flatdim.register(Discrete) +def flatdim_discrete(space): + return int(space.n) + + +@flatdim.register(MultiDiscrete) +def flatdim_multidiscrete(space): + return int(np.sum(space.nvec)) + + +@flatdim.register(Tuple) +def flatdim_tuple(space): + return sum([flatdim(s) for s in space.spaces]) + + +@flatdim.register(Dict) +def flatdim_dict(space): + return sum([flatdim(s) for s in space.spaces.values()]) + + +@singledispatch +def flatten(space, x): + """Flatten a data point from a space. + + This is useful when e.g. points from spaces must be passed to a neural + network, which only understands flat arrays of floats. + + Accepts a space and a point from that space. Always returns a 1D array. + Raises ``NotImplementedError`` if the space is not defined in + ``gym.spaces``. + """ + raise NotImplementedError(f"Unknown space: `{space}`") + + +@flatten.register(Box) +@flatten.register(MultiBinary) +def flatten_box_multibinary(space, x): + return np.asarray(x, dtype=space.dtype).flatten() + + +@flatten.register(Discrete) +def flatten_discrete(space, x): + onehot = np.zeros(space.n, dtype=space.dtype) + onehot[x] = 1 + return onehot + + +@flatten.register(MultiDiscrete) +def flatten_multidiscrete(space, x): + offsets = np.zeros((space.nvec.size + 1,), dtype=space.dtype) + offsets[1:] = np.cumsum(space.nvec.flatten()) + + onehot = np.zeros((offsets[-1],), dtype=space.dtype) + onehot[offsets[:-1] + x.flatten()] = 1 + return onehot + + +@flatten.register(Tuple) +def flatten_tuple(space, x): + return np.concatenate([flatten(s, x_part) for x_part, s in zip(x, space.spaces)]) + + +@flatten.register(Dict) +def flatten_dict(space, x): + return np.concatenate([flatten(s, x[key]) for key, s in space.spaces.items()]) + + +@singledispatch +def unflatten(space, x): + """Unflatten a data point from a space. + + This reverses the transformation applied by ``flatten()``. You must ensure + that the ``space`` argument is the same as for the ``flatten()`` call. + + Accepts a space and a flattened point. Returns a point with a structure + that matches the space. Raises ``NotImplementedError`` if the space is not + defined in ``gym.spaces``. + """ + raise NotImplementedError(f"Unknown space: `{space}`") + + +@unflatten.register(Box) +@unflatten.register(MultiBinary) +def unflatten_box_multibinary(space, x): + return np.asarray(x, dtype=space.dtype).reshape(space.shape) + + +@unflatten.register(Discrete) +def unflatten_discrete(space, x): + return int(np.nonzero(x)[0][0]) + + +@unflatten.register(MultiDiscrete) +def unflatten_multidiscrete(space, x): + offsets = np.zeros((space.nvec.size + 1,), dtype=space.dtype) + offsets[1:] = np.cumsum(space.nvec.flatten()) + + (indices,) = np.nonzero(x) + return np.asarray(indices - offsets[:-1], dtype=space.dtype).reshape(space.shape) + + +@unflatten.register(Tuple) +def unflatten_tuple(space, x): + dims = np.asarray([flatdim(s) for s in space.spaces], dtype=np.int_) + list_flattened = np.split(x, np.cumsum(dims[:-1])) + return tuple( + unflatten(s, flattened) for flattened, s in zip(list_flattened, space.spaces) + ) + + +@unflatten.register(Dict) +def unflatten_dict(space, x): + dims = np.asarray([flatdim(s) for s in space.spaces.values()], dtype=np.int_) + list_flattened = np.split(x, np.cumsum(dims[:-1])) + return OrderedDict( + [ + (key, unflatten(s, flattened)) + for flattened, (key, s) in zip(list_flattened, space.spaces.items()) + ] + ) + + +@singledispatch +def flatten_space(space): + """Flatten a space into a single ``Box``. + + This is equivalent to ``flatten()``, but operates on the space itself. The + result always is a `Box` with flat boundaries. The box has exactly + ``flatdim(space)`` dimensions. Flattening a sample of the original space + has the same effect as taking a sample of the flattenend space. + + Raises ``NotImplementedError`` if the space is not defined in + ``gym.spaces``. + + Example:: + + >>> box = Box(0.0, 1.0, shape=(3, 4, 5)) + >>> box + Box(3, 4, 5) + >>> flatten_space(box) + Box(60,) + >>> flatten(box, box.sample()) in flatten_space(box) + True + + Example that flattens a discrete space:: + + >>> discrete = Discrete(5) + >>> flatten_space(discrete) + Box(5,) + >>> flatten(box, box.sample()) in flatten_space(box) + True + + Example that recursively flattens a dict:: + + >>> space = Dict({"position": Discrete(2), + ... "velocity": Box(0, 1, shape=(2, 2))}) + >>> flatten_space(space) + Box(6,) + >>> flatten(space, space.sample()) in flatten_space(space) + True + """ + raise NotImplementedError(f"Unknown space: `{space}`") + + +@flatten_space.register(Box) +def flatten_space_box(space): + return Box(space.low.flatten(), space.high.flatten(), dtype=space.dtype) + + +@flatten_space.register(Discrete) +@flatten_space.register(MultiBinary) +@flatten_space.register(MultiDiscrete) +def flatten_space_binary(space): + return Box(low=0, high=1, shape=(flatdim(space),), dtype=space.dtype) + + +@flatten_space.register(Tuple) +def flatten_space_tuple(space): + space = [flatten_space(s) for s in space.spaces] + return Box( + low=np.concatenate([s.low for s in space]), + high=np.concatenate([s.high for s in space]), + dtype=np.result_type(*[s.dtype for s in space]), + ) + + +@flatten_space.register(Dict) +def flatten_space_dict(space): + space = [flatten_space(s) for s in space.spaces.values()] + return Box( + low=np.concatenate([s.low for s in space]), + high=np.concatenate([s.high for s in space]), + dtype=np.result_type(*[s.dtype for s in space]), + ) diff --git a/gym/utils/__init__.py b/gym/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e01a19841b1e3d05ecaff92398b065cb88fd8a0a --- /dev/null +++ b/gym/utils/__init__.py @@ -0,0 +1,9 @@ +"""A set of common utilities used within the environments. These are +not intended as API functions, and will not remain stable over time. +""" + +# These submodules should not have any import-time dependencies. +# We want this since we use `utils` during our import-time sanity checks +# that verify that our dependencies are actually present. +from .colorize import colorize +from .ezpickle import EzPickle diff --git a/gym/utils/__pycache__/__init__.cpython-39.pyc b/gym/utils/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..716313c7bc8c3d57a8b26bf9430bcc819be525bc Binary files /dev/null and b/gym/utils/__pycache__/__init__.cpython-39.pyc differ diff --git a/gym/utils/__pycache__/atomic_write.cpython-39.pyc b/gym/utils/__pycache__/atomic_write.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..221328155a27d38d01c30121105f700ee3f2b211 Binary files /dev/null and b/gym/utils/__pycache__/atomic_write.cpython-39.pyc differ diff --git a/gym/utils/__pycache__/closer.cpython-39.pyc b/gym/utils/__pycache__/closer.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..298d881ccd63d81589b0b7911ae5c109798a6c4f Binary files /dev/null and b/gym/utils/__pycache__/closer.cpython-39.pyc differ diff --git a/gym/utils/__pycache__/colorize.cpython-39.pyc b/gym/utils/__pycache__/colorize.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bea7563f47fa6fc910cd4170b3bac1b8edfe1cb8 Binary files /dev/null and b/gym/utils/__pycache__/colorize.cpython-39.pyc differ diff --git a/gym/utils/__pycache__/env_checker.cpython-39.pyc b/gym/utils/__pycache__/env_checker.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18c1bec74dd9b15b68b2613a5559e876d9c64aad Binary files /dev/null and b/gym/utils/__pycache__/env_checker.cpython-39.pyc differ diff --git a/gym/utils/__pycache__/ezpickle.cpython-39.pyc b/gym/utils/__pycache__/ezpickle.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddf7691ecaede033e5ea43cbeccd587b5c860071 Binary files /dev/null and b/gym/utils/__pycache__/ezpickle.cpython-39.pyc differ diff --git a/gym/utils/__pycache__/json_utils.cpython-39.pyc b/gym/utils/__pycache__/json_utils.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5aea87feb322ca305df995d2b59715f2c244a2e8 Binary files /dev/null and b/gym/utils/__pycache__/json_utils.cpython-39.pyc differ diff --git a/gym/utils/__pycache__/play.cpython-39.pyc b/gym/utils/__pycache__/play.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e504b08ea7639dc7555526edb9fa8fc7befdf742 Binary files /dev/null and b/gym/utils/__pycache__/play.cpython-39.pyc differ diff --git a/gym/utils/__pycache__/seeding.cpython-39.pyc b/gym/utils/__pycache__/seeding.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f784076cec0e3d589550b40c90e39402a60182f Binary files /dev/null and b/gym/utils/__pycache__/seeding.cpython-39.pyc differ diff --git a/gym/utils/atomic_write.py b/gym/utils/atomic_write.py new file mode 100644 index 0000000000000000000000000000000000000000..25d546de1460802cfcd78556a5a15c1036b0b099 --- /dev/null +++ b/gym/utils/atomic_write.py @@ -0,0 +1,60 @@ +# Based on http://stackoverflow.com/questions/2333872/atomic-writing-to-file-with-python + +import os +from contextlib import contextmanager + +# We would ideally atomically replace any existing file with the new +# version. However, on Windows there's no Python-only solution prior +# to Python 3.3. (This library includes a C extension to do so: +# https://pypi.python.org/pypi/pyosreplace/0.1.) +# +# Correspondingly, we make a best effort, but on Python < 3.3 use a +# replace method which could result in the file temporarily +# disappearing. +import sys + +if sys.version_info >= (3, 3): + # Python 3.3 and up have a native `replace` method + from os import replace +elif sys.platform.startswith("win"): + + def replace(src, dst): + # TODO: on Windows, this will raise if the file is in use, + # which is possible. We'll need to make this more robust over + # time. + try: + os.remove(dst) + except OSError: + pass + os.rename(src, dst) + + +else: + # POSIX rename() is always atomic + from os import rename as replace + + +@contextmanager +def atomic_write(filepath, binary=False, fsync=False): + """Writeable file object that atomically updates a file (using a temporary file). In some cases (namely Python < 3.3 on Windows), this could result in an existing file being temporarily unlinked. + + :param filepath: the file path to be opened + :param binary: whether to open the file in a binary mode instead of textual + :param fsync: whether to force write the file to disk + """ + + tmppath = filepath + "~" + while os.path.isfile(tmppath): + tmppath += "~" + try: + with open(tmppath, "wb" if binary else "w") as file: + yield file + if fsync: + file.flush() + os.fsync(file.fileno()) + replace(tmppath, filepath) + finally: + try: + os.remove(tmppath) + except (IOError, OSError): + pass diff --git a/gym/utils/closer.py b/gym/utils/closer.py new file mode 100644 index 0000000000000000000000000000000000000000..635b65f0c7c2fd29451a46d42a683d7017dfb0a8 --- /dev/null +++ b/gym/utils/closer.py @@ -0,0 +1,68 @@ +import atexit +import threading +import weakref + + +class Closer(object): + """A registry that ensures your objects get closed, whether manually, + upon garbage collection, or upon exit. To work properly, your + objects need to cooperate and do something like the following: + + ``` + closer = Closer() + class Example(object): + def __init__(self): + self._id = closer.register(self) + + def close(self): + # Probably worth making idempotent too! + ... + closer.unregister(self._id) + + def __del__(self): + self.close() + ``` + + That is, your objects should: + + - register() themselves and save the returned ID + - unregister() themselves upon close() + - include a __del__ method which close()'s the object + """ + + def __init__(self, atexit_register=True): + self.lock = threading.Lock() + self.next_id = -1 + self.closeables = weakref.WeakValueDictionary() + + if atexit_register: + atexit.register(self.close) + + def generate_next_id(self): + with self.lock: + self.next_id += 1 + return self.next_id + + def register(self, closeable): + """Registers an object with a 'close' method. + + Returns: + int: The registration ID of this object. It is the caller's responsibility to save this ID if early closing is desired. + """ + assert hasattr(closeable, "close"), "No close method for {}".format(closeable) + + next_id = self.generate_next_id() + self.closeables[next_id] = closeable + return next_id + + def unregister(self, id): + assert id is not None + if id in self.closeables: + del self.closeables[id] + + def close(self): + # Explicitly fetch all monitors first so that they can't disappear while + # we iterate. cf. http://stackoverflow.com/a/12429620 + closeables = list(self.closeables.values()) + for closeable in closeables: + closeable.close() diff --git a/gym/utils/colorize.py b/gym/utils/colorize.py new file mode 100644 index 0000000000000000000000000000000000000000..f4e4947023fd07df60feaa6549d365c920895c2b --- /dev/null +++ b/gym/utils/colorize.py @@ -0,0 +1,32 @@ +"""A set of common utilities used within the environments. These are +not intended as API functions, and will not remain stable over time. +""" + +color2num = dict( + gray=30, + red=31, + green=32, + yellow=33, + blue=34, + magenta=35, + cyan=36, + white=37, + crimson=38, +) + + +def colorize(string, color, bold=False, highlight=False): + """Return string surrounded by appropriate terminal color codes to + print colorized text. Valid colors: gray, red, green, yellow, + blue, magenta, cyan, white, crimson + """ + + attr = [] + num = color2num[color] + if highlight: + num += 10 + attr.append(str(num)) + if bold: + attr.append("1") + attrs = ";".join(attr) + return "\x1b[%sm%s\x1b[0m" % (attrs, string) diff --git a/gym/utils/env_checker.py b/gym/utils/env_checker.py new file mode 100644 index 0000000000000000000000000000000000000000..0101ad5abe24b82034ecae1f5ed220e3f7dc6e74 --- /dev/null +++ b/gym/utils/env_checker.py @@ -0,0 +1,338 @@ +""" +This file is originally from the Stable Baselines3 repository hosted on GitHub +(https://github.com/DLR-RM/stable-baselines3/) +Original Author: Antonin Raffin + +It also uses some warnings/assertions from the PettingZoo repository hosted on GitHub +(https://github.com/PettingZoo-Team/PettingZoo) +Original Author: Justin Terry + +These projects are covered by the MIT License. +""" + +from typing import Union + +import gym +import numpy as np +from gym import logger +from gym import spaces + + +def _is_numpy_array_space(space: spaces.Space) -> bool: + """ + Returns False if provided space is not representable as a single numpy array + (e.g. Dict and Tuple spaces return False) + """ + return not isinstance(space, (spaces.Dict, spaces.Tuple)) + + +def _check_image_input(observation_space: spaces.Box, key: str = "") -> None: + """ + Check that the input adheres to general standards + when the observation is apparently an image. + """ + if observation_space.dtype != np.uint8: + logger.warn( + f"It seems that your observation {key} is an image but the `dtype` " + "of your observation_space is not `np.uint8`. " + "If your observation is not an image, we recommend you to flatten the observation " + "to have only a 1D vector" + ) + + if np.any(observation_space.low != 0) or np.any(observation_space.high != 255): + logger.warn( + f"It seems that your observation space {key} is an image but the " + "upper and lower bounds are not in [0, 255]. " + "Generally, CNN policies assume observations are within that range, " + "so you may encounter an issue if the observation values are not." + ) + + +def _check_nan(env: gym.Env, check_inf: bool = True) -> None: + """Check for NaN and Inf.""" + for _ in range(10): + action = env.action_space.sample() + observation, reward, _, _ = env.step(action) + + if np.any(np.isnan(observation)): + logger.warn("Encountered NaN value in observations.") + if np.any(np.isnan(reward)): + logger.warn("Encountered NaN value in rewards.") + if check_inf and np.any(np.isinf(observation)): + logger.warn("Encountered inf value in observations.") + if check_inf and np.any(np.isinf(reward)): + logger.warn("Encountered inf value in rewards.") + + +def _check_obs( + obs: Union[tuple, dict, np.ndarray, int], + observation_space: spaces.Space, + method_name: str, +) -> None: + """ + Check that the observation returned by the environment + correspond to the declared one. + """ + if not isinstance(observation_space, spaces.Tuple): + assert not isinstance( + obs, tuple + ), f"The observation returned by the `{method_name}()` method should be a single value, not a tuple" + + # The check for a GoalEnv is done by the base class + if isinstance(observation_space, spaces.Discrete): + assert isinstance( + obs, int + ), f"The observation returned by `{method_name}()` method must be an int" + elif _is_numpy_array_space(observation_space): + assert isinstance( + obs, np.ndarray + ), f"The observation returned by `{method_name}()` method must be a numpy array" + + assert observation_space.contains( + obs + ), f"The observation returned by the `{method_name}()` method does not match the given observation space" + + +def _check_box_obs(observation_space: spaces.Box, key: str = "") -> None: + """ + Check that the observation space is correctly formatted + when dealing with a ``Box()`` space. In particular, it checks: + - that the dimensions are big enough when it is an image, and that the type matches + - that the observation has an expected shape (warn the user if not) + """ + # If image, check the low and high values, the type and the number of channels + # and the shape (minimal value) + if len(observation_space.shape) == 3: + _check_image_input(observation_space) + + if len(observation_space.shape) not in [1, 3]: + logger.warn( + f"Your observation {key} has an unconventional shape (neither an image, nor a 1D vector). " + "We recommend you to flatten the observation " + "to have only a 1D vector or use a custom policy to properly process the data." + ) + + if np.any(np.equal(observation_space.low, -np.inf)): + logger.warn( + "Agent's minimum observation space value is -infinity. This is probably too low." + ) + if np.any(np.equal(observation_space.high, np.inf)): + logger.warn( + "Agent's maxmimum observation space value is infinity. This is probably too high" + ) + if np.any(np.equal(observation_space.low, observation_space.high)): + logger.warn("Agent's maximum and minimum observation space values are equal") + if np.any(np.greater(observation_space.low, observation_space.high)): + assert False, "Agent's minimum observation value is greater than it's maximum" + if observation_space.low.shape != observation_space.shape: + assert ( + False + ), "Agent's observation_space.low and observation_space have different shapes" + if observation_space.high.shape != observation_space.shape: + assert ( + False + ), "Agent's observation_space.high and observation_space have different shapes" + + +def _check_box_action(action_space: spaces.Box): + if np.any(np.equal(action_space.low, -np.inf)): + logger.warn( + "Agent's minimum action space value is -infinity. This is probably too low." + ) + if np.any(np.equal(action_space.high, np.inf)): + logger.warn( + "Agent's maxmimum action space value is infinity. This is probably too high" + ) + if np.any(np.equal(action_space.low, action_space.high)): + logger.warn("Agent's maximum and minimum action space values are equal") + if np.any(np.greater(action_space.low, action_space.high)): + assert False, "Agent's minimum action value is greater than it's maximum" + if action_space.low.shape != action_space.shape: + assert False, "Agent's action_space.low and action_space have different shapes" + if action_space.high.shape != action_space.shape: + assert False, "Agent's action_space.high and action_space have different shapes" + + +def _check_normalized_action(action_space: spaces.Box): + if ( + np.any(np.abs(action_space.low) != np.abs(action_space.high)) + or np.any(np.abs(action_space.low) > 1) + or np.any(np.abs(action_space.high) > 1) + ): + logger.warn( + "We recommend you to use a symmetric and normalized Box action space (range=[-1, 1]) " + "cf https://stable-baselines3.readthedocs.io/en/master/guide/rl_tips.html" + ) + + +def _check_returned_values( + env: gym.Env, observation_space: spaces.Space, action_space: spaces.Space +) -> None: + """ + Check the returned values by the env when calling `.reset()` or `.step()` methods. + """ + # because env inherits from gym.Env, we assume that `reset()` and `step()` methods exists + obs = env.reset() + + if isinstance(observation_space, spaces.Dict): + assert isinstance( + obs, dict + ), "The observation returned by `reset()` must be a dictionary" + for key in observation_space.spaces.keys(): + try: + _check_obs(obs[key], observation_space.spaces[key], "reset") + except AssertionError as e: + raise AssertionError(f"Error while checking key={key}: " + str(e)) + else: + _check_obs(obs, observation_space, "reset") + + # Sample a random action + action = action_space.sample() + data = env.step(action) + + assert ( + len(data) == 4 + ), "The `step()` method must return four values: obs, reward, done, info" + + # Unpack + obs, reward, done, info = data + + if isinstance(observation_space, spaces.Dict): + assert isinstance( + obs, dict + ), "The observation returned by `step()` must be a dictionary" + for key in observation_space.spaces.keys(): + try: + _check_obs(obs[key], observation_space.spaces[key], "step") + except AssertionError as e: + raise AssertionError(f"Error while checking key={key}: " + str(e)) + + else: + _check_obs(obs, observation_space, "step") + + # We also allow int because the reward will be cast to float + assert isinstance( + reward, (float, int, np.float32) + ), "The reward returned by `step()` must be a float" + assert isinstance(done, bool), "The `done` signal must be a boolean" + assert isinstance( + info, dict + ), "The `info` returned by `step()` must be a python dictionary" + + if isinstance(env, gym.GoalEnv): + # For a GoalEnv, the keys are checked at reset + assert reward == env.compute_reward( + obs["achieved_goal"], obs["desired_goal"], info + ) + + +def _check_spaces(env: gym.Env) -> None: + """ + Check that the observation and action spaces are defined + and inherit from gym.spaces.Space. + """ + # Helper to link to the code, because gym has no proper documentation + gym_spaces = " cf https://github.com/openai/gym/blob/master/gym/spaces/" + + assert hasattr(env, "observation_space"), ( + "You must specify an observation space (cf gym.spaces)" + gym_spaces + ) + assert hasattr(env, "action_space"), ( + "You must specify an action space (cf gym.spaces)" + gym_spaces + ) + + assert isinstance(env.observation_space, spaces.Space), ( + "The observation space must inherit from gym.spaces" + gym_spaces + ) + assert isinstance(env.action_space, spaces.Space), ( + "The action space must inherit from gym.spaces" + gym_spaces + ) + + +# Check render cannot be covered by CI +def _check_render( + env: gym.Env, warn: bool = True, headless: bool = False +) -> None: # pragma: no cover + """ + Check the declared render modes and the `render()`/`close()` + method of the environment. + :param env: The environment to check + :param warn: Whether to output additional warnings + :param headless: Whether to disable render modes + that require a graphical interface. False by default. + """ + render_modes = env.metadata.get("render.modes") + if render_modes is None: + if warn: + logger.warn( + "No render modes was declared in the environment " + " (env.metadata['render.modes'] is None or not defined), " + "you may have trouble when calling `.render()`" + ) + + else: + # Don't check render mode that require a + # graphical interface (useful for CI) + if headless and "human" in render_modes: + render_modes.remove("human") + # Check all declared render modes + for render_mode in render_modes: + env.render(mode=render_mode) + env.close() + + +def check_env(env: gym.Env, warn: bool = True, skip_render_check: bool = True) -> None: + """ + Check that an environment follows Gym API. + This is particularly useful when using a custom environment. + Please take a look at https://github.com/openai/gym/blob/master/gym/core.py + for more information about the API. + It also optionally check that the environment is compatible with Stable-Baselines. + :param env: The Gym environment that will be checked + :param warn: Whether to output additional warnings + mainly related to the interaction with Stable Baselines + :param skip_render_check: Whether to skip the checks for the render method. + True by default (useful for the CI) + """ + assert isinstance( + env, gym.Env + ), "Your environment must inherit from the gym.Env class cf https://github.com/openai/gym/blob/master/gym/core.py" + + # ============= Check the spaces (observation and action) ================ + _check_spaces(env) + # Define aliases for convenience + observation_space = env.observation_space + action_space = env.action_space + try: + env.step(env.action_space.sample()) + + except AssertionError as e: + assert str(e) == "Cannot call env.step() before calling reset()" + + # Warn the user if needed. + # A warning means that the environment may run but not work properly with popular RL libraries. + if warn: + obs_spaces = ( + observation_space.spaces + if isinstance(observation_space, spaces.Dict) + else {"": observation_space} + ) + for key, space in obs_spaces.items(): + if isinstance(space, spaces.Box): + _check_box_obs(space, key) + + # Check for the action space, it may lead to hard-to-debug issues + if isinstance(action_space, spaces.Box): + _check_box_action(action_space) + _check_normalized_action(action_space) + + # ============ Check the returned values =============== + _check_returned_values(env, observation_space, action_space) + + # ==== Check the render method and the declared render modes ==== + if not skip_render_check: + _check_render(env, warn=warn) # pragma: no cover + + # The check only works with numpy arrays + if _is_numpy_array_space(observation_space) and _is_numpy_array_space(action_space): + _check_nan(env) diff --git a/gym/utils/ezpickle.py b/gym/utils/ezpickle.py new file mode 100644 index 0000000000000000000000000000000000000000..4fda27aec2a7baf40be569a641ebb0fa729abf25 --- /dev/null +++ b/gym/utils/ezpickle.py @@ -0,0 +1,33 @@ +class EzPickle(object): + """Objects that are pickled and unpickled via their constructor + arguments. + + Example usage: + + class Dog(Animal, EzPickle): + def __init__(self, furcolor, tailkind="bushy"): + Animal.__init__() + EzPickle.__init__(furcolor, tailkind) + ... + + When this object is unpickled, a new Dog will be constructed by passing the provided + furcolor and tailkind into the constructor. However, philosophers are still not sure + whether it is still the same dog. + + This is generally needed only for environments which wrap C/C++ code, such as MuJoCo + and Atari. + """ + + def __init__(self, *args, **kwargs): + self._ezpickle_args = args + self._ezpickle_kwargs = kwargs + + def __getstate__(self): + return { + "_ezpickle_args": self._ezpickle_args, + "_ezpickle_kwargs": self._ezpickle_kwargs, + } + + def __setstate__(self, d): + out = type(self)(*d["_ezpickle_args"], **d["_ezpickle_kwargs"]) + self.__dict__.update(out.__dict__) diff --git a/gym/utils/json_utils.py b/gym/utils/json_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..09c7ecdd782cc3d95ec26b0658b3b9a2f2a40a89 --- /dev/null +++ b/gym/utils/json_utils.py @@ -0,0 +1,23 @@ +import numpy as np + + +def json_encode_np(obj): + """ + JSON can't serialize numpy types, so convert to pure python + """ + if isinstance(obj, np.ndarray): + return list(obj) + elif isinstance(obj, np.float32): + return float(obj) + elif isinstance(obj, np.float64): + return float(obj) + elif isinstance(obj, np.int8): + return int(obj) + elif isinstance(obj, np.int16): + return int(obj) + elif isinstance(obj, np.int32): + return int(obj) + elif isinstance(obj, np.int64): + return int(obj) + else: + return obj diff --git a/gym/utils/play.py b/gym/utils/play.py new file mode 100644 index 0000000000000000000000000000000000000000..2e06f4a32e650a3e223c25a8da33d0b7a46d169a --- /dev/null +++ b/gym/utils/play.py @@ -0,0 +1,196 @@ +import gym +import pygame +import matplotlib +import argparse +from gym import logger + +try: + matplotlib.use("TkAgg") + import matplotlib.pyplot as plt +except ImportError as e: + logger.warn("failed to set matplotlib backend, plotting will not work: %s" % str(e)) + plt = None + +from collections import deque +from pygame.locals import VIDEORESIZE + + +def display_arr(screen, arr, video_size, transpose): + arr_min, arr_max = arr.min(), arr.max() + arr = 255.0 * (arr - arr_min) / (arr_max - arr_min) + pyg_img = pygame.surfarray.make_surface(arr.swapaxes(0, 1) if transpose else arr) + pyg_img = pygame.transform.scale(pyg_img, video_size) + screen.blit(pyg_img, (0, 0)) + + +def play(env, transpose=True, fps=30, zoom=None, callback=None, keys_to_action=None): + """Allows one to play the game using keyboard. + + To simply play the game use: + + play(gym.make("Pong-v4")) + + Above code works also if env is wrapped, so it's particularly useful in + verifying that the frame-level preprocessing does not render the game + unplayable. + + If you wish to plot real time statistics as you play, you can use + gym.utils.play.PlayPlot. Here's a sample code for plotting the reward + for last 5 second of gameplay. + + def callback(obs_t, obs_tp1, action, rew, done, info): + return [rew,] + plotter = PlayPlot(callback, 30 * 5, ["reward"]) + + env = gym.make("Pong-v4") + play(env, callback=plotter.callback) + + + Arguments + --------- + env: gym.Env + Environment to use for playing. + transpose: bool + If True the output of observation is transposed. + Defaults to true. + fps: int + Maximum number of steps of the environment to execute every second. + Defaults to 30. + zoom: float + Make screen edge this many times bigger + callback: lambda or None + Callback if a callback is provided it will be executed after + every step. It takes the following input: + obs_t: observation before performing action + obs_tp1: observation after performing action + action: action that was executed + rew: reward that was received + done: whether the environment is done or not + info: debug info + keys_to_action: dict: tuple(int) -> int or None + Mapping from keys pressed to action performed. + For example if pressed 'w' and space at the same time is supposed + to trigger action number 2 then key_to_action dict would look like this: + + { + # ... + sorted(ord('w'), ord(' ')) -> 2 + # ... + } + If None, default key_to_action mapping for that env is used, if provided. + """ + env.reset() + rendered = env.render(mode="rgb_array") + + if keys_to_action is None: + if hasattr(env, "get_keys_to_action"): + keys_to_action = env.get_keys_to_action() + elif hasattr(env.unwrapped, "get_keys_to_action"): + keys_to_action = env.unwrapped.get_keys_to_action() + else: + assert False, ( + env.spec.id + + " does not have explicit key to action mapping, " + + "please specify one manually" + ) + relevant_keys = set(sum(map(list, keys_to_action.keys()), [])) + + video_size = [rendered.shape[1], rendered.shape[0]] + if zoom is not None: + video_size = int(video_size[0] * zoom), int(video_size[1] * zoom) + + pressed_keys = [] + running = True + env_done = True + + screen = pygame.display.set_mode(video_size) + clock = pygame.time.Clock() + + while running: + if env_done: + env_done = False + obs = env.reset() + else: + action = keys_to_action.get(tuple(sorted(pressed_keys)), 0) + prev_obs = obs + obs, rew, env_done, info = env.step(action) + if callback is not None: + callback(prev_obs, obs, action, rew, env_done, info) + if obs is not None: + rendered = env.render(mode="rgb_array") + display_arr(screen, rendered, transpose=transpose, video_size=video_size) + + # process pygame events + for event in pygame.event.get(): + # test events, set key states + if event.type == pygame.KEYDOWN: + if event.key in relevant_keys: + pressed_keys.append(event.key) + elif event.key == 27: + running = False + elif event.type == pygame.KEYUP: + if event.key in relevant_keys: + pressed_keys.remove(event.key) + elif event.type == pygame.QUIT: + running = False + elif event.type == VIDEORESIZE: + video_size = event.size + screen = pygame.display.set_mode(video_size) + print(video_size) + + pygame.display.flip() + clock.tick(fps) + pygame.quit() + + +class PlayPlot(object): + def __init__(self, callback, horizon_timesteps, plot_names): + self.data_callback = callback + self.horizon_timesteps = horizon_timesteps + self.plot_names = plot_names + + assert plt is not None, "matplotlib backend failed, plotting will not work" + + num_plots = len(self.plot_names) + self.fig, self.ax = plt.subplots(num_plots) + if num_plots == 1: + self.ax = [self.ax] + for axis, name in zip(self.ax, plot_names): + axis.set_title(name) + self.t = 0 + self.cur_plot = [None for _ in range(num_plots)] + self.data = [deque(maxlen=horizon_timesteps) for _ in range(num_plots)] + + def callback(self, obs_t, obs_tp1, action, rew, done, info): + points = self.data_callback(obs_t, obs_tp1, action, rew, done, info) + for point, data_series in zip(points, self.data): + data_series.append(point) + self.t += 1 + + xmin, xmax = max(0, self.t - self.horizon_timesteps), self.t + + for i, plot in enumerate(self.cur_plot): + if plot is not None: + plot.remove() + self.cur_plot[i] = self.ax[i].scatter( + range(xmin, xmax), list(self.data[i]), c="blue" + ) + self.ax[i].set_xlim(xmin, xmax) + plt.pause(0.000001) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument( + "--env", + type=str, + default="MontezumaRevengeNoFrameskip-v4", + help="Define Environment", + ) + args = parser.parse_args() + env = gym.make(args.env) + play(env, zoom=4, fps=60) + + +if __name__ == "__main__": + main() diff --git a/gym/utils/seeding.py b/gym/utils/seeding.py new file mode 100644 index 0000000000000000000000000000000000000000..d7726b01f0935b4fbba0c2372f88fcbb4333f105 --- /dev/null +++ b/gym/utils/seeding.py @@ -0,0 +1,97 @@ +import hashlib +import numpy as np +import os +import random as _random +import struct +import sys + +from gym import error + + +def np_random(seed=None): + if seed is not None and not (isinstance(seed, int) and 0 <= seed): + raise error.Error( + "Seed must be a non-negative integer or omitted, not {}".format(seed) + ) + + seed = create_seed(seed) + + rng = np.random.RandomState() + rng.seed(_int_list_from_bigint(hash_seed(seed))) + return rng, seed + + +def hash_seed(seed=None, max_bytes=8): + """Any given evaluation is likely to have many PRNG's active at + once. (Most commonly, because the environment is running in + multiple processes.) There's literature indicating that having + linear correlations between seeds of multiple PRNG's can correlate + the outputs: + + http://blogs.unity3d.com/2015/01/07/a-primer-on-repeatable-random-numbers/ + http://stackoverflow.com/questions/1554958/how-different-do-random-seeds-need-to-be + http://dl.acm.org/citation.cfm?id=1276928 + + Thus, for sanity we hash the seeds before using them. (This scheme + is likely not crypto-strength, but it should be good enough to get + rid of simple correlations.) + + Args: + seed (Optional[int]): None seeds from an operating system specific randomness source. + max_bytes: Maximum number of bytes to use in the hashed seed. + """ + if seed is None: + seed = create_seed(max_bytes=max_bytes) + hash = hashlib.sha512(str(seed).encode("utf8")).digest() + return _bigint_from_bytes(hash[:max_bytes]) + + +def create_seed(a=None, max_bytes=8): + """Create a strong random seed. Otherwise, Python 2 would seed using + the system time, which might be non-robust especially in the + presence of concurrency. + + Args: + a (Optional[int, str]): None seeds from an operating system specific randomness source. + max_bytes: Maximum number of bytes to use in the seed. + """ + # Adapted from https://svn.python.org/projects/python/tags/r32/Lib/random.py + if a is None: + a = _bigint_from_bytes(os.urandom(max_bytes)) + elif isinstance(a, str): + a = a.encode("utf8") + a += hashlib.sha512(a).digest() + a = _bigint_from_bytes(a[:max_bytes]) + elif isinstance(a, int): + a = a % 2 ** (8 * max_bytes) + else: + raise error.Error("Invalid type for seed: {} ({})".format(type(a), a)) + + return a + + +# TODO: don't hardcode sizeof_int here +def _bigint_from_bytes(bytes): + sizeof_int = 4 + padding = sizeof_int - len(bytes) % sizeof_int + bytes += b"\0" * padding + int_count = int(len(bytes) / sizeof_int) + unpacked = struct.unpack("{}I".format(int_count), bytes) + accum = 0 + for i, val in enumerate(unpacked): + accum += 2 ** (sizeof_int * 8 * i) * val + return accum + + +def _int_list_from_bigint(bigint): + # Special case 0 + if bigint < 0: + raise error.Error("Seed must be non-negative, not {}".format(bigint)) + elif bigint == 0: + return [0] + + ints = [] + while bigint > 0: + bigint, mod = divmod(bigint, 2 ** 32) + ints.append(mod) + return ints diff --git a/gym/vector/__init__.py b/gym/vector/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c42a25caf4f02e32619362c999454b60a29e82f1 --- /dev/null +++ b/gym/vector/__init__.py @@ -0,0 +1,66 @@ +try: + from collections.abc import Iterable +except ImportError: + Iterable = (tuple, list) + +from gym.vector.async_vector_env import AsyncVectorEnv +from gym.vector.sync_vector_env import SyncVectorEnv +from gym.vector.vector_env import VectorEnv, VectorEnvWrapper + +__all__ = ["AsyncVectorEnv", "SyncVectorEnv", "VectorEnv", "VectorEnvWrapper", "make"] + + +def make(id, num_envs=1, asynchronous=True, wrappers=None, **kwargs): + """Create a vectorized environment from multiple copies of an environment, + from its id + + Parameters + ---------- + id : str + The environment ID. This must be a valid ID from the registry. + + num_envs : int + Number of copies of the environment. + + asynchronous : bool (default: `True`) + If `True`, wraps the environments in an `AsyncVectorEnv` (which uses + `multiprocessing` to run the environments in parallel). If `False`, + wraps the environments in a `SyncVectorEnv`. + + wrappers : Callable or Iterable of Callables (default: `None`) + If not `None`, then apply the wrappers to each internal + environment during creation. + + Returns + ------- + env : `gym.vector.VectorEnv` instance + The vectorized environment. + + Example + ------- + >>> import gym + >>> env = gym.vector.make('CartPole-v1', 3) + >>> env.reset() + array([[-0.04456399, 0.04653909, 0.01326909, -0.02099827], + [ 0.03073904, 0.00145001, -0.03088818, -0.03131252], + [ 0.03468829, 0.01500225, 0.01230312, 0.01825218]], + dtype=float32) + """ + from gym.envs import make as make_ + + def _make_env(): + env = make_(id, **kwargs) + if wrappers is not None: + if callable(wrappers): + env = wrappers(env) + elif isinstance(wrappers, Iterable) and all( + [callable(w) for w in wrappers] + ): + for wrapper in wrappers: + env = wrapper(env) + else: + raise NotImplementedError + return env + + env_fns = [_make_env for _ in range(num_envs)] + return AsyncVectorEnv(env_fns) if asynchronous else SyncVectorEnv(env_fns) diff --git a/gym/vector/__pycache__/__init__.cpython-39.pyc b/gym/vector/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9baa31d23cc6381c9d9ff9a746dce072e49199a Binary files /dev/null and b/gym/vector/__pycache__/__init__.cpython-39.pyc differ diff --git a/gym/vector/__pycache__/async_vector_env.cpython-39.pyc b/gym/vector/__pycache__/async_vector_env.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63828902b246ae34fec50f96204770e712c04f7a Binary files /dev/null and b/gym/vector/__pycache__/async_vector_env.cpython-39.pyc differ diff --git a/gym/vector/__pycache__/sync_vector_env.cpython-39.pyc b/gym/vector/__pycache__/sync_vector_env.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e799bb58bf3ac7fdca517f837355cdd37c013999 Binary files /dev/null and b/gym/vector/__pycache__/sync_vector_env.cpython-39.pyc differ diff --git a/gym/vector/__pycache__/vector_env.cpython-39.pyc b/gym/vector/__pycache__/vector_env.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b72cdced9e5e83b0c2c0e79150e5caedfeb3ac68 Binary files /dev/null and b/gym/vector/__pycache__/vector_env.cpython-39.pyc differ diff --git a/gym/vector/async_vector_env.py b/gym/vector/async_vector_env.py new file mode 100644 index 0000000000000000000000000000000000000000..331dfcd5568deb3f92018331c2ca4e465cfe763b --- /dev/null +++ b/gym/vector/async_vector_env.py @@ -0,0 +1,479 @@ +import numpy as np +import multiprocessing as mp +import time +import sys +from enum import Enum +from copy import deepcopy + +from gym import logger +from gym.vector.vector_env import VectorEnv +from gym.error import ( + AlreadyPendingCallError, + NoAsyncCallError, + ClosedEnvironmentError, + CustomSpaceError, +) +from gym.vector.utils import ( + create_shared_memory, + create_empty_array, + write_to_shared_memory, + read_from_shared_memory, + concatenate, + CloudpickleWrapper, + clear_mpi_env_vars, +) + +__all__ = ["AsyncVectorEnv"] + + +class AsyncState(Enum): + DEFAULT = "default" + WAITING_RESET = "reset" + WAITING_STEP = "step" + + +class AsyncVectorEnv(VectorEnv): + """Vectorized environment that runs multiple environments in parallel. It + uses `multiprocessing` processes, and pipes for communication. + + Parameters + ---------- + env_fns : iterable of callable + Functions that create the environments. + + observation_space : `gym.spaces.Space` instance, optional + Observation space of a single environment. If `None`, then the + observation space of the first environment is taken. + + action_space : `gym.spaces.Space` instance, optional + Action space of a single environment. If `None`, then the action space + of the first environment is taken. + + shared_memory : bool (default: `True`) + If `True`, then the observations from the worker processes are + communicated back through shared variables. This can improve the + efficiency if the observations are large (e.g. images). + + copy : bool (default: `True`) + If `True`, then the `reset` and `step` methods return a copy of the + observations. + + context : str, optional + Context for multiprocessing. If `None`, then the default context is used. + Only available in Python 3. + + daemon : bool (default: `True`) + If `True`, then subprocesses have `daemon` flag turned on; that is, they + will quit if the head process quits. However, `daemon=True` prevents + subprocesses to spawn children, so for some environments you may want + to have it set to `False` + + worker : function, optional + WARNING - advanced mode option! If set, then use that worker in a subprocess + instead of a default one. Can be useful to override some inner vector env + logic, for instance, how resets on done are handled. Provides high + degree of flexibility and a high chance to shoot yourself in the foot; thus, + if you are writing your own worker, it is recommended to start from the code + for `_worker` (or `_worker_shared_memory`) method below, and add changes + """ + + def __init__( + self, + env_fns, + observation_space=None, + action_space=None, + shared_memory=True, + copy=True, + context=None, + daemon=True, + worker=None, + ): + ctx = mp.get_context(context) + self.env_fns = env_fns + self.shared_memory = shared_memory + self.copy = copy + dummy_env = env_fns[0]() + self.metadata = dummy_env.metadata + + if (observation_space is None) or (action_space is None): + observation_space = observation_space or dummy_env.observation_space + action_space = action_space or dummy_env.action_space + dummy_env.close() + del dummy_env + super(AsyncVectorEnv, self).__init__( + num_envs=len(env_fns), + observation_space=observation_space, + action_space=action_space, + ) + + if self.shared_memory: + try: + _obs_buffer = create_shared_memory( + self.single_observation_space, n=self.num_envs, ctx=ctx + ) + self.observations = read_from_shared_memory( + _obs_buffer, self.single_observation_space, n=self.num_envs + ) + except CustomSpaceError: + raise ValueError( + "Using `shared_memory=True` in `AsyncVectorEnv` " + "is incompatible with non-standard Gym observation spaces " + "(i.e. custom spaces inheriting from `gym.Space`), and is " + "only compatible with default Gym spaces (e.g. `Box`, " + "`Tuple`, `Dict`) for batching. Set `shared_memory=False` " + "if you use custom observation spaces." + ) + else: + _obs_buffer = None + self.observations = create_empty_array( + self.single_observation_space, n=self.num_envs, fn=np.zeros + ) + + self.parent_pipes, self.processes = [], [] + self.error_queue = ctx.Queue() + target = _worker_shared_memory if self.shared_memory else _worker + target = worker or target + with clear_mpi_env_vars(): + for idx, env_fn in enumerate(self.env_fns): + parent_pipe, child_pipe = ctx.Pipe() + process = ctx.Process( + target=target, + name="Worker<{0}>-{1}".format(type(self).__name__, idx), + args=( + idx, + CloudpickleWrapper(env_fn), + child_pipe, + parent_pipe, + _obs_buffer, + self.error_queue, + ), + ) + + self.parent_pipes.append(parent_pipe) + self.processes.append(process) + + process.daemon = daemon + process.start() + child_pipe.close() + + self._state = AsyncState.DEFAULT + self._check_observation_spaces() + + def seed(self, seeds=None): + self._assert_is_running() + if seeds is None: + seeds = [None for _ in range(self.num_envs)] + if isinstance(seeds, int): + seeds = [seeds + i for i in range(self.num_envs)] + assert len(seeds) == self.num_envs + + if self._state != AsyncState.DEFAULT: + raise AlreadyPendingCallError( + "Calling `seed` while waiting " + "for a pending call to `{0}` to complete.".format(self._state.value), + self._state.value, + ) + + for pipe, seed in zip(self.parent_pipes, seeds): + pipe.send(("seed", seed)) + _, successes = zip(*[pipe.recv() for pipe in self.parent_pipes]) + self._raise_if_errors(successes) + + def reset_async(self): + self._assert_is_running() + if self._state != AsyncState.DEFAULT: + raise AlreadyPendingCallError( + "Calling `reset_async` while waiting " + "for a pending call to `{0}` to complete".format(self._state.value), + self._state.value, + ) + + for pipe in self.parent_pipes: + pipe.send(("reset", None)) + self._state = AsyncState.WAITING_RESET + + def reset_wait(self, timeout=None): + """ + Parameters + ---------- + timeout : int or float, optional + Number of seconds before the call to `reset_wait` times out. If + `None`, the call to `reset_wait` never times out. + + Returns + ------- + observations : sample from `observation_space` + A batch of observations from the vectorized environment. + """ + self._assert_is_running() + if self._state != AsyncState.WAITING_RESET: + raise NoAsyncCallError( + "Calling `reset_wait` without any prior " "call to `reset_async`.", + AsyncState.WAITING_RESET.value, + ) + + if not self._poll(timeout): + self._state = AsyncState.DEFAULT + raise mp.TimeoutError( + "The call to `reset_wait` has timed out after " + "{0} second{1}.".format(timeout, "s" if timeout > 1 else "") + ) + + results, successes = zip(*[pipe.recv() for pipe in self.parent_pipes]) + self._raise_if_errors(successes) + self._state = AsyncState.DEFAULT + + if not self.shared_memory: + self.observations = concatenate( + results, self.observations, self.single_observation_space + ) + + return deepcopy(self.observations) if self.copy else self.observations + + def step_async(self, actions): + """ + Parameters + ---------- + actions : iterable of samples from `action_space` + List of actions. + """ + self._assert_is_running() + if self._state != AsyncState.DEFAULT: + raise AlreadyPendingCallError( + "Calling `step_async` while waiting " + "for a pending call to `{0}` to complete.".format(self._state.value), + self._state.value, + ) + + for pipe, action in zip(self.parent_pipes, actions): + pipe.send(("step", action)) + self._state = AsyncState.WAITING_STEP + + def step_wait(self, timeout=None): + """ + Parameters + ---------- + timeout : int or float, optional + Number of seconds before the call to `step_wait` times out. If + `None`, the call to `step_wait` never times out. + + Returns + ------- + observations : sample from `observation_space` + A batch of observations from the vectorized environment. + + rewards : `np.ndarray` instance (dtype `np.float_`) + A vector of rewards from the vectorized environment. + + dones : `np.ndarray` instance (dtype `np.bool_`) + A vector whose entries indicate whether the episode has ended. + + infos : list of dict + A list of auxiliary diagnostic information. + """ + self._assert_is_running() + if self._state != AsyncState.WAITING_STEP: + raise NoAsyncCallError( + "Calling `step_wait` without any prior call " "to `step_async`.", + AsyncState.WAITING_STEP.value, + ) + + if not self._poll(timeout): + self._state = AsyncState.DEFAULT + raise mp.TimeoutError( + "The call to `step_wait` has timed out after " + "{0} second{1}.".format(timeout, "s" if timeout > 1 else "") + ) + + results, successes = zip(*[pipe.recv() for pipe in self.parent_pipes]) + self._raise_if_errors(successes) + self._state = AsyncState.DEFAULT + observations_list, rewards, dones, infos = zip(*results) + + if not self.shared_memory: + self.observations = concatenate( + observations_list, self.observations, self.single_observation_space + ) + + return ( + deepcopy(self.observations) if self.copy else self.observations, + np.array(rewards), + np.array(dones, dtype=np.bool_), + infos, + ) + + def close_extras(self, timeout=None, terminate=False): + """ + Parameters + ---------- + timeout : int or float, optional + Number of seconds before the call to `close` times out. If `None`, + the call to `close` never times out. If the call to `close` times + out, then all processes are terminated. + + terminate : bool (default: `False`) + If `True`, then the `close` operation is forced and all processes + are terminated. + """ + timeout = 0 if terminate else timeout + try: + if self._state != AsyncState.DEFAULT: + logger.warn( + "Calling `close` while waiting for a pending " + "call to `{0}` to complete.".format(self._state.value) + ) + function = getattr(self, "{0}_wait".format(self._state.value)) + function(timeout) + except mp.TimeoutError: + terminate = True + + if terminate: + for process in self.processes: + if process.is_alive(): + process.terminate() + else: + for pipe in self.parent_pipes: + if (pipe is not None) and (not pipe.closed): + pipe.send(("close", None)) + for pipe in self.parent_pipes: + if (pipe is not None) and (not pipe.closed): + pipe.recv() + + for pipe in self.parent_pipes: + if pipe is not None: + pipe.close() + for process in self.processes: + process.join() + + def _poll(self, timeout=None): + self._assert_is_running() + if timeout is None: + return True + end_time = time.perf_counter() + timeout + delta = None + for pipe in self.parent_pipes: + delta = max(end_time - time.perf_counter(), 0) + if pipe is None: + return False + if pipe.closed or (not pipe.poll(delta)): + return False + return True + + def _check_observation_spaces(self): + self._assert_is_running() + for pipe in self.parent_pipes: + pipe.send(("_check_observation_space", self.single_observation_space)) + same_spaces, successes = zip(*[pipe.recv() for pipe in self.parent_pipes]) + self._raise_if_errors(successes) + if not all(same_spaces): + raise RuntimeError( + "Some environments have an observation space " + "different from `{0}`. In order to batch observations, the " + "observation spaces from all environments must be " + "equal.".format(self.single_observation_space) + ) + + def _assert_is_running(self): + if self.closed: + raise ClosedEnvironmentError( + "Trying to operate on `{0}`, after a " + "call to `close()`.".format(type(self).__name__) + ) + + def _raise_if_errors(self, successes): + if all(successes): + return + + num_errors = self.num_envs - sum(successes) + assert num_errors > 0 + for _ in range(num_errors): + index, exctype, value = self.error_queue.get() + logger.error( + "Received the following error from Worker-{0}: " + "{1}: {2}".format(index, exctype.__name__, value) + ) + logger.error("Shutting down Worker-{0}.".format(index)) + self.parent_pipes[index].close() + self.parent_pipes[index] = None + + logger.error("Raising the last exception back to the main process.") + raise exctype(value) + + +def _worker(index, env_fn, pipe, parent_pipe, shared_memory, error_queue): + assert shared_memory is None + env = env_fn() + parent_pipe.close() + try: + while True: + command, data = pipe.recv() + if command == "reset": + observation = env.reset() + pipe.send((observation, True)) + elif command == "step": + observation, reward, done, info = env.step(data) + if done: + observation = env.reset() + pipe.send(((observation, reward, done, info), True)) + elif command == "seed": + env.seed(data) + pipe.send((None, True)) + elif command == "close": + pipe.send((None, True)) + break + elif command == "_check_observation_space": + pipe.send((data == env.observation_space, True)) + else: + raise RuntimeError( + "Received unknown command `{0}`. Must " + "be one of {`reset`, `step`, `seed`, `close`, " + "`_check_observation_space`}.".format(command) + ) + except (KeyboardInterrupt, Exception): + error_queue.put((index,) + sys.exc_info()[:2]) + pipe.send((None, False)) + finally: + env.close() + + +def _worker_shared_memory(index, env_fn, pipe, parent_pipe, shared_memory, error_queue): + assert shared_memory is not None + env = env_fn() + observation_space = env.observation_space + parent_pipe.close() + try: + while True: + command, data = pipe.recv() + if command == "reset": + observation = env.reset() + write_to_shared_memory( + index, observation, shared_memory, observation_space + ) + pipe.send((None, True)) + elif command == "step": + observation, reward, done, info = env.step(data) + if done: + observation = env.reset() + write_to_shared_memory( + index, observation, shared_memory, observation_space + ) + pipe.send(((None, reward, done, info), True)) + elif command == "seed": + env.seed(data) + pipe.send((None, True)) + elif command == "close": + pipe.send((None, True)) + break + elif command == "_check_observation_space": + pipe.send((data == observation_space, True)) + else: + raise RuntimeError( + "Received unknown command `{0}`. Must " + "be one of {`reset`, `step`, `seed`, `close`, " + "`_check_observation_space`}.".format(command) + ) + except (KeyboardInterrupt, Exception): + error_queue.put((index,) + sys.exc_info()[:2]) + pipe.send((None, False)) + finally: + env.close() diff --git a/gym/vector/sync_vector_env.py b/gym/vector/sync_vector_env.py new file mode 100644 index 0000000000000000000000000000000000000000..068022c56a0c866697d2eccda379bbc124f49aa6 --- /dev/null +++ b/gym/vector/sync_vector_env.py @@ -0,0 +1,113 @@ +import numpy as np +from copy import deepcopy + +from gym import logger +from gym.vector.vector_env import VectorEnv +from gym.vector.utils import concatenate, create_empty_array + +__all__ = ["SyncVectorEnv"] + + +class SyncVectorEnv(VectorEnv): + """Vectorized environment that serially runs multiple environments. + + Parameters + ---------- + env_fns : iterable of callable + Functions that create the environments. + + observation_space : `gym.spaces.Space` instance, optional + Observation space of a single environment. If `None`, then the + observation space of the first environment is taken. + + action_space : `gym.spaces.Space` instance, optional + Action space of a single environment. If `None`, then the action space + of the first environment is taken. + + copy : bool (default: `True`) + If `True`, then the `reset` and `step` methods return a copy of the + observations. + """ + + def __init__(self, env_fns, observation_space=None, action_space=None, copy=True): + self.env_fns = env_fns + self.envs = [env_fn() for env_fn in env_fns] + self.copy = copy + self.metadata = self.envs[0].metadata + + if (observation_space is None) or (action_space is None): + observation_space = observation_space or self.envs[0].observation_space + action_space = action_space or self.envs[0].action_space + super(SyncVectorEnv, self).__init__( + num_envs=len(env_fns), + observation_space=observation_space, + action_space=action_space, + ) + + self._check_observation_spaces() + self.observations = create_empty_array( + self.single_observation_space, n=self.num_envs, fn=np.zeros + ) + self._rewards = np.zeros((self.num_envs,), dtype=np.float64) + self._dones = np.zeros((self.num_envs,), dtype=np.bool_) + self._actions = None + + def seed(self, seeds=None): + if seeds is None: + seeds = [None for _ in range(self.num_envs)] + if isinstance(seeds, int): + seeds = [seeds + i for i in range(self.num_envs)] + assert len(seeds) == self.num_envs + + for env, seed in zip(self.envs, seeds): + env.seed(seed) + + def reset_wait(self): + self._dones[:] = False + observations = [] + for env in self.envs: + observation = env.reset() + observations.append(observation) + self.observations = concatenate( + observations, self.observations, self.single_observation_space + ) + + return deepcopy(self.observations) if self.copy else self.observations + + def step_async(self, actions): + self._actions = actions + + def step_wait(self): + observations, infos = [], [] + for i, (env, action) in enumerate(zip(self.envs, self._actions)): + observation, self._rewards[i], self._dones[i], info = env.step(action) + if self._dones[i]: + observation = env.reset() + observations.append(observation) + infos.append(info) + self.observations = concatenate( + observations, self.observations, self.single_observation_space + ) + + return ( + deepcopy(self.observations) if self.copy else self.observations, + np.copy(self._rewards), + np.copy(self._dones), + infos, + ) + + def close_extras(self, **kwargs): + [env.close() for env in self.envs] + + def _check_observation_spaces(self): + for env in self.envs: + if not (env.observation_space == self.single_observation_space): + break + else: + return True + raise RuntimeError( + "Some environments have an observation space " + "different from `{0}`. In order to batch observations, the " + "observation spaces from all environments must be " + "equal.".format(self.single_observation_space) + ) diff --git a/gym/vector/utils/__init__.py b/gym/vector/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe57d38d891028bf47d5ad8c9e2f23069873724c --- /dev/null +++ b/gym/vector/utils/__init__.py @@ -0,0 +1,20 @@ +from gym.vector.utils.misc import CloudpickleWrapper, clear_mpi_env_vars +from gym.vector.utils.numpy_utils import concatenate, create_empty_array +from gym.vector.utils.shared_memory import ( + create_shared_memory, + read_from_shared_memory, + write_to_shared_memory, +) +from gym.vector.utils.spaces import _BaseGymSpaces, batch_space + +__all__ = [ + "CloudpickleWrapper", + "clear_mpi_env_vars", + "concatenate", + "create_empty_array", + "create_shared_memory", + "read_from_shared_memory", + "write_to_shared_memory", + "_BaseGymSpaces", + "batch_space", +] diff --git a/gym/vector/utils/__pycache__/__init__.cpython-39.pyc b/gym/vector/utils/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d5368e7be519a1d2d5ccd7a9a743359b0925c36 Binary files /dev/null and b/gym/vector/utils/__pycache__/__init__.cpython-39.pyc differ diff --git a/gym/vector/utils/__pycache__/misc.cpython-39.pyc b/gym/vector/utils/__pycache__/misc.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c7e7f56351eaeffc2baca420545ac9f884909dd Binary files /dev/null and b/gym/vector/utils/__pycache__/misc.cpython-39.pyc differ diff --git a/gym/vector/utils/__pycache__/numpy_utils.cpython-39.pyc b/gym/vector/utils/__pycache__/numpy_utils.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b31fea5f404fe85249cc16b1171a74173ad5d70 Binary files /dev/null and b/gym/vector/utils/__pycache__/numpy_utils.cpython-39.pyc differ diff --git a/gym/vector/utils/__pycache__/shared_memory.cpython-39.pyc b/gym/vector/utils/__pycache__/shared_memory.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1c766075b07d7e2cd3ec56444b416e9195c7ff9 Binary files /dev/null and b/gym/vector/utils/__pycache__/shared_memory.cpython-39.pyc differ diff --git a/gym/vector/utils/__pycache__/spaces.cpython-39.pyc b/gym/vector/utils/__pycache__/spaces.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94672b65e9f8f44bb0d9e4ca39e4feaa7c010b61 Binary files /dev/null and b/gym/vector/utils/__pycache__/spaces.cpython-39.pyc differ diff --git a/gym/vector/utils/misc.py b/gym/vector/utils/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..aa38253dabf1aadebbe89243d2888fd3fa290948 --- /dev/null +++ b/gym/vector/utils/misc.py @@ -0,0 +1,44 @@ +import contextlib +import os + +__all__ = ["CloudpickleWrapper", "clear_mpi_env_vars"] + + +class CloudpickleWrapper(object): + def __init__(self, fn): + self.fn = fn + + def __getstate__(self): + import cloudpickle + + return cloudpickle.dumps(self.fn) + + def __setstate__(self, ob): + import pickle + + self.fn = pickle.loads(ob) + + def __call__(self): + return self.fn() + + +@contextlib.contextmanager +def clear_mpi_env_vars(): + """ + `from mpi4py import MPI` will call `MPI_Init` by default. If the child + process has MPI environment variables, MPI will think that the child process + is an MPI process just like the parent and do bad things such as hang. + + This context manager is a hacky way to clear those environment variables + temporarily such as when we are starting multiprocessing Processes. + """ + removed_environment = {} + for k, v in list(os.environ.items()): + for prefix in ["OMPI_", "PMI_"]: + if k.startswith(prefix): + removed_environment[k] = v + del os.environ[k] + try: + yield + finally: + os.environ.update(removed_environment) diff --git a/gym/vector/utils/numpy_utils.py b/gym/vector/utils/numpy_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2465ab24946e243d2f18084c9a38bbd30d51cdde --- /dev/null +++ b/gym/vector/utils/numpy_utils.py @@ -0,0 +1,146 @@ +import numpy as np + +from gym.spaces import Space, Tuple, Dict +from gym.vector.utils.spaces import _BaseGymSpaces +from collections import OrderedDict + +__all__ = ["concatenate", "create_empty_array"] + + +def concatenate(items, out, space): + """Concatenate multiple samples from space into a single object. + + Parameters + ---------- + items : iterable of samples of `space` + Samples to be concatenated. + + out : tuple, dict, or `np.ndarray` + The output object. This object is a (possibly nested) numpy array. + + space : `gym.spaces.Space` instance + Observation space of a single environment in the vectorized environment. + + Returns + ------- + out : tuple, dict, or `np.ndarray` + The output object. This object is a (possibly nested) numpy array. + + Example + ------- + >>> from gym.spaces import Box + >>> space = Box(low=0, high=1, shape=(3,), dtype=np.float32) + >>> out = np.zeros((2, 3), dtype=np.float32) + >>> items = [space.sample() for _ in range(2)] + >>> concatenate(items, out, space) + array([[0.6348213 , 0.28607962, 0.60760117], + [0.87383074, 0.192658 , 0.2148103 ]], dtype=float32) + """ + assert isinstance(items, (list, tuple)) + if isinstance(space, _BaseGymSpaces): + return concatenate_base(items, out, space) + elif isinstance(space, Tuple): + return concatenate_tuple(items, out, space) + elif isinstance(space, Dict): + return concatenate_dict(items, out, space) + elif isinstance(space, Space): + return concatenate_custom(items, out, space) + else: + raise ValueError( + "Space of type `{0}` is not a valid `gym.Space` " + "instance.".format(type(space)) + ) + + +def concatenate_base(items, out, space): + return np.stack(items, axis=0, out=out) + + +def concatenate_tuple(items, out, space): + return tuple( + concatenate([item[i] for item in items], out[i], subspace) + for (i, subspace) in enumerate(space.spaces) + ) + + +def concatenate_dict(items, out, space): + return OrderedDict( + [ + (key, concatenate([item[key] for item in items], out[key], subspace)) + for (key, subspace) in space.spaces.items() + ] + ) + + +def concatenate_custom(items, out, space): + return tuple(items) + + +def create_empty_array(space, n=1, fn=np.zeros): + """Create an empty (possibly nested) numpy array. + + Parameters + ---------- + space : `gym.spaces.Space` instance + Observation space of a single environment in the vectorized environment. + + n : int + Number of environments in the vectorized environment. If `None`, creates + an empty sample from `space`. + + fn : callable + Function to apply when creating the empty numpy array. Examples of such + functions are `np.empty` or `np.zeros`. + + Returns + ------- + out : tuple, dict, or `np.ndarray` + The output object. This object is a (possibly nested) numpy array. + + Example + ------- + >>> from gym.spaces import Box, Dict + >>> space = Dict({ + ... 'position': Box(low=0, high=1, shape=(3,), dtype=np.float32), + ... 'velocity': Box(low=0, high=1, shape=(2,), dtype=np.float32)}) + >>> create_empty_array(space, n=2, fn=np.zeros) + OrderedDict([('position', array([[0., 0., 0.], + [0., 0., 0.]], dtype=float32)), + ('velocity', array([[0., 0.], + [0., 0.]], dtype=float32))]) + """ + if isinstance(space, _BaseGymSpaces): + return create_empty_array_base(space, n=n, fn=fn) + elif isinstance(space, Tuple): + return create_empty_array_tuple(space, n=n, fn=fn) + elif isinstance(space, Dict): + return create_empty_array_dict(space, n=n, fn=fn) + elif isinstance(space, Space): + return create_empty_array_custom(space, n=n, fn=fn) + else: + raise ValueError( + "Space of type `{0}` is not a valid `gym.Space` " + "instance.".format(type(space)) + ) + + +def create_empty_array_base(space, n=1, fn=np.zeros): + shape = space.shape if (n is None) else (n,) + space.shape + return fn(shape, dtype=space.dtype) + + +def create_empty_array_tuple(space, n=1, fn=np.zeros): + return tuple(create_empty_array(subspace, n=n, fn=fn) for subspace in space.spaces) + + +def create_empty_array_dict(space, n=1, fn=np.zeros): + return OrderedDict( + [ + (key, create_empty_array(subspace, n=n, fn=fn)) + for (key, subspace) in space.spaces.items() + ] + ) + + +def create_empty_array_custom(space, n=1, fn=np.zeros): + return None diff --git a/gym/vector/utils/shared_memory.py b/gym/vector/utils/shared_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..1021c139f8690203907fb2726c09319d4026dd57 --- /dev/null +++ b/gym/vector/utils/shared_memory.py @@ -0,0 +1,192 @@ +import numpy as np +import multiprocessing as mp +from ctypes import c_bool +from collections import OrderedDict + +from gym import logger +from gym.spaces import Tuple, Dict +from gym.error import CustomSpaceError +from gym.vector.utils.spaces import _BaseGymSpaces + +__all__ = ["create_shared_memory", "read_from_shared_memory", "write_to_shared_memory"] + + +def create_shared_memory(space, n=1, ctx=mp): + """Create a shared memory object, to be shared across processes. This + eventually contains the observations from the vectorized environment. + + Parameters + ---------- + space : `gym.spaces.Space` instance + Observation space of a single environment in the vectorized environment. + + n : int + Number of environments in the vectorized environment (i.e. the number + of processes). + + ctx : `multiprocessing` context + Context for multiprocessing. + + Returns + ------- + shared_memory : dict, tuple, or `multiprocessing.Array` instance + Shared object across processes. + """ + if isinstance(space, _BaseGymSpaces): + return create_base_shared_memory(space, n=n, ctx=ctx) + elif isinstance(space, Tuple): + return create_tuple_shared_memory(space, n=n, ctx=ctx) + elif isinstance(space, Dict): + return create_dict_shared_memory(space, n=n, ctx=ctx) + else: + raise CustomSpaceError( + "Cannot create a shared memory for space with " + "type `{0}`. Shared memory only supports " + "default Gym spaces (e.g. `Box`, `Tuple`, " + "`Dict`, etc...), and does not support custom " + "Gym spaces.".format(type(space)) + ) + + +def create_base_shared_memory(space, n=1, ctx=mp): + dtype = space.dtype.char + if dtype in "?": + dtype = c_bool + return ctx.Array(dtype, n * int(np.prod(space.shape))) + + +def create_tuple_shared_memory(space, n=1, ctx=mp): + return tuple( + create_shared_memory(subspace, n=n, ctx=ctx) for subspace in space.spaces + ) + + +def create_dict_shared_memory(space, n=1, ctx=mp): + return OrderedDict( + [ + (key, create_shared_memory(subspace, n=n, ctx=ctx)) + for (key, subspace) in space.spaces.items() + ] + ) + + +def read_from_shared_memory(shared_memory, space, n=1): + """Read the batch of observations from shared memory as a numpy array. + + Parameters + ---------- + shared_memory : dict, tuple, or `multiprocessing.Array` instance + Shared object across processes. This contains the observations from the + vectorized environment. This object is created with `create_shared_memory`. + + space : `gym.spaces.Space` instance + Observation space of a single environment in the vectorized environment. + + n : int + Number of environments in the vectorized environment (i.e. the number + of processes). + + Returns + ------- + observations : dict, tuple or `np.ndarray` instance + Batch of observations as a (possibly nested) numpy array. + + Notes + ----- + The numpy array objects returned by `read_from_shared_memory` shares the + memory of `shared_memory`. Any changes to `shared_memory` are forwarded + to `observations`, and vice-versa. To avoid any side-effect, use `np.copy`. + """ + if isinstance(space, _BaseGymSpaces): + return read_base_from_shared_memory(shared_memory, space, n=n) + elif isinstance(space, Tuple): + return read_tuple_from_shared_memory(shared_memory, space, n=n) + elif isinstance(space, Dict): + return read_dict_from_shared_memory(shared_memory, space, n=n) + else: + raise CustomSpaceError( + "Cannot read from a shared memory for space with " + "type `{0}`. Shared memory only supports " + "default Gym spaces (e.g. `Box`, `Tuple`, " + "`Dict`, etc...), and does not support custom " + "Gym spaces.".format(type(space)) + ) + + +def read_base_from_shared_memory(shared_memory, space, n=1): + return np.frombuffer(shared_memory.get_obj(), dtype=space.dtype).reshape( + (n,) + space.shape + ) + + +def read_tuple_from_shared_memory(shared_memory, space, n=1): + return tuple( + read_from_shared_memory(memory, subspace, n=n) + for (memory, subspace) in zip(shared_memory, space.spaces) + ) + + +def read_dict_from_shared_memory(shared_memory, space, n=1): + return OrderedDict( + [ + (key, read_from_shared_memory(shared_memory[key], subspace, n=n)) + for (key, subspace) in space.spaces.items() + ] + ) + + +def write_to_shared_memory(index, value, shared_memory, space): + """Write the observation of a single environment into shared memory. + + Parameters + ---------- + index : int + Index of the environment (must be in `[0, num_envs)`). + + value : sample from `space` + Observation of the single environment to write to shared memory. + + shared_memory : dict, tuple, or `multiprocessing.Array` instance + Shared object across processes. This contains the observations from the + vectorized environment. This object is created with `create_shared_memory`. + + space : `gym.spaces.Space` instance + Observation space of a single environment in the vectorized environment. + + Returns + ------- + `None` + """ + if isinstance(space, _BaseGymSpaces): + write_base_to_shared_memory(index, value, shared_memory, space) + elif isinstance(space, Tuple): + write_tuple_to_shared_memory(index, value, shared_memory, space) + elif isinstance(space, Dict): + write_dict_to_shared_memory(index, value, shared_memory, space) + else: + raise CustomSpaceError( + "Cannot write to a shared memory for space with " + "type `{0}`. Shared memory only supports " + "default Gym spaces (e.g. `Box`, `Tuple`, " + "`Dict`, etc...), and does not support custom " + "Gym spaces.".format(type(space)) + ) + + +def write_base_to_shared_memory(index, value, shared_memory, space): + size = int(np.prod(space.shape)) + destination = np.frombuffer(shared_memory.get_obj(), dtype=space.dtype) + np.copyto( + destination[index * size : (index + 1) * size], + np.asarray(value, dtype=space.dtype).flatten(), + ) + + +def write_tuple_to_shared_memory(index, values, shared_memory, space): + for value, memory, subspace in zip(values, shared_memory, space.spaces): + write_to_shared_memory(index, value, memory, subspace) + + +def write_dict_to_shared_memory(index, values, shared_memory, space): + for key, subspace in space.spaces.items(): + write_to_shared_memory(index, values[key], shared_memory[key], subspace) diff --git a/gym/vector/utils/spaces.py b/gym/vector/utils/spaces.py new file mode 100644 index 0000000000000000000000000000000000000000..ac4727de5a08fa3d77e14177bf38b3d94fa5fe4e --- /dev/null +++ b/gym/vector/utils/spaces.py @@ -0,0 +1,89 @@ +import numpy as np +from collections import OrderedDict + +from gym.spaces import Space, Box, Discrete, MultiDiscrete, MultiBinary, Tuple, Dict + +_BaseGymSpaces = (Box, Discrete, MultiDiscrete, MultiBinary) +__all__ = ["_BaseGymSpaces", "batch_space"] + + +def batch_space(space, n=1): + """Create a (batched) space, containing multiple copies of a single space. + + Parameters + ---------- + space : `gym.spaces.Space` instance + Space (e.g. the observation space) for a single environment in the + vectorized environment. + + n : int + Number of environments in the vectorized environment. + + Returns + ------- + batched_space : `gym.spaces.Space` instance + Space (e.g. the observation space) for a batch of environments in the + vectorized environment. + + Example + ------- + >>> from gym.spaces import Box, Dict + >>> space = Dict({ + ... 'position': Box(low=0, high=1, shape=(3,), dtype=np.float32), + ... 'velocity': Box(low=0, high=1, shape=(2,), dtype=np.float32)}) + >>> batch_space(space, n=5) + Dict(position:Box(5, 3), velocity:Box(5, 2)) + """ + if isinstance(space, _BaseGymSpaces): + return batch_space_base(space, n=n) + elif isinstance(space, Tuple): + return batch_space_tuple(space, n=n) + elif isinstance(space, Dict): + return batch_space_dict(space, n=n) + elif isinstance(space, Space): + return batch_space_custom(space, n=n) + else: + raise ValueError( + "Cannot batch space with type `{0}`. The space must " + "be a valid `gym.Space` instance.".format(type(space)) + ) + + +def batch_space_base(space, n=1): + if isinstance(space, Box): + repeats = tuple([n] + [1] * space.low.ndim) + low, high = np.tile(space.low, repeats), np.tile(space.high, repeats) + return Box(low=low, high=high, dtype=space.dtype) + + elif isinstance(space, Discrete): + return MultiDiscrete(np.full((n,), space.n, dtype=space.dtype)) + + elif isinstance(space, MultiDiscrete): + repeats = tuple([n] + [1] * space.nvec.ndim) + high = np.tile(space.nvec, repeats) - 1 + return Box(low=np.zeros_like(high), high=high, dtype=space.dtype) + + elif isinstance(space, MultiBinary): + return Box(low=0, high=1, shape=(n,) + space.shape, dtype=space.dtype) + + else: + raise ValueError("Space type `{0}` is not supported.".format(type(space))) + + +def batch_space_tuple(space, n=1): + return Tuple(tuple(batch_space(subspace, n=n) for subspace in space.spaces)) + + +def batch_space_dict(space, n=1): + return Dict( + OrderedDict( + [ + (key, batch_space(subspace, n=n)) + for (key, subspace) in space.spaces.items() + ] + ) + ) + + +def batch_space_custom(space, n=1): + return Tuple(tuple(space for _ in range(n))) diff --git a/gym/vector/vector_env.py b/gym/vector/vector_env.py new file mode 100644 index 0000000000000000000000000000000000000000..d6bbaa7c38d35e5a7576c63b5c81400840f7236c --- /dev/null +++ b/gym/vector/vector_env.py @@ -0,0 +1,203 @@ +import gym +from gym.spaces import Tuple +from gym.vector.utils.spaces import batch_space + +__all__ = ["VectorEnv"] + + +class VectorEnv(gym.Env): + r"""Base class for vectorized environments. + + Each observation returned from vectorized environment is a batch of observations + for each sub-environment. And :meth:`step` is also expected to receive a batch of + actions for each sub-environment. + + .. note:: + + All sub-environments should share the identical observation and action spaces. + In other words, a vector of multiple different environments is not supported. + + Parameters + ---------- + num_envs : int + Number of environments in the vectorized environment. + + observation_space : `gym.spaces.Space` instance + Observation space of a single environment. + + action_space : `gym.spaces.Space` instance + Action space of a single environment. + """ + + def __init__(self, num_envs, observation_space, action_space): + super(VectorEnv, self).__init__() + self.num_envs = num_envs + self.is_vector_env = True + self.observation_space = batch_space(observation_space, n=num_envs) + self.action_space = Tuple((action_space,) * num_envs) + + self.closed = False + self.viewer = None + + # The observation and action spaces of a single environment are + # kept in separate properties + self.single_observation_space = observation_space + self.single_action_space = action_space + + def reset_async(self): + pass + + def reset_wait(self, **kwargs): + raise NotImplementedError() + + def reset(self): + r"""Reset all sub-environments and return a batch of initial observations. + + Returns + ------- + observations : sample from `observation_space` + A batch of observations from the vectorized environment. + """ + self.reset_async() + return self.reset_wait() + + def step_async(self, actions): + pass + + def step_wait(self, **kwargs): + raise NotImplementedError() + + def step(self, actions): + r"""Take an action for each sub-environments. + + Parameters + ---------- + actions : iterable of samples from `action_space` + List of actions. + + Returns + ------- + observations : sample from `observation_space` + A batch of observations from the vectorized environment. + + rewards : `np.ndarray` instance (dtype `np.float_`) + A vector of rewards from the vectorized environment. + + dones : `np.ndarray` instance (dtype `np.bool_`) + A vector whose entries indicate whether the episode has ended. + + infos : list of dict + A list of auxiliary diagnostic information dicts from sub-environments. + """ + + self.step_async(actions) + return self.step_wait() + + def close_extras(self, **kwargs): + r"""Clean up the extra resources e.g. beyond what's in this base class.""" + raise NotImplementedError() + + def close(self, **kwargs): + r"""Close all sub-environments and release resources. + + It also closes all the existing image viewers, then calls :meth:`close_extras` and set + :attr:`closed` as ``True``. + + .. warning:: + + This function itself does not close the environments, it should be handled + in :meth:`close_extras`. This is generic for both synchronous and asynchronous + vectorized environments. + + .. note:: + + This will be automatically called when garbage collected or program exited. + + """ + if self.closed: + return + if self.viewer is not None: + self.viewer.close() + self.close_extras(**kwargs) + self.closed = True + + def seed(self, seeds=None): + """ + Parameters + ---------- + seeds : list of int, or int, optional + Random seed for each individual environment. If `seeds` is a list of + length `num_envs`, then the items of the list are chosen as random + seeds. If `seeds` is an int, then each environment uses the random + seed `seeds + n`, where `n` is the index of the environment (between + `0` and `num_envs - 1`). + """ + pass + + def __del__(self): + if not getattr(self, "closed", True): + self.close(terminate=True) + + def __repr__(self): + if self.spec is None: + return "{}({})".format(self.__class__.__name__, self.num_envs) + else: + return "{}({}, {})".format( + self.__class__.__name__, self.spec.id, self.num_envs + ) + + +class VectorEnvWrapper(VectorEnv): + r"""Wraps the vectorized environment to allow a modular transformation. + + This class is the base class for all wrappers for vectorized environments. The subclass + could override some methods to change the behavior of the original vectorized environment + without touching the original code. + + .. note:: + + Don't forget to call ``super().__init__(env)`` if the subclass overrides :meth:`__init__`. + + """ + + def __init__(self, env): + assert isinstance(env, VectorEnv) + self.env = env + + # explicitly forward the methods defined in VectorEnv + # to self.env (instead of the base class) + def reset_async(self): + return self.env.reset_async() + + def reset_wait(self): + return self.env.reset_wait() + + def step_async(self, actions): + return self.env.step_async(actions) + + def step_wait(self): + return self.env.step_wait() + + def close(self, **kwargs): + return self.env.close(**kwargs) + + def close_extras(self, **kwargs): + return self.env.close_extras(**kwargs) + + def seed(self, seeds=None): + return self.env.seed(seeds) + + # implicitly forward all other methods and attributes to self.env + def __getattr__(self, name): + if name.startswith("_"): + raise AttributeError( + "attempted to get missing private attribute '{}'".format(name) + ) + return getattr(self.env, name) + + @property + def unwrapped(self): + return self.env.unwrapped + + def __repr__(self): + return "<{}, {}>".format(self.__class__.__name__, self.env) diff --git a/gym/version.py b/gym/version.py new file mode 100644 index 0000000000000000000000000000000000000000..ccccb9d9b5e395e4690239fc6fcc68dfe9bc7725 --- /dev/null +++ b/gym/version.py @@ -0,0 +1 @@ +VERSION = "0.21.0" diff --git a/gym/wrappers/__init__.py b/gym/wrappers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5b215bf51c5652231f4bbd32677563bdc9846cae --- /dev/null +++ b/gym/wrappers/__init__.py @@ -0,0 +1,18 @@ +from gym import error +from gym.wrappers.monitor import Monitor +from gym.wrappers.time_limit import TimeLimit +from gym.wrappers.filter_observation import FilterObservation +from gym.wrappers.atari_preprocessing import AtariPreprocessing +from gym.wrappers.time_aware_observation import TimeAwareObservation +from gym.wrappers.rescale_action import RescaleAction +from gym.wrappers.flatten_observation import FlattenObservation +from gym.wrappers.gray_scale_observation import GrayScaleObservation +from gym.wrappers.frame_stack import LazyFrames +from gym.wrappers.frame_stack import FrameStack +from gym.wrappers.transform_observation import TransformObservation +from gym.wrappers.transform_reward import TransformReward +from gym.wrappers.resize_observation import ResizeObservation +from gym.wrappers.clip_action import ClipAction +from gym.wrappers.record_episode_statistics import RecordEpisodeStatistics +from gym.wrappers.normalize import NormalizeObservation, NormalizeReward +from gym.wrappers.record_video import RecordVideo, capped_cubic_video_schedule diff --git a/gym/wrappers/__pycache__/__init__.cpython-39.pyc b/gym/wrappers/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..311ada0726cc9996c74ff8fdbae36140f423f9b8 Binary files /dev/null and b/gym/wrappers/__pycache__/__init__.cpython-39.pyc differ diff --git a/gym/wrappers/__pycache__/atari_preprocessing.cpython-39.pyc b/gym/wrappers/__pycache__/atari_preprocessing.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba43f46018100dcd7f994563f19a80dfed17c549 Binary files /dev/null and b/gym/wrappers/__pycache__/atari_preprocessing.cpython-39.pyc differ diff --git a/gym/wrappers/__pycache__/clip_action.cpython-39.pyc b/gym/wrappers/__pycache__/clip_action.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e476a9bff7549371b8f0bdaf67effdab5c795c40 Binary files /dev/null and b/gym/wrappers/__pycache__/clip_action.cpython-39.pyc differ diff --git a/gym/wrappers/__pycache__/filter_observation.cpython-39.pyc b/gym/wrappers/__pycache__/filter_observation.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c271f03cec7b1a240c5d88d5bd5e70839bc4a0f0 Binary files /dev/null and b/gym/wrappers/__pycache__/filter_observation.cpython-39.pyc differ diff --git a/gym/wrappers/__pycache__/flatten_observation.cpython-39.pyc b/gym/wrappers/__pycache__/flatten_observation.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a01f19df50716332a904ed82a533e3cb73b5647b Binary files /dev/null and b/gym/wrappers/__pycache__/flatten_observation.cpython-39.pyc differ diff --git a/gym/wrappers/__pycache__/frame_stack.cpython-39.pyc b/gym/wrappers/__pycache__/frame_stack.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f93f4888e84e06926bbf1f8f2f7e7f66fcde2329 Binary files /dev/null and b/gym/wrappers/__pycache__/frame_stack.cpython-39.pyc differ diff --git a/gym/wrappers/__pycache__/gray_scale_observation.cpython-39.pyc b/gym/wrappers/__pycache__/gray_scale_observation.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de0bba09701785643f62b722535502a80d61e21e Binary files /dev/null and b/gym/wrappers/__pycache__/gray_scale_observation.cpython-39.pyc differ diff --git a/gym/wrappers/__pycache__/monitor.cpython-39.pyc b/gym/wrappers/__pycache__/monitor.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c7c72c836703b0acd2f246392bb5fb91c0a6b7a Binary files /dev/null and b/gym/wrappers/__pycache__/monitor.cpython-39.pyc differ diff --git a/gym/wrappers/__pycache__/normalize.cpython-39.pyc b/gym/wrappers/__pycache__/normalize.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a0d840191cdb6ebc8d675ab4424a7676026a458 Binary files /dev/null and b/gym/wrappers/__pycache__/normalize.cpython-39.pyc differ diff --git a/gym/wrappers/__pycache__/order_enforcing.cpython-39.pyc b/gym/wrappers/__pycache__/order_enforcing.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72886cf1fcc1769b2ea064df12ce8b42c0e2de84 Binary files /dev/null and b/gym/wrappers/__pycache__/order_enforcing.cpython-39.pyc differ diff --git a/gym/wrappers/__pycache__/pixel_observation.cpython-39.pyc b/gym/wrappers/__pycache__/pixel_observation.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61010518a2e07064b902829d06725b479758c380 Binary files /dev/null and b/gym/wrappers/__pycache__/pixel_observation.cpython-39.pyc differ diff --git a/gym/wrappers/__pycache__/record_episode_statistics.cpython-39.pyc b/gym/wrappers/__pycache__/record_episode_statistics.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc9c7f0d3319bf08a471bfd10d6beec24d0c6302 Binary files /dev/null and b/gym/wrappers/__pycache__/record_episode_statistics.cpython-39.pyc differ diff --git a/gym/wrappers/__pycache__/record_video.cpython-39.pyc b/gym/wrappers/__pycache__/record_video.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59f5ca27560600ac971a83dda215ceb938610edc Binary files /dev/null and b/gym/wrappers/__pycache__/record_video.cpython-39.pyc differ diff --git a/gym/wrappers/__pycache__/rescale_action.cpython-39.pyc b/gym/wrappers/__pycache__/rescale_action.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b983e0a558cb00af8d71d89c69f60ac8aa078b5b Binary files /dev/null and b/gym/wrappers/__pycache__/rescale_action.cpython-39.pyc differ diff --git a/gym/wrappers/__pycache__/resize_observation.cpython-39.pyc b/gym/wrappers/__pycache__/resize_observation.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddc654615c541cf6553373965d206501c0978095 Binary files /dev/null and b/gym/wrappers/__pycache__/resize_observation.cpython-39.pyc differ diff --git a/gym/wrappers/__pycache__/time_aware_observation.cpython-39.pyc b/gym/wrappers/__pycache__/time_aware_observation.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0594fb56068fea32882c2c285526484f717df114 Binary files /dev/null and b/gym/wrappers/__pycache__/time_aware_observation.cpython-39.pyc differ diff --git a/gym/wrappers/__pycache__/time_limit.cpython-39.pyc b/gym/wrappers/__pycache__/time_limit.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..409e55b932a0b8a2802c1eb74db9a5ee1d2e0014 Binary files /dev/null and b/gym/wrappers/__pycache__/time_limit.cpython-39.pyc differ diff --git a/gym/wrappers/__pycache__/transform_observation.cpython-39.pyc b/gym/wrappers/__pycache__/transform_observation.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..799850209d426481290a1f11919947ae0db14026 Binary files /dev/null and b/gym/wrappers/__pycache__/transform_observation.cpython-39.pyc differ diff --git a/gym/wrappers/__pycache__/transform_reward.cpython-39.pyc b/gym/wrappers/__pycache__/transform_reward.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7f2c0f83ad519f67edbdc446547b5607af6ff8e Binary files /dev/null and b/gym/wrappers/__pycache__/transform_reward.cpython-39.pyc differ diff --git a/gym/wrappers/atari_preprocessing.py b/gym/wrappers/atari_preprocessing.py new file mode 100644 index 0000000000000000000000000000000000000000..12dafc0dd0f04f0ec4bcd540f700538665ec3115 --- /dev/null +++ b/gym/wrappers/atari_preprocessing.py @@ -0,0 +1,167 @@ +import numpy as np +import gym +from gym.spaces import Box +from gym.wrappers import TimeLimit + +try: + import cv2 +except ImportError: + cv2 = None + + +class AtariPreprocessing(gym.Wrapper): + r"""Atari 2600 preprocessings. + + This class follows the guidelines in + Machado et al. (2018), "Revisiting the Arcade Learning Environment: + Evaluation Protocols and Open Problems for General Agents". + + Specifically: + + * NoopReset: obtain initial state by taking random number of no-ops on reset. + * Frame skipping: 4 by default + * Max-pooling: most recent two observations + * Termination signal when a life is lost: turned off by default. Not recommended by Machado et al. (2018). + * Resize to a square image: 84x84 by default + * Grayscale observation: optional + * Scale observation: optional + + Args: + env (Env): environment + noop_max (int): max number of no-ops + frame_skip (int): the frequency at which the agent experiences the game. + screen_size (int): resize Atari frame + terminal_on_life_loss (bool): if True, then step() returns done=True whenever a + life is lost. + grayscale_obs (bool): if True, then gray scale observation is returned, otherwise, RGB observation + is returned. + grayscale_newaxis (bool): if True and grayscale_obs=True, then a channel axis is added to + grayscale observations to make them 3-dimensional. + scale_obs (bool): if True, then observation normalized in range [0,1] is returned. It also limits memory + optimization benefits of FrameStack Wrapper. + """ + + def __init__( + self, + env, + noop_max=30, + frame_skip=4, + screen_size=84, + terminal_on_life_loss=False, + grayscale_obs=True, + grayscale_newaxis=False, + scale_obs=False, + ): + super().__init__(env) + assert ( + cv2 is not None + ), "opencv-python package not installed! Try running pip install gym[atari] to get dependencies for atari" + assert frame_skip > 0 + assert screen_size > 0 + assert noop_max >= 0 + if frame_skip > 1: + assert "NoFrameskip" in env.spec.id, ( + "disable frame-skipping in the original env. for more than one" + " frame-skip as it will be done by the wrapper" + ) + self.noop_max = noop_max + assert env.unwrapped.get_action_meanings()[0] == "NOOP" + + self.frame_skip = frame_skip + self.screen_size = screen_size + self.terminal_on_life_loss = terminal_on_life_loss + self.grayscale_obs = grayscale_obs + self.grayscale_newaxis = grayscale_newaxis + self.scale_obs = scale_obs + + # buffer of most recent two observations for max pooling + if grayscale_obs: + self.obs_buffer = [ + np.empty(env.observation_space.shape[:2], dtype=np.uint8), + np.empty(env.observation_space.shape[:2], dtype=np.uint8), + ] + else: + self.obs_buffer = [ + np.empty(env.observation_space.shape, dtype=np.uint8), + np.empty(env.observation_space.shape, dtype=np.uint8), + ] + + self.ale = env.unwrapped.ale + self.lives = 0 + self.game_over = False + + _low, _high, _obs_dtype = ( + (0, 255, np.uint8) if not scale_obs else (0, 1, np.float32) + ) + _shape = (screen_size, screen_size, 1 if grayscale_obs else 3) + if grayscale_obs and not grayscale_newaxis: + _shape = _shape[:-1] # Remove channel axis + self.observation_space = Box( + low=_low, high=_high, shape=_shape, dtype=_obs_dtype + ) + + def step(self, action): + R = 0.0 + + for t in range(self.frame_skip): + _, reward, done, info = self.env.step(action) + R += reward + self.game_over = done + + if self.terminal_on_life_loss: + new_lives = self.ale.lives() + done = done or new_lives < self.lives + self.lives = new_lives + + if done: + break + if t == self.frame_skip - 2: + if self.grayscale_obs: + self.ale.getScreenGrayscale(self.obs_buffer[1]) + else: + self.ale.getScreenRGB(self.obs_buffer[1]) + elif t == self.frame_skip - 1: + if self.grayscale_obs: + self.ale.getScreenGrayscale(self.obs_buffer[0]) + else: + self.ale.getScreenRGB(self.obs_buffer[0]) + return self._get_obs(), R, done, info + + def reset(self, **kwargs): + # NoopReset + self.env.reset(**kwargs) + noops = ( + self.env.unwrapped.np_random.randint(1, self.noop_max + 1) + if self.noop_max > 0 + else 0 + ) + for _ in range(noops): + _, _, done, _ = self.env.step(0) + if done: + self.env.reset(**kwargs) + + self.lives = self.ale.lives() + if self.grayscale_obs: + self.ale.getScreenGrayscale(self.obs_buffer[0]) + else: + self.ale.getScreenRGB(self.obs_buffer[0]) + self.obs_buffer[1].fill(0) + return self._get_obs() + + def _get_obs(self): + if self.frame_skip > 1: # more efficient in-place pooling + np.maximum(self.obs_buffer[0], self.obs_buffer[1], out=self.obs_buffer[0]) + obs = cv2.resize( + self.obs_buffer[0], + (self.screen_size, self.screen_size), + interpolation=cv2.INTER_AREA, + ) + + if self.scale_obs: + obs = np.asarray(obs, dtype=np.float32) / 255.0 + else: + obs = np.asarray(obs, dtype=np.uint8) + + if self.grayscale_obs and self.grayscale_newaxis: + obs = np.expand_dims(obs, axis=-1) # Add a channel axis + return obs diff --git a/gym/wrappers/clip_action.py b/gym/wrappers/clip_action.py new file mode 100644 index 0000000000000000000000000000000000000000..64227dcb10808ba9bd2cb9024060772ab2fa6f0d --- /dev/null +++ b/gym/wrappers/clip_action.py @@ -0,0 +1,14 @@ +import numpy as np +from gym import ActionWrapper +from gym.spaces import Box + + +class ClipAction(ActionWrapper): + r"""Clip the continuous action within the valid bound.""" + + def __init__(self, env): + assert isinstance(env.action_space, Box) + super(ClipAction, self).__init__(env) + + def action(self, action): + return np.clip(action, self.action_space.low, self.action_space.high) diff --git a/gym/wrappers/filter_observation.py b/gym/wrappers/filter_observation.py new file mode 100644 index 0000000000000000000000000000000000000000..0f52c04492ba2aba6c34d734491e4ad37917978d --- /dev/null +++ b/gym/wrappers/filter_observation.py @@ -0,0 +1,72 @@ +import copy +from gym import spaces +from gym import ObservationWrapper + + +class FilterObservation(ObservationWrapper): + """Filter dictionary observations by their keys. + + Args: + env: The environment to wrap. + filter_keys: List of keys to be included in the observations. + + Raises: + ValueError: If observation keys in not instance of None or + iterable. + ValueError: If any of the `filter_keys` are not included in + the original `env`'s observation space + + """ + + def __init__(self, env, filter_keys=None): + super(FilterObservation, self).__init__(env) + + wrapped_observation_space = env.observation_space + assert isinstance( + wrapped_observation_space, spaces.Dict + ), "FilterObservationWrapper is only usable with dict observations." + + observation_keys = wrapped_observation_space.spaces.keys() + + if filter_keys is None: + filter_keys = tuple(observation_keys) + + missing_keys = set(key for key in filter_keys if key not in observation_keys) + + if missing_keys: + raise ValueError( + "All the filter_keys must be included in the " + "original obsrevation space.\n" + "Filter keys: {filter_keys}\n" + "Observation keys: {observation_keys}\n" + "Missing keys: {missing_keys}".format( + filter_keys=filter_keys, + observation_keys=observation_keys, + missing_keys=missing_keys, + ) + ) + + self.observation_space = type(wrapped_observation_space)( + [ + (name, copy.deepcopy(space)) + for name, space in wrapped_observation_space.spaces.items() + if name in filter_keys + ] + ) + + self._env = env + self._filter_keys = tuple(filter_keys) + + def observation(self, observation): + filter_observation = self._filter_observation(observation) + return filter_observation + + def _filter_observation(self, observation): + observation = type(observation)( + [ + (name, value) + for name, value in observation.items() + if name in self._filter_keys + ] + ) + return observation diff --git a/gym/wrappers/flatten_observation.py b/gym/wrappers/flatten_observation.py new file mode 100644 index 0000000000000000000000000000000000000000..9dca4da256a398e53407533850b620a13fdaf1f0 --- /dev/null +++ b/gym/wrappers/flatten_observation.py @@ -0,0 +1,13 @@ +import gym.spaces as spaces +from gym import ObservationWrapper + + +class FlattenObservation(ObservationWrapper): + r"""Observation wrapper that flattens the observation.""" + + def __init__(self, env): + super(FlattenObservation, self).__init__(env) + self.observation_space = spaces.flatten_space(env.observation_space) + + def observation(self, observation): + return spaces.flatten(self.env.observation_space, observation) diff --git a/gym/wrappers/frame_stack.py b/gym/wrappers/frame_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..e087482c6aefe0f353d126ea383826d07179ac1b --- /dev/null +++ b/gym/wrappers/frame_stack.py @@ -0,0 +1,122 @@ +from collections import deque +import numpy as np +from gym.spaces import Box +from gym import ObservationWrapper + + +class LazyFrames(object): + r"""Ensures common frames are only stored once to optimize memory use. + + To further reduce the memory use, it is optionally to turn on lz4 to + compress the observations. + + .. note:: + + This object should only be converted to numpy array just before forward pass. + + Args: + lz4_compress (bool): use lz4 to compress the frames internally + + """ + __slots__ = ("frame_shape", "dtype", "shape", "lz4_compress", "_frames") + + def __init__(self, frames, lz4_compress=False): + self.frame_shape = tuple(frames[0].shape) + self.shape = (len(frames),) + self.frame_shape + self.dtype = frames[0].dtype + if lz4_compress: + from lz4.block import compress + + frames = [compress(frame) for frame in frames] + self._frames = frames + self.lz4_compress = lz4_compress + + def __array__(self, dtype=None): + arr = self[:] + if dtype is not None: + return arr.astype(dtype) + return arr + + def __len__(self): + return self.shape[0] + + def __getitem__(self, int_or_slice): + if isinstance(int_or_slice, int): + return self._check_decompress(self._frames[int_or_slice]) # single frame + return np.stack( + [self._check_decompress(f) for f in self._frames[int_or_slice]], axis=0 + ) + + def __eq__(self, other): + return self.__array__() == other + + def _check_decompress(self, frame): + if self.lz4_compress: + from lz4.block import decompress + + return np.frombuffer(decompress(frame), dtype=self.dtype).reshape( + self.frame_shape + ) + return frame + + +class FrameStack(ObservationWrapper): + r"""Observation wrapper that stacks the observations in a rolling manner. + + For example, if the number of stacks is 4, then the returned observation contains + the most recent 4 observations. For environment 'Pendulum-v1', the original observation + is an array with shape [3], so if we stack 4 observations, the processed observation + has shape [4, 3]. + + .. note:: + + To be memory efficient, the stacked observations are wrapped by :class:`LazyFrame`. + + .. note:: + + The observation space must be `Box` type. If one uses `Dict` + as observation space, it should apply `FlattenDictWrapper` at first. + + Example:: + + >>> import gym + >>> env = gym.make('PongNoFrameskip-v0') + >>> env = FrameStack(env, 4) + >>> env.observation_space + Box(4, 210, 160, 3) + + Args: + env (Env): environment object + num_stack (int): number of stacks + lz4_compress (bool): use lz4 to compress the frames internally + + """ + + def __init__(self, env, num_stack, lz4_compress=False): + super(FrameStack, self).__init__(env) + self.num_stack = num_stack + self.lz4_compress = lz4_compress + + self.frames = deque(maxlen=num_stack) + + low = np.repeat(self.observation_space.low[np.newaxis, ...], num_stack, axis=0) + high = np.repeat( + self.observation_space.high[np.newaxis, ...], num_stack, axis=0 + ) + self.observation_space = Box( + low=low, high=high, dtype=self.observation_space.dtype + ) + + def observation(self): + assert len(self.frames) == self.num_stack, (len(self.frames), self.num_stack) + return LazyFrames(list(self.frames), self.lz4_compress) + + def step(self, action): + observation, reward, done, info = self.env.step(action) + self.frames.append(observation) + return self.observation(), reward, done, info + + def reset(self, **kwargs): + observation = self.env.reset(**kwargs) + [self.frames.append(observation) for _ in range(self.num_stack)] + return self.observation() diff --git a/gym/wrappers/gray_scale_observation.py b/gym/wrappers/gray_scale_observation.py new file mode 100644 index 0000000000000000000000000000000000000000..5e789ba94f4360ab763a301d35be6f3726a31b6d --- /dev/null +++ b/gym/wrappers/gray_scale_observation.py @@ -0,0 +1,34 @@ +import numpy as np +from gym.spaces import Box +from gym import ObservationWrapper + + +class GrayScaleObservation(ObservationWrapper): + r"""Convert the image observation from RGB to gray scale.""" + + def __init__(self, env, keep_dim=False): + super(GrayScaleObservation, self).__init__(env) + self.keep_dim = keep_dim + + assert ( + len(env.observation_space.shape) == 3 + and env.observation_space.shape[-1] == 3 + ) + + obs_shape = self.observation_space.shape[:2] + if self.keep_dim: + self.observation_space = Box( + low=0, high=255, shape=(obs_shape[0], obs_shape[1], 1), dtype=np.uint8 + ) + else: + self.observation_space = Box( + low=0, high=255, shape=obs_shape, dtype=np.uint8 + ) + + def observation(self, observation): + import cv2 + + observation = cv2.cvtColor(observation, cv2.COLOR_RGB2GRAY) + if self.keep_dim: + observation = np.expand_dims(observation, -1) + return observation diff --git a/gym/wrappers/monitor.py b/gym/wrappers/monitor.py new file mode 100644 index 0000000000000000000000000000000000000000..9e33057bc9bcf9ade5cf0d2af1594d729fb98374 --- /dev/null +++ b/gym/wrappers/monitor.py @@ -0,0 +1,485 @@ +import json +import os + +import numpy as np + +from gym import Wrapper +from gym import error, version, logger +from gym.wrappers.monitoring import stats_recorder, video_recorder +from gym.utils import atomic_write, closer +from gym.utils.json_utils import json_encode_np + +FILE_PREFIX = "openaigym" +MANIFEST_PREFIX = FILE_PREFIX + ".manifest" + + +class Monitor(Wrapper): + def __init__( + self, + env, + directory, + video_callable=None, + force=False, + resume=False, + write_upon_reset=False, + uid=None, + mode=None, + ): + super(Monitor, self).__init__(env) + logger.deprecation( + "The Monitor wrapper is being deprecated in favor of gym.wrappers.RecordVideo and gym.wrappers.RecordEpisodeStatistics (see https://github.com/openai/gym/issues/2297)" + ) + + self.videos = [] + + self.stats_recorder = None + self.video_recorder = None + self.enabled = False + self.episode_id = 0 + self._monitor_id = None + self.env_semantics_autoreset = env.metadata.get("semantics.autoreset") + + self._start( + directory, video_callable, force, resume, write_upon_reset, uid, mode + ) + + def step(self, action): + self._before_step(action) + observation, reward, done, info = self.env.step(action) + done = self._after_step(observation, reward, done, info) + + return observation, reward, done, info + + def reset(self, **kwargs): + self._before_reset() + observation = self.env.reset(**kwargs) + self._after_reset(observation) + + return observation + + def set_monitor_mode(self, mode): + logger.info("Setting the monitor mode is deprecated and will be removed soon") + self._set_mode(mode) + + def _start( + self, + directory, + video_callable=None, + force=False, + resume=False, + write_upon_reset=False, + uid=None, + mode=None, + ): + """Start monitoring. + + Args: + directory (str): A per-training run directory where to record stats. + video_callable (Optional[function, False]): function that takes in the index of the episode and outputs a boolean, indicating whether we should record a video on this episode. The default (for video_callable is None) is to take perfect cubes, capped at 1000. False disables video recording. + force (bool): Clear out existing training data from this directory (by deleting every file prefixed with "openaigym."). + resume (bool): Retain the training data already in this directory, which will be merged with our new data + write_upon_reset (bool): Write the manifest file on each reset. (This is currently a JSON file, so writing it is somewhat expensive.) + uid (Optional[str]): A unique id used as part of the suffix for the file. By default, uses os.getpid(). + mode (['evaluation', 'training']): Whether this is an evaluation or training episode. + """ + if self.env.spec is None: + logger.warn( + "Trying to monitor an environment which has no 'spec' set. This usually means you did not create it via 'gym.make', and is recommended only for advanced users." + ) + env_id = "(unknown)" + else: + env_id = self.env.spec.id + + self.directory = os.path.abspath(directory) + + if not os.path.exists(self.directory): + logger.info("Creating monitor directory %s", self.directory) + os.makedirs(self.directory, exist_ok=True) + + if video_callable is None: + video_callable = capped_cubic_video_schedule + elif video_callable == False: + video_callable = disable_videos + elif not callable(video_callable): + raise error.Error( + "You must provide a function, None, or False for video_callable, not {}: {}".format( + type(video_callable), video_callable + ) + ) + self.video_callable = video_callable + + # Check on whether we need to clear anything + if force: + clear_monitor_files(self.directory) + elif not resume: + training_manifests = detect_training_manifests(self.directory) + if len(training_manifests) > 0: + raise error.Error( + """Trying to write to monitor directory {} with existing monitor files: {}. + You should use a unique directory for each training run, or use 'force=True' to automatically clear previous monitor files.""".format( + directory, ", ".join(training_manifests[:5]) + ) + ) + + self._monitor_id = monitor_closer.register(self) + + self.enabled = True + # We use the 'openai-gym' prefix to determine if a file is + # ours + self.file_prefix = FILE_PREFIX + self.file_infix = "{}.{}".format(self._monitor_id, uid if uid else os.getpid()) + + self.stats_recorder = stats_recorder.StatsRecorder( + self.directory, + "{}.episode_batch.{}".format(self.file_prefix, self.file_infix), + autoreset=self.env_semantics_autoreset, + env_id=env_id, + ) + + self.write_upon_reset = write_upon_reset + + if mode is not None: + self._set_mode(mode) + + def _flush(self, force=False): + """Flush all relevant monitor information to disk.""" + if not self.write_upon_reset and not force: + return + + self.stats_recorder.flush() + + # Give it a very distinguished name, since we need to pick it + # up from the filesystem later. + path = os.path.join( + self.directory, + "{}.manifest.{}.manifest.json".format(self.file_prefix, self.file_infix), + ) + logger.debug("Writing training manifest file to %s", path) + with atomic_write.atomic_write(path) as f: + # We need to write relative paths here since people may + # move the training_dir around. It would be cleaner to + # already have the basenames rather than basename'ing + # manually, but this works for now. + json.dump( + { + "stats": os.path.basename(self.stats_recorder.path), + "videos": [ + (os.path.basename(v), os.path.basename(m)) + for v, m in self.videos + ], + "env_info": self._env_info(), + }, + f, + default=json_encode_np, + ) + + def close(self): + """Flush all monitor data to disk and close any open rending windows.""" + super(Monitor, self).close() + + if not self.enabled: + return + self.stats_recorder.close() + if self.video_recorder is not None: + self._close_video_recorder() + self._flush(force=True) + + # Stop tracking this for autoclose + monitor_closer.unregister(self._monitor_id) + self.enabled = False + + logger.info( + """Finished writing results. You can upload them to the scoreboard via gym.upload(%r)""", + self.directory, + ) + + def _set_mode(self, mode): + if mode == "evaluation": + type = "e" + elif mode == "training": + type = "t" + else: + raise error.Error( + 'Invalid mode {}: must be "training" or "evaluation"', mode + ) + self.stats_recorder.type = type + + def _before_step(self, action): + if not self.enabled: + return + self.stats_recorder.before_step(action) + + def _after_step(self, observation, reward, done, info): + if not self.enabled: + return done + + if done and self.env_semantics_autoreset: + # For envs with BlockingReset wrapping VNCEnv, this observation will be the first one of the new episode + self.reset_video_recorder() + self.episode_id += 1 + self._flush() + + # Record stats + self.stats_recorder.after_step(observation, reward, done, info) + # Record video + self.video_recorder.capture_frame() + + return done + + def _before_reset(self): + if not self.enabled: + return + self.stats_recorder.before_reset() + + def _after_reset(self, observation): + if not self.enabled: + return + + # Reset the stat count + self.stats_recorder.after_reset(observation) + + self.reset_video_recorder() + + # Bump *after* all reset activity has finished + self.episode_id += 1 + + self._flush() + + def reset_video_recorder(self): + # Close any existing video recorder + if self.video_recorder: + self._close_video_recorder() + + # Start recording the next video. + # + # TODO: calculate a more correct 'episode_id' upon merge + self.video_recorder = video_recorder.VideoRecorder( + env=self.env, + base_path=os.path.join( + self.directory, + "{}.video.{}.video{:06}".format( + self.file_prefix, self.file_infix, self.episode_id + ), + ), + metadata={"episode_id": self.episode_id}, + enabled=self._video_enabled(), + ) + self.video_recorder.capture_frame() + + def _close_video_recorder(self): + self.video_recorder.close() + if self.video_recorder.functional: + self.videos.append( + (self.video_recorder.path, self.video_recorder.metadata_path) + ) + + def _video_enabled(self): + return self.video_callable(self.episode_id) + + def _env_info(self): + env_info = { + "gym_version": version.VERSION, + } + if self.env.spec: + env_info["env_id"] = self.env.spec.id + return env_info + + def __del__(self): + # Make sure we've closed up shop when garbage collecting + self.close() + + def get_total_steps(self): + return self.stats_recorder.total_steps + + def get_episode_rewards(self): + return self.stats_recorder.episode_rewards + + def get_episode_lengths(self): + return self.stats_recorder.episode_lengths + + +def detect_training_manifests(training_dir, files=None): + if files is None: + files = os.listdir(training_dir) + return [ + os.path.join(training_dir, f) + for f in files + if f.startswith(MANIFEST_PREFIX + ".") + ] + + +def detect_monitor_files(training_dir): + return [ + os.path.join(training_dir, f) + for f in os.listdir(training_dir) + if f.startswith(FILE_PREFIX + ".") + ] + + +def clear_monitor_files(training_dir): + files = detect_monitor_files(training_dir) + if len(files) == 0: + return + + logger.info( + "Clearing %d monitor files from previous run (because force=True was provided)", + len(files), + ) + for file in files: + os.unlink(file) + + +def capped_cubic_video_schedule(episode_id): + if episode_id < 1000: + return int(round(episode_id ** (1.0 / 3))) ** 3 == episode_id + else: + return episode_id % 1000 == 0 + + +def disable_videos(episode_id): + return False + + +monitor_closer = closer.Closer() + + +# This method gets used for a sanity check in scoreboard/api.py. It's +# not intended for use outside of the gym codebase. +def _open_monitors(): + return list(monitor_closer.closeables.values()) + + +def load_env_info_from_manifests(manifests, training_dir): + env_infos = [] + for manifest in manifests: + with open(manifest) as f: + contents = json.load(f) + env_infos.append(contents["env_info"]) + + env_info = collapse_env_infos(env_infos, training_dir) + return env_info + + +def load_results(training_dir): + if not os.path.exists(training_dir): + logger.error("Training directory %s not found", training_dir) + return + + manifests = detect_training_manifests(training_dir) + if not manifests: + logger.error("No manifests found in training directory %s", training_dir) + return + + logger.debug("Uploading data from manifest %s", ", ".join(manifests)) + + # Load up stats + video files + stats_files = [] + videos = [] + env_infos = [] + + for manifest in manifests: + with open(manifest) as f: + contents = json.load(f) + # Make these paths absolute again + stats_files.append(os.path.join(training_dir, contents["stats"])) + videos += [ + (os.path.join(training_dir, v), os.path.join(training_dir, m)) + for v, m in contents["videos"] + ] + env_infos.append(contents["env_info"]) + + env_info = collapse_env_infos(env_infos, training_dir) + ( + data_sources, + initial_reset_timestamps, + timestamps, + episode_lengths, + episode_rewards, + episode_types, + initial_reset_timestamp, + ) = merge_stats_files(stats_files) + + return { + "manifests": manifests, + "env_info": env_info, + "data_sources": data_sources, + "timestamps": timestamps, + "episode_lengths": episode_lengths, + "episode_rewards": episode_rewards, + "episode_types": episode_types, + "initial_reset_timestamps": initial_reset_timestamps, + "initial_reset_timestamp": initial_reset_timestamp, + "videos": videos, + } + + +def merge_stats_files(stats_files): + timestamps = [] + episode_lengths = [] + episode_rewards = [] + episode_types = [] + initial_reset_timestamps = [] + data_sources = [] + + for i, path in enumerate(stats_files): + with open(path) as f: + content = json.load(f) + if len(content["timestamps"]) == 0: + continue # so empty file doesn't mess up results, due to null initial_reset_timestamp + data_sources += [i] * len(content["timestamps"]) + timestamps += content["timestamps"] + episode_lengths += content["episode_lengths"] + episode_rewards += content["episode_rewards"] + # Recent addition + episode_types += content.get("episode_types", []) + # Keep track of where each episode came from. + initial_reset_timestamps.append(content["initial_reset_timestamp"]) + + idxs = np.argsort(timestamps) + timestamps = np.array(timestamps)[idxs].tolist() + episode_lengths = np.array(episode_lengths)[idxs].tolist() + episode_rewards = np.array(episode_rewards)[idxs].tolist() + data_sources = np.array(data_sources)[idxs].tolist() + + if episode_types: + episode_types = np.array(episode_types)[idxs].tolist() + else: + episode_types = None + + if len(initial_reset_timestamps) > 0: + initial_reset_timestamp = min(initial_reset_timestamps) + else: + initial_reset_timestamp = 0 + + return ( + data_sources, + initial_reset_timestamps, + timestamps, + episode_lengths, + episode_rewards, + episode_types, + initial_reset_timestamp, + ) + + +# TODO training_dir isn't used except for error messages, clean up the layering +def collapse_env_infos(env_infos, training_dir): + assert len(env_infos) > 0 + + first = env_infos[0] + for other in env_infos[1:]: + if first != other: + raise error.Error( + "Found two unequal env_infos: {} and {}. This usually indicates that your training directory {} has commingled results from multiple runs.".format( + first, other, training_dir + ) + ) + + for key in ["env_id", "gym_version"]: + if key not in first: + raise error.Error( + "env_info {} from training directory {} is missing expected key {}. This is unexpected and likely indicates a bug in gym.".format( + first, training_dir, key + ) + ) + return first diff --git a/gym/wrappers/monitoring/__init__.py b/gym/wrappers/monitoring/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gym/wrappers/monitoring/__pycache__/__init__.cpython-39.pyc b/gym/wrappers/monitoring/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..026bc5676b41c603ca46b759aaf1d5f0af2cc84c Binary files /dev/null and b/gym/wrappers/monitoring/__pycache__/__init__.cpython-39.pyc differ diff --git a/gym/wrappers/monitoring/__pycache__/stats_recorder.cpython-39.pyc b/gym/wrappers/monitoring/__pycache__/stats_recorder.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41d156992a6a58834becdffd81836fa48525a133 Binary files /dev/null and b/gym/wrappers/monitoring/__pycache__/stats_recorder.cpython-39.pyc differ diff --git a/gym/wrappers/monitoring/__pycache__/video_recorder.cpython-39.pyc b/gym/wrappers/monitoring/__pycache__/video_recorder.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c748a2caacedef4d5a240b54b9e9574eaa881070 Binary files /dev/null and b/gym/wrappers/monitoring/__pycache__/video_recorder.cpython-39.pyc differ diff --git a/gym/wrappers/monitoring/stats_recorder.py b/gym/wrappers/monitoring/stats_recorder.py new file mode 100644 index 0000000000000000000000000000000000000000..32a693e50eb3bb8b7980d91f6c0901ec88ccdda6 --- /dev/null +++ b/gym/wrappers/monitoring/stats_recorder.py @@ -0,0 +1,123 @@ +import json +import os +import time + +from gym import error +from gym.utils import atomic_write +from gym.utils.json_utils import json_encode_np + + +class StatsRecorder(object): + def __init__(self, directory, file_prefix, autoreset=False, env_id=None): + self.autoreset = autoreset + self.env_id = env_id + + self.initial_reset_timestamp = None + self.directory = directory + self.file_prefix = file_prefix + self.episode_lengths = [] + self.episode_rewards = [] + self.episode_types = [] # experimental addition + self._type = "t" + self.timestamps = [] + self.steps = None + self.total_steps = 0 + self.rewards = None + + self.done = None + self.closed = False + + filename = "{}.stats.json".format(self.file_prefix) + self.path = os.path.join(self.directory, filename) + + @property + def type(self): + return self._type + + @type.setter + def type(self, type): + if type not in ["t", "e"]: + raise error.Error( + "Invalid episode type {}: must be t for training or e for evaluation", + type, + ) + self._type = type + + def before_step(self, action): + assert not self.closed + + if self.done: + raise error.ResetNeeded( + "Trying to step environment which is currently done. While the monitor is active for {}, you cannot step beyond the end of an episode. Call 'env.reset()' to start the next episode.".format( + self.env_id + ) + ) + elif self.steps is None: + raise error.ResetNeeded( + "Trying to step an environment before reset. While the monitor is active for {}, you must call 'env.reset()' before taking an initial step.".format( + self.env_id + ) + ) + + def after_step(self, observation, reward, done, info): + self.steps += 1 + self.total_steps += 1 + self.rewards += reward + self.done = done + + if done: + self.save_complete() + + if done: + if self.autoreset: + self.before_reset() + self.after_reset(observation) + + def before_reset(self): + assert not self.closed + + if self.done is not None and not self.done and self.steps > 0: + raise error.Error( + "Tried to reset environment which is not done. While the monitor is active for {}, you cannot call reset() unless the episode is over.".format( + self.env_id + ) + ) + + self.done = False + if self.initial_reset_timestamp is None: + self.initial_reset_timestamp = time.perf_counter() + + def after_reset(self, observation): + self.steps = 0 + self.rewards = 0 + # We write the type at the beginning of the episode. If a user + # changes the type, it's more natural for it to apply next + # time the user calls reset(). + self.episode_types.append(self._type) + + def save_complete(self): + if self.steps is not None: + self.episode_lengths.append(self.steps) + self.episode_rewards.append(float(self.rewards)) + self.timestamps.append(time.perf_counter()) + + def close(self): + self.flush() + self.closed = True + + def flush(self): + if self.closed: + return + + with atomic_write.atomic_write(self.path) as f: + json.dump( + { + "initial_reset_timestamp": self.initial_reset_timestamp, + "timestamps": self.timestamps, + "episode_lengths": self.episode_lengths, + "episode_rewards": self.episode_rewards, + "episode_types": self.episode_types, + }, + f, + default=json_encode_np, + ) diff --git a/gym/wrappers/monitoring/video_recorder.py b/gym/wrappers/monitoring/video_recorder.py new file mode 100644 index 0000000000000000000000000000000000000000..5e53a1168d52def9efd262b40be98818ae6bde3a --- /dev/null +++ b/gym/wrappers/monitoring/video_recorder.py @@ -0,0 +1,427 @@ +import json +import os +import os.path +import pkgutil +import subprocess +import tempfile +from io import StringIO + +import distutils.spawn +import distutils.version +import numpy as np + +from gym import error, logger + + +def touch(path): + open(path, "a").close() + + +class VideoRecorder(object): + """VideoRecorder renders a nice movie of a rollout, frame by frame. It + comes with an `enabled` option so you can still use the same code + on episodes where you don't want to record video. + + Note: + You are responsible for calling `close` on a created + VideoRecorder, or else you may leak an encoder process. + + Args: + env (Env): Environment to take video of. + path (Optional[str]): Path to the video file; will be randomly chosen if omitted. + base_path (Optional[str]): Alternatively, path to the video file without extension, which will be added. + metadata (Optional[dict]): Contents to save to the metadata file. + enabled (bool): Whether to actually record video, or just no-op (for convenience) + """ + + def __init__(self, env, path=None, metadata=None, enabled=True, base_path=None): + modes = env.metadata.get("render.modes", []) + self._async = env.metadata.get("semantics.async") + self.enabled = enabled + self._closed = False + + # Don't bother setting anything else if not enabled + if not self.enabled: + return + + self.ansi_mode = False + if "rgb_array" not in modes: + if "ansi" in modes: + self.ansi_mode = True + else: + logger.info( + 'Disabling video recorder because {} neither supports video mode "rgb_array" nor "ansi".'.format( + env + ) + ) + # Whoops, turns out we shouldn't be enabled after all + self.enabled = False + return + + if path is not None and base_path is not None: + raise error.Error("You can pass at most one of `path` or `base_path`.") + + self.last_frame = None + self.env = env + + required_ext = ".json" if self.ansi_mode else ".mp4" + if path is None: + if base_path is not None: + # Base path given, append ext + path = base_path + required_ext + else: + # Otherwise, just generate a unique filename + with tempfile.NamedTemporaryFile( + suffix=required_ext, delete=False + ) as f: + path = f.name + self.path = path + + path_base, actual_ext = os.path.splitext(self.path) + + if actual_ext != required_ext: + hint = ( + " HINT: The environment is text-only, therefore we're recording its text output in a structured JSON format." + if self.ansi_mode + else "" + ) + raise error.Error( + "Invalid path given: {} -- must have file extension {}.{}".format( + self.path, required_ext, hint + ) + ) + # Touch the file in any case, so we know it's present. (This + # corrects for platform platform differences. Using ffmpeg on + # OS X, the file is precreated, but not on Linux. + touch(path) + + self.frames_per_sec = env.metadata.get("video.frames_per_second", 30) + self.output_frames_per_sec = env.metadata.get( + "video.output_frames_per_second", self.frames_per_sec + ) + self.encoder = None # lazily start the process + self.broken = False + + # Dump metadata + self.metadata = metadata or {} + self.metadata["content_type"] = ( + "video/vnd.openai.ansivid" if self.ansi_mode else "video/mp4" + ) + self.metadata_path = "{}.meta.json".format(path_base) + self.write_metadata() + + logger.info("Starting new video recorder writing to %s", self.path) + self.empty = True + + @property + def functional(self): + return self.enabled and not self.broken + + def capture_frame(self): + """Render the given `env` and add the resulting frame to the video.""" + if not self.functional: + return + if self._closed: + logger.warn( + "The video recorder has been closed and no frames will be captured anymore." + ) + return + logger.debug("Capturing video frame: path=%s", self.path) + + render_mode = "ansi" if self.ansi_mode else "rgb_array" + frame = self.env.render(mode=render_mode) + + if frame is None: + if self._async: + return + else: + # Indicates a bug in the environment: don't want to raise + # an error here. + logger.warn( + "Env returned None on render(). Disabling further rendering for video recorder by marking as disabled: path=%s metadata_path=%s", + self.path, + self.metadata_path, + ) + self.broken = True + else: + self.last_frame = frame + if self.ansi_mode: + self._encode_ansi_frame(frame) + else: + self._encode_image_frame(frame) + + def close(self): + """Flush all data to disk and close any open frame encoders.""" + if not self.enabled or self._closed: + return + + if self.encoder: + logger.debug("Closing video encoder: path=%s", self.path) + self.encoder.close() + self.encoder = None + else: + # No frames captured. Set metadata, and remove the empty output file. + os.remove(self.path) + + if self.metadata is None: + self.metadata = {} + self.metadata["empty"] = True + + # If broken, get rid of the output file, otherwise we'd leak it. + if self.broken: + logger.info( + "Cleaning up paths for broken video recorder: path=%s metadata_path=%s", + self.path, + self.metadata_path, + ) + + # Might have crashed before even starting the output file, don't try to remove in that case. + if os.path.exists(self.path): + os.remove(self.path) + + if self.metadata is None: + self.metadata = {} + self.metadata["broken"] = True + + self.write_metadata() + + # Stop tracking this for autoclose + self._closed = True + + def write_metadata(self): + with open(self.metadata_path, "w") as f: + json.dump(self.metadata, f) + + def __del__(self): + # Make sure we've closed up shop when garbage collecting + self.close() + + def _encode_ansi_frame(self, frame): + if not self.encoder: + self.encoder = TextEncoder(self.path, self.frames_per_sec) + self.metadata["encoder_version"] = self.encoder.version_info + self.encoder.capture_frame(frame) + self.empty = False + + def _encode_image_frame(self, frame): + if not self.encoder: + self.encoder = ImageEncoder( + self.path, frame.shape, self.frames_per_sec, self.output_frames_per_sec + ) + self.metadata["encoder_version"] = self.encoder.version_info + + try: + self.encoder.capture_frame(frame) + except error.InvalidFrame as e: + logger.warn("Tried to pass invalid video frame, marking as broken: %s", e) + self.broken = True + else: + self.empty = False + + +class TextEncoder(object): + """Store a moving picture made out of ANSI frames. Format adapted from + https://github.com/asciinema/asciinema/blob/master/doc/asciicast-v1.md""" + + def __init__(self, output_path, frames_per_sec): + self.output_path = output_path + self.frames_per_sec = frames_per_sec + self.frames = [] + + def capture_frame(self, frame): + string = None + if isinstance(frame, str): + string = frame + elif isinstance(frame, StringIO): + string = frame.getvalue() + else: + raise error.InvalidFrame( + "Wrong type {} for {}: text frame must be a string or StringIO".format( + type(frame), frame + ) + ) + + frame_bytes = string.encode("utf-8") + + if frame_bytes[-1:] != b"\n": + raise error.InvalidFrame( + 'Frame must end with a newline: """{}"""'.format(string) + ) + + if b"\r" in frame_bytes: + raise error.InvalidFrame( + 'Frame contains carriage returns (only newlines are allowed: """{}"""'.format( + string + ) + ) + + self.frames.append(frame_bytes) + + def close(self): + # frame_duration = float(1) / self.frames_per_sec + frame_duration = 0.5 + + # Turn frames into events: clear screen beforehand + # https://rosettacode.org/wiki/Terminal_control/Clear_the_screen#Python + # https://rosettacode.org/wiki/Terminal_control/Cursor_positioning#Python + clear_code = b"%c[2J\033[1;1H" % (27) + # Decode the bytes as UTF-8 since JSON may only contain UTF-8 + events = [ + ( + frame_duration, + (clear_code + frame.replace(b"\n", b"\r\n")).decode("utf-8"), + ) + for frame in self.frames + ] + + # Calculate frame size from the largest frames. + # Add some padding since we'll get cut off otherwise. + height = max([frame.count(b"\n") for frame in self.frames]) + 1 + width = ( + max( + [ + max([len(line) for line in frame.split(b"\n")]) + for frame in self.frames + ] + ) + + 2 + ) + + data = { + "version": 1, + "width": width, + "height": height, + "duration": len(self.frames) * frame_duration, + "command": "-", + "title": "gym VideoRecorder episode", + "env": {}, # could add some env metadata here + "stdout": events, + } + + with open(self.output_path, "w") as f: + json.dump(data, f) + + @property + def version_info(self): + return {"backend": "TextEncoder", "version": 1} + + +class ImageEncoder(object): + def __init__(self, output_path, frame_shape, frames_per_sec, output_frames_per_sec): + self.proc = None + self.output_path = output_path + # Frame shape should be lines-first, so w and h are swapped + h, w, pixfmt = frame_shape + if pixfmt != 3 and pixfmt != 4: + raise error.InvalidFrame( + "Your frame has shape {}, but we require (w,h,3) or (w,h,4), i.e., RGB values for a w-by-h image, with an optional alpha channel.".format( + frame_shape + ) + ) + self.wh = (w, h) + self.includes_alpha = pixfmt == 4 + self.frame_shape = frame_shape + self.frames_per_sec = frames_per_sec + self.output_frames_per_sec = output_frames_per_sec + + if distutils.spawn.find_executable("avconv") is not None: + self.backend = "avconv" + elif distutils.spawn.find_executable("ffmpeg") is not None: + self.backend = "ffmpeg" + elif pkgutil.find_loader("imageio_ffmpeg"): + import imageio_ffmpeg + + self.backend = imageio_ffmpeg.get_ffmpeg_exe() + else: + raise error.DependencyNotInstalled( + """Found neither the ffmpeg nor avconv executables. On OS X, you can install ffmpeg via `brew install ffmpeg`. On most Ubuntu variants, `sudo apt-get install ffmpeg` should do it. On Ubuntu 14.04, however, you'll need to install avconv with `sudo apt-get install libav-tools`. Alternatively, please install imageio-ffmpeg with `pip install imageio-ffmpeg`""" + ) + + self.start() + + @property + def version_info(self): + return { + "backend": self.backend, + "version": str( + subprocess.check_output( + [self.backend, "-version"], stderr=subprocess.STDOUT + ) + ), + "cmdline": self.cmdline, + } + + def start(self): + self.cmdline = ( + self.backend, + "-nostats", + "-loglevel", + "error", # suppress warnings + "-y", + # input + "-f", + "rawvideo", + "-s:v", + "{}x{}".format(*self.wh), + "-pix_fmt", + ("rgb32" if self.includes_alpha else "rgb24"), + "-framerate", + "%d" % self.frames_per_sec, + "-i", + "-", # this used to be /dev/stdin, which is not Windows-friendly + # output + "-vf", + "scale=trunc(iw/2)*2:trunc(ih/2)*2", + "-vcodec", + "libx264", + "-pix_fmt", + "yuv420p", + "-r", + "%d" % self.output_frames_per_sec, + self.output_path, + ) + + logger.debug('Starting %s with "%s"', self.backend, " ".join(self.cmdline)) + if hasattr(os, "setsid"): # setsid not present on Windows + self.proc = subprocess.Popen( + self.cmdline, stdin=subprocess.PIPE, preexec_fn=os.setsid + ) + else: + self.proc = subprocess.Popen(self.cmdline, stdin=subprocess.PIPE) + + def capture_frame(self, frame): + if not isinstance(frame, (np.ndarray, np.generic)): + raise error.InvalidFrame( + "Wrong type {} for {} (must be np.ndarray or np.generic)".format( + type(frame), frame + ) + ) + if frame.shape != self.frame_shape: + raise error.InvalidFrame( + "Your frame has shape {}, but the VideoRecorder is configured for shape {}.".format( + frame.shape, self.frame_shape + ) + ) + if frame.dtype != np.uint8: + raise error.InvalidFrame( + "Your frame has data type {}, but we require uint8 (i.e. RGB values from 0-255).".format( + frame.dtype + ) + ) + + try: + if distutils.version.LooseVersion( + np.__version__ + ) >= distutils.version.LooseVersion("1.9.0"): + self.proc.stdin.write(frame.tobytes()) + else: + self.proc.stdin.write(frame.tostring()) + except Exception as e: + stdout, stderr = self.proc.communicate() + logger.error("VideoRecorder encoder failed: %s", stderr) + + def close(self): + self.proc.stdin.close() + ret = self.proc.wait() + if ret != 0: + logger.error("VideoRecorder encoder exited with status {}".format(ret)) diff --git a/gym/wrappers/normalize.py b/gym/wrappers/normalize.py new file mode 100644 index 0000000000000000000000000000000000000000..c4e9a07a1cf8e3e1eede9783e83acffd5e9191ca --- /dev/null +++ b/gym/wrappers/normalize.py @@ -0,0 +1,105 @@ +import numpy as np +import gym + + +# taken from https://github.com/openai/baselines/blob/master/baselines/common/vec_env/vec_normalize.py +class RunningMeanStd(object): + # https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm + def __init__(self, epsilon=1e-4, shape=()): + self.mean = np.zeros(shape, "float64") + self.var = np.ones(shape, "float64") + self.count = epsilon + + def update(self, x): + batch_mean = np.mean(x, axis=0) + batch_var = np.var(x, axis=0) + batch_count = x.shape[0] + self.update_from_moments(batch_mean, batch_var, batch_count) + + def update_from_moments(self, batch_mean, batch_var, batch_count): + self.mean, self.var, self.count = update_mean_var_count_from_moments( + self.mean, self.var, self.count, batch_mean, batch_var, batch_count + ) + + +def update_mean_var_count_from_moments( + mean, var, count, batch_mean, batch_var, batch_count +): + delta = batch_mean - mean + tot_count = count + batch_count + + new_mean = mean + delta * batch_count / tot_count + m_a = var * count + m_b = batch_var * batch_count + M2 = m_a + m_b + np.square(delta) * count * batch_count / tot_count + new_var = M2 / tot_count + new_count = tot_count + + return new_mean, new_var, new_count + + +class NormalizeObservation(gym.core.Wrapper): + def __init__( + self, + env, + epsilon=1e-8, + ): + super(NormalizeObservation, self).__init__(env) + self.num_envs = getattr(env, "num_envs", 1) + self.is_vector_env = getattr(env, "is_vector_env", False) + if self.is_vector_env: + self.obs_rms = RunningMeanStd(shape=self.single_observation_space.shape) + else: + self.obs_rms = RunningMeanStd(shape=self.observation_space.shape) + self.epsilon = epsilon + + def step(self, action): + obs, rews, dones, infos = self.env.step(action) + if self.is_vector_env: + obs = self.normalize(obs) + else: + obs = self.normalize(np.array([obs]))[0] + return obs, rews, dones, infos + + def reset(self): + obs = self.env.reset() + if self.is_vector_env: + obs = self.normalize(obs) + else: + obs = self.normalize(np.array([obs]))[0] + return obs + + def normalize(self, obs): + self.obs_rms.update(obs) + return (obs - self.obs_rms.mean) / np.sqrt(self.obs_rms.var + self.epsilon) + + +class NormalizeReward(gym.core.Wrapper): + def __init__( + self, + env, + gamma=0.99, + epsilon=1e-8, + ): + super(NormalizeReward, self).__init__(env) + self.num_envs = getattr(env, "num_envs", 1) + self.is_vector_env = getattr(env, "is_vector_env", False) + self.return_rms = RunningMeanStd(shape=()) + self.returns = np.zeros(self.num_envs) + self.gamma = gamma + self.epsilon = epsilon + + def step(self, action): + obs, rews, dones, infos = self.env.step(action) + if not self.is_vector_env: + rews = np.array([rews]) + self.returns = self.returns * self.gamma + rews + rews = self.normalize(rews) + self.returns[dones] = 0.0 + if not self.is_vector_env: + rews = rews[0] + return obs, rews, dones, infos + + def normalize(self, rews): + self.return_rms.update(self.returns) + return rews / np.sqrt(self.return_rms.var + self.epsilon) diff --git a/gym/wrappers/order_enforcing.py b/gym/wrappers/order_enforcing.py new file mode 100644 index 0000000000000000000000000000000000000000..f3bbd838dd1e8e4d0c9a386b6a547b685209109c --- /dev/null +++ b/gym/wrappers/order_enforcing.py @@ -0,0 +1,16 @@ +import gym + + +class OrderEnforcing(gym.Wrapper): + def __init__(self, env): + super(OrderEnforcing, self).__init__(env) + self._has_reset = False + + def step(self, action): + assert self._has_reset, "Cannot call env.step() before calling reset()" + observation, reward, done, info = self.env.step(action) + return observation, reward, done, info + + def reset(self, **kwargs): + self._has_reset = True + return self.env.reset(**kwargs) diff --git a/gym/wrappers/pixel_observation.py b/gym/wrappers/pixel_observation.py new file mode 100644 index 0000000000000000000000000000000000000000..80c8d943f1ce996b9330f02be737a8c1198b0187 --- /dev/null +++ b/gym/wrappers/pixel_observation.py @@ -0,0 +1,127 @@ +import collections +from collections.abc import MutableMapping +import copy +import numpy as np + +from gym import spaces +from gym import ObservationWrapper + + +STATE_KEY = "state" + + +class PixelObservationWrapper(ObservationWrapper): + """Augment observations by pixel values.""" + + def __init__( + self, env, pixels_only=True, render_kwargs=None, pixel_keys=("pixels",) + ): + """Initializes a new pixel Wrapper. + + Args: + env: The environment to wrap. + pixels_only: If `True` (default), the original observation returned + by the wrapped environment will be discarded, and a dictionary + observation will only include pixels. If `False`, the + observation dictionary will contain both the original + observations and the pixel observations. + render_kwargs: Optional `dict` containing keyword arguments passed + to the `self.render` method. + pixel_keys: Optional custom string specifying the pixel + observation's key in the `OrderedDict` of observations. + Defaults to 'pixels'. + + Raises: + ValueError: If `env`'s observation spec is not compatible with the + wrapper. Supported formats are a single array, or a dict of + arrays. + ValueError: If `env`'s observation already contains any of the + specified `pixel_keys`. + """ + + super(PixelObservationWrapper, self).__init__(env) + + if render_kwargs is None: + render_kwargs = {} + + for key in pixel_keys: + render_kwargs.setdefault(key, {}) + + render_mode = render_kwargs[key].pop("mode", "rgb_array") + assert render_mode == "rgb_array", render_mode + render_kwargs[key]["mode"] = "rgb_array" + + wrapped_observation_space = env.observation_space + + if isinstance(wrapped_observation_space, spaces.Box): + self._observation_is_dict = False + invalid_keys = set([STATE_KEY]) + elif isinstance(wrapped_observation_space, (spaces.Dict, MutableMapping)): + self._observation_is_dict = True + invalid_keys = set(wrapped_observation_space.spaces.keys()) + else: + raise ValueError("Unsupported observation space structure.") + + if not pixels_only: + # Make sure that now keys in the `pixel_keys` overlap with + # `observation_keys` + overlapping_keys = set(pixel_keys) & set(invalid_keys) + if overlapping_keys: + raise ValueError( + "Duplicate or reserved pixel keys {!r}.".format(overlapping_keys) + ) + + if pixels_only: + self.observation_space = spaces.Dict() + elif self._observation_is_dict: + self.observation_space = copy.deepcopy(wrapped_observation_space) + else: + self.observation_space = spaces.Dict() + self.observation_space.spaces[STATE_KEY] = wrapped_observation_space + + # Extend observation space with pixels. + + pixels_spaces = {} + for pixel_key in pixel_keys: + pixels = self.env.render(**render_kwargs[pixel_key]) + + if np.issubdtype(pixels.dtype, np.integer): + low, high = (0, 255) + elif np.issubdtype(pixels.dtype, np.float): + low, high = (-float("inf"), float("inf")) + else: + raise TypeError(pixels.dtype) + + pixels_space = spaces.Box( + shape=pixels.shape, low=low, high=high, dtype=pixels.dtype + ) + pixels_spaces[pixel_key] = pixels_space + + self.observation_space.spaces.update(pixels_spaces) + + self._env = env + self._pixels_only = pixels_only + self._render_kwargs = render_kwargs + self._pixel_keys = pixel_keys + + def observation(self, observation): + pixel_observation = self._add_pixel_observation(observation) + return pixel_observation + + def _add_pixel_observation(self, wrapped_observation): + if self._pixels_only: + observation = collections.OrderedDict() + elif self._observation_is_dict: + observation = type(wrapped_observation)(wrapped_observation) + else: + observation = collections.OrderedDict() + observation[STATE_KEY] = wrapped_observation + + pixel_observations = { + pixel_key: self.env.render(**self._render_kwargs[pixel_key]) + for pixel_key in self._pixel_keys + } + + observation.update(pixel_observations) + + return observation diff --git a/gym/wrappers/record_episode_statistics.py b/gym/wrappers/record_episode_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..5d5d348d3a452dbccad077b19c084d733f25382f --- /dev/null +++ b/gym/wrappers/record_episode_statistics.py @@ -0,0 +1,55 @@ +import time +from collections import deque +import numpy as np +import gym + + +class RecordEpisodeStatistics(gym.Wrapper): + def __init__(self, env, deque_size=100): + super(RecordEpisodeStatistics, self).__init__(env) + self.num_envs = getattr(env, "num_envs", 1) + self.t0 = time.perf_counter() + self.episode_count = 0 + self.episode_returns = None + self.episode_lengths = None + self.return_queue = deque(maxlen=deque_size) + self.length_queue = deque(maxlen=deque_size) + self.is_vector_env = getattr(env, "is_vector_env", False) + + def reset(self, **kwargs): + observations = super(RecordEpisodeStatistics, self).reset(**kwargs) + self.episode_returns = np.zeros(self.num_envs, dtype=np.float32) + self.episode_lengths = np.zeros(self.num_envs, dtype=np.int32) + return observations + + def step(self, action): + observations, rewards, dones, infos = super(RecordEpisodeStatistics, self).step( + action + ) + self.episode_returns += rewards + self.episode_lengths += 1 + if not self.is_vector_env: + infos = [infos] + dones = [dones] + for i in range(len(dones)): + if dones[i]: + infos[i] = infos[i].copy() + episode_return = self.episode_returns[i] + episode_length = self.episode_lengths[i] + episode_info = { + "r": episode_return, + "l": episode_length, + "t": round(time.perf_counter() - self.t0, 6), + } + infos[i]["episode"] = episode_info + self.return_queue.append(episode_return) + self.length_queue.append(episode_length) + self.episode_count += 1 + self.episode_returns[i] = 0 + self.episode_lengths[i] = 0 + return ( + observations, + rewards, + dones if self.is_vector_env else dones[0], + infos if self.is_vector_env else infos[0], + ) diff --git a/gym/wrappers/record_video.py b/gym/wrappers/record_video.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b5a4ede731d618cf5af3a8d9e29973f32132ac --- /dev/null +++ b/gym/wrappers/record_video.py @@ -0,0 +1,118 @@ +import os +import gym +from typing import Callable + +from gym import logger +from gym.wrappers.monitoring import video_recorder + + +def capped_cubic_video_schedule(episode_id): + if episode_id < 1000: + return int(round(episode_id ** (1.0 / 3))) ** 3 == episode_id + else: + return episode_id % 1000 == 0 + + +class RecordVideo(gym.Wrapper): + def __init__( + self, + env, + video_folder: str, + episode_trigger: Callable[[int], bool] = None, + step_trigger: Callable[[int], bool] = None, + video_length: int = 0, + name_prefix: str = "rl-video", + ): + super(RecordVideo, self).__init__(env) + + if episode_trigger is None and step_trigger is None: + episode_trigger = capped_cubic_video_schedule + + trigger_count = sum([x is not None for x in [episode_trigger, step_trigger]]) + assert trigger_count == 1, "Must specify exactly one trigger" + + self.episode_trigger = episode_trigger + self.step_trigger = step_trigger + self.video_recorder = None + + self.video_folder = os.path.abspath(video_folder) + # Create output folder if needed + if os.path.isdir(self.video_folder): + logger.warn( + f"Overwriting existing videos at {self.video_folder} folder (try specifying a different `video_folder` for the `RecordVideo` wrapper if this is not desired)" + ) + os.makedirs(self.video_folder, exist_ok=True) + + self.name_prefix = name_prefix + self.step_id = 0 + self.video_length = video_length + + self.recording = False + self.recorded_frames = 0 + self.is_vector_env = getattr(env, "is_vector_env", False) + self.episode_id = 0 + + def reset(self, **kwargs): + observations = super(RecordVideo, self).reset(**kwargs) + if not self.recording and self._video_enabled(): + self.start_video_recorder() + return observations + + def start_video_recorder(self): + self.close_video_recorder() + + video_name = f"{self.name_prefix}-step-{self.step_id}" + if self.episode_trigger: + video_name = f"{self.name_prefix}-episode-{self.episode_id}" + + base_path = os.path.join(self.video_folder, video_name) + self.video_recorder = video_recorder.VideoRecorder( + env=self.env, + base_path=base_path, + metadata={"step_id": self.step_id, "episode_id": self.episode_id}, + ) + + self.video_recorder.capture_frame() + self.recorded_frames = 1 + self.recording = True + + def _video_enabled(self): + if self.step_trigger: + return self.step_trigger(self.step_id) + else: + return self.episode_trigger(self.episode_id) + + def step(self, action): + observations, rewards, dones, infos = super(RecordVideo, self).step(action) + + # increment steps and episodes + self.step_id += 1 + if not self.is_vector_env: + if dones: + self.episode_id += 1 + elif dones[0]: + self.episode_id += 1 + + if self.recording: + self.video_recorder.capture_frame() + self.recorded_frames += 1 + if self.video_length > 0: + if self.recorded_frames > self.video_length: + self.close_video_recorder() + else: + if not self.is_vector_env: + if dones: + self.close_video_recorder() + elif dones[0]: + self.close_video_recorder() + + elif self._video_enabled(): + self.start_video_recorder() + + return observations, rewards, dones, infos + + def close_video_recorder(self) -> None: + if self.recording: + self.video_recorder.close() + self.recording = False + self.recorded_frames = 1 diff --git a/gym/wrappers/rescale_action.py b/gym/wrappers/rescale_action.py new file mode 100644 index 0000000000000000000000000000000000000000..6143d1c1554ad93c5c560f023cc945d1a79b080e --- /dev/null +++ b/gym/wrappers/rescale_action.py @@ -0,0 +1,48 @@ +import numpy as np +import gym +from gym import spaces + + +class RescaleAction(gym.ActionWrapper): + r"""Rescales the continuous action space of the environment to a range [min_action, max_action]. + + Example:: + + >>> RescaleAction(env, min_action, max_action).action_space == Box(min_action, max_action) + True + + """ + + def __init__(self, env, min_action, max_action): + assert isinstance( + env.action_space, spaces.Box + ), "expected Box action space, got {}".format(type(env.action_space)) + assert np.less_equal(min_action, max_action).all(), (min_action, max_action) + + super(RescaleAction, self).__init__(env) + self.min_action = ( + np.zeros(env.action_space.shape, dtype=env.action_space.dtype) + min_action + ) + self.max_action = ( + np.zeros(env.action_space.shape, dtype=env.action_space.dtype) + max_action + ) + self.action_space = spaces.Box( + low=min_action, + high=max_action, + shape=env.action_space.shape, + dtype=env.action_space.dtype, + ) + + def action(self, action): + assert np.all(np.greater_equal(action, self.min_action)), ( + action, + self.min_action, + ) + assert np.all(np.less_equal(action, self.max_action)), (action, self.max_action) + low = self.env.action_space.low + high = self.env.action_space.high + action = low + (high - low) * ( + (action - self.min_action) / (self.max_action - self.min_action) + ) + action = np.clip(action, low, high) + return action diff --git a/gym/wrappers/resize_observation.py b/gym/wrappers/resize_observation.py new file mode 100644 index 0000000000000000000000000000000000000000..4227932e51eb87dd7133fcb253d49c4dd87cf8a4 --- /dev/null +++ b/gym/wrappers/resize_observation.py @@ -0,0 +1,28 @@ +import numpy as np +from gym.spaces import Box +from gym import ObservationWrapper + + +class ResizeObservation(ObservationWrapper): + r"""Downsample the image observation to a square image.""" + + def __init__(self, env, shape): + super(ResizeObservation, self).__init__(env) + if isinstance(shape, int): + shape = (shape, shape) + assert all(x > 0 for x in shape), shape + + self.shape = tuple(shape) + + obs_shape = self.shape + self.observation_space.shape[2:] + self.observation_space = Box(low=0, high=255, shape=obs_shape, dtype=np.uint8) + + def observation(self, observation): + import cv2 + + observation = cv2.resize( + observation, self.shape[::-1], interpolation=cv2.INTER_AREA + ) + if observation.ndim == 2: + observation = np.expand_dims(observation, -1) + return observation diff --git a/gym/wrappers/time_aware_observation.py b/gym/wrappers/time_aware_observation.py new file mode 100644 index 0000000000000000000000000000000000000000..71ec32f5bfce64b8910c6d906acb64bf14ee14e6 --- /dev/null +++ b/gym/wrappers/time_aware_observation.py @@ -0,0 +1,32 @@ +import numpy as np +from gym.spaces import Box +from gym import ObservationWrapper + + +class TimeAwareObservation(ObservationWrapper): + r"""Augment the observation with current time step in the trajectory. + + .. note:: + Currently it only works with one-dimensional observation space. It doesn't + support pixel observation space yet. + + """ + + def __init__(self, env): + super(TimeAwareObservation, self).__init__(env) + assert isinstance(env.observation_space, Box) + assert env.observation_space.dtype == np.float32 + low = np.append(self.observation_space.low, 0.0) + high = np.append(self.observation_space.high, np.inf) + self.observation_space = Box(low, high, dtype=np.float32) + + def observation(self, observation): + return np.append(observation, self.t) + + def step(self, action): + self.t += 1 + return super(TimeAwareObservation, self).step(action) + + def reset(self, **kwargs): + self.t = 0 + return super(TimeAwareObservation, self).reset(**kwargs) diff --git a/gym/wrappers/time_limit.py b/gym/wrappers/time_limit.py new file mode 100644 index 0000000000000000000000000000000000000000..ee8cac96f4ef85b3fdfc0903d11260845d002bda --- /dev/null +++ b/gym/wrappers/time_limit.py @@ -0,0 +1,27 @@ +import gym + + +class TimeLimit(gym.Wrapper): + def __init__(self, env, max_episode_steps=None): + super(TimeLimit, self).__init__(env) + if max_episode_steps is None and self.env.spec is not None: + max_episode_steps = env.spec.max_episode_steps + if self.env.spec is not None: + self.env.spec.max_episode_steps = max_episode_steps + self._max_episode_steps = max_episode_steps + self._elapsed_steps = None + + def step(self, action): + assert ( + self._elapsed_steps is not None + ), "Cannot call env.step() before calling reset()" + observation, reward, done, info = self.env.step(action) + self._elapsed_steps += 1 + if self._elapsed_steps >= self._max_episode_steps: + info["TimeLimit.truncated"] = not done + done = True + return observation, reward, done, info + + def reset(self, **kwargs): + self._elapsed_steps = 0 + return self.env.reset(**kwargs) diff --git a/gym/wrappers/transform_observation.py b/gym/wrappers/transform_observation.py new file mode 100644 index 0000000000000000000000000000000000000000..ade8f9357792043d2a578074413b9267af47194b --- /dev/null +++ b/gym/wrappers/transform_observation.py @@ -0,0 +1,27 @@ +from gym import ObservationWrapper + + +class TransformObservation(ObservationWrapper): + r"""Transform the observation via an arbitrary function. + + Example:: + + >>> import gym + >>> env = gym.make('CartPole-v1') + >>> env = TransformObservation(env, lambda obs: obs + 0.1*np.random.randn(*obs.shape)) + >>> env.reset() + array([-0.08319338, 0.04635121, -0.07394746, 0.20877492]) + + Args: + env (Env): environment + f (callable): a function that transforms the observation + + """ + + def __init__(self, env, f): + super(TransformObservation, self).__init__(env) + assert callable(f) + self.f = f + + def observation(self, observation): + return self.f(observation) diff --git a/gym/wrappers/transform_reward.py b/gym/wrappers/transform_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..cd90c5ebfa69c3a0ef234a425cf42794e1262347 --- /dev/null +++ b/gym/wrappers/transform_reward.py @@ -0,0 +1,29 @@ +from gym import RewardWrapper + + +class TransformReward(RewardWrapper): + r"""Transform the reward via an arbitrary function. + + Example:: + + >>> import gym + >>> env = gym.make('CartPole-v1') + >>> env = TransformReward(env, lambda r: 0.01*r) + >>> env.reset() + >>> observation, reward, done, info = env.step(env.action_space.sample()) + >>> reward + 0.01 + + Args: + env (Env): environment + f (callable): a function that transforms the reward + + """ + + def __init__(self, env, f): + super(TransformReward, self).__init__(env) + assert callable(f) + self.f = f + + def reward(self, reward): + return self.f(reward) diff --git a/video.mp4/rl-video-episode-0.mp4 b/video.mp4/rl-video-episode-0.mp4 index b50d0f7252404ce68867a63f50465dd14c5a57f3..bc4271805b9e43419b7f12a0df1664a752f3b49e 100644 Binary files a/video.mp4/rl-video-episode-0.mp4 and b/video.mp4/rl-video-episode-0.mp4 differ