wrappers.py 28 KB

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