minigrid.py 36 KB

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