wrappers.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. new_image_space = spaces.Box(
  98. low=0,
  99. high=255,
  100. shape=(obs_shape[0], obs_shape[1], num_bits),
  101. dtype='uint8'
  102. )
  103. self.observation_space = spaces.Dict({**self.observation_space, 'image':new_image_space})
  104. def observation(self, obs):
  105. img = obs['image']
  106. out = np.zeros(self.observation_space.spaces['image'].shape, dtype='uint8')
  107. for i in range(img.shape[0]):
  108. for j in range(img.shape[1]):
  109. type = img[i, j, 0]
  110. color = img[i, j, 1]
  111. state = img[i, j, 2]
  112. out[i, j, type] = 1
  113. out[i, j, len(OBJECT_TO_IDX) + color] = 1
  114. out[i, j, len(OBJECT_TO_IDX) + len(COLOR_TO_IDX) + state] = 1
  115. return {
  116. **obs,
  117. 'image': out
  118. }
  119. class RGBImgObsWrapper(gym.core.ObservationWrapper):
  120. """
  121. Wrapper to use fully observable RGB image as observation,
  122. This can be used to have the agent to solve the gridworld in pixel space.
  123. """
  124. def __init__(self, env, tile_size=8):
  125. super().__init__(env)
  126. self.tile_size = tile_size
  127. new_image_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. self.observation_space = spaces.Dict({**self.observation_space, 'image':new_image_space})
  134. def observation(self, obs):
  135. env = self.unwrapped
  136. rgb_img = env.render(
  137. mode='rgb_array',
  138. highlight=False,
  139. tile_size=self.tile_size
  140. )
  141. return {
  142. **obs,
  143. 'image': rgb_img
  144. }
  145. class RGBImgPartialObsWrapper(gym.core.ObservationWrapper):
  146. """
  147. Wrapper to use partially observable RGB image as observation.
  148. This can be used to have the agent to solve the gridworld in pixel space.
  149. """
  150. def __init__(self, env, tile_size=8):
  151. super().__init__(env)
  152. self.tile_size = tile_size
  153. obs_shape = env.observation_space.spaces['image'].shape
  154. new_image_space = spaces.Box(
  155. low=0,
  156. high=255,
  157. shape=(obs_shape[0] * tile_size, obs_shape[1] * tile_size, 3),
  158. dtype='uint8'
  159. )
  160. self.observation_space = spaces.Dict({**self.observation_space, 'image':new_image_space})
  161. def observation(self, obs):
  162. env = self.unwrapped
  163. rgb_img_partial = env.get_obs_render(
  164. obs['image'],
  165. tile_size=self.tile_size
  166. )
  167. return {
  168. **obs,
  169. 'image': rgb_img_partial
  170. }
  171. class FullyObsWrapper(gym.core.ObservationWrapper):
  172. """
  173. Fully observable gridworld using a compact grid encoding
  174. """
  175. def __init__(self, env):
  176. super().__init__(env)
  177. new_image_space = spaces.Box(
  178. low=0,
  179. high=255,
  180. shape=(self.env.width, self.env.height, 3), # number of cells
  181. dtype='uint8'
  182. )
  183. self.observation_space = spaces.Dict({**self.observation_space, 'image':new_image_space})
  184. def observation(self, obs):
  185. env = self.unwrapped
  186. full_grid = env.grid.encode()
  187. full_grid[env.agent_pos[0]][env.agent_pos[1]] = np.array([
  188. OBJECT_TO_IDX['agent'],
  189. COLOR_TO_IDX['red'],
  190. env.agent_dir
  191. ])
  192. return {
  193. **obs,
  194. 'image': full_grid
  195. }
  196. class DictObservationSpaceWrapper(gym.core.ObservationWrapper):
  197. """
  198. Use a Dict Obsevation Space encoding images, missions, and directions
  199. """
  200. def __init__(self, env, max_words_in_mission=50, word_dict=None):
  201. """
  202. max_words_in_mission is the length of the array to represent a mission, value 0 for missing words
  203. word_dict is a dictionary of words to use (keys=words, values=indices from 1 to < max_words_in_mission),
  204. if None, use the Minigrid language
  205. """
  206. super().__init__(env)
  207. if word_dict is None:
  208. word_dict = DictObservationSpaceWrapper.get_minigrid_words()
  209. self.max_words_in_mission = max_words_in_mission
  210. self.word_dict = word_dict
  211. image_observation_space = spaces.Box(
  212. low=0,
  213. high=255,
  214. shape=(self.agent_view_size, self.agent_view_size, 3),
  215. dtype='uint8'
  216. )
  217. self.observation_space = spaces.Dict({
  218. 'image': image_observation_space,
  219. 'direction': spaces.Discrete(4),
  220. 'mission': spaces.MultiDiscrete([len(self.word_dict.keys())]
  221. * max_words_in_mission)
  222. })
  223. @staticmethod
  224. def get_minigrid_words():
  225. colors = ['red', 'green', 'blue', 'yellow', 'purple', 'grey']
  226. objects = ['unseen', 'empty', 'wall', 'floor', 'box', 'key', 'ball',
  227. 'door', 'goal', 'agent', 'lava']
  228. verbs = ['pick', 'avoid', 'get', 'find', 'put',
  229. 'use', 'open', 'go', 'fetch',
  230. 'reach', 'unlock', 'traverse']
  231. extra_words = ['up', 'the', 'a', 'at', ',', 'square',
  232. 'and', 'then', 'to', 'of', 'rooms', 'near',
  233. 'opening', 'must', 'you', 'matching', 'end',
  234. 'hallway', 'object', 'from', 'room']
  235. all_words = colors + objects + verbs + extra_words
  236. assert len(all_words) == len(set(all_words))
  237. return {word: i for i, word in enumerate(all_words)}
  238. def string_to_indices(self, string, offset=1):
  239. """
  240. Convert a string to a list of indices.
  241. """
  242. indices = []
  243. string = string.replace(',', ' , ') # adding space before and after commas
  244. for word in string.split():
  245. if word in self.word_dict.keys():
  246. indices.append(self.word_dict[word] + offset)
  247. else:
  248. raise ValueError('Unknown word: {}'.format(word))
  249. return indices
  250. def observation(self, obs):
  251. obs['mission'] = self.string_to_indices(obs['mission'])
  252. assert len(obs['mission']) < self.max_words_in_mission
  253. obs['mission'] += [0] * (self.max_words_in_mission - len(obs['mission']))
  254. return obs
  255. class FlatObsWrapper(gym.core.ObservationWrapper):
  256. """
  257. Encode mission strings using a one-hot scheme,
  258. and combine these with observed images into one flat array
  259. """
  260. def __init__(self, env, maxStrLen=96):
  261. super().__init__(env)
  262. self.maxStrLen = maxStrLen
  263. self.numCharCodes = 27
  264. imgSpace = env.observation_space.spaces['image']
  265. imgSize = reduce(operator.mul, imgSpace.shape, 1)
  266. self.observation_space = spaces.Box(
  267. low=0,
  268. high=255,
  269. shape=(imgSize + self.numCharCodes * self.maxStrLen,),
  270. dtype='uint8'
  271. )
  272. self.cachedStr = None
  273. self.cachedArray = None
  274. def observation(self, obs):
  275. image = obs['image']
  276. mission = obs['mission']
  277. # Cache the last-encoded mission string
  278. if mission != self.cachedStr:
  279. assert len(mission) <= self.maxStrLen, 'mission string too long ({} chars)'.format(len(mission))
  280. mission = mission.lower()
  281. strArray = np.zeros(shape=(self.maxStrLen, self.numCharCodes), dtype='float32')
  282. for idx, ch in enumerate(mission):
  283. if ch >= 'a' and ch <= 'z':
  284. chNo = ord(ch) - ord('a')
  285. elif ch == ' ':
  286. chNo = ord('z') - ord('a') + 1
  287. assert chNo < self.numCharCodes, '%s : %d' % (ch, chNo)
  288. strArray[idx, chNo] = 1
  289. self.cachedStr = mission
  290. self.cachedArray = strArray
  291. obs = np.concatenate((image.flatten(), self.cachedArray.flatten()))
  292. return obs
  293. class ViewSizeWrapper(gym.core.Wrapper):
  294. """
  295. Wrapper to customize the agent field of view size.
  296. This cannot be used with fully observable wrappers.
  297. """
  298. def __init__(self, env, agent_view_size=7):
  299. super().__init__(env)
  300. assert agent_view_size % 2 == 1
  301. assert agent_view_size >= 3
  302. # Override default view size
  303. env.unwrapped.agent_view_size = agent_view_size
  304. # Compute observation space with specified view size
  305. new_image_space = gym.spaces.Box(
  306. low=0,
  307. high=255,
  308. shape=(agent_view_size, agent_view_size, 3),
  309. dtype='uint8'
  310. )
  311. # Override the environment's observation spaceexit
  312. self.observation_space = spaces.Dict({**self.observation_space, 'image':new_image_space})
  313. def reset(self, **kwargs):
  314. return self.env.reset(**kwargs)
  315. def step(self, action):
  316. return self.env.step(action)
  317. class DirectionObsWrapper(gym.core.ObservationWrapper):
  318. """
  319. Provides the slope/angular direction to the goal with the observations as modeled by (y2 - y2 )/( x2 - x1)
  320. type = {slope , angle}
  321. """
  322. def __init__(self, env,type='slope'):
  323. super().__init__(env)
  324. self.goal_position = None
  325. self.type = type
  326. def reset(self):
  327. obs = self.env.reset()
  328. if not self.goal_position:
  329. self.goal_position = [x for x,y in enumerate(self.grid.grid) if isinstance(y,(Goal) ) ]
  330. if len(self.goal_position) >= 1: # in case there are multiple goals , needs to be handled for other env types
  331. self.goal_position = (int(self.goal_position[0]/self.height) , self.goal_position[0]%self.width)
  332. return obs
  333. def observation(self, obs):
  334. slope = np.divide( self.goal_position[1] - self.agent_pos[1] , self.goal_position[0] - self.agent_pos[0])
  335. obs['goal_direction'] = np.arctan( slope ) if self.type == 'angle' else slope
  336. return obs
  337. class SymbolicObsWrapper(gym.core.ObservationWrapper):
  338. """
  339. Fully observable grid with a symbolic state representation.
  340. The symbol is a triple of (X, Y, IDX), where X and Y are
  341. the coordinates on the grid, and IDX is the id of the object.
  342. """
  343. def __init__(self, env):
  344. super().__init__(env)
  345. new_image_space = spaces.Box(
  346. low=0,
  347. high=max(OBJECT_TO_IDX.values()),
  348. shape=(self.env.width, self.env.height, 3), # number of cells
  349. dtype="uint8",
  350. )
  351. self.observation_space = spaces.Dict({**self.observation_space, 'image':new_image_space})
  352. def observation(self, obs):
  353. objects = np.array(
  354. [OBJECT_TO_IDX[o.type] if o is not None else -1 for o in self.grid.grid]
  355. )
  356. w, h = self.width, self.height
  357. grid = np.mgrid[:w, :h]
  358. grid = np.concatenate([grid, objects.reshape(1, w, h)])
  359. grid = np.transpose(grid, (1, 2, 0))
  360. obs['image'] = grid
  361. return obs