wrappers.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  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 ActionWrapper, 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. self.observation_space = spaces.Dict(
  371. {
  372. "image": env.observation_space["image"],
  373. "direction": spaces.Discrete(4),
  374. "mission": spaces.MultiDiscrete(
  375. [len(self.word_dict.keys())] * max_words_in_mission
  376. ),
  377. }
  378. )
  379. @staticmethod
  380. def get_minigrid_words():
  381. colors = ["red", "green", "blue", "yellow", "purple", "grey"]
  382. objects = [
  383. "unseen",
  384. "empty",
  385. "wall",
  386. "floor",
  387. "box",
  388. "key",
  389. "ball",
  390. "door",
  391. "goal",
  392. "agent",
  393. "lava",
  394. ]
  395. verbs = [
  396. "pick",
  397. "avoid",
  398. "get",
  399. "find",
  400. "put",
  401. "use",
  402. "open",
  403. "go",
  404. "fetch",
  405. "reach",
  406. "unlock",
  407. "traverse",
  408. ]
  409. extra_words = [
  410. "up",
  411. "the",
  412. "a",
  413. "at",
  414. ",",
  415. "square",
  416. "and",
  417. "then",
  418. "to",
  419. "of",
  420. "rooms",
  421. "near",
  422. "opening",
  423. "must",
  424. "you",
  425. "matching",
  426. "end",
  427. "hallway",
  428. "object",
  429. "from",
  430. "room",
  431. ]
  432. all_words = colors + objects + verbs + extra_words
  433. assert len(all_words) == len(set(all_words))
  434. return {word: i for i, word in enumerate(all_words)}
  435. def string_to_indices(self, string, offset=1):
  436. """
  437. Convert a string to a list of indices.
  438. """
  439. indices = []
  440. # adding space before and after commas
  441. string = string.replace(",", " , ")
  442. for word in string.split():
  443. if word in self.word_dict.keys():
  444. indices.append(self.word_dict[word] + offset)
  445. else:
  446. raise ValueError(f"Unknown word: {word}")
  447. return indices
  448. def observation(self, obs):
  449. obs["mission"] = self.string_to_indices(obs["mission"])
  450. assert len(obs["mission"]) < self.max_words_in_mission
  451. obs["mission"] += [0] * (self.max_words_in_mission - len(obs["mission"]))
  452. return obs
  453. class FlatObsWrapper(ObservationWrapper):
  454. """
  455. Encode mission strings using a one-hot scheme,
  456. and combine these with observed images into one flat array.
  457. This wrapper is not applicable to BabyAI environments, given that these have their own language component.
  458. Example:
  459. >>> import gymnasium as gym
  460. >>> import matplotlib.pyplot as plt
  461. >>> from minigrid.wrappers import FlatObsWrapper
  462. >>> env = gym.make("MiniGrid-LavaCrossingS11N5-v0")
  463. >>> env_obs = FlatObsWrapper(env)
  464. >>> obs, _ = env_obs.reset()
  465. >>> obs.shape
  466. (2835,)
  467. """
  468. def __init__(self, env, maxStrLen=96):
  469. super().__init__(env)
  470. self.maxStrLen = maxStrLen
  471. self.numCharCodes = 28
  472. imgSpace = env.observation_space.spaces["image"]
  473. imgSize = reduce(operator.mul, imgSpace.shape, 1)
  474. self.observation_space = spaces.Box(
  475. low=0,
  476. high=255,
  477. shape=(imgSize + self.numCharCodes * self.maxStrLen,),
  478. dtype="uint8",
  479. )
  480. self.cachedStr: str = None
  481. def observation(self, obs):
  482. image = obs["image"]
  483. mission = obs["mission"]
  484. # Cache the last-encoded mission string
  485. if mission != self.cachedStr:
  486. assert (
  487. len(mission) <= self.maxStrLen
  488. ), f"mission string too long ({len(mission)} chars)"
  489. mission = mission.lower()
  490. strArray = np.zeros(
  491. shape=(self.maxStrLen, self.numCharCodes), dtype="float32"
  492. )
  493. for idx, ch in enumerate(mission):
  494. if ch >= "a" and ch <= "z":
  495. chNo = ord(ch) - ord("a")
  496. elif ch == " ":
  497. chNo = ord("z") - ord("a") + 1
  498. elif ch == ",":
  499. chNo = ord("z") - ord("a") + 2
  500. else:
  501. raise ValueError(
  502. f"Character {ch} is not available in mission string."
  503. )
  504. assert chNo < self.numCharCodes, "%s : %d" % (ch, chNo)
  505. strArray[idx, chNo] = 1
  506. self.cachedStr = mission
  507. self.cachedArray = strArray
  508. obs = np.concatenate((image.flatten(), self.cachedArray.flatten()))
  509. return obs
  510. class ViewSizeWrapper(ObservationWrapper):
  511. """
  512. Wrapper to customize the agent field of view size.
  513. This cannot be used with fully observable wrappers.
  514. Example:
  515. >>> import gymnasium as gym
  516. >>> from minigrid.wrappers import ViewSizeWrapper
  517. >>> env = gym.make("MiniGrid-LavaCrossingS11N5-v0")
  518. >>> obs, _ = env.reset()
  519. >>> obs['image'].shape
  520. (7, 7, 3)
  521. >>> env_obs = ViewSizeWrapper(env, agent_view_size=5)
  522. >>> obs, _ = env_obs.reset()
  523. >>> obs['image'].shape
  524. (5, 5, 3)
  525. """
  526. def __init__(self, env, agent_view_size=7):
  527. super().__init__(env)
  528. assert agent_view_size % 2 == 1
  529. assert agent_view_size >= 3
  530. self.agent_view_size = agent_view_size
  531. # Compute observation space with specified view size
  532. new_image_space = gym.spaces.Box(
  533. low=0, high=255, shape=(agent_view_size, agent_view_size, 3), dtype="uint8"
  534. )
  535. # Override the environment's observation spaceexit
  536. self.observation_space = spaces.Dict(
  537. {**self.observation_space.spaces, "image": new_image_space}
  538. )
  539. def observation(self, obs):
  540. env = self.unwrapped
  541. grid, vis_mask = env.gen_obs_grid(self.agent_view_size)
  542. # Encode the partially observable view into a numpy array
  543. image = grid.encode(vis_mask)
  544. return {**obs, "image": image}
  545. class DirectionObsWrapper(ObservationWrapper):
  546. """
  547. Provides the slope/angular direction to the goal with the observations as modeled by (y2 - y2 )/( x2 - x1)
  548. type = {slope , angle}
  549. Example:
  550. >>> import gymnasium as gym
  551. >>> import matplotlib.pyplot as plt
  552. >>> from minigrid.wrappers import DirectionObsWrapper
  553. >>> env = gym.make("MiniGrid-LavaCrossingS11N5-v0")
  554. >>> env_obs = DirectionObsWrapper(env, type="slope")
  555. >>> obs, _ = env_obs.reset()
  556. >>> obs['goal_direction']
  557. 1.0
  558. """
  559. def __init__(self, env, type="slope"):
  560. super().__init__(env)
  561. self.goal_position: tuple = None
  562. self.type = type
  563. def reset(
  564. self, *, seed: int | None = None, options: dict[str, Any] | None = None
  565. ) -> tuple[ObsType, dict[str, Any]]:
  566. obs, info = self.env.reset()
  567. if not self.goal_position:
  568. self.goal_position = [
  569. x for x, y in enumerate(self.grid.grid) if isinstance(y, Goal)
  570. ]
  571. # in case there are multiple goals , needs to be handled for other env types
  572. if len(self.goal_position) >= 1:
  573. self.goal_position = (
  574. int(self.goal_position[0] / self.height),
  575. self.goal_position[0] % self.width,
  576. )
  577. return self.observation(obs), info
  578. def observation(self, obs):
  579. slope = np.divide(
  580. self.goal_position[1] - self.agent_pos[1],
  581. self.goal_position[0] - self.agent_pos[0],
  582. )
  583. if self.type == "angle":
  584. obs["goal_direction"] = np.arctan(slope)
  585. else:
  586. obs["goal_direction"] = slope
  587. return obs
  588. class SymbolicObsWrapper(ObservationWrapper):
  589. """
  590. Fully observable grid with a symbolic state representation.
  591. The symbol is a triple of (X, Y, IDX), where X and Y are
  592. the coordinates on the grid, and IDX is the id of the object.
  593. Example:
  594. >>> import gymnasium as gym
  595. >>> from minigrid.wrappers import SymbolicObsWrapper
  596. >>> env = gym.make("MiniGrid-LavaCrossingS11N5-v0")
  597. >>> obs, _ = env.reset()
  598. >>> obs['image'].shape
  599. (7, 7, 3)
  600. >>> env_obs = SymbolicObsWrapper(env)
  601. >>> obs, _ = env_obs.reset()
  602. >>> obs['image'].shape
  603. (11, 11, 3)
  604. """
  605. def __init__(self, env):
  606. super().__init__(env)
  607. new_image_space = spaces.Box(
  608. low=0,
  609. high=max(OBJECT_TO_IDX.values()),
  610. shape=(self.env.width, self.env.height, 3), # number of cells
  611. dtype="uint8",
  612. )
  613. self.observation_space = spaces.Dict(
  614. {**self.observation_space.spaces, "image": new_image_space}
  615. )
  616. def observation(self, obs):
  617. objects = np.array(
  618. [OBJECT_TO_IDX[o.type] if o is not None else -1 for o in self.grid.grid]
  619. )
  620. agent_pos = self.env.agent_pos
  621. ncol, nrow = self.width, self.height
  622. grid = np.mgrid[:ncol, :nrow]
  623. _objects = np.transpose(objects.reshape(1, nrow, ncol), (0, 2, 1))
  624. grid = np.concatenate([grid, _objects])
  625. grid = np.transpose(grid, (1, 2, 0))
  626. grid[agent_pos[0], agent_pos[1], 2] = OBJECT_TO_IDX["agent"]
  627. obs["image"] = grid
  628. return obs
  629. class StochasticActionWrapper(ActionWrapper):
  630. """
  631. Add stochasticity to the actions
  632. If a random action is provided, it is returned with probability `1 - prob`.
  633. Else, a random action is sampled from the action space.
  634. """
  635. def __init__(self, env=None, prob=0.9, random_action=None):
  636. super().__init__(env)
  637. self.prob = prob
  638. self.random_action = random_action
  639. def action(self, action):
  640. """ """
  641. if np.random.uniform() < self.prob:
  642. return action
  643. else:
  644. if self.random_action is None:
  645. return self.np_random.integers(0, high=6)
  646. else:
  647. return self.random_action
  648. class NoDeath(Wrapper):
  649. """
  650. Wrapper to prevent death in specific cells (e.g., lava cells).
  651. Instead of dying, the agent will receive a negative reward.
  652. Example:
  653. >>> import gymnasium as gym
  654. >>> from minigrid.wrappers import NoDeath
  655. >>>
  656. >>> env = gym.make("MiniGrid-LavaCrossingS9N1-v0")
  657. >>> _, _ = env.reset(seed=2)
  658. >>> _, _, _, _, _ = env.step(1)
  659. >>> _, reward, term, *_ = env.step(2)
  660. >>> reward, term
  661. (0, True)
  662. >>>
  663. >>> env = NoDeath(env, no_death_types=("lava",), death_cost=-1.0)
  664. >>> _, _ = env.reset(seed=2)
  665. >>> _, _, _, _, _ = env.step(1)
  666. >>> _, reward, term, *_ = env.step(2)
  667. >>> reward, term
  668. (-1.0, False)
  669. >>>
  670. >>>
  671. >>> env = gym.make("MiniGrid-Dynamic-Obstacles-5x5-v0")
  672. >>> _, _ = env.reset(seed=2)
  673. >>> _, reward, term, *_ = env.step(2)
  674. >>> reward, term
  675. (-1, True)
  676. >>>
  677. >>> env = NoDeath(env, no_death_types=("ball",), death_cost=-1.0)
  678. >>> _, _ = env.reset(seed=2)
  679. >>> _, reward, term, *_ = env.step(2)
  680. >>> reward, term
  681. (-2.0, False)
  682. """
  683. def __init__(self, env, no_death_types: tuple[str, ...], death_cost: float = -1.0):
  684. """A wrapper to prevent death in specific cells.
  685. Args:
  686. env: The environment to apply the wrapper
  687. no_death_types: List of strings to identify death cells
  688. death_cost: The negative reward received in death cells
  689. """
  690. assert "goal" not in no_death_types, "goal cannot be a death cell"
  691. super().__init__(env)
  692. self.death_cost = death_cost
  693. self.no_death_types = no_death_types
  694. def step(self, action):
  695. # In Dynamic-Obstacles, obstacles move after the agent moves,
  696. # so we need to check for collision before self.env.step()
  697. front_cell = self.grid.get(*self.front_pos)
  698. going_to_death = (
  699. action == self.actions.forward
  700. and front_cell is not None
  701. and front_cell.type in self.no_death_types
  702. )
  703. obs, reward, terminated, truncated, info = self.env.step(action)
  704. # We also check if the agent stays in death cells (e.g., lava)
  705. # without moving
  706. current_cell = self.grid.get(*self.agent_pos)
  707. in_death = current_cell is not None and current_cell.type in self.no_death_types
  708. if terminated and (going_to_death or in_death):
  709. terminated = False
  710. reward += self.death_cost
  711. return obs, reward, terminated, truncated, info