-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathinteractive_rendering.py
More file actions
407 lines (353 loc) · 14.5 KB
/
interactive_rendering.py
File metadata and controls
407 lines (353 loc) · 14.5 KB
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# Copyright (c) ProrokLab.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""
Use this script to interactively play with scenarios
You can change agent by pressing TAB
You can reset the environment by pressing R
You can move agents with the arrow keys
If you have more than 1 agent, you can control another one with W,A,S,D
and switch the agent with these controls using LSHIFT
"""
from argparse import ArgumentParser, BooleanOptionalAction
from operator import add
from typing import Dict, Union
import numpy as np
from torch import Tensor
from vmas.make_env import make_env
from vmas.simulator.environment.gym import GymWrapper
from vmas.simulator.scenario import BaseScenario
from vmas.simulator.utils import save_video
N_TEXT_LINES_INTERACTIVE = 6
class InteractiveEnv:
"""
Use this script to interactively play with scenarios
You can change agent by pressing TAB
You can reset the environment by pressing R
You can control agent actions with the arrow keys and M/N (left/right control the first action, up/down control the second, M/N controls the third)
If you have more than 1 agent, you can control another one with W,A,S,D and Q,E in the same way.
and switch the agent with these controls using LSHIFT
"""
def __init__(
self,
env: GymWrapper,
control_two_agents: bool = False,
display_info: bool = True,
save_render: bool = False,
render_name: str = "interactive",
):
self.env = env
self.control_two_agents = control_two_agents
# hard-coded keyboard events
self.current_agent_index = 0
self.current_agent_index2 = 1
self.n_agents = self.env.unwrapped.n_agents
self.agents = self.env.unwrapped.agents
self.continuous = self.env.unwrapped.continuous_actions
self.reset = False
self.keys = np.array(
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
) # up, down, left, right, rot+, rot-
self.keys2 = np.array(
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
) # up, down, left, right, rot+, rot-
self.u = [0] * (3 if self.continuous else 2)
self.u2 = [0] * (3 if self.continuous else 2)
self.frame_list = []
self.display_info = display_info
self.save_render = save_render
self.render_name = render_name
if self.control_two_agents:
assert (
self.n_agents >= 2
), "Control_two_agents is true but not enough agents in scenario"
self.text_lines = []
self.font_size = 15
self.env.render()
self.text_idx = len(self.env.unwrapped.text_lines)
self._init_text()
self.env.unwrapped.viewer.window.on_key_press = self._key_press
self.env.unwrapped.viewer.window.on_key_release = self._key_release
self._cycle()
def _increment_selected_agent_index(self, index: int):
index += 1
if index == self.n_agents:
index = 0
return index
def _cycle(self):
total_rew = [0] * self.n_agents
while True:
if self.reset:
if self.save_render:
save_video(
self.render_name,
self.frame_list,
fps=1 / self.env.unwrapped.world.dt,
)
self.env.reset()
self.reset = False
total_rew = [0] * self.n_agents
if self.n_agents > 0:
action_list = [[0.0] * agent.action_size for agent in self.agents]
action_list[self.current_agent_index][
: self.agents[self.current_agent_index].dynamics.needed_action_size
] = self.u[
: self.agents[self.current_agent_index].dynamics.needed_action_size
]
else:
action_list = []
if self.n_agents > 1 and self.control_two_agents:
action_list[self.current_agent_index2][
: self.agents[self.current_agent_index2].dynamics.needed_action_size
] = self.u2[
: self.agents[self.current_agent_index2].dynamics.needed_action_size
]
obs, rew, done, info = self.env.step(action_list)
if self.display_info and self.n_agents > 0:
# TODO: Determine number of lines of obs_str and render accordingly
obs_str = str(InteractiveEnv.format_obs(obs[self.current_agent_index]))
message = f"\t\t{obs_str[len(obs_str) // 2:]}"
self._write_values(0, message)
message = f"Obs: {obs_str[:len(obs_str) // 2]}"
self._write_values(1, message)
message = f"Rew: {round(rew[self.current_agent_index],3)}"
self._write_values(2, message)
total_rew = list(map(add, total_rew, rew))
message = f"Total rew: {round(total_rew[self.current_agent_index], 3)}"
self._write_values(3, message)
message = f"Done: {done}"
self._write_values(4, message)
message = f"Selected: {self.env.unwrapped.agents[self.current_agent_index].name}"
self._write_values(5, message)
frame = self.env.render(
mode="rgb_array" if self.save_render else "human",
visualize_when_rgb=True,
)
if self.save_render:
self.frame_list.append(frame)
if done:
self.reset = True
def _init_text(self):
from vmas.simulator import rendering
for i in range(N_TEXT_LINES_INTERACTIVE):
text_line = rendering.TextLine(
y=(self.text_idx + i) * 40, font_size=self.font_size
)
self.env.unwrapped.viewer.add_geom(text_line)
self.text_lines.append(text_line)
def _write_values(self, index: int, message: str):
self.text_lines[index].set_text(message)
# keyboard event callbacks
def _key_press(self, k, mod):
from pyglet.window import key
agent_range = self.agents[self.current_agent_index].action.u_range_tensor
try:
if k == key.LEFT:
self.keys[0] = agent_range[0]
elif k == key.RIGHT:
self.keys[1] = agent_range[0]
elif k == key.DOWN:
self.keys[2] = agent_range[1]
elif k == key.UP:
self.keys[3] = agent_range[1]
elif k == key.M:
self.keys[4] = agent_range[2]
elif k == key.N:
self.keys[5] = agent_range[2]
elif k == key.TAB:
self.current_agent_index = self._increment_selected_agent_index(
self.current_agent_index
)
if self.control_two_agents:
while self.current_agent_index == self.current_agent_index2:
self.current_agent_index = self._increment_selected_agent_index(
self.current_agent_index
)
if self.control_two_agents:
agent2_range = self.agents[
self.current_agent_index2
].action.u_range_tensor
if k == key.A:
self.keys2[0] = agent2_range[0]
elif k == key.D:
self.keys2[1] = agent2_range[0]
elif k == key.S:
self.keys2[2] = agent2_range[1]
elif k == key.W:
self.keys2[3] = agent2_range[1]
elif k == key.E:
self.keys2[4] = agent2_range[2]
elif k == key.Q:
self.keys2[5] = agent2_range[2]
elif k == key.LSHIFT:
self.current_agent_index2 = self._increment_selected_agent_index(
self.current_agent_index2
)
while self.current_agent_index == self.current_agent_index2:
self.current_agent_index2 = (
self._increment_selected_agent_index(
self.current_agent_index2
)
)
except IndexError:
print("Action not available")
if k == key.R:
self.reset = True
self.set_u()
def _key_release(self, k, mod):
from pyglet.window import key
if k == key.LEFT:
self.keys[0] = 0
elif k == key.RIGHT:
self.keys[1] = 0
elif k == key.DOWN:
self.keys[2] = 0
elif k == key.UP:
self.keys[3] = 0
elif k == key.M:
self.keys[4] = 0
elif k == key.N:
self.keys[5] = 0
if self.control_two_agents:
if k == key.A:
self.keys2[0] = 0
elif k == key.D:
self.keys2[1] = 0
elif k == key.S:
self.keys2[2] = 0
elif k == key.W:
self.keys2[3] = 0
elif k == key.E:
self.keys2[4] = 0
elif k == key.Q:
self.keys2[5] = 0
self.set_u()
def set_u(self):
if self.continuous:
self.u = [
self.keys[1] - self.keys[0],
self.keys[3] - self.keys[2],
self.keys[4] - self.keys[5],
]
self.u2 = [
self.keys2[1] - self.keys2[0],
self.keys2[3] - self.keys2[2],
self.keys2[4] - self.keys2[5],
]
else:
if np.sum(self.keys[:4]) >= 1:
self.u[0] = np.argmax(self.keys[:4]) + 1
else:
self.u[0] = 0
if np.sum(self.keys[4:]) >= 1:
self.u[1] = np.argmax(self.keys[4:]) + 1
else:
self.u[1] = 0
if np.sum(self.keys2[:4]) >= 1:
self.u2[0] = np.argmax(self.keys2[:4]) + 1
else:
self.u2[0] = 0
if np.sum(self.keys2[4:]) >= 1:
self.u2[1] = np.argmax(self.keys2[4:]) + 1
else:
self.u2[1] = 0
@staticmethod
def format_obs(obs):
if isinstance(obs, (Tensor, np.ndarray)):
return list(np.around(obs.tolist(), decimals=2))
elif isinstance(obs, Dict):
return {key: InteractiveEnv.format_obs(value) for key, value in obs.items()}
else:
raise NotImplementedError(f"Invalid type of observation {obs}")
def render_interactively(
scenario: Union[str, BaseScenario],
control_two_agents: bool = False,
display_info: bool = True,
save_render: bool = False,
**kwargs,
):
"""Executes a scenario and renders it so that you can debug and control agents interactively.
You can change the agent to control by pressing TAB.
You can reset the environment by pressing R.
You can control agent actions with the arrow keys and M/N (left/right control the first action, up/down control the second, M/N controls the third)
If you have more than 1 agent, you can control another one with W,A,S,D and Q,E in the same way.
and switch the agent using LSHIFT.
Args:
scenario (Union[str, BaseScenario]): Scenario to load.
Can be the name of a file in `vmas.scenarios` folder or a :class:`~vmas.simulator.scenario.BaseScenario` class
control_two_agents (bool, optional): Whether to control two agents or just one. Defaults to ``False``.
display_info (bool, optional): Whether to display on the screen the following info from the first controlled agent:
name, reward, total reward, done, and observation. Defaults to ``True``.
save_render (bool, optional): Whether to save a video of the render up to the first reset.
The video will be saved in the directory of this file with the name ``{scenario}_interactive``.
Defaults to ``False``.
Examples:
>>> from vmas import render_interactively
>>> render_interactively(
... "waterfall",
... control_two_agents=True,
... save_render=False,
... display_info=True,
... )
"""
InteractiveEnv(
make_env(
scenario=scenario,
num_envs=1,
device="cpu",
continuous_actions=True,
wrapper="gym",
seed=0,
wrapper_kwargs={"return_numpy": False},
# Environment specific variables
**kwargs,
),
control_two_agents=control_two_agents,
display_info=display_info,
save_render=save_render,
render_name=f"{scenario}_interactive"
if isinstance(scenario, str)
else "interactive",
)
def parse_args():
parser = ArgumentParser(description="Interactive rendering")
parser.add_argument(
"--scenario",
type=str,
default="waterfall",
help="Scenario to load. Can be the name of a file in `vmas.scenarios` folder or a :class:`~vmas.simulator.scenario.BaseScenario` class",
)
parser.add_argument(
"--control_two_agents",
action=BooleanOptionalAction,
default=True,
help="Whether to control two agents or just one",
)
parser.add_argument(
"--display_info",
action=BooleanOptionalAction,
default=True,
help="Whether to display on the screen the following info from the first controlled agent: name, reward, total reward, done, and observation",
)
parser.add_argument(
"--save_render",
action="store_true",
help="Whether to save a video of the render up to the first reset",
)
return parser.parse_args()
if __name__ == "__main__":
# Use this script to interactively play with scenarios
#
# You can change agent by pressing TAB
# You can reset the environment by pressing R
# You can control agent actions with the arrow keys and M/N (left/right control the first action, up/down control the second, M/N controls the third)
# If you have more than 1 agent, you can control another one with W,A,S,D and Q,E in the same way.
# and switch the agent with these controls using LSHIFT
args = parse_args()
render_interactively(
scenario=args.scenario,
control_two_agents=args.control_two_agents,
save_render=args.save_render,
display_info=args.display_info,
)