Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
1300 lines (1056 loc) · 39.7 KB
/
Copy pathutils.py
File metadata and controls
1300 lines (1056 loc) · 39.7 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
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from collections import namedtuple
import asyncio
import os
import sys
import signal
import operator
import uuid
from functools import reduce
from weakref import ref, WeakKeyDictionary
import types
import inspect
from inspect import Parameter, Signature
import itertools
from collections import Iterable
import numpy as np
from cycler import cycler
import logging
import datetime
from functools import wraps, partial
import threading
import time
from tqdm import tqdm
from tqdm._utils import _environ_cols_wrapper, _term_move_up, _unicode
import warnings
try:
# cytools is a drop-in replacement for toolz, implemented in Cython
from cytools import groupby
except ImportError:
from toolz import groupby
class Msg(namedtuple('Msg_base', ['command', 'obj', 'args', 'kwargs'])):
__slots__ = ()
def __new__(cls, command, obj=None, *args, **kwargs):
return super(Msg, cls).__new__(cls, command, obj, args, kwargs)
def __repr__(self):
return '{}: ({}), {}, {}'.format(
self.command, self.obj, self.args, self.kwargs)
class RunEngineControlException(Exception):
pass
class RequestAbort(RunEngineControlException):
pass
class RequestStop(RunEngineControlException):
pass
class RunEngineInterrupted(Exception):
pass
class NoReplayAllowed(Exception):
pass
class IllegalMessageSequence(Exception):
pass
class FailedPause(Exception):
pass
class FailedStatus(Exception):
'Exception to be raised if a SatusBase object reports done but failed'
class InvalidCommand(KeyError):
pass
class PlanHalt(GeneratorExit):
pass
class RampFail(RuntimeError):
...
PLAN_TYPES = (types.GeneratorType,)
try:
from types import CoroutineType
except ImportError:
# < py35
pass
else:
PLAN_TYPES = PLAN_TYPES + (CoroutineType, )
del CoroutineType
def ensure_generator(plan):
"""
Ensure that the input is a generator.
Parameters
----------
plan : iterable or iterator
Returns
-------
gen : coroutine
"""
if isinstance(plan, Msg):
return single_gen(plan)
gen = iter(plan) # no-op on generators; needed for classes
if not isinstance(gen, PLAN_TYPES):
# If plan does not support .send, we must wrap it in a generator.
gen = (msg for msg in gen)
return gen
def single_gen(msg):
'''Turn a single message into a plan
If ``lambda x: yield x`` were valid Python, this would be equivalent.
In Python 3.6 or 3.7 we might get lambda generators.
Parameters
----------
msg : Msg
a single message
Yields
------
msg : Msg
the input message
'''
return (yield msg)
class SignalHandler:
def __init__(self, sig, log=None):
self.sig = sig
self.interrupted = False
self.count = 0
self.log = log
def __enter__(self):
self.interrupted = False
self.released = False
self.count = 0
self.original_handler = signal.getsignal(self.sig)
def handler(signum, frame):
self.interrupted = True
self.count += 1
if self.log is not None:
self.log.debug('SignalHandler caught SIGINT; count is %r',
self.count)
if self.count > 10:
orig_func = self.original_handler
self.release()
orig_func(signum, frame)
signal.signal(self.sig, handler)
return self
def __exit__(self, type, value, tb):
self.release()
def release(self):
if self.released:
return False
signal.signal(self.sig, self.original_handler)
self.released = True
return True
class SigintHandler(SignalHandler):
def __init__(self, RE):
super().__init__(signal.SIGINT, log=RE.log)
self.RE = RE
self.last_sigint_time = None # time most recent SIGINT was processed
self.num_sigints_processed = 0 # count SIGINTs processed
def __enter__(self):
self.RE.loop.call_later(0.1, self.check_for_signals)
return super().__enter__()
def check_for_signals(self):
# Check for pause requests from keyboard.
if self.RE.state.is_running and (not self.RE._interrupted):
if self.count > self.num_sigints_processed:
self.num_sigints_processed = self.count
self.log.debug("RunEngine caught a new SIGINT")
self.last_sigint_time = time.time()
if self.count == 1:
# Ctrl-C once -> request a deferred pause
if not self.RE._deferred_pause_requested:
self.RE.loop.call_soon(self.RE.request_pause, True)
print("A 'deferred pause' has been requested. The "
"RunEngine will pause at the next checkpoint. "
"To pause immediately, hit Ctrl+C again in the "
"next 10 seconds.")
elif self.count > 1:
# - Ctrl-C twice within 10 seconds -> hard pause
self.log.debug("RunEngine detected two SIGINTs. "
"A hard pause will be requested.")
self.RE.loop.call_soon(self.RE.request_pause, False)
else:
# No new SIGINTs to process.
if self.num_sigints_processed > 0:
if time.time() - self.last_sigint_time > 10:
self.log.debug("It has been 10 seconds since the "
"last SIGINT. Resetting SIGINT "
"handler.")
# It's been 10 seconds since the last SIGINT. Reset.
self.num_sigints_processed = 0
self.count = 0
self.interrupted = False
self.last_sigint_time = None
if not self.released:
self.RE.loop.call_later(0.1, self.check_for_signals)
class CallbackRegistry:
"""
See matplotlib.cbook.CallbackRegistry. This is a simplified since
``bluesky`` is python3.4+ only!
"""
def __init__(self, ignore_exceptions=False, allowed_sigs=None):
self.ignore_exceptions = ignore_exceptions
self.allowed_sigs = allowed_sigs
self.callbacks = dict()
self._cid = 0
self._func_cid_map = {}
def __getstate__(self):
# We cannot currently pickle the callables in the registry, so
# return an empty dictionary.
return {}
def __setstate__(self, state):
# re-initialise an empty callback registry
self.__init__()
def connect(self, sig, func):
"""Register ``func`` to be called when ``sig`` is generated
Parameters
----------
sig
func
Returns
-------
cid : int
The callback index. To be used with ``disconnect`` to deregister
``func`` so that it will no longer be called when ``sig`` is
generated
"""
if self.allowed_sigs is not None:
if sig not in self.allowed_sigs:
raise ValueError("Allowed signals are {0}".format(
self.allowed_sigs))
self._func_cid_map.setdefault(sig, WeakKeyDictionary())
# Note proxy not needed in python 3.
# TODO rewrite this when support for python2.x gets dropped.
proxy = _BoundMethodProxy(func)
if proxy in self._func_cid_map[sig]:
return self._func_cid_map[sig][proxy]
proxy.add_destroy_callback(self._remove_proxy)
self._cid += 1
cid = self._cid
self._func_cid_map[sig][proxy] = cid
self.callbacks.setdefault(sig, dict())
self.callbacks[sig][cid] = proxy
return cid
def _remove_proxy(self, proxy):
# need the list because `del self._func_cid_map[sig]` mutates the dict
for sig, proxies in list(self._func_cid_map.items()):
try:
del self.callbacks[sig][proxies[proxy]]
except KeyError:
pass
if len(self.callbacks[sig]) == 0:
del self.callbacks[sig]
del self._func_cid_map[sig]
def disconnect(self, cid):
"""Disconnect the callback registered with callback id *cid*
Parameters
----------
cid : int
The callback index and return value from ``connect``
"""
for eventname, callbackd in self.callbacks.items():
try:
del callbackd[cid]
except KeyError:
continue
else:
for sig, functions in self._func_cid_map.items():
for function, value in list(functions.items()):
if value == cid:
del functions[function]
return
def process(self, sig, *args, **kwargs):
"""Process ``sig``
All of the functions registered to receive callbacks on ``sig``
will be called with ``args`` and ``kwargs``
Parameters
----------
sig
args
kwargs
"""
if self.allowed_sigs is not None:
if sig not in self.allowed_sigs:
raise ValueError("Allowed signals are {0}".format(
self.allowed_sigs))
exceptions = []
if sig in self.callbacks:
for cid, func in list(self.callbacks[sig].items()):
try:
func(*args, **kwargs)
except ReferenceError:
self._remove_proxy(func)
except Exception as e:
if self.ignore_exceptions:
exceptions.append((e, sys.exc_info()[2]))
else:
raise
return exceptions
class _BoundMethodProxy:
'''
Our own proxy object which enables weak references to bound and unbound
methods and arbitrary callables. Pulls information about the function,
class, and instance out of a bound method. Stores a weak reference to the
instance to support garbage collection.
@organization: IBM Corporation
@copyright: Copyright (c) 2005, 2006 IBM Corporation
@license: The BSD License
Minor bugfixes by Michael Droettboom
'''
def __init__(self, cb):
self._hash = hash(cb)
self._destroy_callbacks = []
try:
try:
self.inst = ref(cb.__self__, self._destroy)
except TypeError:
self.inst = None
self.func = cb.__func__
self.klass = cb.__self__.__class__
except AttributeError:
self.inst = None
self.func = cb
self.klass = None
def add_destroy_callback(self, callback):
self._destroy_callbacks.append(_BoundMethodProxy(callback))
def _destroy(self, wk):
for callback in self._destroy_callbacks:
try:
callback(self)
except ReferenceError:
pass
def __getstate__(self):
d = self.__dict__.copy()
# de-weak reference inst
inst = d['inst']
if inst is not None:
d['inst'] = inst()
return d
def __setstate__(self, statedict):
self.__dict__ = statedict
inst = statedict['inst']
# turn inst back into a weakref
if inst is not None:
self.inst = ref(inst)
def __call__(self, *args, **kwargs):
'''
Proxy for a call to the weak referenced object. Take
arbitrary params to pass to the callable.
Raises `ReferenceError`: When the weak reference refers to
a dead object
'''
if self.inst is not None and self.inst() is None:
raise ReferenceError
elif self.inst is not None:
# build a new instance method with a strong reference to the
# instance
mtd = types.MethodType(self.func, self.inst())
else:
# not a bound method, just return the func
mtd = self.func
# invoke the callable and return the result
return mtd(*args, **kwargs)
def __eq__(self, other):
'''
Compare the held function and instance with that held by
another proxy.
'''
try:
if self.inst is None:
return self.func == other.func and other.inst is None
else:
return self.func == other.func and self.inst() == other.inst()
except Exception:
return False
def __ne__(self, other):
'''
Inverse of __eq__.
'''
return not self.__eq__(other)
def __hash__(self):
return self._hash
# The following two code blocks are adapted from David Beazley's
# 'Python 3 Metaprogramming' https://www.youtube.com/watch?v=sPiWg5jSoZI
class StructMeta(type):
def __new__(cls, name, bases, clsdict):
clsobj = super().__new__(cls, name, bases, clsdict)
args_params = [Parameter(name, Parameter.POSITIONAL_OR_KEYWORD)
for name in clsobj._fields]
kwargs_params = [Parameter(name, Parameter.KEYWORD_ONLY, default=None)
for name in ['md']]
sig = Signature(args_params + kwargs_params)
setattr(clsobj, '__signature__', sig)
return clsobj
class Struct(metaclass=StructMeta):
"The _fields of any subclass become its attritubes and __init__ args."
_fields = []
def __init__(self, *args, **kwargs):
# Now bind default values of optional arguments.
# If it seems like there should be a cleaner way to do this, see
# http://bugs.python.org/msg221104
bound = self.__signature__.bind(*args, **kwargs)
for name, param in self.__signature__.parameters.items():
if (name not in bound.arguments and
param.default is not inspect._empty):
bound.arguments[name] = param.default
for name, val in bound.arguments.items():
setattr(self, name, val)
self.flyers = []
def set(self, **kwargs):
"Update attributes as keyword arguments."
for attr, val in kwargs.items():
setattr(self, attr, val)
SUBS_NAMES = ['all', 'start', 'stop', 'event', 'descriptor']
def normalize_subs_input(subs):
"Accept a callable, a list, or a dict. Normalize to a dict of lists."
normalized = {name: [] for name in SUBS_NAMES}
if subs is None:
pass
elif callable(subs):
normalized['all'].append(subs)
elif hasattr(subs, 'items'):
for key, funcs in list(subs.items()):
if key not in SUBS_NAMES:
raise KeyError("Keys must be one of {!r:0}".format(SUBS_NAMES))
if callable(funcs):
normalized[key].append(funcs)
else:
normalized[key].extend(funcs)
elif isinstance(subs, Iterable):
normalized['all'].extend(subs)
else:
raise ValueError("Subscriptions should be a callable, a list of "
"callables, or a dictionary mapping subscription "
"names to lists of callables.")
# Validates that all entries are callables.
for name, funcs in normalized.items():
for func in funcs:
if not callable(func):
raise ValueError("subs values must be functions or lists "
"of functions. The offending entry is\n "
"{0}".format(func))
return normalized
class DefaultSubs:
"""a class-level descriptor"""
def __init__(self, default=None):
self._value = normalize_subs_input(default)
def __get__(self, instance, owner):
return self._value
def __set__(self, instance, value):
self._value = normalize_subs_input(value)
class Subs:
"""a 'reusable' property"""
def __init__(self, default=None):
self.default = normalize_subs_input(default)
self.data = WeakKeyDictionary()
def __get__(self, instance, owner):
return self.data.get(instance, self.default)
def __set__(self, instance, value):
self.data[instance] = normalize_subs_input(value)
def snake_cyclers(cyclers, snake_booleans):
"""
Combine cyclers with a 'snaking' back-and-forth order.
Parameters
----------
cyclers : cycler.Cycler
or any iterable that yields dictionaries of lists
snake_booleans : list
a list of the same length as cyclers indicating whether each cycler
should 'snake' (True) or not (False). Note that the first boolean
does not make a difference because the first (slowest) dimension
does not repeat.
Returns
-------
result : cycler
"""
if len(cyclers) != len(snake_booleans):
raise ValueError("number of cyclers does not match number of booleans")
lengths = []
new_cyclers = []
for c in cyclers:
lengths.append(len(c))
total_length = np.product(lengths)
for i, (c, snake) in enumerate(zip(cyclers, snake_booleans)):
num_tiles = np.product(lengths[:i])
num_repeats = np.product(lengths[i+1:])
for k, v in c._transpose().items():
if snake:
v = v + v[::-1]
v2 = np.tile(np.repeat(v, num_repeats), num_tiles)
expanded = v2[:total_length]
new_cyclers.append(cycler(k, expanded))
return reduce(operator.add, new_cyclers)
def first_key_heuristic(device):
"""
Get the fully-qualified data key for the first entry in describe().
This will raise is that entry's `describe()` method does not return a
dictionary with exactly one key.
"""
return next(iter(device.describe()))
def ancestry(obj):
"""
List self, parent, grandparent, ... back to ultimate ancestor.
Parameters
----------
obj : object
must have a `parent` attribute
Returns
-------
ancestry : list
list of objects, starting with obj and tracing parents recursively
"""
ancestry = []
ancestor = obj
while True:
ancestry.append(ancestor)
if ancestor.parent is None:
return ancestry
ancestor = ancestor.parent
def root_ancestor(obj):
"""
Traverse ancestry to obtain root ancestor.
Parameters
----------
obj : object
must have a `parent` attribute
Returns
-------
root : object
"""
return ancestry(obj)[-1]
def share_ancestor(obj1, obj2):
"""
Check whether obj1 and obj2 have a common ancestor.
Parameters
----------
obj1 : object
must have a `parent` attribute
obj2 : object
must have a `parent` attribute
Returns
-------
result : boolean
"""
return ancestry(obj1)[-1] is ancestry(obj2)[-1]
def separate_devices(devices):
"""
Filter out elements that have other elements as their ancestors.
If A is an ancestor of B, [A, B, C] -> [A, C].
Paremeters
----------
devices : list
All elements must have a `parent` attribute.
Returns
-------
result : list
subset of input, with order retained
"""
result = []
for det in devices:
for existing_det in result[:]:
if existing_det in ancestry(det):
# known issue: here we assume that det is in the read_attrs
# of existing_det -- to be addressed after plans.py refactor
break
elif det in ancestry(existing_det):
# existing_det is redundant; use det in its place
result.remove(existing_det)
else:
result.append(det)
return result
def all_safe_rewind(devices):
'''If all devices can have their trigger method re-run on resume.
Parameters
----------
devices : list
List of devices
Returns
-------
safe_rewind : bool
If all the device can safely re-triggered
'''
for d in devices:
if hasattr(d, 'rewindable'):
rewindable = d.rewindable.get()
if not rewindable:
return False
return True
SEARCH_PATH = []
ENV_VAR = 'BLUESKY_HISTORY_PATH'
if ENV_VAR in os.environ:
SEARCH_PATH.append(os.environ[ENV_VAR])
SEARCH_PATH.extend([os.path.expanduser('~/.config/bluesky/bluesky_history.db'),
'/etc/bluesky/bluesky_history.db'])
def get_history():
"""
Return a dict-like object for stashing metadata.
If historydict is not installed, return a dict.
If historydict is installed, look for a sqlite file in:
- $BLUESKY_HISTORY_PATH, if defined
- ~/.config/bluesky/bluesky_history.db
- /etc/bluesky/bluesky_history.db
If no existing file is found, create a new sqlite file in:
- $BLUESKY_HISTORY_PATH, if defined
- ~/.config/bluesky/bluesky_history.db, otherwise
"""
try:
import historydict
except ImportError:
print("You do not have historydict installed, your metadata "
"will not be persistent or have any history of the "
"values.")
return dict()
else:
for path in SEARCH_PATH:
if os.path.isfile(path):
print("Loading metadata history from %s" % path)
return historydict.HistoryDict(path)
# No existing file was found. Try creating one.
path = SEARCH_PATH[0]
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
print("Storing metadata history in a new file at %s." % path)
return historydict.HistoryDict(path)
except IOError as exc:
print(exc)
print("Failed to create metadata history file at %s" % path)
print("Storing HistoryDict in memory; it will not persist "
"when session is ended.")
return historydict.HistoryDict(':memory:')
_QT_KICKER_INSTALLED = {}
_NB_KICKER_INSTALLED = {}
def install_kicker(loop=None, update_rate=0.03):
"""
Install a periodic callback to integrate drawing and asyncio event loops.
This dispatches to :func:`install_qt_kicker` or :func:`install_nb_kicker`
depending on the current matplotlib backend.
Parameters
----------
loop : event loop, optional
update_rate : number
Seconds between periodic updates. Default is 0.03.
"""
import matplotlib
backend = matplotlib.get_backend()
if backend == 'nbAgg':
install_nb_kicker(loop=loop, update_rate=update_rate)
elif backend in ('Qt4Agg', 'Qt5Agg'):
install_qt_kicker(loop=loop, update_rate=update_rate)
else:
raise NotImplementedError("The matplotlib backend {} is not yet "
"supported.".format(backend))
def install_qt_kicker(loop=None, update_rate=0.03):
"""Install a periodic callback to integrate Qt and asyncio event loops.
If a version of the Qt bindings are not already imported, this function
will do nothing.
It is safe to call this function multiple times.
Parameters
----------
loop : event loop, optional
update_rate : number
Seconds between periodic updates. Default is 0.03.
"""
if loop is None:
loop = asyncio.get_event_loop()
global _QT_KICKER_INSTALLED
if loop in _QT_KICKER_INSTALLED:
return
if not any(p in sys.modules for p in ['PyQt4', 'pyside', 'PyQt5']):
return
import matplotlib.backends.backend_qt5
from matplotlib.backends.backend_qt5 import _create_qApp
from matplotlib._pylab_helpers import Gcf
_create_qApp()
qApp = matplotlib.backends.backend_qt5.qApp
try:
_draw_all = Gcf.draw_all # mpl version >= 1.5
except AttributeError:
# slower, but backward-compatible
def _draw_all():
for f_mgr in Gcf.get_all_fig_managers():
f_mgr.canvas.draw_idle()
def _qt_kicker():
# The RunEngine Event Loop interferes with the qt event loop. Here we
# kick it to keep it going.
_draw_all()
qApp.processEvents()
loop.call_later(update_rate, _qt_kicker)
_QT_KICKER_INSTALLED[loop] = loop.call_soon(_qt_kicker)
def install_nb_kicker(loop=None, update_rate=0.03):
"""
Install a periodic callback to integrate ipykernel and asyncio event loops.
It is safe to call this function multiple times.
Parameters
----------
loop : event loop, optional
update_rate : number
Seconds between periodic updates. Default is 0.03.
"""
import matplotlib
if loop is None:
loop = asyncio.get_event_loop()
global _NB_KICKER_INSTALLED
if loop in _NB_KICKER_INSTALLED:
return
def _nbagg_kicker():
# This is more brute-force variant of the _qt_kicker function used
# inside install_qt_kicker.
for f_mgr in matplotlib._pylab_helpers.Gcf.get_all_fig_managers():
if f_mgr.canvas.figure.stale:
f_mgr.canvas.draw()
loop.call_later(update_rate, _nbagg_kicker)
_NB_KICKER_INSTALLED[loop] = loop.call_soon(_nbagg_kicker)
def apply_sub_factories(factories, plan):
'''Run sub factory functions for a plan
Factory functions should return lists, which will be added onto the
subscription key (e.g., 'all' or 'start') specified in the factory
definition.
If the factory function returns None, the list will not be modified.
'''
factories = normalize_subs_input(factories)
out = {k: list(itertools.filterfalse(lambda x: x is None,
(sf(plan) for sf in v)))
for k, v in factories.items()}
return out
def update_sub_lists(out, inp):
"""Extends dictionary `out` lists with those in `inp`
Assumes dictionaries where all values are lists
"""
for k, v in inp.items():
try:
out[k].extend(v)
except KeyError:
out[k] = list(v)
def register_transform(RE, *, prefix='<'):
'''Register RunEngine IPython magic convenience transform
Assuming the default parameters
This maps `< stuff(*args, **kwargs)` -> `RE(stuff(*args, **kwargs))`
RE is assumed to be available in the global namespace
Parameters
----------
RE : str
The name of a valid RunEngine instance in the global IPython namespace
prefix : str, optional
The prefix to trigger this transform on. If this collides with
valid python syntax or an existing transform you are on your own.
'''
import IPython
from IPython.core.inputtransformer import StatelessInputTransformer
@StatelessInputTransformer.wrap
def tr_re(line):
if line.startswith(prefix):
line = line[len(prefix):].strip()
return '{}({})'.format(RE, line)
return line
ip = IPython.get_ipython()
ip.input_splitter.logical_line_transforms.append(tr_re())
ip.input_transformer_manager.logical_line_transforms.append(tr_re())
class AsyncInput:
"""a input prompt that allows event loop to run in the background
adapted from http://stackoverflow.com/a/35514777/1221924
"""
def __init__(self, loop=None):
self.loop = loop or asyncio.get_event_loop()
self.q = asyncio.Queue(loop=self.loop)
self.loop.add_reader(sys.stdin, self.got_input)
def got_input(self):
asyncio.ensure_future(self.q.put(sys.stdin.readline()), loop=self.loop)
@asyncio.coroutine
def __call__(self, prompt, end='\n', flush=False):
print(prompt, end=end, flush=flush)
return (yield from self.q.get()).rstrip('\n')
def new_uid():
return str(uuid.uuid4())
def sanitize_np(val):
"Convert any numpy objects into built-in Python types."
if isinstance(val, (np.generic, np.ndarray)):
if np.isscalar(val):
return val.item()
return val.tolist()
return val
def expiring_function(func, loop, *args, **kwargs):
"""
If timeout has not occurred, call func(*args, **kwargs).
This is meant to used with the event loop's run_in_executor
method. Outside that context, it doesn't make any sense.
"""
def dummy(start_time, timeout):
if loop.time() > start_time + timeout:
return
func(*args, **kwargs)
return
return dummy
def short_uid(label=None, truncate=6):
"Return a readable but unique id like 'label-fjfi5a'"
if label:
return '-'.join([label, new_uid()[:truncate]])
else:
return new_uid()[:truncate]
def ensure_uid(doc_or_uid):
"""
Accept a uid or a dict with a 'uid' key. Return the uid.
"""
try:
return doc_or_uid['uid']
except TypeError:
return doc_or_uid
def ts_msg_hook(msg, file=sys.stdout):
t = '{:%H:%M:%S.%f}'.format(datetime.datetime.now())
msg_fmt = '{: <17s} -> {!s: <15s} args: {}, kwargs: {}'.format(
msg.command,
msg.obj.name if hasattr(msg.obj, 'name') else msg.obj,
msg.args,
msg.kwargs)
print('{} {}'.format(t, msg_fmt), file=file)
def make_decorator(wrapper):
"""
Turn a generator instance wrapper into a generator function decorator.
The functions named <something>_wrapper accept a generator instance and
return a mutated generator instance.
Example of a 'wrapper':
>>> plan = count([det]) # returns a generator instance
>>> revised_plan = some_wrapper(plan) # returns a new instance
Example of a decorator:
>>> some_decorator = make_decorator(some_wrapper) # returns decorator
>>> customized_count = some_decorator(count) # returns generator func
>>> plan = customized_count([det]) # returns a generator instance