Esempio n. 1
0
class LaserScan(Spyrelet):
    requires = {
        #'wm': Bristol_771,
        'pmd': PM100D
    }
    conn1 = NetworkConnection('1.1.1.2')

    dlc = Client(conn1)

    
    @Task()
    def scan(self):
        param=self.parameters.widget.get()     
        filename = param['Filename']
        F =open(filename+'.dat','w')
        f=filename+'\'.dat'
        F2 = open(f,'w')
        start_wavelength = param['Start'].magnitude*1e9
        stop_wavelength = param['Stop'].magnitude*1e9
        step = param['Step'].magnitude*1e9
        n = param['Num Scan']
        self.wv = np.arange(start_wavelength,stop_wavelength+step,step)

        with Client(self.conn1) as dlc:
            for x in range(n):
                xx=[]            
                dlc.set("laser1:ctl:wavelength-set",start_wavelength)
                time.sleep(10)
                act_start = self.wm.measure_wavelength()
                time.sleep(2)
                for item in self.wv:
                    dlc.set("laser1:ctl:wavelength-set",item)
                    time.sleep(0.0001)
                    xx.append(self.pmd.power.magnitude * 1000)
                act_stop = self.wm.measure_wavelength()
                print('%f,%f'%(act_start,act_stop))
                wl = np.linspace(act_wavelength,act_wavelength,len(xx))
                for item in xx:
                    F.write("%f,"%item)
                for item in wl:
                    F2.write("%f,"%item)
                F.write("\n")
                F2.write("\n")

        return

    @Element(name='Params')
    def parameters(self):
        params = [
    #    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
        ('Start', {'type': float, 'default': 1460*1e-9, 'units':'m'}),
        ('Step', {'type': float, 'default': 0.01*1e-9, 'units':'m'}),
        ('Stop', {'type': float, 'default': 1570*1e-9, 'units':'m'}),
        ('Num Scan', {'type': int, 'default': 1}),
        ('Filename', {'type': str, 'default':'D:\\Data\\09.06.2019\\wavelengthsweep'})

        # ('Amplitude', {'type': float, 'default': 1, 'units':'V'})
        ]
        w = ParamWidget(params)
        return w
Esempio n. 2
0
 def _connection(self):
     if self.connection == 'serial':
         return SerialConnection(self.COM_port, loop=self.loop)
     elif self.connection == 'network':
         return NetworkConnection(self.COM_port, loop=self.loop)
     else:
         logging.warning(
             'DLCProCs warning in _connection() : specify serial or network connection'
         )
Esempio n. 3
0
 def set(self, cmd, value):
     with Client(NetworkConnection(self.COM_port, timeout=5)) as client:
         client.set(cmd, value)
         set = client.get(cmd, type(value))
         if set != value:
             func_name = sys._getframe(1).f_code.co_name
             logging.warning("DLCProCs warning in {0}() : ".format(func_name) \
                             + str(err))
     return
Esempio n. 4
0
class MonochromatorSpyrelet(Spyrelet):

    requires = {
        'wm': Bristol_771,
		'fungen': Keysight_33622A,
		'SRS': SRS900,
        'sp': SpectraPro,
    }
    qutag = None
	laser = NetworkConnection('1.1.1.2')
Esempio n. 5
0
class Lifetime(Spyrelet):
	requires = {
		'wm': Bristol_771
	}
	qutag = None
	conn1 = NetworkConnection('1.1.1.2')
	#conn1 = conn1 = SerialConnection('COM1') 
	dlc = Client(conn1)

	def configureQutag(self):
		qutagparams = self.qutag_params.widget.get()
		start = qutagparams['Start Channel']
		stop = qutagparams['Stop Channel']
		##True = rising edge, False = falling edge. Final value is threshold voltage
		self.qutag.setSignalConditioning(start,self.qutag.SIGNALCOND_MISC,True,1)
		self.qutag.setSignalConditioning(stop,self.qutag.SIGNALCOND_MISC,True,0.1)
		self.qutag.enableChannels((start,stop))

	def createHistogram(self,stoparray, timebase, bincount, period, index, wls):
		hist = [0]*bincount
		for stoptime in stoparray:
			binNumber = int(stoptime*timebase*bincount/(period))
			if binNumber >= bincount:
				continue
			else:
				hist[binNumber]+=1
		out_name = "D:\\Data\\10.9.2019\\film"
		np.savez(os.path.join(out_name,str(index)),hist,wls)
		#np.savez(os.path.join(out_name,str(index+40)),hist,wls)
		print('Data stored under File Name: ' + self.exp_parameters.widget.get()['File Name'] + str(index))


	@Task()
	def startpulse(self, timestep=1e-9):
		with Client(self.conn1) as dlc:
			print(dlc.get("laser1:ctl:wavelength"))

		time.sleep(1000)

		self.configureQutag()

		qutagparams = self.qutag_params.widget.get()
		lost = self.qutag.getLastTimestamps(True) # clear Timestamp buffer
		stoptimestamp = 0
		synctimestamp = 0
		bincount = qutagparams['Bin Count']
		timebase = self.qutag.getTimebase()
		start = qutagparams['Start Channel']
		stop = qutagparams['Stop Channel']

		expparams = self.exp_parameters.widget.get()
		for i in range(expparams['# of points']):
			##Wavemeter measurements
			stoparray = []
			startTime = time.time()
			wls=[]
			lost = self.qutag.getLastTimestamps(True)
			while time.time()-startTime < expparams['Measurement Time'].magnitude:
				lost = self.qutag.getLastTimestamps(True)
				time.sleep(30*100e-3)
				timestamps = self.qutag.getLastTimestamps(True)

				tstamp = timestamps[0] # array of timestamps
				tchannel = timestamps[1] # array of channels
				values = timestamps[2] # number of recorded timestamps
				for k in range(values):
					# output all stop events together with the latest start event
					if tchannel[k] == start:
						synctimestamp = tstamp[k]
					else:
						stoptimestamp = tstamp[k]
						stoparray.append(stoptimestamp)
				wls.append(str(self.wm.measure_wavelength()))
			self.createHistogram(stoparray, timebase, bincount, 100e-3,i, wls)
			print(i)
			#self.fungen.voltage[2] = self.fungen.voltage[2].magnitude + 2*dcparams['DC step size'].magnitude
			#time.sleep(100000)


	@Task()
	def qutagInit(self):
		print('qutag successfully initialized')
		

	@Element(name='Pulse parameters')
	def pulse_parameters(self):
		params = [
	#    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
		('pulse height', {'type': float, 'default': 3, 'units':'V'}),
		('pulse width', {'type': float, 'default': 500e-9, 'units':'s'}),
		('period', {'type': float, 'default': 0.1, 'units':'s'}),
		]
		w = ParamWidget(params)
		return w

	@Element(name='DC parameters')
	def DC_parameters(self):
		params = [
	#    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
		('DC height', {'type': float, 'default': 0, 'units':'V'}),
		('DC step size', {'type': float, 'default': 0.1, 'units':'V'}),
		]
		w = ParamWidget(params)
		return w

	@Element(name='Experiment Parameters')
	def exp_parameters(self):
		params = [
	#    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
		('# of points', {'type': int, 'default': 10}),
		('Measurement Time', {'type': int, 'default': 10, 'units':'s'}),
		('File Name', {'type': str})
		]
		w = ParamWidget(params)
		return w

	@Element(name='QuTAG Parameters')
	def qutag_params(self):
		params = [
	#    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
		('Start Channel', {'type': int, 'default': 0}),
		('Stop Channel', {'type': int, 'default': 1}),
		('Bin Count', {'type': int, 'default': 1000})
		]
		w = ParamWidget(params)
		return w

	@startpulse.initializer
	def initialize(self):
		self.wm.start_data()

	@startpulse.finalizer
	def finalize(self):
		self.wm.stop_data()
		print('Lifetime measurements complete.')
		return

	@qutagInit.initializer
	def initialize(self):
		from lantz.drivers.qutools import QuTAG
		self.qutag = QuTAG()
		devType = self.qutag.getDeviceType()
		if (devType == self.qutag.DEVTYPE_QUTAG):
			print("found quTAG!")
		else:
			print("no suitable device found - demo mode activated")
		print("Device timebase:" + str(self.qutag.getTimebase()))
		return

	@qutagInit.finalizer
	def finalize(self):
		return
