wrappers.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. from __future__ import annotations
  2. import math
  3. import operator
  4. from functools import reduce
  5. from typing import Any
  6. import gymnasium as gym
  7. import numpy as np
  8. from gymnasium import logger, spaces
  9. from gymnasium.core import ObservationWrapper, ObsType, Wrapper
  10. from minigrid.core.constants import COLOR_TO_IDX, OBJECT_TO_IDX, STATE_TO_IDX
  11. from minigrid.core.world_object import Goal
  12. class ReseedWrapper(Wrapper):
  13. """
  14. Wrapper to always regenerate an environment with the same set of seeds.
  15. This can be used to force an environment to always keep the same
  16. configuration when reset.
  17. Example:
  18. >>> import minigrid
  19. >>> import gymnasium as gym
  20. >>> from minigrid.wrappers import ReseedWrapper
  21. >>> env = gym.make("MiniGrid-Empty-5x5-v0")
  22. >>> _ = env.reset(seed=123)
  23. >>> [env.np_random.integers(10) for i in range(10)]
  24. [0, 6, 5, 0, 9, 2, 2, 1, 3, 1]
  25. >>> env = ReseedWrapper(env, seeds=[0, 1], seed_idx=0)
  26. >>> _, _ = env.reset()
  27. >>> [env.np_random.integers(10) for i in range(10)]
  28. [8, 6, 5, 2, 3, 0, 0, 0, 1, 8]
  29. >>> _, _ = env.reset()
  30. >>> [env.np_random.integers(10) for i in range(10)]
  31. [4, 5, 7, 9, 0, 1, 8, 9, 2, 3]
  32. >>> _, _ = env.reset()
  33. >>> [env.np_random.integers(10) for i in range(10)]
  34. [8, 6, 5, 2, 3, 0, 0, 0, 1, 8]
  35. >>> _, _ = env.reset()
  36. >>> [env.np_random.integers(10) for i in range(10)]
  37. [4, 5, 7, 9, 0, 1, 8, 9, 2, 3]
  38. """
  39. def __init__(self, env, seeds=(0,), seed_idx=0):
  40. """A wrapper that always regenerate an environment with the same set of seeds.
  41. Args:
  42. env: The environment to apply the wrapper
  43. seeds: A list of seed to be applied to the env
  44. seed_idx: Index of the initial seed in seeds
  45. """
  46. self.seeds = list(seeds)
  47. self.seed_idx = seed_idx
  48. super().__init__(env)
  49. def reset(
  50. self, *, seed: int | None = None, options: dict[str, Any] | None = None
  51. ) -> tuple[ObsType, dict[str, Any]]:
  52. if seed is not None:
  53. logger.warn(
  54. "A seed has been passed to `ReseedWrapper.reset` which is ignored."
  55. )
  56. seed = self.seeds[self.seed_idx]
  57. self.seed_idx = (self.seed_idx + 1) % len(self.seeds)
  58. return self.env.reset(seed=seed, options=options)
  59. class ActionBonus(gym.Wrapper):
  60. """
  61. Wrapper which adds an exploration bonus.
  62. This is a reward to encourage exploration of less
  63. visited (state,action) pairs.
  64. Example:
  65. >>> import gymnasium as gym
  66. >>> from minigrid.wrappers import ActionBonus
  67. >>> env = gym.make("MiniGrid-Empty-5x5-v0")
  68. >>> _, _ = env.reset(seed=0)
  69. >>> _, reward, _, _, _ = env.step(1)
  70. >>> print(reward)
  71. 0
  72. >>> _, reward, _, _, _ = env.step(1)
  73. >>> print(reward)
  74. 0
  75. >>> env_bonus = ActionBonus(env)
  76. >>> _, _ = env_bonus.reset(seed=0)
  77. >>> _, reward, _, _, _ = env_bonus.step(1)
  78. >>> print(reward)
  79. 1.0
  80. >>> _, reward, _, _, _ = env_bonus.step(1)
  81. >>> print(reward)
  82. 1.0
  83. """
  84. def __init__(self, env):
  85. """A wrapper that adds an exploration bonus to less visited (state,action) pairs.
  86. Args:
  87. env: The environment to apply the wrapper
  88. """
  89. super().__init__(env)
  90. self.counts = {}
  91. def step(self, action):
  92. """Steps through the environment with `action`."""
  93. obs, reward, terminated, truncated, info = self.env.step(action)
  94. env = self.unwrapped
  95. tup = (tuple(env.agent_pos), env.agent_dir, action)
  96. # Get the count for this (s,a) pair
  97. pre_count = 0
  98. if tup in self.counts:
  99. pre_count = self.counts[tup]
  100. # Update the count for this (s,a) pair
  101. new_count = pre_count + 1
  102. self.counts[tup] = new_count
  103. bonus = 1 / math.sqrt(new_count)
  104. reward += bonus
  105. return obs, reward, terminated, truncated, info
  106. class PositionBonus(Wrapper):
  107. """
  108. Adds an exploration bonus based on which positions
  109. are visited on the grid.
  110. Note:
  111. This wrapper was previously called ``StateBonus``.
  112. Example:
  113. >>> import gymnasium as gym
  114. >>> from minigrid.wrappers import PositionBonus
  115. >>> env = gym.make("MiniGrid-Empty-5x5-v0")
  116. >>> _, _ = env.reset(seed=0)
  117. >>> _, reward, _, _, _ = env.step(1)
  118. >>> print(reward)
  119. 0
  120. >>> _, reward, _, _, _ = env.step(1)
  121. >>> print(reward)
  122. 0
  123. >>> env_bonus = PositionBonus(env)
  124. >>> obs, _ = env_bonus.reset(seed=0)
  125. >>> obs, reward, terminated, truncated, info = env_bonus.step(1)
  126. >>> print(reward)
  127. 1.0
  128. >>> obs, reward, terminated, truncated, info = env_bonus.step(1)
  129. >>> print(reward)
  130. 0.7071067811865475
  131. """
  132. def __init__(self, env):
  133. """A wrapper that adds an exploration bonus to less visited positions.
  134. Args:
  135. env: The environment to apply the wrapper
  136. """
  137. super().__init__(env)
  138. self.counts = {}
  139. def step(self, action):
  140. """Steps through the environment with `action`."""
  141. obs, reward, terminated, truncated, info = self.env.step(action)
  142. # Tuple based on which we index the counts
  143. # We use the position after an update
  144. env = self.unwrapped
  145. tup = tuple(env.agent_pos)
  146. # Get the count for this key
  147. pre_count = 0
  148. if tup in self.counts:
  149. pre_count = self.counts[tup]
  150. # Update the count for this key
  151. new_count = pre_count + 1
  152. self.counts[tup] = new_count
  153. bonus = 1 / math.sqrt(new_count)
  154. reward += bonus
  155. return obs, reward, terminated, truncated, info
  156. class ImgObsWrapper(ObservationWrapper):
  157. """
  158. Use the image as the only observation output, no language/mission.
  159. Example:
  160. >>> import gymnasium as gym
  161. >>> from minigrid.wrappers import ImgObsWrapper
  162. >>> env = gym.make("MiniGrid-Empty-5x5-v0")
  163. >>> obs, _ = env.reset()
  164. >>> obs.keys()
  165. dict_keys(['image', 'direction', 'mission'])
  166. >>> env = ImgObsWrapper(env)
  167. >>> obs, _ = env.reset()
  168. >>> obs.shape
  169. (7, 7, 3)
  170. """
  171. def __init__(self, env):
  172. """A wrapper that makes image the only observation.
  173. Args:
  174. env: The environment to apply the wrapper
  175. """
  176. super().__init__(env)
  177. self.observation_space = env.observation_space.spaces["image"]
  178. def observation(self, obs):
  179. return obs["image"]
  180. class OneHotPartialObsWrapper(ObservationWrapper):
  181. """
  182. Wrapper to get a one-hot encoding of a partially observable
  183. agent view as observation.
  184. Example:
  185. >>> import gymnasium as gym
  186. >>> from minigrid.wrappers import OneHotPartialObsWrapper
  187. >>> env = gym.make("MiniGrid-Empty-5x5-v0")
  188. >>> obs, _ = env.reset()
  189. >>> obs["image"][0, :, :]
  190. array([[2, 5, 0],
  191. [2, 5, 0],
  192. [2, 5, 0],
  193. [2, 5, 0],
  194. [2, 5, 0],
  195. [2, 5, 0],
  196. [2, 5, 0]], dtype=uint8)
  197. >>> env = OneHotPartialObsWrapper(env)
  198. >>> obs, _ = env.reset()
  199. >>> obs["image"][0, :, :]
  200. array([[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
  201. [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
  202. [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
  203. [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
  204. [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
  205. [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
  206. [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0]],
  207. dtype=uint8)
  208. """
  209. def __init__(self, env, tile_size=8):
  210. """A wrapper that makes the image observation a one-hot encoding of a partially observable agent view.
  211. Args:
  212. env: The environment to apply the wrapper
  213. """
  214. super().__init__(env)
  215. self.tile_size = tile_size
  216. obs_shape = env.observation_space["image"].shape
  217. # Number of bits per cell
  218. num_bits = len(OBJECT_TO_IDX) + len(COLOR_TO_IDX) + len(STATE_TO_IDX)
  219. new_image_space = spaces.Box(
  220. low=0, high=255, shape=(obs_shape[0], obs_shape[1], num_bits), dtype="uint8"
  221. )
  222. self.observation_space = spaces.Dict(
  223. {**self.observation_space.spaces, "image": new_image_space}
  224. )
  225. def observation(self, obs):
  226. img = obs["image"]
  227. out = np.zeros(self.observation_space.spaces["image"].shape, dtype="uint8")
  228. for i in range(img.shape[0]):
  229. for j in range(img.shape[1]):
  230. type = img[i, j, 0]
  231. color = img[i, j, 1]
  232. state = img[i, j, 2]
  233. out[i, j, type] = 1
  234. out[i, j, len(OBJECT_TO_IDX) + color] = 1
  235. out[i, j, len(OBJECT_TO_IDX) + len(COLOR_TO_IDX) + state] = 1
  236. return {**obs, "image": out}
  237. class RGBImgObsWrapper(ObservationWrapper):
  238. """
  239. Wrapper to use fully observable RGB image as observation,
  240. This can be used to have the agent to solve the gridworld in pixel space.
  241. Example:
  242. >>> import gymnasium as gym
  243. >>> import matplotlib.pyplot as plt
  244. >>> from minigrid.wrappers import RGBImgObsWrapper
  245. >>> env = gym.make("MiniGrid-Empty-5x5-v0")
  246. >>> obs, _ = env.reset()
  247. >>> plt.imshow(obs['image']) # doctest: +SKIP
  248. ![NoWrapper](../figures/lavacrossing_NoWrapper.png)
  249. >>> env = RGBImgObsWrapper(env)
  250. >>> obs, _ = env.reset()
  251. >>> plt.imshow(obs['image']) # doctest: +SKIP
  252. ![RGBImgObsWrapper](../figures/lavacrossing_RGBImgObsWrapper.png)
  253. """
  254. def __init__(self, env, tile_size=8):
  255. super().__init__(env)
  256. self.tile_size = tile_size
  257. new_image_space = spaces.Box(
  258. low=0,
  259. high=255,
  260. shape=(self.env.width * tile_size, self.env.height * tile_size, 3),
  261. dtype="uint8",
  262. )
  263. self.observation_space = spaces.Dict(
  264. {**self.observation_space.spaces, "image": new_image_space}
  265. )
  266. def observation(self, obs):
  267. rgb_img = self.get_frame(highlight=True, tile_size=self.tile_size)
  268. return {**obs, "image": rgb_img}
  269. class RGBImgPartialObsWrapper(ObservationWrapper):
  270. """
  271. Wrapper to use partially observable RGB image as observation.
  272. This can be used to have the agent to solve the gridworld in pixel space.
  273. Example:
  274. >>> import gymnasium as gym
  275. >>> import matplotlib.pyplot as plt
  276. >>> from minigrid.wrappers import RGBImgObsWrapper, RGBImgPartialObsWrapper
  277. >>> env = gym.make("MiniGrid-LavaCrossingS11N5-v0")
  278. >>> obs, _ = env.reset()
  279. >>> plt.imshow(obs["image"]) # doctest: +SKIP
  280. ![NoWrapper](../figures/lavacrossing_NoWrapper.png)
  281. >>> env_obs = RGBImgObsWrapper(env)
  282. >>> obs, _ = env_obs.reset()
  283. >>> plt.imshow(obs["image"]) # doctest: +SKIP
  284. ![RGBImgObsWrapper](../figures/lavacrossing_RGBImgObsWrapper.png)
  285. >>> env_obs = RGBImgPartialObsWrapper(env)
  286. >>> obs, _ = env_obs.reset()
  287. >>> plt.imshow(obs["image"]) # doctest: +SKIP
  288. ![RGBImgPartialObsWrapper](../figures/lavacrossing_RGBImgPartialObsWrapper.png)
  289. """
  290. def __init__(self, env, tile_size=8):
  291. super().__init__(env)
  292. # Rendering attributes for observations
  293. self.tile_size = tile_size
  294. obs_shape = env.observation_space.spaces["image"].shape
  295. new_image_space = spaces.Box(
  296. low=0,
  297. high=255,
  298. shape=(obs_shape[0] * tile_size, obs_shape[1] * tile_size, 3),
  299. dtype="uint8",
  300. )
  301. self.observation_space = spaces.Dict(
  302. {**self.observation_space.spaces, "image": new_image_space}
  303. )
  304. def observation(self, obs):
  305. rgb_img_partial = self.get_frame(tile_size=self.tile_size, agent_pov=True)
  306. return {**obs, "image": rgb_img_partial}
  307. class FullyObsWrapper(ObservationWrapper):
  308. """
  309. Fully observable gridworld using a compact grid encoding instead of the agent view.
  310. Example:
  311. >>> import gymnasium as gym
  312. >>> import matplotlib.pyplot as plt
  313. >>> from minigrid.wrappers import FullyObsWrapper
  314. >>> env = gym.make("MiniGrid-LavaCrossingS11N5-v0")
  315. >>> obs, _ = env.reset()
  316. >>> obs['image'].shape
  317. (7, 7, 3)
  318. >>> env_obs = FullyObsWrapper(env)
  319. >>> obs, _ = env_obs.reset()
  320. >>> obs['image'].shape
  321. (11, 11, 3)
  322. """
  323. def __init__(self, env):
  324. super().__init__(env)
  325. new_image_space = spaces.Box(
  326. low=0,
  327. high=255,
  328. shape=(self.env.width, self.env.height, 3), # number of cells
  329. dtype="uint8",
  330. )
  331. self.observation_space = spaces.Dict(
  332. {**self.observation_space.spaces, "image": new_image_space}
  333. )
  334. def observation(self, obs):
  335. env = self.unwrapped
  336. full_grid = env.grid.encode()
  337. full_grid[env.agent_pos[0]][env.agent_pos[1]] = np.array(
  338. [OBJECT_TO_IDX["agent"], COLOR_TO_IDX["red"], env.agent_dir]
  339. )
  340. return {**obs, "image": full_grid}
  341. class DictObservationSpaceWrapper(ObservationWrapper):
  342. """
  343. Transforms the observation space (that has a textual component) to a fully numerical observation space,
  344. where the textual instructions are replaced by arrays representing the indices of each word in a fixed vocabulary.
  345. This wrapper is not applicable to BabyAI environments, given that these have their own language component.
  346. Example:
  347. >>> import gymnasium as gym
  348. >>> import matplotlib.pyplot as plt
  349. >>> from minigrid.wrappers import DictObservationSpaceWrapper
  350. >>> env = gym.make("MiniGrid-LavaCrossingS11N5-v0")
  351. >>> obs, _ = env.reset()
  352. >>> obs['mission']
  353. 'avoid the lava and get to the green goal square'
  354. >>> env_obs = DictObservationSpaceWrapper(env)
  355. >>> obs, _ = env_obs.reset()
  356. >>> obs['mission'][:10]
  357. [19, 31, 17, 36, 20, 38, 31, 2, 15, 35]
  358. """
  359. def __init__(self, env, max_words_in_mission=50, word_dict=None):
  360. """
  361. max_words_in_mission is the length of the array to represent a mission, value 0 for missing words
  362. word_dict is a dictionary of words to use (keys=words, values=indices from 1 to < max_words_in_mission),
  363. if None, use the Minigrid language
  364. """
  365. super().__init__(env)
  366. if word_dict is None:
  367. word_dict = self.get_minigrid_words()
  368. self.max_words_in_mission = max_words_in_mission
  369. self.word_dict = word_dict
  370. image_observation_space = spaces.Box(
  371. low=0,
  372. high=255,
  373. shape=(self.agent_view_size, self.agent_view_size, 3),
  374. dtype="uint8",
  375. )
  376. self.observation_space = spaces.Dict(
  377. {
  378. "image": image_observation_space,
  379. "direction": spaces.Discrete(4),
  380. "mission": spaces.MultiDiscrete(
  381. [len(self.word_dict.keys())] * max_words_in_mission
  382. ),
  383. }
  384. )
  385. @staticmethod
  386. def get_minigrid_words():
  387. colors = ["red", "green", "blue", "yellow", "purple", "grey"]
  388. objects = [
  389. "unseen",
  390. "empty",
  391. "wall",
  392. "floor",
  393. "box",
  394. "key",
  395. "ball",
  396. "door",
  397. "goal",
  398. "agent",
  399. "lava",
  400. ]
  401. verbs = [
  402. "pick",
  403. "avoid",
  404. "get",
  405. "find",
  406. "put",
  407. "use",
  408. "open",
  409. "go",
  410. "fetch",
  411. "reach",
  412. "unlock",
  413. "traverse",
  414. ]
  415. extra_words = [
  416. "up",
  417. "the",
  418. "a",
  419. "at",
  420. ",",
  421. "square",
  422. "and",
  423. "then",
  424. "to",
  425. "of",
  426. "rooms",
  427. "near",
  428. "opening",
  429. "must",
  430. "you",
  431. "matching",
  432. "end",
  433. "hallway",
  434. "object",
  435. "from",
  436. "room",
  437. ]
  438. all_words = colors + objects + verbs + extra_words
  439. assert len(all_words) == len(set(all_words))
  440. return {word: i for i, word in enumerate(all_words)}
  441. def string_to_indices(self, string, offset=1):
  442. """
  443. Convert a string to a list of indices.
  444. """
  445. indices = []
  446. # adding space before and after commas
  447. string = string.replace(",", " , ")
  448. for word in string.split():
  449. if word in self.word_dict.keys():
  450. indices.append(self.word_dict[word] + offset)
  451. else:
  452. raise ValueError(f"Unknown word: {word}")
  453. return indices
  454. def observation(self, obs):
  455. obs["mission"] = self.string_to_indices(obs["mission"])
  456. assert len(obs["mission"]) < self.max_words_in_mission
  457. obs["mission"] += [0] * (self.max_words_in_mission - len(obs["mission"]))
  458. return obs
  459. class FlatObsWrapper(ObservationWrapper):
  460. """
  461. Encode mission strings using a one-hot scheme,
  462. and combine these with observed images into one flat array.
  463. This wrapper is not applicable to BabyAI environments, given that these have their own language component.
  464. Example:
  465. >>> import gymnasium as gym
  466. >>> import matplotlib.pyplot as plt
  467. >>> from minigrid.wrappers import FlatObsWrapper
  468. >>> env = gym.make("MiniGrid-LavaCrossingS11N5-v0")
  469. >>> env_obs = FlatObsWrapper(env)
  470. >>> obs, _ = env_obs.reset()
  471. >>> obs.shape
  472. (2835,)
  473. """
  474. def __init__(self, env, maxStrLen=96):
  475. super().__init__(env)
  476. self.maxStrLen = maxStrLen
  477. self.numCharCodes = 28
  478. imgSpace = env.observation_space.spaces["image"]
  479. imgSize = reduce(operator.mul, imgSpace.shape, 1)
  480. self.observation_space = spaces.Box(
  481. low=0,
  482. high=255,
  483. shape=(imgSize + self.numCharCodes * self.maxStrLen,),
  484. dtype="uint8",
  485. )
  486. self.cachedStr: str = None
  487. def observation(self, obs):
  488. image = obs["image"]
  489. mission = obs["mission"]
  490. # Cache the last-encoded mission string
  491. if mission != self.cachedStr:
  492. assert (
  493. len(mission) <= self.maxStrLen
  494. ), f"mission string too long ({len(mission)} chars)"
  495. mission = mission.lower()
  496. strArray = np.zeros(
  497. shape=(self.maxStrLen, self.numCharCodes), dtype="float32"
  498. )
  499. for idx, ch in enumerate(mission):
  500. if ch >= "a" and ch <= "z":
  501. chNo = ord(ch) - ord("a")
  502. elif ch == " ":
  503. chNo = ord("z") - ord("a") + 1
  504. elif ch == ",":
  505. chNo = ord("z") - ord("a") + 2
  506. else:
  507. raise ValueError(
  508. f"Character {ch} is not available in mission string."
  509. )
  510. assert chNo < self.numCharCodes, "%s : %d" % (ch, chNo)
  511. strArray[idx, chNo] = 1
  512. self.cachedStr = mission
  513. self.cachedArray = strArray
  514. obs = np.concatenate((image.flatten(), self.cachedArray.flatten()))
  515. return obs
  516. class ViewSizeWrapper(ObservationWrapper):
  517. """
  518. Wrapper to customize the agent field of view size.
  519. This cannot be used with fully observable wrappers.
  520. Example:
  521. >>> import gymnasium as gym
  522. >>> from minigrid.wrappers import ViewSizeWrapper
  523. >>> env = gym.make("MiniGrid-LavaCrossingS11N5-v0")
  524. >>> obs, _ = env.reset()
  525. >>> obs['image'].shape
  526. (7, 7, 3)
  527. >>> env_obs = ViewSizeWrapper(env, agent_view_size=5)
  528. >>> obs, _ = env_obs.reset()
  529. >>> obs['image'].shape
  530. (5, 5, 3)
  531. """
  532. def __init__(self, env, agent_view_size=7):
  533. super().__init__(env)
  534. assert agent_view_size % 2 == 1
  535. assert agent_view_size >= 3
  536. self.agent_view_size = agent_view_size
  537. # Compute observation space with specified view size
  538. new_image_space = gym.spaces.Box(
  539. low=0, high=255, shape=(agent_view_size, agent_view_size, 3), dtype="uint8"
  540. )
  541. # Override the environment's observation spaceexit
  542. self.observation_space = spaces.Dict(
  543. {**self.observation_space.spaces, "image": new_image_space}
  544. )
  545. def observation(self, obs):
  546. env = self.unwrapped
  547. grid, vis_mask = env.gen_obs_grid(self.agent_view_size)
  548. # Encode the partially observable view into a numpy array
  549. image = grid.encode(vis_mask)
  550. return {**obs, "image": image}
  551. class DirectionObsWrapper(ObservationWrapper):
  552. """
  553. Provides the slope/angular direction to the goal with the observations as modeled by (y2 - y2 )/( x2 - x1)
  554. type = {slope , angle}
  555. Example:
  556. >>> import gymnasium as gym
  557. >>> import matplotlib.pyplot as plt
  558. >>> from minigrid.wrappers import DirectionObsWrapper
  559. >>> env = gym.make("MiniGrid-LavaCrossingS11N5-v0")
  560. >>> env_obs = DirectionObsWrapper(env, type="slope")
  561. >>> obs, _ = env_obs.reset()
  562. >>> obs['goal_direction']
  563. 1.0
  564. """
  565. def __init__(self, env, type="slope"):
  566. super().__init__(env)
  567. self.goal_position: tuple = None
  568. self.type = type
  569. def reset(
  570. self, *, seed: int | None = None, options: dict[str, Any] | None = None
  571. ) -> tuple[ObsType, dict[str, Any]]:
  572. obs, info = self.env.reset()
  573. if not self.goal_position:
  574. self.goal_position = [
  575. x for x, y in enumerate(self.grid.grid) if isinstance(y, Goal)
  576. ]
  577. # in case there are multiple goals , needs to be handled for other env types
  578. if len(self.goal_position) >= 1:
  579. self.goal_position = (
  580. int(self.goal_position[0] / self.height),
  581. self.goal_position[0] % self.width,
  582. )
  583. return self.observation(obs), info
  584. def observation(self, obs):
  585. slope = np.divide(
  586. self.goal_position[1] - self.agent_pos[1],
  587. self.goal_position[0] - self.agent_pos[0],
  588. )
  589. if self.type == "angle":
  590. obs["goal_direction"] = np.arctan(slope)
  591. else:
  592. obs["goal_direction"] = slope
  593. return obs
  594. class SymbolicObsWrapper(ObservationWrapper):
  595. """
  596. Fully observable grid with a symbolic state representation.
  597. The symbol is a triple of (X, Y, IDX), where X and Y are
  598. the coordinates on the grid, and IDX is the id of the object.
  599. Example:
  600. >>> import gymnasium as gym
  601. >>> from minigrid.wrappers import SymbolicObsWrapper
  602. >>> env = gym.make("MiniGrid-LavaCrossingS11N5-v0")
  603. >>> obs, _ = env.reset()
  604. >>> obs['image'].shape
  605. (7, 7, 3)
  606. >>> env_obs = SymbolicObsWrapper(env)
  607. >>> obs, _ = env_obs.reset()
  608. >>> obs['image'].shape
  609. (11, 11, 3)
  610. """
  611. def __init__(self, env):
  612. super().__init__(env)
  613. new_image_space = spaces.Box(
  614. low=0,
  615. high=max(OBJECT_TO_IDX.values()),
  616. shape=(self.env.width, self.env.height, 3), # number of cells
  617. dtype="uint8",
  618. )
  619. self.observation_space = spaces.Dict(
  620. {**self.observation_space.spaces, "image": new_image_space}
  621. )
  622. def observation(self, obs):
  623. objects = np.array(
  624. [OBJECT_TO_IDX[o.type] if o is not None else -1 for o in self.grid.grid]
  625. )
  626. agent_pos = self.env.agent_pos
  627. ncol, nrow = self.width, self.height
  628. grid = np.mgrid[:ncol, :nrow]
  629. _objects = np.transpose(objects.reshape(1, nrow, ncol), (0, 2, 1))
  630. grid = np.concatenate([grid, _objects])
  631. grid = np.transpose(grid, (1, 2, 0))
  632. grid[agent_pos[0], agent_pos[1], 2] = OBJECT_TO_IDX["agent"]
  633. obs["image"] = grid
  634. return obs