fetch.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. from minigrid.core.constants import COLOR_NAMES
  2. from minigrid.core.grid import Grid
  3. from minigrid.core.mission import MissionSpace
  4. from minigrid.core.world_object import Ball, Key
  5. from minigrid.minigrid import MiniGridEnv
  6. class FetchEnv(MiniGridEnv):
  7. """
  8. ### Description
  9. This environment has multiple objects of assorted types and colors. The
  10. agent receives a textual string as part of its observation telling it which
  11. object to pick up. Picking up the wrong object terminates the episode with
  12. zero reward.
  13. ### Mission Space
  14. "{syntax} {color} {type}"
  15. {syntax} is one of the following: "get a", "go get a", "fetch a",
  16. "go fetch a", "you must fetch a".
  17. {color} is the color of the box. Can be "red", "green", "blue", "purple",
  18. "yellow" or "grey".
  19. {type} is the type of the object. Can be "key" or "ball".
  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 | Pick up an object |
  27. | 4 | drop | Unused |
  28. | 5 | toggle | Unused |
  29. | 6 | done | Unused |
  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' 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 picks up the correct object.
  41. 2. The agent picks up the wrong object.
  42. 2. Timeout (see `max_steps`).
  43. ### Registered Configurations
  44. N: number of objects to be generated.
  45. - `MiniGrid-Fetch-5x5-N2-v0`
  46. - `MiniGrid-Fetch-6x6-N2-v0`
  47. - `MiniGrid-Fetch-8x8-N3-v0`
  48. """
  49. def __init__(self, size=8, numObjs=3, **kwargs):
  50. self.numObjs = numObjs
  51. self.obj_types = ["key", "ball"]
  52. MISSION_SYNTAX = [
  53. "get a",
  54. "go get a",
  55. "fetch a",
  56. "go fetch a",
  57. "you must fetch a",
  58. ]
  59. self.size = size
  60. mission_space = MissionSpace(
  61. mission_func=lambda syntax, color, type: f"{syntax} {color} {type}",
  62. ordered_placeholders=[MISSION_SYNTAX, COLOR_NAMES, self.obj_types],
  63. )
  64. super().__init__(
  65. mission_space=mission_space,
  66. width=size,
  67. height=size,
  68. max_steps=5 * size**2,
  69. # Set this to True for maximum speed
  70. see_through_walls=True,
  71. **kwargs,
  72. )
  73. def _gen_grid(self, width, height):
  74. self.grid = Grid(width, height)
  75. # Generate the surrounding walls
  76. self.grid.horz_wall(0, 0)
  77. self.grid.horz_wall(0, height - 1)
  78. self.grid.vert_wall(0, 0)
  79. self.grid.vert_wall(width - 1, 0)
  80. objs = []
  81. # For each object to be generated
  82. while len(objs) < self.numObjs:
  83. objType = self._rand_elem(self.obj_types)
  84. objColor = self._rand_elem(COLOR_NAMES)
  85. if objType == "key":
  86. obj = Key(objColor)
  87. elif objType == "ball":
  88. obj = Ball(objColor)
  89. else:
  90. raise ValueError(
  91. "{} object type given. Object type can only be of values key and ball.".format(
  92. objType
  93. )
  94. )
  95. self.place_obj(obj)
  96. objs.append(obj)
  97. # Randomize the player start position and orientation
  98. self.place_agent()
  99. # Choose a random object to be picked up
  100. target = objs[self._rand_int(0, len(objs))]
  101. self.targetType = target.type
  102. self.targetColor = target.color
  103. descStr = f"{self.targetColor} {self.targetType}"
  104. # Generate the mission string
  105. idx = self._rand_int(0, 5)
  106. if idx == 0:
  107. self.mission = "get a %s" % descStr
  108. elif idx == 1:
  109. self.mission = "go get a %s" % descStr
  110. elif idx == 2:
  111. self.mission = "fetch a %s" % descStr
  112. elif idx == 3:
  113. self.mission = "go fetch a %s" % descStr
  114. elif idx == 4:
  115. self.mission = "you must fetch a %s" % descStr
  116. assert hasattr(self, "mission")
  117. def step(self, action):
  118. obs, reward, terminated, truncated, info = super().step(action)
  119. if self.carrying:
  120. if (
  121. self.carrying.color == self.targetColor
  122. and self.carrying.type == self.targetType
  123. ):
  124. reward = self._reward()
  125. terminated = True
  126. else:
  127. reward = 0
  128. terminated = True
  129. return obs, reward, terminated, truncated, info