minigrid.py 34 KB

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