Esempio n. 6
0
class FastHeterodyne(Spyrelet):
    requires = {'fungen': Keysight_33622A, 'osc': TDS5104}
    maxy = 0
    laser = NetworkConnection('1.1.1.2')

    def setwv(self, wv):
        with Client(self.laser) as client:
            client.set('laser1:ctl:wavelength-set', wv)

    def saveData(self, x, y, index, ind):
        out_name = "D:\\Data\\1.16.2020\\test4"
        index = str(round(index, 8))
        ind = '.' + str(ind)
        np.savez(os.path.join(out_name, str(index + ind)), x, y)
        print('Data stored under File Name: ' + str(index) + '.' + str(ind))

    def stepDown(self, channel, scale):
        scales = [1.0, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01]
        i = scales.index(scale)
        if i + 1 < len(scales):
            return scales[i + 1]
        else:
            return scales[i]

    @Task()
    def startpulse(self, timestep=1e-9):
        params = self.pulse_parameters.widget.get()
        tau = params['start tau'].magnitude
        #self.osc.set_time(2*tau+0.4e-6)
        period = params['period'].magnitude
        repeat_unit = params['repeat unit'].magnitude
        pulse_width = params['pulse width'].magnitude
        echo = params['echo'].magnitude
        varwidth = pulse_width * 2
        step_tau = params['step tau'].magnitude
        self.osc.datasource(1)
        self.osc.scale(1, 1)
        for i in range(300):
            self.dataset.clear()
            self.fungen.output[1] = 'OFF'
            self.fungen.output[2] = 'OFF'
            self.fungen.clear_mem(1)
            self.fungen.clear_mem(2)
            self.fungen.wait()

            ## build pulse sequence for AWG channel 1
            chn1pulse = Arbseq_Class('chn1pulse', timestep)
            chn1pulse.delays = [0]
            chn1pulse.heights = [1]
            chn1pulse.widths = [pulse_width]
            chn1pulse.totaltime = pulse_width
            chn1pulse.nrepeats = 0
            chn1pulse.repeatstring = 'once'
            chn1pulse.markerstring = 'highAtStartGoLow'
            chn1pulse.markerloc = 0
            chn1pulsewidth = pulse_width
            chn1pulse.create_sequence()

            chn1dc = Arbseq_Class('chn1dc', timestep)
            chn1dc.delays = [0]
            chn1dc.heights = [0]
            chn1dc.widths = [repeat_unit]
            chn1dc.totaltime = repeat_unit
            chn1dc.repeatstring = 'repeat'
            chn1dc.markerstring = 'lowAtStart'
            chn1dc.markerloc = 0
            chn1dcrepeats = int(
                (tau - 0.5 * pulse_width - pulse_width) / repeat_unit)
            chn1dc.nrepeats = chn1dcrepeats
            chn1dcwidth = repeat_unit * chn1dcrepeats
            print(tau, pulse_width, chn1dcrepeats)
            chn1dc.create_sequence()

            chn1pulse2 = Arbseq_Class('chn1pulse2', timestep)
            chn1pulse2.delays = [0]
            chn1pulse2.heights = [1]
            chn1pulse2.widths = [pulse_width * 2]
            chn1pulse2.totaltime = pulse_width * 2
            chn1pulse2width = pulse_width * 2
            chn1pulse2.nrepeats = 0
            chn1pulse2.repeatstring = 'once'
            chn1pulse2.markerstring = 'lowAtStart'
            chn1pulse2.markerloc = 0
            chn1pulse2.create_sequence()

            chn1pulse3 = Arbseq_Class('chn1pulse3', timestep)
            chn1pulse3.delays = [0]
            chn1pulse3.heights = [0]
            chn1pulse3.widths = [repeat_unit]
            chn1pulse3.totaltime = repeat_unit
            chn1pulse3width = echo
            chn1pulse3.nrepeats = echo / repeat_unit
            chn1pulse3.repeatstring = 'repeat'
            chn1pulse3.markerstring = 'lowAtStart'
            chn1pulse3.markerloc = 0
            chn1pulse3.create_sequence()

            chn1dc2 = Arbseq_Class('chn1dc2', timestep)
            chn1dc2.delays = [0]
            chn1dc2.heights = [0]
            chn1dc2.widths = [1e-5]
            chn1dc2.totaltime = 1e-5
            chn1dc2.repeatstring = 'repeat'
            chn1dc2.markerstring = 'lowAtStart'
            print(
                float(
                    (period - chn1pulsewidth - chn1dcwidth - chn1pulse2width) /
                    1e-6))
            chn1dc2repeats = 1e4  #int((period-chn1pulsewidth-chn1dcwidth-chn1pulse2width)/1e-6)
            chn1dc2.nrepeats = chn1dc2repeats
            chn1dc2.markerloc = 0
            chn1dc2.create_sequence()

            self.fungen.send_arb(chn1pulse, 1)
            self.fungen.send_arb(chn1dc, 1)
            self.fungen.send_arb(chn1pulse2, 1)
            # self.fungen.send_arb(chn1pulse3, 1)
            self.fungen.send_arb(chn1dc2, 1)
            seq = [chn1pulse, chn1dc, chn1pulse2, chn1dc2]

            self.fungen.create_arbseq('twoPulse', seq, 1)

            self.fungen.wait()
            self.fungen.voltage[
                1] = params['pulse height'].magnitude + 0.000000000001 * i

            print(self.fungen.voltage[1])
            self.fungen.output[1] = 'ON'
            # self.osc.set_time(tau*2+pulse_width*3-tau/20)
            #time.sleep(100000)
            # if tau>6.0e-6:
            # 	if tau>60e-6:
            # 		self.osc.scale(1,0.01)
            # 	elif tau>30.0e-6:
            # 		self.osc.scale(1,0.02)
            # 	else:
            # 		self.osc.scale(1,0.02)
            # 	if tau>100e-6:
            # 		self.osc.scale(1,0.01)
            # else:
            # 	self.osc.scale(1,0.02)
            # maxy=self.osc.measure_max(1)
            # print(maxy)

            # if maxIndex<75000:
            # 	self.osc.set_time(curTime-700e-9)

            curTime = float(self.osc.query_time())
            # self.osc.set_time(curTime-step_tau)
            #print(maxy,float(self.osc.scale_query(1)))
            print("maxy", self.maxy)
            print("scale", float(self.osc.scale_query(1)))
            if i != 0:
                if self.maxy < 1 * float(self.osc.scale_query(1)):
                    self.osc.scale(
                        1, self.stepDown(1, float(self.osc.scale_query(1))))
            self.setwv(1535.120)
            time.sleep(5)
            self.maxy = 0
            for j in range(100):
                self.setwv(1535.137)
                time.sleep(0.3 + 0.004 * j)
                x, y = self.osc.curv()
                x = np.array(x)
                x = x - x.min()
                y = np.array(y)
                if max(y) > self.maxy:
                    self.maxy = max(y)
                self.saveData(x, y, tau, j)
                time.sleep(0.5)
                self.setwv(1535.120)
                time.sleep(5)

            #time.sleep(100000)

            tau = tau + step_tau
            curTime = float(self.osc.query_time())
            self.osc.set_time(curTime + 2 * step_tau - 20e-9 * step_tau * 1e6)

    @Element(name='Pulse parameters')
    def pulse_parameters(self):
        params = [
            #    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
            ('pulse height', {
                'type': float,
                'default': 3,
                'units': 'V'
            }),
            ('pulse width', {
                'type': float,
                'default': 5e-6,
                'units': 's'
            }),
            ('period', {
                'type': float,
                'default': 0.1,
                'units': 's'
            }),
            ('repeat unit', {
                'type': float,
                'default': 100e-9,
                'units': 's'
            }),
            ('start tau', {
                'type': float,
                'default': 3e-6,
                'units': 's'
            }),
            ('stop tau', {
                'type': float,
                'default': 10e-6,
                'units': 's'
            }),
            ('step tau', {
                'type': float,
                'default': 1e-6,
                'units': 's'
            }),
            ('echo', {
                'type': float,
                'default': 100e-6,
                'units': 's'
            }),
        ]
        w = ParamWidget(params)
        return w

    @startpulse.initializer
    def initialize(self):
        self.fungen.output[1] = 'OFF'
        self.fungen.output[2] = 'OFF'
        self.fungen.clear_mem(1)
        self.fungen.clear_mem(2)
        self.fungen.wait()
        self.osc.set_time(20.4e-6)

    @startpulse.finalizer
    def finalize(self):
        #self.fungen.output[1] = 'OFF'
        #self.fungen.output[2] = 'OFF'
        print('Two Pulse measurements complete.')
        return
Esempio n. 7
0
class LaserScan(Spyrelet):
    requires = {'wm': Bristol_771}
    conn1 = NetworkConnection('1.1.1.2')

    dlc = Client(conn1)
    daq = nidaqmx.Task()
    daq.ai_channels.add_ai_voltage_chan("Dev1/ai6")

    @Task()
    def scan(self):
        param = self.parameters.widget.get()
        filename = param['Filename']
        F = open(filename + '.dat', 'w')
        f = filename + '\'.dat'
        F2 = open(f, 'w')
        start_wavelength = param[
            'Start'].magnitude * 1e9  # set the start wavelength
        stop_voltage = param['Stop'].magnitude  # set the width of the piezo
        # scan by changign the stop voltage (the piezo scan scans from higher to
        # lower wavelengths)
        step = param['Step'].magnitude  # step is also a voltage
        n = param['Num Scan']  # number of piezo scans performed
        self.vt = np.arange(0, stop_voltage, step)  # voltage points over which
        # scan is performed
        self.daq.start(
        )  # why is the start function used here and not in other
        # spyrelets?
        with Client(self.conn1) as dlc:
            dlc.set("laser1:ctl:wavelength-set", start_wavelength)
            time.sleep(10)  # take 10s to initialize the laser at the start
            # wavelength
            for x in range(n):
                xx = []
                wl = []
                dlc.set("laser1:dl:pc:voltage-set", 0)
                time.sleep(3)  # take 3s to set the piezo voltage to 0
                act_start = self.wm.measure_wavelength()
                for item in self.vt:
                    dlc.set("laser1:dl:pc:voltage-set", item)
                    time.sleep(0.5)
                    xx.append(self.daq.read())
                time.sleep(5)
                act_stop = self.wm.measure_wavelength()
                wl = np.linspace(act_start, act_stop, len(xx))

                for item in xx:
                    F.write("%f," % item)
                for item in wl:
                    F2.write("%f," % item)
                F.write("\n")
                F2.write("\n")
        self.daq.stop()
        return

    @Element(name='Params')
    def parameters(self):
        params = [
            #    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
            ('Start', {
                'type': float,
                'default': 1499 * 1e-9,
                'units': 'm'
            }),
            ('Step', {
                'type': float,
                'default': 0.01,
                'units': 'V'
            }),
            ('Stop', {
                'type': float,
                'default': 2,
                'units': 'V'
            }),
            ('Num Scan', {
                'type': int,
                'default': 1
            }),
            ('Filename', {
                'type': str,
                'default': 'D:\\Data\\CW_cavity\\09.25\\wavelengthsweep'
            })
            # ('Amplitude', {'type': float, 'default': 1, 'units':'V'})
        ]
        w = ParamWidget(params)
        return w
Esempio n. 8
0
class LaserScan(Spyrelet):
    # delete if not using power meter
    requires = {'pmd': PM100D}
    conn1 = NetworkConnection('1.1.1.2')

    dlc = Client(conn1)

    daq = nidaqmx.Task()
    daq.ai_channels.add_ai_voltage_chan("Dev1/ai3")

    @Task()
    def scan(self):
        param = self.parameters.widget.get()
        filename = param['Filename']
        F = open(filename + '.dat', 'w')
        f = filename + '\'.dat'
        F2 = open(f, 'w')
        start_wavelength = param['Start'].magnitude * 1e9
        stop_wavelength = param['Stop'].magnitude * 1e9
        step = param['Step'].magnitude * 1e9
        n = param['Num Scan']
        self.wv = np.arange(start_wavelength, stop_wavelength, step)
        self.daq.start()
        print('here')
        with Client(self.conn1) as dlc:
            print('here')
            for x in range(n):
                xx = []
                dlc.set("laser1:ctl:wavelength-set", start_wavelength)
                time.sleep(8)
                for item in self.wv:
                    dlc.set("laser1:ctl:wavelength-set", item)
                    time.sleep(0.01)
                    xx.append(self.daq.read())  #daq

                    #xx.append(self.pmd.power.magnitude)# powermeter
                time.sleep(1)

                wl = np.linspace(start_wavelength, stop_wavelength, len(xx))
                for item in xx:
                    F.write("%f," % item)
                for item in wl:
                    F2.write("%f," % item)
                F.write("\n")
                F2.write("\n")
        self.daq.stop()
        return

    @Element(name='Params')
    def parameters(self):
        params = [
            #    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
            ('Start', {
                'type': float,
                'default': 1460 * 1e-9,
                'units': 'm'
            }),
            ('Step', {
                'type': float,
                'default': 0.01 * 1e-9,
                'units': 'm'
            }),
            ('Stop', {
                'type': float,
                'default': 1570 * 1e-9,
                'units': 'm'
            }),
            ('Num Scan', {
                'type': int,
                'default': 1
            }),
            ('Filename', {
                'type': str,
                'default': 'D:\\Data\\09.06.2019\\wavelengthsweep'
            })

            # ('Amplitude', {'type': float, 'default': 1, 'units':'V'})
        ]
        w = ParamWidget(params)
        return w
Esempio n. 9
0
import sys
import time
import socket

from toptica.lasersdk.client import Client, NetworkConnection
from toptica.lasersdk.dlcpro.v1_6_3 import DLCpro

