-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsEQE.py
1290 lines (1002 loc) · 53.7 KB
/
sEQE.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 28 11:59:40 2018
@author: jungbluth
"""
import io
import itertools
import math
import os
import re
import sys
import time
import logging
import warnings
import GUI_template
import matplotlib
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import pandas as pd
import serial
import zhinst.utils
import zhinst.ziPython
# for the gui
from PyQt5 import QtCore, QtGui, QtWidgets
from matplotlib import style
from numpy import *
from scipy.interpolate import interp1d
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
warnings.filterwarnings("ignore")
self.logger = self.get_logger()
# Set up the user interface from Designer
self.ui = GUI_template.Ui_MainWindow()
self.ui.setupUi(self)
# Connections
self.mono_connected = False # Set the monochromator connection to False
self.lockin_connected = False # Set the Lock-in connection to False
self.filter_connected = False # Set the filterwheel connection to False
# General Setup
self.channel = 1
self.c = str(self.channel-1)
self.c6 = str(6)
self.do_plot = True
self.complete_scan = False
self.filter_addition = 'None' ####################################################################################
# Handle Monochromator Buttons
self.ui.connectButton_Mono.clicked.connect(self.connectToMono) # Connect only to Monochromator
self.ui.monoGotoButton.clicked.connect(self.MonoHandleWavelengthButton) # Go to specific wavelength
self.ui.monoSpeedButton.clicked.connect(self.MonoHandleSpeedButton) # Set scan speed
self.ui.monoGratingButton.clicked.connect(self.MonoHandleGratingButtons) # Change grating
self.ui.monoFilterButton.clicked.connect(self.MonoHandleFilterButton) # Change filter
self.ui.monoFilterInitButton.clicked.connect(self.MonoHandleFilterInitButton) # Initialize filter
# Handle Lock-in Buttons
self.ui.connectButton_Lockin.clicked.connect(self.connectToLockin) # Connect only to Lock-in
self.ui.lockinParameterButton.clicked.connect(self.LockinHandleParameterButton) # Set Lock-in parameters
# Handle Filterwheel Buttons
self.ui.connectButton_Filter.clicked.connect(self.connectToFilter) # Connect only to Filterwheel
# Handle Combined Buttons
self.ui.connectButton.clicked.connect(self.connectToEquipment)
self.ui.measureButtonRef_Si.clicked.connect(self.MonoHandleSiRefButton)
self.ui.measureButtonRef_GA.clicked.connect(self.MonoHandleGARefButton)
self.ui.measureButtonDev.clicked.connect(self.MonoHandleMeasureButton)
self.ui.stopButton.clicked.connect(self.HandleStopButton)
self.ui.completeScanButton_start.clicked.connect(self.MonoHandleCompleteScanButton) #########################################################################################
self.ui.completeScanButton_stop.clicked.connect(self.HandleStopCompleteScanButton) #########################################################################################
# Import photodiode calibration files
Si_file = pd.ExcelFile("FDS100-CAL.xlsx") # The files are in the sEQE Analysis folder
# print(Si_file.sheet_names)
self.Si_cal = Si_file.parse('Sheet1')
# print(self.Si_cal)
InGaAs_file = pd.ExcelFile("FGA21-CAL.xlsx")
self.InGaAs_cal = InGaAs_file.parse('Sheet1')
# Path to USB connections
self.filter_usb = '/dev/ttyUSB0' # NOTE: Change this if necessary
self.mono_usb = '/dev/ttyUSB1' # NOTE: Change this if necessary
# Path to save data
self.save_path = '/home/jungbluthl/Desktop/sEQE Data' # NOTE: Change this if necessary
# Close connection to Monochromator when window is closed
def __del__(self):
try:
self.p.close()
except:
pass
# -----------------------------------------------------------------------------------------------------------
#### Functions to connect to Monochromator and Lock-in
# -----------------------------------------------------------------------------------------------------------
# Establish serial connection to Monochromator
def connectToMono(self):
"""Function to establish connection to monochromator
:return: None
"""
self.p = serial.Serial(self.mono_usb, 9600, timeout=0)
self.p.write('HELLO\r'.encode()) # "Hello" initializes the Monochromator
time.sleep(25) # Sleep function makes window time out. This is to avoid that the user sends signals while the Monochromator is still initializing
self.mono_connected = self.waitForOK() # Checks for OK response of Monochromator
if self.mono_connected:
self.logger.info('Connection to Monochromator Established')
self.ui.imageConnect_mono.setPixmap(QtGui.QPixmap("Button_on.png"))
# Check Monochromator response
def waitForOK(self):
"""Function to wait for acceptance signal from monochromator
:raises LoggerError: Raises error if monochromator connection failed
...
:return: Returns True of connection successful, and False otherwise
:rtype: bool
"""
ret = False
self.p.timeout = 40000
shouldbEOk = self.p.readline()
if (shouldbEOk == ' ok\r\n'.encode()) or (shouldbEOk == ' ok\r\n'.encode()):
ret = True
else:
self.logger.error('Connection to Monochromator Could Not Be Established')
self.p.timeout = 0
return ret
# Establish connection to LOCKIN
def connectToLockin(self):
"""Function to establish connection to Lockin
:return: Returns Zurich Instruments localhost name and device details
"""
self.lockin_connected = False
# Open connection to ziServer
daq = zhinst.ziPython.ziDAQServer('localhost', 8005) # NOTE: Modify address if necessary
self.daq = daq
# Detect device
self.device = zhinst.utils.autoDetect(daq)
self.logger.info('Connection to Lock-In Established')
self.lockin_connected = True
self.ui.imageConnect_lockin.setPixmap(QtGui.QPixmap("Button_on.png"))
return self.daq, self.device
# Establish connection to Filterwheel
def connectToFilter(self):
"""Function to establish connection to filter wheel
:raises SerialException: Raises exception if filter wheel USB port is inaccessible
:raises OSError: Raises exception if filter wheel USB port is inaccessible
...
:return: None
"""
try:
self._fw = serial.Serial(port=self.filter_usb, baudrate=115200,
bytesize=8, parity='N', stopbits=1,
timeout=1, xonxoff=0, rtscts=0)
except serial.SerialException as ex:
self.logger.error('Port {0} is unavailable: {1}'.format(self.filter_usb, ex))
self.filter_connected = False
return
except OSError as ex:
self.logger.error('Port {0} is unavailable: {1}'.format(self.filter_usb, ex))
self.filter_connected = False
return
self._sio = io.TextIOWrapper(io.BufferedRWPair(self._fw, self._fw, 1),
newline=None, encoding='ascii')
self.logger.info("Connection to External Filter Wheel Established")
# self._sio.write('*idn?\r')
# devInfo = self._sio.readlines(2048)[1][:-1]
# print(devInfo)
self._sio.flush()
self.filter_connected = True
self.ui.imageConnect_filter.setPixmap(QtGui.QPixmap("Button_on.png"))
# -----------------------------------------------------------------------------------------------------------
# Establish connection to both
def connectToEquipment(self):
"""Function to establish connection to monochromator, Lockin & filter wheel
:return: None
"""
self.connectToLockin()
self.connectToMono()
self.connectToFilter()
self.ui.imageConnect.setPixmap(QtGui.QPixmap("Button_on.png"))
# -----------------------------------------------------------------------------------------------------------
#### Functions to handle parameter buttons for Monochromator and Lock-in
# -----------------------------------------------------------------------------------------------------------
## Monochromator Functions
# Set and GOTO wavelength
def MonoHandleWavelengthButton(self): # Function sets desired wavelength and calls chooseWavelength function
"""Function to read wavelength value from GUI
:return: None
"""
wavelength = self.ui.pickNM.value()
self.chooseWavelength(wavelength)
def chooseWavelength(self, wavelength): # Function to send GOTO command to monochromator
"""Function to send wavelength command to monochromator
:param wavelength: target wavelength
:type wavelength: float, required
...
:raises LoggerError: Raises error if monochromator not connected
...
:return: None
"""
if self.mono_connected:
print('%d nm' % wavelength)
self.p.write('{:.2f} GOTO\r'.format(wavelength).encode())
self.waitForOK()
else:
self.logger.error('Monochromator Not Connected')
# Update the scan speed
def MonoHandleSpeedButton(self): # Function sets desired scan speed and calls chooseScanSpeed function
"""Function to read monochromator speed from GUI
:return: None
"""
speed = self.ui.pickScanSpeed.value()
self.chooseScanSpeed(speed)
def chooseScanSpeed(self, speed): # Function to send scan speed command to monochromator
"""Function to send scan speed command to monochromator
:param speed: monochromator grating scan speed
:type speed: float, required
...
:raises LoggerError: Raises error if monochromator not connected
...
:return: None
"""
if self.mono_connected:
# self.logger.info('Updating Scan Speed to %d nm/min.' % speed)
self.p.write('{:.2f} NM/MIN\r'.format(speed).encode())
self.waitForOK()
else:
self.logger.error('Monochromator Not Connected')
# Set and move to grating
def MonoHandleGratingButtons(self): # Function sets desired grating number and calls chooseGrating function
"""Function to read grating number from monochromator
:return: None
"""
if self.ui.Blaze_300.isChecked():
gratingNo = 1
elif self.ui.Blaze_750.isChecked():
gratingNo = 2
elif self.ui.Blaze_1600.isChecked():
gratingNo = 3
self.chooseGrating(gratingNo)
def chooseGrating(self, gratingNo): # Function to send grating command to monochromator
"""Function to send grating command to monochromator
:param gratingNo: Monochromator grating number
:type gratingNo: float, required
...
:raises LoggerError: Raises error if monochromator not connected
...
:return: None
"""
if self.mono_connected:
self.logger.info('Moving to Grating %d' % gratingNo)
self.p.write('{:d} grating\r'.format(gratingNo).encode())
self.waitForOK()
else:
self.logger.error('Monochromator Not Connected')
# Update filter number
def MonoHandleFilterButton(self):
"""Function to read filter position from GUI
:return: None
"""
filterNo = int(self.ui.pickFilter.value())
self.chooseFilter(filterNo)
def chooseFilter(self, filterNo):
"""Function to send filter selection command to filter wheel
:param filterNo: Filter position
:type filterNo: float, required
...
:raises LoggerError: Raises error if monochromator not connected
...
:return: None
"""
if self.mono_connected:
# self.logger.info('Moving to Monochromator Filter %d' % filterNo)
self.p.write('{:d} FILTER\r'.format(filterNo).encode())
self.waitForOK()
else:
self.logger.error('Monochromator Not Connected')
# Initialize filter
def MonoHandleFilterInitButton(self):
"""Function to read filter initialization position from GUI
:return: None
"""
filterStart = self.ui.pickFilterInitStart.value()
filterDiff = int(8-filterStart)
self.initializeFilter(filterDiff)
def initializeFilter(self, filterDiff):
"""Function to initialize filter wheel
:param filterDiff: Difference between filter position and initialization position
:type filterDiff: int, required
...
:raises LoggerError: Raises error if monochromator not connected
...
:return: None
"""
if self.mono_connected:
self.logger.info('Initializing Monochromator Filter Wheel')
self.p.write('{:d} FILTER\r'.format(filterDiff).encode())
self.p.write('FHOME\r'.encode())
self.waitForOK()
self.ui.imageInit_filterwheel.setPixmap(QtGui.QPixmap("Button_on.png"))
else:
self.logger.error('Monochromator Not Connected')
# -----------------------------------------------------------------------------------------------------------
## Lock-in Functions
# Define and set Lock-in parameters
def LockinHandleParameterButton(self):
"""Function to read Lockin amplification value from GUI
:return: None
"""
if self.lockin_connected:
self.amplification = self.ui.pickAmp.value()
self.LockinUpdateParameters()
def LockinUpdateParameters(self): # Function sets desired Lock-in parameters and calls setParameter function
"""Function to update Lockin parameters
:raises LoggerError: Raises error if Lockin not connected
...
:return: None
"""
if self.lockin_connected:
self.c_2 = str(self.channel) # Channel 2, with value 1, for the reference input
self.tc = self.ui.pickTC.value() # Import value for time constant
self.rate = self.ui.pickDTR.value() # Import value for data transfer rate
self.lowpass = self.ui.pickLPFO.value() # Import value for low pass filter order
self.range = 2 # This sets the default voltage range to 2
self.ac = 0 # AC off
self.imp50 = 0 # 50 Ohm off
self.imp50_2 = 1 # Turn on 50 Ohm on channel 2 to attenuate signal from chopper controller as reference signal
self.diff = 1 # Diff off
# if self.ui.acButton.isChecked(): # AC on if button is checked
# self.ac = 1
# if self.ui.imp50Button.isChecked(): # 50 Ohm on if button is checked
# self.imp50 = 1
# if self.ui.diffButton.isChecked(): # Diff on if button is checked
# self.diff = 1
# self.frequency = self.ui.pickFreq.value() # For manual frequency control. The frequency tab is currently not implemented in the GUI
self.setParameters()
self.logger.info('Updating Lock-In Settings')
else:
self.logger.error("Lock-In Not Connected")
def setParameters(self):
"""Function to set default Lockin parameters
:return: None
"""
# c = str(0)
# print(self.amplification)
# Disable all outputs and all demods
general_setting = [
[['/', self.device, '/demods/0/trigger'], 0],
[['/', self.device, '/demods/1/trigger'], 0],
[['/', self.device, '/demods/2/trigger'], 0],
[['/', self.device, '/demods/3/trigger'], 0],
[['/', self.device, '/demods/4/trigger'], 0],
[['/', self.device, '/demods/5/trigger'], 0],
[['/', self.device, '/sigouts/0/enables/*'], 0],
[['/', self.device, '/sigouts/1/enables/*'], 0]
]
self.daq.set(general_setting)
# Set test settings
t1_sigOutIn_setting = [
[['/', self.device, '/sigins/',self.c,'/diff'], self.diff], # Diff Button (Enable for differential mode to measure the difference between +In and -In.)
[['/', self.device, '/sigins/',self.c,'/imp50'], self.imp50], # 50 Ohm Button (Enable to switch input impedance between low (50 Ohm) and high (approx 1 MOhm). Select for signal frequencies of > 10 MHz.)
[['/', self.device, '/sigins/',self.c,'/ac'], self.ac], # AC Button (Enable for AC coupling to remove DC signal. Cutoff frequency = 1kHz)
[['/', self.device, '/sigins/',self.c,'/range'], self.range], # Input Range
[['/', self.device, '/demods/',self.c,'/order'], self.lowpass], # Low-Pass Filter Order
[['/', self.device, '/demods/',self.c,'/timeconstant'], self.tc], # Time Constant
[['/', self.device, '/demods/',self.c,'/rate'], self.rate], # Data Transfer Rate
[['/', self.device, '/demods/',self.c,'/oscselect'], self.channel-1], # Oscillators
[['/', self.device, '/demods/',self.c,'/harmonic'], 1], # Harmonicss
[['/', self.device, '/demods/',self.c,'/phaseshift'], 0], # Phase Shift
[['/', self.device, '/zctrls/',self.c,'/tamp/0/currentgain'], self.amplification], # Amplifier Setting
[['/', self.device, '/demods/',self.c,'/adcselect'], self.channel-1], # ???
# For locked reference signal
[['/', self.device, '/sigins/', self.c_2,'/imp50'], self.imp50_2], # 50 Ohm Button (Enable to switch input impedance between low (50 Ohm) and high (approx 1 MOhm). Select for signal frequencies of > 10 MHz.)
[['/', self.device, '/plls/',self.c,'/enable'], 1], # Manual [0], External Reference [1]
[['/', self.device, '/plls/',self.c,'/adcselect'], 1], # ???
# For manual reference signal - The frequency tab is currently not implemented in the GUI
# [['/', self.device, '/plls/',self.c,'/enable'], 0], # Manual [0], External Reference [1]
# [['/', self.device, '/oscs/',self.c,'/freq'], self.frequency], # Demodulation Frequency
# Additional settings ?
# [['/', self.device, '/sigouts/',self.c,'/add'], -179.8390], # Output Add Button (Adds signal from "Add" connection)
# [['/', self.device, '/sigouts/',self.c,'/on'], 1], # Turn on Output Channel
# [['/', self.device, '/sigouts/',self.c,'/enables/',c6], 1], # Enable Output Channel
# [['/', self.device, '/sigouts/',self.c,'/range'], 1], # Output Range
# [['/', self.device, '/sigouts/',self.c,'/amplitudes/',c6], amplitude], # Output Amplitude
# [['/', self.device, '/sigouts/',self.c,'/offset'], 0], # Output Offset
]
self.daq.set(t1_sigOutIn_setting);
time.sleep(1) # wait 1s to get a settled lowpass filter
self.daq.flush() # clean queue
# self.logger.info("Lock-in settings have been updated")
# -----------------------------------------------------------------------------------------------------------
#### Functions to handle filter and grating changes
# -----------------------------------------------------------------------------------------------------------
def monoCheckFilter(self, wavelength): # Filter switching points from GUI
"""Function to update position of first filter wheel from GUI defaults
:param wavelength: Current wavelength position of monochromator
:type wavelength: float, required
...
:raises LoggerError: Raises error if filter wheel commands are invalid or monochromator not connected
...
:return: None
"""
if self.mono_connected:
self.p.write('?filter\r'.encode())
self.p.timeout = 30000
response = self.p.readline()
if (response == '1 ok\r\n'.encode()) or (response == ' 1 ok\r\n'.encode()):
filterNo = 1
elif (response == '2 ok\r\n'.encode()) or (response == ' 2 ok\r\n'.encode()):
filterNo = 2
elif (response == '3 ok\r\n'.encode()) or (response == ' 3 ok\r\n'.encode()):
filterNo = 3
elif (response == '4 ok\r\n'.encode()) or (response == ' 4 ok\r\n'.encode()):
filterNo = 4
elif (response == '5 ok\r\n'.encode()) or (response == ' 5 ok\r\n'.encode()):
filterNo = 5
elif (response == '6 ok\r\n'.encode()) or (response == ' 6 ok\r\n'.encode()):
filterNo = 6
else: # Do I need this?
self.logger.error('Error: Filter Response')
startNM_F2 = int(self.ui.startNM_F2.value())
stopNM_F2 = int(self.ui.stopNM_F2.value())
startNM_F3 = int(self.ui.startNM_F3.value())
stopNM_F3 = int(self.ui.stopNM_F3.value())
startNM_F4 = int(self.ui.startNM_F4.value())
stopNM_F4 = int(self.ui.stopNM_F4.value())
startNM_F5 = int(self.ui.startNM_F5.value())
stopNM_F5 = int(self.ui.stopNM_F5.value())
if startNM_F2 <= wavelength < stopNM_F2: # Filter 3 [FESH0700]: from 350 - 649 -- including start, excluing end
shouldbeFilterNo = 2
elif startNM_F3 <= wavelength < stopNM_F3: # Filter 3 [FESH0700]: from 350 - 649 -- including start, excluing end
shouldbeFilterNo = 3
elif startNM_F4 <= wavelength < stopNM_F4: # Filter 4 [FESH1000]: from 650 - 984 -- including start, excluding end
shouldbeFilterNo = 4
elif startNM_F5 <= wavelength <= stopNM_F5: # Filter 5 [FELH0950]: from 985 - 1800 -- including start, including end
shouldbeFilterNo = 5
else:
# shouldbeFilterNo = 2
self.logger.error('Error: Filter Out Of Range')
if shouldbeFilterNo != filterNo:
self.chooseFilter(shouldbeFilterNo)
# Take data and discard it, this is required to avoid kinks
# Poll data for 5 time constants, second parameter is poll timeout in [ms] (recomended value is 500ms)
dataDict = self.daq.poll(5*self.tc,500) # Dictionary with ['timestamp']['x']['y']['frequency']['phase']['dio']['trigger']['auxin0']['auxin1']['time']
else:
pass
else:
self.logger.error('Monochromator Not Connected')
def monoCheckGrating(self, wavelength): # Grating switching points from GUI
"""Function to update monochromator grating position from GUI defaults
:param wavelength: Current wavelength position of monochromator
:type wavelength: float, required
...
:raises LoggerError: Raises error if grating commands are invalid or monochromator not connected
...
:return: None
"""
if self.mono_connected:
self.p.write('?grating\r'.encode())
self.p.timeout = 30000
response = self.p.readline()
if (response == '1 ok\r\n'.encode()) or (response == ' 1 ok\r\n'.encode()):
gratingNo = 1
elif (response == '2 ok\r\n'.encode()) or (response == ' 2 ok\r\n'.encode()):
gratingNo = 2
elif (response == '3 ok\r\n'.encode()) or (response == ' 3 ok\r\n'.encode()):
gratingNo = 3
else: # Do I need this?
self.logger.error('Error: Grating Response')
startNM_G1 = int(self.ui.startNM_G1.value())
stopNM_G1 = int(self.ui.stopNM_G1.value())
startNM_G2 = int(self.ui.startNM_G2.value())
stopNM_G2 = int(self.ui.stopNM_G2.value())
startNM_G3 = int(self.ui.startNM_G3.value())
stopNM_G3 = int(self.ui.stopNM_G3.value())
if startNM_G1 <= wavelength < stopNM_G1: # Grating 1: from 350 - 549 -- including start, excluding end
shouldbeGratingNo = 1
elif startNM_G2 <= wavelength < stopNM_G2: # Grating 2: from 550 - 1299 -- including start, excluding end
shouldbeGratingNo = 2
elif startNM_G3 <= wavelength <= stopNM_G3: # Grating 3: from 1300 - 1800 -- including start, including end
shouldbeGratingNo = 3
else: # Do I need this?
self.logger.error('Error: Grating Out Of Range')
if shouldbeGratingNo != gratingNo:
self.chooseGrating(shouldbeGratingNo)
# Take data and discard it, this is required to avoid kinks
# Poll data for 5 time constants, second parameter is poll timeout in [ms] (recomended value is 500ms)
dataDict = self.daq.poll(5*self.tc,500) # Dictionary with ['timestamp']['x']['y']['frequency']['phase']['dio']['trigger']['auxin0']['auxin1']['time']
else:
pass
else:
self.logger.error('Monochromator Not Connected')
# -----------------------------------------------------------------------------------------------------------
#### Function to handle filter changes of Thorlabs filterwheel
# -----------------------------------------------------------------------------------------------------------
def changeFilter(self, pos):
"""Function to update position of second filter wheel
:param pos: Target filter position, between 1-6
:type pos: int, required
...
:raises LoggerError: Raises error if second filter wheel not connected
...
:return: Returns True if connection to second filter wheel is successful, False otherwise
"""
if not self.filter_connected:
self.logger.error("External Filter Wheel Not Connected")
return False
#ans = 'ERROR'
self._sio.flush()
self._sio.write('pos=' + str(pos) + '\r')
# ans = self._sio.readlines(2048)
# regerr = re.compile("Command error.*")
# errors = [m.group(0) for l in ans for m in [regerr.search(l)] if m]
# # print 'res=',repr(res),'ans=',repr(ans),cmd
# if len(errors) > 0:
# print(errors[0])
# return False
# ans = self.query(cmd + '?')
# print 'ans=',repr(ans),cmd+'?'
# print(ans)
return True
# -----------------------------------------------------------------------------------------------------------
#### Functions to handle measurement buttons
# -----------------------------------------------------------------------------------------------------------
# Set parameters and measure Silicon reference diode
def MonoHandleSiRefButton(self):
"""Function to meausure silicon reference photodiode
:return: None
"""
start_si = self.ui.startNM_Si.value()
stop_si = self.ui.stopNM_Si.value()
step_si = self.ui.stepNM_Si.value()
amp_si = self.ui.pickAmp_Si.value()
self.amplification = amp_si
self.LockinUpdateParameters()
self.MonoHandleSpeedButton()
scan_list = self.createScanJob(start_si, stop_si, step_si)
self.HandleMeasurement(scan_list, start_si, stop_si, step_si, amp_si, 1)
self.chooseFilter(1)
self.ui.imageRef_Si.setPixmap(QtGui.QPixmap("Button_on.png"))
self.logger.info('Finished Measurement')
# Set parameters and measure InGaAs reference diode
def MonoHandleGARefButton(self):
"""Function to meausure silicon reference photodiode
:return: None
"""
start_ga = self.ui.startNM_GA.value()
stop_ga = self.ui.stopNM_GA.value()
step_ga = self.ui.stepNM_GA.value()
amp_ga = self.ui.pickAmp_GA.value()
self.amplification = amp_ga
self.LockinUpdateParameters()
self.MonoHandleSpeedButton()
scan_list = self.createScanJob(start_ga, stop_ga, step_ga)
self.HandleMeasurement(scan_list, start_ga, stop_ga, step_ga, amp_ga, 2)
self.chooseFilter(1)
self.ui.imageRef_GA.setPixmap(QtGui.QPixmap("Button_on.png"))
self.logger.info('Finished Measurement')
# Set parameters and measure sample
def MonoHandleMeasureButton(self):
"""Function to meausure samples with different wavelength ranges
:return: None
"""
if self.ui.Range1.isChecked():
start_r1 = self.ui.startNM_R1.value()
stop_r1 = self.ui.stopNM_R1.value()
step_r1 = self.ui.stepNM_R1.value()
amp_r1 = self.ui.pickAmp_R1.value()
self.amplification = amp_r1
self.LockinUpdateParameters()
self.MonoHandleSpeedButton()
scan_list = self.createScanJob(start_r1, stop_r1, step_r1)
self.HandleMeasurement(scan_list, start_r1, stop_r1, step_r1, amp_r1, 3)
if self.ui.Range2.isChecked():
start_r2 = self.ui.startNM_R2.value()
stop_r2 = self.ui.stopNM_R2.value()
step_r2 = self.ui.stepNM_R2.value()
amp_r2 = self.ui.pickAmp_R2.value()
self.amplification = amp_r2
self.LockinUpdateParameters()
self.MonoHandleSpeedButton()
scan_list = self.createScanJob(start_r2, stop_r2, step_r2)
self.HandleMeasurement(scan_list, start_r2, stop_r2, step_r2, amp_r2, 3)
if self.ui.Range3.isChecked():
start_r3 = self.ui.startNM_R3.value()
stop_r3 = self.ui.stopNM_R3.value()
step_r3 = self.ui.stepNM_R3.value()
amp_r3 = self.ui.pickAmp_R3.value()
self.amplification = amp_r3
self.LockinUpdateParameters()
self.MonoHandleSpeedButton()
scan_list = self.createScanJob(start_r3, stop_r3, step_r3)
self.HandleMeasurement(scan_list, start_r3, stop_r3, step_r3, amp_r3, 3)
if self.ui.Range4.isChecked():
start_r4 = self.ui.startNM_R4.value()
stop_r4 = self.ui.stopNM_R4.value()
step_r4 = self.ui.stepNM_R4.value()
amp_r4 = self.ui.pickAmp_R4.value()
self.amplification = amp_r4
self.LockinUpdateParameters()
self.MonoHandleSpeedButton()
scan_list = self.createScanJob(start_r4, stop_r4, step_r4)
self.HandleMeasurement(scan_list, start_r4, stop_r4, step_r4, amp_r4, 3)
self.chooseFilter(1)
self.ui.imageMeasure.setPixmap(QtGui.QPixmap("Button_on.png"))
self.logger.info('Finished Measurement')
# Set parameters for complete scan and measure sample
def MonoHandleCompleteScanButton(self):
"""Function to meausure samples with different filters
:return: None
"""
self.complete_scan = True
if self.ui.scan_noFilter.isChecked():
self.changeFilter(1)
if self.changeFilter(1):
self.filter_addition = 'no'
self.logger.info('Moving to Open Filter Position')
start_f1 = self.ui.scan_startNM_1.value()
stop_f1 = self.ui.scan_stopNM_1.value()
step_f1 = self.ui.scan_stepNM_1.value()
amp_f1 = self.ui.scan_pickAmp_1.value()
self.amplification = amp_f1
self.LockinUpdateParameters()
self.MonoHandleSpeedButton()
scan_list = self.createScanJob(start_f1, stop_f1, step_f1)
self.HandleMeasurement(scan_list, start_f1, stop_f1, step_f1, amp_f1, 3)
if self.ui.scan_Filter2.isChecked():
self.changeFilter(2)
if self.changeFilter(2):
self.filter_addition = str(int(self.ui.cuton_filter_2.value()))
self.logger.info('Moving to %s nm Filter' % self.filter_addition)
start_f2 = self.ui.scan_startNM_2.value()
stop_f2 = self.ui.scan_stopNM_2.value()
step_f2 = self.ui.scan_stepNM_2.value()
amp_f2 = self.ui.scan_pickAmp_2.value()
self.amplification = amp_f2
self.LockinUpdateParameters()
self.MonoHandleSpeedButton()
scan_list = self.createScanJob(start_f2, stop_f2, step_f2)
self.HandleMeasurement(scan_list, start_f2, stop_f2, step_f2, amp_f2, 3)
if self.ui.scan_Filter3.isChecked():
self.changeFilter(3)
if self.changeFilter(3):
self.filter_addition = str(int(self.ui.cuton_filter_3.value()))
self.logger.info('Moving to %s nm Filter' % self.filter_addition)
start_f3 = self.ui.scan_startNM_3.value()
stop_f3 = self.ui.scan_stopNM_3.value()
step_f3 = self.ui.scan_stepNM_3.value()
amp_f3 = self.ui.scan_pickAmp_3.value()
self.amplification = amp_f3
self.LockinUpdateParameters()
self.MonoHandleSpeedButton()
scan_list = self.createScanJob(start_f3, stop_f3, step_f3)
self.HandleMeasurement(scan_list, start_f3, stop_f3, step_f3, amp_f3, 3)
if self.ui.scan_Filter4.isChecked():
self.changeFilter(4)
if self.changeFilter(4):
self.filter_addition = str(int(self.ui.cuton_filter_4.value()))
self.logger.info('Moving to %s nm Filter' % self.filter_addition)
start_f4 = self.ui.scan_startNM_4.value()
stop_f4 = self.ui.scan_stopNM_4.value()
step_f4 = self.ui.scan_stepNM_4.value()
amp_f4 = self.ui.scan_pickAmp_4.value()
self.amplification = amp_f4
self.LockinUpdateParameters()
self.MonoHandleSpeedButton()
scan_list = self.createScanJob(start_f4, stop_f4, step_f4)
self.HandleMeasurement(scan_list, start_f4, stop_f4, step_f4, amp_f4, 3)
if self.ui.scan_Filter5.isChecked():
self.changeFilter(5)
if self.changeFilter(5):
self.filter_addition = str(int(self.ui.cuton_filter_5.value()))
self.logger.info('Moving to %s nm Filter' % self.filter_addition)
start_f5 = self.ui.scan_startNM_5.value()
stop_f5 = self.ui.scan_stopNM_5.value()
step_f5 = self.ui.scan_stepNM_5.value()
amp_f5 = self.ui.scan_pickAmp_5.value()
self.amplification = amp_f5
self.LockinUpdateParameters()
self.MonoHandleSpeedButton()
scan_list = self.createScanJob(start_f5, stop_f5, step_f5)
self.HandleMeasurement(scan_list, start_f5, stop_f5, step_f5, amp_f5, 3)
if self.ui.scan_Filter6.isChecked():
self.changeFilter(6)
if self.changeFilter(6):
self.filter_addition = str(int(self.ui.cuton_filter_6.value()))
self.logger.info('Moving to %s nm Filter' % self.filter_addition)
start_f6 = self.ui.scan_startNM_6.value()
stop_f6 = self.ui.scan_stopNM_6.value()
step_f6 = self.ui.scan_stepNM_6.value()
amp_f6 = self.ui.scan_pickAmp_6.value()
self.amplification = amp_f6
self.LockinUpdateParameters()
self.MonoHandleSpeedButton()
scan_list = self.createScanJob(start_f6, stop_f6, step_f6)
self.HandleMeasurement(scan_list, start_f6, stop_f6, step_f6, amp_f6, 3)
self.changeFilter(1)
self.logger.info('Moving to open filter')
self.chooseFilter(1)
self.complete_scan = False
self.ui.imageCompleteScan_start.setPixmap(QtGui.QPixmap("Button_on.png"))
self.logger.info('Finished Measurement')
# General function to create scanning list
def createScanJob(self, start, stop, step):
"""Function to compile scan parameters
:param start: Wavelength start value
:type start: float, required
:param stop: Wavelength stop value
:type stop: float, required
:param step: Wavelength step value
:type step: float, required
...
:return: List of integer wavelength values
"""
scan_list = []
number = int((stop-start)/step)
for n in range(-1, number + 1): # -1 to start from before the beginning, +1 to include the last iteration of 'number', [and +2 to go above stop (this can be changed later])
wavelength = start + n*step
scan_list.append(wavelength)
return scan_list
# Scan through wavelength range ### Not being used currently
def Scan(self, scan_list):
"""Function to send commmands to monochromator and move through wavelength list
:param scan_list: List of wavelength values to scan
:type scan_list: list of ints, required
...
:raises LoggerError: Raises error if second filter wheel not connected
...
:return: None
"""
if self.mono_connected:
for element in scan_list:
self.p.write('{:.2f} GOTO\r'.format(element).encode())
# self.p.write('{:.2f} NM\r'.format(stop).encode())
self.waitForOK()
else:
self.logger.error('Monochromator Not Connected')
# -----------------------------------------------------------------------------------------------------------
#### Functions to handle measurement
# -----------------------------------------------------------------------------------------------------------
# Measure LOCKIN response
def HandleMeasurement(self, scan_list, start, stop, step, amp, number):
"""Function to prepare sample measurement
:param scan_list: List of wavelength values to scan
:type scan_list: list of ints, required
:param start: Wavelength start value
:type start: float, required
:param stop: Wavelength stop value
:type stop: float, required
:param step: Wavelength step value
:type step: float, required
:param amp: Pre-amplifier amplification value
:type amp: float, required
:param number: Specifier to decide if power value is calculated (1) or not (0)
:type number: int, required
...
:return: None
"""
if self.mono_connected and self.lockin_connected and self.filter_connected:
# Assign user, expriment and file name for current measurement
userName = self.ui.user.text()
experimentName = self.ui.experiment.text()
start_no = str(int(start))
stop_no = str(int(stop))
step_no = str(int(step))
amp_no = str(int(amp))
if number == 1:
# name = 'Si_ref_diode'
name = self.ui.file.text()
if number == 2:
# name = 'InGaAs_ref_diode'
name = self.ui.file.text()
if number == 3:
name = self.ui.file.text()
if not self.complete_scan: # If not a complete scan is taken
fileName = name + '_(' + start_no + '-' + stop_no + 'nm_' + step_no + 'nm_' + amp_no + 'x)'
elif self.complete_scan:
fileName = name + '_' + self.filter_addition + 'Filter' + '_(' + start_no + '-' + stop_no + 'nm_' + step_no + 'nm_' + amp_no + 'x)'
#Set up path to save data
self.path =f'{self.save_path}/{userName}/{experimentName}'
self.logger.info(f'Saving data to: {self.path}')
if not os.path.exists(self.path):
os.makedirs(self.path)
else: