putnext.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. """
  2. Copied and adapted from https://github.com/mila-iqia/babyai.
  3. Levels described in the Baby AI ICLR 2019 submission, with the `Put Next` instruction.
  4. """
  5. from __future__ import annotations
  6. from minigrid.envs.babyai.core.roomgrid_level import RoomGridLevel
  7. from minigrid.envs.babyai.core.verifier import ObjDesc, PutNextInstr
  8. class PutNextLocal(RoomGridLevel):
  9. """
  10. Put an object next to another object, inside a single room
  11. with no doors, no distractors
  12. """
  13. def __init__(self, room_size=8, num_objs=8, **kwargs):
  14. self.num_objs = num_objs
  15. super().__init__(num_rows=1, num_cols=1, room_size=room_size, **kwargs)
  16. def gen_mission(self):
  17. self.place_agent()
  18. objs = self.add_distractors(num_distractors=self.num_objs, all_unique=True)
  19. self.check_objs_reachable()
  20. o1, o2 = self._rand_subset(objs, 2)
  21. self.instrs = PutNextInstr(
  22. ObjDesc(o1.type, o1.color), ObjDesc(o2.type, o2.color)
  23. )
  24. class PutNext(RoomGridLevel):
  25. """
  26. Task of the form: move the A next to the B and the C next to the D.
  27. This task is structured to have a very large number of possible
  28. instructions.
  29. """
  30. def __init__(
  31. self,
  32. room_size,
  33. objs_per_room,
  34. start_carrying=False,
  35. max_steps: int | None = None,
  36. **kwargs,
  37. ):
  38. assert room_size >= 4
  39. assert objs_per_room <= 9
  40. self.objs_per_room = objs_per_room
  41. self.start_carrying = start_carrying
  42. if max_steps is None:
  43. max_steps = 8 * room_size**2
  44. super().__init__(
  45. num_rows=1, num_cols=2, room_size=room_size, max_steps=max_steps, **kwargs
  46. )
  47. def gen_mission(self):
  48. self.place_agent(0, 0)
  49. # Add objects to both the left and right rooms
  50. # so that we know that we have two non-adjacent set of objects
  51. objs_l = self.add_distractors(0, 0, self.objs_per_room)
  52. objs_r = self.add_distractors(1, 0, self.objs_per_room)
  53. # Remove the wall between the two rooms
  54. self.remove_wall(0, 0, 0)
  55. # Select objects from both subsets
  56. a = self._rand_elem(objs_l)
  57. b = self._rand_elem(objs_r)
  58. # Randomly flip the object to be moved
  59. if self._rand_bool():
  60. t = a
  61. a = b
  62. b = t
  63. self.obj_a = a
  64. self.instrs = PutNextInstr(ObjDesc(a.type, a.color), ObjDesc(b.type, b.color))
  65. def reset(self, **kwargs):
  66. obs = super().reset(**kwargs)
  67. # If the agent starts off carrying the object
  68. if self.start_carrying:
  69. assert self.obj_a.init_pos is not None
  70. self.grid.set(*self.obj_a.init_pos, None)
  71. self.carrying = self.obj_a
  72. return obs