wrappers.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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, Goal
  8. class ReseedWrapper(gym.core.Wrapper):
  9. """
  10. Wrapper to always regenerate an environment with the same set of seeds.
  11. This can be used to force an environment to always keep the same
  12. configuration when reset.
  13. """
  14. def __init__(self, env, seeds=[0], seed_idx=0):
  15. self.seeds = list(seeds)
  16. self.seed_idx = seed_idx
  17. super().__init__(env)
  18. def reset(self, **kwargs):
  19. seed = self.seeds[self.seed_idx]
  20. self.seed_idx = (self.seed_idx + 1) % len(self.seeds)
  21. self.env.seed(seed)
  22. return self.env.reset(**kwargs)
  23. def step(self, action):
  24. obs, reward, done, info = self.env.step(action)
  25. return obs, reward, done, info
  26. class ActionBonus(gym.core.Wrapper):
  27. """
  28. Wrapper which adds an exploration bonus.
  29. This is a reward to encourage exploration of less
  30. visited (state,action) pairs.
  31. """
  32. def __init__(self, env):
  33. super().__init__(env)
  34. self.counts = {}
  35. def step(self, action):
  36. obs, reward, done, info = self.env.step(action)
  37. env = self.unwrapped
  38. tup = (tuple(env.agent_pos), env.agent_dir, action)
  39. # Get the count for this (s,a) pair
  40. pre_count = 0
  41. if tup in self.counts:
  42. pre_count = self.counts[tup]
  43. # Update the count for this (s,a) pair
  44. new_count = pre_count + 1
  45. self.counts[tup] = new_count
  46. bonus = 1 / math.sqrt(new_count)
  47. reward += bonus
  48. return obs, reward, done, info
  49. def reset(self, **kwargs):
  50. return self.env.reset(**kwargs)
  51. class StateBonus(gym.core.Wrapper):
  52. """
  53. Adds an exploration bonus based on which positions
  54. are visited on the grid.
  55. """
  56. def __init__(self, env):
  57. super().__init__(env)
  58. self.counts = {}
  59. def step(self, action):
  60. obs, reward, done, info = self.env.step(action)
  61. # Tuple based on which we index the counts
  62. # We use the position after an update
  63. env = self.unwrapped
  64. tup = (tuple(env.agent_pos))
  65. # Get the count for this key
  66. pre_count = 0
  67. if tup in self.counts:
  68. pre_count = self.counts[tup]
  69. # Update the count for this key
  70. new_count = pre_count + 1
  71. self.counts[tup] = new_count
  72. bonus = 1 / math.sqrt(new_count)
  73. reward += bonus
  74. return obs, reward, done, info
  75. def reset(self, **kwargs):
  76. return self.env.reset(**kwargs)
  77. class ImgObsWrapper(gym.core.ObservationWrapper):
  78. """
  79. Use the image as the only observation output, no language/mission.
  80. """
  81. def __init__(self, env):
  82. super().__init__(env)
  83. self.observation_space = env.observation_space.spaces['image']
  84. def observation(self, obs):
  85. return obs['image']
  86. class OneHotPartialObsWrapper(gym.core.ObservationWrapper):
  87. """
  88. Wrapper to get a one-hot encoding of a partially observable
  89. agent view as observation.
  90. """
  91. def __init__(self, env, tile_size=8):
  92. super().__init__(env)
  93. self.tile_size = tile_size
  94. obs_shape = env.observation_space['image'].shape
  95. # Number of bits per cell
  96. num_bits = len(OBJECT_TO_IDX) + len(COLOR_TO_IDX) + len(STATE_TO_IDX)
  97. self.observation_space.spaces["image"] = 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.spaces['image'].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. **obs,
  116. 'image': out
  117. }
  118. class RGBImgObsWrapper(gym.core.ObservationWrapper):
  119. """
  120. Wrapper to use fully observable RGB image as observation,
  121. This can be used to have the agent to solve the gridworld in pixel space.
  122. """
  123. def __init__(self, env, tile_size=8):
  124. super().__init__(env)
  125. self.tile_size = tile_size
  126. self.observation_space.spaces['image'] = spaces.Box(
  127. low=0,
  128. high=255,
  129. shape=(self.env.width * tile_size, self.env.height * tile_size, 3),
  130. dtype='uint8'
  131. )
  132. def observation(self, obs):
  133. env = self.unwrapped
  134. rgb_img = env.render(
  135. mode='rgb_array',
  136. highlight=False,
  137. tile_size=self.tile_size
  138. )
  139. return {
  140. **obs,
  141. 'image': rgb_img
  142. }
  143. class RGBImgPartialObsWrapper(gym.core.ObservationWrapper):
  144. """
  145. Wrapper to use partially observable RGB image as observation.
  146. This can be used to have the agent to solve the gridworld in pixel space.
  147. """
  148. def __init__(self, env, tile_size=8):
  149. super().__init__(env)
  150. self.tile_size = tile_size
  151. obs_shape = env.observation_space.spaces['image'].shape
  152. self.observation_space.spaces['image'] = spaces.Box(
  153. low=0,
  154. high=255,
  155. shape=(obs_shape[0] * tile_size, obs_shape[1] * tile_size, 3),
  156. dtype='uint8'
  157. )
  158. def observation(self, obs):
  159. env = self.unwrapped
  160. rgb_img_partial = env.get_obs_render(
  161. obs['image'],
  162. tile_size=self.tile_size
  163. )
  164. return {
  165. **obs,
  166. 'image': rgb_img_partial
  167. }
  168. class FullyObsWrapper(gym.core.ObservationWrapper):
  169. """
  170. Fully observable gridworld using a compact grid encoding
  171. """
  172. def __init__(self, env):
  173. super().__init__(env)
  174. self.observation_space.spaces["image"] = spaces.Box(
  175. low=0,
  176. high=255,
  177. shape=(self.env.width, self.env.height, 3), # number of cells
  178. dtype='uint8'
  179. )
  180. def observation(self, obs):
  181. env = self.unwrapped
  182. full_grid = env.grid.encode()
  183. full_grid[env.agent_pos[0]][env.agent_pos[1]] = np.array([
  184. OBJECT_TO_IDX['agent'],
  185. COLOR_TO_IDX['red'],
  186. env.agent_dir
  187. ])
  188. return {
  189. **obs,
  190. 'image': full_grid
  191. }
  192. class FlatObsWrapper(gym.core.ObservationWrapper):
  193. """
  194. Encode mission strings using a one-hot scheme,
  195. and combine these with observed images into one flat array
  196. """
  197. def __init__(self, env, maxStrLen=96):
  198. super().__init__(env)
  199. self.maxStrLen = maxStrLen
  200. self.numCharCodes = 27
  201. imgSpace = env.observation_space.spaces['image']
  202. imgSize = reduce(operator.mul, imgSpace.shape, 1)
  203. self.observation_space = spaces.Box(
  204. low=0,
  205. high=255,
  206. shape=(imgSize + self.numCharCodes * self.maxStrLen,),
  207. dtype='uint8'
  208. )
  209. self.cachedStr = None
  210. self.cachedArray = None
  211. def observation(self, obs):
  212. image = obs['image']
  213. mission = obs['mission']
  214. # Cache the last-encoded mission string
  215. if mission != self.cachedStr:
  216. assert len(mission) <= self.maxStrLen, 'mission string too long ({} chars)'.format(len(mission))
  217. mission = mission.lower()
  218. strArray = np.zeros(shape=(self.maxStrLen, self.numCharCodes), dtype='float32')
  219. for idx, ch in enumerate(mission):
  220. if ch >= 'a' and ch <= 'z':
  221. chNo = ord(ch) - ord('a')
  222. elif ch == ' ':
  223. chNo = ord('z') - ord('a') + 1
  224. assert chNo < self.numCharCodes, '%s : %d' % (ch, chNo)
  225. strArray[idx, chNo] = 1
  226. self.cachedStr = mission
  227. self.cachedArray = strArray
  228. obs = np.concatenate((image.flatten(), self.cachedArray.flatten()))
  229. return obs
  230. class ViewSizeWrapper(gym.core.Wrapper):
  231. """
  232. Wrapper to customize the agent field of view size.
  233. This cannot be used with fully observable wrappers.
  234. """
  235. def __init__(self, env, agent_view_size=7):
  236. super().__init__(env)
  237. assert agent_view_size % 2 == 1
  238. assert agent_view_size >= 3
  239. # Override default view size
  240. env.unwrapped.agent_view_size = agent_view_size
  241. # Compute observation space with specified view size
  242. observation_space = gym.spaces.Box(
  243. low=0,
  244. high=255,
  245. shape=(agent_view_size, agent_view_size, 3),
  246. dtype='uint8'
  247. )
  248. # Override the environment's observation space
  249. self.observation_space = spaces.Dict({
  250. 'image': observation_space
  251. })
  252. def reset(self, **kwargs):
  253. return self.env.reset(**kwargs)
  254. def step(self, action):
  255. return self.env.step(action)
  256. class DirectionObsWrapper(gym.core.ObservationWrapper):
  257. """
  258. Provides the slope/angular direction to the goal with the observations as modeled by (y2 - y2 )/( x2 - x1)
  259. type = {slope , angle}
  260. """
  261. def __init__(self, env,type='slope'):
  262. super().__init__(env)
  263. self.goal_position = None
  264. self.type = type
  265. def reset(self):
  266. obs = self.env.reset()
  267. if not self.goal_position:
  268. self.goal_position = [x for x,y in enumerate(self.grid.grid) if isinstance(y,(Goal) ) ]
  269. if len(self.goal_position) >= 1: # in case there are multiple goals , needs to be handled for other env types
  270. self.goal_position = (int(self.goal_position[0]/self.height) , self.goal_position[0]%self.width)
  271. return obs
  272. def observation(self, obs):
  273. slope = np.divide( self.goal_position[1] - self.agent_pos[1] , self.goal_position[0] - self.agent_pos[0])
  274. obs['goal_direction'] = np.arctan( slope ) if self.type == 'angle' else slope
  275. return obs
  276. class SymbolicObsWrapper(gym.core.ObservationWrapper):
  277. """
  278. Fully observable grid with a symbolic state representation.
  279. The symbol is a triple of (X, Y, IDX), where X and Y are
  280. the coordinates on the grid, and IDX is the id of the object.
  281. """
  282. def __init__(self, env):
  283. super().__init__(env)
  284. self.observation_space.spaces["image"] = spaces.Box(
  285. low=0,
  286. high=max(OBJECT_TO_IDX.values()),
  287. shape=(self.env.width, self.env.height, 3), # number of cells
  288. dtype="uint8",
  289. )
  290. def observation(self, obs):
  291. objects = np.array(
  292. [OBJECT_TO_IDX[o.type] if o is not None else -1 for o in self.grid.grid]
  293. )
  294. w, h = self.width, self.height
  295. grid = np.mgrid[:w, :h]
  296. grid = np.concatenate([grid, objects.reshape(1, w, h)])
  297. grid = np.transpose(grid, (1, 2, 0))
  298. obs['image'] = grid
  299. return obs