minigrid.py 35 KB

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