#Provide IP adress and Port:1998
conn1 = NetworkConnection('172.30.56.206')

#with Client(conn1) as client:
#    print(client.get('system-label', str))
#    client.set('system-label', 'Please do not touch!')
#   #client.exec('laser1:dl:lock:close')
#   # Execute command with binary output stream and no return value
#    print(client.get('system-type',str))
#    print(client.get('serial-number',str))




import base64
import sys
import time

from toptica.lasersdk.dlcpro.v2_0_3 import DLCpro, NetworkConnection, DeviceNotFoundError, DecopError, UserLevel

script = 'OyBjaGVja3N1bSBmYzc4NDcwOWE5MTQwY2M1Mjg3ZWNiN2M1ZTAxYTQ3YQo7CihwYXJhbS1zZXQh' \
         'ICd1cHRpbWUgMTIzNCkKKGRpc3BsYXkgIkhhbGxpaGFsbG9cbiIp'

Esempio n. 10
0
class PLThinFilm(Spyrelet):
	requires = {
		'wm': Bristol_771,
		'fungen': Keysight_33622A,
		'SRS': SRS900
	}
	qutag = None
	laser = NetworkConnection('1.1.1.2')
	xs=np.array([])
	ys=np.array([])
	hist=[]

	def configureQutag(self):
		qutagparams = self.qutag_params.widget.get()
		start = qutagparams['Start Channel']
		stop = qutagparams['Stop Channel']
		##True = rising edge, False = falling edge. Final value is threshold voltage
		self.qutag.setSignalConditioning(start,self.qutag.SIGNALCOND_MISC,True,1)
		self.qutag.setSignalConditioning(stop,self.qutag.SIGNALCOND_MISC,True,0.1)
		self.qutag.enableChannels((start,stop))

	def homelaser(self,start):
		current=self.wm.measure_wavelength()
		with Client(self.laser) as client:

			while current<start-0.001 or current>start+0.001:
				setting=client.get('laser1:ctl:wavelength-set', float)
				offset=current-start
				client.set('laser1:ctl:wavelength-set', setting-offset)
				time.sleep(3)
				current=self.wm.measure_wavelength()
				print(current, start)

	def createHistogram(self,stoparray, timebase, bincount, period, index, wls,out_name,extra_data=False):
		print('creating histogram')

		hist = [0]*bincount
		for stoptime in stoparray:
			# stoptime=ps
			# timebase = converts to seconds
			# bincount: # of bins specified by user
			# period: measurement time specified by user
			binNumber = int(stoptime*timebase*bincount/(period))
			if binNumber >= bincount:
				continue
				print('error')
			else:
				hist[binNumber]+=1
		if extra_data==False:
			np.savez(os.path.join(out_name,str(index)),hist,wls)
		if extra_data!=False:
			np.savez(os.path.join(out_name,str(index)),hist,wls,extra_data)
		#np.savez(os.path.join(out_name,str(index+40)),hist,wls)
		print('Data stored under File Name: ' + out_name +'\\'+str(index)+'.npz')

	def resetTargets(self,targets,totalShift,i,channel):
		print('AWG limit exceeded, resetting voltage targets')

		# get the current wavelength
		current=self.wm.measure_wavelength()

		# adjust all targets to be lower again
		# reset totalShift
		print('totalShift: '+str(totalShift))
		newTargets=[j-totalShift for j in targets]
		print('newTargets')
		voltageTargets=newTargets
		totalShift=0

		# bring voltage back to ideal
		
		self.fungen.offset[channel]=Q_(voltageTargets[i-1],'V')
		# drive to last wavelength again
		self.homelaser(current)
		wl=self.wm.measure_wavelength()
		return voltageTargets,totalShift,wl

	def reset_quench(self):
		"""
		A typical quench shows the voltage exceeding 2mV.
		"""
		qutagparams = self.qutag_params.widget.get()
		# vm1=qutagparams['Voltmeter Channel 1']
		vm2=qutagparams['Voltmeter Channel 2']
		# vs1=qutagparams['Battery Port 1']
		vs2=qutagparams['Battery Port 2']

		# self.SRS.clear_status()
		# V1=self.SRS.SIM970_voltage[vm1].magnitude
		self.SRS.clear_status()
		V2=self.SRS.SIM970_voltage[vm2].magnitude

		quenchfix='YES'

		# i=0
		# while (float(V1)>=0.010):
		# 	i+=1
		# 	print('Voltage 1 higher than 10mV, resetting')
		# 	self.SRS.SIM928_on_off[vs1]='OFF'
		# 	self.SRS.SIM928_on_off[vs2]='OFF'
		# 	self.SRS.SIM928_on_off[vs1]='ON'
		# 	self.SRS.SIM928_on_off[vs2]='ON'
		# 	print('checking Voltage 1 again')
		# 	self.SRS.clear_status()
		# 	time.sleep(1)
		# 	V1=self.SRS.SIM970_voltage[vm1].magnitude
		# 	print('Voltage 1: '+str(V1)+'V')
		# 	if i>10:
		# 		self.fungen.output[1]='OFF'
		# 		self.fungen.output[2]='OFF'
		# 		quenchfix='NO'
		# 		break

		i=0
		while (float(V2)>=0.010):
			i+=1
			print('Voltage 2 higher than 10mV, resetting')
			self.SRS.SIM928_on_off[vs1]='OFF'
			self.SRS.SIM928_on_off[vs2]='OFF'
			self.SRS.SIM928_on_off[vs1]='ON'
			self.SRS.SIM928_on_off[vs2]='ON'
			print('checking Voltage 2 again')
			self.SRS.clear_status()
			time.sleep(1)
			V2=self.SRS.SIM970_voltage[vm2].magnitude
			print('Voltage 2: '+str(V2)+'V')
			if i>10:
				self.fungen.output[1]='OFF'
				self.fungen.output[2]='OFF'
				quenchfix='NO'
				break
		return quenchfix
	
	@Task()
	def piezo_scan(self,timestep=100e-9):
		
		#self.fungen.output[1]='ON'
		piezo_params=self.piezo_parameters.widget.get()
		Vstart=piezo_params['voltage start']
		Vstop=piezo_params['voltage end']
		pts=piezo_params['scan points']

		voltageTargets=np.linspace(Vstart,Vstop,pts)
		reversedTargets=voltageTargets[::-1]
		voltageTargets=reversedTargets

		print('voltageTargets: '+str(voltageTargets))


		channel=piezo_params['AWG channel']

		# turn off AWG
		self.fungen.output[channel]='OFF'

		##Qutag Part
		self.configureQutag()
		expparams = self.exp_parameters.widget.get()
		wlparams = self.wl_parameters.widget.get()

		# drive to the offset estimated by the piezo voltage
		# 1MOhm impedance of laser mismatch with 50Ohm impedance of AWG
		# multiplies voltage 2x
		# 140V ~ 40GHz ~ 315pm

		piezo_range=(Vstop.magnitude-Vstart.magnitude)*0.315/(140)*piezo_params['Scale factor'] #pm
		print('piezo_range: '+str(piezo_range)+str(' nm'))

		wl_start=wlparams['start']-piezo_range
		wl_stop=wlparams['stop']+piezo_range
		wlpts=np.linspace(wl_start,wl_stop,pts)

		self.homelaser(wlparams['start']-piezo_range)
		print('Laser Homed!')
		qutagparams = self.qutag_params.widget.get()
		lost = self.qutag.getLastTimestamps(True) # clear Timestamp buffer
		stoptimestamp = 0
		synctimestamp = 0
		bincount = qutagparams['Bin Count']
		timebase = self.qutag.getTimebase()
		start = qutagparams['Start Channel']
		stop = qutagparams['Stop Channel']

		PATH="C:\\Data\\"+self.exp_parameters.widget.get()['File Name']

		if PATH!="C:\\Data\\":
			if (os.path.exists(PATH)):
				print('deleting old directory with same name')
				os.system('rm -rf '+str(PATH))
			print('making new directory')
			Path(PATH).mkdir(parents=True, exist_ok=True)
		else:
			print("Specify a foldername & rerun task.")
			print("Task will error trying to saving data.")

		# turn on AWG
		self.fungen.output[channel]='ON'

		last_wl=self.wm.measure_wavelength()
		wls=[]
		totalShift=0

		for i in range(pts):
			print(i)
			if (voltageTargets[i]>5) or (voltageTargets[i]<-5):

				newTargets,newShift,wl=self.resetTargets(voltageTargets,totalShift,i,channel)
				voltageTargets=newTargets
				totalShift=newShift

			self.fungen.offset[channel]=Q_(voltageTargets[i],'V')
			wl=self.wm.measure_wavelength()
			counter=0
			if len(wls)!=0:
				last_wl=np.mean(np.array(wls).astype(np.float))
			
			print('i: '+str(i)+', initializing')

			while ((wl<wlpts[i]-0.0002) or (wl>wlpts[i]+0.0002)):
					offset=wl-wlpts[i]
					Voff=offset/0.315*140/(piezo_params['Scale factor']*2)
					if offset<0:
						if voltageTargets[i]+Voff<-5:
							newTargets,newShift,wl=self.resetTargets(voltageTargets,totalShift,i,channel)
							voltageTargets=newTargets
							totalShift=newShift
							print('AWG limit exceeded, resetting voltage targets')
						else:
							newTargets=[j+Voff for j in voltageTargets]
							voltageTargets=newTargets
							self.fungen.offset[channel]=Q_(newTargets[i],'V')
							time.sleep(3)
							wl=self.wm.measure_wavelength()
							counter+=Voff
							totalShift+=Voff
					else:
						if voltageTargets[i]+Voff>5:
							newTargets,newShift,wl=self.resetTargets(voltageTargets,totalShift,i,channel)
							voltageTargets=newTargets
							totalShift=newShift
							print('AWG limit exceeded, resetting voltage targets')
						else:
							newTargets=[j+Voff for j in voltageTargets]
							voltageTargets=newTargets
							self.fungen.offset[channel]=Q_(newTargets[i],'V')
							time.sleep(3)
							wl=self.wm.measure_wavelength()
							counter+=Voff
							totalShift+=Voff

			print('taking data')
			print('current target wavelength: '+str(wlpts[i]))
			print('current set voltage: '+str(voltageTargets[i]))
			print('actual wavelength: '+str(self.wm.measure_wavelength()))
			
			time.sleep(1)
			##Wavemeter measurements
			stoparray = []
			startTime = time.time()
			wls=[]
			lost = self.qutag.getLastTimestamps(True)
			counter2=0

			looptime=startTime
			while looptime-startTime < expparams['Measurement Time'].magnitude:
				loopstart=time.time()
				# get the lost timestamps
				lost = self.qutag.getLastTimestamps(True)
				# wait half a milisecond
				time.sleep(5*0.1)
				# get thte timestamps in the last half milisecond
				timestamps = self.qutag.getLastTimestamps(True)

				tstamp = timestamps[0] # array of timestamps
				tchannel = timestamps[1] # array of channels
				values = timestamps[2] # number of recorded timestamps

				for k in range(values):
					# output all stop events together with the latest start event
					if tchannel[k] == start:
						synctimestamp = tstamp[k]
					else:
						stoptimestamp = tstamp[k]
						stoparray.append(stoptimestamp)
				wl=self.wm.measure_wavelength()
				wls.append(str(wl))
				looptime+=time.time()-loopstart
				#print('i: '+str(i)+', looptime-startTime: '+str(looptime-startTime))
				quenchfix=self.reset_quench()
				if quenchfix!='YES':
					print('SNSPD quenched and could not be reset')
					self.fungen.output[1]='OFF'
					self.fungen.output[2]='OFF'
					endloop

				
				while ((wl<wlpts[i]-0.0002) or (wl>wlpts[i]+0.0002)) and (time.time()-startTime < expparams['Measurement Time'].magnitude):
					offset=wl-wlpts[i]
					Voff=offset/0.315*140/(piezo_params['Scale factor']*2)
					if offset<0:
						if voltageTargets[i]+Voff<-5:
							break
						else:
							newTargets=[j+Voff for j in voltageTargets]
							voltageTargets=newTargets
							self.fungen.offset[channel]=Q_(newTargets[i],'V')
							time.sleep(3)
							wl=self.wm.measure_wavelength()
							counter2+=Voff
							totalShift+=Voff
					else:
						if voltageTargets[i]+Voff>5:
							break
						else:
							newTargets=[j+Voff for j in voltageTargets]
							voltageTargets=newTargets
							self.fungen.offset[channel]=Q_(newTargets[i],'V')
							time.sleep(3)
							wl=self.wm.measure_wavelength()
							counter2+=Voff
							totalShift+=Voff
				
			print('actual  wavelength: '+str(wl))
			print('targets shift during measurement:  '+str(counter2)+'V')
				

			self.createHistogram(stoparray, timebase, bincount,
				expparams['AWG Pulse Repetition Period'].magnitude,i, wls,
				"C:\\Data\\"+self.exp_parameters.widget.get()['File Name'])
		# turn off AWG
		self.fungen.output[channel]='OFF'
	

	@Task()
	def startpulse(self, timestep=100e-9):

		self.fungen.output[1]='OFF'
		#self.fungen.output[2]='OFF'
		self.SRS.SIMmodule_on[6] ##Turn on the power supply of the SNSPD
		time.sleep(3)  ##wait 1s to turn on the SNSPD

		##Qutag Part
		self.configureQutag()
		expparams = self.exp_parameters.widget.get()
		wlparams = self.wl_parameters.widget.get()
		self.homelaser(wlparams['start'])
		print('Laser Homed!')
		qutagparams = self.qutag_params.widget.get()
		lost = self.qutag.getLastTimestamps(True) # clear Timestamp buffer
		stoptimestamp = 0
		synctimestamp = 0
		bincount = qutagparams['Bin Count']
		timebase = self.qutag.getTimebase()
		start = qutagparams['Start Channel']
		stop = qutagparams['Stop Channel']

		self.fungen.frequency[1]=expparams['AWG Pulse Frequency']
		self.fungen.voltage[1]=3.5
		self.fungen.offset[1]=1.75
		self.fungen.phase[1]=0   
		self.fungen.pulse_width[1]=expparams['AWG Pulse Width']
		self.fungen.waveform[1]='PULS'
		self.fungen.output[1]='ON'
		

		#PATH="C:\\Data\\12.18.2020_ffpc\\"+self.exp_parameters.widget.get()['File Name']+"\\motor_scan"
		PATH="Q:\\Data\\5.28.2021_ffpc\\"+self.exp_parameters.widget.get()['File Name']
		print('here')
		print('PATH: '+str(PATH))
		if PATH!="Q:\\Data\\5.28.2021_ffpc\\":
			if (os.path.exists(PATH)):
				print('deleting old directory with same name')
				os.system('rm -rf '+str(PATH))
			print('making new directory')
			Path(PATH).mkdir(parents=True, exist_ok=True)
			#os.mkdir(PATH)
		else:
			print("Specify a foldername & rerun task.")
			print("Task will error trying to saving data.")

		wlTargets=np.linspace(wlparams['start'],wlparams['stop'],expparams['# of points'])
		

		print('wlTargets: '+str(wlTargets))
		for i in range(expparams['# of points']):
			print(i)
			with Client(self.laser) as client:

				setting=client.get('laser1:ctl:wavelength-set', float)
				client.set('laser1:ctl:wavelength-set', wlTargets[i])
				wl=self.wm.measure_wavelength()
				

			while ((wl<wlTargets[i]-0.001) or (wl>wlTargets[i]+0.001)):
					print('correcting for laser drift')
					self.homelaser(wlTargets[i])
					wl=self.wm.measure_wavelength()
					print('current target wavelength: '+str(wlTargets[i]))
					print('actual wavelength: '+str(self.wm.measure_wavelength()))
					time.sleep(1)


			print('taking data')
			print('current target wavelength: '+str(wlTargets[i]))
			print('actual wavelength: '+str(self.wm.measure_wavelength()))
			
			time.sleep(1)
			##Wavemeter measurements
			stoparray = []
			startTime = time.time()
			wls=[]
			lost = self.qutag.getLastTimestamps(True)
			#counter2=0

			looptime=startTime
			while looptime-startTime < expparams['Measurement Time'].magnitude:
				loopstart=time.time()
				# get the lost timestamps
				lost = self.qutag.getLastTimestamps(True)
				# wait half a milisecond
				time.sleep(5*0.1)   #
				# get thte timestamps in the last half milisecond
				timestamps = self.qutag.getLastTimestamps(True)

				tstamp = timestamps[0] # array of timestamps
				tchannel = timestamps[1] # array of channels
				values = timestamps[2] # number of recorded timestamps

				for k in range(values):
					# output all stop events together with the latest start event
					if tchannel[k] == start:
						synctimestamp = tstamp[k]
					else:
						stoptimestamp = tstamp[k]
						stoparray.append(stoptimestamp)
				wl=self.wm.measure_wavelength()
				wls.append(str(wl))
				looptime+=time.time()-loopstart
				print('i: '+str(i)+', looptime-startTime: '+str(looptime-startTime))
				# quenchfix=self.reset_quench()
				# if quenchfix!='YES':
				# 	print('SNSPD quenched and could not be reset')
				# 	# self.fungen.output[1]='OFF'
				# 	self.fungen.output[2]='OFF'
				# 	endloop

				
				while ((wl<wlTargets[i]-0.001) or (wl>wlTargets[i]+0.001)) and (time.time()-startTime < expparams['Measurement Time'].magnitude):
					print('correcting for laser drift')
					self.homelaser(wlTargets[i])
					wl=self.wm.measure_wavelength()
			print('actual  wavelength: '+str(wl))
			#print('I am here')
			self.createHistogram(stoparray, timebase, bincount, expparams['AWG Pulse Repetition Period'].magnitude,str(i), wls,PATH)
			# self.createHistogram(stoparray, timebase, bincount,period,str(i),
			# 	wls,PATH,savefreqs)
		self.fungen.output[1]='OFF'
		self.SRS.SIMmodule_off[6] ##turn off the SNSPD power suppy after the measurement

	#@Task()
	#def spectralDiffusion_wRFsource(self):
		""" Task to measure spectral diffusion on timescales < T1. Assumes that
		1 channel of the keysight AWG is sending a sine wave to an EOM. The
		amplitude of the RF drive for the EOM is set such that the sidebands
		have an equal amplitude to the pump beam. This tasks sweeps the
		frequency of the sine wave (separation of the EOM sidebands) while
		collecting PL, which can be used to determine the spectral diffusion
		linewidth since the saturation of the ions will be determined by how
		much the sidebands overlap with the spectral  diffusion lineshape.
		
		This task is good for modulating between 1MHz and 200MHz. 
		JDSU EOM amplifier has nonlinear performance below 1MHz (amplification
		increases), but the N5181A works down to 100kHz if desired.
		"""

		# get the parameters for the experiment from the widget
		"""
		SD_wRFparams=self.SD_wRFparams.widget.get()
		startFreq=SD_wRFparams['Start frequency']
		stopFreq=SD_wRFparams['Stop frequency']

		power=SD_wRFparams['RF Power']

		runtime=SD_wRFparams['Runtime']
		wl=SD_wRFparams['Wavelength']
		points=SD_wRFparams['# of points']
		period=SD_wRFparams['Period']
		foldername=self.SD_wRFparams.widget.get()['File Name']

		# convert the period & runtime to floats
		period=period.magnitude
		runtime=runtime.magnitude

		# set the amplitude of the RF signal
		self.source.set_RF_Power(power)

		# home the laser
		self.configureQutag()
		self.homelaser(wl)
		print('Laser Homed!')

		##Qutag Part
		qutagparams = self.qutag_params.widget.get()
		lost = self.qutag.getLastTimestamps(True) # clear Timestamp buffer
		stoptimestamp = 0
		synctimestamp = 0
		bincount = qutagparams['Bin Count']
		timebase = self.qutag.getTimebase()
		start = qutagparams['Start Channel']
		stop = qutagparams['Stop Channel']

		PATH="D:\\Data\\"+foldername
		if PATH!="D:\\Data\\":
			if (os.path.exists(PATH)):
				print('deleting old directory with same name')
				os.system('rm -rf '+str(PATH))
			print('making new directory')
			Path(PATH).mkdir(parents=True, exist_ok=True)

		# make a vector containing all the frequency setpoints for the EOM
		freqs=np.linspace(startFreq,stopFreq,points)

		# now loop through all the set frequencies of the EOM modulation
		# and record the PL on the qutag

		# turn on the RF source & set it in CW mode
		self.source.FM_ON()
		self.source.set_CW_mode()

		for i in range(points):

			#set the frequency on the RF source
			self.source.set_CW_Freq(freqs[i])
			

			# want to actively stabilize the laser frequency since it can
			# drift on the MHz scale
			with Client(self.laser) as client:

				setting=client.get('laser1:ctl:wavelength-set', float)
				client.set('laser1:ctl:wavelength-set', wl)
				currentwl=self.wm.measure_wavelength()
				

			while ((currentwl<wl-0.001) or (currentwl>wl+0.001)):
					print('correcting for laser drift')
					self.homelaser(wl)
					currentwl=self.wm.measure_wavelength()
					print('current target wavelength: '+str(wl))
					print('actual wavelength: '+str(currentwl))
					time.sleep(1)


			print('taking data')
			print('current frequency: '+str(freqs[i]))
			print('current target wavelength: '+str(wl))
			print('actual wavelength: '+str(self.wm.measure_wavelength()))
			
			time.sleep(1)


			stoparray = []
			startTime = time.time()
			wls=[]
			savefreqs=[]
			lost = self.qutag.getLastTimestamps(True)

			looptime=startTime
			while looptime-startTime < runtime:
				loopstart=time.time()
				# get the lost timestamps
				lost = self.qutag.getLastTimestamps(True)
				# wait half a milisecond
				time.sleep(5*0.1)
				# get thte timestamps in the last half milisecond
				timestamps = self.qutag.getLastTimestamps(True)

				tstamp = timestamps[0] # array of timestamps
				tchannel = timestamps[1] # array of channels
				values = timestamps[2] # number of recorded timestamps

				for k in range(values):
					# output all stop events together with the latest start event
					if tchannel[k] == start:
						synctimestamp = tstamp[k]
					else:
						stoptimestamp = tstamp[k]
						stoparray.append(stoptimestamp)
				currentwl=self.wm.measure_wavelength()
				wls.append(str(currentwl))
				savefreqs.append(float(freqs[i]))
				looptime+=time.time()-loopstart

				while ((currentwl<wl-0.001) or (currentwl>wl+0.001)) and (time.time()-startTime < runtime):
					print('correcting for laser drift')
					self.homelaser(wl)
					currentwl=self.wm.measure_wavelength()
			print('actual  wavelength: '+str(currentwl))

			self.createHistogram(stoparray, timebase, bincount,period,str(i),
				wls,PATH,savefreqs)

		# turnn off the RF output of the N5181A whenn done
		self.source.RF_OFF()
		"""
	@Task()
	def spectralDiffusion_wAWG(self):
		""" Task to measure spectral diffusion on timescales < T1. Uses the 
		Agilent N5181A RF source to send a sine wave to the phase EOM. The
		amplitude of the RF drive for the EOM is set such that the sidebands
		have an equal amplitude to the pump beam (Calibrated on 11/19/20 to 
		be 6Vpp for the JDSU phase EOM). This tasks sweeps the
		frequency of the sine wave (separation of the EOM sidebands) while
		collecting PL, which can be used to determine the spectral diffusion
		linewidth since the saturation of the ions will be determined by how
		much the sidebands overlap with the spectral  diffusion lineshape.
		
		The Keysight AWG only works up to 80MHz. 

		Could potentially modify code to use Siglent AWG which can go up to 120MHz
		"""
		self.fungen.output[1]='OFF'
		self.fungen.output[2]='OFF'
		# some initialization of the function generator
		self.fungen.clear_mem(1)
		self.fungen.clear_mem(2)
		self.fungen.wait()
		#self.fungen.output[1]='ON'
		self.SRS.SIMmodule_on[6] ##Turn on the power supply of the SNSPD
		time.sleep(1)  ##wait 1s to turn on the SNSPD


		# get the parameters for the experiment from the widget
		SD_wAWGparams=self.SD_wAWGparams.widget.get()
		startFreq=SD_wAWGparams['Start frequency']
		stopFreq=SD_wAWGparams['Stop frequency']
		EOMvoltage=SD_wAWGparams['EOM voltage']
		runtime=SD_wAWGparams['Runtime']
		EOMchannel=SD_wAWGparams['EOM channel']
		Pulsechannel=SD_wAWGparams['Pulse channel']
		Pulsefreq=SD_wAWGparams['Pulse Frequency']
		Pulsewidth=SD_wAWGparams['Pulse Width']
		period=SD_wAWGparams['Pulse Repetition Period']
		wl=SD_wAWGparams['Wavelength']
		points=SD_wAWGparams['# of points']
		foldername=SD_wAWGparams['File Name']

		# convert the period & runtime to floats
		period=period.magnitude
		runtime=runtime.magnitude
		self.fungen.clear_mem(EOMchannel)
		self.fungen.clear_mem(Pulsechannel)
		self.fungen.waveform[Pulsechannel]='PULS'
		self.fungen.waveform[EOMchannel]='SIN'


		# set the sine wave driving the EOM on the other channel
		self.fungen.waveform[EOMchannel]='SIN'
		self.fungen.voltage[EOMchannel]=EOMvoltage
		self.fungen.offset[EOMchannel]=0
		self.fungen.phase[EOMchannel]=0


		self.fungen.waveform[Pulsechannel]='PULS'
		self.fungen.frequency[Pulsechannel]=Pulsefreq
		self.fungen.voltage[Pulsechannel]=3.5
		self.fungen.offset[Pulsechannel]=1.75
		self.fungen.phase[Pulsechannel]=0
		self.fungen.pulse_width[Pulsechannel]=Pulsewidth


		self.fungen.output[EOMchannel]='ON'
		self.fungen.output[Pulsechannel]='ON'
		

		# home the laser
		self.configureQutag()
		self.homelaser(wl)
		print('Laser Homed!')

		##Qutag Part
		qutagparams = self.qutag_params.widget.get()
		lost = self.qutag.getLastTimestamps(True) # clear Timestamp buffer
		stoptimestamp = 0
		synctimestamp = 0
		bincount = qutagparams['Bin Count']
		timebase = self.qutag.getTimebase()
		start = qutagparams['Start Channel']
		stop = qutagparams['Stop Channel']

		PATH="C:\\Data\\12.29.2020_ffpc\\SD0.1mW20dBatt195227GHz\\"+str(foldername)
		print('PATH: '+str(PATH))
		if PATH!="C:\\Data\\12.29.2020_ffpc\\SD0.1mW20dBatt195227GHz\\":
			if (os.path.exists(PATH)):
				print('deleting old directory with same name')
				os.system('rm -rf '+str(PATH))
				print('PATH: '+str(PATH))
			print('making new directory')
			Path(PATH).mkdir(parents=True, exist_ok=True)
		else:
			print("Specify a foldername & rerun task.")
			print("Task will error trying to saving data.")

		# make a vector containing all the frequency setpoints for the EOM
		freqs=np.linspace(startFreq,stopFreq,points)

		# now loop through all the set frequencies of the EOM modulation
		# and record the PL on the qutag


		for i in range(points):
			self.fungen.frequency[EOMchannel]=freqs[i]

			# want to actively stabilize the laser frequency since it can
			# drift on the MHz scale
			with Client(self.laser) as client:

				setting=client.get('laser1:ctl:wavelength-set', float)
				client.set('laser1:ctl:wavelength-set', wl)
				currentwl=self.wm.measure_wavelength()
				

			while ((currentwl<wl-0.001) or (currentwl>wl+0.001)):
					print('correcting for laser drift')
					self.homelaser(wl)
					currentwl=self.wm.measure_wavelength()
					print('current target wavelength: '+str(wl))
					print('actual wavelength: '+str(currentwl))
					time.sleep(1)


			print('taking data')
			print('current frequency: '+str(freqs[i]))
			print('current target wavelength: '+str(wl))
			print('actual wavelength: '+str(self.wm.measure_wavelength()))
			
			time.sleep(1)


			stoparray = []
			startTime = time.time()
			wls=[]
			savefreqs=[]
			lost = self.qutag.getLastTimestamps(True)

			looptime=startTime
			while looptime-startTime < runtime:
				loopstart=time.time()
				# get the lost timestamps
				lost = self.qutag.getLastTimestamps(True)
				# wait half a milisecond
				time.sleep(5*0.1)
				# get thte timestamps in the last half milisecond
				timestamps = self.qutag.getLastTimestamps(True)

				tstamp = timestamps[0] # array of timestamps
				tchannel = timestamps[1] # array of channels
				values = timestamps[2] # number of recorded timestamps

				for k in range(values):
					# output all stop events together with the latest start event
					if tchannel[k] == start:
						synctimestamp = tstamp[k]
					else:
						stoptimestamp = tstamp[k]
						stoparray.append(stoptimestamp)
				currentwl=self.wm.measure_wavelength()
				wls.append(str(currentwl))
				savefreqs.append(float(freqs[i]))
				looptime+=time.time()-loopstart

				# quenchfix=self.reset_quench()
				# if quenchfix!='YES':
				# 	print('SNSPD quenched and could not be reset')
				# 	self.fungen.output[1]='OFF'
				# 	self.fungen.output[2]='OFF'
				# 	endloop

				while ((currentwl<wl-0.001) or (currentwl>wl+0.001)) and (time.time()-startTime < runtime):
					print('correcting for laser drift')
					self.homelaser(wl)
					currentwl=self.wm.measure_wavelength()
			print('actual  wavelength: '+str(currentwl))

			self.createHistogram(stoparray, timebase, bincount,period,str(i),wls,PATH,savefreqs)

		self.fungen.output[EOMchannel]='OFF'  ##turn off the AWG for both channels
		self.fungen.output[Pulsechannel]='OFF'
		self.SRS.SIMmodule_off[6] ##turn off the SNSPD power suppy after the measurement


	@Task()
	def qutagInit(self):
		print('qutag successfully initialized')

	@Element(name='Wavelength parameters')
	def wl_parameters(self):
		params = [
	#    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
		# ('start', {'type': float, 'default': 1535.665}),
		('start', {'type': float, 'default': 1535.527}),
		('stop', {'type': float, 'default':  1535.685})
		# ('stop', {'type': float, 'default': 1535.61})
		]
		w = ParamWidget(params)
		return w

	@Element(name='Piezo scan parameters')
	def piezo_parameters(self):
		params=[
			('voltage start',{'type': float,'default':-3,'units':'V'}),
			('voltage end',{'type': float,'default':3,'units':'V'}),
			('scan points',{'type':int,'default':100}),
			('AWG channel',{'type':int,'default':0}),
			('Scale factor',{'type':float,'default':2})
		]
		w=ParamWidget(params)
		return w

	@Element(name='Experiment Parameters')
	def exp_parameters(self):
		params = [
	#    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
		('# of points', {'type': int, 'default': 40}),
		('Measurement Time', {'type': int, 'default': 180, 'units':'s'}),
		('File Name', {'type': str}),
		('AWG Pulse Repetition Period',{'type': float,'default': 2e-3,'units':'s'}),
		('AWG Pulse Frequency',{'type': int,'default': 500,'units':'Hz'}),
		('AWG Pulse Width',{'type': float,'default': 300e-9,'units':'s'}),
		]
		w = ParamWidget(params)
		return w

	@Element(name='QuTAG Parameters')
	def qutag_params(self):
		params = [
	#    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
		('Start Channel', {'type': int, 'default': 0}),
		('Stop Channel', {'type': int, 'default': 2}),
		('Bin Count', {'type': int, 'default': 1000}),
		# ('Voltmeter Channel 1',{'type':int,'default':1}),
		('Voltmeter Channel 2',{'type':int,'default':2}),
		# ('Battery Port 1',{'type':int,'default':5}),
		('Battery Port 2',{'type':int,'default':6})
		]
		w = ParamWidget(params)
		return w

	@Element(name='Spectral diffusion experiment parameters')
	def SD_wAWGparams(self):
		""" Widget containing the parameters used in the spectral diffusion
		experiment.

		Default EOM voltage calibrated by Christina and Yizhong on 11/19/20.
		(rough estimate for equal amplitude sidebands)
		"""
		params=[
		('Start frequency',{'type':float,'default':3.1e6,'units':'Hz'}),
		('Stop frequency',{'type':float,'default':3.3e6,'units':'Hz'}),
		('EOM voltage',{'type':float,'default':6,'units':'V'}),
		('Runtime',{'type':float,'default':300,'units':'s'}),
		('EOM channel',{'type':int,'default':1}),
		('Pulse channel',{'type':int,'default':2}),
		('Pulse Repetition Period',{'type': float,'default': 0.001,'units':'s'}),
		('Pulse Frequency',{'type': int,'default': 1000,'units':'Hz'}),
		('Pulse Width',{'type': float,'default': 500e-9,'units':'s'}),
		('Wavelength',{'type':float,'default':1535.61}),
		('# of points',{'type':int,'default':2}),
		('File Name',{'type':str}),
		]
		w=ParamWidget(params)
		return w

	#@Element(name='Spectral diffusion experiment parameters')
	#def SD_wRFparams(self):
		""" Widget containing the parameters used in the spectral diffusion
		experiment.

		Default EOM voltage calibrated by Christina and Yizhong on 11/19/20.
		(rough estimate for equal amplitude sidebands)
		"""
		"""
		params=[
		('Start frequency',{'type':float,'default':5e6,'units':'Hz'}),
		('Stop frequency',{'type':float,'default':200e6,'units':'Hz'}),
		('RF Power',{'type':float,'default':-1.30,'units':'dBm'}),
		('Runtime',{'type':float,'default':10,'units':'s'}),
		('Wavelength',{'type':float,'default':1536.480}),
		('Period',{'type':float,'default':100e-3,'units':'s'}),
		('# of points',{'type':int,'default':40}),
		('File Name',{'type':str}),
		]
		w=ParamWidget(params)
		return w
		"""

	@startpulse.initializer
	def initialize(self):
		self.wm.start_data()

	@startpulse.finalizer
	def finalize(self):
		self.wm.stop_data()
		print('Lifetime measurements complete.')
		return

	@qutagInit.initializer
	def initialize(self):
		from lantz.drivers.qutools import QuTAG
		self.qutag = QuTAG()
		devType = self.qutag.getDeviceType()
		print('devType: '+str(devType))
		if (devType == self.qutag.DEVTYPE_QUTAG):
			print("found quTAG!")
		else:
			print("no suitable device found - demo mode activated")
		print("Device timebase:" + str(self.qutag.getTimebase()))
		return

	@qutagInit.finalizer
	def finalize(self):
		return
