fetch.py 4.9 KB

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