fetch.py 5.2 KB

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