def main():

    if 1:
        with DLCpro(NetworkConnection('192.168.1.205')) as dlcpro:
            #client.exec('buzzer:play "A B C D E G F E D F E D C E D C"')
            #client.exec('buzzer:play "A A A A A A E E H E H E AAAA"')
            #client.exec('laser1:dl:lock:close')
            #client.exec('laser1:dl:lock:open')
            #old_voltage=dlcpro.laser1.dl.pc.voltage_act.get()
            #v_locked=dlcpro.laser1.dl.pc.voltage_act.get()
            #dlcpro.laser1.dl.lock.open()
            #dlcpro.laser1.dl.pc.voltage_set.set(v_locked)
            for i in range(10):
                print(dlcpro.laser1.dl.lock.pid1.values())
                time.sleep(0.2)
            #dlcpro.laser1.dl.lock.close()

        if 0:
            my_jump = -2.30

            old_setvolt = dlcpro.laser1.dl.pc.voltage_set.get()
            #print(old_setvolt)
            #old_actvolt=dlcpro.laser1.dl.pc.voltage_act.get()
            #new_actvolt=old_actvolt+my_jump

            #new_setvolt=old_actvolt+my_jump

            new_setvolt = old_setvolt + my_jump
            #print('old:',old_actvolt)
            print('old:', old_setvolt)

            print('new:', new_setvolt)
            dlcpro.laser1.dl.pc.voltage_set.set(new_setvolt)
            time.sleep(0.2)
            dlcpro.laser1.dl.lock.close()

    if 0:
        with DLCpro(NetworkConnection('192.168.1.205')) as dlcpro:
            #client.exec('buzzer:play "A B C D E G F E D F E D C E D C"')
            #client.exec('buzzer:play "A A A A A A E E H E H E AAAA"')
            #client.exec('laser1:dl:lock:close')
            #client.exec('laser1:dl:lock:open')
            #old_voltage=dlcpro.laser1.dl.pc.voltage_act.get()

            my_jump = +2.3

            old_setvolt = dlcpro.laser1.dl.pc.voltage_set.get()
            old_actvolt = dlcpro.laser1.dl.pc.voltage_act.get()
            new_actvolt = old_actvolt + my_jump
            new_setvolt = old_setvolt + my_jump
            dlcpro.laser1.dl.pc.voltage_set.set(new_setvolt)

            print('jump 1 of 4 done, wait 3 sec.')
            time.sleep(3)

            temp_actvolt = dlcpro.laser1.dl.pc.voltage_act.get()
            delta = new_actvolt - temp_actvolt
            new_setvolt = new_setvolt - delta
            dlcpro.laser1.dl.pc.voltage_set.set(new_setvolt)

            print('jump 2 of 4 done, wait 2 sec.')
            time.sleep(2)

            temp_actvolt = dlcpro.laser1.dl.pc.voltage_act.get()
            delta = new_actvolt - temp_actvolt
            new_setvolt = new_setvolt - delta
            dlcpro.laser1.dl.pc.voltage_set.set(new_setvolt)

            print('jump 3 of 4 done, wait 1 sec.')
            time.sleep(1)

            temp_actvolt = dlcpro.laser1.dl.pc.voltage_act.get()
            delta = new_actvolt - temp_actvolt
            new_setvolt = new_setvolt - delta
            dlcpro.laser1.dl.pc.voltage_set.set(new_setvolt)
            print('jump 4 done')

            #print(old_setvolt)
            #76.539430
            #74.309430
            #72.263703

            #71.4
            #74.0
            #76.3
            #78.6
            #80.9
            #83.1

            #print(old_actvolt)
            #delta=old_actvolt-old_setvolt
            #print(delta)
            #new_volt=old_setvolt+2.3+delta
            #new_volt=old_setvolt+0.1

            #print(new_volt)
            #dlcpro.laser1.dl.pc.voltage_set.set(new_volt)
            #print(dlcpro.laser1.dl.lock.state.get())

    if 0:
        with Client(NetworkConnection('192.168.1.205')) as client:
            #client.laser1.dl.pc.set.voltage('80.018000')
            #client.laser1.dl.pc.voltage.set('80.018000')
            #client.exec('laser1.dl.pc.set.voltage "80.018000"')
            client.exec('laser1:dl:lock:close')
            #print(new_volt)
            #dlcpro.laser1.dl.pc.voltage_set.set(new_volt)
            #print(dlcpro.laser1.dl.lock.state.get())

    if 0:
        with Client(NetworkConnection('192.168.1.205')) as client:
            #client.laser1.dl.pc.set.voltage('80.018000')
            #client.laser1.dl.pc.voltage.set('80.018000')
            #client.exec('laser1.dl.pc.set.voltage "80.018000"')
            client.exec('laser1:dl:lock:close')
            #client.exec('laser1:dl:lock:open')


