forked from NSLS-II/lsdc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
daq_macros.py
3987 lines (3551 loc) · 166 KB
/
daq_macros.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 Gen_Commands
import Gen_Traj_Square
import beamline_support
from beamline_support import getPvValFromDescriptor as getPvDesc, setPvValFromDescriptor as setPvDesc
import beamline_lib #did this really screw me if I imported b/c of daq_utils import??
import daq_lib
import daq_utils
import db_lib
from daq_utils import getBlConfig, setBlConfig
import det_lib
import math
import time
import glob
import xmltodict
from start_bs import *
import super_state_machine
import _thread
import parseSheet
import attenCalc
import raddoseLib
from raddoseLib import *
import logging
logger = logging.getLogger(__name__)
import os #for runDozorThread
import numpy as np # for runDozorThread
from string import Template
from collections import OrderedDict
from threading import Thread
from config_params import *
from kafka_producer import send_kafka_message
import gov_lib
from scans import (zebra_daq_prep, setup_zebra_vector_scan,
setup_zebra_vector_scan_for_raster,
setup_vector_program)
import bluesky.plan_stubs as bps
import bluesky.plans as bp
from bluesky.preprocessors import finalize_wrapper
from fmx_annealer import govStatusGet, govStateSet, fmxAnnealer, amxAnnealer # for using annealer specific to FMX and AMX
try:
import ispybLib
except Exception as e:
logger.error("daq_macros: ISPYB import error, %s" % e)
from XSDataMXv1 import XSDataResultCharacterisation
global rasterRowResultsList, processedRasterRowCount
global ednaActiveFlag
ednaActiveFlag = 0
global autoRasterFlag
autoRasterFlag = 0
rasterRowResultsList = []
global autoVectorFlag, autoVectorCoarseCoords
autoVectorCoarseCoords = {}
autoVectorFlag=False
C3D_SEARCH_BASE = f'{os.environ["PROJDIR"]}/software/c3d/c3d_search -p=$CONFIGDIR/'
IMAGES_PER_FILE = 500 # default images per HDF5 data file for Eiger
EXTERNAL_TRIGGER = 2 # external trigger for detector
#12/19 - general comments. This file takes the brunt of the near daily changes and additions the scientists request. Some duplication and sloppiness reflects that.
# I'm going to leave a lot of the commented lines in, since they might shed light on things or be useful later.
def hi_macro():
logger.info("hello from macros\n")
daq_lib.broadcast_output("broadcast hi")
def BS():
movr(omega,40)
def BS2():
ascan(omega,0,100,10)
def abortBS():
if (RE.state != "idle"):
try:
RE.abort()
except super_state_machine.errors.TransitionError:
logger.error("caught BS")
def changeImageCenterLowMag(x,y,czoom):
zoom = int(czoom)
zoomMinXRBV = getPvDesc("lowMagZoomMinXRBV")
zoomMinYRBV = getPvDesc("lowMagZoomMinYRBV")
minXRBV = getPvDesc("lowMagMinXRBV")
minYRBV = getPvDesc("lowMagMinYRBV")
sizeXRBV = getPvDesc("lowMagZoomSizeXRBV")
sizeYRBV = getPvDesc("lowMagZoomSizeYRBV")
sizeXRBV = 640.0
sizeYRBV = 512.0
roiSizeXRBV = getPvDesc("lowMagROISizeXRBV")
roiSizeYRBV = getPvDesc("lowMagROISizeYRBV")
roiSizeZoomXRBV = getPvDesc("lowMagZoomROISizeXRBV")
roiSizeZoomYRBV = getPvDesc("lowMagZoomROISizeYRBV")
inputSizeZoomXRBV = getPvDesc("lowMagZoomMaxSizeXRBV")
inputSizeZoomYRBV = getPvDesc("lowMagZoomMaxSizeYRBV")
inputSizeXRBV = getPvDesc("lowMagMaxSizeXRBV")
inputSizeYRBV = getPvDesc("lowMagMaxSizeYRBV")
x_click = float(x)
y_click = float(y)
binningFactor = 2.0
if (zoom):
xclickFullFOV = x_click + zoomMinXRBV
yclickFullFOV = y_click + zoomMinYRBV
else:
binningFactor = 2.0
xclickFullFOV = (x_click * binningFactor) + minXRBV
yclickFullFOV = (y_click * binningFactor) + minYRBV
new_minXZoom = xclickFullFOV-(sizeXRBV/2.0)
new_minYZoom = yclickFullFOV-(sizeYRBV/2.0)
new_minX = new_minXZoom - (sizeXRBV/2.0)
new_minY = new_minYZoom - (sizeYRBV/2.0)
noZoomCenterX = sizeXRBV/2.0
noZoomCenterY = sizeYRBV/2.0
if (new_minX < 0):
new_minX = 0
noZoomCenterX = (new_minXZoom+(sizeXRBV/2.0))/binningFactor
if (new_minY < 0):
new_minY = 0
noZoomCenterY = (new_minYZoom+(sizeYRBV/2.0))/binningFactor
if (new_minX+roiSizeXRBV>inputSizeXRBV):
new_minX = inputSizeXRBV-roiSizeXRBV
noZoomCenterX = ((new_minXZoom+(sizeXRBV/2.0)) - new_minX)/binningFactor
if (new_minY+roiSizeYRBV>inputSizeYRBV):
new_minY = inputSizeYRBV-roiSizeYRBV
noZoomCenterY = ((new_minYZoom+(sizeYRBV/2.0)) - new_minY)/binningFactor
if (new_minXZoom+roiSizeZoomXRBV>inputSizeZoomXRBV):
new_minXZoom = inputSizeZoomXRBV-roiSizeZoomXRBV
if (new_minXZoom < 0):
new_minXZoom = 0
setPvDesc("lowMagZoomMinX",new_minXZoom)
if (new_minYZoom+roiSizeZoomYRBV>inputSizeZoomYRBV):
new_minYZoom = inputSizeZoomYRBV-roiSizeZoomYRBV
if (new_minYZoom < 0):
new_minYZoom = 0
setPvDesc("lowMagZoomMinY",new_minYZoom)
setPvDesc("lowMagMinX",new_minX)
setPvDesc("lowMagMinY",new_minY)
setPvDesc("lowMagCursorX",noZoomCenterX)
setPvDesc("lowMagCursorY",noZoomCenterY)
def changeImageCenterHighMag(x,y,czoom):
zoom = int(czoom)
zoomMinXRBV = getPvDesc("highMagZoomMinXRBV")
zoomMinYRBV = getPvDesc("highMagZoomMinYRBV")
minXRBV = getPvDesc("highMagMinXRBV")
minYRBV = getPvDesc("highMagMinYRBV")
sizeXRBV = getPvDesc("highMagZoomSizeXRBV")
sizeYRBV = getPvDesc("highMagZoomSizeYRBV")
sizeXRBV = 640.0
sizeYRBV = 512.0
roiSizeXRBV = getPvDesc("highMagROISizeXRBV")
roiSizeYRBV = getPvDesc("highMagROISizeYRBV")
roiSizeZoomXRBV = getPvDesc("highMagZoomROISizeXRBV")
roiSizeZoomYRBV = getPvDesc("highMagZoomROISizeYRBV")
inputSizeZoomXRBV = getPvDesc("highMagZoomMaxSizeXRBV")
inputSizeZoomYRBV = getPvDesc("highMagZoomMaxSizeYRBV")
inputSizeXRBV = getPvDesc("highMagMaxSizeXRBV")
inputSizeYRBV = getPvDesc("highMagMaxSizeYRBV")
x_click = float(x)
y_click = float(y)
binningFactor = 2.0
if (zoom):
xclickFullFOV = x_click + zoomMinXRBV
yclickFullFOV = y_click + zoomMinYRBV
else:
binningFactor = 2.0
xclickFullFOV = (x_click * binningFactor) + minXRBV
yclickFullFOV = (y_click * binningFactor) + minYRBV
new_minXZoom = xclickFullFOV-(sizeXRBV/2.0)
new_minYZoom = yclickFullFOV-(sizeYRBV/2.0)
new_minX = new_minXZoom - (sizeXRBV/2.0)
new_minY = new_minYZoom - (sizeYRBV/2.0)
noZoomCenterX = sizeXRBV/2.0
noZoomCenterY = sizeYRBV/2.0
if (new_minX < 0):
new_minX = 0
noZoomCenterX = (new_minXZoom+(sizeXRBV/2.0))/binningFactor
if (new_minY < 0):
new_minY = 0
noZoomCenterY = (new_minYZoom+(sizeYRBV/2.0))/binningFactor
if (new_minX+roiSizeXRBV>inputSizeXRBV):
new_minX = inputSizeXRBV-roiSizeXRBV
noZoomCenterX = ((new_minXZoom+(sizeXRBV/2.0)) - new_minX)/binningFactor
if (new_minY+roiSizeYRBV>inputSizeYRBV):
new_minY = inputSizeYRBV-roiSizeYRBV
noZoomCenterY = ((new_minYZoom+(sizeYRBV/2.0)) - new_minY)/binningFactor
if (new_minXZoom+roiSizeZoomXRBV>inputSizeZoomXRBV):
new_minXZoom = inputSizeZoomXRBV-roiSizeZoomXRBV
if (new_minXZoom < 0):
new_minXZoom = 0
if (new_minYZoom+roiSizeZoomYRBV>inputSizeZoomYRBV):
new_minYZoom = inputSizeZoomYRBV-roiSizeZoomYRBV
if (new_minYZoom < 0):
new_minYZoom = 0
setPvDesc("highMagZoomMinX",new_minXZoom)
setPvDesc("highMagZoomMinY",new_minYZoom)
setPvDesc("highMagMinX",new_minX)
setPvDesc("highMagMinY",new_minY)
setPvDesc("highMagCursorX",noZoomCenterX)
setPvDesc("highMagCursorY",noZoomCenterY)
def autoRasterLoop(currentRequest):
global autoRasterFlag
gov_status = gov_lib.setGovRobot(gov_robot, 'SA')
if not gov_status.success:
return 0
if (getBlConfig("queueCollect") == 1):
delayTime = getBlConfig("autoRasterDelay")
time.sleep(delayTime)
reqObj = currentRequest["request_obj"]
if ("centeringOption" in reqObj):
if (reqObj["centeringOption"] == "AutoLoop"):
status = loop_center_xrec()
if (status== 0):
beamline_lib.mvrDescriptor("sampleX",1000)
status = loop_center_xrec()
if (status== 0):
beamline_lib.mvrDescriptor("sampleX",1000)
status = loop_center_xrec()
time.sleep(2.0)
status = loop_center_xrec()
return status
setTrans(getBlConfig("rasterDefaultTrans"))
daq_lib.set_field("xrecRasterFlag","100")
sampleID = currentRequest["sample"]
logger.info("auto raster " + str(sampleID))
status = loop_center_xrec()
if (status== 0):
beamline_lib.mvrDescriptor("sampleX",1000)
status = loop_center_xrec()
if (status== 0):
beamline_lib.mvrDescriptor("sampleX",1000)
status = loop_center_xrec()
time.sleep(2.0)
status = loop_center_xrec()
if (status == -99): #abort, never hit this
db_lib.updatePriority(currentRequest["uid"],5000)
return 0
if not (status):
return 0
time.sleep(2.0) #looks like I really need this sleep, they really improve the appearance
runRasterScan(currentRequest,"Coarse")
time.sleep(1.5)
loop_center_mask()
time.sleep(1)
autoRasterFlag = 1
runRasterScan(currentRequest,"Fine")
time.sleep(1)
runRasterScan(currentRequest,"Line")
gov_lib.setGovRobot(gov_robot, 'DI')
time.sleep(1)
autoRasterFlag = 0
return 1
def autoVector(currentRequest): #12/19 - not tested!
global autoVectorFlag
gov_status = gov_lib.setGovRobot(gov_robot, 'SA')
if not gov_status.success:
return 0
reqObj = currentRequest["request_obj"]
daq_lib.set_field("xrecRasterFlag","100")
sampleID = currentRequest["sample"]
logger.info("auto raster " + str(sampleID))
status = loop_center_xrec()
if (status== 0):
beamline_lib.mvrDescriptor("sampleX",1000)
status = loop_center_xrec()
if (status== 0):
beamline_lib.mvrDescriptor("sampleX",1000)
status = loop_center_xrec()
time.sleep(2.0)
status = loop_center_xrec()
if (status == -99): #abort, never hit this
db_lib.updatePriority(currentRequest["uid"],5000)
return 0
if not (status):
return 0
time.sleep(2.0) #looks like I really need this sleep, they really improve the appearance
autoVectorFlag = True
runRasterScan(currentRequest,"autoVector")
logger.info("autovec coarse coords 1")
logger.info(autoVectorCoarseCoords)
x1Start = autoVectorCoarseCoords["start"]["x"]
y1Start = autoVectorCoarseCoords["start"]["y"]
z1Start = autoVectorCoarseCoords["start"]["z"]
x1End = autoVectorCoarseCoords["end"]["x"]
y1End = autoVectorCoarseCoords["end"]["y"]
z1End = autoVectorCoarseCoords["end"]["z"]
loop_center_mask()
time.sleep(1)
runRasterScan(currentRequest,"autoVector")
autoVectorFlag = False
logger.info("autovec coarse coords 2")
logger.info(autoVectorCoarseCoords)
x2Start = autoVectorCoarseCoords["start"]["x"]
y2Start = autoVectorCoarseCoords["start"]["y"]
z2Start = autoVectorCoarseCoords["start"]["z"]
x2End = autoVectorCoarseCoords["end"]["x"]
y2End = autoVectorCoarseCoords["end"]["y"]
z2End = autoVectorCoarseCoords["end"]["z"]
x_vec_start = min(x1Start,x2Start)
y_vec_start = (y1Start+y2Start)/2.0
z_vec_start = (z1Start+z2Start)/2.0
x_vec_end = max(x1End,x2End)
y_vec_end = (y1End+y2End)/2.0
z_vec_end = (z1End+z2End)/2.0
vectorStart = {"x":x_vec_start,"y":y_vec_start,"z":z_vec_start}
vectorEnd = {"x":x_vec_end,"y":y_vec_end,"z":z_vec_end}
x_vec = x_vec_end - x_vec_start
y_vec = y_vec_end - y_vec_start
z_vec = z_vec_end - z_vec_start
trans_total = math.sqrt(x_vec**2 + y_vec**2 + z_vec**2)
framesPerPoint = 1
vectorParams={"vecStart":vectorStart,"vecEnd":vectorEnd,"x_vec":x_vec,"y_vec":y_vec,"z_vec":z_vec,"trans_total":trans_total,"fpp":framesPerPoint}
reqObj["vectorParams"] = vectorParams
reqObj["centeringOption"] = "Interactive" #kind of kludgy so that collectData doesn't go rastering for vector params again
currentRequest["request_obj"] = reqObj
db_lib.updateRequest(currentRequest)
daq_lib.collectData(currentRequest)
gov_lib.setGovRobot(gov_robot, 'SA')
return 1
def rasterScreen(currentRequest):
if (daq_utils.beamline == "fmx" and getBlConfig("scannerType") == "PI"):
gridRaster(currentRequest)
return
daq_lib.set_field("xrecRasterFlag","100")
sampleID = currentRequest["sample"]
reqObj = currentRequest["request_obj"]
gridStep = reqObj["gridStep"]
logger.info("rasterScreen " + str(sampleID))
time.sleep(20)
status = loop_center_xrec()
if (status== 0):
beamline_lib.mvrDescriptor("sampleX",200)
status = loop_center_xrec()
time.sleep(2.0)
status = loop_center_xrec()
if not (status):
return 0
time.sleep(1) #looks like I really need this sleep, they really improve the appearance
loopSize = getLoopSize()
if (loopSize != []):
rasterW = 1.5 * screenXPixels2microns(loopSize[1])
rasterH = 2.5 * screenXPixels2microns(loopSize[0])
if (rasterH > (1.2 * rasterW)): # for c3d error
rasterW = 630
rasterH = 510
else:
rasterW = 630
rasterH = 510
rasterReqID = defineRectRaster(currentRequest,rasterW,rasterH,gridStep)
db_lib.updatePriority(rasterReqID, -1)
RE(snakeRaster(rasterReqID))
def multiCol(currentRequest):
daq_lib.set_field("xrecRasterFlag","100")
sampleID = currentRequest["sample"]
logger.info("multiCol " + str(sampleID))
status = loop_center_xrec()
if not (status):
return 0
time.sleep(1) #looks like I really need this sleep, they really improve the appearance
runRasterScan(currentRequest,"Coarse")
def loop_center_xrec_slow():
global face_on
daq_lib.abort_flag = 0
for i in range(0,360,40):
if (daq_lib.abort_flag == 1):
logger.info("caught abort in loop center")
return 0
beamline_lib.mvaDescriptor("omega",i)
pic_prefix = "findloop_" + str(i)
time.sleep(1.5) #for video lag. This sucks
daq_utils.take_crystal_picture(filename=pic_prefix)
comm_s = "xrec " + os.environ["CONFIGDIR"] + "/xrec_360_40.txt xrec_result.txt"
logger.info(comm_s)
os.system(comm_s)
xrec_out_file = open("xrec_result.txt","r")
target_angle = 0.0
radius = 0
x_centre = 0
y_centre = 0
reliability = 0
for result_line in xrec_out_file.readlines():
logger.info(result_line)
tokens = result_line.split()
tag = tokens[0]
val = tokens[1]
if (tag == "TARGET_ANGLE"):
target_angle = float(val )
elif (tag == "RADIUS"):
radius = float(val )
elif (tag == "Y_CENTRE"):
y_centre_xrec = float(val )
elif (tag == "X_CENTRE"):
x_centre_xrec = float(val )
elif (tag == "RELIABILITY"):
reliability = int(val )
elif (tag == "FACE"):
face_on = float(tokens[3])
xrec_out_file.close()
xrec_check_file = open("Xrec_check.txt","r")
check_result = int(xrec_check_file.read(1))
logger.info("result = " + str(check_result))
xrec_check_file.close()
if (reliability < 70 or check_result == 0): #bail if xrec couldn't align loop
return 0
beamline_lib.mvaDescriptor("omega",target_angle)
x_center = getPvDesc("lowMagCursorX")
y_center = getPvDesc("lowMagCursorY")
logger.info("center on click " + str(x_center) + " " + str(y_center-radius))
logger.info("center on click " + str((x_center*2) - y_centre_xrec) + " " + str(x_centre_xrec))
fovx = daq_utils.lowMagFOVx
fovy = daq_utils.lowMagFOVy
daq_lib.center_on_click(x_center,y_center-radius,fovx,fovy,source="macro")
daq_lib.center_on_click((x_center*2) - y_centre_xrec,x_centre_xrec,fovx,fovy,source="macro")
beamline_lib.mvaDescriptor("omega",face_on)
#now try to get the loopshape starting from here
return 1
def generateRasterCoords4Traj(rasterRequest):
reqObj = rasterRequest["request_obj"]
exptimePerCell = reqObj["exposure_time"]
rasterDef = reqObj["rasterDef"]
stepsize = float(rasterDef["stepsize"])
omega = float(rasterDef["omega"])
rasterStartX = float(rasterDef["x"])
rasterStartY = float(rasterDef["y"])
rasterStartZ = float(rasterDef["z"])
omegaRad = math.radians(omega)
rasterCellMap = {}
numsteps = float(rasterDef["rowDefs"][0]["numsteps"])
columns = numsteps
rows = len(rasterDef["rowDefs"])
firstRow = rasterDef["rowDefs"][0]
sx1 = firstRow["start"]["x"] #startX
sy1 = firstRow["start"]["y"]
logger.info("start x,y")
logger.info(sx1)
logger.info(sy1)
#9/18 - I think these are crap, but will leave them
xRelativeMove = sx1
yzRelativeMove = sy1*math.sin(omegaRad)
yyRelativeMove = sy1*cos(omegaRad)
xMotAbsoluteMove1 = xRelativeMove
yMotAbsoluteMove1 = yyRelativeMove
zMotAbsoluteMove1 = yzRelativeMove
lastRow= rasterDef["rowDefs"][-1]
ex1 = lastRow["end"]["x"] #endX
ey1 = lastRow["end"]["y"]
logger.info("end x,y")
logger.info(ex1)
logger.info(ey1)
deltax = ex1-sx1
deltay = ey1-sy1
xMotAbsoluteMove1 = -(deltax/2.0)
xMotAbsoluteMove2 = (deltax/2.0)
yMotAbsoluteMove1 = -(deltay/2.0)*math.cos(omegaRad)
yMotAbsoluteMove2 = (deltay/2.0)*math.cos(omegaRad)
zMotAbsoluteMove1 = -(deltay/2.0)*math.sin(omegaRad)
zMotAbsoluteMove2 = (deltay/2.0)*math.sin(omegaRad)
logger.info(xMotAbsoluteMove1)
logger.info(yMotAbsoluteMove1)
logger.info(zMotAbsoluteMove1)
logger.info(xMotAbsoluteMove2)
logger.info(yMotAbsoluteMove2)
logger.info(zMotAbsoluteMove2)
logger.info(stepsize)
genTraj = Gen_Traj_Square.gen_traj_square(xMotAbsoluteMove1, xMotAbsoluteMove2, yMotAbsoluteMove2, yMotAbsoluteMove1, zMotAbsoluteMove2, zMotAbsoluteMove1, columns,rows)
Gen_Commands.gen_commands(genTraj,exptimePerCell)
def generateGridMap(rasterRequest,rasterEncoderMap=None): #12/19 - there's some dials vs dozor stuff in here
global rasterRowResultsList
reqObj = rasterRequest["request_obj"]
rasterDef = reqObj["rasterDef"]
stepsize = float(rasterDef["stepsize"])
omega = float(rasterDef["omega"])
rasterStartX = float(rasterDef["x"])
rasterStartY = float(rasterDef["y"])
rasterStartZ = float(rasterDef["z"])
omegaRad = math.radians(omega)
filePrefix = reqObj["directory"]+"/"+reqObj["file_prefix"]
rasterCellMap = {}
os.system("mkdir -p " + reqObj["directory"])
for i in range(len(rasterDef["rowDefs"])):
numsteps = float(rasterDef["rowDefs"][i]["numsteps"])
#next 6 lines to differentiate horizontal vs vertical raster
startX = rasterDef["rowDefs"][i]["start"]["x"]
endX = rasterDef["rowDefs"][i]["end"]["x"]
startY = rasterDef["rowDefs"][i]["start"]["y"]
endY = rasterDef["rowDefs"][i]["end"]["y"]
deltaX = abs(endX-startX)
deltaY = abs(endY-startY)
if ((deltaX != 0) and (deltaX>deltaY or not getBlConfig("vertRasterOn"))): #horizontal raster
if (i%2 == 0): #left to right if even, else right to left - a snake attempt
startX = rasterDef["rowDefs"][i]["start"]["x"]+(stepsize/2.0) #this is relative to center, so signs are reversed from motor movements.
else:
startX = (numsteps*stepsize) + rasterDef["rowDefs"][i]["start"]["x"]-(stepsize/2.0)
startY = rasterDef["rowDefs"][i]["start"]["y"]+(stepsize/2.0)
xRelativeMove = startX
yzRelativeMove = startY*math.sin(omegaRad)
yyRelativeMove = startY*math.cos(omegaRad)
xMotAbsoluteMove = rasterStartX+xRelativeMove
yMotAbsoluteMove = rasterStartY-yyRelativeMove
zMotAbsoluteMove = rasterStartZ-yzRelativeMove
numsteps = int(rasterDef["rowDefs"][i]["numsteps"])
for j in range(numsteps):
imIndexStr = str((i*numsteps)+j+1)
if (i%2 == 0): #left to right if even, else right to left - a snake attempt
xMotCellAbsoluteMove = xMotAbsoluteMove+(j*stepsize)
else:
xMotCellAbsoluteMove = xMotAbsoluteMove-(j*stepsize)
cellMapKey = 'cellMap_{}'.format(imIndexStr)
rasterCellCoords = {"x":xMotCellAbsoluteMove,"y":yMotAbsoluteMove,"z":zMotAbsoluteMove}
rasterCellMap[cellMapKey] = rasterCellCoords
else: #vertical raster
if (i%2 == 0): #top to bottom if even, else bottom to top - a snake attempt
startY = rasterDef["rowDefs"][i]["start"]["y"]+(stepsize/2.0) #this is relative to center, so signs are reversed from motor movements.
else:
startY = (numsteps*stepsize) + rasterDef["rowDefs"][i]["start"]["y"]-(stepsize/2.0)
startX = rasterDef["rowDefs"][i]["start"]["x"]+(stepsize/2.0)
xRelativeMove = startX
yzRelativeMove = startY*math.sin(omegaRad)
yyRelativeMove = startY*math.cos(omegaRad)
xMotAbsoluteMove = rasterStartX+xRelativeMove
yMotAbsoluteMove = rasterStartY-yyRelativeMove
zMotAbsoluteMove = rasterStartZ-yzRelativeMove
numsteps = int(rasterDef["rowDefs"][i]["numsteps"])
for j in range(numsteps):
imIndexStr = str((i*numsteps)+j+1)
if (i%2 == 0): #top to bottom if even, else bottom to top - a snake attempt
yMotCellAbsoluteMove = yMotAbsoluteMove-(math.cos(omegaRad)*(j*stepsize))
zMotCellAbsoluteMove = zMotAbsoluteMove-(math.sin(omegaRad)*(j*stepsize))
else:
yMotCellAbsoluteMove = yMotAbsoluteMove+(math.cos(omegaRad)*(j*stepsize))
zMotCellAbsoluteMove = zMotAbsoluteMove+(math.sin(omegaRad)*(j*stepsize))
cellMapKey = 'cellMap_{}'.format(imIndexStr)
rasterCellCoords = {"x":xMotAbsoluteMove,"y":yMotCellAbsoluteMove,"z":zMotCellAbsoluteMove}
rasterCellMap[cellMapKey] = rasterCellCoords
#commented out all of the processing, as this should have been done by the thread
if (rasterEncoderMap!= None):
rasterCellMap = rasterEncoderMap
if ("parentReqID" in rasterRequest["request_obj"]):
parentReqID = rasterRequest["request_obj"]["parentReqID"]
else:
parentReqID = -1
logger.info("RASTER CELL RESULTS")
dialsResultLocalList = []
for i in range (0,len(rasterRowResultsList)):
for j in range (0,len(rasterRowResultsList[i])):
try:
dialsResultLocalList.append(rasterRowResultsList[i][j])
except KeyError: #this is to deal with single cell row. Instead of getting back a list of one row, I get back just the row from Dials.
dialsResultLocalList.append(rasterRowResultsList[i])
break
rasterResultObj = {"sample_id": rasterRequest["sample"],"parentReqID":parentReqID,"rasterCellMap":rasterCellMap,"rasterCellResults":{"type":"dialsRasterResult","resultObj":dialsResultLocalList}}
rasterResultID = db_lib.addResultforRequest("rasterResult",rasterRequest["uid"], owner=daq_utils.owner,result_obj=rasterResultObj,proposalID=daq_utils.getProposalID(),beamline=daq_utils.beamline)
rasterResult = db_lib.getResult(rasterResultID)
return rasterResult
def rasterWait():
time.sleep(0.2)
while (getPvDesc("RasterActive")):
time.sleep(0.2)
def vectorWait():
time.sleep(0.15)
while (getPvDesc("VectorActive")):
time.sleep(0.05)
def vectorActiveWait():
start_time = time.time()
while (getPvDesc("VectorActive")!=1):
if time.time() - start_time > 3: #if we have waited long enough, just throw an exception
raise TimeoutError()
time.sleep(0.05)
def vectorHoldWait():
time.sleep(0.15)
while (getPvDesc("VectorState")!=2):
time.sleep(0.05)
def vectorProceed():
setPvDesc("vectorProceed",1)
def vectorSync():
setPvDesc("vectorSync",1)
def vectorWaitForGo(source="raster",timeout_trials=3):
while 1:
try:
setPvDesc("vectorGo",1)
vectorActiveWait()
break
except TimeoutError:
timeout_trials -= 1
logger.info('timeout_trials is down to: %s' % timeout_trials)
if not timeout_trials:
message = 'too many errors during %s vectorGo checks' % source
logger.error(message)
raise TimeoutError(message)
def makeDozorRowDir(directory,rowIndex):
"""Makes separate directory for each row for dozor output,
necessary to prevent file overwriting with mult. threads.
Parameters
----------
directory: str
main data directory with .h5 files
rowIndex: int
raster row index starts at 0
Returns
-------
rowDir: str
path to row directory
"""
dozorDir = directory + "/dozor"
rowDir = dozorDir + "/row_{}/".format(rowIndex)
os.system("mkdir -p " + rowDir)
return rowDir
def makeDozorInputFile(directory,prefix,rowIndex,rowCellCount,seqNum,rasterReqObj):
"""Creates input file for dozor that corresponds to an individual
raster row.
Parameters
----------
directory: str
main data directory with .h5 files
prefix: str
sample name from spreadsheet and include _Raster if raster
rowIndex: int
index of row to be processed from raster
rowCellCount: int
number of frames in specified row
seqNum: int
seqNum, not sure why skinner included these (unique id?)
rasterReqObj: dict
describes experimental metadata for raster request used to
set detector distance and beam center for dozor input file
"""
#detector metadata from raster request
orgX = rasterReqObj["xbeam"]
orgY = rasterReqObj["ybeam"]
wavelength = rasterReqObj["wavelength"]
detectorDistance = rasterReqObj["detDist"]
#detector metadata from epics PVs
roiMode = beamline_support.getPvValFromDescriptor("detectorROIMode")
if roiMode == 1:
detector = "eiger4m"
elif daq_utils.beamline in ("amx", "fmx"):
detector = beamline_support.getPvValFromDescriptor("detectorDescription")
detector = ''.join(detector.split()[1::]).lower() #format for dozor
else:
detector = "eiger2-9m"
nx = beamline_support.getPvValFromDescriptor("detectorNx")
ny = beamline_support.getPvValFromDescriptor("detectorNy")
firstImageNumber = int(rowIndex)*int(rowCellCount) + 1
hdf5TemplateImage = "../../{}_{}_??????.h5".format(prefix,seqNum,rowIndex)
daqMacrosPath = os.path.dirname(__file__)
inputTemplate = open(os.path.join(daqMacrosPath,"h5_template.dat"))
src = Template(inputTemplate.read())
dozorRowDir = makeDozorRowDir(directory,rowIndex)
dozorSpotLevel = getBlConfig(RASTER_DOZOR_SPOT_LEVEL)
if daq_utils.beamline == "nyx":
dozorPlugin = "/nsls2/software/mx/nyx/bin/dectris-neggia.so"
else:
dozorPlugin = "/usr/lib64/dectris-neggia.so"
templateDict = {"detector": detector,
"nx": nx,
"ny": ny,
"wavelength": wavelength,
"orgx": orgX,
"orgy": orgY,
"detector_distance": detectorDistance,
"first_image_number": firstImageNumber,
"number_images": rowCellCount,
"spot_level": dozorSpotLevel,
"name_template_image": hdf5TemplateImage,
"processing_plugin": dozorPlugin,}
with open("".join([dozorRowDir,f"h5_row_{rowIndex}.dat"]),"w") as f:
f.write(src.substitute(templateDict))
return dozorRowDir
def dozorOutputToList(dozorRowDir,rowIndex,rowCellCount,pathToMasterH5):
"""Takes a dozor_average.dat file and converts the results into
a list of dictionaries in the format previously implemented
in lsdc for dials.find_spots_client output. Intended for use
on a single row.
Parameters
----------
dozorRowDir: str
path to dozor row directory
rowIndex: int
index of row currently being processed by dozor thread
Returns
-------
localDozorRowList: list
list of dictionaries for input into analysisstore database
"""
dozorDat = str(os.path.join(dozorRowDir,"dozor_average.dat"))
if os.path.isfile(dozorDat):
try:
dozorData = np.genfromtxt(dozorDat,skip_header=3)[:,0:4]
except IndexError:
#in event of single cell raster, 1d array needs 2 dimensions
dozorData = np.genfromtxt(dozorDat,skip_header=3)[0:4]
dozorData = np.reshape(dozorData,(1,4))
else:
dozorData = np.zeros((rowCellCount,4))
dozorData[:,0] = np.arange(start=1,stop=dozorData.shape[0]+1)
logger.info(f"dozor_avg.dat file not found, empty result returned for row {rowIndex}")
dozorData[:,3][dozorData[:,3]==0] = 50 #required for scaling/visualizing res. results
keys = ["image",
"spot_count",
"spot_count_no_ice",
"d_min",
"d_min_method_1",
"d_min_method_2",
"total_intensity",
"cellMapKey"]
localList = []
for cell in range(0,dozorData.shape[0]):
seriesIndex = int(rowCellCount*rowIndex + dozorData[cell,:][0])
values = [(pathToMasterH5,seriesIndex),
dozorData[cell,:][1],
dozorData[cell,:][1],
dozorData[cell,:][3],
dozorData[cell,:][3],
dozorData[cell,:][3],
dozorData[cell,:][1]*dozorData[cell,:][2],
"cellMap_{}".format(seriesIndex)]
localList.append(OrderedDict(zip(keys,values)))
return localList
def runDozorThread(directory,
prefix,
rowIndex,
rowCellCount,
seqNum,
rasterReqObj,
rasterReqID):
"""Creates sub-directory that contains dozor input and output files
that result from master.h5 file in directory. Dozor executed via
ssh on remote node(s).
Parameters
----------
directory: str
path to directory containing .h5 files
prefix: str
includes sample name from spreadsheet and protocol if raster
rowIndex: int
row number to be processed (starts at 0)
seqNum: int
some parameter Skinner included, maybe to avoid duplicate filenames
rasterReqObj: dict
contains experimental metadata, used for setting detector dist and
beam center for dozor input files
rasterReqID: str
ID of raster collection
"""
global rasterRowResultsList,processedRasterRowCount
time.sleep(0.5) #allow for file writing
node = getNodeName("spot", rowIndex, 8)
if (seqNum>-1): #eiger
dozorRowDir = makeDozorInputFile(directory,
prefix,
rowIndex,
rowCellCount,
seqNum,
rasterReqObj)
else:
raise Exception("seqNum seems to be non-standard (<0)")
comm_s = f"ssh -q {node} \"{os.environ['MXPROCESSINGSCRIPTSDIR']}dozor.sh {rasterReqID} {rowIndex}\""
os.system(comm_s)
logger.info('checking for results on remote node: %s' % comm_s)
logger.info("leaving thread")
processedRasterRowCount += 1
pathToMasterH5 = "{}/{}_{}_master.h5".format(directory,
prefix,
seqNum)
rasterRowResultsList[rowIndex] = dozorOutputToList(dozorRowDir,
rowIndex,
rowCellCount,
pathToMasterH5)
return
def runDialsThread(requestID, directory,prefix,rowIndex,rowCellCount,seqNum):
global rasterRowResultsList,processedRasterRowCount
time.sleep(1.0)
node = getNodeName("spot", rowIndex, 8)
if (seqNum>-1): #eiger
startIndex=(rowIndex*rowCellCount) + 1
endIndex = startIndex+rowCellCount-1
comm_s = f"ssh -q {node} \"{os.environ['MXPROCESSINGSCRIPTSDIR']}eiger2cbf.sh {requestID} {startIndex} {endIndex} {rowIndex} {seqNum}\""
logger.info('eiger2cbf command: %s' % comm_s)
os.system(comm_s)
cbfDir = os.path.join(directory, "cbf")
CBF_conversion_pattern = os.path.join(cbfDir, f'{prefix}_{rowIndex}_')
CBFpattern = CBF_conversion_pattern + "*.cbf"
else:
CBFpattern = directory + "/cbf/" + prefix+"_" + str(rowIndex) + "_" + "*.cbf"
time.sleep(1.0)
comm_s = f"ssh -q {node} \"{os.environ['MXPROCESSINGSCRIPTSDIR']}dials_spotfind.sh {requestID} {rowIndex} {seqNum}\""
logger.info('checking for results on remote node: %s' % comm_s)
retry = 3
while(1):
resultString = "<data>\n"+os.popen(comm_s).read()+"</data>\n"
localDialsResultDict = xmltodict.parse(resultString)
if (localDialsResultDict["data"] == None and retry>0):
logger.error("ERROR \n" + resultString + " retry = " + str(retry))
retry = retry - 1
if (retry==0):
localDialsResultDict["data"]={}
localDialsResultDict["data"]["response"]=[]
for jj in range (0,rowCellCount):
localDialsResultDict["data"]["response"].append({'d_min': '-1.00',
'd_min_method_1': '-1.00',
'd_min_method_2': '-1.00',
'image': '',
'spot_count': '0',
'spot_count_no_ice': '0',
'total_intensity': '0',
'cellMapKey': 'cellMap_{}'.format(rowIndex*rowCellCount + jj + 1)})
break
else:
break
for kk in range(0,rowCellCount):
localDialsResultDict["data"]["response"][kk]["cellMapKey"] = 'cellMap_{}'.format(rowIndex*rowCellCount + kk + 1)
rasterRowResultsList[rowIndex] = localDialsResultDict["data"]["response"]
processedRasterRowCount+=1
logger.info("leaving thread")
def generateGridMapFine(rasterRequest,rasterEncoderMap=None,rowsOfSubrasters=0,columnsOfSubrasters=0,rowsPerSubraster=0,cellsPerSubrasterRow=0):
global rasterRowResultsList
reqObj = rasterRequest["request_obj"]
rasterDef = reqObj["rasterDef"]
stepsize = float(rasterDef["stepsize"])
omega = float(rasterDef["omega"])
rasterStartX = float(rasterDef["x"])
rasterStartY = float(rasterDef["y"])
rasterStartZ = float(rasterDef["z"])
omegaRad = math.radians(omega)
filePrefix = reqObj["directory"]+"/"+reqObj["file_prefix"]
rasterCellMap = {}
os.system("mkdir -p " + reqObj["directory"])
for i in range(len(rasterDef["rowDefs"])):
numsteps = float(rasterDef["rowDefs"][i]["numsteps"])
#next 6 lines to differentiate horizontal vs vertical raster
startX = rasterDef["rowDefs"][i]["start"]["x"]
endX = rasterDef["rowDefs"][i]["end"]["x"]
startY = rasterDef["rowDefs"][i]["start"]["y"]
endY = rasterDef["rowDefs"][i]["end"]["y"]
deltaX = abs(endX-startX)
deltaY = abs(endY-startY)
if (deltaX>deltaY): #horizontal raster
if (i%2 == 0): #left to right if even, else right to left - a snake attempt
startX = rasterDef["rowDefs"][i]["start"]["x"]+(stepsize/2.0) #this is relative to center, so signs are reversed from motor movements.
else:
startX = (numsteps*stepsize) + rasterDef["rowDefs"][i]["start"]["x"]-(stepsize/2.0)
startY = rasterDef["rowDefs"][i]["start"]["y"]+(stepsize/2.0)
xRelativeMove = startX
yzRelativeMove = startY*math.sin(omegaRad)
yyRelativeMove = startY*math.cos(omegaRad)
xMotAbsoluteMove = rasterStartX+xRelativeMove
yMotAbsoluteMove = rasterStartY-yyRelativeMove
zMotAbsoluteMove = rasterStartZ-yzRelativeMove
numsteps = int(rasterDef["rowDefs"][i]["numsteps"])
for j in range(numsteps):
imIndexStr = str((i*numsteps)+j+1)
if (i%2 == 0): #left to right if even, else right to left - a snake attempt
xMotCellAbsoluteMove = xMotAbsoluteMove+(j*stepsize)
else:
xMotCellAbsoluteMove = xMotAbsoluteMove-(j*stepsize)
if (daq_utils.detector_id == "EIGER-16"):
dataFileName = "%s_%06d.cbf" % (reqObj["directory"]+"/cbf/"+reqObj["file_prefix"]+"_Raster_"+str(i),(i*numsteps)+j+1)
else:
dataFileName = daq_utils.create_filename(filePrefix+"_Raster_"+str(i),(i*numsteps)+j+1)
rasterCellCoords = {"x":xMotCellAbsoluteMove,"y":yMotAbsoluteMove,"z":zMotAbsoluteMove}
rasterCellMap[dataFileName[:-4]] = rasterCellCoords
else: #vertical raster
if (i%2 == 0): #top to bottom if even, else bottom to top - a snake attempt
startY = rasterDef["rowDefs"][i]["start"]["y"]+(stepsize/2.0) #this is relative to center, so signs are reversed from motor movements.
else:
startY = (numsteps*stepsize) + rasterDef["rowDefs"][i]["start"]["y"]-(stepsize/2.0)
startX = rasterDef["rowDefs"][i]["start"]["x"]+(stepsize/2.0)
xRelativeMove = startX
yzRelativeMove = startY*math.sin(omegaRad)
yyRelativeMove = startY*math.cos(omegaRad)
xMotAbsoluteMove = rasterStartX+xRelativeMove
yMotAbsoluteMove = rasterStartY-yyRelativeMove
zMotAbsoluteMove = rasterStartZ-yzRelativeMove
numsteps = int(rasterDef["rowDefs"][i]["numsteps"])
for j in range(numsteps):
imIndexStr = str((i*numsteps)+j+1)
if (i%2 == 0): #top to bottom if even, else bottom to top - a snake attempt
yMotCellAbsoluteMove = yMotAbsoluteMove-(math.cos(omegaRad)*(j*stepsize))
zMotCellAbsoluteMove = zMotAbsoluteMove-(math.sin(omegaRad)*(j*stepsize))
else:
yMotCellAbsoluteMove = yMotAbsoluteMove+(math.cos(omegaRad)*(j*stepsize))
zMotCellAbsoluteMove = zMotAbsoluteMove+(math.sin(omegaRad)*(j*stepsize))
if (daq_utils.detector_id == "EIGER-16"):
dataFileName = "%s_%06d.cbf" % (reqObj["directory"]+"/cbf/"+reqObj["file_prefix"]+"_Raster_"+str(i),(i*numsteps)+j+1)
else:
dataFileName = daq_utils.create_filename(filePrefix+"_Raster_"+str(i),j+1)
rasterCellCoords = {"x":xMotAbsoluteMove,"y":yMotCellAbsoluteMove,"z":zMotCellAbsoluteMove}
rasterCellMap[dataFileName[:-4]] = rasterCellCoords
#commented out all of the processing, as this should have been done by the thread
if (rasterEncoderMap!= None):
rasterCellMap = rasterEncoderMap
if ("parentReqID" in rasterRequest["request_obj"]):
parentReqID = rasterRequest["request_obj"]["parentReqID"]
else:
parentReqID = -1
logger.info("RASTER CELL RESULTS")
if (rowsOfSubrasters != 0):
cellsPerSubraster = rowsPerSubraster*cellsPerSubrasterRow
subrastersPerCompositeRaster = rowsOfSubrasters*columnsOfSubrasters
rowsPerCompositeRaster = rowsPerSubraster*rowsOfSubrasters
cellsPerCompositeRasterRow = columnsOfSubrasters*cellsPerSubrasterRow
cellsPerCompositeRaster = cellsPerSubraster*subrastersPerCompositeRaster
subRasterListFlipped = []
for ii in range (0,len(rasterRowResultsList)):
subrasterFlipped = []
for i in range (0,rowsPerSubraster):
for j in range (0,cellsPerSubrasterRow):
origSubrasterIndex = (i*cellsPerSubrasterRow)+j
if (i%2 == 1): #odd,flip
subrasterIndex = (i*cellsPerSubrasterRow)+(cellsPerSubrasterRow-j-1)
else:
subrasterIndex = origSubrasterIndex
subrasterFlipped.append(rasterRowResultsList[ii][subrasterIndex])
subRasterListFlipped.append(subrasterFlipped)
dialsResultLocalList = []
for ii in range (0,rowsOfSubrasters):
for jj in range (0,rowsPerSubraster):
for i in range (0,columnsOfSubrasters):