minigrid.py 35 KB

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