def freq_sweep_save(self, c, name='untitled'): """Initiate a frequency sweep. The data will be saved to the data vault in the current directory for this context. Note that the default directory in the data vault is the root directory, so you should cd before trying to save. """ dev = self.selectedDevice(c) resp = yield dev.query('SENS:FREQ:STAR?; STOP?') fstar, fstop = [float(f) for f in resp.split(';')] sweeptime, npoints = yield self.startSweep(dev, 'LIN') if sweeptime > 1: sweeptime *= self.sweepFactor(c) yield util.wakeupCall(sweeptime) sparams = yield self.getSweepData(dev, c['meas']) freq = util.linspace(fstar, fstop, npoints) freq = [T.Value(f, 'Hz') for f in freq] for s in sparams: for i, cplx in enumerate(s): s[i] = T.Complex(cplx) f = numpy.array(freq) s = 20 * numpy.log10(abs(numpy.array(sparams))) phases = numpy.angle(numpy.array(sparams)) data = numpy.vstack((f, s, phases)).T data = data.astype('float64') dv = self.client.data_vault power = yield self.power(c) bw = yield self.bandwidth(c) independents = ['frequency [Hz]'] dependents = [(Sij, 'log mag', 'dB') for Sij in c['meas']] + [(Sij, 'phase', 'dB') for Sij in c['meas']] p = dv.packet() p.new(name, independents, dependents) p.add(data) p.add_comment('Autosaved by PNA server.') p.add_parameter('power', power) p.add_parameter('bandwidth', bw) yield p.send(context=c.ID) returnValue(data)
def func(): # build registry packet regs = regAdcRun(self, RUN_MODE_AVERAGE_AUTO, 1, filterFunc, filterStretchLen, filterStretchAt, demods) p = self.makePacket() # create packet for the ethernet server #self.makeFilter(filterFunc, p) # upload filter function, adds a p.write() #self.makeTrigLookups(demods, p) # upload trig lookup tables adds a p.write() p.write(regs.tostring()) # send register packet p.timeout(T.Value(10, 's')) # set a conservative timeout p.read(self.buildParams['AVERAGE_PACKETS']) # read back all packets from average buffer ans = yield p.send() #Send the packet to the direct ethernet server # parse the packets out and return data packets = [data for src, dst, eth, data in ans.read] returnValue(extractAverage(packets))
def func(): # build register packet regs = regAdcRun(self, RUN_MODE_DEMOD_AUTO, 1, filterFunc, filterStretchLen, filterStretchAt, demods) # create packet for the ethernet server p = self.makePacket() self.makeFilter(filterFunc, p) # upload filter function self.makeTrigLookups(demods, p) # upload trig lookup tables, cosine and sine for each demod channel p.write(regs.tostring()) # send registry packet p.timeout(T.Value(10, 's')) # set a conservative timeout p.read(1) # read back one demodulation packet ans = yield p.send() #Send the packet to the direct ethernet server # parse the packets out and return data packets = [data for src, dst, eth, data in ans.read] #list of 48-byte strings returnValue(extractDemod(packets, self.buildParams['DEMOD_CHANNELS_PER_PACKET']))
def power_sweep_phase(self, c): """Initiate a power sweep.""" dev = self.selectedDevice(c) resp = yield dev.query('SOUR:POW:STAR?; STOP?') pstar, pstop = [float(p) for p in resp.split(';')] sweeptime, npoints = yield self.startSweep(dev, 'POW') if sweeptime > 1: sweeptime *= self.sweepFactor(c) yield util.wakeupCall(sweeptime) power = util.linspace(pstar, pstop, npoints) power = [T.Value(p, 'dBm') for p in power] phase = yield self.getSweepDataPhase(dev, c['meas']) returnValue((power, phase))
def func(): # build registry packet regs = self.regRun(self.RUN_MODE_AVERAGE_AUTO, {}, 1) p = self.makePacket("runAverage") p.write(regs.tostring()) p.timeout(T.Value(10, 's')) p.read(self.AVERAGE_PACKETS) ans = yield p.send() # parse the packets out and return data packets = [data for src, dst, eth, data in ans.read] # print "average mode packets:" # for p in packets: # print "len: %d, first 64 byes:" % (len(p),) # print labrad.support.hexdump(p[0:64]) returnValue(self.extractAverage(packets))
def _sendRegisters(self, regs, readback=True, timeout=T.Value(10, 's')): """Send a register packet and optionally readback the result. If readback is True, the result packet is returned as a string of bytes. """ if not isinstance(regs, np.ndarray): regs = np.asarray(regs, dtype='<u1') p = self.makePacket() p.write(regs.tostring()) if readback: p.timeout(timeout) p.read() ans = yield p.send() if readback: src, dst, eth, data = ans.read returnValue(data)
def func(): # build registry packet regs = self.regRun(mode=self.RUN_MODE_AVERAGE_AUTO, reps=1, filterFunc=filterFunc, filterStretchAt=filterStretchAt, filterStretchLen=filterStretchLen, demods=demods) p = self.makePacket() p.write(regs.tostring()) p.timeout(T.Value(10, 's')) p.read(self.AVERAGE_PACKETS) ans = yield p.send() # parse the packets out and return data packets = [data for src, dst, eth, data in ans.read] returnValue(self.extractAverage(packets))
def lookupDeviceName(self, server, channel): """Try to send a *IDN? query to lookup info about a device. Returns the name of the device and the actual response string to the identification query. If the response cannot be parsed or the query fails, the name will be listed as '<unknown>'. """ p = self.client.servers[server].packet() p.address(channel).timeout(T.Value(1, 's')).write('*IDN?').read() print 'Sending *IDN? to', server, channel resp = None try: resp = (yield p.send()).read name = parseIDNResponse(resp) except Exception, e: print 'Error sending *IDN? to', server, channel + ':', e name = UNKNOWN
class TrapServer( SerialDeviceServer ): name = SERVERNAME regKey = 'TrapControl' port = None serNode = getNodeName() timeout = T.Value(TIMEOUT,'s') @inlineCallbacks def initServer( self ): if not self.regKey or not self.serNode: raise SerialDeviceError( 'Must define regKey and serNode attributes' ) port = yield self.getPortFromReg( self.regKey ) self.port = port try: serStr = yield self.findSerial( self.serNode ) self.initSerial( serStr, port, baudrate = BAUDRATE ) except SerialConnectionError, e: self.ser = None if e.code == 0: print 'Could not find serial server for node: %s' % self.serNode print 'Please start correct serial server' elif e.code == 1: print 'Error opening serial connection' print 'Check set up and restart serial server' else: raise # Define the trap electronics parameters self.max_frequency = 500.e6 # Hz self.max_amplitude = 1233. #V self.max_phase = 360. # degrees self.max_hv = 1600. # V self.max_dc = 52.9 # V self.frequency_steps = 2**32-1 self.amplitude_steps = 2**10-1 self.phase_steps = 2**14-1 self.dc_steps = 2**12-1 self.hv_steps = 2**12-1 # Set the state of the rf map self.use_RFMap = False # Set the state of RF self.enable_RF = True # Set the battery charging self.bat_charging = False
def __init__(self, trap_frequency, projection_angle, sideband_order, nmax=5000, ionnumber=1, amumass=40, wavelength=T.Value(729, 'nm')): self.ionnumber = ionnumber self.trap_frequency = trap_frequency['Hz'] self.wavelength = wavelength['m'] self.mass = amumass * U.amu['kg'] self.projection_angle = projection_angle self.sideband_order = sideband_order #0 for carrier, 1 for 1st sideband etc self.n = np.arange(0, nmax + 1) #how many vibrational states to consider self.eta = self.lamb_dicke() / np.sqrt(ionnumber) self.rabi_coupling = self.rabi_coupling()
def initServer(self): self.saveFolder = ['', 'PMT Counts'] self.dataSetName = 'PMT Counts' self.modes = ['Normal', 'Differential'] self.collection_period = T.Value(0.100, 's') self.lastDifferential = {'ON': 0, 'OFF': 0} self.currentMode = 'Normal' self.dv = None self.pulser = None self.collectTimeRange = None self.openDataSet = None self.recordingInterrupted = False self.requestList = [] self.listeners = set() self.recording = LoopingCall(self._record) yield self.connect_data_vault() yield self.connect_pulser() yield self.setupListeners()
def power_range(self, c, ps=None): """Get or set the power range.""" dev = self.selectedDevice(c) dev.write('SENS:SWE:TYPE POW') if ps is None: resp = yield dev.query('SOUR:POW:STAR?; STOP?') ps = tuple(T.Value(float(p), 'dBm') for p in resp.split(';')) else: good_atten = None for attn in [0, 10, 20, 30, 40, 50, 60]: if -attn - 30 <= ps[0] and -attn + 20 >= ps[1]: good_atten = attn break if good_atten is None: raise Exception('Power out of range.') yield dev.write('SOUR:POW:ATT %f; STAR %f; STOP %f' % (good_atten, ps[0]['dBm'], ps[1]['dBm'])) returnValue(ps)
class HighVoltBoxA(SerialDeviceServer): name = SERVERNAME regKey = 'HighVoltA' port = None serNode = 'lattice_control' timeout = T.Value(TIMEOUT, 's') onNewVoltage = Signal(795474, 'signal: new voltage', 'v') @inlineCallbacks def initServer(self): """ Initialize DC Box server Initializes dictionary (dcDict) of relevant device data Initializes queue (queue) for commands to send Initializes serial connection Frees connection for writing @raise SerialDeviceError: (For subclass author) Define regKey and serNode attributes """ self.listeners = set() self.createDict() self.queue = [] if not self.regKey or not self.serNode: raise SerialDeviceError( 'Must define regKey and serNode attributes') port = yield self.getPortFromReg(self.regKey) self.port = port try: serStr = yield self.findSerial(self.serNode) self.initSerial(serStr, port) except SerialConnectionError, e: self.ser = None if e.code == 0: print 'Could not find serial server for node: %s' % self.serNode print 'Please start correct serial server' elif e.code == 1: print 'Error opening serial connection' print 'Check set up and restart serial server' else: raise yield self.populateDict() self.free = True
def connectToGauge(self, ser, G): """Connect to a single gauge.""" port = G['port'] ctx = G['context'] = ser.context() log.msg(' Connecting to %s...' % port) try: res = yield ser.open(port, context=ctx) ready = G['ready'] = res == port except: ready = False if ready: # set up baudrate p = ser.packet(context=ctx)\ .baudrate(9600L)\ .timeout() yield p.send() res = yield ser.read(context=ctx) while res: res = yield ser.read(context=ctx) yield ser.timeout(T.Value(2, 's'), context=ctx) # check units p = ser.packet()\ .write_line('u')\ .read_line(key='units') res = yield p.send(context=ctx) if 'units' in res.settings: G['units'] = res['units'] else: G['ready'] = False # create a packet to read the pressure p = ser.packet(context=ctx)\ .write_line('p')\ .read_line(key='pressure') G['packet'] = p G['server'] = ser if ready: self.gauges.append(G) log.msg(' OK') else: log.msg(' ERROR')
def connect(self, name, group, de, port, board, build): """Establish a connection to the board.""" print 'connecting to ADC board: %s (build #%d)' % (macFor(board), build) self.boardGroup = group self.server = de self.cxn = de._cxn self.ctx = de.context() self.port = port self.board = board self.build = build self.MAC = macFor(board) self.devName = name self.serverName = de._labrad_name self.timeout = T.Value(1, 's') # set up our context with the ethernet server p = self.makePacket() p.connect(port) #p.require_length(70) # ADC boards send packets with different lengths: # - register readback: 46 bytes # - demodulator output: 48 bytes # - average readout: 1024 bytes p.destination_mac(self.MAC) p.require_source_mac(self.MAC) #p.source_mac(self.boardGroup.sourceMac) p.timeout(self.timeout) p.listen() yield p.send() #Get build specific information about this device #We talk to the labrad system using a new context and close it when done reg = self.cxn.registry ctxt = reg.context() p = reg.packet() p.cd(['','Servers','GHz FPGAs']) p.get('adcBuild'+str(self.build)) try: hardwareParams = yield p.send() hardwareParams = hardwareParams['get'] parseBuildParameters(hardwareParams, self) finally: yield self.cxn.manager.expire_context(reg.ID, context=ctxt)
def lamb_dicke(self, trap_frequency, projection_angle, laser_wavelength=T.Value(729, 'nm'), amumass=40): '''computes the lamb dicke parameter @var theta: angle between the laser and the mode of motion. 90 degrees is perpendicular @var laser_wavelength: laser wavelength @var trap_frequency: trap frequency @amumass particle mass in amu ''' theta = projection_angle frequency = trap_frequency mass = amumass * U.amu k = 2. * np.pi / laser_wavelength eta = k * (U.hbar / (2 * mass * 2 * np.pi * frequency))**.5 * np.abs( np.cos(theta * 2. * np.pi / 360.0)) eta = eta.inBaseUnits() return eta
def connect(self, name, group, de, port, board, build): """Establish a connection to the board.""" print 'connecting to DAC board: %s (build #%d)' % (macFor(board), build) self.boardGroup = group self.server = de self.cxn = de._cxn self.ctx = de.context() self.port = port self.board = board self.build = build self.MAC = macFor(board) self.devName = name self.serverName = de._labrad_name self.timeout = T.Value(1, 's') # set up our context with the ethernet server # This context is expired when the device shuts down p = self.makePacket() p.connect(port) p.require_length(READBACK_LEN) p.destination_mac(self.MAC) p.require_source_mac(self.MAC) p.timeout(self.timeout) p.listen() yield p.send() #Get build specific information about this device #We talk to the labrad system using a new context and close it when done reg = self.cxn.registry ctxt = reg.context() p = reg.packet() p.cd(['','Servers','GHz FPGAs']) p.get('dacBuild'+str(self.build),key='buildParams') p.get('dac'+self.devName.split(' ')[-1],key='boardParams') try: resp = yield p.send() buildParams = resp['buildParams'] boardParams = resp['boardParams'] parseBuildParameters(buildParams, self) parseBoardParameters(boardParams, self) finally: yield self.cxn.manager.expire_context(reg.ID, context=ctxt)
def connect(self, gpib, addr): """Connect to this device. We set the address and timeout in the context reserved for talking to this device. Then call initialize, which may be overridden in subclasses. """ self.gpib = gpib # wrapper for the gpib server self.addr = addr self._context = gpib.context() # create a new context for this device self._timeout = T.Value(C.TIMEOUT, 's') # set the address and timeout in this context p = self._packet() p.address(self.addr) p.timeout(self._timeout) yield p.send() # do device-specific initialization yield self.initialize()
def power_sweep(self, c): """Initiate a power sweep.""" dev = self.selectedDevice(c) resp = yield dev.query('SOUR:POW:STAR?; STOP?') pstar, pstop = [float(p) for p in resp.split(';')] sweeptime, npoints = yield self.startSweep(dev, 'POW') if sweeptime > 1: sweeptime *= self.sweepFactor(c) yield util.wakeupCall(sweeptime) sparams = yield self.getSweepData(dev, c['meas']) power = util.linspace(pstar, pstop, npoints) power = [T.Value(p, 'dBm') for p in power] for s in sparams: for i, c in enumerate(s): s[i] = T.Complex(c) returnValue((power, sparams))
def func(): # build register packet regs = self.regRun(self.RUN_MODE_DEMOD_AUTO, info, 1) # create packet for the ethernet server p = self.makePacket("runDemod packet") self.makeTriggerTable(triggerTable, p) self.makeMixerTable(demods, p) p.write(regs.tostring()) # send registry packet p.timeout(T.Value(10, 's')) # set a conservative timeout totalReadouts = np.sum([row[0] * row[3] for row in triggerTable]) nPackets = int(np.ceil(totalReadouts / 11.0)) # print "Trying to read back %d packets with %d readouts" % (nPackets, totalReadouts) p.read(nPackets) logging.debug("about to send ADC packet in runDemod") ans = yield p.send() #Send the packet to the direct ethernet # server parse the packets out and return data. packets is a list # of 48-byte strings packets = [data for src, dst, eth, data in ans.read] returnValue(self.extractDemod(packets, triggerTable, mode))
def get_trace(self, c, trace=1): """Returns the y-values of the current trace from the sampling scope. First element: offset time Second element: time step Third to last element: trace """ dev = self.selectedDevice(c) if trace < 1 or trace > 3: raise NotConnectedError() yield dev.write('COND TYP:AVG') while True: if int((yield dev.query('COND? REMA'))[18:]) == 0: break yield util.wakeupCall(2) resp = yield dev.query(__QUERY__ % trace, bytes=20000L) ofs, incr, vals = _parseBinaryData(resp) returnValue([T.Value(v, 'V') for v in np.hstack(([ofs, incr], vals))])
def testCompoundPacket(self): pts = self._get_tester() self.assertTrue(hasattr(pts, 'packet')) # make a simple packet and check the various methods of getting # data out of it pkt = pts.packet() resp = pkt.echo(1).echo(2).settings['echo'](3).send() self.assertTrue(hasattr(resp, 'echo')) self.assertEqual(len(resp.echo), 3) self.assertTrue('echo' in resp.settings) self.assertEqual(len(resp.settings['echo']), 3) self.assertEqual(len(resp['echo']), 3) # test using keys to refer to parts of a packet pkt2 = pts.packet() resp = pkt2.echo(1, key='one')\ .echo_delay(T.Value(0.1, 's'))\ .delayed_echo('blah', key='two')\ .send() self.assertTrue(hasattr(resp, 'one')) self.assertTrue('one' in resp.settings) self.assertEqual(resp['one'], 1) self.assertFalse(hasattr(resp, 'echo_word')) self.assertEqual(resp.two, 'blah') # test packet mutation by key pkt2['two'] = TEST_STR resp = pkt2.send() self.assertEqual(resp.two, TEST_STR) # send packet asynchronously resp = pkt2.send_future() resp = resp.result() self.assertEqual(resp.two, TEST_STR) # allow sending with wait=False for backwards compatibility resp = pkt2.send(wait=False) resp = resp.result() self.assertEqual(resp.two, TEST_STR)
def getFloatSetting(self, c, setting): self.tn.read_very_eager() # Clear the buffer reListBefore = [ setting + " = " ] # A list of regular expressions. In our case, this is trivially a list with 1 string self.tn.write("(param-disp 'laser1:ctl) \r\n") time.sleep( 0.3 ) # Wait for the laser to be able to respond (otherwise we just see an emtpy string) self.tn.expect( reListBefore, 1 ) # Wait up to 1 second to receive a message containing a string in reList. Stop reading once you hit it reListAfter = ['\n'] valStrArr = self.tn.expect(reListAfter, 1) valStr = valStrArr[2] # print(valStr) valFloat = float( valStr[0:-1] ) # Last two characters are "\r\n". But, for some reason, int values need to go back 3 characters val = T.Value(valFloat, self.unitDict[setting]) return val
def runSequence(self, slave, delay, reps, getTimingData=True): server, ctx = self.server, self.ctx pkt = [1, 3] + [0]*54 #pkt[13:15] = reps & 0xFF, (reps >> 8) & 0xFF #pkt[43:45] = int(slave), int(delay) r = yield self.sendRegistersNoReadback(pkt) if not getTimingData: returnValue(r) # TODO: handle multiple timers per cycle npackets = reps/30 totalTime = 2 * (self.seqTime * reps + 1) p = server.packet() p.timeout(T.Value(totalTime * 1000, 'ms')) p.read(npackets) ans = yield p.send(context=ctx) sdata = [ord(data[j*2+3]) + (ord(data[j*2+4]) << 8) for j in range(30) for src, dst, eth, data in ans.read] returnValue(sdata)
def command(self, c, cmd, timeout=T.Value(60, 's')): """Send command to selected controller""" if 'ctrl' not in c: raise Exception('No controller selected') p = c['ctrl']['server'].packet(context=c['ctrl']['context'])\ .timeout(timeout)\ .write('%s\r' % cmd)\ .read_line(key='echo')\ .read_line(key='status') res = yield p.send() status = res['status'] ans = [res['echo'][len(cmd) + 1:]] empties = 5 while ('ok' not in status) and ('? MSG #' not in status): ans.append(status) status = yield c['ctrl']['server'].read_line( context=c['ctrl']['context']) if status == '': empties -= 1 if empties == 0: raise Exception('Invalid response!') returnValue((ans, status))
def testServer(self): pts = self._get_tester() # make sure we can access the setting by both allowed methods self.assert_(hasattr(pts, 'echo')) self.assert_('echo' in pts.settings) # single setting, named explicitly resp = pts.echo(TEST_STR) self.assertEquals(resp, TEST_STR) resp = pts.echo(T.Value(15.0, 's')) self.assertEquals(float(resp), 15.0) self.assertEquals(resp.unit.name, 's') # single setting with the name looked up resp = pts.settings['echo']([1,2,3,4]) self.assertEquals(len(resp), 4) # single setting with delayed response resp = pts.echo(TEST_STR, wait=False) resp = resp.wait() self.assertEquals(resp, TEST_STR)
def sequence(self): self.end = T.Value(10, 'us') self.addSequence(turn_off_all) self.addSequence(doppler_cooling_after_repump_d) if self.p.optical_pumping_enable: self.addSequence(optical_pumping) print self.p.toDict() self.dds_pulses.append( ('729DP', self.end, self.p.preparation_pulse_duration_729, self.p.rabi_excitation_frequency, self.p.rabi_excitation_amplitude)) self.end += self.p.preparation_pulse_duration_729 pulses = self.dds_pulses dur = self.p.dephasing_duration_729 print self.p.dephasing_amplitude_729 print self.end pulses.append( ('729DP', self.end + self.p.pulse_gap / 2.0 - dur / 2.0, dur, self.p.dephasing_frequency_729, self.p.dephasing_amplitude_729)) self.end += self.p.pulse_gap print self.end self.addSequence(rabi_excitation) self.addSequence(state_readout)
def func(): # build register packet regs = self.regRun(mode=self.RUN_MODE_DEMOD_AUTO, reps=1, filterFunc=filterFunc, filterStretchAt=filterStretchAt, filterStretchLen=filterStretchLen, demods=demods) # create packet for the ethernet server p = self.makePacket() self.makeFilter(filterFunc, p) # upload filter function # upload trig lookup tables, cosine and sine for each demod # channel self.makeTrigLookups(demods, p) p.write(regs.tostring()) # send registry packet p.timeout(T.Value(10, 's')) # set a conservative timeout p.read(1) # read back one demodulation packet ans = yield p.send() #Send the packet to the direct ethernet # server parse the packets out and return data. packets is a list # of 48-byte strings packets = [data for src, dst, eth, data in ans.read] returnValue( self.extractDemod(packets, self.DEMOD_CHANNELS_PER_PACKET))
class PS(SerialDeviceServer): name = 'Advantest Server' serNode = 'cctmain' onNewUpdate = Signal(SIGNALID, 'signal: settings updated', '(sv)') port = '/dev/ttyUSB0' timeout = T.Value(.01, 's') @inlineCallbacks def initServer(self): port = self.port try: serStr = yield self.findSerial(self.serNode) self.initSerial(serStr, port) except SerialConnectionError, e: self.ser = None if e.code == 0: print 'Could not find serial server for node: %s' % self.serNode print 'Please start correct serial server' elif e.code == 1: print 'Error opening serial connection' print 'Check set up and restart serial server' else: raise yield self.ser.write('++addr1\r\n')
def run(self, cxn, context): threshold = int(self.parameters.StateReadout.state_readout_threshold) repetitions = int(self.parameters.StateReadout.repeat_each_measurement) pulse_sequence = self.pulse_sequence(self.parameters) pulse_sequence.programSequence(self.pulser) if self.parameters['Excitation_729.lock_excitation_phase']: t_lock = self.parameters['Excitation_729.phase_delay'] period = 1e6 / 60.0 # 60 Hz period in us diff = (t_lock['us'] - pulse_sequence.start_excitation_729['us']) offset = T.Value(diff % period, 'us') self.pulser.line_trigger_state(True) self.pulser.line_trigger_duration(offset) self.pulser.start_number(repetitions) self.pulser.wait_sequence_done() self.pulser.stop_sequence() readouts = self.pulser.get_readout_counts().asarray if len(readouts): perc_excited = numpy.count_nonzero(readouts <= threshold) / float( len(readouts)) else: #got no readouts perc_excited = -1.0 self.save_data(readouts) return perc_excited