putnear.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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. **kwargs,
  36. )
  37. def _gen_grid(self, width, height):
  38. self.grid = Grid(width, height)
  39. # Generate the surrounding walls
  40. self.grid.horz_wall(0, 0)
  41. self.grid.horz_wall(0, height - 1)
  42. self.grid.vert_wall(0, 0)
  43. self.grid.vert_wall(width - 1, 0)
  44. # Types and colors of objects we can generate
  45. types = ["key", "ball", "box"]
  46. objs = []
  47. objPos = []
  48. def near_obj(env, p1):
  49. for p2 in objPos:
  50. dx = p1[0] - p2[0]
  51. dy = p1[1] - p2[1]
  52. if abs(dx) <= 1 and abs(dy) <= 1:
  53. return True
  54. return False
  55. # Until we have generated all the objects
  56. while len(objs) < self.numObjs:
  57. objType = self._rand_elem(types)
  58. objColor = self._rand_elem(COLOR_NAMES)
  59. # If this object already exists, try again
  60. if (objType, objColor) in objs:
  61. continue
  62. if objType == "key":
  63. obj = Key(objColor)
  64. elif objType == "ball":
  65. obj = Ball(objColor)
  66. elif objType == "box":
  67. obj = Box(objColor)
  68. else:
  69. raise ValueError(
  70. "{} object type given. Object type can only be of values key, ball and box.".format(
  71. objType
  72. )
  73. )
  74. pos = self.place_obj(obj, reject_fn=near_obj)
  75. objs.append((objType, objColor))
  76. objPos.append(pos)
  77. # Randomize the agent start position and orientation
  78. self.place_agent()
  79. # Choose a random object to be moved
  80. objIdx = self._rand_int(0, len(objs))
  81. self.move_type, self.moveColor = objs[objIdx]
  82. self.move_pos = objPos[objIdx]
  83. # Choose a target object (to put the first object next to)
  84. while True:
  85. targetIdx = self._rand_int(0, len(objs))
  86. if targetIdx != objIdx:
  87. break
  88. self.target_type, self.target_color = objs[targetIdx]
  89. self.target_pos = objPos[targetIdx]
  90. self.mission = "put the {} {} near the {} {}".format(
  91. self.moveColor,
  92. self.move_type,
  93. self.target_color,
  94. self.target_type,
  95. )
  96. def step(self, action):
  97. preCarrying = self.carrying
  98. obs, reward, terminated, truncated, info = super().step(action)
  99. u, v = self.dir_vec
  100. ox, oy = (self.agent_pos[0] + u, self.agent_pos[1] + v)
  101. tx, ty = self.target_pos
  102. # If we picked up the wrong object, terminate the episode
  103. if action == self.actions.pickup and self.carrying:
  104. if (
  105. self.carrying.type != self.move_type
  106. or self.carrying.color != self.moveColor
  107. ):
  108. terminated = True
  109. # If successfully dropping an object near the target
  110. if action == self.actions.drop and preCarrying:
  111. if self.grid.get(ox, oy) is preCarrying:
  112. if abs(ox - tx) <= 1 and abs(oy - ty) <= 1:
  113. reward = self._reward()
  114. terminated = True
  115. return obs, reward, terminated, truncated, info