-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwrappers.py
411 lines (356 loc) · 13.9 KB
/
wrappers.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
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
408
409
410
411
from mlagents_envs import base_env
import numpy as np
import copy
import gym
from gym_unity.envs import ActionFlattener
from ray.rllib.env.apis.task_settable_env import TaskSettableEnv
from ray.rllib.models.preprocessors import OneHotPreprocessor
import uuid
from soccer_twos.wrappers import MultiAgentUnityWrapper
import random
from ray.rllib.utils.annotations import override
class SingleObsWrapper(gym.core.Wrapper):
"""
A wrapper to unstack the agent observation, returning only the last information
"""
def __init__(self, env):
super(SingleObsWrapper, self).__init__(env)
self.env = env
#original obs format:
# size = 336
#[fowardt_-2(88), fowardt_-1(88), fowardt_0(88), backwardt_-2(24), backwardt_-1(24), backwardt_0(24)]
#single obs format:
# size = 112
# [fowardt_0(88), backwardt_0(24)]
self.observation_space = gym.spaces.Box(
0, 1, dtype=np.float32, shape=(112,)
)
def step(self, action):
obs, rewards, done, info = self.env.step(action)
return (
self._preprocess_obs(obs),
rewards,
done,
info,
)
def reset(self):
return self._preprocess_obs(self.env.reset())
def _preprocess_obs(self, obs):
return SingleObsWrapper.preprocess_obs(obs)
@staticmethod
def preprocess_obs(obs, **kwargs):
new_obs = {}
for agent_id, agent_obs in obs.items():
new_agent_obs = np.zeros((112,))
new_agent_obs[:88] = agent_obs[176:264]
new_agent_obs[88:] = agent_obs[312:]
new_obs[agent_id] = new_agent_obs
return new_obs
class MultiagentTeamObsWrapper(gym.core.Wrapper):
"""
A wrapper for multiagent a environment.
Join the observation of each team for each agent.
"""
def __init__(self, env):
super(MultiagentTeamObsWrapper, self).__init__(env)
self.env = env
# duplicate obs space (concatenate team players)
self.observation_space = gym.spaces.Box(
0, 1, dtype=np.float32, shape=(env.observation_space.shape[0] * 2,)
)
def step(self, action):
obs, rewards, done, info = self.env.step(action)
return (
self._preprocess_obs(obs),
rewards,
done,
info,
)
def reset(self):
return self._preprocess_obs(self.env.reset())
def _preprocess_obs(self, obs):
return {
0: np.concatenate((obs[1], obs[0])),
1: np.concatenate((obs[0], obs[1])),
2: np.concatenate((obs[3], obs[2])),
3: np.concatenate((obs[2], obs[3])),
}
@staticmethod
def preprocess_obs(obs, **kwargs):
return {
0: np.concatenate((obs[1], obs[0])),
1: np.concatenate((obs[0], obs[1])),
}
class AgentIdInfoWrapper(gym.core.Wrapper):
"""
A wrapper for multiagent a environment.
Adds agent id information to the observation.
"""
def __init__(self, env):
super(AgentIdInfoWrapper, self).__init__(env)
self.env = env
self.observation_space = gym.spaces.Box(
0, 1, dtype=np.float32, shape=(env.observation_space.shape[0]+2,)
)
def step(self, action):
obs, rewards, done, info = self.env.step(action)
return (
self._preprocess_obs(obs),
rewards,
done,
info,
)
def reset(self):
return self._preprocess_obs(self.env.reset())
def _preprocess_obs(self, obs):
return {
0: np.concatenate(([0, 1], obs[0])),
1: np.concatenate(([1, 0], obs[1])),
2: np.concatenate(([0, 1], obs[2])),
3: np.concatenate(([1, 0], obs[3])),
}
@staticmethod
def preprocess_obs(obs, **kwargs):
return {
0: np.concatenate(([0, 1], obs[0])),
1: np.concatenate(([1, 0], obs[1])),
}
class PreviousActionWrapper(gym.core.Wrapper):
"""
A wrapper that adds agent previous action information to the observation.
"""
def __init__(self, env):
super(PreviousActionWrapper, self).__init__(env)
self.env = env
self.preprocessor = OneHotPreprocessor(env.action_space)
# duplicate obs space (concatenate team players)
self.observation_space = gym.spaces.Box(
0, 1, dtype=np.float32, shape=(env.observation_space.shape[0]+self.preprocessor.shape[0],)
)
if isinstance(env.action_space, gym.spaces.Discrete):
self.zero_action = self.preprocessor.transform(0)
else:
self.zero_action = self.preprocessor.transform(np.zeros(env.action_space.shape).astype(int))
self.last_action = {
0: self.zero_action,
1: self.zero_action,
2: self.zero_action,
3: self.zero_action,
}
def step(self, action):
for agent_id, a in action.items():
self.last_action[agent_id] = self.preprocessor.transform(a)
obs, rewards, done, info = self.env.step(action)
return (
self._preprocess_obs(obs),
rewards,
done,
info,
)
def reset(self):
self.last_action = {
0: self.zero_action,
1: self.zero_action,
2: self.zero_action,
3: self.zero_action,
}
return self._preprocess_obs(self.env.reset())
def _preprocess_obs(self, obs):
return {
0: np.concatenate((self.last_action[0], obs[0])),
1: np.concatenate((self.last_action[1], obs[1])),
2: np.concatenate((self.last_action[2], obs[2])),
3: np.concatenate((self.last_action[3], obs[3])),
}
@staticmethod
def preprocess_obs(obs, **kwargs):
return {
0: np.concatenate((kwargs['last_action'][0], obs[0])),
1: np.concatenate((kwargs['last_action'][1], obs[1])),
}
class RandomEnvWrapper(gym.core.Wrapper):
"""
A wrapper randomizes the envoriment.
(By default Does only randomize Ball position and Player rotation)
"""
def __init__(self, env, randomize = {'ball': ['position'], 'player': ['rotation_y']}, min_divergence = 0.3, k=1):
super(RandomEnvWrapper, self).__init__(env)
self.env = env
self.randomize = randomize
self.base_env = self.env.unwrapped
while not isinstance(self.base_env, MultiAgentUnityWrapper):
self.base_env = self.base_env.unwrapped
self.env_channel = self.base_env._env._side_channel_manager._side_channels_dict[uuid.UUID('3f07928c-2b0e-494a-810b-5f0bbb7aaeca')]
self.k = 1
self.min_divergence = min_divergence
self.default_watch_position = {
'ball_info': {
'position': [0., 0.],
'velocity': [0., 0.]
},
'player_info': {
0: {
'position': [-8.190001, -1.2],
'rotation_y': 90.0,
'velocity': [0., 0.],
},
1: {
'position': [-8.190001, 1.2],
'rotation_y': 90.0,
'velocity': [0., 0.],
},
2: {
'position': [8.190001, 1.2],
'rotation_y': 270.0,
'velocity': [0., 0.],
},
3: {
'position': [8.190001, -1.2],
'rotation_y': 270.0,
'velocity': [0., 0.],
}
}
}
self.default_train_position = {
'ball_info': {
'position': [1.0909986, 1.8254881],
'velocity': [0., 0.]
},
'player_info': {
0: {
'position': [-9.031397, -1.2],
'rotation_y': 87.729774,
'velocity': [0., 0.],
},
1: {
'position': [-6.2403193, 1.2],
'rotation_y': 85.95333,
'velocity': [0., 0.],
},
2: {
'position': [6.4539313, 1.2],
'rotation_y': 277.19568,
'velocity': [0., 0.],
},
3: {
'position': [6.6643953, -1.2],
'rotation_y': 270.04953,
'velocity': [0., 0.],
}
}
}
VELOCITY_RANGE = 5
self.limits = {
'ball_info': {
'position': ([-10, 10], [-5, 5]),
'velocity': ([-VELOCITY_RANGE, VELOCITY_RANGE], [-VELOCITY_RANGE, VELOCITY_RANGE])
},
'player_info': {
0: {
'position': ([-5, 18], [-5, 5]),
'rotation_y': ([-80,270],),
'velocity': ([-VELOCITY_RANGE, VELOCITY_RANGE], [-VELOCITY_RANGE, VELOCITY_RANGE]),
},
1: {
'position': ([-5, 18], [-5, 5]),
'rotation_y': ([-80,270],),
'velocity': ([-VELOCITY_RANGE, VELOCITY_RANGE], [-VELOCITY_RANGE, VELOCITY_RANGE]),
},
2: {
'position': ([-18, 5], [-5, 5]),
'rotation_y':([-270,80],),
'velocity': ([-VELOCITY_RANGE, VELOCITY_RANGE], [-VELOCITY_RANGE, VELOCITY_RANGE]),
},
3: {
'position': ([-18, 5], [-5, 5]),
'rotation_y': ([-270,80],),
'velocity': ([-VELOCITY_RANGE, VELOCITY_RANGE], [-VELOCITY_RANGE, VELOCITY_RANGE]),
}
}
}
def reset(self):
obs = self.env.reset()
base = self.default_watch_position#np.random.choice([self.default_train_position, self.default_watch_position])
max_divergence = np.random.random()
if max_divergence < self.min_divergence:
state = base
max_divergence = 0
else:
state = copy.deepcopy(base)
for data_point, limits in self.limits['ball_info'].items():
if data_point not in self.randomize['ball']:
continue
p1 = np.random.uniform(limits[0][0],limits[0][1])
if len(limits) == 2:
p2 = np.random.uniform(limits[1][0],limits[1][1])
state['ball_info'][data_point][0] += p1*max_divergence*self.k
state['ball_info'][data_point][1] += p2*max_divergence*self.k
else:
state['ball_info'][data_point] += p1
for agent_id in self.limits['player_info']:
for data_point, limits in self.limits['player_info'][agent_id].items():
if data_point not in self.randomize['player']:
continue
p1 = np.random.uniform(limits[0][0],limits[0][1])
if len(limits) == 2:
p2 = np.random.uniform(limits[1][0],limits[1][1])
state['player_info'][agent_id][data_point][0] += p1*max_divergence*self.k
state['player_info'][agent_id][data_point][1] += p2*max_divergence*self.k
else:
state['player_info'][agent_id][data_point] += p1*max_divergence*self.k
#print("Randomizing ambient", max_divergence, self.k)
#print("setted state", state)
self.env_channel.set_parameters(
ball_state = state['ball_info'],
players_states = state['player_info']
)
return obs
class CurriculumWrapper(gym.core.Wrapper):
def __init__(self, env):
super(CurriculumWrapper, self).__init__(env)
self.env = env
self.current_env = env
self.cur_level = 0
self.number_of_tasks = 6
def reset(self):
return self.current_env.reset()
def step(self, action):
return self.current_env.step(action)
#@override(TaskSettableEnv)
def sample_tasks(self, n_tasks):
"""Implement this to sample n random tasks."""
return [random.randint(0, self.number_of_tasks) for _ in range(n_tasks)]
#@override(TaskSettableEnv)
def set_task(self, task) -> None:
"""Sets the specified task to the current environment
Args:
task: task of the meta-learning environment
"""
if task == 0:
self.current_env = self.env
elif task == 1:
randomize = {'ball': [], 'player': ['rotation_y']}
self.current_env = RandomEnvWrapper(self.env, randomize=randomize)
elif task == 2:
randomize = {'ball': ['position'], 'player': ['rotation_y']}
self.current_env = RandomEnvWrapper(self.env, randomize=randomize)
elif task == 3:
randomize = {'ball': ['position'], 'player': ['rotation_y', 'velocity']}
self.current_env = RandomEnvWrapper(self.env, randomize=randomize)
elif task == 4:
randomize = {'ball': ['position', 'velocity'], 'player': ['rotation_y', 'velocity']}
self.current_env = RandomEnvWrapper(self.env, randomize=randomize)
elif task == 5:
randomize = {'ball': ['position', 'velocity'], 'player': ['rotation_y', 'velocity']}
self.current_env = RandomEnvWrapper(self.env, randomize=randomize, min_divergence=0.5, k=0.7)
else:
print(f"Invalid Task number {task}, setting enviroment task 0")
self.current_env = self.env
task = 0
self.cur_level = task
#@override(TaskSettableEnv)
def get_task(self):
"""Implement this to get the current task (curriculum level)."""
return self.cur_level
def next_task(self):
self.set_task((self.cur_level + 1) %self.number_of_tasks)