putnear.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. from gym_minigrid.minigrid import *
  2. from gym_minigrid.register import register
  3. class PutNearEnv(MiniGridEnv):
  4. """
  5. Environment in which the agent is instructed to place an object near
  6. another object through a natural language string.
  7. """
  8. def __init__(
  9. self,
  10. size=6,
  11. numObjs=2
  12. ):
  13. self.numObjs = numObjs
  14. super().__init__(gridSize=size, maxSteps=5*size)
  15. self.observation_space = spaces.Dict({
  16. 'image': self.observation_space
  17. })
  18. self.reward_range = (-1, 1)
  19. def _genGrid(self, width, height):
  20. # Create a grid surrounded by walls
  21. grid = Grid(width, height)
  22. for i in range(0, width):
  23. grid.set(i, 0, Wall())
  24. grid.set(i, height-1, Wall())
  25. for j in range(0, height):
  26. grid.set(0, j, Wall())
  27. grid.set(width-1, j, Wall())
  28. # Types and colors of objects we can generate
  29. types = ['key', 'ball']
  30. colors = list(COLORS.keys())
  31. objs = []
  32. objPos = []
  33. def nearObj(p1):
  34. for p2 in objPos:
  35. dx = p1[0] - p2[0]
  36. dy = p1[1] - p2[1]
  37. if abs(dx) <= 1 and abs(dy) <= 1:
  38. return True
  39. return False
  40. # Until we have generated all the objects
  41. while len(objs) < self.numObjs:
  42. objType = self._randElem(types)
  43. objColor = self._randElem(colors)
  44. # If this object already exists, try again
  45. if (objType, objColor) in objs:
  46. continue
  47. if objType == 'key':
  48. obj = Key(objColor)
  49. elif objType == 'ball':
  50. obj = Ball(objColor)
  51. elif objType == 'box':
  52. obj = Box(objColor)
  53. while True:
  54. pos = (
  55. self._randInt(1, width - 1),
  56. self._randInt(1, height - 1)
  57. )
  58. if nearObj(pos):
  59. continue
  60. if pos == self.startPos:
  61. continue
  62. grid.set(*pos, obj)
  63. break
  64. objs.append((objType, objColor))
  65. objPos.append(pos)
  66. # Choose a random object to be moved
  67. objIdx = self._randInt(0, len(objs))
  68. self.moveType, self.moveColor = objs[objIdx]
  69. self.movePos = objPos[objIdx]
  70. # Choose a target object (to put the first object next to)
  71. while True:
  72. targetIdx = self._randInt(0, len(objs))
  73. if targetIdx != objIdx:
  74. break
  75. self.targetType, self.targetColor = objs[targetIdx]
  76. self.targetPos = objPos[targetIdx]
  77. self.mission = 'put the %s %s near the %s %s' % (
  78. self.moveColor,
  79. self.moveType,
  80. self.targetColor,
  81. self.targetType
  82. )
  83. return grid
  84. def _observation(self, obs):
  85. """
  86. Encode observations
  87. """
  88. obs = {
  89. 'image': obs,
  90. 'mission': self.mission
  91. }
  92. return obs
  93. def _reset(self):
  94. obs = MiniGridEnv._reset(self)
  95. return self._observation(obs)
  96. def _step(self, action):
  97. preCarrying = self.carrying
  98. obs, reward, done, info = MiniGridEnv._step(self, action)
  99. u, v = self.getDirVec()
  100. ox, oy = (self.agentPos[0] + u, self.agentPos[1] + v)
  101. tx, ty = self.targetPos
  102. # Pickup/drop action
  103. if action == self.actions.toggle:
  104. # If we picked up the wrong object, terminate the episode
  105. if self.carrying:
  106. if self.carrying.type != self.moveType or self.carrying.color != self.moveColor:
  107. done = True
  108. # If successfully dropping an object near the target
  109. if preCarrying:
  110. if self.grid.get(ox, oy) is preCarrying:
  111. if abs(ox - tx) <= 1 and abs(oy - ty) <= 1:
  112. reward = 1
  113. done = True
  114. obs = self._observation(obs)
  115. return obs, reward, done, info
  116. class PutNear8x8N3(PutNearEnv):
  117. def __init__(self):
  118. super().__init__(size=8, numObjs=3)
  119. register(
  120. id='MiniGrid-PutNear-6x6-N2-v0',
  121. entry_point='gym_minigrid.envs:PutNearEnv'
  122. )
  123. register(
  124. id='MiniGrid-PutNear-8x8-N3-v0',
  125. entry_point='gym_minigrid.envs:PutNear8x8N3'
  126. )