wrappers.py 15 KB

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