putnear.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. from gym_minigrid.minigrid import (
  2. COLOR_NAMES,
  3. Ball,
  4. Box,
  5. Grid,
  6. Key,
  7. MiniGridEnv,
  8. MissionSpace,
  9. )
  10. class PutNearEnv(MiniGridEnv):
  11. """
  12. Environment in which the agent is instructed to place an object near
  13. another object through a natural language string.
  14. """
  15. def __init__(self, size=6, numObjs=2, **kwargs):
  16. self.size = size
  17. self.numObjs = numObjs
  18. self.obj_types = ["key", "ball", "box"]
  19. mission_space = MissionSpace(
  20. mission_func=lambda move_color, move_type, target_color, target_type: f"put the {move_color} {move_type} near the {target_color} {target_type}",
  21. ordered_placeholders=[
  22. COLOR_NAMES,
  23. self.obj_types,
  24. COLOR_NAMES,
  25. self.obj_types,
  26. ],
  27. )
  28. super().__init__(
  29. mission_space=mission_space,
  30. width=size,
  31. height=size,
  32. max_steps=5 * size,
  33. # Set this to True for maximum speed
  34. see_through_walls=True,
  35. )
  36. def _gen_grid(self, width, height):
  37. self.grid = Grid(width, height)
  38. # Generate the surrounding walls
  39. self.grid.horz_wall(0, 0)
  40. self.grid.horz_wall(0, height - 1)
  41. self.grid.vert_wall(0, 0)
  42. self.grid.vert_wall(width - 1, 0)
  43. # Types and colors of objects we can generate
  44. types = ["key", "ball", "box"]
  45. objs = []
  46. objPos = []
  47. def near_obj(env, p1):
  48. for p2 in objPos:
  49. dx = p1[0] - p2[0]
  50. dy = p1[1] - p2[1]
  51. if abs(dx) <= 1 and abs(dy) <= 1:
  52. return True
  53. return False
  54. # Until we have generated all the objects
  55. while len(objs) < self.numObjs:
  56. objType = self._rand_elem(types)
  57. objColor = self._rand_elem(COLOR_NAMES)
  58. # If this object already exists, try again
  59. if (objType, objColor) in objs:
  60. continue
  61. if objType == "key":
  62. obj = Key(objColor)
  63. elif objType == "ball":
  64. obj = Ball(objColor)
  65. elif objType == "box":
  66. obj = Box(objColor)
  67. else:
  68. raise ValueError(
  69. "{} object type given. Object type can only be of values key, ball and box.".format(
  70. objType
  71. )
  72. )
  73. pos = self.place_obj(obj, reject_fn=near_obj)
  74. objs.append((objType, objColor))
  75. objPos.append(pos)
  76. # Randomize the agent start position and orientation
  77. self.place_agent()
  78. # Choose a random object to be moved
  79. objIdx = self._rand_int(0, len(objs))
  80. self.move_type, self.moveColor = objs[objIdx]
  81. self.move_pos = objPos[objIdx]
  82. # Choose a target object (to put the first object next to)
  83. while True:
  84. targetIdx = self._rand_int(0, len(objs))
  85. if targetIdx != objIdx:
  86. break
  87. self.target_type, self.target_color = objs[targetIdx]
  88. self.target_pos = objPos[targetIdx]
  89. self.mission = "put the {} {} near the {} {}".format(
  90. self.moveColor,
  91. self.move_type,
  92. self.target_color,
  93. self.target_type,
  94. )
  95. def step(self, action):
  96. preCarrying = self.carrying
  97. obs, reward, terminated, truncated, info = super().step(action)
  98. u, v = self.dir_vec
  99. ox, oy = (self.agent_pos[0] + u, self.agent_pos[1] + v)
  100. tx, ty = self.target_pos
  101. # If we picked up the wrong object, terminate the episode
  102. if action == self.actions.pickup and self.carrying:
  103. if (
  104. self.carrying.type != self.move_type
  105. or self.carrying.color != self.moveColor
  106. ):
  107. terminated = True
  108. # If successfully dropping an object near the target
  109. if action == self.actions.drop and preCarrying:
  110. if self.grid.get(ox, oy) is preCarrying:
  111. if abs(ox - tx) <= 1 and abs(oy - ty) <= 1:
  112. reward = self._reward()
  113. terminated = True
  114. return obs, reward, terminated, truncated, info