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.

149 lines
4.7 KiB

2 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 Door
  6. from minigrid.minigrid_env import MiniGridEnv
  7. class GoToDoorEnv(MiniGridEnv):
  8. """
  9. ## Description
  10. This environment is a room with four doors, one on each wall. The agent
  11. receives a textual (mission) string as input, telling it which door to go
  12. to, (eg: "go to the red door"). It receives a positive reward for performing
  13. the `done` action next to the correct door, as indicated in the mission
  14. string.
  15. ## Mission Space
  16. "go to the {color} door"
  17. {color} is the color of the door. Can be "red", "green", "blue", "purple",
  18. "yellow" or "grey".
  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 | Unused |
  26. | 4 | drop | Unused |
  27. | 5 | toggle | Unused |
  28. | 6 | done | Done completing task |
  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 stands next the correct door performing the `done` action.
  40. 2. Timeout (see `max_steps`).
  41. ## Registered Configurations
  42. - `MiniGrid-GoToDoor-5x5-v0`
  43. - `MiniGrid-GoToDoor-6x6-v0`
  44. - `MiniGrid-GoToDoor-8x8-v0`
  45. """
  46. def __init__(self, size=5, max_steps: int | None = None, **kwargs):
  47. assert size >= 5
  48. self.size = size
  49. mission_space = MissionSpace(
  50. mission_func=self._gen_mission,
  51. ordered_placeholders=[COLOR_NAMES],
  52. )
  53. if max_steps is None:
  54. max_steps = 4 * size**2
  55. super().__init__(
  56. mission_space=mission_space,
  57. width=size,
  58. height=size,
  59. # Set this to True for maximum speed
  60. see_through_walls=True,
  61. max_steps=max_steps,
  62. **kwargs,
  63. )
  64. @staticmethod
  65. def _gen_mission(color: str):
  66. return f"go to the {color} door"
  67. def _gen_grid(self, width, height):
  68. # Create the grid
  69. self.grid = Grid(width, height)
  70. # Randomly vary the room width and height
  71. width = self._rand_int(5, width + 1)
  72. height = self._rand_int(5, height + 1)
  73. # Generate the surrounding walls
  74. self.grid.wall_rect(0, 0, width, height)
  75. # Generate the 4 doors at random positions
  76. doorPos = []
  77. doorPos.append((self._rand_int(2, width - 2), 0))
  78. doorPos.append((self._rand_int(2, width - 2), height - 1))
  79. doorPos.append((0, self._rand_int(2, height - 2)))
  80. doorPos.append((width - 1, self._rand_int(2, height - 2)))
  81. # Generate the door colors
  82. doorColors = []
  83. while len(doorColors) < len(doorPos):
  84. color = self._rand_elem(COLOR_NAMES)
  85. if color in doorColors:
  86. continue
  87. doorColors.append(color)
  88. # Place the doors in the grid
  89. for idx, pos in enumerate(doorPos):
  90. color = doorColors[idx]
  91. self.grid.set(*pos, Door(color))
  92. # Randomize the agent start position and orientation
  93. self.place_agent(size=(width, height))
  94. # Select a random target door
  95. doorIdx = self._rand_int(0, len(doorPos))
  96. self.target_pos = doorPos[doorIdx]
  97. self.target_color = doorColors[doorIdx]
  98. # Generate the mission string
  99. self.mission = "go to the %s door" % self.target_color
  100. def step(self, action):
  101. obs, reward, terminated, truncated, info = super().step(action)
  102. ax, ay = self.agent_pos
  103. tx, ty = self.target_pos
  104. # Don't let the agent open any of the doors
  105. if action == self.actions.toggle:
  106. terminated = True
  107. # Reward performing done action in front of the target door
  108. if action == self.actions.done:
  109. if (ax == tx and abs(ay - ty) == 1) or (ay == ty and abs(ax - tx) == 1):
  110. reward = self._reward()
  111. terminated = True
  112. return obs, reward, terminated, truncated, info