roomgrid.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import numpy as np
  2. from minigrid.core.constants import COLOR_NAMES
  3. from minigrid.core.grid import Grid
  4. from minigrid.core.world_object import Ball, Box, Door, Key
  5. from minigrid.minigrid import MiniGridEnv
  6. def reject_next_to(env, pos):
  7. """
  8. Function to filter out object positions that are right next to
  9. the agent's starting point
  10. """
  11. sx, sy = env.agent_pos
  12. x, y = pos
  13. d = abs(sx - x) + abs(sy - y)
  14. return d < 2
  15. class Room:
  16. def __init__(self, top, size):
  17. # Top-left corner and size (tuples)
  18. self.top = top
  19. self.size = size
  20. # List of door objects and door positions
  21. # Order of the doors is right, down, left, up
  22. self.doors = [None] * 4
  23. self.door_pos = [None] * 4
  24. # List of rooms adjacent to this one
  25. # Order of the neighbors is right, down, left, up
  26. self.neighbors = [None] * 4
  27. # Indicates if this room is behind a locked door
  28. self.locked = False
  29. # List of objects contained
  30. self.objs = []
  31. def rand_pos(self, env):
  32. topX, topY = self.top
  33. sizeX, sizeY = self.size
  34. return env._randPos(topX + 1, topX + sizeX - 1, topY + 1, topY + sizeY - 1)
  35. def pos_inside(self, x, y):
  36. """
  37. Check if a position is within the bounds of this room
  38. """
  39. topX, topY = self.top
  40. sizeX, sizeY = self.size
  41. if x < topX or y < topY:
  42. return False
  43. if x >= topX + sizeX or y >= topY + sizeY:
  44. return False
  45. return True
  46. class RoomGrid(MiniGridEnv):
  47. """
  48. Environment with multiple rooms and random objects.
  49. This is meant to serve as a base class for other environments.
  50. """
  51. def __init__(
  52. self,
  53. room_size=7,
  54. num_rows=3,
  55. num_cols=3,
  56. max_steps=100,
  57. agent_view_size=7,
  58. **kwargs,
  59. ):
  60. assert room_size > 0
  61. assert room_size >= 3
  62. assert num_rows > 0
  63. assert num_cols > 0
  64. self.room_size = room_size
  65. self.num_rows = num_rows
  66. self.num_cols = num_cols
  67. height = (room_size - 1) * num_rows + 1
  68. width = (room_size - 1) * num_cols + 1
  69. # By default, this environment has no mission
  70. self.mission = ""
  71. super().__init__(
  72. width=width,
  73. height=height,
  74. max_steps=max_steps,
  75. see_through_walls=False,
  76. agent_view_size=agent_view_size,
  77. **kwargs,
  78. )
  79. def room_from_pos(self, x, y):
  80. """Get the room a given position maps to"""
  81. assert x >= 0
  82. assert y >= 0
  83. i = x // (self.room_size - 1)
  84. j = y // (self.room_size - 1)
  85. assert i < self.num_cols
  86. assert j < self.num_rows
  87. return self.room_grid[j][i]
  88. def get_room(self, i, j):
  89. assert i < self.num_cols
  90. assert j < self.num_rows
  91. return self.room_grid[j][i]
  92. def _gen_grid(self, width, height):
  93. # Create the grid
  94. self.grid = Grid(width, height)
  95. self.room_grid = []
  96. # For each row of rooms
  97. for j in range(0, self.num_rows):
  98. row = []
  99. # For each column of rooms
  100. for i in range(0, self.num_cols):
  101. room = Room(
  102. (i * (self.room_size - 1), j * (self.room_size - 1)),
  103. (self.room_size, self.room_size),
  104. )
  105. row.append(room)
  106. # Generate the walls for this room
  107. self.grid.wall_rect(*room.top, *room.size)
  108. self.room_grid.append(row)
  109. # For each row of rooms
  110. for j in range(0, self.num_rows):
  111. # For each column of rooms
  112. for i in range(0, self.num_cols):
  113. room = self.room_grid[j][i]
  114. x_l, y_l = (room.top[0] + 1, room.top[1] + 1)
  115. x_m, y_m = (
  116. room.top[0] + room.size[0] - 1,
  117. room.top[1] + room.size[1] - 1,
  118. )
  119. # Door positions, order is right, down, left, up
  120. if i < self.num_cols - 1:
  121. room.neighbors[0] = self.room_grid[j][i + 1]
  122. room.door_pos[0] = (x_m, self._rand_int(y_l, y_m))
  123. if j < self.num_rows - 1:
  124. room.neighbors[1] = self.room_grid[j + 1][i]
  125. room.door_pos[1] = (self._rand_int(x_l, x_m), y_m)
  126. if i > 0:
  127. room.neighbors[2] = self.room_grid[j][i - 1]
  128. room.door_pos[2] = room.neighbors[2].door_pos[0]
  129. if j > 0:
  130. room.neighbors[3] = self.room_grid[j - 1][i]
  131. room.door_pos[3] = room.neighbors[3].door_pos[1]
  132. # The agent starts in the middle, facing right
  133. self.agent_pos = np.array(
  134. (
  135. (self.num_cols // 2) * (self.room_size - 1) + (self.room_size // 2),
  136. (self.num_rows // 2) * (self.room_size - 1) + (self.room_size // 2),
  137. )
  138. )
  139. self.agent_dir = 0
  140. def place_in_room(self, i, j, obj):
  141. """
  142. Add an existing object to room (i, j)
  143. """
  144. room = self.get_room(i, j)
  145. pos = self.place_obj(
  146. obj, room.top, room.size, reject_fn=reject_next_to, max_tries=1000
  147. )
  148. room.objs.append(obj)
  149. return obj, pos
  150. def add_object(self, i, j, kind=None, color=None):
  151. """
  152. Add a new object to room (i, j)
  153. """
  154. if kind is None:
  155. kind = self._rand_elem(["key", "ball", "box"])
  156. if color is None:
  157. color = self._rand_color()
  158. # TODO: we probably want to add an Object.make helper function
  159. assert kind in ["key", "ball", "box"]
  160. if kind == "key":
  161. obj = Key(color)
  162. elif kind == "ball":
  163. obj = Ball(color)
  164. elif kind == "box":
  165. obj = Box(color)
  166. else:
  167. raise ValueError(
  168. f"{kind} object kind is not available in this environment."
  169. )
  170. return self.place_in_room(i, j, obj)
  171. def add_door(self, i, j, door_idx=None, color=None, locked=None):
  172. """
  173. Add a door to a room, connecting it to a neighbor
  174. """
  175. room = self.get_room(i, j)
  176. if door_idx is None:
  177. # Need to make sure that there is a neighbor along this wall
  178. # and that there is not already a door
  179. while True:
  180. door_idx = self._rand_int(0, 4)
  181. if room.neighbors[door_idx] and room.doors[door_idx] is None:
  182. break
  183. if color is None:
  184. color = self._rand_color()
  185. if locked is None:
  186. locked = self._rand_bool()
  187. assert room.doors[door_idx] is None, "door already exists"
  188. room.locked = locked
  189. door = Door(color, is_locked=locked)
  190. pos = room.door_pos[door_idx]
  191. self.grid.set(pos[0], pos[1], door)
  192. door.cur_pos = pos
  193. neighbor = room.neighbors[door_idx]
  194. room.doors[door_idx] = door
  195. neighbor.doors[(door_idx + 2) % 4] = door
  196. return door, pos
  197. def remove_wall(self, i, j, wall_idx):
  198. """
  199. Remove a wall between two rooms
  200. """
  201. room = self.get_room(i, j)
  202. assert wall_idx >= 0 and wall_idx < 4
  203. assert room.doors[wall_idx] is None, "door exists on this wall"
  204. assert room.neighbors[wall_idx], "invalid wall"
  205. neighbor = room.neighbors[wall_idx]
  206. tx, ty = room.top
  207. w, h = room.size
  208. # Ordering of walls is right, down, left, up
  209. if wall_idx == 0:
  210. for i in range(1, h - 1):
  211. self.grid.set(tx + w - 1, ty + i, None)
  212. elif wall_idx == 1:
  213. for i in range(1, w - 1):
  214. self.grid.set(tx + i, ty + h - 1, None)
  215. elif wall_idx == 2:
  216. for i in range(1, h - 1):
  217. self.grid.set(tx, ty + i, None)
  218. elif wall_idx == 3:
  219. for i in range(1, w - 1):
  220. self.grid.set(tx + i, ty, None)
  221. else:
  222. assert False, "invalid wall index"
  223. # Mark the rooms as connected
  224. room.doors[wall_idx] = True
  225. neighbor.doors[(wall_idx + 2) % 4] = True
  226. def place_agent(self, i=None, j=None, rand_dir=True):
  227. """
  228. Place the agent in a room
  229. """
  230. if i is None:
  231. i = self._rand_int(0, self.num_cols)
  232. if j is None:
  233. j = self._rand_int(0, self.num_rows)
  234. room = self.room_grid[j][i]
  235. # Find a position that is not right in front of an object
  236. while True:
  237. super().place_agent(room.top, room.size, rand_dir, max_tries=1000)
  238. front_cell = self.grid.get(*self.front_pos)
  239. if front_cell is None or front_cell.type == "wall":
  240. break
  241. return self.agent_pos
  242. def connect_all(self, door_colors=COLOR_NAMES, max_itrs=5000):
  243. """
  244. Make sure that all rooms are reachable by the agent from its
  245. starting position
  246. """
  247. start_room = self.room_from_pos(*self.agent_pos)
  248. added_doors = []
  249. def find_reach():
  250. reach = set()
  251. stack = [start_room]
  252. while len(stack) > 0:
  253. room = stack.pop()
  254. if room in reach:
  255. continue
  256. reach.add(room)
  257. for i in range(0, 4):
  258. if room.doors[i]:
  259. stack.append(room.neighbors[i])
  260. return reach
  261. num_itrs = 0
  262. while True:
  263. # This is to handle rare situations where random sampling produces
  264. # a level that cannot be connected, producing in an infinite loop
  265. if num_itrs > max_itrs:
  266. raise RecursionError("connect_all failed")
  267. num_itrs += 1
  268. # If all rooms are reachable, stop
  269. reach = find_reach()
  270. if len(reach) == self.num_rows * self.num_cols:
  271. break
  272. # Pick a random room and door position
  273. i = self._rand_int(0, self.num_cols)
  274. j = self._rand_int(0, self.num_rows)
  275. k = self._rand_int(0, 4)
  276. room = self.get_room(i, j)
  277. # If there is already a door there, skip
  278. if not room.door_pos[k] or room.doors[k]:
  279. continue
  280. if room.locked or room.neighbors[k].locked:
  281. continue
  282. color = self._rand_elem(door_colors)
  283. door, _ = self.add_door(i, j, k, color, False)
  284. added_doors.append(door)
  285. return added_doors
  286. def add_distractors(self, i=None, j=None, num_distractors=10, all_unique=True):
  287. """
  288. Add random objects that can potentially distract/confuse the agent.
  289. """
  290. # Collect a list of existing objects
  291. objs = []
  292. for row in self.room_grid:
  293. for room in row:
  294. for obj in room.objs:
  295. objs.append((obj.type, obj.color))
  296. # List of distractors added
  297. dists = []
  298. while len(dists) < num_distractors:
  299. color = self._rand_elem(COLOR_NAMES)
  300. type = self._rand_elem(["key", "ball", "box"])
  301. obj = (type, color)
  302. if all_unique and obj in objs:
  303. continue
  304. # Add the object to a random room if no room specified
  305. room_i = i
  306. room_j = j
  307. if room_i is None:
  308. room_i = self._rand_int(0, self.num_cols)
  309. if room_j is None:
  310. room_j = self._rand_int(0, self.num_rows)
  311. dist, pos = self.add_object(room_i, room_j, *obj)
  312. objs.append(obj)
  313. dists.append(dist)
  314. return dists