-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
217 lines (147 loc) · 5.17 KB
/
utils.py
File metadata and controls
217 lines (147 loc) · 5.17 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
""" general utilities that might find use in many seperate cases """
import numpy as np
import pandas as pd
import random
import torch
import sys
import os
import collections
class HistoryBuffer:
"""A buffer that keeps track of state visitation history."""
def __init__(self, bufferSize=10):
self.bufferSize = bufferSize
self.buffer = []
self.device = torch.device(
"cuda" if torch.cuda.is_available() else "cpu"
)
def addState(self, state):
""" add a state to the history buffer each state is assumed to be of
shape ( 1 x S ) """
if len(self.buffer) >= self.bufferSize:
del self.buffer[0] # remove the oldest state
self.buffer.append(state.cpu().numpy())
def getHistory(self):
"""
returns the 10 states in the buffer in the form of a torch tensor in
the order in which they were encountered
"""
arrSize = self.buffer[0].shape[1]
arrayHist = np.asarray(self.buffer)
arrayHist = np.reshape(arrayHist, (1, arrSize * self.bufferSize))
state = torch.from_numpy(arrayHist).to(self.device)
state = state.type(torch.cuda.FloatTensor)
return state
def to_oh(idx, size):
"""
creates a one-hot array of length 'size' and sets indexes in list 'idx' to
be ones.
params:
idx: list or numpy array of indices to be one.
size: size of output vector.
return:
output numpy vector of size ('size' x 1)
"""
out = np.zeros(size)
out[idx] = 1
return out
def reset_torch_state(dtype=torch.float32):
"""decorator to return a torch tensor from gym's env.reset() function.
:param f: function being decorated, in this case env.reset().
"""
def real_decorator(f):
"""real decorator, taking into account the dtype.
:param f: env.reset() being decorated.
"""
def inner(*args, **kwargs):
"""returns a torch tensor for cpu or gpu when appropriate."""
s = f(*args, **kwargs)
if torch.cuda.is_available():
return torch.from_numpy(s).cuda().type(dtype)
return torch.from_numpy(s).type(dtype)
return inner
return real_decorator
def step_torch_state(dtype=torch.float32):
"""decorator to return a torch tensor from gym's env.step() function.
:param f: function being decorated, in this case env.step().
"""
def real_decorator(f):
"""real decorator, taking into account the dtype.
:param f: env.step() being decorated.
"""
def inner(*args, **kwargs):
"""returns a torch tensor for cpu or gpu when appropriate."""
s, r, d, p = f(*args, **kwargs)
if torch.cuda.is_available():
s = torch.from_numpy(s).cuda().type(dtype)
else:
s = torch.from_numpy(s).type(dtype)
return s, r, d, p
return inner
return real_decorator
def identity_dec(f):
def same_func(*args, **kwargs):
return f(*args, **kwargs)
return same_func
def identity_wrapper(*output):
if len(output) == 1:
return output[0]
elif len(output) == 0:
return None
return output
def step_wrapper(s, r, d, p, dtype=torch.float):
if torch.cuda.is_available():
s = torch.from_numpy(s).cuda().type(dtype)
else:
s = torch.from_numpy(s).type(dtype)
return s, r, d, p
def reset_wrapper(s, dtype=torch.float):
if torch.cuda.is_available():
return torch.from_numpy(s).cuda().type(dtype)
return torch.from_numpy(s).type(dtype)
def copy_dict(in_dict):
"""
Makes a faster deep copy of a dictionary, provided it only includes
native types, numpy arrays, and other dicts containing the
aforementioned.
:param in_dict: dictionary to copy.
:type in_dict: dict.
:return: (deep) copy of input dictionary.
:rtype: dict.
"""
if in_dict is None:
return None
out_dict = {}
for key, val in in_dict.items():
if isinstance(val, np.ndarray):
out_dict[key] = val.copy()
elif isinstance(val, dict):
out_dict[key] = copy_dict(val)
else:
out_dict[key] = val
return out_dict
def seed_all(seed):
""" Use a seed to seed numpy, pytorch, and python random modules. """
np.random.seed(seed)
torch.manual_seed(seed)
random.seed(seed)
class HiddenPrints:
def __enter__(self):
self._original_stdout = sys.stdout
sys.stdout = open(os.devnull, "w")
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout.close()
sys.stdout = self._original_stdout
class DataTable:
def __init__(self):
self.data = collections.defaultdict(list)
def add_row(self, data_dict, step):
for key, val in data_dict.items():
if isinstance(val, torch.Tensor):
corrected_val = val.cpu().detach().item()
else:
corrected_val = val
self.data[key].append(corrected_val)
self.data['step'].append(step)
def write_csv(self, file):
pd_data = pd.DataFrame(self.data)
pd_data.to_csv(file)