minigrid.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  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, r):
  158. orange = 255, 128, 0
  159. r.setLineColor(*orange)
  160. r.setColor(*orange)
  161. r.drawPolygon([
  162. (0 , TILE_PIXELS),
  163. (TILE_PIXELS, TILE_PIXELS),
  164. (TILE_PIXELS, 0),
  165. (0 , 0)
  166. ])
  167. # drawing the waves
  168. r.setLineColor(0, 0, 0)
  169. r.drawPolyline([
  170. (.1 * TILE_PIXELS, .3 * TILE_PIXELS),
  171. (.3 * TILE_PIXELS, .4 * TILE_PIXELS),
  172. (.5 * TILE_PIXELS, .3 * TILE_PIXELS),
  173. (.7 * TILE_PIXELS, .4 * TILE_PIXELS),
  174. (.9 * TILE_PIXELS, .3 * TILE_PIXELS),
  175. ])
  176. r.drawPolyline([
  177. (.1 * TILE_PIXELS, .5 * TILE_PIXELS),
  178. (.3 * TILE_PIXELS, .6 * TILE_PIXELS),
  179. (.5 * TILE_PIXELS, .5 * TILE_PIXELS),
  180. (.7 * TILE_PIXELS, .6 * TILE_PIXELS),
  181. (.9 * TILE_PIXELS, .5 * TILE_PIXELS),
  182. ])
  183. r.drawPolyline([
  184. (.1 * TILE_PIXELS, .7 * TILE_PIXELS),
  185. (.3 * TILE_PIXELS, .8 * TILE_PIXELS),
  186. (.5 * TILE_PIXELS, .7 * TILE_PIXELS),
  187. (.7 * TILE_PIXELS, .8 * TILE_PIXELS),
  188. (.9 * TILE_PIXELS, .7 * TILE_PIXELS),
  189. ])
  190. class Wall(WorldObj):
  191. def __init__(self, color='grey'):
  192. super().__init__('wall', color)
  193. def see_behind(self):
  194. return False
  195. def render(self, img):
  196. fill_coords(img, point_in_rect(0, 1, 0, 1), COLORS[self.color])
  197. class Door(WorldObj):
  198. def __init__(self, color, is_open=False, is_locked=False):
  199. super().__init__('door', color)
  200. self.is_open = is_open
  201. self.is_locked = is_locked
  202. def can_overlap(self):
  203. """The agent can only walk over this cell when the door is open"""
  204. return self.is_open
  205. def see_behind(self):
  206. return self.is_open
  207. def toggle(self, env, pos):
  208. # If the player has the right key to open the door
  209. if self.is_locked:
  210. if isinstance(env.carrying, Key) and env.carrying.color == self.color:
  211. self.is_locked = False
  212. self.is_open = True
  213. return True
  214. return False
  215. self.is_open = not self.is_open
  216. return True
  217. def encode(self):
  218. """Encode the a description of this object as a 3-tuple of integers"""
  219. # State, 0: open, 1: closed, 2: locked
  220. if self.is_open:
  221. state = 0
  222. elif self.is_locked:
  223. state = 2
  224. elif not self.is_open:
  225. state = 1
  226. return (OBJECT_TO_IDX[self.type], COLOR_TO_IDX[self.color], state)
  227. def render(self, r):
  228. c = COLORS[self.color]
  229. r.setLineColor(c[0], c[1], c[2])
  230. r.setColor(c[0], c[1], c[2], 50 if self.is_locked else 0)
  231. if self.is_open:
  232. r.drawPolygon([
  233. (TILE_PIXELS-2, TILE_PIXELS),
  234. (TILE_PIXELS , TILE_PIXELS),
  235. (TILE_PIXELS , 0),
  236. (TILE_PIXELS-2, 0)
  237. ])
  238. return
  239. r.drawPolygon([
  240. (0 , TILE_PIXELS),
  241. (TILE_PIXELS, TILE_PIXELS),
  242. (TILE_PIXELS, 0),
  243. (0 , 0)
  244. ])
  245. r.drawPolygon([
  246. (2 , TILE_PIXELS-2),
  247. (TILE_PIXELS-2, TILE_PIXELS-2),
  248. (TILE_PIXELS-2, 2),
  249. (2 , 2)
  250. ])
  251. if self.is_locked:
  252. # Draw key slot
  253. r.drawLine(
  254. TILE_PIXELS * 0.55,
  255. TILE_PIXELS * 0.5,
  256. TILE_PIXELS * 0.75,
  257. TILE_PIXELS * 0.5
  258. )
  259. else:
  260. # Draw door handle
  261. r.drawCircle(TILE_PIXELS * 0.75, TILE_PIXELS * 0.5, 2)
  262. class Key(WorldObj):
  263. def __init__(self, color='blue'):
  264. super(Key, self).__init__('key', color)
  265. def can_pickup(self):
  266. return True
  267. def render(self, r):
  268. self._set_color(r)
  269. # Vertical quad
  270. r.drawPolygon([
  271. (16, 10),
  272. (20, 10),
  273. (20, 28),
  274. (16, 28)
  275. ])
  276. # Teeth
  277. r.drawPolygon([
  278. (12, 19),
  279. (16, 19),
  280. (16, 21),
  281. (12, 21)
  282. ])
  283. r.drawPolygon([
  284. (12, 26),
  285. (16, 26),
  286. (16, 28),
  287. (12, 28)
  288. ])
  289. r.drawCircle(18, 9, 6)
  290. r.setLineColor(0, 0, 0)
  291. r.setColor(0, 0, 0)
  292. r.drawCircle(18, 9, 2)
  293. class Ball(WorldObj):
  294. def __init__(self, color='blue'):
  295. super(Ball, self).__init__('ball', color)
  296. def can_pickup(self):
  297. return True
  298. def render(self, img):
  299. fill_coords(img, point_in_circle(0.5, 0.5, 0.31), COLORS[self.color])
  300. class Box(WorldObj):
  301. def __init__(self, color, contains=None):
  302. super(Box, self).__init__('box', color)
  303. self.contains = contains
  304. def can_pickup(self):
  305. return True
  306. def render(self, r):
  307. c = COLORS[self.color]
  308. r.setLineColor(c[0], c[1], c[2])
  309. r.setColor(0, 0, 0)
  310. r.setLineWidth(2)
  311. r.drawPolygon([
  312. (4 , TILE_PIXELS-4),
  313. (TILE_PIXELS-4, TILE_PIXELS-4),
  314. (TILE_PIXELS-4, 4),
  315. (4 , 4)
  316. ])
  317. r.drawLine(
  318. 4,
  319. TILE_PIXELS / 2,
  320. TILE_PIXELS - 4,
  321. TILE_PIXELS / 2
  322. )
  323. r.setLineWidth(1)
  324. def toggle(self, env, pos):
  325. # Replace the box by its contents
  326. env.grid.set(*pos, self.contains)
  327. return True
  328. class Grid:
  329. """
  330. Represent a grid and operations on it
  331. """
  332. # Static cache of pre-renderer tiles
  333. tile_cache = {}
  334. def __init__(self, width, height):
  335. assert width >= 3
  336. assert height >= 3
  337. self.width = width
  338. self.height = height
  339. self.grid = [None] * width * height
  340. def __contains__(self, key):
  341. if isinstance(key, WorldObj):
  342. for e in self.grid:
  343. if e is key:
  344. return True
  345. elif isinstance(key, tuple):
  346. for e in self.grid:
  347. if e is None:
  348. continue
  349. if (e.color, e.type) == key:
  350. return True
  351. if key[0] is None and key[1] == e.type:
  352. return True
  353. return False
  354. def __eq__(self, other):
  355. grid1 = self.encode()
  356. grid2 = other.encode()
  357. return np.array_equal(grid2, grid1)
  358. def __ne__(self, other):
  359. return not self == other
  360. def copy(self):
  361. from copy import deepcopy
  362. return deepcopy(self)
  363. def set(self, i, j, v):
  364. assert i >= 0 and i < self.width
  365. assert j >= 0 and j < self.height
  366. self.grid[j * self.width + i] = v
  367. def get(self, i, j):
  368. assert i >= 0 and i < self.width
  369. assert j >= 0 and j < self.height
  370. return self.grid[j * self.width + i]
  371. def horz_wall(self, x, y, length=None, obj_type=Wall):
  372. if length is None:
  373. length = self.width - x
  374. for i in range(0, length):
  375. self.set(x + i, y, obj_type())
  376. def vert_wall(self, x, y, length=None, obj_type=Wall):
  377. if length is None:
  378. length = self.height - y
  379. for j in range(0, length):
  380. self.set(x, y + j, obj_type())
  381. def wall_rect(self, x, y, w, h):
  382. self.horz_wall(x, y, w)
  383. self.horz_wall(x, y+h-1, w)
  384. self.vert_wall(x, y, h)
  385. self.vert_wall(x+w-1, y, h)
  386. def rotate_left(self):
  387. """
  388. Rotate the grid to the left (counter-clockwise)
  389. """
  390. grid = Grid(self.height, self.width)
  391. for i in range(self.width):
  392. for j in range(self.height):
  393. v = self.get(i, j)
  394. grid.set(j, grid.height - 1 - i, v)
  395. return grid
  396. def slice(self, topX, topY, width, height):
  397. """
  398. Get a subset of the grid
  399. """
  400. grid = Grid(width, height)
  401. for j in range(0, height):
  402. for i in range(0, width):
  403. x = topX + i
  404. y = topY + j
  405. if x >= 0 and x < self.width and \
  406. y >= 0 and y < self.height:
  407. v = self.get(x, y)
  408. else:
  409. v = Wall()
  410. grid.set(i, j, v)
  411. return grid
  412. @classmethod
  413. def render_tile(
  414. cls,
  415. obj,
  416. agent_dir=None,
  417. highlight=False,
  418. tile_size=TILE_PIXELS
  419. ):
  420. """
  421. Render a tile and cache the result
  422. """
  423. # Hash map lookup key for the cache
  424. key = (agent_dir, highlight, tile_size)
  425. key = obj.encode() + key if obj else key
  426. if key in cls.tile_cache:
  427. return cls.tile_cache[key]
  428. img = np.zeros(shape=(tile_size, tile_size, 3), dtype=np.uint8)
  429. # Draw the grid lines (top and left edges)
  430. fill_coords(img, point_in_rect(0, 0.031, 0, 1), (100, 100, 100))
  431. fill_coords(img, point_in_rect(0, 1, 0, 0.031), (100, 100, 100))
  432. if obj != None:
  433. obj.render(img)
  434. # Overlay the agent on top
  435. if agent_dir is not None:
  436. tri_fn = point_in_triangle(
  437. (0.12, 0.19),
  438. (0.87, 0.50),
  439. (0.12, 0.81),
  440. )
  441. # Rotate the agent based on its direction
  442. tri_fn = rotate_fn(tri_fn, cx=0.5, cy=0.5, theta=0.5*math.pi*agent_dir)
  443. fill_coords(img, tri_fn, (255, 0, 0))
  444. # Highlight the cell if needed
  445. if highlight:
  446. img = highlight_img(img)
  447. # Cache the rendered tile
  448. cls.tile_cache[key] = img
  449. return img
  450. def render(
  451. self,
  452. tile_size,
  453. agent_pos=None,
  454. agent_dir=None,
  455. highlight_mask=None
  456. ):
  457. """
  458. Render this grid at a given scale
  459. :param r: target renderer object
  460. :param tile_size: tile size in pixels
  461. """
  462. if highlight_mask is None:
  463. highlight_mask = np.zeros(shape=(self.width, self.height), dtype=np.bool)
  464. # Compute the total grid size
  465. width_px = self.width * TILE_PIXELS
  466. height_px = self.height * TILE_PIXELS
  467. img = np.zeros(shape=(height_px, width_px, 3), dtype=np.uint8)
  468. # Render the grid
  469. for j in range(0, self.height):
  470. for i in range(0, self.width):
  471. cell = self.get(i, j)
  472. agent_here = np.array_equal(agent_pos, (i, j))
  473. tile_img = Grid.render_tile(
  474. cell,
  475. agent_dir=agent_dir if agent_here else None,
  476. highlight=highlight_mask[i, j],
  477. tile_size=tile_size
  478. )
  479. ymin = j * tile_size
  480. ymax = (j+1) * tile_size
  481. xmin = i * tile_size
  482. xmax = (i+1) * tile_size
  483. img[ymin:ymax, xmin:xmax, :] = tile_img
  484. return img
  485. def encode(self, vis_mask=None):
  486. """
  487. Produce a compact numpy encoding of the grid
  488. """
  489. if vis_mask is None:
  490. vis_mask = np.ones((self.width, self.height), dtype=bool)
  491. array = np.zeros((self.width, self.height, 3), dtype='uint8')
  492. for i in range(self.width):
  493. for j in range(self.height):
  494. if vis_mask[i, j]:
  495. v = self.get(i, j)
  496. if v is None:
  497. array[i, j, 0] = OBJECT_TO_IDX['empty']
  498. array[i, j, 1] = 0
  499. array[i, j, 2] = 0
  500. else:
  501. array[i, j, :] = v.encode()
  502. return array
  503. @staticmethod
  504. def decode(array):
  505. """
  506. Decode an array grid encoding back into a grid
  507. """
  508. width, height, channels = array.shape
  509. assert channels == 3
  510. grid = Grid(width, height)
  511. for i in range(width):
  512. for j in range(height):
  513. type_idx, color_idx, state = array[i, j]
  514. v = WorldObj.decode(type_idx, color_idx, state)
  515. grid.set(i, j, v)
  516. return grid
  517. def process_vis(grid, agent_pos):
  518. mask = np.zeros(shape=(grid.width, grid.height), dtype=np.bool)
  519. mask[agent_pos[0], agent_pos[1]] = True
  520. for j in reversed(range(0, grid.height)):
  521. for i in range(0, grid.width-1):
  522. if not mask[i, j]:
  523. continue
  524. cell = grid.get(i, j)
  525. if cell and not cell.see_behind():
  526. continue
  527. mask[i+1, j] = True
  528. if j > 0:
  529. mask[i+1, j-1] = True
  530. mask[i, j-1] = True
  531. for i in reversed(range(1, grid.width)):
  532. if not mask[i, j]:
  533. continue
  534. cell = grid.get(i, j)
  535. if cell and not cell.see_behind():
  536. continue
  537. mask[i-1, j] = True
  538. if j > 0:
  539. mask[i-1, j-1] = True
  540. mask[i, j-1] = True
  541. for j in range(0, grid.height):
  542. for i in range(0, grid.width):
  543. if not mask[i, j]:
  544. grid.set(i, j, None)
  545. return mask
  546. class MiniGridEnv(gym.Env):
  547. """
  548. 2D grid world game environment
  549. """
  550. metadata = {
  551. 'render.modes': ['human', 'rgb_array', 'pixmap'],
  552. 'video.frames_per_second' : 10
  553. }
  554. # Enumeration of possible actions
  555. class Actions(IntEnum):
  556. # Turn left, turn right, move forward
  557. left = 0
  558. right = 1
  559. forward = 2
  560. # Pick up an object
  561. pickup = 3
  562. # Drop an object
  563. drop = 4
  564. # Toggle/activate an object
  565. toggle = 5
  566. # Done completing task
  567. done = 6
  568. def __init__(
  569. self,
  570. grid_size=None,
  571. width=None,
  572. height=None,
  573. max_steps=100,
  574. see_through_walls=False,
  575. seed=1337,
  576. agent_view_size=7
  577. ):
  578. # Can't set both grid_size and width/height
  579. if grid_size:
  580. assert width == None and height == None
  581. width = grid_size
  582. height = grid_size
  583. # Action enumeration for this environment
  584. self.actions = MiniGridEnv.Actions
  585. # Actions are discrete integer values
  586. self.action_space = spaces.Discrete(len(self.actions))
  587. # Number of cells (width and height) in the agent view
  588. self.agent_view_size = agent_view_size
  589. # Observations are dictionaries containing an
  590. # encoding of the grid and a textual 'mission' string
  591. self.observation_space = spaces.Box(
  592. low=0,
  593. high=255,
  594. shape=(self.agent_view_size, self.agent_view_size, 3),
  595. dtype='uint8'
  596. )
  597. self.observation_space = spaces.Dict({
  598. 'image': self.observation_space
  599. })
  600. # Range of possible rewards
  601. self.reward_range = (0, 1)
  602. # Renderer object used to render the whole grid (full-scale)
  603. self.grid_render = None
  604. # Renderer used to render observations (small-scale agent view)
  605. self.obs_render = None
  606. # Environment configuration
  607. self.width = width
  608. self.height = height
  609. self.max_steps = max_steps
  610. self.see_through_walls = see_through_walls
  611. # Current position and direction of the agent
  612. self.agent_pos = None
  613. self.agent_dir = None
  614. # Initialize the RNG
  615. self.seed(seed=seed)
  616. # Initialize the state
  617. self.reset()
  618. def reset(self):
  619. # Current position and direction of the agent
  620. self.agent_pos = None
  621. self.agent_dir = None
  622. # Generate a new random grid at the start of each episode
  623. # To keep the same grid for each episode, call env.seed() with
  624. # the same seed before calling env.reset()
  625. self._gen_grid(self.width, self.height)
  626. # These fields should be defined by _gen_grid
  627. assert self.agent_pos is not None
  628. assert self.agent_dir is not None
  629. # Check that the agent doesn't overlap with an object
  630. start_cell = self.grid.get(*self.agent_pos)
  631. assert start_cell is None or start_cell.can_overlap()
  632. # Item picked up, being carried, initially nothing
  633. self.carrying = None
  634. # Step count since episode start
  635. self.step_count = 0
  636. # Return first observation
  637. obs = self.gen_obs()
  638. return obs
  639. def seed(self, seed=1337):
  640. # Seed the random number generator
  641. self.np_random, _ = seeding.np_random(seed)
  642. return [seed]
  643. @property
  644. def steps_remaining(self):
  645. return self.max_steps - self.step_count
  646. def __str__(self):
  647. """
  648. Produce a pretty string of the environment's grid along with the agent.
  649. A grid cell is represented by 2-character string, the first one for
  650. the object and the second one for the color.
  651. """
  652. # Map of object types to short string
  653. OBJECT_TO_STR = {
  654. 'wall' : 'W',
  655. 'floor' : 'F',
  656. 'door' : 'D',
  657. 'key' : 'K',
  658. 'ball' : 'A',
  659. 'box' : 'B',
  660. 'goal' : 'G',
  661. 'lava' : 'V',
  662. }
  663. # Short string for opened door
  664. OPENDED_DOOR_IDS = '_'
  665. # Map agent's direction to short string
  666. AGENT_DIR_TO_STR = {
  667. 0: '>',
  668. 1: 'V',
  669. 2: '<',
  670. 3: '^'
  671. }
  672. str = ''
  673. for j in range(self.grid.height):
  674. for i in range(self.grid.width):
  675. if i == self.agent_pos[0] and j == self.agent_pos[1]:
  676. str += 2 * AGENT_DIR_TO_STR[self.agent_dir]
  677. continue
  678. c = self.grid.get(i, j)
  679. if c == None:
  680. str += ' '
  681. continue
  682. if c.type == 'door':
  683. if c.is_open:
  684. str += '__'
  685. elif c.is_locked:
  686. str += 'L' + c.color[0].upper()
  687. else:
  688. str += 'D' + c.color[0].upper()
  689. continue
  690. str += OBJECT_TO_STR[c.type] + c.color[0].upper()
  691. if j < self.grid.height - 1:
  692. str += '\n'
  693. return str
  694. def _gen_grid(self, width, height):
  695. assert False, "_gen_grid needs to be implemented by each environment"
  696. def _reward(self):
  697. """
  698. Compute the reward to be given upon success
  699. """
  700. return 1 - 0.9 * (self.step_count / self.max_steps)
  701. def _rand_int(self, low, high):
  702. """
  703. Generate random integer in [low,high[
  704. """
  705. return self.np_random.randint(low, high)
  706. def _rand_float(self, low, high):
  707. """
  708. Generate random float in [low,high[
  709. """
  710. return self.np_random.uniform(low, high)
  711. def _rand_bool(self):
  712. """
  713. Generate random boolean value
  714. """
  715. return (self.np_random.randint(0, 2) == 0)
  716. def _rand_elem(self, iterable):
  717. """
  718. Pick a random element in a list
  719. """
  720. lst = list(iterable)
  721. idx = self._rand_int(0, len(lst))
  722. return lst[idx]
  723. def _rand_subset(self, iterable, num_elems):
  724. """
  725. Sample a random subset of distinct elements of a list
  726. """
  727. lst = list(iterable)
  728. assert num_elems <= len(lst)
  729. out = []
  730. while len(out) < num_elems:
  731. elem = self._rand_elem(lst)
  732. lst.remove(elem)
  733. out.append(elem)
  734. return out
  735. def _rand_color(self):
  736. """
  737. Generate a random color name (string)
  738. """
  739. return self._rand_elem(COLOR_NAMES)
  740. def _rand_pos(self, xLow, xHigh, yLow, yHigh):
  741. """
  742. Generate a random (x,y) position tuple
  743. """
  744. return (
  745. self.np_random.randint(xLow, xHigh),
  746. self.np_random.randint(yLow, yHigh)
  747. )
  748. def place_obj(self,
  749. obj,
  750. top=None,
  751. size=None,
  752. reject_fn=None,
  753. max_tries=math.inf
  754. ):
  755. """
  756. Place an object at an empty position in the grid
  757. :param top: top-left position of the rectangle where to place
  758. :param size: size of the rectangle where to place
  759. :param reject_fn: function to filter out potential positions
  760. """
  761. if top is None:
  762. top = (0, 0)
  763. else:
  764. top = (max(top[0], 0), max(top[1], 0))
  765. if size is None:
  766. size = (self.grid.width, self.grid.height)
  767. num_tries = 0
  768. while True:
  769. # This is to handle with rare cases where rejection sampling
  770. # gets stuck in an infinite loop
  771. if num_tries > max_tries:
  772. raise RecursionError('rejection sampling failed in place_obj')
  773. num_tries += 1
  774. pos = np.array((
  775. self._rand_int(top[0], min(top[0] + size[0], self.grid.width)),
  776. self._rand_int(top[1], min(top[1] + size[1], self.grid.height))
  777. ))
  778. # Don't place the object on top of another object
  779. if self.grid.get(*pos) != None:
  780. continue
  781. # Don't place the object where the agent is
  782. if np.array_equal(pos, self.agent_pos):
  783. continue
  784. # Check if there is a filtering criterion
  785. if reject_fn and reject_fn(self, pos):
  786. continue
  787. break
  788. self.grid.set(*pos, obj)
  789. if obj is not None:
  790. obj.init_pos = pos
  791. obj.cur_pos = pos
  792. return pos
  793. def put_obj(self, obj, i, j):
  794. """
  795. Put an object at a specific position in the grid
  796. """
  797. self.grid.set(i, j, obj)
  798. obj.init_pos = (i, j)
  799. obj.cur_pos = (i, j)
  800. def place_agent(
  801. self,
  802. top=None,
  803. size=None,
  804. rand_dir=True,
  805. max_tries=math.inf
  806. ):
  807. """
  808. Set the agent's starting point at an empty position in the grid
  809. """
  810. self.agent_pos = None
  811. pos = self.place_obj(None, top, size, max_tries=max_tries)
  812. self.agent_pos = pos
  813. if rand_dir:
  814. self.agent_dir = self._rand_int(0, 4)
  815. return pos
  816. @property
  817. def dir_vec(self):
  818. """
  819. Get the direction vector for the agent, pointing in the direction
  820. of forward movement.
  821. """
  822. assert self.agent_dir >= 0 and self.agent_dir < 4
  823. return DIR_TO_VEC[self.agent_dir]
  824. @property
  825. def right_vec(self):
  826. """
  827. Get the vector pointing to the right of the agent.
  828. """
  829. dx, dy = self.dir_vec
  830. return np.array((-dy, dx))
  831. @property
  832. def front_pos(self):
  833. """
  834. Get the position of the cell that is right in front of the agent
  835. """
  836. return self.agent_pos + self.dir_vec
  837. def get_view_coords(self, i, j):
  838. """
  839. Translate and rotate absolute grid coordinates (i, j) into the
  840. agent's partially observable view (sub-grid). Note that the resulting
  841. coordinates may be negative or outside of the agent's view size.
  842. """
  843. ax, ay = self.agent_pos
  844. dx, dy = self.dir_vec
  845. rx, ry = self.right_vec
  846. # Compute the absolute coordinates of the top-left view corner
  847. sz = self.agent_view_size
  848. hs = self.agent_view_size // 2
  849. tx = ax + (dx * (sz-1)) - (rx * hs)
  850. ty = ay + (dy * (sz-1)) - (ry * hs)
  851. lx = i - tx
  852. ly = j - ty
  853. # Project the coordinates of the object relative to the top-left
  854. # corner onto the agent's own coordinate system
  855. vx = (rx*lx + ry*ly)
  856. vy = -(dx*lx + dy*ly)
  857. return vx, vy
  858. def get_view_exts(self):
  859. """
  860. Get the extents of the square set of tiles visible to the agent
  861. Note: the bottom extent indices are not included in the set
  862. """
  863. # Facing right
  864. if self.agent_dir == 0:
  865. topX = self.agent_pos[0]
  866. topY = self.agent_pos[1] - self.agent_view_size // 2
  867. # Facing down
  868. elif self.agent_dir == 1:
  869. topX = self.agent_pos[0] - self.agent_view_size // 2
  870. topY = self.agent_pos[1]
  871. # Facing left
  872. elif self.agent_dir == 2:
  873. topX = self.agent_pos[0] - self.agent_view_size + 1
  874. topY = self.agent_pos[1] - self.agent_view_size // 2
  875. # Facing up
  876. elif self.agent_dir == 3:
  877. topX = self.agent_pos[0] - self.agent_view_size // 2
  878. topY = self.agent_pos[1] - self.agent_view_size + 1
  879. else:
  880. assert False, "invalid agent direction"
  881. botX = topX + self.agent_view_size
  882. botY = topY + self.agent_view_size
  883. return (topX, topY, botX, botY)
  884. def relative_coords(self, x, y):
  885. """
  886. Check if a grid position belongs to the agent's field of view, and returns the corresponding coordinates
  887. """
  888. vx, vy = self.get_view_coords(x, y)
  889. if vx < 0 or vy < 0 or vx >= self.agent_view_size or vy >= self.agent_view_size:
  890. return None
  891. return vx, vy
  892. def in_view(self, x, y):
  893. """
  894. check if a grid position is visible to the agent
  895. """
  896. return self.relative_coords(x, y) is not None
  897. def agent_sees(self, x, y):
  898. """
  899. Check if a non-empty grid position is visible to the agent
  900. """
  901. coordinates = self.relative_coords(x, y)
  902. if coordinates is None:
  903. return False
  904. vx, vy = coordinates
  905. obs = self.gen_obs()
  906. obs_grid = Grid.decode(obs['image'])
  907. obs_cell = obs_grid.get(vx, vy)
  908. world_cell = self.grid.get(x, y)
  909. return obs_cell is not None and obs_cell.type == world_cell.type
  910. def step(self, action):
  911. self.step_count += 1
  912. reward = 0
  913. done = False
  914. # Get the position in front of the agent
  915. fwd_pos = self.front_pos
  916. # Get the contents of the cell in front of the agent
  917. fwd_cell = self.grid.get(*fwd_pos)
  918. # Rotate left
  919. if action == self.actions.left:
  920. self.agent_dir -= 1
  921. if self.agent_dir < 0:
  922. self.agent_dir += 4
  923. # Rotate right
  924. elif action == self.actions.right:
  925. self.agent_dir = (self.agent_dir + 1) % 4
  926. # Move forward
  927. elif action == self.actions.forward:
  928. if fwd_cell == None or fwd_cell.can_overlap():
  929. self.agent_pos = fwd_pos
  930. if fwd_cell != None and fwd_cell.type == 'goal':
  931. done = True
  932. reward = self._reward()
  933. if fwd_cell != None and fwd_cell.type == 'lava':
  934. done = True
  935. # Pick up an object
  936. elif action == self.actions.pickup:
  937. if fwd_cell and fwd_cell.can_pickup():
  938. if self.carrying is None:
  939. self.carrying = fwd_cell
  940. self.carrying.cur_pos = np.array([-1, -1])
  941. self.grid.set(*fwd_pos, None)
  942. # Drop an object
  943. elif action == self.actions.drop:
  944. if not fwd_cell and self.carrying:
  945. self.grid.set(*fwd_pos, self.carrying)
  946. self.carrying.cur_pos = fwd_pos
  947. self.carrying = None
  948. # Toggle/activate an object
  949. elif action == self.actions.toggle:
  950. if fwd_cell:
  951. fwd_cell.toggle(self, fwd_pos)
  952. # Done action (not used by default)
  953. elif action == self.actions.done:
  954. pass
  955. else:
  956. assert False, "unknown action"
  957. if self.step_count >= self.max_steps:
  958. done = True
  959. obs = self.gen_obs()
  960. return obs, reward, done, {}
  961. def gen_obs_grid(self):
  962. """
  963. Generate the sub-grid observed by the agent.
  964. This method also outputs a visibility mask telling us which grid
  965. cells the agent can actually see.
  966. """
  967. topX, topY, botX, botY = self.get_view_exts()
  968. grid = self.grid.slice(topX, topY, self.agent_view_size, self.agent_view_size)
  969. for i in range(self.agent_dir + 1):
  970. grid = grid.rotate_left()
  971. # Process occluders and visibility
  972. # Note that this incurs some performance cost
  973. if not self.see_through_walls:
  974. vis_mask = grid.process_vis(agent_pos=(self.agent_view_size // 2 , self.agent_view_size - 1))
  975. else:
  976. vis_mask = np.ones(shape=(grid.width, grid.height), dtype=np.bool)
  977. # Make it so the agent sees what it's carrying
  978. # We do this by placing the carried object at the agent's position
  979. # in the agent's partially observable view
  980. agent_pos = grid.width // 2, grid.height - 1
  981. if self.carrying:
  982. grid.set(*agent_pos, self.carrying)
  983. else:
  984. grid.set(*agent_pos, None)
  985. return grid, vis_mask
  986. def gen_obs(self):
  987. """
  988. Generate the agent's view (partially observable, low-resolution encoding)
  989. """
  990. grid, vis_mask = self.gen_obs_grid()
  991. # Encode the partially observable view into a numpy array
  992. image = grid.encode(vis_mask)
  993. assert hasattr(self, 'mission'), "environments must define a textual mission string"
  994. # Observations are dictionaries containing:
  995. # - an image (partially observable view of the environment)
  996. # - the agent's direction/orientation (acting as a compass)
  997. # - a textual mission string (instructions for the agent)
  998. obs = {
  999. 'image': image,
  1000. 'direction': self.agent_dir,
  1001. 'mission': self.mission
  1002. }
  1003. return obs
  1004. def get_obs_render(self, obs, tile_size=TILE_PIXELS//2):
  1005. """
  1006. Render an agent observation for visualization
  1007. """
  1008. grid = Grid.decode(obs)
  1009. # Render the whole grid
  1010. img = grid.render(r, tile_size)
  1011. assert False
  1012. """
  1013. # Draw the agent
  1014. ratio = tile_size / TILE_PIXELS
  1015. r.push()
  1016. r.scale(ratio, ratio)
  1017. r.translate(
  1018. TILE_PIXELS * (0.5 + self.agent_view_size // 2),
  1019. TILE_PIXELS * (self.agent_view_size - 0.5)
  1020. )
  1021. r.rotate(3 * 90)
  1022. r.setLineColor(255, 0, 0)
  1023. r.setColor(255, 0, 0)
  1024. r.drawPolygon([
  1025. (-12, 10),
  1026. ( 12, 0),
  1027. (-12, -10)
  1028. ])
  1029. r.pop()
  1030. """
  1031. return img
  1032. def render(self, mode='human', close=False, highlight=True, tile_size=TILE_PIXELS):
  1033. """
  1034. Render the whole-grid human view
  1035. """
  1036. """
  1037. if close:
  1038. if self.grid_render:
  1039. self.grid_render.close()
  1040. return
  1041. """
  1042. # Compute which cells are visible to the agent
  1043. _, vis_mask = self.gen_obs_grid()
  1044. # Compute the world coordinates of the bottom-left corner
  1045. # of the agent's view area
  1046. f_vec = self.dir_vec
  1047. r_vec = self.right_vec
  1048. top_left = self.agent_pos + f_vec * (self.agent_view_size-1) - r_vec * (self.agent_view_size // 2)
  1049. # Mask of which cells to highlight
  1050. highlight_mask = np.zeros(shape=(self.width, self.height), dtype=np.bool)
  1051. # For each cell in the visibility mask
  1052. for vis_j in range(0, self.agent_view_size):
  1053. for vis_i in range(0, self.agent_view_size):
  1054. # If this cell is not visible, don't highlight it
  1055. if not vis_mask[vis_i, vis_j]:
  1056. continue
  1057. # Compute the world coordinates of this cell
  1058. abs_i, abs_j = top_left - (f_vec * vis_j) + (r_vec * vis_i)
  1059. if abs_i < 0 or abs_i >= self.width:
  1060. continue
  1061. if abs_j < 0 or abs_j >= self.height:
  1062. continue
  1063. # Mark this cell to be highlighted
  1064. highlight_mask[abs_i, abs_j] = True
  1065. # Render the whole grid
  1066. img = self.grid.render(
  1067. tile_size,
  1068. self.agent_pos,
  1069. self.agent_dir,
  1070. highlight_mask=highlight_mask if highlight else None
  1071. )
  1072. return img