minigrid.py 37 KB

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