wrappers.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import math
  2. import operator
  3. from functools import reduce
  4. import numpy as np
  5. import gym
  6. from gym import error, spaces, utils
  7. from .minigrid import OBJECT_TO_IDX, COLOR_TO_IDX, STATE_TO_IDX
  8. from .minigrid import CELL_PIXELS
  9. class ReseedWrapper(gym.core.Wrapper):
  10. """
  11. Wrapper to always regenerate an environment with the same set of seeds.
  12. This can be used to force an environment to always keep the same
  13. configuration when reset.
  14. """
  15. def __init__(self, env, seeds=[0], seed_idx=0):
  16. self.seeds = list(seeds)
  17. self.seed_idx = seed_idx
  18. super().__init__(env)
  19. def reset(self, **kwargs):
  20. seed = self.seeds[self.seed_idx]
  21. self.seed_idx = (self.seed_idx + 1) % len(self.seeds)
  22. self.env.seed(seed)
  23. return self.env.reset(**kwargs)
  24. def step(self, action):
  25. obs, reward, done, info = self.env.step(action)
  26. return obs, reward, done, info
  27. class ActionBonus(gym.core.Wrapper):
  28. """
  29. Wrapper which adds an exploration bonus.
  30. This is a reward to encourage exploration of less
  31. visited (state,action) pairs.
  32. """
  33. def __init__(self, env):
  34. super().__init__(env)
  35. self.counts = {}
  36. def step(self, action):
  37. obs, reward, done, info = self.env.step(action)
  38. env = self.unwrapped
  39. tup = (tuple(env.agent_pos), env.agent_dir, action)
  40. # Get the count for this (s,a) pair
  41. pre_count = 0
  42. if tup in self.counts:
  43. pre_count = self.counts[tup]
  44. # Update the count for this (s,a) pair
  45. new_count = pre_count + 1
  46. self.counts[tup] = new_count
  47. bonus = 1 / math.sqrt(new_count)
  48. reward += bonus
  49. return obs, reward, done, info
  50. def reset(self, **kwargs):
  51. return self.env.reset(**kwargs)
  52. class StateBonus(gym.core.Wrapper):
  53. """
  54. Adds an exploration bonus based on which positions
  55. are visited on the grid.
  56. """
  57. def __init__(self, env):
  58. super().__init__(env)
  59. self.counts = {}
  60. def step(self, action):
  61. obs, reward, done, info = self.env.step(action)
  62. # Tuple based on which we index the counts
  63. # We use the position after an update
  64. env = self.unwrapped
  65. tup = (tuple(env.agent_pos))
  66. # Get the count for this key
  67. pre_count = 0
  68. if tup in self.counts:
  69. pre_count = self.counts[tup]
  70. # Update the count for this key
  71. new_count = pre_count + 1
  72. self.counts[tup] = new_count
  73. bonus = 1 / math.sqrt(new_count)
  74. reward += bonus
  75. return obs, reward, done, info
  76. def reset(self, **kwargs):
  77. return self.env.reset(**kwargs)
  78. class ImgObsWrapper(gym.core.ObservationWrapper):
  79. """
  80. Use the image as the only observation output, no language/mission.
  81. """
  82. def __init__(self, env):
  83. super().__init__(env)
  84. self.observation_space = env.observation_space.spaces['image']
  85. def observation(self, obs):
  86. return obs['image']
  87. class OneHotPartialObsWrapper(gym.core.ObservationWrapper):
  88. """
  89. Wrapper to get a one-hot encoding of a partially observable
  90. agent view as observation.
  91. """
  92. def __init__(self, env, tile_size=8):
  93. super().__init__(env)
  94. self.tile_size = tile_size
  95. obs_shape = env.observation_space['image'].shape
  96. num_bits = len(OBJECT_TO_IDX) + len(COLOR_TO_IDX) + len(STATE_TO_IDX)
  97. self.observation_space = spaces.Box(
  98. low=0,
  99. high=255,
  100. shape=(obs_shape[0], obs_shape[1], num_bits),
  101. dtype='uint8'
  102. )
  103. def observation(self, obs):
  104. img = obs['image']
  105. out = np.zeros(self.observation_space.shape, dtype='uint8')
  106. for i in range(img.shape[0]):
  107. for j in range(img.shape[1]):
  108. type = img[i, j, 0]
  109. color = img[i, j, 1]
  110. state = img[i, j, 2]
  111. out[i, j, type] = 1
  112. out[i, j, len(OBJECT_TO_IDX) + color] = 1
  113. out[i, j, len(OBJECT_TO_IDX) + len(COLOR_TO_IDX) + state] = 1
  114. return {
  115. 'mission': obs['mission'],
  116. 'image': out
  117. }
  118. class RGBImgObsWrapper(gym.core.ObservationWrapper):
  119. """
  120. Wrapper to use fully observable RGB image as the only observation output,
  121. no language/mission. This can be used to have the agent to solve the
  122. gridworld in pixel space.
  123. """
  124. def __init__(self, env, tile_size=8):
  125. super().__init__(env)
  126. self.tile_size = tile_size
  127. self.observation_space = spaces.Box(
  128. low=0,
  129. high=255,
  130. shape=(self.env.width*tile_size, self.env.height*tile_size, 3),
  131. dtype='uint8'
  132. )
  133. def observation(self, obs):
  134. env = self.unwrapped
  135. return env.render(
  136. mode='rgb_array',
  137. highlight=False,
  138. tile_size=self.tile_size
  139. )
  140. class RGBImgPartialObsWrapper(gym.core.ObservationWrapper):
  141. """
  142. Wrapper to use partially observable RGB image as the only observation output
  143. This can be used to have the agent to solve the gridworld in pixel space.
  144. """
  145. def __init__(self, env, tile_size=8):
  146. super().__init__(env)
  147. self.tile_size = tile_size
  148. obs_shape = env.observation_space['image'].shape
  149. self.observation_space = spaces.Box(
  150. low=0,
  151. high=255,
  152. shape=(obs_shape[0] * tile_size, obs_shape[1] * tile_size, 3),
  153. dtype='uint8'
  154. )
  155. def observation(self, obs):
  156. env = self.unwrapped
  157. return {
  158. 'mission': obs['mission'],
  159. 'image': env.get_obs_render(obs['image'], tile_size=self.tile_size, mode='rgb_array')
  160. }
  161. class FullyObsWrapper(gym.core.ObservationWrapper):
  162. """
  163. Fully observable gridworld using a compact grid encoding
  164. """
  165. def __init__(self, env):
  166. super().__init__(env)
  167. self.observation_space = spaces.Box(
  168. low=0,
  169. high=255,
  170. shape=(self.env.width, self.env.height, 3), # number of cells
  171. dtype='uint8'
  172. )
  173. def observation(self, obs):
  174. env = self.unwrapped
  175. full_grid = env.grid.encode()
  176. full_grid[env.agent_pos[0]][env.agent_pos[1]] = np.array([
  177. OBJECT_TO_IDX['agent'],
  178. COLOR_TO_IDX['red'],
  179. env.agent_dir
  180. ])
  181. return full_grid
  182. class FlatObsWrapper(gym.core.ObservationWrapper):
  183. """
  184. Encode mission strings using a one-hot scheme,
  185. and combine these with observed images into one flat array
  186. """
  187. def __init__(self, env, maxStrLen=96):
  188. super().__init__(env)
  189. self.maxStrLen = maxStrLen
  190. self.numCharCodes = 27
  191. imgSpace = env.observation_space.spaces['image']
  192. imgSize = reduce(operator.mul, imgSpace.shape, 1)
  193. self.observation_space = spaces.Box(
  194. low=0,
  195. high=255,
  196. shape=(1, imgSize + self.numCharCodes * self.maxStrLen),
  197. dtype='uint8'
  198. )
  199. self.cachedStr = None
  200. self.cachedArray = None
  201. def observation(self, obs):
  202. image = obs['image']
  203. mission = obs['mission']
  204. # Cache the last-encoded mission string
  205. if mission != self.cachedStr:
  206. assert len(mission) <= self.maxStrLen, 'mission string too long ({} chars)'.format(len(mission))
  207. mission = mission.lower()
  208. strArray = np.zeros(shape=(self.maxStrLen, self.numCharCodes), dtype='float32')
  209. for idx, ch in enumerate(mission):
  210. if ch >= 'a' and ch <= 'z':
  211. chNo = ord(ch) - ord('a')
  212. elif ch == ' ':
  213. chNo = ord('z') - ord('a') + 1
  214. assert chNo < self.numCharCodes, '%s : %d' % (ch, chNo)
  215. strArray[idx, chNo] = 1
  216. self.cachedStr = mission
  217. self.cachedArray = strArray
  218. obs = np.concatenate((image.flatten(), self.cachedArray.flatten()))
  219. return obs
  220. class AgentViewWrapper(gym.core.Wrapper):
  221. """
  222. Wrapper to customize the agent field of view size.
  223. """
  224. def __init__(self, env, agent_view_size=7):
  225. super(AgentViewWrapper, self).__init__(env)
  226. # Override default view size
  227. env.unwrapped.agent_view_size = agent_view_size
  228. # Compute observation space with specified view size
  229. observation_space = gym.spaces.Box(
  230. low=0,
  231. high=255,
  232. shape=(agent_view_size, agent_view_size, 3),
  233. dtype='uint8'
  234. )
  235. # Override the environment's observation space
  236. self.observation_space = spaces.Dict({
  237. 'image': observation_space
  238. })
  239. def reset(self, **kwargs):
  240. return self.env.reset(**kwargs)
  241. def step(self, action):
  242. return self.env.step(action)