The source code and dockerfile for the GSW2024 AI Lab.
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.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

176 lines
5.3 KiB

4 weeks 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, Key
  6. from minigrid.minigrid_env import MiniGridEnv
  7. class FetchEnv(MiniGridEnv):
  8. """
  9. ## Description
  10. This environment has multiple objects of assorted types and colors. The
  11. agent receives a textual string as part of its observation telling it which
  12. object to pick up. Picking up the wrong object terminates the episode with
  13. zero reward.
  14. ## Mission Space
  15. "{syntax} {color} {type}"
  16. {syntax} is one of the following: "get a", "go get a", "fetch a",
  17. "go fetch a", "you must fetch a".
  18. {color} is the color of the box. Can be "red", "green", "blue", "purple",
  19. "yellow" or "grey".
  20. {type} is the type of the object. Can be "key" or "ball".
  21. ## Action Space
  22. | Num | Name | Action |
  23. |-----|--------------|----------------------|
  24. | 0 | left | Turn left |
  25. | 1 | right | Turn right |
  26. | 2 | forward | Move forward |
  27. | 3 | pickup | Pick up an object |
  28. | 4 | drop | Unused |
  29. | 5 | toggle | Unused |
  30. | 6 | done | Unused |
  31. ## Observation Encoding
  32. - Each tile is encoded as a 3 dimensional tuple:
  33. `(OBJECT_IDX, COLOR_IDX, STATE)`
  34. - `OBJECT_TO_IDX` and `COLOR_TO_IDX` mapping can be found in
  35. [minigrid/minigrid.py](minigrid/minigrid.py)
  36. - `STATE` refers to the door state with 0=open, 1=closed and 2=locked
  37. ## Rewards
  38. A reward of '1 - 0.9 * (step_count / max_steps)' is given for success, and '0' for failure.
  39. ## Termination
  40. The episode ends if any one of the following conditions is met:
  41. 1. The agent picks up the correct object.
  42. 2. The agent picks up the wrong object.
  43. 2. Timeout (see `max_steps`).
  44. ## Registered Configurations
  45. N: number of objects to be generated.
  46. - `MiniGrid-Fetch-5x5-N2-v0`
  47. - `MiniGrid-Fetch-6x6-N2-v0`
  48. - `MiniGrid-Fetch-8x8-N3-v0`
  49. """
  50. def __init__(self, size=8, numObjs=3, max_steps: int | None = None, **kwargs):
  51. self.numObjs = numObjs
  52. self.obj_types = ["key", "ball"]
  53. MISSION_SYNTAX = [
  54. "get a",
  55. "go get a",
  56. "fetch a",
  57. "go fetch a",
  58. "you must fetch a",
  59. ]
  60. self.size = size
  61. mission_space = MissionSpace(
  62. mission_func=self._gen_mission,
  63. ordered_placeholders=[MISSION_SYNTAX, COLOR_NAMES, self.obj_types],
  64. )
  65. if max_steps is None:
  66. max_steps = 5 * size**2
  67. super().__init__(
  68. mission_space=mission_space,
  69. width=size,
  70. height=size,
  71. # Set this to True for maximum speed
  72. see_through_walls=True,
  73. max_steps=max_steps,
  74. **kwargs,
  75. )
  76. @staticmethod
  77. def _gen_mission(syntax: str, color: str, obj_type: str):
  78. return f"{syntax} {color} {obj_type}"
  79. def _gen_grid(self, width, height):
  80. self.grid = Grid(width, height)
  81. # Generate the surrounding walls
  82. self.grid.horz_wall(0, 0)
  83. self.grid.horz_wall(0, height - 1)
  84. self.grid.vert_wall(0, 0)
  85. self.grid.vert_wall(width - 1, 0)
  86. objs = []
  87. # For each object to be generated
  88. while len(objs) < self.numObjs:
  89. objType = self._rand_elem(self.obj_types)
  90. objColor = self._rand_elem(COLOR_NAMES)
  91. if objType == "key":
  92. obj = Key(objColor)
  93. elif objType == "ball":
  94. obj = Ball(objColor)
  95. else:
  96. raise ValueError(
  97. "{} object type given. Object type can only be of values key and ball.".format(
  98. objType
  99. )
  100. )
  101. self.place_obj(obj)
  102. objs.append(obj)
  103. # Randomize the player start position and orientation
  104. self.place_agent()
  105. # Choose a random object to be picked up
  106. target = objs[self._rand_int(0, len(objs))]
  107. self.targetType = target.type
  108. self.targetColor = target.color
  109. descStr = f"{self.targetColor} {self.targetType}"
  110. # Generate the mission string
  111. idx = self._rand_int(0, 5)
  112. if idx == 0:
  113. self.mission = "get a %s" % descStr
  114. elif idx == 1:
  115. self.mission = "go get a %s" % descStr
  116. elif idx == 2:
  117. self.mission = "fetch a %s" % descStr
  118. elif idx == 3:
  119. self.mission = "go fetch a %s" % descStr
  120. elif idx == 4:
  121. self.mission = "you must fetch a %s" % descStr
  122. assert hasattr(self, "mission")
  123. def step(self, action):
  124. obs, reward, terminated, truncated, info = super().step(action)
  125. if self.carrying:
  126. if (
  127. self.carrying.color == self.targetColor
  128. and self.carrying.type == self.targetType
  129. ):
  130. reward = self._reward()
  131. terminated = True
  132. else:
  133. reward = 0
  134. terminated = True
  135. return obs, reward, terminated, truncated, info