wrappers.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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. env = self.unwrapped
  133. rgb_img = env.render(mode="rgb_array", 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. 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. env = self.unwrapped
  155. rgb_img_partial = env.get_obs_render(obs["image"], tile_size=self.tile_size)
  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. """
  184. def __init__(self, env, max_words_in_mission=50, word_dict=None):
  185. """
  186. max_words_in_mission is the length of the array to represent a mission, value 0 for missing words
  187. word_dict is a dictionary of words to use (keys=words, values=indices from 1 to < max_words_in_mission),
  188. if None, use the Minigrid language
  189. """
  190. super().__init__(env)
  191. if word_dict is None:
  192. word_dict = self.get_minigrid_words()
  193. self.max_words_in_mission = max_words_in_mission
  194. self.word_dict = word_dict
  195. image_observation_space = spaces.Box(
  196. low=0,
  197. high=255,
  198. shape=(self.agent_view_size, self.agent_view_size, 3),
  199. dtype="uint8",
  200. )
  201. self.observation_space = spaces.Dict(
  202. {
  203. "image": image_observation_space,
  204. "direction": spaces.Discrete(4),
  205. "mission": spaces.MultiDiscrete(
  206. [len(self.word_dict.keys())] * max_words_in_mission
  207. ),
  208. }
  209. )
  210. @staticmethod
  211. def get_minigrid_words():
  212. colors = ["red", "green", "blue", "yellow", "purple", "grey"]
  213. objects = [
  214. "unseen",
  215. "empty",
  216. "wall",
  217. "floor",
  218. "box",
  219. "key",
  220. "ball",
  221. "door",
  222. "goal",
  223. "agent",
  224. "lava",
  225. ]
  226. verbs = [
  227. "pick",
  228. "avoid",
  229. "get",
  230. "find",
  231. "put",
  232. "use",
  233. "open",
  234. "go",
  235. "fetch",
  236. "reach",
  237. "unlock",
  238. "traverse",
  239. ]
  240. extra_words = [
  241. "up",
  242. "the",
  243. "a",
  244. "at",
  245. ",",
  246. "square",
  247. "and",
  248. "then",
  249. "to",
  250. "of",
  251. "rooms",
  252. "near",
  253. "opening",
  254. "must",
  255. "you",
  256. "matching",
  257. "end",
  258. "hallway",
  259. "object",
  260. "from",
  261. "room",
  262. ]
  263. all_words = colors + objects + verbs + extra_words
  264. assert len(all_words) == len(set(all_words))
  265. return {word: i for i, word in enumerate(all_words)}
  266. def string_to_indices(self, string, offset=1):
  267. """
  268. Convert a string to a list of indices.
  269. """
  270. indices = []
  271. # adding space before and after commas
  272. string = string.replace(",", " , ")
  273. for word in string.split():
  274. if word in self.word_dict.keys():
  275. indices.append(self.word_dict[word] + offset)
  276. else:
  277. raise ValueError(f"Unknown word: {word}")
  278. return indices
  279. def observation(self, obs):
  280. obs["mission"] = self.string_to_indices(obs["mission"])
  281. assert len(obs["mission"]) < self.max_words_in_mission
  282. obs["mission"] += [0] * (self.max_words_in_mission - len(obs["mission"]))
  283. return obs
  284. class FlatObsWrapper(ObservationWrapper):
  285. """
  286. Encode mission strings using a one-hot scheme,
  287. and combine these with observed images into one flat array
  288. """
  289. def __init__(self, env, maxStrLen=96):
  290. super().__init__(env)
  291. self.maxStrLen = maxStrLen
  292. self.numCharCodes = 28
  293. imgSpace = env.observation_space.spaces["image"]
  294. imgSize = reduce(operator.mul, imgSpace.shape, 1)
  295. self.observation_space = spaces.Box(
  296. low=0,
  297. high=255,
  298. shape=(imgSize + self.numCharCodes * self.maxStrLen,),
  299. dtype="uint8",
  300. )
  301. self.cachedStr: str = None
  302. def observation(self, obs):
  303. image = obs["image"]
  304. mission = obs["mission"]
  305. # Cache the last-encoded mission string
  306. if mission != self.cachedStr:
  307. assert (
  308. len(mission) <= self.maxStrLen
  309. ), f"mission string too long ({len(mission)} chars)"
  310. mission = mission.lower()
  311. strArray = np.zeros(
  312. shape=(self.maxStrLen, self.numCharCodes), dtype="float32"
  313. )
  314. for idx, ch in enumerate(mission):
  315. if ch >= "a" and ch <= "z":
  316. chNo = ord(ch) - ord("a")
  317. elif ch == " ":
  318. chNo = ord("z") - ord("a") + 1
  319. elif ch == ",":
  320. chNo = ord("z") - ord("a") + 2
  321. else:
  322. raise ValueError(
  323. f"Character {ch} is not available in mission string."
  324. )
  325. assert chNo < self.numCharCodes, "%s : %d" % (ch, chNo)
  326. strArray[idx, chNo] = 1
  327. self.cachedStr = mission
  328. self.cachedArray = strArray
  329. obs = np.concatenate((image.flatten(), self.cachedArray.flatten()))
  330. return obs
  331. class ViewSizeWrapper(Wrapper):
  332. """
  333. Wrapper to customize the agent field of view size.
  334. This cannot be used with fully observable wrappers.
  335. """
  336. def __init__(self, env, agent_view_size=7):
  337. super().__init__(env)
  338. assert agent_view_size % 2 == 1
  339. assert agent_view_size >= 3
  340. self.agent_view_size = agent_view_size
  341. # Compute observation space with specified view size
  342. new_image_space = gym.spaces.Box(
  343. low=0, high=255, shape=(agent_view_size, agent_view_size, 3), dtype="uint8"
  344. )
  345. # Override the environment's observation spaceexit
  346. self.observation_space = spaces.Dict(
  347. {**self.observation_space.spaces, "image": new_image_space}
  348. )
  349. def observation(self, obs):
  350. env = self.unwrapped
  351. grid, vis_mask = env.gen_obs_grid(self.agent_view_size)
  352. # Encode the partially observable view into a numpy array
  353. image = grid.encode(vis_mask)
  354. return {**obs, "image": image}
  355. class DirectionObsWrapper(ObservationWrapper):
  356. """
  357. Provides the slope/angular direction to the goal with the observations as modeled by (y2 - y2 )/( x2 - x1)
  358. type = {slope , angle}
  359. """
  360. def __init__(self, env, type="slope"):
  361. super().__init__(env)
  362. self.goal_position: tuple = None
  363. self.type = type
  364. def reset(self):
  365. obs = self.env.reset()
  366. if not self.goal_position:
  367. self.goal_position = [
  368. x for x, y in enumerate(self.grid.grid) if isinstance(y, Goal)
  369. ]
  370. # in case there are multiple goals , needs to be handled for other env types
  371. if len(self.goal_position) >= 1:
  372. self.goal_position = (
  373. int(self.goal_position[0] / self.height),
  374. self.goal_position[0] % self.width,
  375. )
  376. return obs
  377. def observation(self, obs):
  378. slope = np.divide(
  379. self.goal_position[1] - self.agent_pos[1],
  380. self.goal_position[0] - self.agent_pos[0],
  381. )
  382. obs["goal_direction"] = np.arctan(slope) if self.type == "angle" else slope
  383. return obs
  384. class SymbolicObsWrapper(ObservationWrapper):
  385. """
  386. Fully observable grid with a symbolic state representation.
  387. The symbol is a triple of (X, Y, IDX), where X and Y are
  388. the coordinates on the grid, and IDX is the id of the object.
  389. """
  390. def __init__(self, env):
  391. super().__init__(env)
  392. new_image_space = spaces.Box(
  393. low=0,
  394. high=max(OBJECT_TO_IDX.values()),
  395. shape=(self.env.width, self.env.height, 3), # number of cells
  396. dtype="uint8",
  397. )
  398. self.observation_space = spaces.Dict(
  399. {**self.observation_space.spaces, "image": new_image_space}
  400. )
  401. def observation(self, obs):
  402. objects = np.array(
  403. [OBJECT_TO_IDX[o.type] if o is not None else -1 for o in self.grid.grid]
  404. )
  405. w, h = self.width, self.height
  406. grid = np.mgrid[:w, :h]
  407. grid = np.concatenate([grid, objects.reshape(1, w, h)])
  408. grid = np.transpose(grid, (1, 2, 0))
  409. obs["image"] = grid
  410. return obs