wrappers.py 6.7 KB

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