minigrid.py 37 KB

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