if 0:
    if 0:
        with DLCpro(NetworkConnection('192.168.1.205')) as dlcpro:
            # Retrieve scan, lock raw data from device
            scope_data = extract_float_arrays('xyY',
                                              dlcpro.laser1.scope.data.get())
            raw_lock_candidates = dlcpro.laser1.dl.lock.candidates.get()
            lock_candidates = extract_lock_points('clt', raw_lock_candidates)
            lock_state = extract_lock_state(raw_lock_candidates)

            # Create double y axis plot
            fig, laxis = pyplot.subplots()
            fig.suptitle('DLC pro Scope Output')

            ch1_available = dlcpro.laser1.scope.channel1.signal.get(
            ) != -3  # Signal is 'none'
            ch2_available = dlcpro.laser1.scope.channel2.signal.get() != -3
Esempio n. 13
0
class Contour(Spyrelet):
	requires = {
		'fungen': Keysight_33622A,
		'wm': Bristol_771
	}
	qutag = None
	laser = NetworkConnection('1.1.1.1')

	def configureQutag(self):
		qutagparams = self.qutag_params.widget.get()
		start = qutagparams['Start Channel']
		stop = qutagparams['Stop Channel']
		##True = rising edge, False = falling edge. Final value is threshold voltage
		self.qutag.setSignalConditioning(start,self.qutag.SIGNALCOND_MISC,True,1)
		self.qutag.setSignalConditioning(stop,self.qutag.SIGNALCOND_MISC,True,0.1)
		self.qutag.enableChannels((start,stop))

	def homelaser(self,start):
		current=self.wm.measure_wavelength()
		with Client(self.laser) as client:
			while current<start-0.001 or current>start+0.001:
				setting=client.get('laser1:ctl:wavelength-set', float)
				offset=current-start
				client.set('laser1:ctl:wavelength-set', setting-offset)
				time.sleep(3)
				current=self.wm.measure_wavelength()
				print(current, start)

	def createHistogram(self,stoparray, timebase, bincount, period, index, wls):
		hist = [0]*bincount
		for stoptime in stoparray:
			binNumber = int(stoptime*timebase*bincount/(period))
			if binNumber >= bincount:
				continue
			else:
				hist[binNumber]+=1
		out_name = "D:\\Data\\8.30.2019\\0.1"
		np.savez(os.path.join(out_name,str(index)),hist,wls)
		#np.savez(os.path.join(out_name,str(index+40)),hist,wls)
		print('Data stored under File Name: ' + self.exp_parameters.widget.get()['File Name'] + str(index))


	@Task()
	def startpulse(self, timestep=1e-9):
		self.fungen.output[1] = 'OFF'
		self.fungen.output[2] = 'OFF'
		self.fungen.clear_mem(1)
		self.fungen.clear_mem(2)
		params = self.pulse_parameters.widget.get()

		pre1 = Arbseq_Class('pre1', timestep)
		pre1.delays = [0]
		pre1.heights = [0]
		pre1.widths = [params['pulse width'].magnitude]
		pre1.totaltime = params['pulse width'].magnitude
		pre1.nrepeats = 1000
		pre1.repeatstring = 'repeat'
		pre1.markerstring = 'lowAtStart'
		pre1.markerloc = 0
		pre1.create_sequence()

		pulse = Arbseq_Class('pulse', timestep)
		pulse.delays = [0]
		pulse.heights = [1]
		pulse.widths = [params['pulse width'].magnitude]
		pulse.totaltime = params['pulse width'].magnitude
		pulse.nrepeats = 0
		pulse.repeatstring = 'once'
		pulse.markerstring = 'highAtStartGoLow'
		pulse.markerloc = 0
		pulse.create_sequence()

		post1 = Arbseq_Class('post1', timestep)
		post1.delays = [0]
		post1.heights = [0]
		post1.widths = [params['pulse width'].magnitude]
		post1.totaltime = params['pulse width'].magnitude
		post1.nrepeats = 1000
		post1.repeatstring = 'repeat'
		post1.markerstring = 'lowAtStart'
		post1.markerloc = 0
		post1.create_sequence()

		dc = Arbseq_Class('dc', timestep)
		dc.delays = [0]
		dc.heights = [0]
		dc.widths = [params['pulse width'].magnitude]
		dc.totaltime = params['pulse width'].magnitude
		dc.repeatstring = 'repeat'
		dc.markerstring = 'lowAtStart'
		dc.markerloc = 0
		period = params['period'].magnitude
		width = params['pulse width'].magnitude
		repeats = period/width - 1
		dc.nrepeats = repeats
		dc.create_sequence()

		pre2 = Arbseq_Class('pre2', timestep)
		pre2.delays = [0]
		pre2.heights = [1]
		pre2.widths = [params['pulse width'].magnitude]
		pre2.totaltime = params['pulse width'].magnitude
		pre2.nrepeats = 1000
		pre2.repeatstring = 'repeat'
		pre2.markerstring = 'lowAtStart'
		pre2.markerloc = 0
		pre2.create_sequence()

		pulse2 = Arbseq_Class('pulse2', timestep)
		pulse2.delays = [0]
		pulse2.heights = [1]
		pulse2.widths = [params['pulse width'].magnitude]
		pulse2.totaltime = params['pulse width'].magnitude
		pulse2.nrepeats = 0
		pulse2.repeatstring = 'once'
		pulse2.markerstring = 'highAtStartGoLow'
		pulse2.markerloc = 0
		pulse2.create_sequence()

		post2 = Arbseq_Class('post2', timestep)
		post2.delays = [0]
		post2.heights = [1]
		post2.widths = [params['pulse width'].magnitude]
		post2.totaltime = params['pulse width'].magnitude
		post2.nrepeats = 1000
		post2.repeatstring = 'repeat'
		post2.markerstring = 'lowAtStart'
		post2.markerloc = 0
		post2.create_sequence()

		dc2 = Arbseq_Class('dc2', timestep)
		dc2.delays = [0]
		dc2.heights = [-1]
		dc2.widths = [params['pulse width'].magnitude]
		dc2.totaltime = params['pulse width'].magnitude
		dc2.repeatstring = 'repeat'
		dc2.markerstring = 'lowAtStart'
		dc2.markerloc = 0
		period = params['period'].magnitude
		width = params['pulse width'].magnitude
		repeats = period/width - 1
		dc2.nrepeats = repeats
		dc2.create_sequence()

		self.fungen.send_arb(pulse, 1)
		self.fungen.send_arb(dc, 1)
		self.fungen.send_arb(pulse2, 2)
		self.fungen.send_arb(dc2, 2)
		self.fungen.send_arb(pre1, 1)
		self.fungen.send_arb(pre2, 2)
		self.fungen.send_arb(post1, 1)
		self.fungen.send_arb(post2, 2)

		seq1 = [pre1,pulse,post1,dc]
		seq2 = [pre2,pulse2,post2,dc2]

		self.fungen.create_arbseq('pulsetest', seq1, 1)
		self.fungen.wait()
		self.fungen.voltage[1] = params['pulse height']

		self.fungen.create_arbseq('shutter', seq2, 2)
		self.fungen.wait()
		self.fungen.voltage[2] = 7.1
		self.fungen.sync()

		self.configureQutag()

		expparams = self.exp_parameters.widget.get()
		wlparams = self.wl_parameters.widget.get()
		self.homelaser(wlparams['start'])
		print('Laser Homed!')
		self.fungen.output[2] = 'ON'
		self.fungen.output[1] = 'ON'
		qutagparams = self.qutag_params.widget.get()
		lost = self.qutag.getLastTimestamps(True) # clear Timestamp buffer
		stoptimestamp = 0
		synctimestamp = 0
		bincount = qutagparams['Bin Count']
		timebase = self.qutag.getTimebase()
		start = qutagparams['Start Channel']
		stop = qutagparams['Stop Channel']
		for i in range(expparams['# of points']):
			##Wavemeter measurements
			stoparray = []
			startTime = time.time()
			wls=[]
			lost = self.qutag.getLastTimestamps(True)
			while time.time()-startTime < expparams['Measurement Time'].magnitude:
				lost = self.qutag.getLastTimestamps(True)
				time.sleep(30*period)
				timestamps = self.qutag.getLastTimestamps(True)

				tstamp = timestamps[0] # array of timestamps
				tchannel = timestamps[1] # array of channels
				values = timestamps[2] # number of recorded timestamps
				for k in range(values):
					# output all stop events together with the latest start event
					if tchannel[k] == start:
						synctimestamp = tstamp[k]
					else:
						stoptimestamp = tstamp[k]
						stoparray.append(stoptimestamp)
				wls.append(str(self.wm.measure_wavelength()))
			self.createHistogram(stoparray, timebase, bincount, period,i, wls)
			print(i)
			with Client(self.laser) as client:
				setting=client.get('laser1:ctl:wavelength-set', float)
				client.set('laser1:ctl:wavelength-set', setting-0.002)
				time.sleep(1)

		self.fungen.output[1] = 'OFF'
		self.fungen.output[2] = 'OFF'

	@Task()
	def qutagInit(self):
		print('qutag successfully initialized')
		

	@Element(name='Pulse parameters')
	def pulse_parameters(self):
		params = [
	#    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
		('pulse height', {'type': float, 'default': 3, 'units':'V'}),
		('pulse width', {'type': float, 'default': 500e-9, 'units':'s'}),
		('period', {'type': float, 'default': 0.1, 'units':'s'}),
		]
		w = ParamWidget(params)
		return w

	@Element(name='Wavelength parameters')
	def wl_parameters(self):
		params = [
	#    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
		('start', {'type': float, 'default': 1535.63}),
		('stop', {'type': float, 'default': 1535.43})
		]
		w = ParamWidget(params)
		return w

	@Element(name='Experiment Parameters')
	def exp_parameters(self):
		params = [
	#    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
		('# of points', {'type': int, 'default': 10}),
		('Measurement Time', {'type': int, 'default': 10, 'units':'s'}),
		('File Name', {'type': str})
		]
		w = ParamWidget(params)
		return w

	@Element(name='QuTAG Parameters')
	def qutag_params(self):
		params = [
	#    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
		('Start Channel', {'type': int, 'default': 0}),
		('Stop Channel', {'type': int, 'default': 1}),
		('Bin Count', {'type': int, 'default': 1000})
		]
		w = ParamWidget(params)
		return w

	@startpulse.initializer
	def initialize(self):
		self.wm.start_data()
		self.fungen.output[1] = 'OFF'
		self.fungen.output[2] = 'OFF'
		self.fungen.clear_mem(1)
		self.fungen.clear_mem(2)
		self.fungen.wait()

	@startpulse.finalizer
	def finalize(self):
		self.wm.stop_data()
		self.fungen.output[1] = 'OFF'
		self.fungen.output[2] = 'OFF'
		print('Lifetime measurements complete.')
		return

	@qutagInit.initializer
	def initialize(self):
		from lantz.drivers.qutools import QuTAG
		self.qutag = QuTAG()
		devType = self.qutag.getDeviceType()
		if (devType == self.qutag.DEVTYPE_QUTAG):
			print("found quTAG!")
		else:
			print("no suitable device found - demo mode activated")
		print("Device timebase:" + str(self.qutag.getTimebase()))
		return

	@qutagInit.finalizer
	def finalize(self):
		return
