fetch.py 5.4 KB

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