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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441 | from contextlib import suppress
import logging
import html
from timeit import default_timer
import sys
import weakref
from tlz import valmap
from tornado.ioloop import IOLoop
from .progress import format_time, Progress, MultiProgress
from ..core import connect, coerce_to_address, CommClosedError
from ..client import default_client, futures_of
from ..protocol.pickle import dumps
from ..utils import key_split, is_kernel, LoopRunner, parse_timedelta
logger = logging.getLogger(__name__)
def get_scheduler(scheduler):
if scheduler is None:
return default_client().scheduler.address
return coerce_to_address(scheduler)
class ProgressBar:
def __init__(self, keys, scheduler=None, interval="100ms", complete=True):
self.scheduler = get_scheduler(scheduler)
self.client = None
for key in keys:
if hasattr(key, "client"):
self.client = weakref.ref(key.client)
break
self.keys = {k.key if hasattr(k, "key") else k for k in keys}
self.interval = parse_timedelta(interval, default="s")
self.complete = complete
self._start_time = default_timer()
@property
def elapsed(self):
return default_timer() - self._start_time
async def listen(self):
complete = self.complete
keys = self.keys
async def setup(scheduler):
p = Progress(keys, scheduler, complete=complete)
await p.setup()
return p
def function(scheduler, p):
result = {
"all": len(p.all_keys),
"remaining": len(p.keys),
"status": p.status,
}
if p.status == "error":
result.update(p.extra)
return result
self.comm = await connect(
self.scheduler, **(self.client().connection_args if self.client else {})
)
logger.debug("Progressbar Connected to scheduler")
await self.comm.write(
{
"op": "feed",
"setup": dumps(setup),
"function": dumps(function),
"interval": self.interval,
},
serializers=self.client()._serializers if self.client else None,
)
while True:
try:
response = await self.comm.read(
deserializers=self.client()._deserializers if self.client else None
)
except CommClosedError:
break
self._last_response = response
self.status = response["status"]
self._draw_bar(**response)
if response["status"] in ("error", "finished"):
await self.comm.close()
self._draw_stop(**response)
break
logger.debug("Progressbar disconnected from scheduler")
def _draw_stop(self, **kwargs):
pass
def __del__(self):
with suppress(AttributeError):
self.comm.abort()
class TextProgressBar(ProgressBar):
def __init__(
self,
keys,
scheduler=None,
interval="100ms",
width=40,
loop=None,
complete=True,
start=True,
**kwargs,
):
super().__init__(keys, scheduler, interval, complete)
self.width = width
self.loop = loop or IOLoop()
if start:
loop_runner = LoopRunner(self.loop)
loop_runner.run_sync(self.listen)
def _draw_bar(self, remaining, all, **kwargs):
frac = (1 - remaining / all) if all else 1.0
bar = "#" * int(self.width * frac)
percent = int(100 * frac)
elapsed = format_time(self.elapsed)
msg = "\r[{0:<{1}}] | {2}% Completed | {3}".format(
bar, self.width, percent, elapsed
)
with suppress(ValueError):
sys.stdout.write(msg)
sys.stdout.flush()
def _draw_stop(self, **kwargs):
sys.stdout.write("\r")
sys.stdout.flush()
class ProgressWidget(ProgressBar):
"""ProgressBar that uses an IPython ProgressBar widget for the notebook
See Also
--------
progress: User function
TextProgressBar: Text version suitable for the console
"""
def __init__(
self,
keys,
scheduler=None,
interval="100ms",
complete=False,
loop=None,
**kwargs,
):
super().__init__(keys, scheduler, interval, complete)
from ipywidgets import FloatProgress, HBox, VBox, HTML
self.elapsed_time = HTML("")
self.bar = FloatProgress(min=0, max=1, description="")
self.bar_text = HTML("")
self.bar_widget = HBox([self.bar_text, self.bar])
self.widget = VBox([self.elapsed_time, self.bar_widget])
def _ipython_display_(self, **kwargs):
IOLoop.current().add_callback(self.listen)
return self.widget._ipython_display_(**kwargs)
def _draw_stop(self, remaining, status, exception=None, **kwargs):
if status == "error":
self.bar.bar_style = "danger"
self.elapsed_time.value = (
'<div style="padding: 0px 10px 5px 10px"><b>Exception</b> '
"<tt>"
+ repr(exception)
+ "</tt>:"
+ format_time(self.elapsed)
+ " "
+ "</div>"
)
elif not remaining:
self.bar.bar_style = "success"
self.elapsed_time.value = (
'<div style="padding: 0px 10px 5px 10px"><b>Finished:</b> '
+ format_time(self.elapsed)
+ "</div>"
)
def _draw_bar(self, remaining, all, **kwargs):
ndone = all - remaining
self.elapsed_time.value = (
'<div style="padding: 0px 10px 5px 10px"><b>Computing:</b> '
+ format_time(self.elapsed)
+ "</div>"
)
self.bar.value = ndone / all if all else 1.0
self.bar_text.value = (
'<div style="padding: 0px 10px 0px 10px; text-align:right;">%d / %d</div>'
% (ndone, all)
)
class MultiProgressBar:
def __init__(
self,
keys,
scheduler=None,
func=key_split,
interval="100ms",
complete=False,
**kwargs,
):
self.scheduler = get_scheduler(scheduler)
self.client = None
for key in keys:
if hasattr(key, "client"):
self.client = weakref.ref(key.client)
break
self.keys = {k.key if hasattr(k, "key") else k for k in keys}
self.func = func
self.interval = interval
self.complete = complete
self._start_time = default_timer()
@property
def elapsed(self):
return default_timer() - self._start_time
async def listen(self):
complete = self.complete
keys = self.keys
func = self.func
async def setup(scheduler):
p = MultiProgress(keys, scheduler, complete=complete, func=func)
await p.setup()
return p
def function(scheduler, p):
result = {
"all": valmap(len, p.all_keys),
"remaining": valmap(len, p.keys),
"status": p.status,
}
if p.status == "error":
result.update(p.extra)
return result
self.comm = await connect(
self.scheduler, **(self.client().connection_args if self.client else {})
)
logger.debug("Progressbar Connected to scheduler")
await self.comm.write(
{
"op": "feed",
"setup": dumps(setup),
"function": dumps(function),
"interval": self.interval,
}
)
while True:
response = await self.comm.read(
deserializers=self.client()._deserializers if self.client else None
)
self._last_response = response
self.status = response["status"]
self._draw_bar(**response)
if response["status"] in ("error", "finished"):
await self.comm.close()
self._draw_stop(**response)
break
logger.debug("Progressbar disconnected from scheduler")
def _draw_stop(self, **kwargs):
pass
def __del__(self):
with suppress(AttributeError):
self.comm.abort()
class MultiProgressWidget(MultiProgressBar):
"""Multiple progress bar Widget suitable for the notebook
Displays multiple progress bars for a computation, split on computation
type.
See Also
--------
progress: User-level function <--- use this
MultiProgress: Non-visualization component that contains most logic
ProgressWidget: Single progress bar widget
"""
def __init__(
self,
keys,
scheduler=None,
minimum=0,
interval=0.1,
func=key_split,
complete=False,
**kwargs,
):
super().__init__(keys, scheduler, func, interval, complete)
from ipywidgets import VBox
self.widget = VBox([])
def make_widget(self, all):
from ipywidgets import FloatProgress, HBox, VBox, HTML
self.elapsed_time = HTML("")
self.bars = {key: FloatProgress(min=0, max=1, description="") for key in all}
self.bar_texts = {key: HTML("") for key in all}
self.bar_labels = {
key: HTML(
'<div style="padding: 0px 10px 0px 10px;'
" text-align:left; word-wrap: "
'break-word;">'
+ html.escape(key.decode() if isinstance(key, bytes) else key)
+ "</div>"
)
for key in all
}
def keyfunc(kv):
""" Order keys by most numerous, then by string name """
return kv[::-1]
key_order = [k for k, v in sorted(all.items(), key=keyfunc, reverse=True)]
self.bar_widgets = VBox(
[
HBox([self.bar_texts[key], self.bars[key], self.bar_labels[key]])
for key in key_order
]
)
self.widget.children = (self.elapsed_time, self.bar_widgets)
def _ipython_display_(self, **kwargs):
IOLoop.current().add_callback(self.listen)
return self.widget._ipython_display_(**kwargs)
def _draw_stop(self, remaining, status, exception=None, key=None, **kwargs):
for k, v in remaining.items():
if not v:
self.bars[k].bar_style = "success"
else:
self.bars[k].bar_style = "danger"
if status == "error":
# self.bars[self.func(key)].bar_style = 'danger' # TODO
self.elapsed_time.value = (
'<div style="padding: 0px 10px 5px 10px"><b>Exception</b> '
+ "<tt>"
+ repr(exception)
+ "</tt>:"
+ format_time(self.elapsed)
+ " "
+ "</div>"
)
else:
self.elapsed_time.value = (
'<div style="padding: 0px 10px 5px 10px"><b>Finished:</b> '
+ format_time(self.elapsed)
+ "</div>"
)
def _draw_bar(self, remaining, all, status, **kwargs):
if self.keys and not self.widget.children:
self.make_widget(all)
for k, ntasks in all.items():
ndone = ntasks - remaining[k]
self.elapsed_time.value = (
'<div style="padding: 0px 10px 5px 10px"><b>Computing:</b> '
+ format_time(self.elapsed)
+ "</div>"
)
self.bars[k].value = ndone / ntasks if ntasks else 1.0
self.bar_texts[k].value = (
'<div style="padding: 0px 10px 0px 10px; text-align: right">%d / %d</div>'
% (ndone, ntasks)
)
def progress(*futures, notebook=None, multi=True, complete=True, **kwargs):
"""Track progress of futures
This operates differently in the notebook and the console
* Notebook: This returns immediately, leaving an IPython widget on screen
* Console: This blocks until the computation completes
Parameters
----------
futures: Futures
A list of futures or keys to track
notebook: bool (optional)
Running in the notebook or not (defaults to guess)
multi: bool (optional)
Track different functions independently (defaults to True)
complete: bool (optional)
Track all keys (True) or only keys that have not yet run (False)
(defaults to True)
Notes
-----
In the notebook, the output of `progress` must be the last statement
in the cell. Typically, this means calling `progress` at the end of a
cell.
Examples
--------
>>> progress(futures) # doctest: +SKIP
[########################################] | 100% Completed | 1.7s
"""
futures = futures_of(futures)
if not isinstance(futures, (set, list)):
futures = [futures]
if notebook is None:
notebook = is_kernel() # often but not always correct assumption
if notebook:
if multi:
bar = MultiProgressWidget(futures, complete=complete, **kwargs)
else:
bar = ProgressWidget(futures, complete=complete, **kwargs)
return bar
else:
TextProgressBar(futures, complete=complete, **kwargs)
|