-
Notifications
You must be signed in to change notification settings - Fork 76
/
sim.py
1501 lines (1254 loc) · 50.1 KB
/
sim.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
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
import copy
import inspect
import itertools
from functools import partial
import numpy as np
import os
import random
import threading
import time as ttime
import uuid
import weakref
import warnings
from collections import deque, OrderedDict
from tempfile import mkdtemp
from .signal import Signal, EpicsSignal, EpicsSignalRO
from .areadetector.base import EpicsSignalWithRBV
from .status import DeviceStatus, StatusBase
from .device import (Device, Component as Cpt,
DynamicDeviceComponent as DDCpt, Kind)
from types import SimpleNamespace
from .pseudopos import (PseudoPositioner, PseudoSingle,
real_position_argument, pseudo_position_argument)
from .positioner import SoftPositioner
from .utils import ReadOnlyError, LimitError
from .log import logger
# two convenience functions 'vendored' from bluesky.utils
def new_uid():
return str(uuid.uuid4())
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]
class NullStatus(StatusBase):
"A simple Status object that is always immediately done, successfully."
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.set_finished()
class EnumSignal(Signal):
def __init__(self, *args, value=0, enum_strings, **kwargs):
super().__init__(*args, value=0, **kwargs)
self._enum_strs = tuple(enum_strings)
self._metadata['enum_strs'] = tuple(enum_strings)
self.put(value)
def put(self, value, **kwargs):
if value in self._enum_strs:
value = self._enum_strs.index(value)
elif isinstance(value, str):
err = f'{value} not in enum strs {self._enum_strs}'
raise ValueError(err)
return super().put(value, **kwargs)
def get(self, *, as_string=True, **kwargs):
"""
Implement getting as enum strings
"""
value = super().get()
if as_string:
if self._enum_strs is not None and isinstance(value, int):
return self._enum_strs[value]
elif value is not None:
return str(value)
return value
def describe(self):
desc = super().describe()
desc[self.name]['enum_strs'] = self._enum_strs
return desc
class SynSignal(Signal):
"""
A synthetic Signal that evaluates a Python function when triggered.
Parameters
----------
func : callable, optional
This function sets the signal to a new value when it is triggered.
Expected signature: ``f() -> value``.
By default, triggering the signal does not change the value.
name : string, keyword only
exposure_time : number, optional
Seconds of delay when triggered (simulated 'exposure time'). Default is
0.
precision : integer, optional
Digits of precision. Default is 3.
parent : Device, optional
Used internally if this Signal is made part of a larger Device.
kind : a member the Kind IntEnum (or equivalent integer), optional
Default is Kind.normal. See Kind for options.
"""
# This signature is arranged to mimic the signature of EpicsSignal, where
# the Python function (func) takes the place of the PV.
def __init__(self, func=None, *,
name, # required, keyword-only
exposure_time=0,
precision=3,
parent=None,
labels=None,
kind=None,
**kwargs):
if func is None:
# When triggered, just put the current value.
func = self.get
# Initialize readback with 0.
self._readback = 0
sentinel = object()
loop = kwargs.pop('loop', sentinel)
if loop is not sentinel:
warnings.warn(
f"{self.__class__} no longer takes a loop as input. "
"Your input will be ignored and may raise in the future",
stacklevel=2
)
self._func = func
self.exposure_time = exposure_time
self.precision = precision
super().__init__(value=self._func(), timestamp=ttime.time(), name=name,
parent=parent, labels=labels, kind=kind, **kwargs)
self._metadata.update(
connected=True,
)
def describe(self):
res = super().describe()
# There should be only one key here, but for the sake of generality....
for k in res:
res[k]['precision'] = self.precision
return res
def trigger(self):
st = DeviceStatus(device=self)
delay_time = self.exposure_time
if delay_time:
def sleep_and_finish():
self.log.info('sleep_and_finish %s', self)
ttime.sleep(delay_time)
self.put(self._func())
st.set_finished()
threading.Thread(target=sleep_and_finish, daemon=True).start()
else:
self.put(self._func())
st.set_finished()
return st
def sim_set_func(self, func):
"""
Update the SynSignal function to set a new value on trigger.
"""
self._func = func
class SynSignalRO(SynSignal):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._metadata.update(
connected=True,
write_access=False,
)
def put(self, value, *, timestamp=None, force=False):
msg = f"{self}.put(value={value}, timestamp={timestamp}, force={force})"
self.log.error(msg)
raise ReadOnlyError(msg)
def set(self, value, *, timestamp=None, force=False):
msg = f"{self} is readonly"
self.log.error(msg)
raise ReadOnlyError(msg)
class SynPeriodicSignal(SynSignal):
"""
A synthetic Signal that evaluates a Python function periodically.
The signal value is updated in a background thread. To start the thread,
call the `start_simulation()` method before the beginning of simulation.
Parameters
----------
func : callable, optional
This function sets the signal to a new value when it is triggered.
Expected signature: ``f() -> value``.
By default, triggering the signal generates white noise on [0, 1].
name : string, keyword only
period : number, optional
How often the Signal's value is updated in the background. Default is
1 second.
period_jitter : number, optional
Random Gaussian variation of the period. Default is 1 second.
exposure_time : number, optional
Seconds of delay when triggered (simulated 'exposure time'). Default is
0.
parent : Device, optional
Used internally if this Signal is made part of a larger Device.
kind : a member the Kind IntEnum (or equivalent integer), optional
Default is Kind.normal. See Kind for options.
"""
def __init__(self, func=None, *,
name, # required, keyword-only
period=1, period_jitter=1,
exposure_time=0,
parent=None,
labels=None,
kind=None,
**kwargs):
if func is None:
func = np.random.rand
self._period = period
self._period_jitter = period_jitter
super().__init__(name=name, func=func,
exposure_time=exposure_time,
parent=parent, labels=labels, kind=kind,
**kwargs)
self.__thread = None
def start_simulation(self):
"""
Start background thread that performs periodic value updates. The method
should be called at least once before the beginning of simulation. Multiple
calls to the method are ignored.
"""
if self.__thread is None:
def periodic_update(ref, period, period_jitter):
while True:
signal = ref()
if not signal:
# Our target Signal has been garbage collected. Shut
# down the Thread.
return
signal.put(signal._func())
del signal
# Sleep for period +/- period_jitter.
ttime.sleep(
max(self._period + self._period_jitter * np.random.randn(), 0))
self.__thread = threading.Thread(target=periodic_update,
daemon=True,
args=(weakref.ref(self),
self._period,
self._period_jitter))
self.__thread.start()
def _start_simulation_deprecated(self):
"""Call `start_simulation` and print deprecation warning."""
if self.__thread is None:
msg = ("Deprecated API: Objects of SynPeriodicSignal must be initialized before simulation\n"
"by calling 'start_simulation()' method. Two such objects ('rand' and 'rand2') are\n"
"created by 'ophyd.sim' module. Call\n"
" rand.start_simulation() or rand2.start_simulation()\n"
"before the object is used.")
self.log.warning(msg)
self.start_simulation()
def trigger(self):
self._start_simulation_deprecated()
return super().trigger()
def get(self, **kwargs):
self._start_simulation_deprecated()
return super().get(**kwargs)
def put(self, *args, **kwargs):
self._start_simulation_deprecated()
super().put(*args, **kwargs)
def set(self, *args, **kwargs):
self._start_simulation_deprecated()
return super().set(*args, **kwargs)
def read(self):
self._start_simulation_deprecated()
return super().read()
def subscribe(self, *args, **kwargs):
self._start_simulation_deprecated()
return super().subscribe(*args, **kwargs)
class _ReadbackSignal(Signal):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._metadata.update(
connected=True,
write_access=False,
)
def get(self):
self._readback = self.parent.sim_state['readback']
return self._readback
def describe(self):
res = super().describe()
# There should be only one key here, but for the sake of
# generality....
for k in res:
res[k]['precision'] = self.parent.precision
return res
@property
def timestamp(self):
'''Timestamp of the readback value'''
return self.parent.sim_state['readback_ts']
def put(self, value, *, timestamp=None, force=False):
raise ReadOnlyError("The signal {} is readonly.".format(self.name))
def set(self, value, *, timestamp=None, force=False):
raise ReadOnlyError("The signal {} is readonly.".format(self.name))
class _SetpointSignal(Signal):
def put(self, value, *, timestamp=None, force=False):
self._readback = float(value)
self.parent.set(float(value))
def get(self):
self._readback = self.parent.sim_state['setpoint']
return self.parent.sim_state['setpoint']
def describe(self):
res = super().describe()
# There should be only one key here, but for the sake of generality....
for k in res:
res[k]['precision'] = self.parent.precision
return res
@property
def timestamp(self):
'''Timestamp of the readback value'''
return self.parent.sim_state['setpoint_ts']
class SynAxis(Device):
"""
A synthetic settable Device mimic any 1D Axis (position, temperature).
Parameters
----------
name : string, keyword only
readback_func : callable, optional
When the Device is set to ``x``, its readback will be updated to
``f(x)``. This can be used to introduce random noise or a systematic
offset.
Expected signature: ``f(x) -> value``.
value : object, optional
The initial value. Default is 0.
delay : number, optional
Simulates how long it takes the device to "move". Default is 0 seconds.
precision : integer, optional
Digits of precision. Default is 3.
parent : Device, optional
Used internally if this Signal is made part of a larger Device.
kind : a member the Kind IntEnum (or equivalent integer), optional
Default is Kind.normal. See Kind for options.
"""
readback = Cpt(_ReadbackSignal, value=0, kind='hinted')
setpoint = Cpt(_SetpointSignal, value=0, kind='normal')
velocity = Cpt(Signal, value=1, kind='config')
acceleration = Cpt(Signal, value=1, kind='config')
unused = Cpt(Signal, value=1, kind='omitted')
SUB_READBACK = 'readback'
_default_sub = SUB_READBACK
def __init__(self, *,
name,
readback_func=None, value=0, delay=0,
precision=3,
parent=None,
labels=None,
kind=None,
**kwargs):
if readback_func is None:
def readback_func(x):
return x
sentinel = object()
loop = kwargs.pop('loop', sentinel)
if loop is not sentinel:
warnings.warn(
f"{self.__class__} no longer takes a loop as input. "
"Your input will be ignored and may raise in the future",
stacklevel=2
)
self.sim_state = {}
self._readback_func = readback_func
self.delay = delay
self.precision = precision
# initialize values
self.sim_state['setpoint'] = value
self.sim_state['setpoint_ts'] = ttime.time()
self.sim_state['readback'] = readback_func(value)
self.sim_state['readback_ts'] = ttime.time()
super().__init__(name=name, parent=parent, labels=labels, kind=kind,
**kwargs)
self.readback.name = self.name
def set(self, value):
old_setpoint = self.sim_state['setpoint']
self.sim_state['setpoint'] = value
self.sim_state['setpoint_ts'] = ttime.time()
self.setpoint._run_subs(sub_type=self.setpoint.SUB_VALUE,
old_value=old_setpoint,
value=self.sim_state['setpoint'],
timestamp=self.sim_state['setpoint_ts'])
def update_state():
old_readback = self.sim_state['readback']
self.sim_state['readback'] = self._readback_func(value)
self.sim_state['readback_ts'] = ttime.time()
self.readback._run_subs(sub_type=self.readback.SUB_VALUE,
old_value=old_readback,
value=self.sim_state['readback'],
timestamp=self.sim_state['readback_ts'])
self._run_subs(sub_type=self.SUB_READBACK,
old_value=old_readback,
value=self.sim_state['readback'],
timestamp=self.sim_state['readback_ts'])
st = DeviceStatus(device=self)
if self.delay:
def sleep_and_finish():
ttime.sleep(self.delay)
update_state()
st.set_finished()
threading.Thread(target=sleep_and_finish, daemon=True).start()
else:
update_state()
st.set_finished()
return st
@property
def position(self):
return self.readback.get()
class SynAxisEmptyHints(SynAxis):
@property
def hints(self):
return {}
class SynAxisNoHints(SynAxis):
readback = Cpt(_ReadbackSignal, value=0, kind='omitted')
@property
def hints(self):
raise AttributeError
class SynGauss(Device):
"""
Evaluate a point on a Gaussian based on the value of a motor.
Parameters
----------
name : string
motor : Device
motor_field : string
center : number
center of peak
Imax : number
max intensity of peak
sigma : number, optional
Default is 1.
noise : {'poisson', 'uniform', None}, optional
Add noise to the gaussian peak.
noise_multiplier : float, optional
Only relevant for 'uniform' noise. Multiply the random amount of
noise by 'noise_multiplier'
random_state : numpy random state object, optional
np.random.RandomState(0), to generate random number with given seed
Example
-------
motor = SynAxis(name='motor')
det = SynGauss('det', motor, 'motor', center=0, Imax=1, sigma=1)
"""
def _compute(self):
m = self._motor.read()[self._motor_field]['value']
# we need to do this one at a time because
# - self.read() may be screwed with by the user
# - self.get() would cause infinite recursion
Imax = self.Imax.get()
center = self.center.get()
sigma = self.sigma.get()
noise = self.noise.get()
noise_multiplier = self.noise_multiplier.get()
v = Imax * np.exp(-(m - center) ** 2 /
(2 * sigma ** 2))
if noise == 'poisson':
v = int(self.random_state.poisson(np.round(v), 1))
elif noise == 'uniform':
v += self.random_state.uniform(-1, 1) * noise_multiplier
return v
val = Cpt(SynSignal, kind='hinted')
Imax = Cpt(Signal, value=10, kind='config')
center = Cpt(Signal, value=0, kind='config')
sigma = Cpt(Signal, value=1, kind='config')
noise = Cpt(EnumSignal, value='none', kind='config',
enum_strings=('none', 'poisson', 'uniform'))
noise_multiplier = Cpt(Signal, value=1, kind='config')
def __init__(self, name, motor, motor_field, center, Imax,
*, random_state=None,
**kwargs):
set_later = {}
for k in ('sigma', 'noise', 'noise_multiplier'):
v = kwargs.pop(k, None)
if v is not None:
set_later[k] = v
super().__init__(name=name, **kwargs)
self._motor = motor
self._motor_field = motor_field
self.center.put(center)
self.Imax.put(Imax)
self.random_state = random_state or np.random
self.val.name = self.name
self.val.sim_set_func(self._compute)
for k, v in set_later.items():
getattr(self, k).put(v)
self.trigger()
def subscribe(self, *args, **kwargs):
return self.val.subscribe(*args, **kwargs)
def clear_sub(self, cb, event_type=None):
return self.val.clear_sub(cb, event_type=event_type)
def unsubscribe(self, cid):
return self.val.unsubscribe(cid)
def unsubscribe_all(self):
return self.val.unsubscribe_all()
def trigger(self, *args, **kwargs):
return self.val.trigger(*args, **kwargs)
@property
def precision(self):
return self.val.precision
@precision.setter
def precision(self, v):
self.val.precision = v
@property
def exposure_time(self):
return self.val.exposure_time
@exposure_time.setter
def exposure_time(self, v):
self.val.exposure_time = v
class Syn2DGauss(Device):
"""
Evaluate a point on a Gaussian based on the value of a motor.
Parameters
----------
name : str
The name of the detector
motor0 : SynAxis
The 'x' coordinate of the 2-D gaussian blob
motor_field0 : str
The name field of the motor. Should be the key in motor0.describe()
motor1 : SynAxis
The 'y' coordinate of the 2-D gaussian blob
motor_field1 : str
The name field of the motor. Should be the key in motor1.describe()
center : iterable, optional
The center of the gaussian blob
Defaults to (0,0)
Imax : float, optional
The intensity at `center`
Defaults to 1
sigma : float, optional
Standard deviation for gaussian blob
Defaults to 1
noise : {'poisson', 'uniform', None}, optional
Add noise to the gaussian peak..
Defaults to None
noise_multiplier : float, optional
Only relevant for 'uniform' noise. Multiply the random amount of
noise by 'noise_multiplier'
Defaults to 1
random_state : numpy random state object, optional
np.random.RandomState(0), to generate random number with given seed
Example
-------
motor = SynAxis(name='motor')
det = SynGauss('det', motor, 'motor', center=0, Imax=1, sigma=1)
"""
val = Cpt(SynSignal, kind='hinted')
Imax = Cpt(Signal, value=10, kind='config')
center = Cpt(Signal, value=0, kind='config')
sigma = Cpt(Signal, value=1, kind='config')
noise = Cpt(EnumSignal, value='none', kind='config',
enum_strings=('none', 'poisson', 'uniform'))
noise_multiplier = Cpt(Signal, value=1, kind='config')
def _compute(self):
x = self._motor0.read()[self._motor_field0]['value']
y = self._motor1.read()[self._motor_field1]['value']
m = np.array([x, y])
Imax = self.Imax.get()
center = self.center.get()
sigma = self.sigma.get()
noise = self.noise.get()
noise_multiplier = self.noise_multiplier.get()
v = Imax * np.exp(-np.sum((m - center) ** 2) / (2 * sigma ** 2))
if noise == 'poisson':
v = int(self.random_state.poisson(np.round(v), 1))
elif noise == 'uniform':
v += self.random_state.uniform(-1, 1) * noise_multiplier
return v
def __init__(self, name, motor0, motor_field0, motor1, motor_field1,
center, Imax, sigma=1, noise="none", noise_multiplier=1,
random_state=None, **kwargs):
super().__init__(name=name, **kwargs)
self._motor0 = motor0
self._motor1 = motor1
self._motor_field0 = motor_field0
self._motor_field1 = motor_field1
self.center.put(center)
self.Imax.put(Imax)
self.sigma.put(sigma)
self.noise.put(noise)
self.noise_multiplier.put(noise_multiplier)
if random_state is None:
random_state = np.random
self.random_state = random_state
self.val.name = self.name
self.val.sim_set_func(self._compute)
self.trigger()
def trigger(self, *args, **kwargs):
return self.val.trigger(*args, **kwargs)
class TrivialFlyer:
"""Trivial flyer that complies to the API but returns empty data."""
name = 'trivial_flyer'
parent = None
def kickoff(self):
return NullStatus()
def describe_collect(self):
return {'stream_name': {}}
def read_configuration(self):
return OrderedDict()
def describe_configuration(self):
return OrderedDict()
def complete(self):
return NullStatus()
def collect(self):
for i in range(100):
yield {'data': {}, 'timestamps': {}, 'time': i, 'seq_num': i}
def stop(self, *, success=False):
pass
class NewTrivialFlyer(TrivialFlyer):
"""
The old-style API inserted Resource and Datum documents into a database
directly. The new-style API only caches the documents and provides an
interface (collect_asset_docs) for accessing that cache. This change was
part of the "asset refactor" that changed that way Resource and Datum
documents flowed through ophyd, bluesky, and databroker. Trivial flyer that
complies to the API but returns empty data.
"""
name = 'new_trivial_flyer'
def collect_asset_docs(self):
for _ in ():
yield _
class MockFlyer:
"""
Class for mocking a flyscan API implemented with stepper motors.
"""
def __init__(self, name, detector, motor, start, stop, num, **kwargs):
self.name = name
self.parent = None
self._mot = motor
self._detector = detector
self._steps = np.linspace(start, stop, num)
self._data = deque()
self._completion_status = None
self._lock = threading.RLock()
sentinel = object()
loop = kwargs.pop("loop", sentinel)
if loop is not sentinel:
warnings.warn(
f"{self.__class__} no longer takes a loop as input. "
"Your input will be ignored and may raise in the future",
stacklevel=2,
)
if kwargs:
raise TypeError(
f"{self.__class__}.__init__ got unexpected "
f"keyword arguments {list(kwargs)}"
)
def __setstate__(self, val):
name, detector, motor, steps = val
self.name = name
self.parent = None
self._mot = motor
self._detector = detector
self._steps = steps
self._completion_status = None
def __getstate__(self):
return (self.name, self._detector, self._mot, self._steps)
def read_configuration(self):
return {}
def describe_configuration(self):
return {}
def describe_collect(self):
dd = dict()
dd.update(self._mot.describe())
dd.update(self._detector.describe())
return {self.name: dd}
def complete(self):
if self._completion_status is None:
raise RuntimeError("No collection in progress")
return self._completion_status
def kickoff(self):
if self._completion_status is not None and not self._completion_status.done:
raise RuntimeError("Kicking off a second time?!")
self._data = deque()
st = DeviceStatus(device=self)
self._completion_status = st
def flyer_worker():
self._scan()
st.set_finished()
threading.Thread(target=flyer_worker, daemon=True).start()
kickoff_st = DeviceStatus(device=self)
kickoff_st.set_finished()
return kickoff_st
def collect(self):
with self._lock:
data = list(self._data)
self._data.clear()
yield from data
def _scan(self):
"This will be run on a separate thread, started in self.kickoff()"
ttime.sleep(0.1)
for p in self._steps:
stat = self._mot.set(p)
stat.wait()
stat = self._detector.trigger()
stat.wait()
event = dict()
event["time"] = ttime.time()
event["data"] = dict()
event["timestamps"] = dict()
for r in [self._mot, self._detector]:
d = r.read()
for k, v in d.items():
event["data"][k] = v["value"]
event["timestamps"][k] = v["timestamp"]
with self._lock:
self._data.append(event)
def stop(self, *, success=False):
pass
class SynSignalWithRegistry(SynSignal):
"""
A SynSignal integrated with databroker.assets
Parameters
----------
func : callable, optional
This function sets the signal to a new value when it is triggered.
Expected signature: ``f() -> value``.
By default, triggering the signal does not change the value.
name : string, keyword only
exposure_time : number, optional
Seconds of delay when triggered (simulated 'exposure time'). Default is
0.
parent : Device, optional
Used internally if this Signal is made part of a larger Device.
reg : Registry, optional
DEPRECATED. If used, this is ignored and a warning is issued. In a
future release, this parameter will be removed.
save_path : str, optional
Path to save files to, if None make a temp dir, defaults to None.
save_func : function, optional
The function to save the data, function signature must be:
`func(file_path, array)`, defaults to np.save
save_spec : str, optional
The spec for the save function, defaults to 'RWFS_NPY'
save_ext : str, optional
The extension to add to the file name, defaults to '.npy'
"""
def __init__(self, *args, save_path=None,
save_func=partial(np.save, allow_pickle=False),
save_spec='NPY_SEQ', save_ext='npy', **kwargs):
super().__init__(*args, **kwargs)
self.save_func = save_func
self.save_ext = save_ext
self._resource_uid = None
self._datum_counter = None
self._asset_docs_cache = deque()
if save_path is None:
self.save_path = mkdtemp()
else:
self.save_path = save_path
self._spec = save_spec # spec name stored in resource doc
self._file_stem = None
self._path_stem = None
self._result = {}
def stage(self):
self._file_stem = short_uid()
self._datum_counter = itertools.count()
self._path_stem = os.path.join(self.save_path, self._file_stem)
# This is temporarily more complicated than it will be in the future.
# It needs to support old configurations that have a registry.
resource = {'spec': self._spec,
'root': self.save_path,
'resource_path': self._file_stem,
'resource_kwargs': {},
'path_semantics': {'posix': 'posix', 'nt': 'windows'}[os.name]}
self._resource_uid = new_uid()
resource['uid'] = self._resource_uid
self._asset_docs_cache.append(('resource', resource))
def trigger(self):
super().trigger()
# save file stash file name
self._result.clear()
for idx, (name, reading) in enumerate(super().read().items()):
# Save the actual reading['value'] to disk. For a real detector,
# this part would be done by the detector IOC, not by ophyd.
data_counter = next(self._datum_counter)
self.save_func('{}_{}.{}'.format(self._path_stem, data_counter,
self.save_ext), reading['value'])
# This is temporarily more complicated than it will be in the
# future. It needs to support old configurations that have a
# registry.
datum = {'resource': self._resource_uid,
'datum_kwargs': dict(index=data_counter)}
# If a Registry is not set, we need to generate the datum_id.
datum_id = '{}/{}'.format(self._resource_uid,
data_counter)
datum['datum_id'] = datum_id
self._asset_docs_cache.append(('datum', datum))
# And now change the reading in place, replacing the value with
# a reference to Registry.
reading['value'] = datum_id
self._result[name] = reading
return NullStatus()
def read(self):
return self._result
def describe(self):
res = super().describe()
for key in res:
res[key]['external'] = "FILESTORE"
return res
def collect_asset_docs(self):
items = list(self._asset_docs_cache)
self._asset_docs_cache.clear()
for item in items:
yield item
def unstage(self):
self._resource_uid = None
self._datum_counter = None
self._asset_docs_cache.clear()
self._file_stem = None
self._path_stem = None
self._result.clear()
class NumpySeqHandler:
specs = {'NPY_SEQ'}
def __init__(self, filename, root=''):
self._name = os.path.join(root, filename)
def __call__(self, index):
return np.load('{}_{}.npy'.format(self._name, index),
allow_pickle=False)
def get_file_list(self, datum_kwarg_gen):
"This method is optional. It is not needed for access, but for export."
return ['{name}_{index}.npy'.format(name=self._name, **kwargs)
for kwargs in datum_kwarg_gen]
class ABDetector(Device):
a = Cpt(SynSignal, func=random.random, kind=Kind.hinted)
b = Cpt(SynSignal, func=random.random)
def trigger(self):
return self.a.trigger() & self.b.trigger()
class DetWithCountTime(Device):
intensity = Cpt(SynSignal, func=lambda: 0, kind=Kind.hinted)
count_time = Cpt(Signal)
class DetWithConf(Device):
a = Cpt(SynSignal, func=lambda: 1, kind=Kind.hinted)
b = Cpt(SynSignal, func=lambda: 2, kind=Kind.hinted)
c = Cpt(SynSignal, func=lambda: 3)
d = Cpt(SynSignal, func=lambda: 4)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.read_attrs = ['a', 'b']
self.configuration_attrs = ['c', 'd']
def trigger(self):
return self.a.trigger() & self.b.trigger()
class InvariantSignal(SynSignal):
# Always returns the same reading, including timestamp.
def read(self):
res = super().read()
for k in res:
res[k]['timestamp'] = 0
return res
def __repr__(self):
return "<INVARIANT REPR>"
class SPseudo3x3(PseudoPositioner):