Esempio n. 14
0
class LaserScan(Spyrelet):
    requires = {'wm': Bristol_771}
    conn1 = NetworkConnection('1.1.1.1')
    #conn1 = conn1 = SerialConnection('COM1')
    dlc = Client(conn1)
    daq = nidaqmx.Task()
    daq.ai_channels.add_ai_voltage_chan("Dev1/ai0")

    @Task()
    def scan(self):
        param = self.parameters.widget.get()
        filename = param['Filename']
        F = open(filename + '.dat', 'w')
        f = filename + 'wavelength.dat'
        F2 = open(f, 'w')
        start_wavelength = param['Start'].magnitude * 1e9
        stop_wavelength = param['Stop'].magnitude * 1e9
        speed = param['Speed'].magnitude * 1e9
        n = param['Num Scan']
        self.spec = []
        with Client(self.conn1) as dlc:
            dlc.set("laser1:ctl:scan:wavelength-begin", start_wavelength)
            dlc.set("laser1:ctl:scan:wavelength-end", stop_wavelength)
            dlc.set("laser1:ctl:scan:speed", speed)
            dlc.set("laser1:ctl:scan:microsteps", True)
            dlc.set("laser1:ctl:scan:shaple", 1)  #0=Sawtooth,1=Triangle
            dlc.set("laser1:ctl:scan:trigger:output-enabled", True)
            for x in range(n - 1):
                dlc.set("laser1:ctl:wavelength-set", start_wavelength)
                dlc.set("laser1:ctl:scan:trigger:output-threshold",
                        start_wavelength + 0.1)
                while True:
                    st = dlc.get("io:digital-out2:value-act+0.1")
                    if st == False:
                        break
                dlc.set("laser1:ctl:scan:trigger:output-threshold",
                        stop_wavelength)
                time.sleep(0.5)
                act_start = self.wm.measure_wavelength()
                dlc.exec("laser1:ctl:scan:start")
                daq.start()
                if dlc.get("io:digital-out2:value-act"):
                    dlc.exec("laser1:ctl:scan:pause")
                    data = daq.read(nidaqmx.constants.READ_ALL_AVAILABLE)
                    daq.wait_until_done()
                    self.xs.append(data)
                    daq.stop()
                    act_stop = self.wm.measure_wavelength()
                    print('%d scan: act start = %f, act stop = %f' %
                          (n, act_start, act_stop))
            for i in range(n - 1):
                self.spec = self.spec + 1 / n * self.xs[i, :]
            self.wl = np.linspace(act_start, act_stop, len(self.spec))
            plt.plot(self.wl, self.spec)
            plt.xlable('wavelength/nm')
            plt.ylable('transmission')
            for item in self.spec:
                F.write("%f," % item)
            F.write("\n")
            for item in self.wl:
                F.write("%f," % item)
            return

    @Element(name='Params')
    def parameters(self):
        params = [
            #    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
            ('Start', {
                'type': float,
                'default': 1460 * 1e-9,
                'units': 'm'
            }),
            ('Speed', {
                'type': float,
                'default': 0.5 * 1e-9,
                'units': 'm'
            }),
            ('Stop', {
                'type': float,
                'default': 1570 * 1e-9,
                'units': 'm'
            }),
            ('Num Scan', {
                'type': int,
                'default': 5
            }),
            ('Filename', {
                'type': str,
                'default': 'D:\\Data\\09.06.2019\\wavelengthsweep'
            })

            # ('Amplitude', {'type': float, 'default': 1, 'units':'V'})
        ]
        w = ParamWidget(params)
        return w
