fetch.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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=lambda syntax, color, type: f"{syntax} {color} {type}",
  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. 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