-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmeasurement.py
2127 lines (2014 loc) · 111 KB
/
measurement.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
# Python imports
from __future__ import division
from hakkipaoli import HakkiPaoli, peakDetect, peakClean
import gainmedium
from numpy import *
from matplotlib import pyplot as pp
pp.ion()
from scipy import constants as scipycsts
import pylab
import sys,os,sqlite3,json,legacy,tables
import warnings
warnings.filterwarnings('ignore', category=tables.NaturalNameWarning)
from string import lower
import cPickle as pickle
from time import sleep, clock, time, strptime, mktime
from datetime import datetime
from scipy import io as scipyio, optimize, interpolate
from filter import savitzky_golay, smooth
from functools import partial
from multiprocessing import Pool, cpu_count
# QT imports
from PyQt4.QtCore import QCoreApplication,Qt,QTimer, QReadLocker
from PyQt4 import QtGui,QtCore
# Try to import visa library. Don't do anything if there is an import error since this is already dealt with in main
try:
from drivepy import visaconnection
NO_VISA=False
except (ImportError, OSError) as e:
NO_VISA=True
# Import the rest of the instruments if visa library exists, otherwise don't bother since no real tests can be done without this library
if not NO_VISA:
# SMU
from drivepy.keithley.smu import SMU
# Flags for instrument to use for power meters. Can take values ("Newport", "DMM", "Winspec", None)
POWER_METERS={"primary":"Agilent","secondary":"Agilent","prealign":"Newport","roughAlign":"Agilent","fineAlign":"Agilent"}
""" Import all the instruments which can be used as a power meter"""
try:
# Main Agilent power meter
from drivepy.agilent.powermeter import PowerMeter as AgilentPowerMeter
except Exception as e:
print("Error: Agilent power meter could not be imported")
try:
# Newport power meter
from drivepy.newport.powermeter import PowerMeter as NewportPowerMeter
except Exception as e:
print("Error: Newport power meter could not be imported")
try:
# Newfocus power meter via DMM
from drivepy.newfocus.powermeter import PowerMeter as NewfocusPowerMeter
except Exception as e:
print("Error: Newfocus power meter could not be imported")
try:
# Winspec used as a power meter
from winspecanalyzer import WinspecAnalyzer as WinspecPowerMeter
except Exception as e:
print("Error: Winspec power meter could not be imported")
def getPowerMeterLib(flag):
""" Return the intended module for the chosen power meter"""
if flag=="Agilent":
return AgilentPowerMeter
elif flag=="Newport":
return NewportPowerMeter
elif flag=="Newfocus":
return NewfocusPowerMeter
elif flag=="Winspec":
return WinspecPowerMeter
else:
print("Flag " + flag + " not found")
PrimaryPowerMeter = getPowerMeterLib(POWER_METERS["primary"])
SecondaryPowerMeter = getPowerMeterLib(POWER_METERS["secondary"])
PrealignPowerMeter = getPowerMeterLib(POWER_METERS["prealign"])
RoughAlignPowerMeter = getPowerMeterLib(POWER_METERS["roughAlign"])
FineAlignPowerMeter = getPowerMeterLib(POWER_METERS["fineAlign"])
from winspecanalyzer import WinspecAnalyzer, MAX_COUNTS
from drivepy.anritsu.spectrumanalyzer import SpectrumAnalyzer
from drivepy.keithley.dmm import DMM
#from drivepy.advantest.spectrumanalyzer import SpectrumAnalyzer
from drivepy.scientificinstruments.temperaturecontroller import TemperatureController
from align import PiezoAlign, MotorAlign
try:
from drivepy.thorlabs.fw102c import FilterWheel
except:
pass
# Global variables
NO_TEMP_SENSOR=False # Flag to remember if the user chose not to measure temperature
MAX_CPS_PER_NANOWATT_LOW_GAIN=50e3 # Assumption for max counts per second per nanowatt input with detector on low gain setting. Measure close to threshold.
SPECTRUM_TAU=1 # Minimum time in ms to meas over necessary to average temporal effects
SPECTRUM_TAU_LOWTEMP=500 # Minimum time in ms to meas over necessary to average temporal effects with cryostat on
WINSPEC_MIN_EXPOSURE=1e-6 # Minimum exposure time possible in Winspec before problems occur (not the same as total measurement time above)
WINSPEC_MIN_EXPOSURE_HIGAIN=50e-3 # Minimum exposure time we want to use under high gain setting
WINSPEC_MAX_ACCUMULATIONS=2000 # Maximum number of accumulations in Winspec before errors start to occur
WINSPEC_DEFAULT_EXPOSURE=0.3 # Default exposure time for Winspec when we have no information to start with
WINSPEC_MAX_TEMPERATURE=-30 # Maximum detector temperature we can get reliable data from
WINSPEC_DEFAULT_EFFICIENCY=1.8e-13 # Default value for num input photons per detector count
ALIGNMENT_CURRENT=80e-3 # Current to set for the device when using autoalign
ALIGNMENT_TAU=400 # Averaging time in ms for power meter measurements (normal conditions)
ALIGNMENT_TAU_LOWTEMP=500 # Averaging time in ms for power meter measurements (low temperature conditions)
ALIGNMENT_FINE_RES=0.50 # Resolution of search grid for fine alignment in um
ALIGNMENT_FINE_SPAN=1.0 # Half-span of search grid for fine alignment in um (1=> +/- 1um)
ALIGNMENT_FINE_CURRENT_DEFAULT=5e-3 # Current to set for the device when using autoalign with fine grid
ALIGNMENT_ROUGH_RES=0.002 # Resolution of search grid for rough alignment in mm
PRE_ALIGNMENT_ROUGH_RES=0.02 # Resolution of search grid for pre-align optimization in mm
PRE_ALIGNMENT_SEARCH_RES=0.04 # Resolution for signal search during pre-align in mm
PREALIGNMENT_SOFT_SEARCH_THRESH = 100e-9
ALIGNMENT_SIGNAL_SEARCH_RES=0.004 # Resolution for signal search in mm
ALIGNMENT_SIGNAL_SEARCH_THRESH=1e-6 # Power threshold for detected signal
ALIGNMENT_SOFT_SEARCH_THRESH=1e-9 # Power threshold before we even attempt optimization during signal search
FEEDBACK_CALIBRATION_CURRENT=60e-3 # Drive current used when calibrating the feedback amount for RIN
LIV_TAU=20 # Averaging time in ms for power meter measurements (normal conditions)
LIV_TAU_LOWTEMP=500 # Averaging time in ms for power meter measurements (low temperature conditions)
LIV_MIN_MAX_POWER=0.5e-6 # The threshold for max(power), below which the measurement is considered unsuccessful
LOWTEMP_THRESHOLD=295 # Temperature in Kelvin, below which we assume the cryostat is on and use a longer measurement time to average vibration
SPECTRUM_MIN_CURRENT=0.01e-3 # Currents below this point will be clipped
MIN_REALIGNMENT_TIME=15 # Minimum time before re-checking the alignment (minutes)
RIN_MIN_FREQ=500e6 # Lower cutoff frequency for RIN plotting and noise floor calculation
AUTO_ALIGN=False
__DBPATH__=None # Path to the database file
class Session(QtCore.QObject):
finished=QtCore.pyqtSignal()
finishedPlottingSignal=QtCore.pyqtSignal()
plotDataReady=QtCore.pyqtSignal(dict)
progress=QtCore.pyqtSignal(float)
plotProgress=QtCore.pyqtSignal(float)
aborted=QtCore.pyqtSignal()
""" Measurement 'session' is a group that holds all the measurements and talks to the database etc """
def __init__(self,newDB,fname,parent=None):
self.main=parent
super(Session, self).__init__()
self.activeMeasList=None
if lower(os.path.splitext(fname)[-1])==".db":
# support opening of legacy db files if they have the *.db extension
self.db=db=sqlite3.connect(fname)
h5fname=os.path.splitext(fname)[0]+".h5"
if os.path.exists(h5fname):
raise DatabaseWriteException, "Please delete or rename the file '" + h5fname + "' so that the selected legacy .db sqlite database can be converted to HDF5."
else:
self.h5db=tables.openFile(h5fname, mode = "w")
else:
# Treat all other files as HDF5 files, or more generally as pytables files (the default extension is h5). Open in append mode so that any existing data isn't overwritten.
if newDB:
self.db=db=tables.openFile(fname, mode = "w")
else:
self.db=db=tables.openFile(fname, mode = "a")
if not db:
# Exit the application if there was an error opening the database for some reason
QtGui.QMessageBox.warning(None,"Database Error",("There was a database error... exiting the application"))
sys.exit(1)
if newDB:
# create new database
self.initializeDatabase_()
self.measurements=[]
else:
# open existing database
self.measurements=self.fetchAllMeasurements()
# set global variable for the database directory
global __DBPATH__
__DBPATH__=os.path.normpath(fname)
def __del__(self):
""" Close the database when the session object is deleted """
self.db.close()
def plot(self,groupName=None,plotType=None):
""" Plots the threshold current vs temperature """
self.plotProgress.emit(0)
# choose a default plot type if none was specified
if plotType is None:
if isinstance(self.activeMeasList[0], LIV):
plotType="ThresholdCurrent"
elif isinstance(self.activeMeasList[0], RinSpectrum):
plotType="PeakRIN"
elif isinstance(self.activeMeasList[0], Spectrum):
plotType="LasingWavelength"
else:
plotType="ThresholdCurrent"
# Get the list of current measurements sorted by temperature
measList=self.sortByTemperature() if self.activeMeasList is None else self.sortByTemperature(self.activeMeasList)
# Generate plot dictionaries according to specified plotType for compatible measurement types
if plotType=="ThresholdCurrent":
tree=self.getMeasTree()
xAll=[]
yAll=[]
legendStrings=[]
# Extract the LIV data for each group and get plot data vs. temperature
for group in (tree if groupName is None else [groupName,]):
#if tree[group].has_key("LIV") and group in ['QD Laser Unit 5097','QD Laser Unit 5098','QD Laser Unit 5781','QD Laser Unit 5782']:
if tree[group].has_key("LIV"):
#livMeas=self.getEnabled(self.sortByTemperature(tree[group]["LIV"]))
livMeas=self.getEnabled(self.sortByTime(tree[group]["LIV"]))
x=array([mean(m.data["temperature"]) for m in livMeas])
y=array([m.getThresholdCurrent()[0] for m in livMeas])*1e3
xAll.append(x)
yAll.append(y)
legendStrings.append(group)
# legendStrings=["8 layers", "8 layers", "6 layers", "7 layers", "6 layers", "7 layers"]
xAxis={"data":tuple(xAll),"label":"Temperature [K]"}
yAxis={"data":tuple(yAll),"lineProp":tuple(["x-" for x in xAll]),"label":"Threshold Current [mA]", "legend":legendStrings}
plotDictionary={"x":xAxis,"y":yAxis,"title":"Threshold current vs temperature"}
elif plotType=="LasingWavelength":
# Lasing wavelength vs temperature plot
tree=self.getMeasTree()
xAll=[]
yAll=[]
legendStrings=[]
# Extract the lasing wavelength data for each group and get plot data vs. temperature
for group in (tree if groupName is None else [groupName,]):
if tree[group].has_key("WinspecGainSpectrum") and group in ['QD Laser Unit 5097','QD Laser Unit 5098','QD Laser Unit 5781','QD Laser Unit 5782']:
specMeas=self.getEnabled(self.sortByTemperature(tree[group]["WinspecGainSpectrum"]))
x=array([mean(m.data["temperature"]) for m in specMeas])
y=array([m.getLasingWavelength() for m in specMeas])*1e9
xAll.append(x)
yAll.append(y)
legendStrings.append(group)
# legendStrings=["8 layers", "8 layers", "6 layers", "7 layers", "6 layers", "7 layers"]
xAxis={"data":tuple(xAll),"label":"Temperature [K]"}
yAxis={"data":tuple(yAll),"lineProp":tuple(["x-" for x in xAll]),"label":"Lasing Wavelength [nm]", "legend":legendStrings}
plotDictionary={"x":xAxis,"y":yAxis,"title":"Lasing wavelength vs temperature"}
elif plotType=="PeakGainEnergy" or plotType=="PeakGainEnergyDelta":
# Difference in energy between the absorption peak at lowest current and gain peak at max current vs temperature
gainMeas=self.dataByClassHandle(WinspecGainSpectrum,measList)
outArgs=[m.getAllGainPeakEnergies() for m in gainMeas]
# Separate the currents and the gain peak positions
xraw=[xy[0] for xy in outArgs]
yraw=[xy[1] for xy in outArgs]
# If there is a NaN value in any of the peak energy values, then remove it and the corresponding current value
current=tuple([xraw[idx][logical_not(isnan(yraw[idx]))] for idx in range(len(xraw))])
peakEnergy=tuple([yi[logical_not(isnan(yi))] for yi in yraw])
temperature=array([mean(m.data["temperature"]) for m in gainMeas])
# Make the plotDictionary
if plotType=="PeakGainEnergyDelta":
x=temperature
y=array([(yi.max()-yi.min())*1e3 if len(yi) >1 else nan for yi in peakEnergy])
xAxis={"data":(x,),"label":"Temperature [K]"}
yAxis={"data":(y,),"lineProp":('x-',),"label":"Max gain peak energy difference [meV]"}
plotDictionary={"x":xAxis,"y":yAxis,"title":"Threshold gain energy shift vs temperature"}
else:
x=current
y=peakEnergy
legend=["{:0.1f}".format(T)+"K" for T in temperature]
lineProp=tuple(["x-" for idx in range(len(y))])
xAxis={"data":x,"label":"I/$I_{th}$"}
yAxis={"data":y,"lineProp":lineProp,"label":"Gain peak energy [meV]","legend":legend}
plotDictionary={"x":xAxis,"y":yAxis,"title":"Threshold gain energy shift vs current and temperature"}
elif plotType=="PeakRIN":
rinMeas=self.dataByClassHandle(RinSpectrum,measList)
feedback=[]
peakRin=[]
# Get list of all unique current set points in set of measurements
current=unique(hstack(array([linspace(m.info["Istart"],m.info["Istop"],m.info["numCurrPoints"]) for m in rinMeas])))
# Get all feedback levels
feedback=array([10*log10(m.data["feedbackAmount"]) if "feedbackAmount" in m.data else NaN for m in rinMeas])
# Sort measurement list by feedback level
sortIdx=feedback.argsort()
feedback=feedback[sortIdx]
rinMeas=[rinMeas[i] for i in sortIdx]
# Create array of peak RIN for each current and feedback level
for m in rinMeas:
# Calculate start index to trim all frequencies below RIN_MIN_FREQ
s=where(m.data["wavelength"] >= RIN_MIN_FREQ)[0][0]
# Get current set points for current meas
ism=linspace(m.info["Istart"],m.info["Istop"],m.info["numCurrPoints"])
# Calculate peak rin at each current in allCurr, setting a dummy value if the current value wasn't included in m
peakRinIdx=[]
for idx in range(len(current)):
try:
idx2=where(ism==current[idx])[0][0]
rin=m.powerDensityToRin(m.data["intensity"][s:,idx2],m.data["thermalNoisePower"][s:],m.data["photoCurrent"][idx2])
peakRinIdx.append(max(rin))
except IndexError:
peakRinIdx.append(NaN)
# Append to main arrays
peakRin.append(array(peakRinIdx))
# Convert to numpy arrays
feedback=array(feedback)-6-8
peakRin=array(peakRin)
# Make plot dictionary
x=tuple(tile(feedback,(len(current),1)))
y=tuple(transpose(peakRin))
legend=["{:0.0f}".format(i*1000)+"mA" for i in current]
lineProp=tuple(["x-" for idx in range(len(y))])
xAxis={"data":x,"label":"Feedback amount (dB)"}
yAxis={"data":y,"lineProp":lineProp,"label":"Peak RIN (dB/Hz)","legend":legend}
plotDictionary={"x":xAxis,"y":yAxis,"title":"Peak RIN vs feedback level at varying currents"}
else:
return
# Emit a signal with data dictionary for the GUI to know what to plot
self.plotProgress.emit(100)
self.plotDataReady.emit(plotDictionary)
def initializeDatabase_(self):
""" Initializes the database. Doesn't do anything atm but could specify a table structure in the future if necessary """
pass
def fetchAllMeasurements(self):
""" Fetch all the data from the database, and convert into list of measurements """
measObjects=[]
if type(self.db)==sqlite3.Connection:
# Allow loading of data from legacy sqlite database
measObjects=legacy.fetchAllMeasurements(self)
self.db=self.h5db
self.measurements=measObjects
self.saveToDB()
# Save the imported data as an h5 database and replace self.db with this new database
else:
# Traverse first 3 levels of file heirarchy assuming pytables group structure in format \groupName\testType\testName\
groupNameDic=self.db.root._v_children
for groupName in groupNameDic:
testTypeDic=groupNameDic[groupName]._v_children
for testType in testTypeDic:
testNameDic=testTypeDic[testType]._v_children
for testName in testNameDic:
# Put all the user attributes into the info dictionary
attrs=testNameDic[testName]._v_attrs
infoDic={}
for attrName in attrs._v_attrnamesuser:
infoDic[attrName]=attrs[attrName]
# Create an empty object of the specified test type if there is no "deleted" attribute set to true
if not infoDic.get("deleted",False):
if testType=="LIV":
meas=LIV(infoDic,dummy=False,parent=self.main)
elif testType=="Spectrum":
# This is a hack for backwards compatibility
meas=WinspecGainSpectrum(infoDic,dummy=False,parent=self.main)
meas.info["type"]="WinspecGainSpectrum"
elif testType=="AdvantestSpectrum":
# This is a hack for backwards compatibility
meas=AdvantestSpectrum(infoDic,dummy=False,parent=self.main)
elif testType=="WinspecSpectrum":
# This is a hack for backwards compatibility
meas=WinspecSpectrum(infoDic,dummy=False,parent=self.main)
elif testType=="WinspecGainSpectrum":
# This is a hack for backwards compatibility
meas=WinspecGainSpectrum(infoDic,dummy=False,parent=self.main)
elif testType=="ManualWinspecSpectrum":
# This is a hack for backwards compatibility
meas=WinspecGainSpectrum(infoDic,dummy=False,parent=self.main)
elif testType=="RinSpectrum":
meas=RinSpectrum(infoDic,dummy=False,parent=self.main)
else:
raise Exception, "An unknown test type was specified in the HDF5 database"
# Assume there's a folder called "data" and set each child data node as an attribute of the measurement object
#dataNodeDic=testNameDic[testName].data._v_children
for dataNodeName in groupNameDic[groupName]._v_children[testType]._v_children[testName].data._v_children:
#meas.data[dataNodeName]=dataNodeDic[dataNodeName][:]
dataNodeObj=groupNameDic[groupName]._v_children[testType]._v_children[testName].data._v_children[dataNodeName].read()
meas.data[dataNodeName]=dataNodeObj
# The below approach doesn't work well when the number of measurement points is set to 1
#if dataNodeObj.size>1:
# meas.data[dataNodeName]=dataNodeObj
#else:
# meas.data[dataNodeName]=float(dataNodeObj)
# Append the newly created measurement object to the main list
measObjects.append(meas)
return measObjects
def getMeasTree(self,measObject=None):
""" Convert self.measurements list into a dictionary representing the object hierarchy """
measDic={}
# Create some empty dictionaries to hold the parents for items at each level on the tree
parentFromGroup = {}
parentFromGroupType = {}
parentFromGroupTypeName = {}
# Get the list of all the measurement objects in the current session
allMeasurements=self.measurements if measObject is None else [measObject]
# From the top to the bottom of the tree, create QTreeWidgetItems and fill the dictionary with parent info
for meas in allMeasurements:
# Get the top level characteristics from the object
groupName=meas.info["groupName"]
typeName=meas.info["type"]
testID=meas.getID()
if groupName not in measDic:
measDic[groupName]={}
if typeName not in measDic[groupName]:
measDic[groupName][typeName]={}
measDic[groupName][typeName][testID]=meas
return measDic
def saveToDB(self,measObject=None):
""" Saves the current list of measurements to the database """
measDic=self.getMeasTree(measObject)
for groupName in measDic:
for typeName in measDic[groupName]:
for testId in measDic[groupName][typeName]:
# create a new group called groupName if it doesn't already exist
if groupName not in self.db.root._v_children:
groupNode=self.db.createGroup(self.db.root,groupName)
else:
groupNode=self.db.getNode(self.db.root,groupName)
# create a new group called typeName if it doesn't already exist
if typeName not in groupNode._v_children:
typeNode=self.db.createGroup(groupNode,typeName)
else:
typeNode=self.db.getNode(groupNode,typeName)
# create a new group for the testID if it doesn't already exist
if testId not in typeNode._v_children:
measNode=self.db.createGroup(typeNode,testId)
# Create a new group for the data
dataNode=self.db.createGroup(measNode,"data")
# Add all of the members of the data dictionary as arrays in dataNode
data=measDic[groupName][typeName][testId].data
for dataName in data:
if data!=None:
try:
self.db.createArray(dataNode,dataName,data[dataName])
except:
pass
else:
measNode=self.db.getNode(typeNode,testId)
# Set all of the members of the info dictionary as attributes of measNode (overwriting any existing attributes)
info=measDic[groupName][typeName][testId].info
for attrName in info:
self.db.setNodeAttr(measNode,attrName,info[attrName])
# force changes to be commited
self.db.flush()
def saveAs(self,groupName):
# This needs to export the threshold current vs temperature for LIV data with groupName as well as raw data for .mat and .pickle
pass
def convertToStr(self,input):
""" converts the json.loads objects from unicode names to str """
if isinstance(input, dict):
#return {self.convertToStr(key): self.convertToStr(value) for key, value in input.iteritems()}
return {self.convertToStr(key): value for key, value in input.iteritems()}
elif isinstance(input, list):
return [self.convertToStr(element) for element in input]
elif isinstance(input, unicode):
return input.encode('utf-8')
else:
return input
def toFloatOrNull(self,QVariantNumber):
""" Convenience function returns a float if QVariant valid, otherwise None """
temp=QVariantNumber.toFloat()
x=temp[0] if temp[1] else None
return x
def unserializeArray(self,numpyVector,sizeTuple):
""" Reverses the function of Spectrum.serializeArray() for getting the data back from the database into a matrix """
return reshape(numpyVector,(sizeTuple[1],sizeTuple[0])).transpose()
def getGroupNames(self):
""" Convenience function which returns array of all the measurement groupNames in the session """
groupNames=[]
for m in self.measurements:
groupNames.append(m.info["groupName"])
return list(set(groupNames))
def append(self,m):
self.measurements.append(m)
def dataByMeasType(self,measType,measList=None):
""" Return all active measurements matching measType """
if measList is None: measList=self.measurements
outList=[]
for m in measList:
if m.info["type"]==measType and m.info["enabled"]:
outList.append(m)
return outList
def dataByClassHandle(self,classHandle,measList=None):
""" Return all active measurements inheriting from classHandle """
if measList is None: measList=self.measurements
outList=[]
for m in measList:
if isinstance(m,classHandle) and m.info["enabled"]:
outList.append(m)
return outList
def sortByTemperature(self,measList=None):
""" Return all the measurements in optional measList sorted by temperature"""
if measList is None: measList=self.measurements
try:
# measList is dictionary / tree structure
measList=[measList[m] for m in measList]
except TypeError:
pass
temp=array([mean(m.data["temperature"]) for m in measList])
sortIdx=temp.argsort()
return [measList[idx] for idx in sortIdx]
def sortByTime(self, measList=None):
""" Return all the measurements in optional measList sorted by creation time"""
if measList is None: measList=self.measurements
try:
# measList is dictionary / tree structure
measList=[measList[m] for m in measList]
except TypeError:
pass
t=array([mktime(strptime(m.info["creationTime"], "%Y-%m-%d %H:%M:%S")) for m in measList])
sortIdx=t.argsort()
return [measList[idx] for idx in sortIdx]
def getEnabled(self,measList):
""" Return only the enabled tests from measList """
try:
# measList is dictionary / tree structure
measList=[measList[m] for m in measList]
except TypeError:
pass
outList=[]
for m in measList:
if m.info["enabled"]:
outList.append(m)
return outList
def dataByTimestamp(self,measType=None):
""" Return array of all the measurements sorted by timestamp, optionally limited to a certain measurement type,
with the type specified by the string in the info dictionary "type" field """
timeStamps=[strptime(m.info["creationTime"],"%Y-%m-%d %H:%M:%S") for m in self.measurements]
measSorted=[self.measurements[i[0]] for i in sorted(enumerate(timeStamps), key=lambda x:x[1])]
if measType!=None:
isType=array([m.info["type"]==measType for m in measSorted])
return array(measSorted)[isType]
return array(measSorted)
class DatabaseWriteException(Exception): pass
class Measurement(QtCore.QObject):
"""Super class for all laser measurement types"""
# pyqt signals (mainly for multithreading purposes)
finished=QtCore.pyqtSignal()
finishedPlottingSignal=QtCore.pyqtSignal()
plotDataReady=QtCore.pyqtSignal(dict)
progress=QtCore.pyqtSignal(float)
progressMessage=QtCore.pyqtSignal(str)
plotProgress=QtCore.pyqtSignal(float)
aborted=QtCore.pyqtSignal()
measError=QtCore.pyqtSignal(str)
# hold main data in numpy.ndarray
def __init__(self,info,dummy,parent=None,lock=None):
super(Measurement, self).__init__()
self.main=parent
self.DUMMY_MODE=dummy
self.info=info
self.data={}
if "creationTime" not in self.info:
self.info["creationTime"]=str(datetime.now().replace(microsecond=0))
if "enabled" not in self.info:
self.info["enabled"]=True
self.fitParameters=None
self.running=True
self.rendering=False
self.cryostatOff=False
self.lock=lock
# Do rough align if specified
self.preAlignFlag=self.info.get("preAlign",True)
self.roughAlignFlag=self.info.get("roughAlign",False)
self.fineAlignFlag=self.info.get("fineAlign",False)
# Set filter wheel position to 1
try:
attentuator=FilterWheel()
attenuator.setPosition(1)
del attenuator
except:
pass
@QtCore.pyqtSlot()
def canceled(self):
""" Slot which cancels the measurement """
self.running=False
@QtCore.pyqtSlot()
def readyToDraw(self):
""" Slot which allows the figure canvas to say when it's ready to draw again """
self.rendering=False
@QtCore.pyqtSlot(float)
def subProgressAvailable(self,subprogress):
""" Slot which accepts subprogress from subroutines """
self.sendProgress(self.mainProgress+self.mainProgressStep*subprogress)
@QtCore.pyqtSlot(float)
def plotSubProgressAvailable(self,subprogress):
""" Slot which accepts subprogress from subroutines """
self.sendPlotProgress(self.mainPlotProgress+self.mainPlotProgressStep*subprogress)
def finishedWork(self):
""" Ensure the thread has been moved back to its parent and emit the finished signal """
self.moveToThread(self.main.thread())
self.finished.emit()
def finishedPlotting(self):
""" Ensure the thread has been moved back to its parent and emit the finished signal """
self.moveToThread(self.main.thread())
self.finishedPlottingSignal.emit()
def getID(self):
""" Returns a human intelligible unique ID for usage in the database"""
return self.info["Name"]+" "+self.info["creationTime"]
def roughAlign(self, preAlign = True):
smu = self._setAlignmentCurrent()
pm = RoughAlignPowerMeter()
motorAlignObject=MotorAlign()
if preAlign:
# If the rough align power meter is below the search threshold then use a pre-align to get the interesting search range
if pm.readPowerAuto(mode='max') < ALIGNMENT_SIGNAL_SEARCH_THRESH:
xm, xM, ym, yM = self._preAlign(motorAlignObject)
span = max((xM - xm)/2, (yM - ym)/2)
else:
span = None
self.sendStatusMessage("\nMain align (rough):\n")
self._roughAlign(motorAlignObject, pm, ALIGNMENT_SIGNAL_SEARCH_RES, ALIGNMENT_ROUGH_RES, ALIGNMENT_SIGNAL_SEARCH_THRESH, ALIGNMENT_SOFT_SEARCH_THRESH, span = span)
def _setAlignmentCurrent(self):
smu = SMU()
smu.setCurrent(ALIGNMENT_CURRENT)
smu.setOutputState("ON")
return smu
def _preAlign(self, motorAlignObject):
""" If there is a power meter in front of the fiber / spatial filter and we don't have first light yet,
a pre-align should be done to figure out the range that we should search over """
def scan(chan, sign):
# Move in steps of 50um away from pre-align peak to find valid scan range
pos = p[chan]
motorAlignObject.moveTo(p)
while pm.readPowerAuto() > preAlignPower*0.75:
pos += sign*PRE_ALIGNMENT_SEARCH_RES
motorAlignObject.move1d(chan, pos)
return pos
self.sendStatusMessage("Prealign:\n")
pm = PrealignPowerMeter()
p, preAlignPower = self._roughAlign(motorAlignObject, pm, PRE_ALIGNMENT_SEARCH_RES, PRE_ALIGNMENT_ROUGH_RES, ALIGNMENT_SIGNAL_SEARCH_THRESH, PREALIGNMENT_SOFT_SEARCH_THRESH)
self.sendStatusMessage("Pre align power meter measured %f uW"%(preAlignPower*1e6))
limits = (scan(0, -1), scan(0, 1), scan(1, -1), scan(1, 1))
self.sendStatusMessage("Pre align determined scan range: x: (%f, %f) y: (%f, %f)"%limits)
return limits
def _roughAlign(self, motorAlignObject, pm, searchRes, res, threshold, softThreshold = None, span = None):
""" Run findFirstSignal() and then do a rough align """
self.sendStatusMessage("Initializing motor controller...")
# Search for the first sign of signal over wide coarse grid using motor controller
self.sendStatusMessage("Searching for the signal...")
p0=self.main.motorCoordinates
profitFunc=lambda : pm.readPowerAuto(tau=1,mode="max")
p,power=motorAlignObject.findFirstSignal(p0,res=searchRes,profitFunction=profitFunc,threshold=threshold, span = span, softThreshold = softThreshold)
with QReadLocker(self.lock):
self.main.motorCoordinates=p
# Rough align to get the rough optimum position over wide but coarse grid
self.sendStatusMessage("Signal found at "+"(%.3f,%.3f)"%p+"mm.\nNow performing rough alignment...")
tau=ALIGNMENT_TAU if self.cryostatOff else ALIGNMENT_TAU_LOWTEMP
p0=p
profitFunc=lambda : pm.readPowerAuto(tau=tau)
p,power=motorAlignObject.autoalign(p0,res=res,profitFunction=profitFunc)
with QReadLocker(self.lock):
self.main.motorCoordinates=p
settings=QtCore.QSettings()
settings.setValue("MotorCoordinates",p)
self.sendStatusMessage("Rough alignment completed with peak at "+"(%.3f,%.3f)"%p+"mm.")
return p, power
def fineAlign(self, piezoAlignObject = None, smu = None):
""" Perform a fine alignment using the piezoelectric actuators, and only the power as the optimization conditions"""
self.sendStatusMessage("Doing fine align with power meter and piezo actuators...")
alignmentCurrent=self.info.get("fineAlignCurrent",ALIGNMENT_CURRENT)
if smu is None: smu = SMU()
if piezoAlignObject is None:
if self.piezoAlignObject is None:
piezoAlignObject=PiezoAlign()
else:
piezoAlignObject = self.piezoAlignObject
pm=FineAlignPowerMeter()
smu.setCurrent(alignmentCurrent)
p0=self.main.piezoCoordinates
tau=ALIGNMENT_TAU if self.cryostatOff else ALIGNMENT_TAU_LOWTEMP
profitFunc=lambda : pm.readPowerAuto(tau=tau)
p,power=piezoAlignObject.autoalign(p0,ALIGNMENT_FINE_RES,ALIGNMENT_FINE_SPAN,profitFunction=profitFunc)
with QReadLocker(self.lock):
self.main.piezoCoordinates=p
self.sendStatusMessage("Fine alignment completed with peak at "+"(%.3f,%.3f)"%p+"um.")
#del PiezoAlignObject, smu, profitFunc
def initTempController(self):
""" Initializes the temperature controller. """
# NEED TO ACCESS THE TEMPERATURE THROUGH THE SAME INTERFACE AS THE TEMPERATURE WIDGET!!!
if not self.main.tempController is None:
self.tempController=self.main.tempController
else:
try:
self.tempController=TemperatureController()
except IOError, e:
reply=QtGui.QMessageBox.question(None,"Do you want to proceed?","There was an IO communication error with the temperature controller. Do you want to proceed without measuring the temperature for the rest of this session?",QtGui.QMessageBox.Yes|QtGui.QMessageBox.No)
if reply==QtGui.QMessageBox.Yes:
self.tempController=None
global NO_TEMP_SENSOR
NO_TEMP_SENSOR=True
elif reply==QtGui.QMessageBox.No:
QtGui.QMessageBox.warning(None,"VisaIOError",("Please check that the temperature controller is turned on and connected properly:\n %1").arg(e.args[0]))
raise MeasurementAbortedError
def serializeArray(self,numpyArray):
""" Serializes numpy array into vector for database """
return reshape(numpyArray.transpose(),-1)
def tileVector(self,numpyVector,m):
""" Tiles a numpy vector into repeated vector for database """
#return tile(numpyVector,(m,1)).transpose()
return reshape(tile(numpyVector,(m,1)).transpose(),-1)
def gridVector(self,numpyVector,m):
""" Tiles a numpy vector into a repeated grid for plotting """
return tile(numpyVector,(m,1))
def dataSummary(self):
""" Returns a list of tuples which summarizes the test data via strings in a logically structured way. Format example is as follows:
[([data1_col1,data1_col2],),([data2_col1,data2_col2],optionsDictionary: {"isCheckable":True,"clickMethod":meas.plot}),([data1_col1,data1_col2],childDataList: [(dataLabel4,data4),(dataLabel5,data5)])] """
toStr=self.numToString # method in parent class which converts float,int,list,numpy.ndarray,str to string
dataSummaryList=[]
dataSummaryList.append((["Enabled"],{"isCheckable":True,"isChecked":self.info["enabled"]}))
# Set information as child so that it doesn't clog up the display
infoList=[]
infoList.append((["time stamp",toStr(self.info["creationTime"])]))
infoList.append((["num curr points",toStr(self.info["numCurrPoints"])]))
infoList.append((["compliance (V)",toStr(self.info["Vcomp"])]))
dataSummaryList.append((["Info"],infoList))
try:
dataSummaryList.append((["Temperature [K]",toStr(self.data["temperature"])]))
dataSummaryList.append((["current (mA)",toStr(self.data["iMeas"]*1000)]))
dataSummaryList.append((["voltage (V)",toStr(self.data["vMeas"])]))
except KeyError as e:
pass
return dataSummaryList
def numToString(self,data,numDigits=2,maxElements=2):
""" Take variable data type and format it as a string appropriate for displaying in a QTreeWidget in main"""
if type(data)==str or type(data)==unicode:
return data
if type(data)==string_:
return str(data)
if data is None:
return "N/A"
elif type(data)==int:
return str(data)
elif type(data)==float or type(data)==float64:
return ("{:0."+str(numDigits)+"f}").format(data)
# If list of n numbers then format as "[data_1, data_2, ..., data_n]" with number shown depending on maxElements
elif type(data)==list or type(data)==ndarray:
outString=['[']
for i in range(len(data)):
if i<maxElements:
outString.append(self.numToString(data[i],numDigits))
outString.append(', ')
else:
break
if len(data)>(maxElements+1):
# Replace remaining elements with ellipsis except for final element
outString.append("... , ")
outString.append(self.numToString(data[-1],numDigits))
outString.append(']')
else:
# Change last comma + space to right square bracket
del outString[-1]
outString.append("]")
return "".join(outString)
def sendProgress(self,progress):
""" Emit a signal indicating the progress, as percentage"""
self.progress.emit(progress*100)
#self.emit(QtCore.SIGNAL("progress"),progress*100)
def sendStatusMessage(self,msg):
""" Send a status message to the user """
print(msg)
self.progressMessage.emit(msg)
QtCore.QCoreApplication.processEvents()
# In addition to printing, ideally also want to send something to the GUI
def sendPlotProgress(self,progress):
""" Emit a signal indicating the progress for plotting, as percentage"""
self.plotProgress.emit(progress*100)
def sendPlotData(self,plotDictionary):
""" Emit a signal with a plot dictionary """
self.plotDataReady.emit(plotDictionary)
#self.emit(QtCore.SIGNAL("plotDataReady"),plotDictionary)
def sendVarToTerminal(self,varName,var):
""" Debug helper function which sends a variable to the console workspace """
self.main.showConsoleDialog()
try:
self.main.debugVars[varName]=var.copy()
except:
self.main.debugVars[varName]=var
self.main.consoleDialog.updateNamespace(varName,self.main.debugVars[varName])
class LIV(Measurement):
""" Subclass of main measurement type to hold data for LIV measurement """
def __init__(self, info, dummy=False, parent = None, lock=None):
info["type"]="LIV"
super(LIV, self).__init__(info, dummy,parent=parent, lock=lock)
def plot(self,maxIndex=None,offset=False,logscale=False):
""" Prepares the LIV data for plotting, and emits a signal when finished for the mainwindow to draw the plot """
# trim the data if a maxIndex is specified, otherwise plot the full data using mA and uW as default
self.sendPlotProgress(0)
x=self.data["iMeas"]*1e3
y1=self.data["lMeas"]*1e6
y2=self.data["vMeas"]
if maxIndex!=None:
x=x[0:maxIndex+1]
y1=y1[0:maxIndex+1]
y2=y2[0:maxIndex+1]
(xth,yth)=(None,None)
else:
try:
(xth,yth)=self.getThresholdCurrent()
xth=xth*1e3
yth=yth*1e6
except Exception:
xth=0
yth=0
# Add the plot data to the dictionary
xAxis={"data":(x,xth),"label":"I [mA]"}
if maxIndex!=None:
xAxis["limit"]=(self.iSet[0]*1000,self.iSet[-1]*1000)
yAxis={"data":(y1,yth),"lineProp":("k","ko"),"label":"L [uW]"}
x2Axis={"data":(x,)} # to allow for multiple lines on second axis as well
y2Axis={"data":(y2,),"lineProp":("r-"),"label":"V [V]","color":"r"}
plotDictionary={"x":xAxis,"y":yAxis,"x2":x2Axis,"y2":y2Axis,"title":"Light output and voltage vs current"}
# Emit a signal with data dictionary for the GUI to know what to plot
#self.emit(QtCore.SIGNAL("plotDataReady"),plotDictionary)
self.sendPlotData(plotDictionary)
self.finishedPlotting()
self.sendPlotProgress(1)
def acquireData(self):
""" Cycles through each current point and does Source/Measure of IV, then power measurement. I'd like to refactor some of this code into the Measurement class
to avoid duplication with acquireData() method in the Spectrum class"""
if not self.DUMMY_MODE:
if self.roughAlignFlag:
self.sendStatusMessage("Initializing piezo controller to center for rough align...")
piezoAlignObject=PiezoAlign()
self.roughAlign(self.preAlignFlag)
self.initTempController()
n=self.info["numCurrPoints"]
#self.iSet=around(linspace(self.info["Istart"],self.info["Istop"],n),5)
self.iSet=linspace(self.info["Istart"],self.info["Istop"],n)
pm=PrimaryPowerMeter()
smu=SMU(autoZero=False,disableScreen=True,defaultCurrent=ALIGNMENT_CURRENT)
self.data["lMeas"]=zeros(n)
self.data["iMeas"]=zeros(n)
self.data["vMeas"]=zeros(n)
with QReadLocker(self.lock):
self.data["temperature"]=self.tempController.getTemperature() if not NO_TEMP_SENSOR else None
self.cryostatOff=True if self.data["temperature"] > LOWTEMP_THRESHOLD else False
self.sendStatusMessage("Acquiring LIV data...")
for i in range(n):
# Cancel the measurement if it has been aborted
QtCore.QCoreApplication.processEvents()
if not self.running:
self.aborted.emit()
#self.emit(QtCore.SIGNAL("aborted"))
return
# Emit progress
self.sendProgress(i/n)
# Set current, then measure V/I/L
smu.setCurrent(self.iSet[i],self.info["Vcomp"])
self.data["vMeas"][i],self.data["iMeas"][i]=smu.measure()
sleep(20e-3) # 20ms wait to account for 1kHz analog filter on power meter + digital filter(10 samples)
try:
tau=LIV_TAU if self.cryostatOff else LIV_TAU_LOWTEMP
powerMeas=pm.readPowerAuto(tau=tau)
except Exception as e:
QtGui.QMessageBox.warning(None,"CommError",("There was a persistent problem with the power meter:\n %1").arg(e.args[0]))
self.aborted.emit()
return
self.data["lMeas"][i]=powerMeas
# Update the plot if not already rendering
QtCore.QCoreApplication.processEvents()
if not self.rendering:
self.rendering=True
self.plot(i)
else:
nCurr=self.info["numCurrPoints"]
self.acquireDummyData()
for i in range(nCurr):
# Cancel the measurement if it has been aborted
if not self.running:
self.aborted.emit()
return
self.sendProgress(i/nCurr)
sleep(20e-3)
# Update the plot if not already rendering
QtCore.QCoreApplication.processEvents()
if not self.rendering:
self.rendering=True
self.plot(i)
# Emit 100% progress and finished message
if max(self.data["lMeas"]) > LIV_MIN_MAX_POWER:
self.sendProgress(1)
self.finishedWork()
else:
try:
del piezoAlignObject
except NameError:
pass
raise SignalTooWeakError
def doWork(self):
""" Test function for QThread """
n=200000
for i in range(n):
self.emit(QtCore.SIGNAL("progress"),i/n*100)
self.emit(QtCore.SIGNAL("progress"),100)
self.finishedWork()
def correctOffset(self,limit=16e-6):
""" Subtract the noise floor at zero if within limit """
if min(self.data["lMeas"])<limit and min(self.data["lMeas"])>0:
self.data["lMeas"]=self.data["lMeas"]-min(self.data["lMeas"])
def bilinearFunction(self,x,b,m1,m2,xt):
""" bilinear function for calculating threshold current (deprecated) """
return b+m1*x+[max(m2*(xi-xt),0) for xi in x]
def fitCurrent(self,maxLight=200e-6):
""" Calculates the fit parameters from the LIV data up to maxLight (noise floor of Newport detector is 20uW, so 200uW is reasonable.
Fit a maximum 5 segment cubic spline and take the peak of the second derivative as the threshold current (deprecated)"""
x=self.data["iMeas"][self.data["lMeas"]<=maxLight]*1e3
y=self.data["lMeas"][self.data["lMeas"]<=maxLight]*1e6
#p=optimize.curve_fit(self.bilinearFunction,x,y,(16,.1,40,10))[0] # do nonlinear fit and extract bilinear parameters
# Set uniform knots for spline fit
t=linspace(min(x),max(x),min(floor(len(x)/5)+1,6))
p=interpolate.LSQUnivariateSpline(x,y,t[1:-1])
self.fitFunction=p
def getFittedLI(self):
""" returns the fitted L data in W (deprecated)"""
#return self.bilinearFunction(self.data["iMeas"]*1e3,*self.getFitParameters())*1e-6
return self.fitFunction(self.data["iMeas"])
def getFitParameters(self,recalculate=True):
""" returns the fit parameters, calculating if necessary """
if recalculate or self.fitParameters is None:
self.fitCurrent()
return self.fitParameters
def getThresholdCurrent(self,maxLight=.05,INTERPOLATE=True):
""" Smooth data and take the peak of the second derivative as the threshold current.
First trim the data to the range below where lMeas first goes abive maxLight. The noise floor of Newport detector is 20uW, so 200uW is reasonable starting point."""
x=self.data["iMeas"]
y=self.data["lMeas"]
# Calculate the second derivative from a Savitky-Golay filter
window=round(len(x)/8)
window=window-1 if window%2 else window # window must be odd number
yprime2=savitzky_golay(y,31,4,2) # second derivative from smoothed data
if size(yprime2)>size(y):
# This seems to happen when the length of y is too small!
raise Exception
if INTERPOLATE:
p=interpolate.interp1d(x,y,'cubic')
ppp=interpolate.interp1d(x,yprime2,'cubic')
# Get the interpolated second derivative vs x
xx=linspace(min(x),max(x),1e5)
yy=p(xx)
# Trim to the bottom of the tail
xxx, yyy = xx, yy
if not maxLight is None:
maxIndex=where(yy>=(maxLight*(y.max()-y.min())+y.min()))[0]
if len(maxIndex > 0):
xxx,yyy = xx[0:maxIndex[0]-1],yy[0:maxIndex[0]-1]
# Get the final threshold current value
yyyprime2=ppp(xxx)
xyTuple=(xxx[yyyprime2==max(yyyprime2)][0],yyy[yyyprime2==max(yyyprime2)][0])
else:
# take the first value where the second derivative is maximum (may be a nicer way to force uniqueness)
xxx, yyy, yyyprime2 = x, y, yprime2
if not maxLight is None:
maxIndex=where(y>=(maxLight*(y.max()-y.min())+y.min()))[0]
xxx=xxx[0:maxIndex[0]-1]
yyy=yyy[0:maxIndex[0]-1]
yyyprime2=yprime2[0:maxIndex[0]-1]
xyTuple=(xxx[yyyprime2==max(yyyprime2)][0],yyy[yyyprime2==max(yyyprime2)][0])
# Plot the second derivative for debugging purposes
"""
self.main.canvas.plot(xxx,yyyprime2)
QtCore.QCoreApplication.processEvents()
sleep(1)
debug_trace() # set a break point
"""
# Recurse with larger limit if we didn't capture the maxima of 2nd derivative
if not maxLight is None and maxLight <= 0.5 and yyyprime2[-1] >= 0.9*yyyprime2.max():
return self.getThresholdCurrent(2*maxLight, INTERPOLATE)
return xyTuple
def acquireDummyData(self):
""" sets some dummy LIV data for remote development with no GPIB """
self.iSet=linspace(self.info["Istart"],self.info["Istop"],self.info["numCurrPoints"])
self.data["vMeas"]=log(self.iSet/1e-9/random.random())*25e-3
self.data["vMeas"]=self.data["vMeas"]*(self.data["vMeas"]<=self.info["Vcomp"])+self.info["Vcomp"]*(self.data["vMeas"]>self.info["Vcomp"])
self.data["iMeas"]=1e-9*exp(self.data["vMeas"]/25e-3)
It=10e-3
self.data["lMeas"]=self.data["iMeas"]*(self.data["iMeas"]>It)-It*(self.data["iMeas"]>It)
self.data["temperature"]=300+random.rand()
def saveAs(self,fname,index=None):
""" Exports the raw data to specified file, with format inferred from extension"""