-
Notifications
You must be signed in to change notification settings - Fork 0
/
hxn_gui_2.0.py
1408 lines (1123 loc) · 55 KB
/
hxn_gui_2.0.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
# __Author__: Ajith Pattammattel
# Original Date:06-23-2020
import os
import signal
import subprocess
import sys
import collections
import webbrowser
import pyqtgraph as pg
import json
import matplotlib
from scipy.ndimage import rotate
from epics import caget, caput
from PyQt5 import QtWidgets, uic, QtCore, QtGui, QtTest
from PyQt5.QtWidgets import QMessageBox, QFileDialog, QApplication, QLCDNumber, QLabel, QErrorMessage
from PyQt5.QtCore import QObject, QTimer, QThread, pyqtSignal, pyqtSlot, QRunnable, QThreadPool, QDate
from pdf_log import *
from xanes2d import *
from xanesFunctions import *
from HXNSampleExchange import *
ui_path = os.path.dirname(os.path.abspath(__file__))
class Ui(QtWidgets.QMainWindow):
def __init__(self):
super(Ui, self).__init__()
uic.loadUi(os.path.join(ui_path,'hxn_gui_2.0.ui'), self)
self.initParams()
self.ImageCorrelationPage()
self.client = webbrowser.get('firefox')
self.threadpool = QThreadPool()
self.tw_hxn_contact.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
self.energies = []
self.roiDict = {}
self.motor_list = {'zpssx': zpssx, 'zpssy': zpssy, 'zpssz': zpssz}
#self.updateLiveValues(self.livePVs)
#self.createlivePVList()
#self.liveUpdateTimer() #working
# updating resolution/tot time
self.dwell.valueChanged.connect(self.initParams)
self.x_step.valueChanged.connect(self.initParams)
self.y_step.valueChanged.connect(self.initParams)
self.x_start.valueChanged.connect(self.initParams)
self.y_start.valueChanged.connect(self.initParams)
self.x_end.valueChanged.connect(self.initParams)
self.y_end.valueChanged.connect(self.initParams)
# logic control for 1d or 2d scan selection
self.rb_1d.clicked.connect(self.disableMot2)
self.rb_2d.clicked.connect(self.enableMot2)
self.rb_1d.clicked.connect(self.initParams)
self.rb_2d.clicked.connect(self.initParams)
#Abort scan plan
self.pb_reqPause.clicked.connect(self.requestScanPause)
self.pb_REAbort.clicked.connect(self.scanAbort)
self.pb_REResume.clicked.connect(self.scanResume)
# text files and editor controls
self.pb_save_cmd.clicked.connect(self.save_file)
self.pb_clear_cmd.clicked.connect(self.clear_cmd)
self.pb_new_macro_gedit.clicked.connect(self.open_gedit)
self.pb_new_macro_vi.clicked.connect(self.open_vi)
self.pb_new_macro_emacs.clicked.connect(self.open_emacs)
self.pb_browse_a_macro.clicked.connect(self.get_a_file)
self.pb_ex_macro_open.clicked.connect(self.open_a_macro)
# plotting controls
self.pb_close_all_plot.clicked.connect(self.close_all_plots)
self.pb_plot.clicked.connect(self.plot_me)
self.pb_erf_fit.clicked.connect(self.plot_erf_fit)
self.pb_plot_line_center.clicked.connect(self.plot_line_center)
# xanes parameters
self.pb_gen_elist.clicked.connect(self.generateDataFrame)
self.pb_set_epoints.clicked.connect(self.generate_epoints)
self.pb_print_xanes_param.clicked.connect(lambda: self.ple_info.setPlainText(str(self.xanesParamsDict)))
self.pb_display_xanes_plan.clicked.connect(self.displayXANESPlan)
#self.pb_Start_Xanes.clicked.connect(self.runZPXANES)
self.pb_xanes_rsr_fldr.clicked.connect(self.getXanesUserFolder)
# scans and motor motion
self.start.clicked.connect(self.initFlyScan)
#self.start.clicked.connect(self.liveUpdateThread)
#self.start.clicked.connect(self.flyThread)
self.pb_move_smarx_pos.clicked.connect(self.move_smarx)
self.pb_move_smary_pos.clicked.connect(self.move_smary)
self.pb_move_smarz_pos.clicked.connect(self.move_smarz)
self.pb_move_dth_pos.clicked.connect(self.move_dsth)
self.pb_move_zpz_pos.clicked.connect(self.move_zpz1)
self.pb_move_smarx_neg.clicked.connect(lambda: self.move_smarx(neg_=True))
self.pb_move_smary_neg.clicked.connect(lambda: self.move_smary(neg_=True))
self.pb_move_smarz_neg.clicked.connect(lambda: self.move_smarz(neg_=True))
self.pb_move_dth_pos_neg.clicked.connect(lambda: self.move_dsth(neg_=True))
self.pb_move_zpz_neg.clicked.connect(lambda: self.move_zpz1(neg_=True))
# Detector/Camera Motions
#Merlin
self.pb_merlinOUT.clicked.connect(self.merlinOUT)
self.pb_merlinIN.clicked.connect(self.merlinIN)
#fluorescence det
self.pb_vortexOUT.clicked.connect(self.vortexOUT)
self.pb_vortexIN.clicked.connect(self.vortexIN)
#cam06
self.pb_cam6IN.clicked.connect(self.cam6IN)
self.pb_cam6OUT.clicked.connect(self.cam6OUT)
self.pb_CAM6_IN.clicked.connect(self.cam6IN)
self.pb_CAM6_OUT.clicked.connect(self.cam6OUT)
#cam11
self.pb_cam11IN.clicked.connect(self.cam11IN)
# sample exchange
#self.pb_start_pump.clicked.connect (lambda:StartPumpingProtocol([self.prb_pump_slow,self.prb_pump_fast]))
#self.pb_auto_he_fill.clicked.connect(lambda: StartAutoHeBackFill(self.prb_he_backfill))
#self.pb_vent.clicked.connect(lambda:ventChamber([self.prb_vent_slow,self.prb_vent_fast]))
# sample exchange
self.pb_start_pump.clicked.connect(self.pumpThread)
self.pb_auto_he_fill.clicked.connect(self.heBackFillThread)
self.pb_vent.clicked.connect(self.ventThread)
#SSA2 motion
self.pb_SSA2_Open.clicked.connect(lambda:self.SSA2_Pos(2.1, 2.1))
self.pb_SSA2_Close.clicked.connect(lambda:self.SSA2_Pos(0.05, 0.03))
self.pb_SSA2_Close.clicked.connect(lambda:self.SSA2_Pos(0.05, 0.03))
self.pb_SSA2_HClose.clicked.connect(lambda:self.SSA2_Pos(0.1, 2.1))
self.pb_SSA2_VClose.clicked.connect(lambda:self.SSA2_Pos(2.1, 0.1))
#s5 slits
self.pb_S5_Open.clicked.connect(lambda:self.S5_Pos(4,4))
self.pb_S5_Close.clicked.connect(lambda:self.S5_Pos(0.28,0.28))
self.pb_S5_HClose.clicked.connect(lambda:self.S5_Pos(0.1,0.28))
self.pb_S5_VClose.clicked.connect(lambda:self.S5_Pos(0.28,0.1))
#front end
self.pb_FS_IN.clicked.connect(self.FS_IN)
self.pb_FS_OUT.clicked.connect(self.FS_OUT)
#OSA Y Pos
self.pb_osa_out.clicked.connect(self.ZP_OSA_OUT)
self.pb_osa_in.clicked.connect(self.ZP_OSA_IN)
#alignment
self.pb_ZPZFocusScanStart.clicked.connect(self.zpFocusScan)
self.pb_MoveZPZ1AbsPos.clicked.connect(self.zpMoveAbs)
# sample position
self.pb_save_pos.clicked.connect(self.generatePositionDict)
self.pb_roiList_import.clicked.connect(self.importROIDict)
self.pb_roiList_export.clicked.connect(self.exportROIDict)
self.pb_roiList_clear.clicked.connect(self.clearROIList)
#self.sampleROI_List.itemClicked.connect(self.showROIPos)
#self.sampleROI_List.itemClicked.connect(lambda: self.ple_info.appendPlainText(
#(str(self.roiDict[self.sampleROI_List.currentItem().text()]))))
self.sampleROI_List.itemClicked.connect(self.showROIPosition)
self.pb_move_pos.clicked.connect(self.gotoROIPosition)
self.pb_recover_scan_pos.clicked.connect(self.gotoPosSID)
self.pb_show_scan_pos.clicked.connect(self.viewScanPosSID)
self.pb_print_scan_meta.clicked.connect(self.viewScanMetaData)
self.pb_copy_curr_pos.clicked.connect(self.copyPosition)
# Quick fill scan Params
self.pb_3030.clicked.connect(self.fill_common_scan_params)
self.pb_2020.clicked.connect(self.fill_common_scan_params)
self.pb_66.clicked.connect(self.fill_common_scan_params)
self.pb_22.clicked.connect(self.fill_common_scan_params)
#copy scan plan
self.pb_scan_copy.clicked.connect(self.copyScanPlan)
self.pb_batchscan_copy.clicked.connect(self.copyForBatch)
# elog
self.pb_pdf_wd.clicked.connect(self.select_pdf_wd)
self.pb_pdf_image.clicked.connect(self.select_pdf_image)
self.pb_save_pdf.clicked.connect(self.force_save_pdf)
self.pb_createpdf.clicked.connect(self.generate_pdf)
self.pb_fig_to_pdf.clicked.connect(self.InsertFigToPDF)
self.dateEdit_elog.setDate(QDate.currentDate())
# admin control
self.pb_apply_user_settings.clicked.connect(self.setUserLevel)
# close the application
self.actionClose_Application.triggered.connect(self.close_application)
self.liveUpdateThread()
self.scanStatusThread()
self.show()
def createlivePVList(self):
#any change here should be made at the thread class too
self.livePVs = {
self.lcd_ic3:int(caget("XF:03IDC-ES{Sclr:2}_cts1.D")),
self.lcd_monoE:caget("XF:03ID{}Energy-I"),
self.lcdPressure:caget("XF:03IDC-VA{VT:Chm-CM:1}P-I"),
self.lcd_scanNumber:int(caget("XF:03IDC-ES{Status}ScanID-I")),
self.db_smarx:smarx.position,
self.db_smary:smary.position,
self.db_smarz:smarz.position,
self.db_zpsth:np.around(zpsth.position,2),
self.lcd_ZpTh:np.around(zpsth.position,2),
self.db_zpz1:np.around(zp.zpz1.position,4),
self.db_ssa2_x:ssa2.hgap.position,
self.db_ssa2_y:ssa2.vgap.position,
self.db_fs:caget("XF:03IDA-OP{FS:1-Ax:Y}Mtr.RBV"),
self.db_cam6:caget("XF:03IDC-OP{Stg:CAM6-Ax:X}Mtr.RBV"),
self.db_fs_det:np.around(fdet1.x.position,1),
self.db_diffx:np.around(diff.x.position,1),
self.db_cam06x:caget("XF:03IDC-OP{Stg:CAM6-Ax:X}Mtr.RBV"),
self.db_s5_x:s5.hgap.position,
self.db_s5_y:s5.vgap.position
}
return self.livePVs
'''
#moved to a thread
def updateLiveValues(self,livePVs):
#print ("updating live values")
self.livePVs = self.createlivePVList()
for item in livePVs.items():
if isinstance (item[0],QLabel):
if item[1]==1:
item[0].setText(" Scan in Progress ")
item[0].setStyleSheet('background-color : green')
else:
item[0].setText(" Idle ")
item[0].setStyleSheet('background-color : yellow')
else:
#print("False")
item[0].setValue(item[1])
'''
def updateLiveVals(self,livePVList):
#print ("updating live values")
self.livePVs = self.createlivePVList()
livePVs = {key:value for key, value in zip(self.livePVs.keys(),livePVList)}
for item in livePVs.items():
item[0].setValue(item[1])
'''
def liveUpdateTimer(self):
#print("live update on")
self.updateTimer = QTimer()
self.updateTimer.timeout.connect(lambda:self.updateLiveValues(self.livePVs))
self.updateTimer.start(500)
'''
def scanStatus(self,sts):
if sts==1:
self.label_scanStatus.setText(" Scan in Progress ")
self.label_scanStatus.setStyleSheet("background-color:rgb(0, 255, 0);color:rgb(255,0, 0)")
else:
self.label_scanStatus.setText(" Idle ")
self.label_scanStatus.setStyleSheet("background-color:rgb(255, 255, 0);color:rgb(0, 255, 0)")
def scanStatusThread(self):
self.scanStatus_thread = liveStatus("XF:03IDC-ES{Status}ScanRunning-I")
self.scanStatus_thread.current_sts.connect(self.scanStatus)
self.scanStatus_thread.start()
def liveUpdateThread(self):
print("Thread Started")
self.liveWorker = liveUpdate()
self.liveWorker.current_positions.connect(self.updateLiveVals)
self.liveWorker.start()
def scanStatusMonitor(self):
scanStatus = caget("XF:03IDC-ES{Status}ScanRunning-I")
if scanStatus == 1:
self.label_scanStatus.setText("Scan in Progress")
self.label_scanStatus.setStyleSheet("background-color:rgb(0, 255, 0);color:rgb(255,0, 0)")
else:
self.label_scanStatus.setText("Idle")
self.label_scanStatus.setStyleSheet("background-color:rgb(255, 255, 0);color:rgb(0, 255, 0)")
def setUserLevel(self):
self.userButtonEnabler(self.cb_det_user, self.gb_det_control)
self.userButtonEnabler(self.cb_xanes_user, self.rb_xanes_scan)
self.userButtonEnabler(self.cb_xanes_user, self.gb_xanes_align)
def userButtonEnabler(self, checkbox_name, control_btn_grp_name):
if checkbox_name.isChecked():
control_btn_grp_name.setEnabled(True)
else:
control_btn_grp_name.setEnabled(False)
def getScanValues(self):
self.det = self.pb_dets.currentText()
self.mot1_s = self.x_start.value()
self.mot1_e = self.x_end.value()
self.mot1_steps = self.x_step.value()
self.mot2_s = self.y_start.value()
self.mot2_e = self.y_end.value()
self.mot2_steps = self.y_step.value()
self.dwell_t = self.dwell.value()
self.motor1 = self.cb_motor1.currentText()
self.motor2 = self.cb_motor2.currentText()
self.det_list = {'dets1': dets1, 'dets2': dets2, 'dets3': dets3,
'dets4': dets4, 'dets_fs': dets_fs}
def initParams(self):
self.getScanValues()
cal_res_x = abs(self.mot1_e - self.mot1_s) / self.mot1_steps
cal_res_y = abs(self.mot2_e - self.mot2_s) / self.mot2_steps
tot_t_2d = self.mot1_steps * self.mot2_steps * self.dwell_t / 60
tot_t_1d = self.mot1_steps * self.dwell_t / 60
if self.rb_1d.isChecked():
self.label_scan_info_calc.setText(f'X: {(cal_res_x * 1000):.2f} nm, Y: {(cal_res_y * 1000):.2f} nm \n'
f'{tot_t_1d:.2f} minutes + overhead')
self.scan_plan = f'fly1d({self.det},{self.motor1}, {self.mot1_s},{self.mot1_e}, ' \
f'{self.mot1_steps}, {self.dwell_t:.3f})'
else:
self.label_scan_info_calc.setText(f'X: {(cal_res_x * 1000):.2f} nm, Y: {(cal_res_y * 1000):.2f} nm \n'
f'{tot_t_2d:.2f} minutes + overhead')
self.scan_plan = f'fly2d({self.det}, {self.motor1},{self.mot1_s}, {self.mot1_e}, {self.mot1_steps},' \
f'{self.motor2},{self.mot2_s},{self.mot2_e},{self.mot2_steps},{self.dwell_t:.3f})'
self.text_scan_plan.setText(self.scan_plan)
def copyForBatch(self):
self.text_scan_plan.setText('yield from '+self.scan_plan)
self.text_scan_plan.selectAll()
self.text_scan_plan.copy()
def copyScanPlan(self):
self.text_scan_plan.setText('<'+self.scan_plan)
self.text_scan_plan.selectAll()
self.text_scan_plan.copy()
def initFlyScan(self):
self.getScanValues()
if self.rb_1d.isChecked():
RE(fly1d(self.det_list[self.det], self.motor_list[self.motor1],
self.mot1_s, self.mot1_e, self.mot1_steps, self.dwell_t))
else:
if self.motor_list[self.motor1] == self.motor_list[self.motor2]:
msg = QErrorMessage(self)
msg.setWindowTitle("Flyscan Motors are the same")
msg.showMessage(f"Choose two different motors for 2D scan. You selected {self.motor_list[self.motor1].name}")
return
else:
RE(fly2d(self.det_list[self.det], self.motor_list[self.motor1], self.mot1_s, self.mot1_e, self.mot1_steps,
self.motor_list[self.motor2], self.mot2_s, self.mot2_e, self.mot2_steps, self.dwell_t))
def flyThread(self):
flyWorker = Worker(self.initFlyScan)
self.threadpool.start(flyWorker)
def disableMot2(self):
self.y_start.setEnabled(False)
self.y_end.setEnabled(False)
self.y_step.setEnabled(False)
def enableMot2(self):
self.y_start.setEnabled(True)
self.y_end.setEnabled(True)
self.y_step.setEnabled(True)
def fill_common_scan_params(self):
button_name = self.sender()
button_names = {'pb_2020': (20, 20, 100, 100, 0.03),
'pb_3030': (30, 30, 30, 30, 0.03),
'pb_66': (6, 6, 100, 100, 0.05),
'pb_22': (2, 2, 100, 100, 0.03)
}
if button_name.objectName() in button_names.keys():
valsToFill = button_names[button_name.objectName()]
self.x_start.setValue(valsToFill[0] / -2)
self.x_end.setValue(valsToFill[0] / 2)
self.y_start.setValue(valsToFill[1] / -2)
self.y_end.setValue(valsToFill[1] / 2)
self.x_step.setValue(valsToFill[2])
self.y_step.setValue(valsToFill[3])
self.dwell.setValue(valsToFill[4])
def requestScanPause(self):
RE.request_pause(True)
self.pb_REAbort.setEnabled(True)
self.pb_REResume.setEnabled(True)
def scanAbort(self):
RE.abort()
self.pb_REAbort.setEnabled(False)
self.pb_REResume.setEnabled(False)
def scanResume():
RE.resume()
self.pb_REAbort.setEnabled(False)
self.pb_REResume.setEnabled(False)
def moveAMotor(self, val_box, mot_name, unit_conv_factor: float = 1, neg=False):
if neg:
move_by = val_box.value() * -1
else:
move_by = val_box.value()
RE(bps.movr(mot_name, move_by * unit_conv_factor))
self.ple_info.appendPlainText(f'{mot_name.name} moved by {move_by} um ')
def move_smarx(self, neg_=False):
self.moveAMotor(self.db_move_smarx, smarx, 0.001, neg=neg_)
def move_smary(self, neg_=False):
self.moveAMotor(self.db_move_smary, smary, 0.001, neg=neg_)
def move_smarz(self, neg_=False):
self.moveAMotor(self.db_move_smarz, smarz, 0.001, neg=neg_)
def move_dsth(self, neg_=False):
self.moveAMotor(self.db_move_dth, zpsth, neg=neg_)
def move_zpz1(self, neg_=False):
if neg_:
RE(movr_zpz1(self.db_move_zpz.value() * 0.001 * -1))
else:
RE(movr_zpz1(self.db_move_zpz.value() * 0.001))
def ZP_OSA_OUT(self):
curr_pos = caget("XF:03IDC-ES{ANC350:5-Ax:1}Mtr.VAL")
if curr_pos >2000:
self.ple_info.appendPlainText('OSAY is out of IN range')
else:
caput("XF:03IDC-ES{ANC350:5-Ax:1}Mtr.VAL",curr_pos+2700)
self.ple_info.appendPlainText('OSA Y moved OUT')
def ZP_OSA_IN(self):
curr_pos = caget("XF:03IDC-ES{ANC350:5-Ax:1}Mtr.VAL")
if curr_pos > 2500:
caput("XF:03IDC-ES{ANC350:5-Ax:1}Mtr.VAL",curr_pos-2700)
self.ple_info.appendPlainText('OSA Y is IN')
else:
self.ple_info.appendPlainText('OSA Y is close to IN position')
pass
def merlinIN(self):
self.client.open('http://10.66.17.43')
choice = QMessageBox.question(self, 'Detector Motion Warning',
"Make sure this motion is safe. \n Move?", QMessageBox.Yes |
QMessageBox.No, QMessageBox.No)
if choice == QMessageBox.Yes:
RE(go_det('merlin'))
else:
pass
def merlinOUT(self):
self.client.open('http://10.66.17.43')
choice = QMessageBox.question(self, 'Detector Motion Warning',
"Make sure this motion is safe. \n Move?", QMessageBox.Yes |
QMessageBox.No, QMessageBox.No)
if choice == QMessageBox.Yes:
RE(bps.mov(diff.x, -600))
else:
pass
def vortexIN(self):
RE(bps.mov(fdet1.x, -7))
caput("XF:03IDC-ES{Det:Vort-Ax:X}Mtr.VAL", -7)
self.ple_info.appendPlainText('FS det Moving')
def vortexOUT(self):
#RE(bps.mov(fdet1.x, -107))
caput("XF:03IDC-ES{Det:Vort-Ax:X}Mtr.VAL", -107)
self.ple_info.appendPlainText('FS det Moving')
def cam11IN(self):
self.client.open('http://10.66.17.43')
QtTest.QTest.qWait(5000)
choice = QMessageBox.question(self, 'Detector Motion Warning',
"Make sure this motion is safe. \n Move?", QMessageBox.Yes |
QMessageBox.No, QMessageBox.No)
if choice == QMessageBox.Yes:
RE(go_det('cam11'))
self.ple_info.appendPlainText('CAM11 is IN')
else:
pass
def cam6IN(self):
caput('XF:03IDC-OP{Stg:CAM6-Ax:X}Mtr.VAL', 0)
QtTest.QTest.qWait(1000)
self.ple_info.appendPlainText('CAM6 Moving!')
def cam6OUT(self):
caput('XF:03IDC-OP{Stg:CAM6-Ax:X}Mtr.VAL', -50)
QtTest.QTest.qWait(1000)
self.ple_info.appendPlainText('CAM6 Moving!')
def FS_IN(self):
caput('XF:03IDA-OP{FS:1-Ax:Y}Mtr.VAL', -57.)
caput("XF:03IDA-BI{FS:1-CAM:1}cam1:Acquire",1)
QtTest.QTest.qWait(20000)
#self.ple_info.appendPlainText('FS Motion Done!')
def FS_OUT(self):
caput('XF:03IDA-OP{FS:1-Ax:Y}Mtr.VAL', -20.)
caput("XF:03IDA-BI{FS:1-CAM:1}cam1:Acquire",0)
QtTest.QTest.qWait(20000)
#self.ple_info.appendPlainText('FS Motion Done!')
def SSA2_Pos(self, x, y):
caput('XF:03IDC-OP{Slt:SSA2-Ax:XAp}Mtr.VAL', x)
caput('XF:03IDC-OP{Slt:SSA2-Ax:YAp}Mtr.VAL', y)
QtTest.QTest.qWait(15000)
def S5_Pos(self, x, y):
caput('XF:03IDC-ES{Slt:5-Ax:Vgap}Mtr.VAL', x) #PV names seems flipped
caput('XF:03IDC-ES{Slt:5-Ax:Hgap}Mtr.VAL', y)
QtTest.QTest.qWait(15000)
def plot_me(self):
sd = self.pb_plot_sd.text()
elem = self.pb_plot_elem.text()
if ',' in sd:
slist_s, slist_e = sd.split(",")
f_sd = int(slist_s.strip())
l_sd = int(slist_e.strip())
space = abs(int(slist_e.strip())-int(slist_s.strip()))+1
s_list = np.linspace(f_sd, l_sd, space)
for sd_ in s_list:
plot_data(int(sd_), elem, 'sclr1_ch4')
else:
plot_data(int(sd), elem, 'sclr1_ch4')
def plot_erf_fit(self):
sd = self.pb_plot_sd.text()
elem = self.pb_plot_elem.text()
erf_fit(int(sd), elem, linear_flag=self.cb_erf_linear_flag.isChecked())
def plot_line_center(self):
sd = self.pb_plot_sd.text()
elem = self.pb_plot_elem.text()
return_line_center(int(sd), elem, threshold=self.dsb_line_center_thre.value())
def close_all_plots(self):
plt.close('all')
#xanes
def getXanesUserFolder(self):
self.xanes_folder = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
self.le_xanes_user_folder.setText(self.xanes_folder)
def generate_epoints(self):
pre = (self.dsb_pre_s.value(), self.dsb_pre_e.value(), self.sb_pre_p.value())
XANES1 = (self.dsb_ed1_s.value(), self.dsb_ed1_e.value(), self.sb_ed1_p.value())
XANES2 = (self.dsb_ed2_s.value(), self.dsb_ed2_e.value(), self.sb_ed2_p.value())
post = (self.dsb_post_s.value(), self.dsb_post_e.value(), self.sb_post_p.value())
self.energies = generateEPoints(ePointsGen=[pre,XANES1,XANES2,post])
self.ple_info.setPlainText(str(self.energies))
def importEPoints(self):
file_name = QFileDialog().getOpenFileName(self, "Save Parameter File", ' ',
'txt file(*txt)')
if file_name:
self.energies = np.loadtxt(file_name[0])
else:
pass
def exportEPoints(self):
self.generate_epoints()
file_name = QFileDialog().getSaveFileName(self, "Save Parameter File",
'xanes_e_points.txt',
'txt file(*txt)')
if file_name:
np.savetxt(file_name[0],np.array(self.energies))
else:
pass
def importXanesParams(self):
file_name = QFileDialog().getOpenFileName(self, "Load Parameter File", ' ',
'json file(*json)')
if file_name:
with open(file_name[0], 'r') as fp:
self.xanesParam = json.load(fp)
else:
pass
self.fillXanesParamBoxes(self.xanesParam)
def exportXanesParams(self):
self.xanesParam = {}
e_pos = {'low': self.dsb_monoe_l.value(), 'high':self.dsb_monoe_h.value()}
zpz1_pos = {'low': self.dsb_zpz_l.value(), 'high': self.dsb_zpz_h.value()}
self.xanesParam['mono_e'] = e_pos
self.xanesParam['zpz1'] = zpz1_pos
file_name = QFileDialog().getSaveFileName(self, "Save Parameter File",
'hxn_xanes_parameters.json',
'json file(*json)')
if file_name:
with open(f'{file_name[0]}', 'w') as fp:
json.dump(self.xanesParam,fp, indent=4)
else:
pass
def fillXanesParamBoxes(self,xanesParam:dict ):
e_low, e_high = xanesParam['mono_e']['low'], xanesParam['mono_e']['high']
ugap_low, ugap_high = xanesParam['ugap']['low'], xanesParam['ugap']['high']
zpz1_low, zpz1_high = xanesParam['zpz1']['low'], xanesParam['zpz1']['high']
self.dsb_monoe_l.setValue(e_low), self.dsb_monoe_h.setValue(e_high)
self.dsb_zpz_l.setValue(zpz1_low), self.dsb_zpz_h.setValue(zpz1_high)
self.le_crl_combo_xanes.setText(crl_combo)
def loadCommonXanesParams(self):
with open(os.path.join('.','xanes_common_elem_params.json'), 'r') as fp:
self.commonXanesParam = json.load(fp)
def insertCommonXanesParams(self):
mot_list = [self.dsb_monoe_l, self.dsb_monoe_h, self.dsb_zpz_l, self.dsb_zpz_h]
commonElems = self.commonXanesParam.keys()
button_name = self.sender().objectName()
if button_name in commonElems:
elemParam = self.commonXanesParam[button_name]
self.fillXanesParamBoxes(elemParam)
else:
pass
def generateDataFrame(self):
self.xanesParamsDict = {'high_e': self.dsb_monoe_h.value(), 'low_e': self.dsb_monoe_l.value(),
'high_e_zpz1': self.dsb_zpz_h.value(), 'zpz1_slope': self.dsb_zpz_slope.value(),
'energy': list(self.energies)}
if not len(self.energies) == 0:
self.e_list = generateEList(XANESParam=self.xanesParamsDict)
# print(energies)
self.ple_info.setPlainText(str(self.e_list))
else:
self.statusbar.showMessage('No energy list found; set or load an e list first')
def initXANESParams(self):
self.getScanValues()
self.doXAlign, self.doYAlign = self.cb_x_align.isChecked(),self.cb_y_align.isChecked()
self.x_align_s, self.x_align_e = self.x_align_start.value(), self.x_align_end.value()
self.x_align_stp, self.x_align_dw = self.x_align_steps.value(), self.x_align_dwell.value()
self.align_x_thr, self.x_align_elem = self.align_x_threshold.value(), self.le_x_align_elem.text()
self.y_align_s, self.y_align_e = self.y_align_start.value(), self.y_align_end.value()
self.y_align_stp, self.y_align_dw = self.y_align_steps.value(), self.y_align_dwell.value()
self.align_y_thr, self.y_align_elem = self.align_y_threshold.value(), self.le_y_align_elem.text()
self.elemPlot = tuple(self.plot_elem_xanes.text().split(','))
self.xanes_folder = self.le_xanes_user_folder.text()
def displayXANESPlan(self):
self.generateDataFrame()
self.initXANESParams()
scan_plan = f"<zp_list_xanes2d({self.xanesParamsDict}, {self.det},{self.motor1},{self.mot1_s}, {self.mot1_e}, {self.mot1_steps}," \
f"{self.motor2}, {self.mot2_s}, {self.mot2_e}, {self.mot2_steps}, {self.dwell_t}," \
f"alignX={(self.x_align_s, self.x_align_e, self.x_align_stp, self.x_align_dw,self.x_align_elem, self.align_x_thr,self.doXAlign)}," \
f"alignY={(self.y_align_s, self.y_align_e, self.y_align_stp,self.y_align_dw, self.y_align_elem, self.align_y_thr,self.doYAlign,)}," \
f"pdfElem={self.elemPlot},saveLogFolder={self.xanes_folder})"
self.te_xanes_plan.setText(str(scan_plan))
def fillCurrentPos(self):
e_ = e.position
zpz1_ = zp.zpz1.position
self.dsb_monoe_h.setValue(e_)
self.dsb_zpz_h.setValue(zpz1_)
def runZPXANES(self):
self.initXANESParams()
dE = e.position - self.e_list['energy'][0]
if dE < 1:
'''
RE(zp_list_xanes2d(self.xanesParamsDict,
self.det_list[self.det],
self.motor_list[self.motor1],
self.mot1_s,
self.mot1_e,
self.mot1_steps,
self.motor_list[self.motor2],
self.mot2_s,
self.mot2_e,
self.mot2_steps,
self.dwell_t,
alignX=(self.x_align_s,
self.x_align_e,
self.x_align_stp,
self.x_align_dw,
self.x_align_elem,
self.align_x_thr,
self.doXAlign),
alignY=(self.y_align_s,
self.y_align_e,
self.y_align_stp,
self.y_align_dw,
self.y_align_elem,
self.align_y_thr,
self.doYAlign),
pdfElem=self.elemPlot,
saveLogFolder=self.xanes_folder))
'''
print (" Test Passed")
else:
msg = QErrorMessage
msg.setWindowTitle("Energy change error")
msg.showMessage("Requested energy change is far from current position")
return
#tomo
def zpTomoStepResCalc(self):
pass
def zpTomo(self):
startAngle = self.sb_tomo_start_angle.value()
endAngle = self.sb_tomo_end_angle.value()
stepsAngle = self.sb_tomo_steps.value()
xAlignStart = None
xAlignEnd = None
xAlignSteps = None
xAlignDwell = None
xAlignElem = None
xAlignThreshold = None
yAlignStart = None
yAlignEnd = None
yAlignSteps = None
yAlignDwell = None
yAlignElem = None
yAlignThreshold = None
#special scans
def zpMosaic(self):
pass
def zpFocusScan(self):
zpStart = self.sb_ZPZ1RelativeStart.value()*0.001
zpEnd = self.sb_ZPZ1RelativeEnd.value()*0.001
zpSteps = self.sb_ZPZ1Steps.value()
scanMotor = self.motor_list[self.cb_foucsScanMotor.currentText()]
scanStart = self.sb_FocusScanMtrStart.value()
scanEnd = self.sb_FocusScanMtrEnd.value()
scanSteps = self.sb_FocusScanMtrStep.value()
scanDwell = self.dsb_FocusScanDwell.value()
fitElem = self.le_FocusingElem.text()
linFlag = self.cb_linearFlag_zpFocus.isChecked()
RE(zp_z_alignment(zpStart,zpEnd,zpSteps,scanMotor,scanStart,scanEnd,scanSteps,scanDwell,
elem= fitElem, linFlag = linFlag))
def zpMoveAbs(self):
zpTarget = self.dsb_ZPZ1TargetPos.value()
choice = QMessageBox.question(self, "Zone Plate Z Motion",
f"You're making an Absolute motion of ZP to {zpTarget}. \n Proceed?",
QMessageBox.Yes |
QMessageBox.No, QMessageBox.No)
QtTest.QTest.qWait(500)
if choice == QMessageBox.Yes:
RE(mov_zpz1(zpTarget))
else:
pass
def zpRotAlignment(self):
pass
#custom macros
def save_file(self):
S__File = QFileDialog.getSaveFileName(None, 'SaveFile', '/', "Python Files (*.py)")
Text = self.pte_run_cmd.toPlainText()
if S__File[0]:
with open(S__File[0], 'w') as file:
file.write(Text)
def clear_cmd(self):
self.pte_run_cmd.clear()
def open_gedit(self):
subprocess.Popen(['gedit'])
def open_vi(self):
subprocess.Popen(['vi'])
def open_emacs(self):
subprocess.Popen(['emacs'])
def get_a_file(self):
file_name = QFileDialog().getOpenFileName(self, "Open file")
self.le_ex_macro.setText(str(file_name[0]))
def open_a_macro(self):
editor = self.cb_ex_macro_with.currentText()
filename = self.le_ex_macro.text()
subprocess.Popen([editor, filename])
def abort_scan(self):
signal.signal(signal.SIGINT, signal.SIG_DFL)
RE.abort()
#Sample Chamber
def qMessageExcecute(self,funct):
QtTest.QTest.qWait(500)
choice = QMessageBox.question(self, 'Sample Chamber Operation Warning',
"Make sure this action is safe. \n Proceed?", QMessageBox.Yes |
QMessageBox.No, QMessageBox.No)
QtTest.QTest.qWait(500)
if choice == QMessageBox.Yes:
RE(funct)
else:
pass
# PDF Log
def select_pdf_wd(self):
folder_path = QFileDialog().getExistingDirectory(self, "Select Folder")
self.le_folder_log.setText(str(folder_path))
def select_pdf_image(self):
file_name = QFileDialog().getOpenFileName(self, "Select an Image")
self.le_elog_image.setText(str(file_name[0]))
def generate_pdf(self):
dt = self.dateEdit_elog.date()
tmp_date = dt.toString(self.dateEdit_elog.displayFormat())
tmp_file = os.path.join(self.le_folder_log.text(), self.le_elog_name.text())
tmp_sample = self.le_elog_sample.text()
tmp_experimenter = self.le_elog_experimenters.text()
tmp_pic = self.le_elog_image.text()
setup_pdf_for_gui(tmp_file, tmp_date, tmp_sample, tmp_experimenter, tmp_pic)
insertTitle_for_gui()
self.statusbar.showMessage(f'pdf generated as {tmp_file}')
def force_save_pdf(self):
save_page_for_gui()
def InsertFigToPDF(self):
insertFig_for_gui(note=self.le_pdf_fig_note.text(),
title=self.le_pdf_fig_title.text())
self.statusbar.showMessage("Figure added to the pdf")
# Sample Stage Navigation
def recordPositions(self):
fx, fy, fz = zpssx.position, zpssy.position, zpssz.position
cx, cy, cz = smarx.position, smary.position, smarz.position
zpz1_pos = zp.zpz1.position
zp_sx, zp_sz = zps.zpsx.position, zps.zpsz.position
th = zpsth.position
self.roi = {
zpssx: fx, zpssy: fy, zpssz: fz,
smarx: cx, smary: cy, smarz: cz,
zp.zpz1: zpz1_pos, zpsth: th,
zps.zpsx: zp_sx, zps.zpsz: zp_sz
}
def generatePositionDict(self):
self.recordPositions()
roi_name = 'ROI' + str(self.sampleROI_List.count())
self.roiDict[roi_name] = self.roi
self.sampleROI_List.addItem(roi_name)
#make the item editable
item = self.sampleROI_List.item(self.sampleROI_List.count()-1)
item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable)
def applyDictWithLabel(self):
label_ = {}
for idx in range(self.sampleROI_List.count()):
label = self.sampleROI_List.item(idx).text()
label_[label] = idx
self.roiDict['user_labels'] = label_
def exportROIDict(self):
self.applyDictWithLabel()
file_name = QFileDialog().getSaveFileName(self, "Save Parameter File",
'hxn_zp_roi_list.json',
'json file(*json)')
if file_name:
with open(file_name[0], 'w') as fp:
json.dump(self.roiDict, fp, indent=4)
else:
pass
def importROIDict(self):
file_name = QFileDialog().getOpenFileName(self, "Open Parameter File",
' ', 'json file(*json)')
if file_name:
self.roiDict = {}
with open(file_name[0], 'r') as fp:
self.roiDict = json.load(fp)
print(self.roiDict['user_labels'])
self.sampleROI_List.clear()
for num,items in enumerate(self.roiDict['user_labels']):
self.sampleROI_List.addItem(items)
item = self.sampleROI_List.item(num)
item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable)
else:
pass
def clearROIList(self):
self.sampleROI_List.clear()
def showROIPos(self,item):
item_num = self.sampleROI_List.row(item)
for key, value in self.roiDict[f'ROI{item_num}'].items():
self.ple_info.appendPlainText(f'{key.name}:{value:.4f}')
def gotoROIPosition(self):
roi_num = self.sampleROI_List.currentRow()
param_file = self.roiDict[f'ROI{roi_num}']
for key, value in param_file.items():
if not key == zp.zpz1:
RE(bps.mov(key, value))
elif key == zp.zpz1:
RE(mov_zpz1(value))
self.ple_info.appendPlainText(f'Sample moved to {key.name}:{value:.4f} ')
def showROIPosition(self, item):
item_num = self.sampleROI_List.row(item)
param_file = self.roiDict[f'ROI{item_num}']
self.ple_info.appendPlainText(('*' * 20))
for key, value in param_file.items():
self.ple_info.appendPlainText(f'{key.name}:{value:.4f}')
#self.sampleROI_List.itemClicked.connect(lambda: self.ple_info.appendPlainText(
# (self.roiDict[self.sampleROI_List.currentItem().text()])))
def gotoPosSID(self):
sd = self.le_sid_position.text()