wrappers.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 .minigrid import COLOR_TO_IDX, OBJECT_TO_IDX, STATE_TO_IDX, Goal
  8. class ReseedWrapper(gym.core.Wrapper):
  9. """
  10. Wrapper to always regenerate an environment with the same set of seeds.
  11. This can be used to force an environment to always keep the same
  12. configuration when reset.
  13. """
  14. def __init__(self, env, seeds=[0], seed_idx=0):
  15. self.seeds = list(seeds)
  16. self.seed_idx = seed_idx
  17. super().__init__(env)
  18. def reset(self, **kwargs):
  19. seed = self.seeds[self.seed_idx]
  20. self.seed_idx = (self.seed_idx + 1) % len(self.seeds)
  21. self.env.seed(seed)
  22. return self.env.reset(**kwargs)
  23. def step(self, action):
  24. obs, reward, done, info = self.env.step(action)
  25. return obs, reward, done, info
  26. class ActionBonus(gym.core.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, done, 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, done, info
  49. def reset(self, **kwargs):
  50. return self.env.reset(**kwargs)
  51. class StateBonus(gym.core.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, done, 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, done, info
  75. def reset(self, **kwargs):
  76. return self.env.reset(**kwargs)
  77. class ImgObsWrapper(gym.core.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(gym.core.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. self.observation_space.spaces["image"] = spaces.Box(
  98. low=0, high=255, shape=(obs_shape[0], obs_shape[1], num_bits), dtype="uint8"
  99. )
  100. def observation(self, obs):
  101. img = obs["image"]
  102. out = np.zeros(self.observation_space.spaces["image"].shape, dtype="uint8")
  103. for i in range(img.shape[0]):
  104. for j in range(img.shape[1]):
  105. type = img[i, j, 0]
  106. color = img[i, j, 1]
  107. state = img[i, j, 2]
  108. out[i, j, type] = 1
  109. out[i, j, len(OBJECT_TO_IDX) + color] = 1
  110. out[i, j, len(OBJECT_TO_IDX) + len(COLOR_TO_IDX) + state] = 1
  111. return {**obs, "image": out}
  112. class RGBImgObsWrapper(gym.core.ObservationWrapper):
  113. """
  114. Wrapper to use fully observable RGB image as observation,
  115. This can be used to have the agent to solve the gridworld in pixel space.
  116. """
  117. def __init__(self, env, tile_size=8):
  118. super().__init__(env)
  119. self.tile_size = tile_size
  120. self.observation_space.spaces["image"] = spaces.Box(
  121. low=0,
  122. high=255,
  123. shape=(self.env.width * tile_size, self.env.height * tile_size, 3),
  124. dtype="uint8",
  125. )
  126. def observation(self, obs):
  127. env = self.unwrapped
  128. rgb_img = env.render(
  129. mode="rgb_array", highlight=False, tile_size=self.tile_size
  130. )
  131. return {**obs, "image": rgb_img}
  132. class RGBImgPartialObsWrapper(gym.core.ObservationWrapper):
  133. """
  134. Wrapper to use partially observable RGB image as observation.
  135. This can be used to have the agent to solve the gridworld in pixel space.
  136. """
  137. def __init__(self, env, tile_size=8):
  138. super().__init__(env)
  139. self.tile_size = tile_size
  140. obs_shape = env.observation_space.spaces["image"].shape
  141. self.observation_space.spaces["image"] = spaces.Box(
  142. low=0,
  143. high=255,
  144. shape=(obs_shape[0] * tile_size, obs_shape[1] * tile_size, 3),
  145. dtype="uint8",
  146. )
  147. def observation(self, obs):
  148. env = self.unwrapped
  149. rgb_img_partial = env.get_obs_render(obs["image"], tile_size=self.tile_size)
  150. return {**obs, "image": rgb_img_partial}
  151. class FullyObsWrapper(gym.core.ObservationWrapper):
  152. """
  153. Fully observable gridworld using a compact grid encoding
  154. """
  155. def __init__(self, env):
  156. super().__init__(env)
  157. self.observation_space.spaces["image"] = spaces.Box(
  158. low=0,
  159. high=255,
  160. shape=(self.env.width, self.env.height, 3), # number of cells
  161. dtype="uint8",
  162. )
  163. def observation(self, obs):
  164. env = self.unwrapped
  165. full_grid = env.grid.encode()
  166. full_grid[env.agent_pos[0]][env.agent_pos[1]] = np.array(
  167. [OBJECT_TO_IDX["agent"], COLOR_TO_IDX["red"], env.agent_dir]
  168. )
  169. return {**obs, "image": full_grid}
  170. class FlatObsWrapper(gym.core.ObservationWrapper):
  171. """
  172. Encode mission strings using a one-hot scheme,
  173. and combine these with observed images into one flat array
  174. """
  175. def __init__(self, env, maxStrLen=96):
  176. super().__init__(env)
  177. self.maxStrLen = maxStrLen
  178. self.numCharCodes = 27
  179. imgSpace = env.observation_space.spaces["image"]
  180. imgSize = reduce(operator.mul, imgSpace.shape, 1)
  181. self.observation_space = spaces.Box(
  182. low=0,
  183. high=255,
  184. shape=(imgSize + self.numCharCodes * self.maxStrLen,),
  185. dtype="uint8",
  186. )
  187. self.cachedStr = None
  188. self.cachedArray = None
  189. def observation(self, obs):
  190. image = obs["image"]
  191. mission = obs["mission"]
  192. # Cache the last-encoded mission string
  193. if mission != self.cachedStr:
  194. assert (
  195. len(mission) <= self.maxStrLen
  196. ), f"mission string too long ({len(mission)} chars)"
  197. mission = mission.lower()
  198. strArray = np.zeros(
  199. shape=(self.maxStrLen, self.numCharCodes), dtype="float32"
  200. )
  201. for idx, ch in enumerate(mission):
  202. if ch >= "a" and ch <= "z":
  203. chNo = ord(ch) - ord("a")
  204. elif ch == " ":
  205. chNo = ord("z") - ord("a") + 1
  206. assert chNo < self.numCharCodes, "%s : %d" % (ch, chNo)
  207. strArray[idx, chNo] = 1
  208. self.cachedStr = mission
  209. self.cachedArray = strArray
  210. obs = np.concatenate((image.flatten(), self.cachedArray.flatten()))
  211. return obs
  212. class ViewSizeWrapper(gym.core.Wrapper):
  213. """
  214. Wrapper to customize the agent field of view size.
  215. This cannot be used with fully observable wrappers.
  216. """
  217. def __init__(self, env, agent_view_size=7):
  218. super().__init__(env)
  219. assert agent_view_size % 2 == 1
  220. assert agent_view_size >= 3
  221. # Override default view size
  222. env.unwrapped.agent_view_size = agent_view_size
  223. # Compute observation space with specified view size
  224. observation_space = gym.spaces.Box(
  225. low=0, high=255, shape=(agent_view_size, agent_view_size, 3), dtype="uint8"
  226. )
  227. # Override the environment's observation space
  228. self.observation_space = spaces.Dict({"image": observation_space})
  229. def reset(self, **kwargs):
  230. return self.env.reset(**kwargs)
  231. def step(self, action):
  232. return self.env.step(action)
  233. class DirectionObsWrapper(gym.core.ObservationWrapper):
  234. """
  235. Provides the slope/angular direction to the goal with the observations as modeled by (y2 - y2 )/( x2 - x1)
  236. type = {slope , angle}
  237. """
  238. def __init__(self, env, type="slope"):
  239. super().__init__(env)
  240. self.goal_position = None
  241. self.type = type
  242. def reset(self):
  243. obs = self.env.reset()
  244. if not self.goal_position:
  245. self.goal_position = [
  246. x for x, y in enumerate(self.grid.grid) if isinstance(y, (Goal))
  247. ]
  248. if (
  249. len(self.goal_position) >= 1
  250. ): # in case there are multiple goals , needs to be handled for other env types
  251. self.goal_position = (
  252. int(self.goal_position[0] / self.height),
  253. self.goal_position[0] % self.width,
  254. )
  255. return obs
  256. def observation(self, obs):
  257. slope = np.divide(
  258. self.goal_position[1] - self.agent_pos[1],
  259. self.goal_position[0] - self.agent_pos[0],
  260. )
  261. obs["goal_direction"] = np.arctan(slope) if self.type == "angle" else slope
  262. return obs
  263. class SymbolicObsWrapper(gym.core.ObservationWrapper):
  264. """
  265. Fully observable grid with a symbolic state representation.
  266. The symbol is a triple of (X, Y, IDX), where X and Y are
  267. the coordinates on the grid, and IDX is the id of the object.
  268. """
  269. def __init__(self, env):
  270. super().__init__(env)
  271. self.observation_space.spaces["image"] = spaces.Box(
  272. low=0,
  273. high=max(OBJECT_TO_IDX.values()),
  274. shape=(self.env.width, self.env.height, 3), # number of cells
  275. dtype="uint8",
  276. )
  277. def observation(self, obs):
  278. objects = np.array(
  279. [OBJECT_TO_IDX[o.type] if o is not None else -1 for o in self.grid.grid]
  280. )
  281. w, h = self.width, self.height
  282. grid = np.mgrid[:w, :h]
  283. grid = np.concatenate([grid, objects.reshape(1, w, h)])
  284. grid = np.transpose(grid, (1, 2, 0))
  285. obs["image"] = grid
  286. return obs