-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathutils.py
335 lines (253 loc) · 8.45 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
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
"""
Utility objects used throughout the code base.
"""
import logging
import re
import subprocess
import sys
import threading
import time
import numpy as np
import progressbar
import tensorflow as tf
from nengo.exceptions import SimulationError
logger = logging.getLogger(__name__)
# check if GPU support is available
# note: we run this in a subprocess because list_physical_devices()
# will fix certain process-level TensorFlow configuration
# options the first time it is called
tf_gpu_installed = not subprocess.call(
[
sys.executable,
"-c",
"import sys; "
"import tensorflow as tf; "
"sys.exit(len(tf.config.list_physical_devices('GPU')) == 0)",
]
)
def sanitize_name(name):
"""
Remove illegal TensorFlow name characters from string.
Valid TensorFlow name characters are ``[A-Za-z0-9_.\\-/]``
Parameters
----------
name : str
Name to be sanitized
Returns
-------
sanitized : str
Sanitized name
"""
if not isinstance(name, str):
name = str(name)
name = name.replace(" ", "_")
name = name.replace(":", "_")
valid_exp = re.compile(r"[A-Za-z0-9_.\-/]")
return "".join([c for c in name if valid_exp.match(c)])
def function_name(func, sanitize=True):
"""
Get the name of the callable object ``func``.
Parameters
----------
func : callable
Callable object (e.g., function, callable class)
sanitize : bool
If True, remove any illegal TensorFlow name characters from name
Returns
-------
name : str
Name of ``func`` (optionally sanitized)
"""
name = getattr(func, "__name__", func.__class__.__name__)
if sanitize:
name = sanitize_name(name)
return name
def align_func(output_dtype):
"""
Decorator that ensures the output of ``func`` is a valid
`~numpy.ndarray` with the given dtype.
Parameters
----------
output_dtype : str or ``tf.DType`` or `~numpy.dtype`
Desired dtype of function output(s)
Raises
------
``nengo.exceptions.SimulationError``
If the function returns ``None`` or a non-finite value.
"""
if isinstance(output_dtype, tf.DType):
output_dtype = output_dtype.as_numpy_dtype
def apply_align(func):
def aligned_func(*args):
output = func(*args)
if output is None:
raise SimulationError(
f"Function '{function_name(func, sanitize=False)}' returned None"
)
try:
if not np.all(np.isfinite(output)):
raise SimulationError(
f"Function '{function_name(func, sanitize=False)}' returned "
f"invalid value {output!r}"
)
except (TypeError, ValueError) as e:
raise SimulationError(
f"Function '{function_name(func, sanitize=False)}' returned a "
f"value {output!r} of invalid type '{type(output).__name__}'"
) from e
output = np.asarray(output, dtype=output_dtype)
return output
return aligned_func
return apply_align
class MessageBar(progressbar.BouncingBar):
"""
ProgressBar widget for progress bars with possibly unknown duration.
Parameters
----------
msg : str
A message to be displayed in the middle of the progress bar
finish_msg : str
A message to be displayed when the progress bar is finished
"""
def __init__(self, msg="", finish_msg="", **kwargs):
super().__init__(**kwargs)
self.msg = msg
self.finish_msg = finish_msg
def __call__(self, progress, data, width):
if progress.end_time:
return self.finish_msg
if progress.max_value is progressbar.UnknownLength:
bar = progressbar.BouncingBar
else:
bar = progressbar.Bar
line = bar.__call__(self, progress, data, width)
if data["percentage"] is None:
msg = self.msg
else:
msg = f"{self.msg} ({int(data['percentage'])}%)"
offset = width // 2 - len(msg) // 2
return line[:offset] + msg + line[offset + len(msg) :]
class ProgressBar(progressbar.ProgressBar): # pylint: disable=too-many-ancestors
"""
Handles progress bar display for some tracked process.
Parameters
----------
present : str
Description of process in present (e.g., "Simulating")
past : str
Description of process in past (e.g., "Simulation")
max_value : int or None
The maximum number of steps in the tracked process (or ``None`` if
the maximum number of steps is unknown)
Notes
-----
Launches a separate thread to handle the progress bar display updates.
"""
def __init__(self, present="", past=None, max_value=1, **kwargs):
self.present = present
self.sub_bar = None
self.finished = None
if past is None:
past = present
self.msg_bar = MessageBar(msg=present, finish_msg=f"{past} finished in")
widgets = [self.msg_bar, " "]
if max_value is None:
widgets.append(progressbar.Timer(format="%(elapsed)s"))
else:
widgets.append(
progressbar.ETA(format="ETA: %(eta)s", format_finished="%(elapsed)s")
)
def update_thread():
while not self.finished:
if self.sub_bar is None or self.sub_bar.finished:
self.update()
time.sleep(0.001)
self.thread = threading.Thread(target=update_thread)
self.thread.daemon = True
if max_value is None:
max_value = progressbar.UnknownLength
super().__init__(
poll_interval=0.1,
widgets=widgets,
fd=sys.stdout,
max_value=max_value,
**kwargs,
)
def start(self, **kwargs):
"""Start tracking process, initialize display."""
super().start(**kwargs)
self.finished = False
self.thread.start()
return self
def finish(self, **kwargs):
"""Stop tracking process, finish display."""
if self.sub_bar is not None and self.sub_bar.finished is False:
self.sub_bar.finish()
self.finished = True
self.thread.join()
super().finish(**kwargs)
def step(self):
"""
Advance the progress bar one step.
"""
self.value += 1
def sub(self, msg=None, **kwargs):
"""
Creates a new progress bar for tracking a sub-process.
Parameters
----------
msg : str
Description of sub-process
"""
if self.sub_bar is not None and self.sub_bar.finished is False:
self.sub_bar.finish()
self.sub_bar = SubProgressBar(
present=f"{self.present}: {msg}" if msg else self.present, **kwargs
)
return self.sub_bar
@property
def max_steps(self):
"""
Alias for max_value to allow this to work with Nengo progress bar
interface.
"""
return self.max_value
@max_steps.setter
def max_steps(self, n):
self.max_value = n
def __enter__(self):
super().__enter__()
return self.start()
def __next__(self):
"""Wraps an iterable using this progress bar."""
try:
assert self.start_time is not None
self.step()
value = next(self._iterable)
return value
except StopIteration:
self.finish()
raise
class SubProgressBar(ProgressBar): # pylint: disable=too-many-ancestors
"""
A progress bar representing a sub-task within an overall progress bar.
"""
def finish(self, **kwargs):
"""Finishing a sub-progress bar doesn't start a new line."""
super().finish(end="\r", **kwargs)
class NullProgressBar(progressbar.NullBar): # pylint: disable=too-many-ancestors
"""
A progress bar that does nothing.
Used to replace ProgressBar when we want to disable output.
"""
def __init__(self, present="", past=None, max_value=1, **kwargs):
super().__init__(max_value=max_value, **kwargs)
def sub(self, *args, **kwargs):
"""
Noop for creating a sub-progress bar.
"""
return self
def step(self, **kwargs):
"""
Noop for incrementing the progress bar.
"""