-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.py
228 lines (182 loc) · 5.86 KB
/
init.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
"""
Module init provides functions useful when initialising simulations or
analysis.
(taken from https://github.com/yketa/active_particles/tree/master/init.py)
"""
from os.path import join as joinpath
from os.path import exists as pathexists
from os import makedirs
from os import environ as envvar
from shutil import rmtree as rmr
import sys
import atexit
import pickle
from collections import OrderedDict
from numbers import Number
import numpy as np
def to_vartype(input, default=None, vartype=str):
"""
Returns input converted to vartype or default if the conversion fails.
Parameters
----------
input : *
Input value (of any type).
default : *
Default value to return if conversion fails.
vartype : data type
Desired data type. (default: string)
Returns
-------
output : vartype or type(default)
Input converted to vartype data type or default.
"""
if vartype == bool and input == 'False': return False # special custom case
try:
try:
return vartype(input)
except ValueError: return vartype(eval(input))
except: return default
def set_env(var_name, var_value):
"""
Sets environment variable var_name value to str(var_value).
Parameters
----------
var_name : string
Environment variable name.
var_value : *
Environment variable value.
NOTE: if var_value=None, then the environment variable is unset
"""
if var_value == None:
if var_name in envvar: del envvar[var_name]
else: envvar[var_name] = str(var_value)
def get_env(var_name, default=None, vartype=str):
"""
Returns environment variable with desired data type.
WARNING: get_env function uses eval function to evaluate environment
variable strings if necessary, therefore extra cautious is recommended when
using it.
Parameters
----------
var_name : string
Name of environment variable.
default : *
Default value to return if environment variable does not exist or if
conversion fails. (default: None)
vartype : data type
Desired data type. (default: string)
Returns
-------
var : vartype or type(default)
Environment variable converted to vartype data type of default.
"""
try:
return to_vartype(envvar[var_name], default=default, vartype=vartype)
except: return default
def get_env_list(var_name, delimiter=':', default=None, vartype=str):
"""
Returns list from environment variable containing values delimited with
delimiter to be converted to vartype data type or taken to be default if
the conversion fails.
NOTE: Returns empty list if the environment variable does not exist or is
an empty string.
Parameters
----------
var_name : string
Name of environment variable.
delimiter : string
Pattern which delimits values to be evaluated in environment variable.
default : *
Default value to return if individual value in environment variable
does not exist or if conversion fails. (default: None)
vartype : data type
Desired data type. (default: string)
Returns
-------
var_list : list of vartype of type(default)
List of individual environment variables values converted to vartype
data type or default.
"""
if not(var_name in envvar) or envvar[var_name] == '': return []
return list(map(
lambda var: to_vartype(var, default=default, vartype=vartype),
envvar[var_name].split(delimiter)
))
class StdOut:
"""
Enables to set output stream to file and revert this setting.
"""
def __init__(self):
"""
Saves original standard output as attribute.
"""
self.stdout = sys.stdout # original standard output
def set(self, output_file):
"""
Sets output to file.
Parameters
----------
output_file : file object
Output file.
"""
try:
self.output_file.close() # if output file already set, close it
except AttributeError: pass
self.output_file = output_file # output file
sys.stdout = self.output_file # new output stream
atexit.register(self.revert) # close file when exiting script
def revert(self):
"""
Revers to original standard output.
"""
try:
self.output_file.close()
sys.stdout = self.stdout # revert to original standart output
except AttributeError: pass # no custom output was set
def mkdir(directory, replace=False):
"""
Creates directory if not existing, erases and recreates it if replace is
set to True.
Parameters
----------
directory : string
Name of directory.
replace : bool
Erase and recreate directory. (default: False)
"""
if pathexists(directory) and replace: rmr(directory)
makedirs(directory, exist_ok=True)
def isnumber(variable):
"""
Returns True if variable is a number, False otherwise.
Parameters
----------
variable : *
Variable to check.
Returns
-------
variableisnumber : bool
Is variable a number?
"""
return isinstance(variable, Number)
def linframes(init_frame, tot_frames, max_frames):
"""
Returns linearly spaced indexes in [|init_frame; tot_frames - 1|], with a
maximum of max_frames indexes.
Parameters
----------
init_frame : int
Index of initial frame.
tot_frames : int
Total number of frames.
max_frames : int
Maximum number of frames.
Returns
-------
frames : 1D Numpy array
Array of frame numbers in ascending order.
"""
return np.array(list(OrderedDict.fromkeys(map(
int,
np.linspace(init_frame, tot_frames - 1, max_frames, dtype=int)
))))