You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

200 lines
6.2 KiB

3 months ago
  1. from __future__ import annotations
  2. from minigrid.core.constants import COLOR_NAMES
  3. from minigrid.core.grid import Grid
  4. from minigrid.core.mission import MissionSpace
  5. from minigrid.core.world_object import Ball, Box, Key
  6. from minigrid.minigrid_env import MiniGridEnv
  7. class PutNearEnv(MiniGridEnv):
  8. """
  9. ## Description
  10. The agent is instructed through a textual string to pick up an object and
  11. place it next to another object. This environment is easy to solve with two
  12. objects, but difficult to solve with more, as it involves both textual
  13. understanding and spatial reasoning involving multiple objects.
  14. ## Mission Space
  15. "put the {move_color} {move_type} near the {target_color} {target_type}"
  16. {move_color} and {target_color} can be "red", "green", "blue", "purple",
  17. "yellow" or "grey".
  18. {move_type} and {target_type} Can be "box", "ball" or "key".
  19. ## Action Space
  20. | Num | Name | Action |
  21. |-----|--------------|-------------------|
  22. | 0 | left | Turn left |
  23. | 1 | right | Turn right |
  24. | 2 | forward | Move forward |
  25. | 3 | pickup | Pick up an object |
  26. | 4 | drop | Drop an object |
  27. | 5 | toggle | Unused |
  28. | 6 | done | Unused |
  29. ## Observation Encoding
  30. - Each tile is encoded as a 3 dimensional tuple:
  31. `(OBJECT_IDX, COLOR_IDX, STATE)`
  32. - `OBJECT_TO_IDX` and `COLOR_TO_IDX` mapping can be found in
  33. [minigrid/minigrid.py](minigrid/minigrid.py)
  34. - `STATE` refers to the door state with 0=open, 1=closed and 2=locked
  35. ## Rewards
  36. A reward of '1 - 0.9 * (step_count / max_steps)' is given for success, and '0' for failure.
  37. ## Termination
  38. The episode ends if any one of the following conditions is met:
  39. 1. The agent picks up the wrong object.
  40. 2. The agent drop the correct object near the target.
  41. 3. Timeout (see `max_steps`).
  42. ## Registered Configurations
  43. N: number of objects.
  44. - `MiniGrid-PutNear-6x6-N2-v0`
  45. - `MiniGrid-PutNear-8x8-N3-v0`
  46. """
  47. def __init__(self, size=6, numObjs=2, max_steps: int | None = None, **kwargs):
  48. self.size = size
  49. self.numObjs = numObjs
  50. self.obj_types = ["key", "ball", "box"]
  51. mission_space = MissionSpace(
  52. mission_func=self._gen_mission,
  53. ordered_placeholders=[
  54. COLOR_NAMES,
  55. self.obj_types,
  56. COLOR_NAMES,
  57. self.obj_types,
  58. ],
  59. )
  60. if max_steps is None:
  61. max_steps = 5 * size
  62. super().__init__(
  63. mission_space=mission_space,
  64. width=size,
  65. height=size,
  66. # Set this to True for maximum speed
  67. see_through_walls=True,
  68. max_steps=max_steps,
  69. **kwargs,
  70. )
  71. @staticmethod
  72. def _gen_mission(
  73. move_color: str, move_type: str, target_color: str, target_type: str
  74. ):
  75. return f"put the {move_color} {move_type} near the {target_color} {target_type}"
  76. def _gen_grid(self, width, height):
  77. self.grid = Grid(width, height)
  78. # Generate the surrounding walls
  79. self.grid.horz_wall(0, 0)
  80. self.grid.horz_wall(0, height - 1)
  81. self.grid.vert_wall(0, 0)
  82. self.grid.vert_wall(width - 1, 0)
  83. # Types and colors of objects we can generate
  84. types = ["key", "ball", "box"]
  85. objs = []
  86. objPos = []
  87. def near_obj(env, p1):
  88. for p2 in objPos:
  89. dx = p1[0] - p2[0]
  90. dy = p1[1] - p2[1]
  91. if abs(dx) <= 1 and abs(dy) <= 1:
  92. return True
  93. return False
  94. # Until we have generated all the objects
  95. while len(objs) < self.numObjs:
  96. objType = self._rand_elem(types)
  97. objColor = self._rand_elem(COLOR_NAMES)
  98. # If this object already exists, try again
  99. if (objType, objColor) in objs:
  100. continue
  101. if objType == "key":
  102. obj = Key(objColor)
  103. elif objType == "ball":
  104. obj = Ball(objColor)
  105. elif objType == "box":
  106. obj = Box(objColor)
  107. else:
  108. raise ValueError(
  109. "{} object type given. Object type can only be of values key, ball and box.".format(
  110. objType
  111. )
  112. )
  113. pos = self.place_obj(obj, reject_fn=near_obj)
  114. objs.append((objType, objColor))
  115. objPos.append(pos)
  116. # Randomize the agent start position and orientation
  117. self.place_agent()
  118. # Choose a random object to be moved
  119. objIdx = self._rand_int(0, len(objs))
  120. self.move_type, self.moveColor = objs[objIdx]
  121. self.move_pos = objPos[objIdx]
  122. # Choose a target object (to put the first object next to)
  123. while True:
  124. targetIdx = self._rand_int(0, len(objs))
  125. if targetIdx != objIdx:
  126. break
  127. self.target_type, self.target_color = objs[targetIdx]
  128. self.target_pos = objPos[targetIdx]
  129. self.mission = "put the {} {} near the {} {}".format(
  130. self.moveColor,
  131. self.move_type,
  132. self.target_color,
  133. self.target_type,
  134. )
  135. def step(self, action):
  136. preCarrying = self.carrying
  137. obs, reward, terminated, truncated, info = super().step(action)
  138. u, v = self.dir_vec
  139. ox, oy = (self.agent_pos[0] + u, self.agent_pos[1] + v)
  140. tx, ty = self.target_pos
  141. # If we picked up the wrong object, terminate the episode
  142. if action == self.actions.pickup and self.carrying:
  143. if (
  144. self.carrying.type != self.move_type
  145. or self.carrying.color != self.moveColor
  146. ):
  147. terminated = True
  148. # If successfully dropping an object near the target
  149. if action == self.actions.drop and preCarrying:
  150. if self.grid.get(ox, oy) is preCarrying:
  151. if abs(ox - tx) <= 1 and abs(oy - ty) <= 1:
  152. reward = self._reward()
  153. terminated = True
  154. return obs, reward, terminated, truncated, info