envs.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import os
  2. import numpy
  3. import gym
  4. from gym.spaces.box import Box
  5. from baselines import bench
  6. from baselines.common.atari_wrappers import make_atari, wrap_deepmind
  7. try:
  8. import pybullet_envs
  9. except ImportError:
  10. pass
  11. try:
  12. import gym_minigrid
  13. from gym_minigrid.wrappers import *
  14. except:
  15. pass
  16. def make_env(env_id, seed, rank, log_dir):
  17. def _thunk():
  18. env = gym.make(env_id)
  19. is_atari = hasattr(gym.envs, 'atari') and isinstance(env.unwrapped, gym.envs.atari.atari_env.AtariEnv)
  20. if is_atari:
  21. env = make_atari(env_id)
  22. env.seed(seed + rank)
  23. if log_dir is not None:
  24. env = bench.Monitor(env, os.path.join(log_dir, str(rank)))
  25. if is_atari:
  26. env = wrap_deepmind(env)
  27. # If the input has shape (W,H,3), wrap for PyTorch convolutions
  28. obs_shape = env.observation_space.shape
  29. if len(obs_shape) == 3 and obs_shape[2] == 3:
  30. env = WrapPyTorch(env)
  31. #env = StateBonus(env)
  32. return env
  33. return _thunk
  34. class WrapPyTorch(gym.ObservationWrapper):
  35. def __init__(self, env=None):
  36. super(WrapPyTorch, self).__init__(env)
  37. obs_shape = self.observation_space.shape
  38. self.observation_space = Box(
  39. self.observation_space.low[0,0,0],
  40. self.observation_space.high[0,0,0],
  41. [obs_shape[2], obs_shape[1], obs_shape[0]]
  42. )
  43. def _observation(self, observation):
  44. return observation.transpose(2, 0, 1)