minigrid.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  1. import hashlib
  2. import math
  3. import string
  4. from abc import abstractmethod
  5. from enum import IntEnum
  6. import gym
  7. import numpy as np
  8. from gym import spaces
  9. # Size in pixels of a tile in the full-scale human view
  10. from gym_minigrid.rendering import (
  11. downsample,
  12. fill_coords,
  13. highlight_img,
  14. point_in_circle,
  15. point_in_line,
  16. point_in_rect,
  17. point_in_triangle,
  18. rotate_fn,
  19. )
  20. from gym_minigrid.window import Window
  21. TILE_PIXELS = 32
  22. # Map of color names to RGB values
  23. COLORS = {
  24. "red": np.array([255, 0, 0]),
  25. "green": np.array([0, 255, 0]),
  26. "blue": np.array([0, 0, 255]),
  27. "purple": np.array([112, 39, 195]),
  28. "yellow": np.array([255, 255, 0]),
  29. "grey": np.array([100, 100, 100]),
  30. }
  31. COLOR_NAMES = sorted(list(COLORS.keys()))
  32. # Used to map colors to integers
  33. COLOR_TO_IDX = {"red": 0, "green": 1, "blue": 2, "purple": 3, "yellow": 4, "grey": 5}
  34. IDX_TO_COLOR = dict(zip(COLOR_TO_IDX.values(), COLOR_TO_IDX.keys()))
  35. # Map of object type to integers
  36. OBJECT_TO_IDX = {
  37. "unseen": 0,
  38. "empty": 1,
  39. "wall": 2,
  40. "floor": 3,
  41. "door": 4,
  42. "key": 5,
  43. "ball": 6,
  44. "box": 7,
  45. "goal": 8,
  46. "lava": 9,
  47. "agent": 10,
  48. }
  49. IDX_TO_OBJECT = dict(zip(OBJECT_TO_IDX.values(), OBJECT_TO_IDX.keys()))
  50. # Map of state names to integers
  51. STATE_TO_IDX = {
  52. "open": 0,
  53. "closed": 1,
  54. "locked": 2,
  55. }
  56. # Map of agent direction indices to vectors
  57. DIR_TO_VEC = [
  58. # Pointing right (positive X)
  59. np.array((1, 0)),
  60. # Down (positive Y)
  61. np.array((0, 1)),
  62. # Pointing left (negative X)
  63. np.array((-1, 0)),
  64. # Up (negative Y)
  65. np.array((0, -1)),
  66. ]
  67. class WorldObj:
  68. """
  69. Base class for grid world objects
  70. """
  71. def __init__(self, type, color):
  72. assert type in OBJECT_TO_IDX, type
  73. assert color in COLOR_TO_IDX, color
  74. self.type = type
  75. self.color = color
  76. self.contains = None
  77. # Initial position of the object
  78. self.init_pos = None
  79. # Current position of the object
  80. self.cur_pos = None
  81. def can_overlap(self):
  82. """Can the agent overlap with this?"""
  83. return False
  84. def can_pickup(self):
  85. """Can the agent pick this up?"""
  86. return False
  87. def can_contain(self):
  88. """Can this contain another object?"""
  89. return False
  90. def see_behind(self):
  91. """Can the agent see behind this object?"""
  92. return True
  93. def toggle(self, env, pos):
  94. """Method to trigger/toggle an action this object performs"""
  95. return False
  96. def encode(self):
  97. """Encode the a description of this object as a 3-tuple of integers"""
  98. return (OBJECT_TO_IDX[self.type], COLOR_TO_IDX[self.color], 0)
  99. @staticmethod
  100. def decode(type_idx, color_idx, state):
  101. """Create an object from a 3-tuple state description"""
  102. obj_type = IDX_TO_OBJECT[type_idx]
  103. color = IDX_TO_COLOR[color_idx]
  104. if obj_type == "empty" or obj_type == "unseen":
  105. return None
  106. # State, 0: open, 1: closed, 2: locked
  107. is_open = state == 0
  108. is_locked = state == 2
  109. if obj_type == "wall":
  110. v = Wall(color)
  111. elif obj_type == "floor":
  112. v = Floor(color)
  113. elif obj_type == "ball":
  114. v = Ball(color)
  115. elif obj_type == "key":
  116. v = Key(color)
  117. elif obj_type == "box":
  118. v = Box(color)
  119. elif obj_type == "door":
  120. v = Door(color, is_open, is_locked)
  121. elif obj_type == "goal":
  122. v = Goal()
  123. elif obj_type == "lava":
  124. v = Lava()
  125. else:
  126. assert False, "unknown object type in decode '%s'" % obj_type
  127. return v
  128. def render(self, r):
  129. """Draw this object with the given renderer"""
  130. raise NotImplementedError
  131. class Goal(WorldObj):
  132. def __init__(self):
  133. super().__init__("goal", "green")
  134. def can_overlap(self):
  135. return True
  136. def render(self, img):
  137. fill_coords(img, point_in_rect(0, 1, 0, 1), COLORS[self.color])
  138. class Floor(WorldObj):
  139. """
  140. Colored floor tile the agent can walk over
  141. """
  142. def __init__(self, color="blue"):
  143. super().__init__("floor", color)
  144. def can_overlap(self):
  145. return True
  146. def render(self, img):
  147. # Give the floor a pale color
  148. color = COLORS[self.color] / 2
  149. fill_coords(img, point_in_rect(0.031, 1, 0.031, 1), color)
  150. class Lava(WorldObj):
  151. def __init__(self):
  152. super().__init__("lava", "red")
  153. def can_overlap(self):
  154. return True
  155. def render(self, img):
  156. c = (255, 128, 0)
  157. # Background color
  158. fill_coords(img, point_in_rect(0, 1, 0, 1), c)
  159. # Little waves
  160. for i in range(3):
  161. ylo = 0.3 + 0.2 * i
  162. yhi = 0.4 + 0.2 * i
  163. fill_coords(img, point_in_line(0.1, ylo, 0.3, yhi, r=0.03), (0, 0, 0))
  164. fill_coords(img, point_in_line(0.3, yhi, 0.5, ylo, r=0.03), (0, 0, 0))
  165. fill_coords(img, point_in_line(0.5, ylo, 0.7, yhi, r=0.03), (0, 0, 0))
  166. fill_coords(img, point_in_line(0.7, yhi, 0.9, ylo, r=0.03), (0, 0, 0))
  167. class Wall(WorldObj):
  168. def __init__(self, color="grey"):
  169. super().__init__("wall", color)
  170. def see_behind(self):
  171. return False
  172. def render(self, img):
  173. fill_coords(img, point_in_rect(0, 1, 0, 1), COLORS[self.color])
  174. class Door(WorldObj):
  175. def __init__(self, color, is_open=False, is_locked=False):
  176. super().__init__("door", color)
  177. self.is_open = is_open
  178. self.is_locked = is_locked
  179. def can_overlap(self):
  180. """The agent can only walk over this cell when the door is open"""
  181. return self.is_open
  182. def see_behind(self):
  183. return self.is_open
  184. def toggle(self, env, pos):
  185. # If the player has the right key to open the door
  186. if self.is_locked:
  187. if isinstance(env.carrying, Key) and env.carrying.color == self.color:
  188. self.is_locked = False
  189. self.is_open = True
  190. return True
  191. return False
  192. self.is_open = not self.is_open
  193. return True
  194. def encode(self):
  195. """Encode the a description of this object as a 3-tuple of integers"""
  196. # State, 0: open, 1: closed, 2: locked
  197. if self.is_open:
  198. state = 0
  199. elif self.is_locked:
  200. state = 2
  201. # if door is closed and unlocked
  202. elif not self.is_open:
  203. state = 1
  204. else:
  205. raise ValueError(
  206. "There is no possible state encoding for the state:\n -Door Open: {}\n -Door Closed: {}\n -Door Locked: {}".format(
  207. self.is_open, not self.is_open, self.is_locked
  208. )
  209. )
  210. return (OBJECT_TO_IDX[self.type], COLOR_TO_IDX[self.color], state)
  211. def render(self, img):
  212. c = COLORS[self.color]
  213. if self.is_open:
  214. fill_coords(img, point_in_rect(0.88, 1.00, 0.00, 1.00), c)
  215. fill_coords(img, point_in_rect(0.92, 0.96, 0.04, 0.96), (0, 0, 0))
  216. return
  217. # Door frame and door
  218. if self.is_locked:
  219. fill_coords(img, point_in_rect(0.00, 1.00, 0.00, 1.00), c)
  220. fill_coords(img, point_in_rect(0.06, 0.94, 0.06, 0.94), 0.45 * np.array(c))
  221. # Draw key slot
  222. fill_coords(img, point_in_rect(0.52, 0.75, 0.50, 0.56), c)
  223. else:
  224. fill_coords(img, point_in_rect(0.00, 1.00, 0.00, 1.00), c)
  225. fill_coords(img, point_in_rect(0.04, 0.96, 0.04, 0.96), (0, 0, 0))
  226. fill_coords(img, point_in_rect(0.08, 0.92, 0.08, 0.92), c)
  227. fill_coords(img, point_in_rect(0.12, 0.88, 0.12, 0.88), (0, 0, 0))
  228. # Draw door handle
  229. fill_coords(img, point_in_circle(cx=0.75, cy=0.50, r=0.08), c)
  230. class Key(WorldObj):
  231. def __init__(self, color="blue"):
  232. super().__init__("key", color)
  233. def can_pickup(self):
  234. return True
  235. def render(self, img):
  236. c = COLORS[self.color]
  237. # Vertical quad
  238. fill_coords(img, point_in_rect(0.50, 0.63, 0.31, 0.88), c)
  239. # Teeth
  240. fill_coords(img, point_in_rect(0.38, 0.50, 0.59, 0.66), c)
  241. fill_coords(img, point_in_rect(0.38, 0.50, 0.81, 0.88), c)
  242. # Ring
  243. fill_coords(img, point_in_circle(cx=0.56, cy=0.28, r=0.190), c)
  244. fill_coords(img, point_in_circle(cx=0.56, cy=0.28, r=0.064), (0, 0, 0))
  245. class Ball(WorldObj):
  246. def __init__(self, color="blue"):
  247. super().__init__("ball", color)
  248. def can_pickup(self):
  249. return True
  250. def render(self, img):
  251. fill_coords(img, point_in_circle(0.5, 0.5, 0.31), COLORS[self.color])
  252. class Box(WorldObj):
  253. def __init__(self, color, contains=None):
  254. super().__init__("box", color)
  255. self.contains = contains
  256. def can_pickup(self):
  257. return True
  258. def render(self, img):
  259. c = COLORS[self.color]
  260. # Outline
  261. fill_coords(img, point_in_rect(0.12, 0.88, 0.12, 0.88), c)
  262. fill_coords(img, point_in_rect(0.18, 0.82, 0.18, 0.82), (0, 0, 0))
  263. # Horizontal slit
  264. fill_coords(img, point_in_rect(0.16, 0.84, 0.47, 0.53), c)
  265. def toggle(self, env, pos):
  266. # Replace the box by its contents
  267. env.grid.set(*pos, self.contains)
  268. return True
  269. class Grid:
  270. """
  271. Represent a grid and operations on it
  272. """
  273. # Static cache of pre-renderer tiles
  274. tile_cache = {}
  275. def __init__(self, width, height):
  276. assert width >= 3
  277. assert height >= 3
  278. self.width = width
  279. self.height = height
  280. self.grid = [None] * width * height
  281. def __contains__(self, key):
  282. if isinstance(key, WorldObj):
  283. for e in self.grid:
  284. if e is key:
  285. return True
  286. elif isinstance(key, tuple):
  287. for e in self.grid:
  288. if e is None:
  289. continue
  290. if (e.color, e.type) == key:
  291. return True
  292. if key[0] is None and key[1] == e.type:
  293. return True
  294. return False
  295. def __eq__(self, other):
  296. grid1 = self.encode()
  297. grid2 = other.encode()
  298. return np.array_equal(grid2, grid1)
  299. def __ne__(self, other):
  300. return not self == other
  301. def copy(self):
  302. from copy import deepcopy
  303. return deepcopy(self)
  304. def set(self, i, j, v):
  305. assert i >= 0 and i < self.width
  306. assert j >= 0 and j < self.height
  307. self.grid[j * self.width + i] = v
  308. def get(self, i, j):
  309. assert i >= 0 and i < self.width
  310. assert j >= 0 and j < self.height
  311. return self.grid[j * self.width + i]
  312. def horz_wall(self, x, y, length=None, obj_type=Wall):
  313. if length is None:
  314. length = self.width - x
  315. for i in range(0, length):
  316. self.set(x + i, y, obj_type())
  317. def vert_wall(self, x, y, length=None, obj_type=Wall):
  318. if length is None:
  319. length = self.height - y
  320. for j in range(0, length):
  321. self.set(x, y + j, obj_type())
  322. def wall_rect(self, x, y, w, h):
  323. self.horz_wall(x, y, w)
  324. self.horz_wall(x, y + h - 1, w)
  325. self.vert_wall(x, y, h)
  326. self.vert_wall(x + w - 1, y, h)
  327. def rotate_left(self):
  328. """
  329. Rotate the grid to the left (counter-clockwise)
  330. """
  331. grid = Grid(self.height, self.width)
  332. for i in range(self.width):
  333. for j in range(self.height):
  334. v = self.get(i, j)
  335. grid.set(j, grid.height - 1 - i, v)
  336. return grid
  337. def slice(self, topX, topY, width, height):
  338. """
  339. Get a subset of the grid
  340. """
  341. grid = Grid(width, height)
  342. for j in range(0, height):
  343. for i in range(0, width):
  344. x = topX + i
  345. y = topY + j
  346. if x >= 0 and x < self.width and y >= 0 and y < self.height:
  347. v = self.get(x, y)
  348. else:
  349. v = Wall()
  350. grid.set(i, j, v)
  351. return grid
  352. @classmethod
  353. def render_tile(
  354. cls, obj, agent_dir=None, highlight=False, tile_size=TILE_PIXELS, subdivs=3
  355. ):
  356. """
  357. Render a tile and cache the result
  358. """
  359. # Hash map lookup key for the cache
  360. key = (agent_dir, highlight, tile_size)
  361. key = obj.encode() + key if obj else key
  362. if key in cls.tile_cache:
  363. return cls.tile_cache[key]
  364. img = np.zeros(
  365. shape=(tile_size * subdivs, tile_size * subdivs, 3), dtype=np.uint8
  366. )
  367. # Draw the grid lines (top and left edges)
  368. fill_coords(img, point_in_rect(0, 0.031, 0, 1), (100, 100, 100))
  369. fill_coords(img, point_in_rect(0, 1, 0, 0.031), (100, 100, 100))
  370. if obj is not None:
  371. obj.render(img)
  372. # Overlay the agent on top
  373. if agent_dir is not None:
  374. tri_fn = point_in_triangle(
  375. (0.12, 0.19),
  376. (0.87, 0.50),
  377. (0.12, 0.81),
  378. )
  379. # Rotate the agent based on its direction
  380. tri_fn = rotate_fn(tri_fn, cx=0.5, cy=0.5, theta=0.5 * math.pi * agent_dir)
  381. fill_coords(img, tri_fn, (255, 0, 0))
  382. # Highlight the cell if needed
  383. if highlight:
  384. highlight_img(img)
  385. # Downsample the image to perform supersampling/anti-aliasing
  386. img = downsample(img, subdivs)
  387. # Cache the rendered tile
  388. cls.tile_cache[key] = img
  389. return img
  390. def render(self, tile_size, agent_pos=None, agent_dir=None, highlight_mask=None):
  391. """
  392. Render this grid at a given scale
  393. :param r: target renderer object
  394. :param tile_size: tile size in pixels
  395. """
  396. if highlight_mask is None:
  397. highlight_mask = np.zeros(shape=(self.width, self.height), dtype=bool)
  398. # Compute the total grid size
  399. width_px = self.width * tile_size
  400. height_px = self.height * tile_size
  401. img = np.zeros(shape=(height_px, width_px, 3), dtype=np.uint8)
  402. # Render the grid
  403. for j in range(0, self.height):
  404. for i in range(0, self.width):
  405. cell = self.get(i, j)
  406. agent_here = np.array_equal(agent_pos, (i, j))
  407. tile_img = Grid.render_tile(
  408. cell,
  409. agent_dir=agent_dir if agent_here else None,
  410. highlight=highlight_mask[i, j],
  411. tile_size=tile_size,
  412. )
  413. ymin = j * tile_size
  414. ymax = (j + 1) * tile_size
  415. xmin = i * tile_size
  416. xmax = (i + 1) * tile_size
  417. img[ymin:ymax, xmin:xmax, :] = tile_img
  418. return img
  419. def encode(self, vis_mask=None):
  420. """
  421. Produce a compact numpy encoding of the grid
  422. """
  423. if vis_mask is None:
  424. vis_mask = np.ones((self.width, self.height), dtype=bool)
  425. array = np.zeros((self.width, self.height, 3), dtype="uint8")
  426. for i in range(self.width):
  427. for j in range(self.height):
  428. if vis_mask[i, j]:
  429. v = self.get(i, j)
  430. if v is None:
  431. array[i, j, 0] = OBJECT_TO_IDX["empty"]
  432. array[i, j, 1] = 0
  433. array[i, j, 2] = 0
  434. else:
  435. array[i, j, :] = v.encode()
  436. return array
  437. @staticmethod
  438. def decode(array):
  439. """
  440. Decode an array grid encoding back into a grid
  441. """
  442. width, height, channels = array.shape
  443. assert channels == 3
  444. vis_mask = np.ones(shape=(width, height), dtype=bool)
  445. grid = Grid(width, height)
  446. for i in range(width):
  447. for j in range(height):
  448. type_idx, color_idx, state = array[i, j]
  449. v = WorldObj.decode(type_idx, color_idx, state)
  450. grid.set(i, j, v)
  451. vis_mask[i, j] = type_idx != OBJECT_TO_IDX["unseen"]
  452. return grid, vis_mask
  453. def process_vis(self, agent_pos):
  454. mask = np.zeros(shape=(self.width, self.height), dtype=bool)
  455. mask[agent_pos[0], agent_pos[1]] = True
  456. for j in reversed(range(0, self.height)):
  457. for i in range(0, self.width - 1):
  458. if not mask[i, j]:
  459. continue
  460. cell = self.get(i, j)
  461. if cell and not cell.see_behind():
  462. continue
  463. mask[i + 1, j] = True
  464. if j > 0:
  465. mask[i + 1, j - 1] = True
  466. mask[i, j - 1] = True
  467. for i in reversed(range(1, self.width)):
  468. if not mask[i, j]:
  469. continue
  470. cell = self.get(i, j)
  471. if cell and not cell.see_behind():
  472. continue
  473. mask[i - 1, j] = True
  474. if j > 0:
  475. mask[i - 1, j - 1] = True
  476. mask[i, j - 1] = True
  477. for j in range(0, self.height):
  478. for i in range(0, self.width):
  479. if not mask[i, j]:
  480. self.set(i, j, None)
  481. return mask
  482. class MiniGridEnv(gym.Env):
  483. """
  484. 2D grid world game environment
  485. """
  486. metadata = {
  487. # Deprecated: use 'render_modes' instead
  488. "render.modes": ["human", "rgb_array"],
  489. "video.frames_per_second": 10, # Deprecated: use 'render_fps' instead
  490. "render_modes": ["human", "rgb_array"],
  491. "render_fps": 10,
  492. }
  493. # Enumeration of possible actions
  494. class Actions(IntEnum):
  495. # Turn left, turn right, move forward
  496. left = 0
  497. right = 1
  498. forward = 2
  499. # Pick up an object
  500. pickup = 3
  501. # Drop an object
  502. drop = 4
  503. # Toggle/activate an object
  504. toggle = 5
  505. # Done completing task
  506. done = 6
  507. def __init__(
  508. self,
  509. grid_size: int = None,
  510. width: int = None,
  511. height: int = None,
  512. max_steps: int = 100,
  513. see_through_walls: bool = False,
  514. agent_view_size: int = 7,
  515. render_mode: str = None,
  516. **kwargs
  517. ):
  518. # Can't set both grid_size and width/height
  519. if grid_size:
  520. assert width is None and height is None
  521. width = grid_size
  522. height = grid_size
  523. # Action enumeration for this environment
  524. self.actions = MiniGridEnv.Actions
  525. # Actions are discrete integer values
  526. self.action_space = spaces.Discrete(len(self.actions))
  527. # Number of cells (width and height) in the agent view
  528. assert agent_view_size % 2 == 1
  529. assert agent_view_size >= 3
  530. self.agent_view_size = agent_view_size
  531. # Observations are dictionaries containing an
  532. # encoding of the grid and a textual 'mission' string
  533. self.observation_space = spaces.Box(
  534. low=0,
  535. high=255,
  536. shape=(self.agent_view_size, self.agent_view_size, 3),
  537. dtype="uint8",
  538. )
  539. self.observation_space = spaces.Dict(
  540. {
  541. "image": self.observation_space,
  542. "direction": spaces.Discrete(4),
  543. "mission": spaces.Text(
  544. max_length=200,
  545. charset=string.ascii_letters + string.digits + " .,!-",
  546. ),
  547. }
  548. )
  549. # render mode
  550. self.render_mode = render_mode
  551. # Range of possible rewards
  552. self.reward_range = (0, 1)
  553. self.window: Window = None
  554. # Environment configuration
  555. self.width = width
  556. self.height = height
  557. self.max_steps = max_steps
  558. self.see_through_walls = see_through_walls
  559. # Current position and direction of the agent
  560. self.agent_pos: np.ndarray = None
  561. self.agent_dir: int = None
  562. # Initialize the state
  563. self.reset()
  564. def reset(self, *, seed=None, return_info=False, options=None):
  565. super().reset(seed=seed)
  566. # Current position and direction of the agent
  567. self.agent_pos = None
  568. self.agent_dir = None
  569. # Generate a new random grid at the start of each episode
  570. self._gen_grid(self.width, self.height)
  571. # These fields should be defined by _gen_grid
  572. assert self.agent_pos is not None
  573. assert self.agent_dir is not None
  574. # Check that the agent doesn't overlap with an object
  575. start_cell = self.grid.get(*self.agent_pos)
  576. assert start_cell is None or start_cell.can_overlap()
  577. # Item picked up, being carried, initially nothing
  578. self.carrying = None
  579. # Step count since episode start
  580. self.step_count = 0
  581. # Return first observation
  582. obs = self.gen_obs()
  583. return obs
  584. def hash(self, size=16):
  585. """Compute a hash that uniquely identifies the current state of the environment.
  586. :param size: Size of the hashing
  587. """
  588. sample_hash = hashlib.sha256()
  589. to_encode = [self.grid.encode().tolist(), self.agent_pos, self.agent_dir]
  590. for item in to_encode:
  591. sample_hash.update(str(item).encode("utf8"))
  592. return sample_hash.hexdigest()[:size]
  593. @property
  594. def steps_remaining(self):
  595. return self.max_steps - self.step_count
  596. def __str__(self):
  597. """
  598. Produce a pretty string of the environment's grid along with the agent.
  599. A grid cell is represented by 2-character string, the first one for
  600. the object and the second one for the color.
  601. """
  602. # Map of object types to short string
  603. OBJECT_TO_STR = {
  604. "wall": "W",
  605. "floor": "F",
  606. "door": "D",
  607. "key": "K",
  608. "ball": "A",
  609. "box": "B",
  610. "goal": "G",
  611. "lava": "V",
  612. }
  613. # Map agent's direction to short string
  614. AGENT_DIR_TO_STR = {0: ">", 1: "V", 2: "<", 3: "^"}
  615. str = ""
  616. for j in range(self.grid.height):
  617. for i in range(self.grid.width):
  618. if i == self.agent_pos[0] and j == self.agent_pos[1]:
  619. str += 2 * AGENT_DIR_TO_STR[self.agent_dir]
  620. continue
  621. c = self.grid.get(i, j)
  622. if c is None:
  623. str += " "
  624. continue
  625. if c.type == "door":
  626. if c.is_open:
  627. str += "__"
  628. elif c.is_locked:
  629. str += "L" + c.color[0].upper()
  630. else:
  631. str += "D" + c.color[0].upper()
  632. continue
  633. str += OBJECT_TO_STR[c.type] + c.color[0].upper()
  634. if j < self.grid.height - 1:
  635. str += "\n"
  636. return str
  637. @abstractmethod
  638. def _gen_grid(self, width, height):
  639. pass
  640. def _reward(self):
  641. """
  642. Compute the reward to be given upon success
  643. """
  644. return 1 - 0.9 * (self.step_count / self.max_steps)
  645. def _rand_int(self, low, high):
  646. """
  647. Generate random integer in [low,high[
  648. """
  649. return self.np_random.integers(low, high)
  650. def _rand_float(self, low, high):
  651. """
  652. Generate random float in [low,high[
  653. """
  654. return self.np_random.uniform(low, high)
  655. def _rand_bool(self):
  656. """
  657. Generate random boolean value
  658. """
  659. return self.np_random.integers(0, 2) == 0
  660. def _rand_elem(self, iterable):
  661. """
  662. Pick a random element in a list
  663. """
  664. lst = list(iterable)
  665. idx = self._rand_int(0, len(lst))
  666. return lst[idx]
  667. def _rand_subset(self, iterable, num_elems):
  668. """
  669. Sample a random subset of distinct elements of a list
  670. """
  671. lst = list(iterable)
  672. assert num_elems <= len(lst)
  673. out = []
  674. while len(out) < num_elems:
  675. elem = self._rand_elem(lst)
  676. lst.remove(elem)
  677. out.append(elem)
  678. return out
  679. def _rand_color(self):
  680. """
  681. Generate a random color name (string)
  682. """
  683. return self._rand_elem(COLOR_NAMES)
  684. def _rand_pos(self, xLow, xHigh, yLow, yHigh):
  685. """
  686. Generate a random (x,y) position tuple
  687. """
  688. return (
  689. self.np_random.integers(xLow, xHigh),
  690. self.np_random.integers(yLow, yHigh),
  691. )
  692. def place_obj(self, obj, top=None, size=None, reject_fn=None, max_tries=math.inf):
  693. """
  694. Place an object at an empty position in the grid
  695. :param top: top-left position of the rectangle where to place
  696. :param size: size of the rectangle where to place
  697. :param reject_fn: function to filter out potential positions
  698. """
  699. if top is None:
  700. top = (0, 0)
  701. else:
  702. top = (max(top[0], 0), max(top[1], 0))
  703. if size is None:
  704. size = (self.grid.width, self.grid.height)
  705. num_tries = 0
  706. while True:
  707. # This is to handle with rare cases where rejection sampling
  708. # gets stuck in an infinite loop
  709. if num_tries > max_tries:
  710. raise RecursionError("rejection sampling failed in place_obj")
  711. num_tries += 1
  712. pos = np.array(
  713. (
  714. self._rand_int(top[0], min(top[0] + size[0], self.grid.width)),
  715. self._rand_int(top[1], min(top[1] + size[1], self.grid.height)),
  716. )
  717. )
  718. # Don't place the object on top of another object
  719. if self.grid.get(*pos) is not None:
  720. continue
  721. # Don't place the object where the agent is
  722. if np.array_equal(pos, self.agent_pos):
  723. continue
  724. # Check if there is a filtering criterion
  725. if reject_fn and reject_fn(self, pos):
  726. continue
  727. break
  728. self.grid.set(*pos, obj)
  729. if obj is not None:
  730. obj.init_pos = pos
  731. obj.cur_pos = pos
  732. return pos
  733. def put_obj(self, obj, i, j):
  734. """
  735. Put an object at a specific position in the grid
  736. """
  737. self.grid.set(i, j, obj)
  738. obj.init_pos = (i, j)
  739. obj.cur_pos = (i, j)
  740. def place_agent(self, top=None, size=None, rand_dir=True, max_tries=math.inf):
  741. """
  742. Set the agent's starting point at an empty position in the grid
  743. """
  744. self.agent_pos = None
  745. pos = self.place_obj(None, top, size, max_tries=max_tries)
  746. self.agent_pos = pos
  747. if rand_dir:
  748. self.agent_dir = self._rand_int(0, 4)
  749. return pos
  750. @property
  751. def dir_vec(self):
  752. """
  753. Get the direction vector for the agent, pointing in the direction
  754. of forward movement.
  755. """
  756. assert self.agent_dir >= 0 and self.agent_dir < 4
  757. return DIR_TO_VEC[self.agent_dir]
  758. @property
  759. def right_vec(self):
  760. """
  761. Get the vector pointing to the right of the agent.
  762. """
  763. dx, dy = self.dir_vec
  764. return np.array((-dy, dx))
  765. @property
  766. def front_pos(self):
  767. """
  768. Get the position of the cell that is right in front of the agent
  769. """
  770. return self.agent_pos + self.dir_vec
  771. def get_view_coords(self, i, j):
  772. """
  773. Translate and rotate absolute grid coordinates (i, j) into the
  774. agent's partially observable view (sub-grid). Note that the resulting
  775. coordinates may be negative or outside of the agent's view size.
  776. """
  777. ax, ay = self.agent_pos
  778. dx, dy = self.dir_vec
  779. rx, ry = self.right_vec
  780. # Compute the absolute coordinates of the top-left view corner
  781. sz = self.agent_view_size
  782. hs = self.agent_view_size // 2
  783. tx = ax + (dx * (sz - 1)) - (rx * hs)
  784. ty = ay + (dy * (sz - 1)) - (ry * hs)
  785. lx = i - tx
  786. ly = j - ty
  787. # Project the coordinates of the object relative to the top-left
  788. # corner onto the agent's own coordinate system
  789. vx = rx * lx + ry * ly
  790. vy = -(dx * lx + dy * ly)
  791. return vx, vy
  792. def get_view_exts(self, agent_view_size=None):
  793. """
  794. Get the extents of the square set of tiles visible to the agent
  795. Note: the bottom extent indices are not included in the set
  796. if agent_view_size is None, use self.agent_view_size
  797. """
  798. agent_view_size = agent_view_size or self.agent_view_size
  799. # Facing right
  800. if self.agent_dir == 0:
  801. topX = self.agent_pos[0]
  802. topY = self.agent_pos[1] - agent_view_size // 2
  803. # Facing down
  804. elif self.agent_dir == 1:
  805. topX = self.agent_pos[0] - agent_view_size // 2
  806. topY = self.agent_pos[1]
  807. # Facing left
  808. elif self.agent_dir == 2:
  809. topX = self.agent_pos[0] - agent_view_size + 1
  810. topY = self.agent_pos[1] - agent_view_size // 2
  811. # Facing up
  812. elif self.agent_dir == 3:
  813. topX = self.agent_pos[0] - agent_view_size // 2
  814. topY = self.agent_pos[1] - agent_view_size + 1
  815. else:
  816. assert False, "invalid agent direction"
  817. botX = topX + agent_view_size
  818. botY = topY + agent_view_size
  819. return (topX, topY, botX, botY)
  820. def relative_coords(self, x, y):
  821. """
  822. Check if a grid position belongs to the agent's field of view, and returns the corresponding coordinates
  823. """
  824. vx, vy = self.get_view_coords(x, y)
  825. if vx < 0 or vy < 0 or vx >= self.agent_view_size or vy >= self.agent_view_size:
  826. return None
  827. return vx, vy
  828. def in_view(self, x, y):
  829. """
  830. check if a grid position is visible to the agent
  831. """
  832. return self.relative_coords(x, y) is not None
  833. def agent_sees(self, x, y):
  834. """
  835. Check if a non-empty grid position is visible to the agent
  836. """
  837. coordinates = self.relative_coords(x, y)
  838. if coordinates is None:
  839. return False
  840. vx, vy = coordinates
  841. obs = self.gen_obs()
  842. obs_grid, _ = Grid.decode(obs["image"])
  843. obs_cell = obs_grid.get(vx, vy)
  844. world_cell = self.grid.get(x, y)
  845. return obs_cell is not None and obs_cell.type == world_cell.type
  846. def step(self, action):
  847. self.step_count += 1
  848. reward = 0
  849. done = False
  850. # Get the position in front of the agent
  851. fwd_pos = self.front_pos
  852. # Get the contents of the cell in front of the agent
  853. fwd_cell = self.grid.get(*fwd_pos)
  854. # Rotate left
  855. if action == self.actions.left:
  856. self.agent_dir -= 1
  857. if self.agent_dir < 0:
  858. self.agent_dir += 4
  859. # Rotate right
  860. elif action == self.actions.right:
  861. self.agent_dir = (self.agent_dir + 1) % 4
  862. # Move forward
  863. elif action == self.actions.forward:
  864. if fwd_cell is None or fwd_cell.can_overlap():
  865. self.agent_pos = fwd_pos
  866. if fwd_cell is not None and fwd_cell.type == "goal":
  867. done = True
  868. reward = self._reward()
  869. if fwd_cell is not None and fwd_cell.type == "lava":
  870. done = True
  871. # Pick up an object
  872. elif action == self.actions.pickup:
  873. if fwd_cell and fwd_cell.can_pickup():
  874. if self.carrying is None:
  875. self.carrying = fwd_cell
  876. self.carrying.cur_pos = np.array([-1, -1])
  877. self.grid.set(*fwd_pos, None)
  878. # Drop an object
  879. elif action == self.actions.drop:
  880. if not fwd_cell and self.carrying:
  881. self.grid.set(*fwd_pos, self.carrying)
  882. self.carrying.cur_pos = fwd_pos
  883. self.carrying = None
  884. # Toggle/activate an object
  885. elif action == self.actions.toggle:
  886. if fwd_cell:
  887. fwd_cell.toggle(self, fwd_pos)
  888. # Done action (not used by default)
  889. elif action == self.actions.done:
  890. pass
  891. else:
  892. assert False, "unknown action"
  893. if self.step_count >= self.max_steps:
  894. done = True
  895. obs = self.gen_obs()
  896. return obs, reward, done, {}
  897. def gen_obs_grid(self, agent_view_size=None):
  898. """
  899. Generate the sub-grid observed by the agent.
  900. This method also outputs a visibility mask telling us which grid
  901. cells the agent can actually see.
  902. if agent_view_size is None, self.agent_view_size is used
  903. """
  904. topX, topY, botX, botY = self.get_view_exts(agent_view_size)
  905. agent_view_size = agent_view_size or self.agent_view_size
  906. grid = self.grid.slice(topX, topY, agent_view_size, agent_view_size)
  907. for i in range(self.agent_dir + 1):
  908. grid = grid.rotate_left()
  909. # Process occluders and visibility
  910. # Note that this incurs some performance cost
  911. if not self.see_through_walls:
  912. vis_mask = grid.process_vis(
  913. agent_pos=(agent_view_size // 2, agent_view_size - 1)
  914. )
  915. else:
  916. vis_mask = np.ones(shape=(grid.width, grid.height), dtype=bool)
  917. # Make it so the agent sees what it's carrying
  918. # We do this by placing the carried object at the agent's position
  919. # in the agent's partially observable view
  920. agent_pos = grid.width // 2, grid.height - 1
  921. if self.carrying:
  922. grid.set(*agent_pos, self.carrying)
  923. else:
  924. grid.set(*agent_pos, None)
  925. return grid, vis_mask
  926. def gen_obs(self):
  927. """
  928. Generate the agent's view (partially observable, low-resolution encoding)
  929. """
  930. grid, vis_mask = self.gen_obs_grid()
  931. # Encode the partially observable view into a numpy array
  932. image = grid.encode(vis_mask)
  933. assert hasattr(
  934. self, "mission"
  935. ), "environments must define a textual mission string"
  936. # Observations are dictionaries containing:
  937. # - an image (partially observable view of the environment)
  938. # - the agent's direction/orientation (acting as a compass)
  939. # - a textual mission string (instructions for the agent)
  940. obs = {"image": image, "direction": self.agent_dir, "mission": self.mission}
  941. return obs
  942. def get_obs_render(self, obs, tile_size=TILE_PIXELS // 2):
  943. """
  944. Render an agent observation for visualization
  945. """
  946. grid, vis_mask = Grid.decode(obs)
  947. # Render the whole grid
  948. img = grid.render(
  949. tile_size,
  950. agent_pos=(self.agent_view_size // 2, self.agent_view_size - 1),
  951. agent_dir=3,
  952. highlight_mask=vis_mask,
  953. )
  954. return img
  955. def render(self, mode="human", close=False, highlight=True, tile_size=TILE_PIXELS):
  956. """
  957. Render the whole-grid human view
  958. """
  959. if self.render_mode is not None:
  960. mode = self.render_mode
  961. if close:
  962. if self.window:
  963. self.window.close()
  964. return
  965. if mode == "human" and not self.window:
  966. self.window = Window("gym_minigrid")
  967. self.window.show(block=False)
  968. # Compute which cells are visible to the agent
  969. _, vis_mask = self.gen_obs_grid()
  970. # Compute the world coordinates of the bottom-left corner
  971. # of the agent's view area
  972. f_vec = self.dir_vec
  973. r_vec = self.right_vec
  974. top_left = (
  975. self.agent_pos
  976. + f_vec * (self.agent_view_size - 1)
  977. - r_vec * (self.agent_view_size // 2)
  978. )
  979. # Mask of which cells to highlight
  980. highlight_mask = np.zeros(shape=(self.width, self.height), dtype=bool)
  981. # For each cell in the visibility mask
  982. for vis_j in range(0, self.agent_view_size):
  983. for vis_i in range(0, self.agent_view_size):
  984. # If this cell is not visible, don't highlight it
  985. if not vis_mask[vis_i, vis_j]:
  986. continue
  987. # Compute the world coordinates of this cell
  988. abs_i, abs_j = top_left - (f_vec * vis_j) + (r_vec * vis_i)
  989. if abs_i < 0 or abs_i >= self.width:
  990. continue
  991. if abs_j < 0 or abs_j >= self.height:
  992. continue
  993. # Mark this cell to be highlighted
  994. highlight_mask[abs_i, abs_j] = True
  995. # Render the whole grid
  996. img = self.grid.render(
  997. tile_size,
  998. self.agent_pos,
  999. self.agent_dir,
  1000. highlight_mask=highlight_mask if highlight else None,
  1001. )
  1002. if mode == "human":
  1003. self.window.set_caption(self.mission)
  1004. self.window.show_img(img)
  1005. return img
  1006. def close(self):
  1007. if self.window:
  1008. self.window.close()
  1009. return