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.

161 lines
5.0 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 GoToObjectEnv(MiniGridEnv):
  8. """
  9. ## Description
  10. This environment is a room with colored objects. The agent
  11. receives a textual (mission) string as input, telling it which colored object to go
  12. to, (eg: "go to the red key"). It receives a positive reward for performing
  13. the `done` action next to the correct object, as indicated in the mission
  14. string.
  15. ## Mission Space
  16. "go to the {color} {obj_type}"
  17. {color} is the color of the object. Can be "red", "green", "blue", "purple",
  18. "yellow" or "grey".
  19. {obj_type} is the type of the object. Can be "key", "ball", "box".
  20. ## Action Space
  21. | Num | Name | Action |
  22. |-----|--------------|----------------------|
  23. | 0 | left | Turn left |
  24. | 1 | right | Turn right |
  25. | 2 | forward | Move forward |
  26. | 3 | pickup | Unused |
  27. | 4 | drop | Unused |
  28. | 5 | toggle | Unused |
  29. | 6 | done | Done completing task |
  30. ## Observation Encoding
  31. - Each tile is encoded as a 3 dimensional tuple:
  32. `(OBJECT_IDX, COLOR_IDX, STATE)`
  33. - `OBJECT_TO_IDX` and `COLOR_TO_IDX` mapping can be found in
  34. [minigrid/minigrid.py](minigrid/minigrid.py)
  35. - `STATE` refers to the door state with 0=open, 1=closed and 2=locked
  36. ## Rewards
  37. A reward of '1 - 0.9 * (step_count / max_steps)' is given for success, and '0' for failure.
  38. ## Termination
  39. The episode ends if any one of the following conditions is met:
  40. 1. The agent stands next the correct door performing the `done` action.
  41. 2. Timeout (see `max_steps`).
  42. ## Registered Configurations
  43. - `MiniGrid-GoToObject-6x6-N2-v0`
  44. - `MiniGrid-GoToObject-8x8-N2-v0`
  45. """
  46. def __init__(self, size=6, numObjs=2, max_steps: int | None = None, **kwargs):
  47. self.numObjs = numObjs
  48. self.size = size
  49. # Types of objects to be generated
  50. self.obj_types = ["key", "ball", "box"]
  51. mission_space = MissionSpace(
  52. mission_func=self._gen_mission,
  53. ordered_placeholders=[COLOR_NAMES, self.obj_types],
  54. )
  55. if max_steps is None:
  56. max_steps = 5 * size**2
  57. super().__init__(
  58. mission_space=mission_space,
  59. width=size,
  60. height=size,
  61. # Set this to True for maximum speed
  62. see_through_walls=True,
  63. max_steps=max_steps,
  64. **kwargs,
  65. )
  66. @staticmethod
  67. def _gen_mission(color: str, obj_type: str):
  68. return f"go to the {color} {obj_type}"
  69. def _gen_grid(self, width, height):
  70. self.grid = Grid(width, height)
  71. # Generate the surrounding walls
  72. self.grid.wall_rect(0, 0, width, height)
  73. # Types and colors of objects we can generate
  74. types = ["key", "ball", "box"]
  75. objs = []
  76. objPos = []
  77. # Until we have generated all the objects
  78. while len(objs) < self.numObjs:
  79. objType = self._rand_elem(types)
  80. objColor = self._rand_elem(COLOR_NAMES)
  81. # If this object already exists, try again
  82. if (objType, objColor) in objs:
  83. continue
  84. if objType == "key":
  85. obj = Key(objColor)
  86. elif objType == "ball":
  87. obj = Ball(objColor)
  88. elif objType == "box":
  89. obj = Box(objColor)
  90. else:
  91. raise ValueError(
  92. "{} object type given. Object type can only be of values key, ball and box.".format(
  93. objType
  94. )
  95. )
  96. pos = self.place_obj(obj)
  97. objs.append((objType, objColor))
  98. objPos.append(pos)
  99. # Randomize the agent start position and orientation
  100. self.place_agent()
  101. # Choose a random object to be picked up
  102. objIdx = self._rand_int(0, len(objs))
  103. self.targetType, self.target_color = objs[objIdx]
  104. self.target_pos = objPos[objIdx]
  105. descStr = f"{self.target_color} {self.targetType}"
  106. self.mission = "go to the %s" % descStr
  107. # print(self.mission)
  108. def step(self, action):
  109. obs, reward, terminated, truncated, info = super().step(action)
  110. ax, ay = self.agent_pos
  111. tx, ty = self.target_pos
  112. # Toggle/pickup action terminates the episode
  113. if action == self.actions.toggle:
  114. terminated = True
  115. # Reward performing the done action next to the target object
  116. if action == self.actions.done:
  117. if (ax == tx and abs(ay - ty) == 1) or (ay == ty and abs(ax - tx) == 1):
  118. reward = self._reward()
  119. terminated = True
  120. return obs, reward, terminated, truncated, info