-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
107 lines (80 loc) · 3.23 KB
/
utils.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
#!/usr/local/bin/python3
# The MIT License (MIT)
# Copyright (c) 2022 Prasanth Suresh and Yikang Gui
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from tqdm import tqdm
import numpy as np
import torch
import torch as th
import sys
import os
# sys.path.append(os.getcwd() + f'/airl-ppo/')
from buffer import Buffer
def obs_as_tensor(obs, device='cpu'):
obs = th.tensor(obs).float().to(device)
if len(obs.shape) == 2:
return obs[None, :]
elif len(obs.shape) == 3:
return obs
def normalize(x):
return (x - x.mean()) / (x.std() + 1e-8)
def soft_update(target, source, tau):
for t, s in zip(target.parameters(), source.parameters()):
t.data.mul_(1.0 - tau)
t.data.add_(tau * s.data)
def disable_gradient(network):
for param in network.parameters():
param.requires_grad = False
def add_random_noise(action, std):
action += np.random.randn(*action.shape) * std
return action.clip(-1.0, 1.0)
def collect_demo(env, algo, buffer_size, device, std, p_rand, seed=0):
env.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
buffer = Buffer(
buffer_size=buffer_size,
state_shape=env.observation_space.shape,
action_shape=env.action_space.shape,
device=device
)
total_return = 0.0
num_episodes = 0
state = env.reset()
t = 0
episode_return = 0.0
for _ in tqdm(range(1, buffer_size + 1)):
t += 1
if np.random.rand() < p_rand:
action = env.action_space.sample()
else:
action = algo.exploit(state)
action = add_random_noise(action, std)
next_state, reward, done, _ = env.step(action)
mask = False if t == env._max_episode_steps else done
buffer.append(state, action, reward, mask, next_state)
episode_return += reward
if done:
num_episodes += 1
total_return += episode_return
state = env.reset()
t = 0
episode_return = 0.0
state = next_state
print(f'Mean return of the expert is {total_return / num_episodes}')
return buffer