wrappers.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. return self.env.reset(seed=seed, **kwargs)
  22. def step(self, action):
  23. obs, reward, done, info = self.env.step(action)
  24. return obs, reward, done, info
  25. class ActionBonus(gym.core.Wrapper):
  26. """
  27. Wrapper which adds an exploration bonus.
  28. This is a reward to encourage exploration of less
  29. visited (state,action) pairs.
  30. """
  31. def __init__(self, env):
  32. super().__init__(env)
  33. self.counts = {}
  34. def step(self, action):
  35. obs, reward, done, info = self.env.step(action)
  36. env = self.unwrapped
  37. tup = (tuple(env.agent_pos), env.agent_dir, action)
  38. # Get the count for this (s,a) pair
  39. pre_count = 0
  40. if tup in self.counts:
  41. pre_count = self.counts[tup]
  42. # Update the count for this (s,a) pair
  43. new_count = pre_count + 1
  44. self.counts[tup] = new_count
  45. bonus = 1 / math.sqrt(new_count)
  46. reward += bonus
  47. return obs, reward, done, info
  48. def reset(self, **kwargs):
  49. return self.env.reset(**kwargs)
  50. class StateBonus(gym.core.Wrapper):
  51. """
  52. Adds an exploration bonus based on which positions
  53. are visited on the grid.
  54. """
  55. def __init__(self, env):
  56. super().__init__(env)
  57. self.counts = {}
  58. def step(self, action):
  59. obs, reward, done, info = self.env.step(action)
  60. # Tuple based on which we index the counts
  61. # We use the position after an update
  62. env = self.unwrapped
  63. tup = (tuple(env.agent_pos))
  64. # Get the count for this key
  65. pre_count = 0
  66. if tup in self.counts:
  67. pre_count = self.counts[tup]
  68. # Update the count for this key
  69. new_count = pre_count + 1
  70. self.counts[tup] = new_count
  71. bonus = 1 / math.sqrt(new_count)
  72. reward += bonus
  73. return obs, reward, done, info
  74. def reset(self, **kwargs):
  75. return self.env.reset(**kwargs)
  76. class ImgObsWrapper(gym.core.ObservationWrapper):
  77. """
  78. Use the image as the only observation output, no language/mission.
  79. """
  80. def __init__(self, env):
  81. super().__init__(env)
  82. self.observation_space = env.observation_space.spaces['image']
  83. def observation(self, obs):
  84. return obs['image']
  85. class OneHotPartialObsWrapper(gym.core.ObservationWrapper):
  86. """
  87. Wrapper to get a one-hot encoding of a partially observable
  88. agent view as observation.
  89. """
  90. def __init__(self, env, tile_size=8):
  91. super().__init__(env)
  92. self.tile_size = tile_size
  93. obs_shape = env.observation_space['image'].shape
  94. # Number of bits per cell
  95. num_bits = len(OBJECT_TO_IDX) + len(COLOR_TO_IDX) + len(STATE_TO_IDX)
  96. new_image_space = spaces.Box(
  97. low=0,
  98. high=255,
  99. shape=(obs_shape[0], obs_shape[1], num_bits),
  100. dtype='uint8'
  101. )
  102. self.observation_space = spaces.Dict({**self.observation_space, 'image':new_image_space})
  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. new_image_space = 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. self.observation_space = spaces.Dict({**self.observation_space, 'image':new_image_space})
  133. def observation(self, obs):
  134. env = self.unwrapped
  135. rgb_img = env.render(
  136. mode='rgb_array',
  137. highlight=False,
  138. tile_size=self.tile_size
  139. )
  140. return {
  141. **obs,
  142. 'image': rgb_img
  143. }
  144. class RGBImgPartialObsWrapper(gym.core.ObservationWrapper):
  145. """
  146. Wrapper to use partially observable RGB image as observation.
  147. This can be used to have the agent to solve the gridworld in pixel space.
  148. """
  149. def __init__(self, env, tile_size=8):
  150. super().__init__(env)
  151. self.tile_size = tile_size
  152. obs_shape = env.observation_space.spaces['image'].shape
  153. new_image_space = spaces.Box(
  154. low=0,
  155. high=255,
  156. shape=(obs_shape[0] * tile_size, obs_shape[1] * tile_size, 3),
  157. dtype='uint8'
  158. )
  159. self.observation_space = spaces.Dict({**self.observation_space, 'image':new_image_space})
  160. def observation(self, obs):
  161. env = self.unwrapped
  162. rgb_img_partial = env.get_obs_render(
  163. obs['image'],
  164. tile_size=self.tile_size
  165. )
  166. return {
  167. **obs,
  168. 'image': rgb_img_partial
  169. }
  170. class FullyObsWrapper(gym.core.ObservationWrapper):
  171. """
  172. Fully observable gridworld using a compact grid encoding
  173. """
  174. def __init__(self, env):
  175. super().__init__(env)
  176. new_image_space = spaces.Box(
  177. low=0,
  178. high=255,
  179. shape=(self.env.width, self.env.height, 3), # number of cells
  180. dtype='uint8'
  181. )
  182. self.observation_space = spaces.Dict({**self.observation_space, 'image':new_image_space})
  183. def observation(self, obs):
  184. env = self.unwrapped
  185. full_grid = env.grid.encode()
  186. full_grid[env.agent_pos[0]][env.agent_pos[1]] = np.array([
  187. OBJECT_TO_IDX['agent'],
  188. COLOR_TO_IDX['red'],
  189. env.agent_dir
  190. ])
  191. return {
  192. **obs,
  193. 'image': full_grid
  194. }
  195. class DictObservationSpaceWrapper(gym.core.ObservationWrapper):
  196. """
  197. Use a Dict Obsevation Space encoding images, missions, and directions
  198. """
  199. def __init__(self, env, max_words_in_mission=50, word_dict=None):
  200. """
  201. max_words_in_mission is the length of the array to represent a mission, value 0 for missing words
  202. word_dict is a dictionary of words to use (keys=words, values=indices from 1 to < max_words_in_mission),
  203. if None, use the Minigrid language
  204. """
  205. super().__init__(env)
  206. if word_dict is None:
  207. word_dict = DictObservationSpaceWrapper.get_minigrid_words()
  208. self.max_words_in_mission = max_words_in_mission
  209. self.word_dict = word_dict
  210. image_observation_space = spaces.Box(
  211. low=0,
  212. high=255,
  213. shape=(self.agent_view_size, self.agent_view_size, 3),
  214. dtype='uint8'
  215. )
  216. self.observation_space = spaces.Dict({
  217. 'image': image_observation_space,
  218. 'direction': spaces.Discrete(4),
  219. 'mission': spaces.MultiDiscrete([len(self.word_dict.keys())]
  220. * max_words_in_mission)
  221. })
  222. @staticmethod
  223. def get_minigrid_words():
  224. colors = ['red', 'green', 'blue', 'yellow', 'purple', 'grey']
  225. objects = ['unseen', 'empty', 'wall', 'floor', 'box', 'key', 'ball',
  226. 'door', 'goal', 'agent', 'lava']
  227. verbs = ['pick', 'avoid', 'get', 'find', 'put',
  228. 'use', 'open', 'go', 'fetch',
  229. 'reach', 'unlock', 'traverse']
  230. extra_words = ['up', 'the', 'a', 'at', ',', 'square',
  231. 'and', 'then', 'to', 'of', 'rooms', 'near',
  232. 'opening', 'must', 'you', 'matching', 'end',
  233. 'hallway', 'object', 'from', 'room']
  234. all_words = colors + objects + verbs + extra_words
  235. assert len(all_words) == len(set(all_words))
  236. return {word: i for i, word in enumerate(all_words)}
  237. def string_to_indices(self, string, offset=1):
  238. """
  239. Convert a string to a list of indices.
  240. """
  241. indices = []
  242. string = string.replace(',', ' , ') # adding space before and after commas
  243. for word in string.split():
  244. if word in self.word_dict.keys():
  245. indices.append(self.word_dict[word] + offset)
  246. else:
  247. raise ValueError('Unknown word: {}'.format(word))
  248. return indices
  249. def observation(self, obs):
  250. obs['mission'] = self.string_to_indices(obs['mission'])
  251. assert len(obs['mission']) < self.max_words_in_mission
  252. obs['mission'] += [0] * (self.max_words_in_mission - len(obs['mission']))
  253. return obs
  254. class FlatObsWrapper(gym.core.ObservationWrapper):
  255. """
  256. Encode mission strings using a one-hot scheme,
  257. and combine these with observed images into one flat array
  258. """
  259. def __init__(self, env, maxStrLen=96):
  260. super().__init__(env)
  261. self.maxStrLen = maxStrLen
  262. self.numCharCodes = 27
  263. imgSpace = env.observation_space.spaces['image']
  264. imgSize = reduce(operator.mul, imgSpace.shape, 1)
  265. self.observation_space = spaces.Box(
  266. low=0,
  267. high=255,
  268. shape=(imgSize + self.numCharCodes * self.maxStrLen,),
  269. dtype='uint8'
  270. )
  271. self.cachedStr = None
  272. self.cachedArray = None
  273. def observation(self, obs):
  274. image = obs['image']
  275. mission = obs['mission']
  276. # Cache the last-encoded mission string
  277. if mission != self.cachedStr:
  278. assert len(mission) <= self.maxStrLen, 'mission string too long ({} chars)'.format(len(mission))
  279. mission = mission.lower()
  280. strArray = np.zeros(shape=(self.maxStrLen, self.numCharCodes), dtype='float32')
  281. for idx, ch in enumerate(mission):
  282. if ch >= 'a' and ch <= 'z':
  283. chNo = ord(ch) - ord('a')
  284. elif ch == ' ':
  285. chNo = ord('z') - ord('a') + 1
  286. assert chNo < self.numCharCodes, '%s : %d' % (ch, chNo)
  287. strArray[idx, chNo] = 1
  288. self.cachedStr = mission
  289. self.cachedArray = strArray
  290. obs = np.concatenate((image.flatten(), self.cachedArray.flatten()))
  291. return obs
  292. class ViewSizeWrapper(gym.core.Wrapper):
  293. """
  294. Wrapper to customize the agent field of view size.
  295. This cannot be used with fully observable wrappers.
  296. """
  297. def __init__(self, env, agent_view_size=7):
  298. super().__init__(env)
  299. assert agent_view_size % 2 == 1
  300. assert agent_view_size >= 3
  301. # Override default view size
  302. env.unwrapped.agent_view_size = agent_view_size
  303. # Compute observation space with specified view size
  304. new_image_space = gym.spaces.Box(
  305. low=0,
  306. high=255,
  307. shape=(agent_view_size, agent_view_size, 3),
  308. dtype='uint8'
  309. )
  310. # Override the environment's observation spaceexit
  311. self.observation_space = spaces.Dict({**self.observation_space, 'image':new_image_space})
  312. def reset(self, **kwargs):
  313. return self.env.reset(**kwargs)
  314. def step(self, action):
  315. return self.env.step(action)
  316. class DirectionObsWrapper(gym.core.ObservationWrapper):
  317. """
  318. Provides the slope/angular direction to the goal with the observations as modeled by (y2 - y2 )/( x2 - x1)
  319. type = {slope , angle}
  320. """
  321. def __init__(self, env,type='slope'):
  322. super().__init__(env)
  323. self.goal_position = None
  324. self.type = type
  325. def reset(self):
  326. obs = self.env.reset()
  327. if not self.goal_position:
  328. self.goal_position = [x for x,y in enumerate(self.grid.grid) if isinstance(y,(Goal) ) ]
  329. if len(self.goal_position) >= 1: # in case there are multiple goals , needs to be handled for other env types
  330. self.goal_position = (int(self.goal_position[0]/self.height) , self.goal_position[0]%self.width)
  331. return obs
  332. def observation(self, obs):
  333. slope = np.divide( self.goal_position[1] - self.agent_pos[1] , self.goal_position[0] - self.agent_pos[0])
  334. obs['goal_direction'] = np.arctan( slope ) if self.type == 'angle' else slope
  335. return obs
  336. class SymbolicObsWrapper(gym.core.ObservationWrapper):
  337. """
  338. Fully observable grid with a symbolic state representation.
  339. The symbol is a triple of (X, Y, IDX), where X and Y are
  340. the coordinates on the grid, and IDX is the id of the object.
  341. """
  342. def __init__(self, env):
  343. super().__init__(env)
  344. new_image_space = spaces.Box(
  345. low=0,
  346. high=max(OBJECT_TO_IDX.values()),
  347. shape=(self.env.width, self.env.height, 3), # number of cells
  348. dtype="uint8",
  349. )
  350. self.observation_space = spaces.Dict({**self.observation_space, 'image':new_image_space})
  351. def observation(self, obs):
  352. objects = np.array(
  353. [OBJECT_TO_IDX[o.type] if o is not None else -1 for o in self.grid.grid]
  354. )
  355. w, h = self.width, self.height
  356. grid = np.mgrid[:w, :h]
  357. grid = np.concatenate([grid, objects.reshape(1, w, h)])
  358. grid = np.transpose(grid, (1, 2, 0))
  359. obs['image'] = grid
  360. return obs