forked from mila-iqia/babyai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
make_human_demos.py
executable file
·273 lines (214 loc) · 8.11 KB
/
make_human_demos.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#!/usr/bin/env python3
"""
Generate a set of human demonstrations
"""
import sys
import copy
import random
import argparse
import gym
import numpy as np
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QInputDialog
from PyQt5.QtWidgets import QLabel, QTextEdit, QFrame
from PyQt5.QtWidgets import QPushButton, QHBoxLayout, QVBoxLayout
import babyai.utils as utils
import blosc
# Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument("--env", required=True,
help="name of the environment to be loaded (REQUIRED)")
parser.add_argument("--demos", default=None,
help="path to save demonstrations (based on --model and --origin by default)")
parser.add_argument("--seed", type=int, default=1,
help="random seed (default: 1)")
parser.add_argument("--shift", type=int, default=None,
help="number of times the environment is reset at the beginning (default: NUM_DEMOS)")
parser.add_argument("--full-view", action="store_true", default=False,
help="show the full environment view")
args = parser.parse_args()
class ImgWidget(QLabel):
"""
Widget to intercept clicks on the full image view
"""
def __init__(self, window):
super().__init__()
self.window = window
class AIGameWindow(QMainWindow):
"""Application window for the baby AI game"""
def __init__(self, env):
super().__init__()
self.initUI()
# By default, manual stepping only
self.fpsLimit = 0
self.env = env
self.lastObs = None
# Demonstrations
self.demos_path = utils.get_demos_path(args.demos, args.env, origin="human", valid=False)
self.demos = utils.load_demos(self.demos_path, raise_not_found=False)
utils.synthesize_demos(self.demos)
self.shift = len(self.demos) if args.shift is None else args.shift
self.shiftEnv()
# Pointing and naming data
self.pointingData = []
def initUI(self):
"""Create and connect the UI elements"""
self.resize(512, 512)
self.setWindowTitle('Baby AI Game')
# Full render view (large view)
self.imgLabel = ImgWidget(self)
self.imgLabel.setFrameStyle(QFrame.Panel | QFrame.Sunken)
leftBox = QVBoxLayout()
leftBox.addStretch(1)
leftBox.addWidget(self.imgLabel)
leftBox.addStretch(1)
# Area on the right of the large view
rightBox = self.createRightArea()
# Arrange widgets horizontally
hbox = QHBoxLayout()
hbox.addLayout(leftBox)
hbox.addLayout(rightBox)
# Create a main widget for the window
mainWidget = QWidget(self)
self.setCentralWidget(mainWidget)
mainWidget.setLayout(hbox)
# Show the application window
self.show()
self.setFocus()
def createRightArea(self):
# Agent render view (partially observable)
self.obsImgLabel = QLabel()
self.obsImgLabel.setFrameStyle(QFrame.Panel | QFrame.Sunken)
miniViewBox = QHBoxLayout()
miniViewBox.addStretch(1)
miniViewBox.addWidget(self.obsImgLabel)
miniViewBox.addStretch(1)
self.missionBox = QTextEdit()
self.missionBox.setMinimumSize(500, 100)
buttonBox = self.createButtons()
self.stepsLabel = QLabel()
self.stepsLabel.setFrameStyle(QFrame.Panel | QFrame.Sunken)
self.stepsLabel.setAlignment(Qt.AlignCenter)
self.stepsLabel.setMinimumSize(60, 10)
restartBtn = QPushButton("Restart")
restartBtn.clicked.connect(self.shiftEnv)
stepsBox = QHBoxLayout()
stepsBox.addStretch(1)
stepsBox.addWidget(QLabel("Steps remaining"))
stepsBox.addWidget(self.stepsLabel)
stepsBox.addWidget(restartBtn)
stepsBox.addStretch(1)
stepsBox.addStretch(1)
hline2 = QFrame()
hline2.setFrameShape(QFrame.HLine)
hline2.setFrameShadow(QFrame.Sunken)
# Stack everything up in a vetical layout
vbox = QVBoxLayout()
vbox.addLayout(miniViewBox)
vbox.addLayout(stepsBox)
vbox.addWidget(hline2)
vbox.addWidget(QLabel(""))
vbox.addWidget(self.missionBox)
vbox.addLayout(buttonBox)
return vbox
def createButtons(self):
"""Create the row of UI buttons"""
# Assemble the buttons into a horizontal layout
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addStretch(1)
return hbox
def keyPressEvent(self, e):
# Manual agent control
actions = self.env.unwrapped.actions
if e.key() == Qt.Key_Left:
self.stepEnv(actions.left)
elif e.key() == Qt.Key_Right:
self.stepEnv(actions.right)
elif e.key() == Qt.Key_Up:
self.stepEnv(actions.forward)
elif e.key() == Qt.Key_PageUp:
self.stepEnv(actions.pickup)
elif e.key() == Qt.Key_PageDown:
self.stepEnv(actions.drop)
elif e.key() == Qt.Key_Space:
self.stepEnv(actions.toggle)
elif e.key() == Qt.Key_Backspace:
self.shiftEnv()
elif e.key() == Qt.Key_Escape:
self.close()
def mousePressEvent(self, event):
"""
Clear the focus of the text boxes and buttons if somewhere
else on the window is clicked
"""
# Set the focus on the full render image
self.imgLabel.setFocus()
QMainWindow.mousePressEvent(self, event)
def shiftEnv(self):
assert self.shift <= len(self.demos)
self.env.seed(args.seed)
self.resetEnv()
for _ in range(self.shift):
self.resetEnv()
def resetEnv(self):
self.current_demo = []
self.current_demo = []
self.current_actions = []
self.current_images = []
self.current_directions = []
obs = self.env.reset()
self.lastObs = obs
self.showEnv(obs)
self.current_mission = obs['mission']
self.missionBox.setText(obs["mission"])
def showEnv(self, obs):
unwrapped = self.env.unwrapped
# Render and display the environment
if args.full_view:
pixmap = self.env.render(mode='pixmap')
self.imgLabel.setPixmap(pixmap)
# Render and display the agent's view
image = obs['image']
obsPixmap = unwrapped.get_obs_render(image)
self.obsImgLabel.setPixmap(obsPixmap)
# Set the steps remaining
stepsRem = unwrapped.steps_remaining
self.stepsLabel.setText(str(stepsRem))
def stepEnv(self, action=None):
# If no manual action was specified by the user
if action is None:
action = random.randint(0, self.env.action_space.n - 1)
action = int(action)
obs, reward, done, info = self.env.step(action)
self.current_actions.append(action)
self.current_images.append(self.lastObs['image'])
self.current_directions.append(self.lastObs['direction'])
self.showEnv(obs)
self.lastObs = obs
if done:
if reward > 0: # i.e. we did not lose
if self.shift < len(self.demos):
self.demos[self.shift] = self.current_demo, self.shift
else:
self.demos.append((self.current_mission,
blosc.pack_array(np.array(self.current_images)),
self.current_directions,
self.current_actions))
utils.save_demos(self.demos, self.demos_path)
self.missionBox.append('Demonstrations are saved.')
utils.synthesize_demos(self.demos)
self.shift += 1
self.resetEnv()
else:
self.shiftEnv()
def main(argv):
# Generate environment
env = gym.make(args.env)
# Create the application window
app = QApplication(sys.argv)
window = AIGameWindow(env)
# Run the application
sys.exit(app.exec_())
if __name__ == '__main__':
main(sys.argv)