minigrid.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  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. # TODO: overlay 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. tri_fn = rotate_fn(tri_fn, cx=0.5, cy=0.5, theta=0.5*math.pi*agent_dir)
  442. fill_coords(img, tri_fn, (255, 0, 0))
  443. # TODO: highlighting
  444. if highlight:
  445. pass
  446. # Cache the rendered tile
  447. cls.tile_cache[key] = img
  448. return img
  449. def render(
  450. self,
  451. tile_size,
  452. agent_pos=None,
  453. agent_dir=None
  454. ):
  455. """
  456. Render this grid at a given scale
  457. :param r: target renderer object
  458. :param tile_size: tile size in pixels
  459. """
  460. # Compute the total grid size
  461. width_px = self.width * TILE_PIXELS
  462. height_px = self.height * TILE_PIXELS
  463. img = np.zeros(shape=(height_px, width_px, 3), dtype=np.uint8)
  464. # Render the grid
  465. for j in range(0, self.height):
  466. for i in range(0, self.width):
  467. cell = self.get(i, j)
  468. tile_img = Grid.render_tile(
  469. cell,
  470. agent_dir=agent_dir if np.array_equal(agent_pos, (i, j)) else None,
  471. highlight=False,
  472. tile_size=tile_size
  473. )
  474. ymin = j * tile_size
  475. ymax = (j+1) * tile_size
  476. xmin = i * tile_size
  477. xmax = (i+1) * tile_size
  478. img[ymin:ymax, xmin:xmax, :] = tile_img
  479. return img
  480. def encode(self, vis_mask=None):
  481. """
  482. Produce a compact numpy encoding of the grid
  483. """
  484. if vis_mask is None:
  485. vis_mask = np.ones((self.width, self.height), dtype=bool)
  486. array = np.zeros((self.width, self.height, 3), dtype='uint8')
  487. for i in range(self.width):
  488. for j in range(self.height):
  489. if vis_mask[i, j]:
  490. v = self.get(i, j)
  491. if v is None:
  492. array[i, j, 0] = OBJECT_TO_IDX['empty']
  493. array[i, j, 1] = 0
  494. array[i, j, 2] = 0
  495. else:
  496. array[i, j, :] = v.encode()
  497. return array
  498. @staticmethod
  499. def decode(array):
  500. """
  501. Decode an array grid encoding back into a grid
  502. """
  503. width, height, channels = array.shape
  504. assert channels == 3
  505. grid = Grid(width, height)
  506. for i in range(width):
  507. for j in range(height):
  508. type_idx, color_idx, state = array[i, j]
  509. v = WorldObj.decode(type_idx, color_idx, state)
  510. grid.set(i, j, v)
  511. return grid
  512. def process_vis(grid, agent_pos):
  513. mask = np.zeros(shape=(grid.width, grid.height), dtype=np.bool)
  514. mask[agent_pos[0], agent_pos[1]] = True
  515. for j in reversed(range(0, grid.height)):
  516. for i in range(0, grid.width-1):
  517. if not mask[i, j]:
  518. continue
  519. cell = grid.get(i, j)
  520. if cell and not cell.see_behind():
  521. continue
  522. mask[i+1, j] = True
  523. if j > 0:
  524. mask[i+1, j-1] = True
  525. mask[i, j-1] = True
  526. for i in reversed(range(1, grid.width)):
  527. if not mask[i, j]:
  528. continue
  529. cell = grid.get(i, j)
  530. if cell and not cell.see_behind():
  531. continue
  532. mask[i-1, j] = True
  533. if j > 0:
  534. mask[i-1, j-1] = True
  535. mask[i, j-1] = True
  536. for j in range(0, grid.height):
  537. for i in range(0, grid.width):
  538. if not mask[i, j]:
  539. grid.set(i, j, None)
  540. return mask
  541. class MiniGridEnv(gym.Env):
  542. """
  543. 2D grid world game environment
  544. """
  545. metadata = {
  546. 'render.modes': ['human', 'rgb_array', 'pixmap'],
  547. 'video.frames_per_second' : 10
  548. }
  549. # Enumeration of possible actions
  550. class Actions(IntEnum):
  551. # Turn left, turn right, move forward
  552. left = 0
  553. right = 1
  554. forward = 2
  555. # Pick up an object
  556. pickup = 3
  557. # Drop an object
  558. drop = 4
  559. # Toggle/activate an object
  560. toggle = 5
  561. # Done completing task
  562. done = 6
  563. def __init__(
  564. self,
  565. grid_size=None,
  566. width=None,
  567. height=None,
  568. max_steps=100,
  569. see_through_walls=False,
  570. seed=1337,
  571. agent_view_size=7
  572. ):
  573. # Can't set both grid_size and width/height
  574. if grid_size:
  575. assert width == None and height == None
  576. width = grid_size
  577. height = grid_size
  578. # Action enumeration for this environment
  579. self.actions = MiniGridEnv.Actions
  580. # Actions are discrete integer values
  581. self.action_space = spaces.Discrete(len(self.actions))
  582. # Number of cells (width and height) in the agent view
  583. self.agent_view_size = agent_view_size
  584. # Observations are dictionaries containing an
  585. # encoding of the grid and a textual 'mission' string
  586. self.observation_space = spaces.Box(
  587. low=0,
  588. high=255,
  589. shape=(self.agent_view_size, self.agent_view_size, 3),
  590. dtype='uint8'
  591. )
  592. self.observation_space = spaces.Dict({
  593. 'image': self.observation_space
  594. })
  595. # Range of possible rewards
  596. self.reward_range = (0, 1)
  597. # Renderer object used to render the whole grid (full-scale)
  598. self.grid_render = None
  599. # Renderer used to render observations (small-scale agent view)
  600. self.obs_render = None
  601. # Environment configuration
  602. self.width = width
  603. self.height = height
  604. self.max_steps = max_steps
  605. self.see_through_walls = see_through_walls
  606. # Current position and direction of the agent
  607. self.agent_pos = None
  608. self.agent_dir = None
  609. # Initialize the RNG
  610. self.seed(seed=seed)
  611. # Initialize the state
  612. self.reset()
  613. def reset(self):
  614. # Current position and direction of the agent
  615. self.agent_pos = None
  616. self.agent_dir = None
  617. # Generate a new random grid at the start of each episode
  618. # To keep the same grid for each episode, call env.seed() with
  619. # the same seed before calling env.reset()
  620. self._gen_grid(self.width, self.height)
  621. # These fields should be defined by _gen_grid
  622. assert self.agent_pos is not None
  623. assert self.agent_dir is not None
  624. # Check that the agent doesn't overlap with an object
  625. start_cell = self.grid.get(*self.agent_pos)
  626. assert start_cell is None or start_cell.can_overlap()
  627. # Item picked up, being carried, initially nothing
  628. self.carrying = None
  629. # Step count since episode start
  630. self.step_count = 0
  631. # Return first observation
  632. obs = self.gen_obs()
  633. return obs
  634. def seed(self, seed=1337):
  635. # Seed the random number generator
  636. self.np_random, _ = seeding.np_random(seed)
  637. return [seed]
  638. @property
  639. def steps_remaining(self):
  640. return self.max_steps - self.step_count
  641. def __str__(self):
  642. """
  643. Produce a pretty string of the environment's grid along with the agent.
  644. A grid cell is represented by 2-character string, the first one for
  645. the object and the second one for the color.
  646. """
  647. # Map of object types to short string
  648. OBJECT_TO_STR = {
  649. 'wall' : 'W',
  650. 'floor' : 'F',
  651. 'door' : 'D',
  652. 'key' : 'K',
  653. 'ball' : 'A',
  654. 'box' : 'B',
  655. 'goal' : 'G',
  656. 'lava' : 'V',
  657. }
  658. # Short string for opened door
  659. OPENDED_DOOR_IDS = '_'
  660. # Map agent's direction to short string
  661. AGENT_DIR_TO_STR = {
  662. 0: '>',
  663. 1: 'V',
  664. 2: '<',
  665. 3: '^'
  666. }
  667. str = ''
  668. for j in range(self.grid.height):
  669. for i in range(self.grid.width):
  670. if i == self.agent_pos[0] and j == self.agent_pos[1]:
  671. str += 2 * AGENT_DIR_TO_STR[self.agent_dir]
  672. continue
  673. c = self.grid.get(i, j)
  674. if c == None:
  675. str += ' '
  676. continue
  677. if c.type == 'door':
  678. if c.is_open:
  679. str += '__'
  680. elif c.is_locked:
  681. str += 'L' + c.color[0].upper()
  682. else:
  683. str += 'D' + c.color[0].upper()
  684. continue
  685. str += OBJECT_TO_STR[c.type] + c.color[0].upper()
  686. if j < self.grid.height - 1:
  687. str += '\n'
  688. return str
  689. def _gen_grid(self, width, height):
  690. assert False, "_gen_grid needs to be implemented by each environment"
  691. def _reward(self):
  692. """
  693. Compute the reward to be given upon success
  694. """
  695. return 1 - 0.9 * (self.step_count / self.max_steps)
  696. def _rand_int(self, low, high):
  697. """
  698. Generate random integer in [low,high[
  699. """
  700. return self.np_random.randint(low, high)
  701. def _rand_float(self, low, high):
  702. """
  703. Generate random float in [low,high[
  704. """
  705. return self.np_random.uniform(low, high)
  706. def _rand_bool(self):
  707. """
  708. Generate random boolean value
  709. """
  710. return (self.np_random.randint(0, 2) == 0)
  711. def _rand_elem(self, iterable):
  712. """
  713. Pick a random element in a list
  714. """
  715. lst = list(iterable)
  716. idx = self._rand_int(0, len(lst))
  717. return lst[idx]
  718. def _rand_subset(self, iterable, num_elems):
  719. """
  720. Sample a random subset of distinct elements of a list
  721. """
  722. lst = list(iterable)
  723. assert num_elems <= len(lst)
  724. out = []
  725. while len(out) < num_elems:
  726. elem = self._rand_elem(lst)
  727. lst.remove(elem)
  728. out.append(elem)
  729. return out
  730. def _rand_color(self):
  731. """
  732. Generate a random color name (string)
  733. """
  734. return self._rand_elem(COLOR_NAMES)
  735. def _rand_pos(self, xLow, xHigh, yLow, yHigh):
  736. """
  737. Generate a random (x,y) position tuple
  738. """
  739. return (
  740. self.np_random.randint(xLow, xHigh),
  741. self.np_random.randint(yLow, yHigh)
  742. )
  743. def place_obj(self,
  744. obj,
  745. top=None,
  746. size=None,
  747. reject_fn=None,
  748. max_tries=math.inf
  749. ):
  750. """
  751. Place an object at an empty position in the grid
  752. :param top: top-left position of the rectangle where to place
  753. :param size: size of the rectangle where to place
  754. :param reject_fn: function to filter out potential positions
  755. """
  756. if top is None:
  757. top = (0, 0)
  758. else:
  759. top = (max(top[0], 0), max(top[1], 0))
  760. if size is None:
  761. size = (self.grid.width, self.grid.height)
  762. num_tries = 0
  763. while True:
  764. # This is to handle with rare cases where rejection sampling
  765. # gets stuck in an infinite loop
  766. if num_tries > max_tries:
  767. raise RecursionError('rejection sampling failed in place_obj')
  768. num_tries += 1
  769. pos = np.array((
  770. self._rand_int(top[0], min(top[0] + size[0], self.grid.width)),
  771. self._rand_int(top[1], min(top[1] + size[1], self.grid.height))
  772. ))
  773. # Don't place the object on top of another object
  774. if self.grid.get(*pos) != None:
  775. continue
  776. # Don't place the object where the agent is
  777. if np.array_equal(pos, self.agent_pos):
  778. continue
  779. # Check if there is a filtering criterion
  780. if reject_fn and reject_fn(self, pos):
  781. continue
  782. break
  783. self.grid.set(*pos, obj)
  784. if obj is not None:
  785. obj.init_pos = pos
  786. obj.cur_pos = pos
  787. return pos
  788. def put_obj(self, obj, i, j):
  789. """
  790. Put an object at a specific position in the grid
  791. """
  792. self.grid.set(i, j, obj)
  793. obj.init_pos = (i, j)
  794. obj.cur_pos = (i, j)
  795. def place_agent(
  796. self,
  797. top=None,
  798. size=None,
  799. rand_dir=True,
  800. max_tries=math.inf
  801. ):
  802. """
  803. Set the agent's starting point at an empty position in the grid
  804. """
  805. self.agent_pos = None
  806. pos = self.place_obj(None, top, size, max_tries=max_tries)
  807. self.agent_pos = pos
  808. if rand_dir:
  809. self.agent_dir = self._rand_int(0, 4)
  810. return pos
  811. @property
  812. def dir_vec(self):
  813. """
  814. Get the direction vector for the agent, pointing in the direction
  815. of forward movement.
  816. """
  817. assert self.agent_dir >= 0 and self.agent_dir < 4
  818. return DIR_TO_VEC[self.agent_dir]
  819. @property
  820. def right_vec(self):
  821. """
  822. Get the vector pointing to the right of the agent.
  823. """
  824. dx, dy = self.dir_vec
  825. return np.array((-dy, dx))
  826. @property
  827. def front_pos(self):
  828. """
  829. Get the position of the cell that is right in front of the agent
  830. """
  831. return self.agent_pos + self.dir_vec
  832. def get_view_coords(self, i, j):
  833. """
  834. Translate and rotate absolute grid coordinates (i, j) into the
  835. agent's partially observable view (sub-grid). Note that the resulting
  836. coordinates may be negative or outside of the agent's view size.
  837. """
  838. ax, ay = self.agent_pos
  839. dx, dy = self.dir_vec
  840. rx, ry = self.right_vec
  841. # Compute the absolute coordinates of the top-left view corner
  842. sz = self.agent_view_size
  843. hs = self.agent_view_size // 2
  844. tx = ax + (dx * (sz-1)) - (rx * hs)
  845. ty = ay + (dy * (sz-1)) - (ry * hs)
  846. lx = i - tx
  847. ly = j - ty
  848. # Project the coordinates of the object relative to the top-left
  849. # corner onto the agent's own coordinate system
  850. vx = (rx*lx + ry*ly)
  851. vy = -(dx*lx + dy*ly)
  852. return vx, vy
  853. def get_view_exts(self):
  854. """
  855. Get the extents of the square set of tiles visible to the agent
  856. Note: the bottom extent indices are not included in the set
  857. """
  858. # Facing right
  859. if self.agent_dir == 0:
  860. topX = self.agent_pos[0]
  861. topY = self.agent_pos[1] - self.agent_view_size // 2
  862. # Facing down
  863. elif self.agent_dir == 1:
  864. topX = self.agent_pos[0] - self.agent_view_size // 2
  865. topY = self.agent_pos[1]
  866. # Facing left
  867. elif self.agent_dir == 2:
  868. topX = self.agent_pos[0] - self.agent_view_size + 1
  869. topY = self.agent_pos[1] - self.agent_view_size // 2
  870. # Facing up
  871. elif self.agent_dir == 3:
  872. topX = self.agent_pos[0] - self.agent_view_size // 2
  873. topY = self.agent_pos[1] - self.agent_view_size + 1
  874. else:
  875. assert False, "invalid agent direction"
  876. botX = topX + self.agent_view_size
  877. botY = topY + self.agent_view_size
  878. return (topX, topY, botX, botY)
  879. def relative_coords(self, x, y):
  880. """
  881. Check if a grid position belongs to the agent's field of view, and returns the corresponding coordinates
  882. """
  883. vx, vy = self.get_view_coords(x, y)
  884. if vx < 0 or vy < 0 or vx >= self.agent_view_size or vy >= self.agent_view_size:
  885. return None
  886. return vx, vy
  887. def in_view(self, x, y):
  888. """
  889. check if a grid position is visible to the agent
  890. """
  891. return self.relative_coords(x, y) is not None
  892. def agent_sees(self, x, y):
  893. """
  894. Check if a non-empty grid position is visible to the agent
  895. """
  896. coordinates = self.relative_coords(x, y)
  897. if coordinates is None:
  898. return False
  899. vx, vy = coordinates
  900. obs = self.gen_obs()
  901. obs_grid = Grid.decode(obs['image'])
  902. obs_cell = obs_grid.get(vx, vy)
  903. world_cell = self.grid.get(x, y)
  904. return obs_cell is not None and obs_cell.type == world_cell.type
  905. def step(self, action):
  906. self.step_count += 1
  907. reward = 0
  908. done = False
  909. # Get the position in front of the agent
  910. fwd_pos = self.front_pos
  911. # Get the contents of the cell in front of the agent
  912. fwd_cell = self.grid.get(*fwd_pos)
  913. # Rotate left
  914. if action == self.actions.left:
  915. self.agent_dir -= 1
  916. if self.agent_dir < 0:
  917. self.agent_dir += 4
  918. # Rotate right
  919. elif action == self.actions.right:
  920. self.agent_dir = (self.agent_dir + 1) % 4
  921. # Move forward
  922. elif action == self.actions.forward:
  923. if fwd_cell == None or fwd_cell.can_overlap():
  924. self.agent_pos = fwd_pos
  925. if fwd_cell != None and fwd_cell.type == 'goal':
  926. done = True
  927. reward = self._reward()
  928. if fwd_cell != None and fwd_cell.type == 'lava':
  929. done = True
  930. # Pick up an object
  931. elif action == self.actions.pickup:
  932. if fwd_cell and fwd_cell.can_pickup():
  933. if self.carrying is None:
  934. self.carrying = fwd_cell
  935. self.carrying.cur_pos = np.array([-1, -1])
  936. self.grid.set(*fwd_pos, None)
  937. # Drop an object
  938. elif action == self.actions.drop:
  939. if not fwd_cell and self.carrying:
  940. self.grid.set(*fwd_pos, self.carrying)
  941. self.carrying.cur_pos = fwd_pos
  942. self.carrying = None
  943. # Toggle/activate an object
  944. elif action == self.actions.toggle:
  945. if fwd_cell:
  946. fwd_cell.toggle(self, fwd_pos)
  947. # Done action (not used by default)
  948. elif action == self.actions.done:
  949. pass
  950. else:
  951. assert False, "unknown action"
  952. if self.step_count >= self.max_steps:
  953. done = True
  954. obs = self.gen_obs()
  955. return obs, reward, done, {}
  956. def gen_obs_grid(self):
  957. """
  958. Generate the sub-grid observed by the agent.
  959. This method also outputs a visibility mask telling us which grid
  960. cells the agent can actually see.
  961. """
  962. topX, topY, botX, botY = self.get_view_exts()
  963. grid = self.grid.slice(topX, topY, self.agent_view_size, self.agent_view_size)
  964. for i in range(self.agent_dir + 1):
  965. grid = grid.rotate_left()
  966. # Process occluders and visibility
  967. # Note that this incurs some performance cost
  968. if not self.see_through_walls:
  969. vis_mask = grid.process_vis(agent_pos=(self.agent_view_size // 2 , self.agent_view_size - 1))
  970. else:
  971. vis_mask = np.ones(shape=(grid.width, grid.height), dtype=np.bool)
  972. # Make it so the agent sees what it's carrying
  973. # We do this by placing the carried object at the agent's position
  974. # in the agent's partially observable view
  975. agent_pos = grid.width // 2, grid.height - 1
  976. if self.carrying:
  977. grid.set(*agent_pos, self.carrying)
  978. else:
  979. grid.set(*agent_pos, None)
  980. return grid, vis_mask
  981. def gen_obs(self):
  982. """
  983. Generate the agent's view (partially observable, low-resolution encoding)
  984. """
  985. grid, vis_mask = self.gen_obs_grid()
  986. # Encode the partially observable view into a numpy array
  987. image = grid.encode(vis_mask)
  988. assert hasattr(self, 'mission'), "environments must define a textual mission string"
  989. # Observations are dictionaries containing:
  990. # - an image (partially observable view of the environment)
  991. # - the agent's direction/orientation (acting as a compass)
  992. # - a textual mission string (instructions for the agent)
  993. obs = {
  994. 'image': image,
  995. 'direction': self.agent_dir,
  996. 'mission': self.mission
  997. }
  998. return obs
  999. def get_obs_render(self, obs, tile_size=TILE_PIXELS//2, mode='pixmap'):
  1000. """
  1001. Render an agent observation for visualization
  1002. """
  1003. grid = Grid.decode(obs)
  1004. # Render the whole grid
  1005. img = grid.render(r, tile_size)
  1006. """
  1007. # Draw the agent
  1008. ratio = tile_size / TILE_PIXELS
  1009. r.push()
  1010. r.scale(ratio, ratio)
  1011. r.translate(
  1012. TILE_PIXELS * (0.5 + self.agent_view_size // 2),
  1013. TILE_PIXELS * (self.agent_view_size - 0.5)
  1014. )
  1015. r.rotate(3 * 90)
  1016. r.setLineColor(255, 0, 0)
  1017. r.setColor(255, 0, 0)
  1018. r.drawPolygon([
  1019. (-12, 10),
  1020. ( 12, 0),
  1021. (-12, -10)
  1022. ])
  1023. r.pop()
  1024. if mode == 'rgb_array':
  1025. return r.getArray()
  1026. elif mode == 'pixmap':
  1027. return r.getPixmap()
  1028. return r
  1029. """
  1030. def render(self, mode='human', close=False, highlight=True, tile_size=TILE_PIXELS):
  1031. """
  1032. Render the whole-grid human view
  1033. """
  1034. """
  1035. if close:
  1036. if self.grid_render:
  1037. self.grid_render.close()
  1038. return
  1039. """
  1040. # Render the whole grid
  1041. img = self.grid.render(
  1042. tile_size,
  1043. self.agent_pos,
  1044. self.agent_dir
  1045. )
  1046. """
  1047. # Compute which cells are visible to the agent
  1048. _, vis_mask = self.gen_obs_grid()
  1049. # Compute the absolute coordinates of the bottom-left corner
  1050. # of the agent's view area
  1051. f_vec = self.dir_vec
  1052. r_vec = self.right_vec
  1053. top_left = self.agent_pos + f_vec * (self.agent_view_size-1) - r_vec * (self.agent_view_size // 2)
  1054. # For each cell in the visibility mask
  1055. if highlight:
  1056. for vis_j in range(0, self.agent_view_size):
  1057. for vis_i in range(0, self.agent_view_size):
  1058. # If this cell is not visible, don't highlight it
  1059. if not vis_mask[vis_i, vis_j]:
  1060. continue
  1061. # Compute the world coordinates of this cell
  1062. abs_i, abs_j = top_left - (f_vec * vis_j) + (r_vec * vis_i)
  1063. # Highlight the cell
  1064. r.fillRect(
  1065. abs_i * tile_size,
  1066. abs_j * tile_size,
  1067. tile_size,
  1068. tile_size,
  1069. 255, 255, 255, 75
  1070. )
  1071. """
  1072. """
  1073. if mode == 'rgb_array':
  1074. return r.getArray()
  1075. elif mode == 'pixmap':
  1076. return r.getPixmap()
  1077. """
  1078. return img