wrappers.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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
  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 RGBImgObsWrapper(gym.core.ObservationWrapper):
  88. """
  89. Wrapper to use fully observable RGB image as the only observation output,
  90. no language/mission. This can be used to have the agent to solve the
  91. gridworld in pixel space.
  92. """
  93. def __init__(self, env, tile_size=8):
  94. super().__init__(env)
  95. self.tile_size = tile_size
  96. self.observation_space = spaces.Box(
  97. low=0,
  98. high=255,
  99. shape=(self.env.width*tile_size, self.env.height*tile_size, 3),
  100. dtype='uint8'
  101. )
  102. def observation(self, obs):
  103. env = self.unwrapped
  104. return env.render(
  105. mode='rgb_array',
  106. highlight=False,
  107. tile_size=self.tile_size
  108. )
  109. class FullyObsWrapper(gym.core.ObservationWrapper):
  110. """
  111. Fully observable gridworld using a compact grid encoding
  112. """
  113. def __init__(self, env):
  114. super().__init__(env)
  115. self.observation_space = spaces.Box(
  116. low=0,
  117. high=255,
  118. shape=(self.env.width, self.env.height, 3), # number of cells
  119. dtype='uint8'
  120. )
  121. def observation(self, obs):
  122. env = self.unwrapped
  123. full_grid = env.grid.encode()
  124. full_grid[env.agent_pos[0]][env.agent_pos[1]] = np.array([
  125. OBJECT_TO_IDX['agent'],
  126. COLOR_TO_IDX['red'],
  127. env.agent_dir
  128. ])
  129. return full_grid
  130. class FlatObsWrapper(gym.core.ObservationWrapper):
  131. """
  132. Encode mission strings using a one-hot scheme,
  133. and combine these with observed images into one flat array
  134. """
  135. def __init__(self, env, maxStrLen=96):
  136. super().__init__(env)
  137. self.maxStrLen = maxStrLen
  138. self.numCharCodes = 27
  139. imgSpace = env.observation_space.spaces['image']
  140. imgSize = reduce(operator.mul, imgSpace.shape, 1)
  141. self.observation_space = spaces.Box(
  142. low=0,
  143. high=255,
  144. shape=(1, imgSize + self.numCharCodes * self.maxStrLen),
  145. dtype='uint8'
  146. )
  147. self.cachedStr = None
  148. self.cachedArray = None
  149. def observation(self, obs):
  150. image = obs['image']
  151. mission = obs['mission']
  152. # Cache the last-encoded mission string
  153. if mission != self.cachedStr:
  154. assert len(mission) <= self.maxStrLen, 'mission string too long ({} chars)'.format(len(mission))
  155. mission = mission.lower()
  156. strArray = np.zeros(shape=(self.maxStrLen, self.numCharCodes), dtype='float32')
  157. for idx, ch in enumerate(mission):
  158. if ch >= 'a' and ch <= 'z':
  159. chNo = ord(ch) - ord('a')
  160. elif ch == ' ':
  161. chNo = ord('z') - ord('a') + 1
  162. assert chNo < self.numCharCodes, '%s : %d' % (ch, chNo)
  163. strArray[idx, chNo] = 1
  164. self.cachedStr = mission
  165. self.cachedArray = strArray
  166. obs = np.concatenate((image.flatten(), self.cachedArray.flatten()))
  167. return obs
  168. class AgentViewWrapper(gym.core.Wrapper):
  169. """
  170. Wrapper to customize the agent field of view size.
  171. """
  172. def __init__(self, env, agent_view_size=7):
  173. super(AgentViewWrapper, self).__init__(env)
  174. # Override default view size
  175. env.unwrapped.agent_view_size = agent_view_size
  176. # Compute observation space with specified view size
  177. observation_space = gym.spaces.Box(
  178. low=0,
  179. high=255,
  180. shape=(agent_view_size, agent_view_size, 3),
  181. dtype='uint8'
  182. )
  183. # Override the environment's observation space
  184. self.observation_space = spaces.Dict({
  185. 'image': observation_space
  186. })
  187. def reset(self, **kwargs):
  188. return self.env.reset(**kwargs)
  189. def step(self, action):
  190. return self.env.step(action)