dreamerv3-torch/envs/wrappers.py

128 lines
3.7 KiB
Python
Raw Normal View History

import datetime
2023-04-15 23:16:43 +09:00
import gym
import numpy as np
2023-04-24 06:25:17 +09:00
import uuid
2023-04-15 23:16:43 +09:00
class TimeLimit(gym.Wrapper):
2023-04-23 22:52:30 +09:00
def __init__(self, env, duration):
super().__init__(env)
2023-04-23 22:52:30 +09:00
self._duration = duration
self._step = None
def step(self, action):
assert self._step is not None, "Must reset environment."
obs, reward, done, info = self.env.step(action)
2023-04-23 22:52:30 +09:00
self._step += 1
if self._step >= self._duration:
done = True
if "discount" not in info:
info["discount"] = np.array(1.0).astype(np.float32)
self._step = None
return obs, reward, done, info
def reset(self):
self._step = 0
return self.env.reset()
2023-04-15 23:16:43 +09:00
class NormalizeActions(gym.Wrapper):
2023-04-23 22:52:30 +09:00
def __init__(self, env):
super().__init__(env)
2023-04-23 22:52:30 +09:00
self._mask = np.logical_and(
np.isfinite(env.action_space.low), np.isfinite(env.action_space.high)
)
self._low = np.where(self._mask, env.action_space.low, -1)
self._high = np.where(self._mask, env.action_space.high, 1)
2023-04-15 23:16:43 +09:00
2023-04-23 22:52:30 +09:00
def action_space(self):
low = np.where(self._mask, -np.ones_like(self._low), self._low)
high = np.where(self._mask, np.ones_like(self._low), self._high)
return gym.spaces.Box(low, high, dtype=np.float32)
2023-04-15 23:16:43 +09:00
2023-04-23 22:52:30 +09:00
def step(self, action):
original = (action + 1) / 2 * (self._high - self._low) + self._low
original = np.where(self._mask, original, action)
return self.env.step(original)
2023-04-15 23:16:43 +09:00
class OneHotAction(gym.Wrapper):
2023-04-23 22:52:30 +09:00
def __init__(self, env):
assert isinstance(env.action_space, gym.spaces.Discrete)
super().__init__(env)
2023-04-23 22:52:30 +09:00
self._random = np.random.RandomState()
def action_space(self):
shape = (self.env.action_space.n,)
2023-04-23 22:52:30 +09:00
space = gym.spaces.Box(low=0, high=1, shape=shape, dtype=np.float32)
space.sample = self._sample_action
space.discrete = True
return space
def step(self, action):
index = np.argmax(action).astype(int)
reference = np.zeros_like(action)
reference[index] = 1
if not np.allclose(reference, action):
raise ValueError(f"Invalid one-hot action:\n{action}")
return self.env.step(index)
2023-04-23 22:52:30 +09:00
def reset(self):
return self.env.reset()
2023-04-23 22:52:30 +09:00
def _sample_action(self):
actions = self.env.action_space.n
2023-04-23 22:52:30 +09:00
index = self._random.randint(0, actions)
reference = np.zeros(actions, dtype=np.float32)
reference[index] = 1.0
return reference
2023-04-15 23:16:43 +09:00
class RewardObs(gym.Wrapper):
2023-04-23 22:52:30 +09:00
def __init__(self, env):
super().__init__(env)
2023-04-15 23:16:43 +09:00
2023-04-23 22:52:30 +09:00
def observation_space(self):
spaces = self.env.observation_space.spaces
2023-06-18 00:02:22 +09:00
if "reward" not in spaces:
spaces["reward"] = gym.spaces.Box(
-np.inf, np.inf, shape=(1,), dtype=np.float32
)
2023-04-23 22:52:30 +09:00
return gym.spaces.Dict(spaces)
2023-04-15 23:16:43 +09:00
2023-04-23 22:52:30 +09:00
def step(self, action):
obs, reward, done, info = self.env.step(action)
2023-06-18 00:02:22 +09:00
if "reward" not in obs:
obs["reward"] = reward
2023-04-23 22:52:30 +09:00
return obs, reward, done, info
2023-04-15 23:16:43 +09:00
2023-04-23 22:52:30 +09:00
def reset(self):
obs = self.env.reset()
2023-06-18 00:02:22 +09:00
if "reward" not in obs:
obs["reward"] = 0.0
2023-04-23 22:52:30 +09:00
return obs
2023-04-15 23:16:43 +09:00
class SelectAction(gym.Wrapper):
2023-04-23 22:52:30 +09:00
def __init__(self, env, key):
super().__init__(env)
2023-04-23 22:52:30 +09:00
self._key = key
2023-04-15 23:16:43 +09:00
2023-04-23 22:52:30 +09:00
def step(self, action):
return self.env.step(action[self._key])
class UUID(gym.Wrapper):
def __init__(self, env):
super().__init__(env)
timestamp = datetime.datetime.now().strftime("%Y%m%dT%H%M%S")
self.id = f"{timestamp}-{str(uuid.uuid4().hex)}"
def reset(self):
timestamp = datetime.datetime.now().strftime("%Y%m%dT%H%M%S")
self.id = f"{timestamp}-{str(uuid.uuid4().hex)}"
return self.env.reset()