wrappers.py 15 KB

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