-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtoolkit.py
181 lines (154 loc) · 5.5 KB
/
toolkit.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
import os
import json
import numpy as np
import random
import string
import matplotlib.pyplot as plt
import h5py
def hdf5_io(mode, file_name, variable_name='data', data=None):
'''
r Readonly, file must exist (default)
r+ Read/write, file must exist
w Create file, truncate if exists
w- or x Create file, fail if exists
a Read/write if exists, create otherwise
'''
if not file_name.endswith('.h5'):
file_name += '.h5'
f = h5py.File(file_name, mode)
if mode.count('r') <= 0 and data is not None:
if type(data) is not dict:
f.create_dataset(variable_name, data=data)
else:
for key, value in data.items():
f.create_dataset(key, data=value)
f.close()
elif mode.count('r') > 0 and data is None:
data = f[variable_name][()]
f.close()
return data
else:
raise ValueError('Wrong arguments!')
def exp_filter(_x, tau_n=5, n=5):
l = int(tau_n * n)
kernel = np.exp(-np.arange(l) / tau_n)
kernel = kernel / np.sum(kernel)
if len(_x.shape) > 1:
_x = _x.flatten()
return np.convolve(_x, kernel)[:-l + 1]
def cm2inch(*tupl):
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl)
def apply_style(ax, scale=1, ylabel=.4):
ax.set_xlabel(ax.get_xlabel(), fontsize=6 * scale)
ax.set_ylabel(ax.get_ylabel(), fontsize=6 * scale)
ax.spines['left'].set_linewidth(.5 * scale)
ax.spines['bottom'].set_linewidth(.5 * scale)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.xaxis.set_tick_params(labelsize=5 * scale, width=.5 * scale, length=3 * scale)
ax.yaxis.set_tick_params(labelsize=5 * scale, width=.5 * scale, length=3 * scale)
ax.yaxis.set_label_coords(-ylabel / 7, 0.5)
def do_inset_colorbar(_ax, _p, _label, loc='right'):
if loc == 'right':
bg_pos = [.925, .1, .075, .8]
in_pos = [.95, .2, .025, .6]
elif loc == 'left':
bg_pos = [.025, .1, .15, .8]
in_pos = [.05, .2, .025, .6]
elif loc == 'middle':
bg_pos = [.025 + .5, .1, .15, .8]
in_pos = [.05 + .5, .2, .025, .6]
else:
raise NotImplementedError(f'must implement location {loc}')
bg_ax = _ax.inset_axes(bg_pos)
bg_ax.set_xticks([])
bg_ax.set_yticks([])
[_a.set_visible(False) for _a in bg_ax.spines.values()]
inset_ax = _ax.inset_axes(in_pos)
cbar = plt.colorbar(_p, cax=inset_ax)
cbar.outline.set_visible(False)
cbar.ax.set_ylabel(_label)
def get_random_identifier(prefix='', length=4):
random_identifier = ''.join(
random.choice(string.ascii_lowercase + string.digits) for _ in range(length))
sim_name = prefix + random_identifier
return sim_name
def split_1(_s):
l = []
cc = ''
for i in range(len(_s)):
if _s[i] != ',':
cc += _s[i]
else:
if cc.count('[') > 0 and cc.count(']') == 0:
cc += _s[i]
else:
l.append(cc)
cc = ''
if cc != '':
l.append(cc)
return l
def split_2(_s):
l = []
if _s.count('[') == 0:
return [_s]
else:
sub = _s[_s.index('[') + 1:_s.index(']')]
base = _s[:_s.index('[')]
kk = sub.split(',')
for tt in kk:
if tt.count('-') > 0:
num_a = tt[:tt.index('-')]
num_b = tt[tt.index('-') + 1:]
digit_len = len(num_a)
assert len(num_a) == len(num_b)
l.extend([base + str(a).zfill(digit_len) for a in range(int(tt[:tt.index('-')]), int(tt[tt.index('-') + 1:]) + 1)])
else:
l.append(base + tt)
return l
def expand_slurm_nodes(_s):
l = []
l1 = split_1(_s)
for a in l1:
l.extend(split_2(a))
return l
def get_tf_config_from_nodelist(node_list, port=12778):
cluster = [a + ':' + str(port) for a in node_list]
tf_config = dict(cluster=cluster, task=dict(type='worker', index=os.environ.get('SLURM_PROCID', 0)))
return json.dumps(tf_config, indent=4)
def set_tf_config_from_slurm(port=12778):
if 'SLURM_JOB_NODELIST' not in os.environ.keys():
return 1, 0
node_list = expand_slurm_nodes(os.environ['SLURM_JOB_NODELIST'])
node_list = [a + 'i.juwels' for a in node_list if a.startswith('jwb')]
cluster = dict(worker=[a + ':' + str(port) for a in node_list])
task_id = int(os.environ['SLURM_PROCID'])
new_tf_config = dict(cluster=cluster, task=dict(type='worker', index=task_id))
tf_config_str = os.environ.get('TF_CONFIG', '')
if tf_config_str == '':
tf_config = dict()
else:
tf_config = json.loads(tf_config_str)
for k, v in new_tf_config.items():
tf_config[k] = v
os.environ['TF_CONFIG'] = json.dumps(tf_config, indent=4)
return len(node_list), task_id
if __name__ == '__main__':
set_tf_config_from_slurm()
print(os.environ['TF_CONFIG'])
quit()
s = 'compute-b24-[1-3,5-9],compute-b25-[1,4,8]'
node_list = expand_slurm_nodes(s)
print(get_tf_config_from_nodelist(node_list))
quit()
print()
s = 'jwc09n[000,003]'
print(expand_slurm_nodes(s))
print()
s = 'jwc09n000'
print(expand_slurm_nodes(s))
print()