-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path94-sample-checkpoint.py
More file actions
4704 lines (3854 loc) · 179 KB
/
Copy path94-sample-checkpoint.py
File metadata and controls
4704 lines (3854 loc) · 179 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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# vi: ts=4 sw=4
################################################################################
# Code for defining a 'Sample' object, which keeps track of its state, and
# simplifies the task of aligning, measuring, etc.
################################################################################
# Known Bugs:
# N/A
################################################################################
# TODO:
# - Search for "TODO" below.
# - Ability to have a collection of simultaneous motions? (E.g. build up a set
# of deferred motions?)
# - Use internal naming scheme to control whether 'saxs'/'waxs' is put in the
# filename
################################################################################
import time
import re
import os
import shutil
import pandas as pds
from datetime import datetime
import functools
class CoordinateSystem(object):
"""
A generic class defining a coordinate system. Several coordinate systems
can be layered on top of one another (with a reference to the underlying
coordinate system given by the 'base_stage' pointer). When motion of a given
CoordinateSystem is requested, the motion is passed (with coordinate
conversion) to the underlying stage.
"""
hint_replacements = {
"positive": "negative",
"up": "down",
"left": "right",
"towards": "away from",
"downstream": "upstream",
"inboard": "outboard",
"clockwise": "counterclockwise",
"CW": "CCW",
}
# Core methods
########################################
def __init__(self, name="<unnamed>", base=None, **kwargs):
"""Create a new CoordinateSystem (e.g. a stage or a sample).
Parameters
----------
name : str
Name for this stage/sample.
base : Stage
The stage on which this stage/sample sits.
"""
self.name = name
self.base_stage = base
self.enabled = True
self.md = {}
self._marks = {}
self._set_axes_definitions()
self._init_axes(self._axes_definitions)
# self.align_success = True
def _set_axes_definitions(self):
"""Internal function which defines the axes for this stage. This is kept
as a separate function so that it can be over-ridden easily."""
# The _axes_definitions array holds a list of dicts, each defining an axis
self._axes_definitions = []
def _init_axes(self, axes):
"""Internal method that generates method names to control the various axes."""
# Note: Instead of defining CoordinateSystem() having methods '.x', '.xr',
# '.y', '.yr', etc., we programmatically generate these methods when the
# class (and subclasses) are instantiated.
# Thus, the Axis() class has generic versions of these methods, which are
# appropriated renamed (bound, actually) when a class is instantiated.
self._axes = {}
for axis in axes:
axis_object = Axis(
axis["name"],
axis["motor"],
axis["enabled"],
axis["scaling"],
axis["units"],
axis["hint"],
self.base_stage,
stage=self,
)
self._axes[axis["name"]] = axis_object
# Bind the methods of axis_object to appropriately-named methods of
# the CoordinateSystem() class.
setattr(self, axis["name"], axis_object.get_position)
setattr(self, axis["name"] + "abs", axis_object.move_absolute)
setattr(self, axis["name"] + "r", axis_object.move_relative)
setattr(self, axis["name"] + "pos", axis_object.get_position)
setattr(self, axis["name"] + "posMotor", axis_object.get_motor_position)
setattr(self, axis["name"] + "units", axis_object.get_units)
setattr(self, axis["name"] + "hint", axis_object.get_hint)
setattr(self, axis["name"] + "info", axis_object.get_info)
setattr(self, axis["name"] + "set", axis_object.set_current_position)
setattr(self, axis["name"] + "o", axis_object.goto_origin)
setattr(self, axis["name"] + "setOrigin", axis_object.set_origin)
setattr(self, axis["name"] + "mark", axis_object.mark)
setattr(self, axis["name"] + "search", axis_object.search)
setattr(self, axis["name"] + "scan", axis_object.scan)
setattr(self, axis["name"] + "c", axis_object.center)
def comment(self, text, logbooks=None, tags=None, append_md=True, **md):
"""Add a comment related to this CoordinateSystem."""
text += "\n\n[comment for CoordinateSystem: {} ({})].".format(self.name, self.__class__.__name__)
if append_md:
md_current = {k: v for k, v in RE.md.items()} # Global md
md_current.update(get_beamline().get_md()) # Beamline md
# Self md
# md_current.update(self.get_md())
# Specified md
md_current.update(md)
text += "\n\n\nMetadata\n----------------------------------------"
for key, value in sorted(md_current.items()):
text += "\n{}: {}".format(key, value)
logbook.log(text, logbooks=logbooks, tags=tags)
def set_base_stage(self, base):
self.base_stage = base
self._init_axes(self._axes_definitions)
# Convenience/helper methods
########################################
def multiple_string_replacements(self, text, replacements, word_boundaries=False):
"""Peform multiple string replacements simultaneously. Matching is case-insensitive.
Parameters
----------
text : str
Text to return modified
replacements : dictionary
Replacement pairs
word_boundaries : bool, optional
Decides whether replacements only occur for words.
"""
# Code inspired from:
# http://stackoverflow.com/questions/6116978/python-replace-multiple-strings
# Note inclusion of r'\b' sequences forces the regex-match to occur at word-boundaries.
if word_boundaries:
replacements = dict((r"\b" + re.escape(k.lower()) + r"\b", v) for k, v in replacements.items())
pattern = re.compile("|".join(replacements.keys()), re.IGNORECASE)
text = pattern.sub(
lambda m: replacements[r"\b" + re.escape(m.group(0).lower()) + r"\b"],
text,
)
else:
replacements = dict((re.escape(k.lower()), v) for k, v in replacements.items())
pattern = re.compile("|".join(replacements.keys()), re.IGNORECfdeASE)
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
return text
def _hint_replacements(self, text):
"""Convert a motor-hint into its logical inverse."""
# Generates all the inverse replacements
replacements = dict((v, k) for k, v in self.hint_replacements.items())
replacements.update(self.hint_replacements)
return self.multiple_string_replacements(text, replacements, word_boundaries=True)
# Control methods
########################################
def setTemperature(self, temperature, verbosity=3):
if verbosity >= 1:
print("Temperature functions not implemented in {}".format(self.__class__.__name__))
def temperature(self, verbosity=3):
if verbosity >= 1:
print("Temperature functions not implemented in {}".format(self.__class__.__name__))
return 0.0
# Motion methods
########################################
def enable(self):
self.enabled = True
def disable(self):
self.enabled = False
def is_enabled(self):
return self.enabled
def pos(self, verbosity=3):
"""Return (and print) the positions of all axes associated with this
stage/sample."""
out = {}
for axis_name, axis_object in sorted(self._axes.items()):
out[axis_name] = axis_object.get_position(verbosity=verbosity)
# if verbosity>=2: print('') # \n
return out
def origin(self, verbosity=3):
"""Returns the origin for axes."""
out = {}
for axis_name, axis_object in sorted(self._axes.items()):
origin = axis_object.get_origin()
if verbosity >= 2:
print("{:s} origin = {:.3f} {:s}".format(axis_name, origin, axis_object.get_units()))
out[axis_name] = origin
return out
def gotoOrigin(self, axes=None):
"""Go to the origin (zero-point) for this stage. All axes are zeroed,
unless one specifies the axes to move."""
# TODO: Guard against possibly buggy behavior if 'axes' is a string instead of a list.
# (Python will happily iterate over the characters in a string.)
if axes is None:
axes_to_move = self._axes.values()
else:
axes_to_move = [self._axes[axis_name] for axis_name in axes]
for axis in axes_to_move:
axis.goto_origin()
def setOrigin(self, axes, positions=None):
"""Define the current position as the zero-point (origin) for this stage/
sample. The axes to be considered in this redefinition must be supplied
as a list.
If the optional positions parameter is passed, then those positions are
used to define the origins for the axes."""
if positions is None:
for axis in axes:
getattr(self, axis + "setOrigin")()
else:
for axis, pos in zip(axes, positions):
getattr(self, axis + "setOrigin")(pos)
def gotoAlignedPosition(self):
"""Goes to the currently-defined 'aligned' position for this stage. If
no specific aligned position is defined, then the zero-point for the stage
is used instead."""
# TODO: Optional offsets? (Like goto mark?)
if "aligned_position" in self.md and self.md["aligned_position"] is not None:
for axis_name, position in self.md["aligned_position"].items():
self._axes[axis_name].move_absolute(position)
else:
self.gotoOrigin()
# Motion logging
########################################
def setAlignedPosition(self, axes):
"""Saves the current position as the 'aligned' position for this stage/
sample. This allows one to return to this position later. One must
specify the axes to be considered.
WARNING: Currently this position data is not saved persistently. E.g. it will
be lost if you close and reopen the console.
"""
positions = {}
for axis_name in axes:
positions[axis_name] = self._axes[axis_name].get_position(verbosity=0)
self.attributes["aligned_position"] = positions
def mark(self, label, *axes, **axes_positions):
"""Set a mark for the stage/sample/etc.
'Marks' are locations that have been labelled, which is useful for
later going to a labelled position (using goto), or just to keep track
of sample information (metadata).
By default, the mark is set at the current position. If no 'axes' are
specified, all motors are logged. Alternately, axes (as strings) can
be specified. If axes_positions are given as keyword arguments, then
positions other than the current position can be specified.
"""
positions = {}
if len(axes) == 0 and len(axes_positions) == 0:
for axis_name in self._axes:
positions[axis_name] = self._axes[axis_name].get_position(verbosity=0)
else:
for axis_name in axes:
positions[axis_name] = self._axes[axis_name].get_position(verbosity=0)
for axis_name, position in axes_positions.items():
positions[axis_name] = position
self._marks[label] = positions
def marks(self, verbosity=3):
"""Get a list of the current marks on the stage/sample/etc. 'Marks'
are locations that have been labelled, which is useful for later
going to a labelled position (using goto), or just to keep track
of sample information (metadata)."""
if verbosity >= 3:
print("Marks for {:s} (class {:s}):".format(self.name, self.__class__.__name__))
if verbosity >= 2:
for label, positions in self._marks.items():
print(label)
for axis_name, position in sorted(positions.items()):
print(" {:s} = {:.4f} {:s}".format(axis_name, position, self._axes[axis_name].get_units()))
return self._marks
def goto(self, label, verbosity=3, **additional):
"""Move the stage/sample to the location given by the label. For this
to work, the specified label must have been 'marked' at some point.
Additional keyword arguments can be provided. For instance, to move
3 mm from the left edge:
sam.goto('left edge', xr=+3.0)
"""
if label not in self._marks:
if verbosity >= 1:
print(
"Label '{:s}' not recognized. Use '.marks()' for the list of marked positions.".format(label)
)
return
for axis_name, position in sorted(self._marks[label].items()):
if axis_name + "abs" in additional:
# Override the marked value for this position
position = additional[axis_name + "abs"]
del additional[axis_name + "abs"]
# relative = 0.0 if axis_name+'r' not in additional else additional[axis_name+'r']
if axis_name + "r" in additional:
relative = additional[axis_name + "r"]
del additional[axis_name + "r"]
else:
relative = 0.0
self._axes[axis_name].move_absolute(position + relative, verbosity=verbosity)
# Handle any optional motions not already covered
for command, amount in additional.items():
if command[-1] == "r":
getattr(self, command)(amount, verbosity=verbosity)
elif command[-3:] == "abs":
getattr(self, command)(amount, verbosity=verbosity)
else:
print("Keyword argument '{}' not understood (should be 'r' or 'abs').".format(command))
# State methods
########################################
def save_state(self):
"""Outputs a string you can use to re-initialize this object back
to its current state."""
# TODO: Save to databroker?
state = {"origin": {}}
for axis_name, axis in self._axes.items():
state["origin"][axis_name] = axis.origin
return state
def restore_state(self, state):
"""Outputs a string you can use to re-initialize this object back
to its current state."""
for axis_name, axis in self._axes.items():
axis.origin = state["origin"][axis_name]
# End class CoordinateSystem(object)
########################################
class Axis(object):
"""Generic motor axis.
Meant to be used within a CoordinateSystem() or Stage() object.
"""
def __init__(self, name, motor, enabled, scaling, units, hint, base, stage=None, origin=0.0):
self.name = name
self.motor = motor
self.enabled = enabled
self.scaling = scaling
self.units = units
self.hint = hint
self.base_stage = base
self.stage = stage
self.origin = 0.0
self._move_settle_max_time = 10.0
self._move_settle_period = 0.05
self._move_settle_tolerance = 0.01
# Coordinate transformations
########################################
def cur_to_base(self, position):
"""Convert from this coordinate system to the coordinate in the (immediate) base."""
base_position = self.get_origin() + self.scaling * position
return base_position
def base_to_cur(self, base_position):
"""Convert from this base position to the coordinate in the current system."""
position = (base_position - self.get_origin()) / self.scaling
return position
def cur_to_motor(self, position):
"""Convert from this coordinate system to the underlying motor."""
if self.motor is not None:
return self.cur_to_base(position)
else:
base_position = self.cur_to_base(position)
return self.base_stage._axes[self.name].cur_to_motor(base_position)
def motor_to_cur(self, motor_position):
"""Convert a motor position into the current coordinate system."""
if self.motor is not None:
return self.base_to_cur(motor_position)
else:
base_position = self.base_stage._axes[self.name].motor_to_cur(motor_position)
return self.base_to_cur(base_position)
# Programmatically-defined methods
########################################
# Note: Instead of defining CoordinateSystem() having methods '.x', '.xr',
# '.xp', etc., we programmatically generate these methods when the class
# (and subclasses) are instantiated.
# Thus, the Axis() class has generic versions of these methods, which are
# appropriated renamed (bound, actually) when a class is instantiated.
def get_position(self, verbosity=3):
"""Return the current position of this axis (in its coordinate system).
By default, this also prints out the current position."""
if self.motor is not None:
base_position = self.motor.position
else:
verbosity_c = verbosity if verbosity >= 4 else 0
base_position = getattr(self.base_stage, self.name + "pos")(verbosity=verbosity_c)
position = self.base_to_cur(base_position)
if verbosity >= 2:
if self.stage:
stg = self.stage.name
else:
stg = "?"
if verbosity >= 5 and self.motor is not None:
print("{:s} = {:.3f} {:s}".format(self.motor.name, base_position, self.get_units()))
print(
"{:s}.{:s} = {:.3f} {:s} (origin = {:.3f})".format(
stg, self.name, position, self.get_units(), self.get_origin()
)
)
return position
def get_motor_position(self, verbosity=3):
"""Returns the position of this axis, traced back to the underlying
motor."""
if self.motor is not None:
return self.motor.position
else:
return getattr(self.base_stage, self.name + "posMotor")(verbosity=verbosity)
# return self.base_stage._axes[self.name].get_motor_position(verbosity=verbosity)
def move_absolute(self, position=None, wait=True, verbosity=3):
"""Move axis to the specified absolute position. The position is given
in terms of this axis' current coordinate system. The "defer" argument
can be used to defer motions until "move" is called."""
if position is None:
# If called without any argument, just print the current position
return self.get_position(verbosity=verbosity)
# Account for coordinate transformation
base_position = self.cur_to_base(position)
if self.is_enabled():
if self.motor:
# mov( self.motor, base_position )
self.motor.user_setpoint.value = base_position
else:
# Call self.base_stage.xabs(base_position)
getattr(self.base_stage, self.name + "abs")(base_position, verbosity=0)
if self.stage:
stg = self.stage.name
else:
stg = "?"
if verbosity >= 2:
# Show a realtime output of position
start_time = time.time()
current_position = self.get_position(verbosity=0)
while (
abs(current_position - position) > self._move_settle_tolerance
and (time.time() - start_time) < self._move_settle_max_time
):
current_position = self.get_position(verbosity=0)
print(
"{:s}.{:s} = {:5.3f} {:s} \r".format(
stg, self.name, current_position, self.get_units()
),
end="",
)
time.sleep(self._move_settle_period)
# if verbosity>=1:
# current_position = self.get_position(verbosity=0)
# print( '{:s}.{:s} = {:5.3f} {:s} '.format(stg, self.name, current_position, self.get_units()))
elif verbosity >= 1:
print("Axis %s disabled (stage %s)." % (self.name, self.stage.name))
def move_relative(self, move_amount=None, verbosity=3):
"""Move axis relative to the current position."""
if move_amount is None:
# If called without any argument, just print the current position
return self.get_position(verbosity=verbosity)
target_position = self.get_position(verbosity=0) + move_amount
return self.move_absolute(target_position, verbosity=verbosity)
def _get_position(self, verbosity=3):
"""Return the current position of this axis (in its coordinate system).
By default, this also prints out the current position."""
if self.motor is not None:
base_position = self.motor.position
else:
verbosity_c = verbosity if verbosity >= 4 else 0
base_position = getattr(self.base_stage, self.name + "pos")(verbosity=verbosity_c)
position = self.base_to_cur(base_position)
if verbosity >= 2:
if self.stage:
stg = self.stage.name
else:
stg = "?"
if verbosity >= 5 and self.motor is not None:
print("{:s} = {:.3f} {:s}".format(self.motor.name, base_position, self.get_units()))
print(
"{:s}.{:s} = {:.3f} {:s} (origin = {:.3f})".format(
stg, self.name, position, self.get_units(), self.get_origin()
)
)
return position
def _move_absolute(self, position=None, wait=True, verbosity=3):
"""Move axis to the specified absolute position. The position is given
in terms of this axis' current coordinate system. The "defer" argument
can be used to defer motions until "move" is called."""
if position is None:
# If called without any argument, just print the current position
return self.get_position(verbosity=verbosity)
# Account for coordinate transformation
base_position = self.cur_to_base(position)
if self.is_enabled():
if self.motor:
# mov( self.motor, base_position )
self.motor.user_setpoint.value = base_position
else:
# Call self.base_stage.xabs(base_position)
getattr(self.base_stage, self.name + "abs")(base_position, verbosity=0)
if self.stage:
stg = self.stage.name
else:
stg = "?"
if verbosity >= 2:
# Show a realtime output of position
start_time = time.time()
current_position = self._get_position(verbosity=0)
# while abs(current_position-position)>self._move_settle_tolerance and (time.time()-start_time)<self._move_settle_max_time:
# current_position = self.get_position(verbosity=0)
# print( '{:s}.{:s} = {:5.3f} {:s} \r'.format(stg, self.name, current_position, self.get_units()), end='')
# time.sleep(self._move_settle_period)
# if verbosity>=1:
# current_position = self.get_position(verbosity=0)
# print( '{:s}.{:s} = {:5.3f} {:s} '.format(stg, self.name, current_position, self.get_units()))
elif verbosity >= 1:
print("Axis %s disabled (stage %s)." % (self.name, self.stage.name))
def _move_relative(self, move_amount=None, verbosity=3):
"""Move axis relative to the current position."""
if move_amount is None:
# If called without any argument, just print the current position
return self.get_position(verbosity=verbosity)
target_position = self.get_position(verbosity=0) + move_amount
return self._move_absolute(target_position, verbosity=verbosity)
def goto_origin(self):
"""Move axis to the currently-defined origin (zero-point)."""
self.move_absolute(0)
def set_origin(self, origin=None):
"""Sets the origin (zero-point) for this axis. If no origin is supplied,
the current position is redefined as zero. Alternatively, you can supply
a position (in the current coordinate system of the axis) that should
henceforth be considered zero."""
if origin is None:
# Use current position
if self.motor is not None:
self.origin = self.motor.position
else:
if self.base_stage is None:
print(
"Error: %s %s has 'base_stage' and 'motor' set to 'None'."
% (self.__class__.__name__, self.name)
)
else:
self.origin = getattr(self.base_stage, self.name + "pos")(verbosity=0)
else:
# Use supplied value (in the current coordinate system)
base_position = self.cur_to_base(origin)
self.origin = base_position
def set_current_position(self, new_position):
"""Redefines the position value of the current position."""
current_position = self.get_position(verbosity=0)
self.origin = self.get_origin() + (current_position - new_position) * self.scaling
def search(
self,
step_size=1.0,
min_step=0.05,
intensity=None,
target=0.5,
detector=None,
detector_suffix=None,
polarity=+1,
verbosity=3,
):
"""Moves this axis, searching for a target value.
Parameters
----------
step_size : float
The initial step size when moving the axis
min_step : float
The final (minimum) step size to try
intensity : float
The expected full-beam intensity readout
target : 0.0 to 1.0
The target ratio of full-beam intensity; 0.5 searches for half-max.
The target can also be 'max' to find a local maximum.
detector, detector_suffix
The beamline detector (and suffix, such as '_stats4_total') to trigger to measure intensity
polarity : +1 or -1
Positive motion assumes, e.g. a step-height 'up' (as the axis goes more positive)
"""
if not get_beamline().beam.is_on():
print("WARNING: Experimental shutter is not open.")
if intensity is None:
intensity = RE.md["beam_intensity_expected"]
if detector is None:
# detector = gs.DETS[0]
detector = get_beamline().detector[0]
if detector_suffix is None:
# value_name = gs.TABLE_COLS[0]
value_name = get_beamline().TABLE_COLS[0]
else:
value_name = detector.name + detector_suffix
bec.disable_table()
# Check current value
RE(count([detector]))
value = detector.read()[value_name]["value"]
if target == "max":
if verbosity >= 5:
print("Performing search on axis '{}' target is 'max'".format(self.name))
max_value = value
max_position = self.get_position(verbosity=0)
direction = +1 * polarity
while step_size >= min_step:
if verbosity >= 4:
print(" move {} by {} × {}".format(self.name, direction, step_size))
self.move_relative(move_amount=direction * step_size, verbosity=verbosity - 2)
prev_value = value
RE(count([detector]))
value = detector.read()[value_name]["value"]
if verbosity >= 3:
print(
" {} = {:.3f} {}; value : {}".format(
self.name, self.get_position(verbosity=0), self.units, value
)
)
if value > max_value:
max_value = value
max_position = self.get_position(verbosity=0)
if value > prev_value:
# Keep going in this direction...
pass
else:
# Switch directions!
direction *= -1
step_size *= 0.5
elif target == "min":
if verbosity >= 5:
print("Performing search on axis '{}' target is 'min'".format(self.name))
direction = +1 * polarity
while step_size >= min_step:
if verbosity >= 4:
print(" move {} by {} × {}".format(self.name, direction, step_size))
self.move_relative(move_amount=direction * step_size, verbosity=verbosity - 2)
prev_value = value
RE(count([detector]))
value = detector.read()[value_name]["value"]
if verbosity >= 3:
print(
" {} = {:.3f} {}; value : {}".format(
self.name, self.get_position(verbosity=0), self.units, value
)
)
if value < prev_value:
# Keep going in this direction...
pass
else:
# Switch directions!
direction *= -1
step_size *= 0.5
else:
target_rel = target
target = target_rel * intensity
if verbosity >= 5:
print(
"Performing search on axis '{}' target {} × {} = {}".format(
self.name, target_rel, intensity, target
)
)
if verbosity >= 4:
print(" value : {} ({:.1f}%)".format(value, 100.0 * value / intensity))
# Determine initial motion direction
if value > target:
direction = -1 * polarity
else:
direction = +1 * polarity
while step_size >= min_step:
if verbosity >= 4:
print(" move {} by {} × {}".format(self.name, direction, step_size))
self.move_relative(move_amount=direction * step_size, verbosity=verbosity - 2)
RE(count([detector]))
value = detector.read()[value_name]["value"]
if verbosity >= 3:
print(
" {} = {:.3f} {}; value : {} ({:.1f}%)".format(
self.name,
self.get_position(verbosity=0),
self.units,
value,
100.0 * value / intensity,
)
)
# Determine direction
if value > target:
new_direction = -1.0 * polarity
else:
new_direction = +1.0 * polarity
if abs(direction - new_direction) < 1e-4:
# Same direction as we've been going...
# ...keep moving this way
pass
else:
# Switch directions!
direction *= -1
step_size *= 0.5
bec.enable_table()
def search_plan(
self,
motor=smy,
step_size=1.0,
min_step=0.05,
intensity=None,
target=0.5,
detector=None,
detector_suffix=None,
polarity=+1,
fastsearch=False,
verbosity=3,
):
"""Moves this axis, searching for a target value.
Parameters
----------
step_size : float
The initial step size when moving the axis
min_step : float
The final (minimum) step size to try
intensity : float
The expected full-beam intensity readout
target : 0.0 to 1.0
The target ratio of full-beam intensity; 0.5 searches for half-max.
The target can also be 'max' to find a local maximum.
detector, detector_suffix
The beamline detector (and suffix, such as '_stats4_total') to trigger to measure intensity
polarity : +1 or -1
Positive motion assumes, e.g. a step-height 'up' (as the axis goes more positive)
"""
@stage_decorator([detector])
def inner_search():
if not get_beamline().beam.is_on():
print("WARNING: Experimental shutter is not open.")
if intensity is None:
intensity = RE.md["beam_intensity_expected"]
if detector is None:
# detector = gs.DETS[0]
detector = get_beamline().detector[0]
if detector_suffix is None:
# value_name = gs.TABLE_COLS[0]
value_name = get_beamline().TABLE_COLS[0]
else:
value_name = detector.name + detector_suffix
bec.disable_table()
# Check current value
yield from bps.trigger_and_read([detector])
# RE(count([detector]))
value = detector.read()[value_name]["value"]
if fastsearch == True:
intenisty_threshold = 10
if (
abs(detector.stats2.max_xy.get().y - detector.stats2.centroid.get().y) < 20
and detector.stats2.max_value.get() > intenisty_threshold
):
# continue the fast alignment
print("The reflective beam is found! Continue the fast alignment")
return
if target == "max":
if verbosity >= 5:
print("Performing search on axis '{}' target is 'max'".format(self.name))
max_value = value
max_position = self.get_position(verbosity=0)
direction = +1 * polarity
while step_size >= min_step:
if verbosity >= 4:
print(" move {} by {} × {}".format(self.name, direction, step_size))
pos = yield from bps.rd(motor)
yield from bps.mv(motor, pos + direction * step_size)
# self.move_relative(move_amount=direction*step_size, verbosity=verbosity-2)
prev_value = value
yield from bps.trigger_and_read([detector])
# RE(count([detector]))
value = detector.read()[value_name]["value"]
if verbosity >= 3:
print(
" {} = {:.3f} {}; value : {}".format(
self.name,
self.get_position(verbosity=0),
self.units,
value,
)
)
if value > max_value:
max_value = value
# max_position = self.get_position(verbosity=0)
if value > prev_value:
# Keep going in this direction...
pass
else:
# Switch directions!
direction *= -1
step_size *= 0.5
elif target == "min":
if verbosity >= 5:
print("Performing search on axis '{}' target is 'min'".format(self.name))
direction = +1 * polarity
while step_size >= min_step:
if verbosity >= 4:
print(" move {} by {} × {}".format(self.name, direction, step_size))
pos = yield from bps.rd(motor)
yield from bps.mv(motor, pos + direction * step_size)
# self.move_relative(move_amount=direction*step_size, verbosity=verbosity-2)
prev_value = value