dm_control_wrapper.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. """
  2. DeepMind Control Suite Wrapper directly sourced from:
  3. https://github.com/denisyarats/dmc2gym
  4. MIT License
  5. Copyright (c) 2020 Denis Yarats
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in all
  13. copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. SOFTWARE.
  21. """
  22. from gym import core, spaces
  23. try:
  24. from dm_env import specs
  25. except ImportError:
  26. specs = None
  27. try:
  28. # Suppress MuJoCo warning (dm_control uses absl logging).
  29. import absl.logging
  30. absl.logging.set_verbosity("error")
  31. from dm_control import suite
  32. except (ImportError, OSError):
  33. suite = None
  34. import numpy as np
  35. def _spec_to_box(spec):
  36. def extract_min_max(s):
  37. assert s.dtype == np.float64 or s.dtype == np.float32
  38. dim = np.int(np.prod(s.shape))
  39. if type(s) == specs.Array:
  40. bound = np.inf * np.ones(dim, dtype=np.float32)
  41. return -bound, bound
  42. elif type(s) == specs.BoundedArray:
  43. zeros = np.zeros(dim, dtype=np.float32)
  44. return s.minimum + zeros, s.maximum + zeros
  45. mins, maxs = [], []
  46. for s in spec:
  47. mn, mx = extract_min_max(s)
  48. mins.append(mn)
  49. maxs.append(mx)
  50. low = np.concatenate(mins, axis=0)
  51. high = np.concatenate(maxs, axis=0)
  52. assert low.shape == high.shape
  53. return spaces.Box(low, high, dtype=np.float32)
  54. def _flatten_obs(obs):
  55. obs_pieces = []
  56. for v in obs.values():
  57. flat = np.array([v]) if np.isscalar(v) else v.ravel()
  58. obs_pieces.append(flat)
  59. return np.concatenate(obs_pieces, axis=0)
  60. class DMCEnv(core.Env):
  61. def __init__(self,
  62. domain_name,
  63. task_name,
  64. task_kwargs=None,
  65. visualize_reward=False,
  66. from_pixels=False,
  67. height=64,
  68. width=64,
  69. camera_id=0,
  70. frame_skip=2,
  71. environment_kwargs=None,
  72. channels_first=True,
  73. preprocess=True):
  74. self._from_pixels = from_pixels
  75. self._height = height
  76. self._width = width
  77. self._camera_id = camera_id
  78. self._frame_skip = frame_skip
  79. self._channels_first = channels_first
  80. self.preprocess = preprocess
  81. if specs is None:
  82. raise RuntimeError((
  83. "The `specs` module from `dm_env` was not imported. Make sure "
  84. "`dm_env` is installed and visible in the current python "
  85. "environment."))
  86. if suite is None:
  87. raise RuntimeError(
  88. ("The `suite` module from `dm_control` was not imported. Make "
  89. "sure `dm_control` is installed and visible in the current "
  90. "python enviornment."))
  91. # create task
  92. self._env = suite.load(
  93. domain_name=domain_name,
  94. task_name=task_name,
  95. task_kwargs=task_kwargs,
  96. visualize_reward=visualize_reward,
  97. environment_kwargs=environment_kwargs)
  98. # true and normalized action spaces
  99. self._true_action_space = _spec_to_box([self._env.action_spec()])
  100. self._norm_action_space = spaces.Box(
  101. low=-1.0,
  102. high=1.0,
  103. shape=self._true_action_space.shape,
  104. dtype=np.float32)
  105. # create observation space
  106. if from_pixels:
  107. shape = [3, height,
  108. width] if channels_first else [height, width, 3]
  109. self._observation_space = spaces.Box(
  110. low=0, high=255, shape=shape, dtype=np.uint8)
  111. if preprocess:
  112. self._observation_space = spaces.Box(
  113. low=-0.5, high=0.5, shape=shape, dtype=np.float32)
  114. else:
  115. self._observation_space = _spec_to_box(
  116. self._env.observation_spec().values())
  117. self._state_space = _spec_to_box(self._env.observation_spec().values())
  118. self.current_state = None
  119. def __getattr__(self, name):
  120. return getattr(self._env, name)
  121. def _get_obs(self, time_step):
  122. if self._from_pixels:
  123. obs = self.render(
  124. height=self._height,
  125. width=self._width,
  126. camera_id=self._camera_id)
  127. if self._channels_first:
  128. obs = obs.transpose(2, 0, 1).copy()
  129. if self.preprocess:
  130. obs = obs / 255.0 - 0.5
  131. else:
  132. obs = _flatten_obs(time_step.observation)
  133. return obs
  134. def _convert_action(self, action):
  135. action = action.astype(np.float64)
  136. true_delta = self._true_action_space.high - self._true_action_space.low
  137. norm_delta = self._norm_action_space.high - self._norm_action_space.low
  138. action = (action - self._norm_action_space.low) / norm_delta
  139. action = action * true_delta + self._true_action_space.low
  140. action = action.astype(np.float32)
  141. return action
  142. @property
  143. def observation_space(self):
  144. return self._observation_space
  145. @property
  146. def state_space(self):
  147. return self._state_space
  148. @property
  149. def action_space(self):
  150. return self._norm_action_space
  151. def step(self, action):
  152. assert self._norm_action_space.contains(action)
  153. action = self._convert_action(action)
  154. assert self._true_action_space.contains(action)
  155. reward = 0
  156. extra = {"internal_state": self._env.physics.get_state().copy()}
  157. for _ in range(self._frame_skip):
  158. time_step = self._env.step(action)
  159. reward += time_step.reward or 0
  160. done = time_step.last()
  161. if done:
  162. break
  163. obs = self._get_obs(time_step)
  164. self.current_state = _flatten_obs(time_step.observation)
  165. extra["discount"] = time_step.discount
  166. return obs, reward, done, extra
  167. def reset(self):
  168. time_step = self._env.reset()
  169. self.current_state = _flatten_obs(time_step.observation)
  170. obs = self._get_obs(time_step)
  171. return obs
  172. def render(self, mode="rgb_array", height=None, width=None, camera_id=0):
  173. assert mode == "rgb_array", "only support for rgb_array mode"
  174. height = height or self._height
  175. width = width or self._width
  176. camera_id = camera_id or self._camera_id
  177. return self._env.physics.render(
  178. height=height, width=width, camera_id=camera_id)