fetch.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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_env import MiniGridEnv
  6. class FetchEnv(MiniGridEnv):
  7. """
  8. ![fetch-env](../_static/figures/fetch-env.png)
  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' 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, **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=lambda syntax, color, type: f"{syntax} {color} {type}",
  63. ordered_placeholders=[MISSION_SYNTAX, COLOR_NAMES, self.obj_types],
  64. )
  65. super().__init__(
  66. mission_space=mission_space,
  67. width=size,
  68. height=size,
  69. max_steps=5 * size**2,
  70. # Set this to True for maximum speed
  71. see_through_walls=True,
  72. **kwargs,
  73. )
  74. def _gen_grid(self, width, height):
  75. self.grid = Grid(width, height)
  76. # Generate the surrounding walls
  77. self.grid.horz_wall(0, 0)
  78. self.grid.horz_wall(0, height - 1)
  79. self.grid.vert_wall(0, 0)
  80. self.grid.vert_wall(width - 1, 0)
  81. objs = []
  82. # For each object to be generated
  83. while len(objs) < self.numObjs:
  84. objType = self._rand_elem(self.obj_types)
  85. objColor = self._rand_elem(COLOR_NAMES)
  86. if objType == "key":
  87. obj = Key(objColor)
  88. elif objType == "ball":
  89. obj = Ball(objColor)
  90. else:
  91. raise ValueError(
  92. "{} object type given. Object type can only be of values key and ball.".format(
  93. objType
  94. )
  95. )
  96. self.place_obj(obj)
  97. objs.append(obj)
  98. # Randomize the player start position and orientation
  99. self.place_agent()
  100. # Choose a random object to be picked up
  101. target = objs[self._rand_int(0, len(objs))]
  102. self.targetType = target.type
  103. self.targetColor = target.color
  104. descStr = f"{self.targetColor} {self.targetType}"
  105. # Generate the mission string
  106. idx = self._rand_int(0, 5)
  107. if idx == 0:
  108. self.mission = "get a %s" % descStr
  109. elif idx == 1:
  110. self.mission = "go get a %s" % descStr
  111. elif idx == 2:
  112. self.mission = "fetch a %s" % descStr
  113. elif idx == 3:
  114. self.mission = "go fetch a %s" % descStr
  115. elif idx == 4:
  116. self.mission = "you must fetch a %s" % descStr
  117. assert hasattr(self, "mission")
  118. def step(self, action):
  119. obs, reward, terminated, truncated, info = super().step(action)
  120. if self.carrying:
  121. if (
  122. self.carrying.color == self.targetColor
  123. and self.carrying.type == self.targetType
  124. ):
  125. reward = self._reward()
  126. terminated = True
  127. else:
  128. reward = 0
  129. terminated = True
  130. return obs, reward, terminated, truncated, info