Esempio n. 15
0
            return self.set_param('laser1:scan:signal-type', val)


        ##Set Wavelength
        @Feat()
        def set_wavelength(self):
            return self.get_param('laser1:ctl:wavelength-set')

        @set_wavelength.setter
        def set_wavelength(self, val):
            return self.set_param('laser1:ctl:wavelength-set', val)

        # def set_wavelength(self, val):
        #     return self.set_param('laser1:ctl:wavelength-set', val)

        def set_output(self, val):
            return self.set_param('laser1:dl:cc:enabled', val)


class DLCException(Exception):
    pass

if __name__ == '__main__':
    import time
    conn1=NetworkConnection('1.1.1.1')
    with Client(conn1) as client:
        idn=client.get('serial-number',str)
        print(idn)

        wl=client.set('laser1:ctl:wavelength-set', 1535)
        print(wl)
Esempio n. 16
0
class LaserScan(Spyrelet):
    requires = {}

    conn1 = NetworkConnection(
        '1.1.1.2')  # these numbers are set on the laser controller
    dlc = Client(conn1)
    daq = nidaqmx.Task()
    daq.ai_channels.add_ai_voltage_chan(
        "Dev1/ai6")  # change the number here to set which channel

    @Task()
    def scan(self):
        param = self.parameters.widget.get()
        filename = param['Filename']
        F = open(filename + '.dat', 'w')
        f = filename + '\'.dat'
        F2 = open(f, 'w')
        start_wavelength = param[
            'Start'].magnitude * 1e9  # looking at a dictionary of the parameters
        stop_wavelength = param['Stop'].magnitude * 1e9
        step = param['Step'].magnitude * 1e9
        n = param['Num Scan']
        self.wv = np.arange(
            start_wavelength, stop_wavelength, step
        )  # create a vector of points that the wavelength will tune to for the scan
        self.daq.start()  # start collecting data from the DAQ
        with Client(
                self.conn1
        ) as dlc:  # why does this need to be set here when it looks like it is set above?
            for x in range(n):
                xx = [
                ]  # this vector stores the value of the power measurements taken in each scan
                dlc.set("laser1:ctl:wavelength-set", start_wavelength)
                time.sleep(8)  # the wavelength wait time is long because if
                # the laser wavelength is initially set far from this starting point it takes some time to get there
                for item in self.wv:
                    dlc.set("laser1:ctl:wavelength-set", item)
                    time.sleep(
                        0.0001
                    )  # after waiting 100us after setting the wavelength read the power from the DAQ
                    xx.append(self.daq.read())
                time.sleep(1)  # wait 1 second after finishing the scan

                wl = np.linspace(
                    start_wavelength, stop_wavelength, len(xx)
                )  # linearly interpolate between the start and stop wavelengths
                for item in xx:
                    F.write("%f," % item)
                for item in wl:
                    F2.write("%f," % item)
                F.write("\n")
                F2.write("\n")
        self.daq.stop()
        return

    @Element(name='Params')
    def parameters(self):
        params = [
            #    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
            ('Start', {
                'type': float,
                'default': 1460 * 1e-9,
                'units': 'm'
            }),
            ('Step', {
                'type': float,
                'default': 0.01 * 1e-9,
                'units': 'm'
            }),
            ('Stop', {
                'type': float,
                'default': 1570 * 1e-9,
                'units': 'm'
            }),
            ('Num Scan', {
                'type': int,
                'default': 1
            }),
            ('Filename', {
                'type': str,
                'default': 'D:\\Data\\09.06.2019\\wavelengthsweep'
            })

            # ('Amplitude', {'type': float, 'default': 1, 'units':'V'})
        ]
        w = ParamWidget(params)
        return w
