wrappers.py 15 KB

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