wrappers.py 27 KB

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