Esempio n. 17
0
 def query(self, cmd, type):
     with Client(NetworkConnection(self.COM_port, timeout=5)) as client:
         return client.get(cmd, type)
Esempio n. 18
0
class PLThinFilm(Spyrelet):
    requires = {'wm': Bristol_771}
    qutag = None
    laser = NetworkConnection('1.1.1.1')

    def configureQutag(self):
        qutagparams = self.qutag_params.widget.get()
        start = qutagparams['Start Channel']
        stop = qutagparams['Stop Channel']
        ##True = rising edge, False = falling edge. Final value is threshold voltage
        self.qutag.setSignalConditioning(start, self.qutag.SIGNALCOND_MISC,
                                         True, 1)
        self.qutag.setSignalConditioning(stop, self.qutag.SIGNALCOND_MISC,
                                         True, 0.1)
        self.qutag.enableChannels((start, stop))

    def homelaser(self, start):
        current = self.wm.measure_wavelength()
        with Client(self.laser) as client:
            while current < start - 0.001 or current > start + 0.001:
                setting = client.get('laser1:ctl:wavelength-set', float)
                offset = current - start
                client.set('laser1:ctl:wavelength-set', setting - offset)
                time.sleep(3)
                current = self.wm.measure_wavelength()
                print(current, start)

    def createHistogram(self, stoparray, timebase, bincount, period, index,
                        wls):
        hist = [0] * bincount
        for stoptime in stoparray:
            binNumber = int(stoptime * timebase * bincount / (period))
            if binNumber >= bincount:
                continue
            else:
                hist[binNumber] += 1
        out_name = "D:\\Data\\9.04.2019\\1T"
        np.savez(os.path.join(out_name, str(index + 59)), hist, wls)
        #np.savez(os.path.join(out_name,str(index+40)),hist,wls)
        print('Data stored under File Name: ' +
              self.exp_parameters.widget.get()['File Name'] + str(index))

    @Task()
    def startpulse(self, timestep=100e-9):

        ##Qutag Part
        self.configureQutag()
        expparams = self.exp_parameters.widget.get()
        wlparams = self.wl_parameters.widget.get()
        self.homelaser(wlparams['start'])
        print('Laser Homed!')
        qutagparams = self.qutag_params.widget.get()
        lost = self.qutag.getLastTimestamps(True)  # clear Timestamp buffer
        stoptimestamp = 0
        synctimestamp = 0
        bincount = qutagparams['Bin Count']
        timebase = self.qutag.getTimebase()
        start = qutagparams['Start Channel']
        stop = qutagparams['Stop Channel']
        for i in range(expparams['# of points']):
            ##Wavemeter measurements
            stoparray = []
            startTime = time.time()
            wls = []
            lost = self.qutag.getLastTimestamps(True)
            while time.time(
            ) - startTime < expparams['Measurement Time'].magnitude:
                lost = self.qutag.getLastTimestamps(True)
                time.sleep(5 * 0.1)
                timestamps = self.qutag.getLastTimestamps(True)

                tstamp = timestamps[0]  # array of timestamps
                tchannel = timestamps[1]  # array of channels
                values = timestamps[2]  # number of recorded timestamps
                for k in range(values):
                    # output all stop events together with the latest start event
                    if tchannel[k] == start:
                        synctimestamp = tstamp[k]
                    else:
                        stoptimestamp = tstamp[k]
                        stoparray.append(stoptimestamp)
                wls.append(str(self.wm.measure_wavelength()))
            self.createHistogram(stoparray, timebase, bincount, 0.1, i, wls)
            print(i)
            with Client(self.laser) as client:
                setting = client.get('laser1:ctl:wavelength-set', float)
                client.set('laser1:ctl:wavelength-set', setting - 0.008)
                time.sleep(1)

    @Task()
    def qutagInit(self):
        print('qutag successfully initialized')

    @Element(name='Wavelength parameters')
    def wl_parameters(self):
        params = [
            #    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
            ('start', {
                'type': float,
                'default': 1535.71
            }),
            ('stop', {
                'type': float,
                'default': 1535.50
            })
        ]
        w = ParamWidget(params)
        return w

    @Element(name='Experiment Parameters')
    def exp_parameters(self):
        params = [
            #    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
            ('# of points', {
                'type': int,
                'default': 50
            }),
            ('Measurement Time', {
                'type': int,
                'default': 100,
                'units': 's'
            }),
            ('File Name', {
                'type': str
            })
        ]
        w = ParamWidget(params)
        return w

    @Element(name='QuTAG Parameters')
    def qutag_params(self):
        params = [
            #    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
            ('Start Channel', {
                'type': int,
                'default': 0
            }),
            ('Stop Channel', {
                'type': int,
                'default': 1
            }),
            ('Bin Count', {
                'type': int,
                'default': 1000
            })
        ]
        w = ParamWidget(params)
        return w

    @startpulse.initializer
    def initialize(self):
        self.wm.start_data()

    @startpulse.finalizer
    def finalize(self):
        self.wm.stop_data()
        print('Lifetime measurements complete.')
        return

    @qutagInit.initializer
    def initialize(self):
        from lantz.drivers.qutools import QuTAG
        self.qutag = QuTAG()
        devType = self.qutag.getDeviceType()
        if (devType == self.qutag.DEVTYPE_QUTAG):
            print("found quTAG!")
        else:
            print("no suitable device found - demo mode activated")
        print("Device timebase:" + str(self.qutag.getTimebase()))
        return

    @qutagInit.finalizer
    def finalize(self):
        return
Esempio n. 19
0
class LaserScan(Spyrelet):
    requires = {'wm': Bristol_771}
    conn1 = NetworkConnection('1.1.1.2')

    dlc = Client(conn1)
    daq = nidaqmx.Task()
    daq.ai_channels.add_ai_voltage_chan("Dev1/ai6")

    @Task()
    def scan(self):
        param = self.parameters.widget.get()
        filename = param['Filename']
        F = open(filename + '.dat', 'w')
        f = filename + '\'.dat'
        F2 = open(f, 'w')
        start_wavelength = param['Start'].magnitude * 1e9
        stop_voltage = param['Stop'].magnitude
        step = param['Step'].magnitude
        n = param['Num Scan']
        self.vt = np.arange(0, stop_voltage, step)
        self.daq.start()
        with Client(self.conn1) as dlc:
            dlc.set("laser1:ctl:wavelength-set", start_wavelength)
            time.sleep(10)
            for x in range(n):
                xx = []
                wl = []
                dlc.set("laser1:dl:pc:voltage-set", 0)
                time.sleep(3)
                act_start = self.wm.measure_wavelength()
                for item in self.vt:
                    dlc.set("laser1:dl:pc:voltage-set", item)
                    time.sleep(0.5)
                    xx.append(self.daq.read())
                time.sleep(5)
                act_stop = self.wm.measure_wavelength()
                wl = np.linspace(act_start, act_stop, len(xx))

                for item in xx:
                    F.write("%f," % item)
                for item in wl:
                    F2.write("%f," % item)
                F.write("\n")
                F2.write("\n")
        self.daq.stop()
        return

    @Element(name='Params')
    def parameters(self):
        params = [
            #    ('arbname', {'type': str, 'default': 'arbitrary_name'}),,
            ('Start', {
                'type': float,
                'default': 1499 * 1e-9,
                'units': 'm'
            }),
            ('Step', {
                'type': float,
                'default': 0.01,
                'units': 'V'
            }),
            ('Stop', {
                'type': float,
                'default': 2,
                'units': 'V'
            }),
            ('Num Scan', {
                'type': int,
                'default': 1
            }),
            ('Filename', {
                'type': str,
                'default': 'D:\\Data\\CW_cavity\\09.25\\wavelengthsweep'
            })
            # ('Amplitude', {'type': float, 'default': 1, 'units':'V'})
        ]
        w = ParamWidget(params)
        return w