コード例 #1
0
class Driver(BaseDriver):
    support_models = ['E8257D', 'SMF100A', 'SMB100A', 'SGS100A']

    quants = [
        QReal('Frequency',
              unit='Hz',
              set_cmd=':FREQ %(value).13e%(unit)s',
              get_cmd=':FREQ?'),
        QReal('Power',
              unit='dBm',
              set_cmd=':POWER %(value).8e%(unit)s',
              get_cmd=':POWER?'),
        QOption('Output',
                set_cmd=':OUTP %(option)s',
                get_cmd=':OUTP?',
                options=[('OFF', 'OFF'), ('ON', 'ON')]),
        QOption('Moutput',
                set_cmd='PULM:STAT %(option)s',
                get_cmd='PULM:STAT?',
                options=[('OFF', 'OFF'), ('ON', 'ON')]),
        QOption('Mform',
                set_cmd='PULM:SOUR %(option)s',
                get_cmd='PULM:SOUR?',
                options=[('EXT', 'EXT'), ('INT', 'INT')]),
    ]
コード例 #2
0
class Driver(BaseDriver):
    error_command = ':SYST:ERR?'
    surport_models = ['HP81110A']

    quants = [

        QReal('Pulse Delay',ch=1,unit='s',set_cmd=':PULS:DEL%(ch)d %(value).9e%(unit)s',get_cmd=':PULS:DEL%(ch)d?'),
        QReal('Pulse Width',ch=1,unit='s',set_cmd=':PULS:WIDT%(ch)d %(value).9e%(unit)s',get_cmd=':PULS:WIDT%(ch)d?'),
        QReal('Pulse Period',ch=1,unit='s',set_cmd=':PULS:PER%(ch)d %(value).9e%(unit)s',get_cmd=':PULS:PER%(ch)d?'),

        #BURST mod, 2 chanels ,then use pulse delay/width/period to modify parameters
        QReal('Burst Ncycles',value=2, set_cmd=':TRIG:COUN %(value)d; :TRIG:SOUR INT; :DIG:PATT OFF',get_cmd=':TRIG:COUN?'),

        #double pulse mode,could use burst mode together, but can't change trigger delay
        #
        QReal('Double Pulse Delay',ch=1,unit='s',set_cmd=':PULS:DOUB%(ch)d:DEL %(value).9e%(unit)s',get_cmd=':PULS:DOUB%(ch)d:DEL?'),
        QOption('Double Pulse',ch=1, set_cmd=':PULS:DOUB%(ch)d %(option)s', get_cmd=':PULS:DOUB%(ch)d?',
                options=[('ON', 'ON'),('OFF', 'OFF'),('1','1'),('0','0')]),

        QReal('High Level',ch=1,unit='V',set_cmd=':VOLT%(ch)d:HIGH %(value).9e%(unit)s',get_cmd=':VOLT%(ch)d:HIGH?'),
        QReal('Low Level',ch=1,unit='V',set_cmd=':VOLT%(ch)d:LOW %(value).9e%(unit)s',get_cmd=':VOLT%(ch)d:LOW?'),
        QReal('Offset',ch=1,unit='V',set_cmd=':VOLT%(ch)d:OFF %(value).9e%(unit)s',get_cmd=':VOLT%(ch)d:OFF?'),
        QReal('Amplitude',ch=1,unit='V',set_cmd=':VOLT%(ch)d:AMP %(value).9e%(unit)s',get_cmd=':VOLT%(ch)d:AMP?'),

        QReal('Trigger Level',ch=1,unit='V',set_cmd=':ARM:LEV %(value).9e%(unit)s',get_cmd=':ARM:LEV?'),
        QReal('Trigger Period',ch=1,unit='s',set_cmd=':ARM:PER %(value).9e%(unit)s',get_cmd=':ARM:PER?'),

        QOption('Output',ch=1, set_cmd=':OUTP%(ch)d %(option)s', get_cmd=':OUTP%(ch)d?',
                options=[('ON', '1'),('OFF', '0')]),
    ]
コード例 #3
0
class Driver(BaseDriver):
    error_command = '*ESR?'
    support_models = ['AFG3102']



    quants = [
        QOption('Output',ch=1,
        set_cmd='OUTP%(ch)d %(option)s', get_cmd='OUTP%(ch)d?'
        options=[('OFF', 'OFF'), ('ON', 'ON')]),  # must set chanel

        QOption('Function',ch=1,set_cmd='SOUR%(ch)d:FUNC %(option)s',get_cmd='SOUR%(ch)d:FUNC?',
            options=[('Sin','SIN'),('Square','SQU'),('Pulse','PULS'),('Ramp','RAMP'),
                ('PRNoise','PRN'),('DC','DC'),('SINC','SINC'),('Gaussian','GAUS'),
                ('Lorentz','LOR'),('Erise','ERIS'),('Edecay','EDEC'),('Haversine','HAV'),
                ('User','USER'),('User2','USER2')]),

        QReal('Frequency',unit='Hz',ch=1,set_cmd='SOUR%(ch)d:FREQ %(value)e%(unit)s',get_cmd='SOUR%(ch)d:FREQ?'),
        QReal('Phase',unit='rad',ch=1,set_cmd='SOUR%(ch)d:PHAS %(value)f%(unit)s',get_cmd='SOUR%(ch)d:PHAS?'),
        QReal('Pulse Delay',unit='s',ch=1,set_cmd='SOUR%(ch)d:PULS:DEL %(value).9e%(unit)s',get_cmd='SOUR%(ch)d:PULS:DEL?'),
        QReal('Pulse Period',unit='s',ch=1,set_cmd='SOUR%(ch)d:PULS:PER %(value).9e%(unit)s',get_cmd='SOUR%(ch)d:PULS:PER?'),
        QReal('Pulse Width',unit='s',ch=1,set_cmd='SOUR%(ch)d:PULS:WIDT %(value).9e%(unit)s',get_cmd='SOUR%(ch)d:PULS:WIDT?'),
        #Burst Mode
        QReal('Burst Tdelay',unit='s',ch=1,set_cmd='SOUR%(ch)d:BURS:TDEL %(value).9e%(unit)s',get_cmd='SOUR%(ch)d:BURS:TDEL?'),
        QReal('Burst Ncycles',ch=1,set_cmd='SOUR%(ch)d:BURS:NCYC %(value)d',get_cmd='SOUR%(ch)d:BURS:NCYC?'),
        ##
        QReal('Frequency',unit='Hz',ch=1,set_cmd='SOUR%(ch)d:FREQ %(value)e%(unit)s',get_cmd='SOUR%(ch)d:FREQ?'),
        QReal('Phase',unit='DEG',ch=1,set_cmd='SOUR%(ch)d:PHAS %(value)f%(unit)s',get_cmd='SOUR%(ch)d:PHAS?'),
        QReal('High Level',unit='V',ch=1,set_cmd='SOUR%(ch)d:VOLT:HIGH %(value)f%(unit)s',get_cmd='SOUR%(ch)d:VOLT:HIGH?'),
        QReal('Low Level',unit='V',ch=1,set_cmd='SOUR%(ch)d:VOLT:LOW %(value)f%(unit)s',get_cmd='SOUR%(ch)d:VOLT:LOW?'),
        QReal('Offset',unit='V',ch=1,set_cmd='SOUR%(ch)d:VOLT:OFFS %(value)f%(unit)s',get_cmd='SOUR%(ch)d:VOLT:OFFS?'),
        QReal('Amplitude',unit='VPP',ch=1,set_cmd='SOUR%(ch)d:VOLT:AMPL %(value)f%(unit)s',get_cmd='SOUR%(ch)d:VOLT:AMPL?'),
    ]
コード例 #4
0
class Driver(BaseDriver):
    support_models = ['DG1062Z']

    quants = [
        # Set the waveform offset voltage of the specified channel.
        # Query the waveform offset voltage of the specified channel.
        # QReal('Voltage_Offset', unit='VDC',
        #   set_cmd=':SOUR1:VOLT:OFFS %(value).8e%(unit)s',
        #   get_cmd=':SOUR1:VOLT:OFFS?'),

        # Set the waveform of the specified channel to DC with the specified offset.
        QReal('Offset',
              unit='V',
              ch=1,
              set_cmd=':SOUR%(ch)d:APPL:DC 1,1, %(value).8e%(unit)s',
              get_cmd=':VOLT?'),

        # QOption('Output',
        #   set_cmd=':OUTP %(option)s', options=[('OFF', 'OFF'), ('ON', 'ON')]),
        QOption('Output',
                ch=1,
                set_cmd='OUTP%(ch)d %(option)s',
                get_cmd='OUTP%(ch)d?',
                options=[('OFF', 'OFF'), ('ON', 'ON')]),  # must set chanel
    ]
コード例 #5
0
ファイル: DP832.py プロジェクト: ParanoiaSYT/Qulab-backup
class Driver(BaseDriver):
    support_models = ['DP832']

    quants = [
        QOption('Output', value='ON',ch=1,
            set_cmd=':OUTP CH%(ch)d,%(option)s', options=[('OFF', 'OFF'), ('ON', 'ON')]),
        QReal('Offset', unit='V', ch=1,
          set_cmd='SOUR%(ch)d:VOLT %(value)f',
          get_cmd='SOUR%(ch)d:VOLT?'),
    ]
コード例 #6
0
ファイル: SRS_SIM.py プロジェクト: ParanoiaSYT/Qulab-backup
class Driver(BaseDriver):

	support_models = ['SIM900']
	'''SRS SIM900 seris DC voltage source'''
	quants = [
		QReal('Offset', value=0, unit='V', ch=1,
			set_cmd='SNDT %(ch)d,"VOLT %(value).2f"',
			get_cmd='SNDT %(ch)d,"VOLT?"'),

		QOption('Output', ch=1,
			set_cmd='SNDT %(ch)d,"%(option)s"',
			get_cmd='SNDT %(ch)d,"EXON?"',
			options=[('OFF', 'OPOF'), ('ON', 'OPON')]),
	]
コード例 #7
0
ファイル: E4407B.py プロジェクト: ParanoiaSYT/Qulab-backup
class Driver(BaseDriver):
    error_command = ':SYST:ERR?'
    support_models = ['E4407B']

    quants = [
        #         QOption('Sweep', value='ON',
        #             set_cmd='INIT:CONT %(option)s', options=[('OFF', 'OFF'), ('ON', 'ON')]),
        #         QOption('Trace Mode', value='WRIT',ch=1,
        #             set_cmd='TRAC%(ch)d:MODE %(option)s',get_cmd='TRAC%(ch)d:MODE?',
        #             options=[('Write', 'WRIT'), ('Maxhold', 'MAXH'),('Minhold','MINH'),
        #             ('View','VIEW'),('Blank','BLAN'),('Videoavg','VID'),('Poweravg','POW')]),
        QOption('Marker',
                value='ON',
                set_cmd=':CALCulate:MARKer1:STATe %(option)s',
                options=[('OFF', 'OFF'), ('ON', 'ON')]),
        QString('Marker_center',
                set_cmd=':CALCulate:MARKer1:CENTer %(value)s',
                get_cmd=':CALCulate:MARKer1:X?'),
        QString('Marker_amp',
                set_cmd=':CALCulate:MARKer1:Y %(value)s',
                get_cmd=':CALCulate:MARKer1:Y?'),
        QReal('Marker_right',
              set_cmd=' :CALCulate:MARKer1:MAXimum:RIGHt %(value)s',
              get_cmd=':CALCulate:MARKer1:X?'),
        # QReal('Marker_center', unit='Hz', set_cmd=':CALCulate:MARKer1:X %(value)e', get_cmd=':CALCulate:MARKer1:X?'),
        QReal('Frequency_center',
              unit='Hz',
              set_cmd=':SENSe:FREQuency:Center %(value)e%(unit)s',
              get_cmd=':SENSe:FREQuency:Center?'),
        QReal('sweep_span',
              unit='Hz',
              set_cmd=':SENSe:FREQuency:SPAN %(value)e%(unit)s',
              get_cmd=':SENSe:FREQuency:SPAN?'),
        QInteger('sweep_point',
                 set_cmd=':SENSe:SWEep:POINts %(value)d',
                 get_cmd=':SENSe:SWEep:POINts?'),
        QInteger('repeats_Average',
                 set_cmd=':SENSe:AVERage:COUNt %(value)d',
                 get_cmd=':SENSe:AVERage:COUNt?'),

        # QReal('Frequency Start', unit='Hz', set_cmd='SENS:FREQ:STAR %(value)e%(unit)s', get_cmd='SENS:FREQ:STAR?'),

        #     QReal('Frequency Stop', unit='Hz', set_cmd='SENS:FREQ:STOP %(value)e%(unit)s', get_cmd='SENS:FREQ:STOP?'),
        #     QInteger('Sweep Points',value=601, set_cmd=':SWE:POIN %(value)d',get_cmd=':SWE:POIN?')
    ]
コード例 #8
0
class Driver(BaseDriver):

    support_models = ['DP832']
    '''Rigol DP800 series DC source'''

    quants = [
        QReal('Offset',
              value=0,
              unit='V',
              ch=1,
              set_cmd=':SOUR%(ch)d:VOLT %(value).2f',
              get_cmd=':SOUR%(ch)d:VOLT?'),
        QOption('Output',
                ch=1,
                set_cmd=':OUTP CH%(ch)d,%(option)s',
                get_cmd=':OUTP? CH%(ch)d',
                options=[('OFF', 'OFF'), ('ON', 'ON')]),
    ]
コード例 #9
0
class Driver(BaseDriver):
    support_models = ['E8363B', 'E8363C', 'E5071C', 'ZNB20-2Port', 'N5232A']

    quants = [
        QReal('Power',
              value=-20,
              unit='dBm',
              set_cmd='SOUR:POW %(value)e%(unit)s',
              get_cmd='SOUR:POW?'),
        QReal('Frequency center',
              value=5e9,
              unit='Hz',
              set_cmd='SENS:FREQ:CENT %(value)e%(unit)s',
              get_cmd='SENS:FREQ:CENT?'),
        QReal('Frequency span',
              value=2e9,
              unit='Hz',
              set_cmd='SENS:FREQ:SPAN %(value)e%(unit)s',
              get_cmd='SENS:FREQ:SPAN?'),
        QReal('Frequency start',
              value=4e9,
              unit='Hz',
              set_cmd='SENS:FREQ:STAR %(value)e%(unit)s',
              get_cmd='SENS:FREQ:STAR?'),
        QReal('Frequency stop',
              value=6e9,
              unit='Hz',
              set_cmd='SENS:FREQ:STOP %(value)e%(unit)s',
              get_cmd='SENS:FREQ:STOP?'),
        QVector('Frequency', unit='Hz'),
        QVector('Trace'),
        QVector('S'),
        QOption('Sweep',
                value='ON',
                set_cmd='INIT:CONT %(option)s',
                options=[('OFF', 'OFF'), ('ON', 'ON')]),
        QInteger('Number of points',
                 value=201,
                 unit='',
                 set_cmd='SENS:SWE:POIN %(value)d',
                 get_cmd='SENS:SWE:POIN?'),
        QOption('Format',
                value='MLOG',
                set_cmd='CALC:FORM %(option)s',
                get_cmd='CALC:FORM?',
                options=[('Mlinear', 'MLIN'), ('Mlog', 'MLOG'),
                         ('Phase', 'PHAS'), ('Unwrapped phase', 'UPH'),
                         ('Imag', 'IMAG'), ('Real', 'REAL'), ('Polar', 'POL'),
                         ('Smith', 'SMIT'), ('SWR', 'SWR'),
                         ('Group Delay', 'GDEL')]),
        QOption('SweepType',
                value='',
                set_cmd='SENS:SWE:TYPE %(option)s',
                get_cmd='SENS:SWE:TYPE?',
                options=[('Linear', 'LIN'), ('Log', 'LOG'), ('Power', 'POW'),
                         ('CW', 'CW'), ('Segment', 'SEGM'), ('Phase', 'PHAS')])
    ]
    '''
    def performSetValue(self, quant, value, **kw):
        if quant.name == 'Power':
            self.setValue('Power:Start', value)
            self.setValue('Power:Center', value)
            self.setValue('Power:Stop', value)
        else:
            super(Driver, self).performSetValue(quant, value, **kw)
    '''
    def performGetValue(self, quant, **kw):
        get_vector_methods = {
            'Frequency': self.get_Frequency,
            'Trace': self.get_Trace,
            'S': self.get_S,
        }
        if quant.name in get_vector_methods.keys():
            return get_vector_methods[quant.name](ch=kw.get('ch', 1))
        else:
            return super(Driver, self).performGetValue(quant, **kw)

    def get_Trace(self, ch=1):
        '''Get trace'''
        return self.get_S(ch, formated=True)

    def get_S(self, ch=1, formated=False):
        '''Get the complex value of S paramenter or formated data'''
        #Select the measurement
        self.pna_select(ch)

        #Stop the sweep
        self.setValue('Sweep', 'OFF')
        #Begin a measurement
        self.write('INIT:IMM')
        self.write('*WAI')
        #Get the data
        self.write('FORMAT:BORD NORM')
        if self.model in ['E5071C']:
            self.write(':FORM:DATA ASC')
            cmd = ("CALC%d:DATA:FDATA?" %
                   ch) if formated else ("CALC%d:DATA:SDATA?" % ch)
        else:
            self.write('FORMAT ASCII')
            cmd = ("CALC%d:DATA? FDATA" %
                   ch) if formated else ("CALC%d:DATA? SDATA" % ch)
        data = np.asarray(self.query_ascii_values(cmd))
        if formated:
            if self.model in ['E5071C']:
                data = data[::2]
        else:
            data = data[::2] + 1j * data[1::2]
        #Start the sweep
        self.setValue('Sweep', 'ON')
        return data

    def pna_select(self, ch=1):
        '''Select the measurement'''
        if self.model in ['E5071C']:
            return
        if self.model in ['E8363C', 'E8363B', 'N5232A']:
            quote = '" '
        elif self.model in ['ZNB20-2Port']:
            quote = "' "
        msg = self.query('CALC%d:PAR:CAT?' % ch).strip(quote)
        measname = msg.split(',')[0]
        self.write('CALC%d:PAR:SEL "%s"' % (ch, measname))

    def get_Frequency(self, ch=1):
        """Return the frequency of pna measurement"""

        #Select the measurement
        self.pna_select(ch)
        if self.model == 'E8363C':
            cmd = 'CALC:X?'
            return np.asarray(self.query_ascii_values(cmd))
        if self.model in ['E8363B', 'N5232A']:
            freq_star = self.getValue('Frequency start')
            freq_stop = self.getValue('Frequency stop')
            num_of_point = self.getValue('Number of points')
            return np.array(np.linspace(freq_star, freq_stop, num_of_point))
        elif self.model in ['ZNB20-2Port']:
            cmd = 'CALC:DATA:STIM?'
            return np.asarray(self.query_ascii_values(cmd))

    def set_segments(self, segments=[], form='Start Stop'):
        self.write('SENS:SEGM:DEL:ALL')
        if form == 'Start Stop':
            cmd = ['SENS:SEGM:LIST SSTOP,%d' % len(segments)]
            for kw in segments:
                data = '1,%(num)d,%(start)g,%(stop)g,%(IFBW)g,0,%(power)g' % kw
                cmd.append(data)
        else:
            cmd = ['SENS:SEGM:LIST CSPAN,%d' % len(segments)]
            for kw in segments:
                data = '1,%(num)d,%(center)g,%(span)g,%(IFBW)g,0,%(power)g' % kw
                cmd.append(data)
        self.write('FORMAT ASCII')
        self.write(','.join(cmd))
コード例 #10
0
class Driver(BaseDriver):
    support_models = ['AWG5014C', 'AWG5208']

    quants = [
        QReal('Sample Rate',
              unit='S/s',
              set_cmd='SOUR:FREQ %(value)f',
              get_cmd='SOUR:FREQ?'),
        QOption('Run Mode',
                set_cmd='AWGC:RMOD %(option)s',
                get_cmd='AWGC:RMOD?',
                options=[('Continuous', 'CONT'), ('Triggered', 'TRIG'),
                         ('Gated', 'GAT'), ('Sequence', 'SEQ')]),
        QOption('Clock Source',
                set_cmd='AWGC:CLOC:SOUR %(option)s',
                get_cmd='AWGC:CLOC:SOUR?',
                options=[('Internal', 'INT'), ('External', 'EXT')]),
        QOption('Reference Source',
                set_cmd='SOUR:ROSC:SOUR %(option)s',
                get_cmd='SOUR:ROSC:SOUR?',
                options=[('Internal', 'INT'), ('External', 'EXT')]),
        QReal('Vpp',
              unit='V',
              ch=1,
              set_cmd='SOUR%(ch)d:VOLT %(value)f',
              get_cmd='SOUR%(ch)d:VOLT?'),
        QReal('Offset',
              unit='V',
              ch=1,
              set_cmd='SOUR%(ch)d:VOLT:OFFS %(value)f',
              get_cmd='SOUR%(ch)d:VOLT:OFFS?'),
        QReal('Volt Low',
              unit='V',
              ch=1,
              set_cmd='SOUR%(ch)d:VOLT:LOW %(value)f',
              get_cmd='SOUR%(ch)d:VOLT:LOW?'),
        QReal('Volt High',
              unit='V',
              ch=1,
              set_cmd='SOUR%(ch)d:VOLT:HIGH %(value)f',
              get_cmd='SOUR%(ch)d:VOLT:HIGH?'),
        QReal('Force Jump',
              unit='Step',
              ch=1,
              set_cmd=' SOURCE%(ch)d:JUMP:FORCE %(value)f'),
        # output delay in time
        QReal('timeDelay',
              unit='s',
              ch=1,
              set_cmd='SOUR%(ch)d:DEL:ADJ %(value)f%(unit)s',
              get_cmd='SOUR%(ch)d:DEL:ADJ?'),
        # output delay in point
        QReal('pointDelay',
              unit='point',
              ch=1,
              set_cmd='SOUR%(ch)d:DEL:POIN %(value)d',
              get_cmd='SOUR%(ch)d:DEL:POIN?'),
        QList('WList'),
        QList('SList'),
    ]

    def performOpen(self):
        self.waveform_list = self.get_waveform_list()
        try:  #没有sequence模块的仪器会产生一个错误
            self.sequence_list = self.get_sequence_list()
        except:
            self.sequence_list = None

    def performSetValue(self, quant, value, **kw):
        if quant.name == '':
            return
        else:
            return BaseDriver.performSetValue(self, quant, value, **kw)

    def performGetValue(self, quant, **kw):
        if quant.name == 'WList':
            quant.value = self.waveform_list
            return self.waveform_list
        elif quant.name == 'SList':
            quant.value = self.sequence_list
            return self.sequence_list
        else:
            return BaseDriver.performGetValue(self, quant, **kw)

    def get_waveform_list(self):
        if self.model in ['AWG5208']:
            return self.query('WLIS:LIST?').strip("\"\n' ").split(',')
        elif self.model in ['AWG5014C']:
            ret = []
            wlist_size = int(self.query("WLIS:SIZE?"))
            for i in range(wlist_size):
                ret.append(self.query("WLIS:NAME? %d" % i).strip("\"\n '"))
            return ret
        else:
            return []

    def get_sequence_list(self):
        if self.model in ['AWG5208']:
            ret = []
            slist_size = int(self.query("SLIS:SIZE?"))
            for i in range(slist_size):
                ret.append(
                    self.query("SLIS:NAME? %d" % (i + 1)).strip("\"\n '"))
            return ret
        else:
            return []

    def create_waveform(self, name, length, format=None):
        '''
        format: REAL, INT or IQ
        '''
        if name in self.waveform_list:
            return
        if format is None:
            if self.model in ['AWG5208']:
                format = 'REAL'
            else:
                format = 'INT'
        self.write('WLIS:WAV:NEW "%s",%d,%s;' % (name, length, format))
        self.waveform_list.append(name)

    def remove_waveform(self, name):
        if name not in self.waveform_list:
            return
        self.waveform_list.remove(name)
        self.write(':WLIS:WAV:DEL "%s"; *CLS' % name)

    def clear_waveform_list(self):
        wavs_to_delete = self.waveform_list.copy()
        for name in wavs_to_delete:
            self.remove_waveform(name)

    def use_waveform(self, name, ch=1):
        self.write('SOURCE%d:WAVEFORM "%s"' % (ch, name))

    def run_state(self):
        return int(self.query('AWGC:RST?'))

    def run(self):
        self.write('AWGC:RUN')
        self.write('*WAI')

    def stop(self):
        self.write('AWGC:STOP')

    def output_on(self, ch=1):
        self.write('OUTP%d:STAT 1' % ch)

    def output_off(self, ch=1):
        self.write('OUTP%d:STAT 0' % ch)

    def get_current_waveforms(self):
        current_waveforms = []
        current_waveform_size = 0
        for i in [1, 2, 3, 4]:
            wn = self.query('SOUR%d:WAV?' % i)[1:-2]
            current_waveforms.append(wn)
            if wn != '' and current_waveform_size == 0:
                current_waveform_size = self.query_ascii_values(
                    'WLIS:WAV:LENGTH? "%s"' % wn, 'd')[0]
        return current_waveform_size, current_waveforms

    def update_waveform(self, points, name='ABS', IQ='I', start=0, size=None):
        w_type = self.query('WLISt:WAVeform:TYPE? "%s"' % name).strip()
        if w_type == 'REAL':
            self._update_waveform_float(points, name, IQ, start, size)
        elif w_type == 'IQ':
            self._update_waveform_float(points[0], name, 'I', start, size)
            self._update_waveform_float(points[1], name, 'Q', start, size)
        else:
            self._update_waveform_int(points, name, start, size)

    def _update_waveform_int(self, points, name='ABS', start=0, size=None):
        """
        points : a 1D numpy.array which values between -1 and 1.
        """
        message = 'WLIST:WAVEFORM:DATA "%s",%d,' % (name, start)
        if size is not None:
            message = message + ('%d,' % size)
        points = points.clip(-1, 1)
        values = (points * 0x1fff).astype(int) + 0x1fff
        self.write_binary_values(message,
                                 values,
                                 datatype=u'H',
                                 is_big_endian=False,
                                 termination=None,
                                 encoding=None)
        self.query('*OPC?')

    def _update_waveform_float(self,
                               points,
                               name='ABS',
                               IQ='I',
                               start=0,
                               size=None):
        if self.model == 'AWG5208':
            message = 'WLIST:WAVEFORM:DATA:%s "%s",%d,' % (IQ, name, start)
        else:
            message = 'WLIST:WAVEFORM:DATA "%s",%d,' % (name, start)
        if size is not None:
            message = message + ('%d,' % size)
        values = points.clip(-1, 1)
        self.write_binary_values(message,
                                 values,
                                 datatype=u'f',
                                 is_big_endian=False,
                                 termination=None,
                                 encoding=None)
        self.query('*OPC?')

    def update_marker(self,
                      name,
                      mk1=None,
                      mk2=None,
                      mk3=None,
                      mk4=None,
                      start=0,
                      size=None):
        def format_marker_data(markers, bits):
            values = 0
            for i, v in enumerate(markers):
                v = 0 if v is None else np.asarray(v, dtype=int)
                values += v << bits[i]
            return values

        if self.model in ['AWG5014C']:
            values = format_marker_data([mk1, mk2], [6, 7])
        elif self.model in ['AWG5208']:
            values = format_marker_data([mk1, mk2, mk3, mk4], [7, 6, 5, 4])
        if size is None:
            message = 'WLIST:WAVEFORM:MARKER:DATA "%s",%d,' % (name, start)
        else:
            message = 'WLIST:WAVEFORM:MARKER:DATA "%s",%d,%d,' % (name, start,
                                                                  size)
        self.write_binary_values(message,
                                 values,
                                 datatype=u'B',
                                 is_big_endian=False,
                                 termination=None,
                                 encoding=None)
        self.query('*OPC?')

    def create_sequence(self, name, steps, tracks):
        if name in self.sequence_list:
            return
        self.write('SLIS:SEQ:NEW "%s", %d, %d' % (name, steps, tracks))
        self.sequence_list.append(name)

    def remove_sequence(self, name):
        if name not in self.sequence_list:
            return
        self.sequence_list.remove(name)
        self.write('SLIS:SEQ:DEL "%s"' % name)

    def clear_sequence_list(self):
        self.write('SLIS:SEQ:DEL ALL')
        self.sequence_list.clear()

    def set_sequence_step(self,
                          name,
                          sub_name,
                          step,
                          wait='OFF',
                          goto='NEXT',
                          repeat=1,
                          jump=None):
        """set a step of sequence
        name: sequence name
        sub_name: subsequence name or list of waveforms for every tracks
        wait: ATRigger | BTRigger | ITRigger | OFF
        goto: <NR1> | LAST | FIRSt | NEXT | END
        repeat: ONCE | INFinite | <NR1>
        jump: a tuple (jump_input, jump_to)
            jump_input: ATRigger | BTRigger | OFF | ITRigger
            jump_to: <NR1> | NEXT | FIRSt | LAST | END
        """
        if isinstance(sub_name, str):
            self.write('SLIS:SEQ:STEP%d:TASS:SEQ "%s","%s"' %
                       (step, name, sub_name))
        else:
            for i, wav in enumerate(sub_name):
                self.write('SLIS:SEQ:STEP%d:TASS%d:WAV "%s","%s"' %
                           (step, i + 1, name, wav))
        self.write('SLIS:SEQ:STEP%d:WINP "%s", %s' % (step, name, wait))
        self.write('SLIS:SEQ:STEP%d:GOTO "%s", %s' % (step, name, goto))
        self.write('SLIS:SEQ:STEP%d:RCO "%s", %s' % (step, name, repeat))
        if jump is not None:
            self.write('SLIS:SEQ:STEP%d:EJIN "%s", %s' % (step, name, jump[0]))
            self.write('SLIS:SEQ:STEP%d:EJUM "%s", %s' % (step, name, jump[1]))

    def set_seq(self,
                wave_name,
                step,
                track,
                seq_name=None,
                tag=None,
                wait='ATR',
                goto='NEXT',
                repeat='1',
                eventinput='OFF',
                eventjump='NEXT'):
        """set a step of sequence
        seq_name: sequence name
        wave_name: subsequence name or list of waveforms for every tracks
        wait: ATRigger | BTRigger | ITRigger | OFF
        goto: <NR1> | LAST | FIRSt | NEXT | END
        repeat: ONCE | INFinite | <NR1>
        eventinput: 
            jump_input: ATRigger | BTRigger | OFF | ITRigger
        eventjump:
            jump_to: <NR1> | NEXT | FIRSt | LAST | END
        """
        if tag == 'subseq':
            self.write('SLISt:SEQ:STEP%d:TASSet%d:SEQ "%s","%s"' %
                       (step, track, seq_name, wave_name))
        else:
            for i, wav in enumerate(wave_name, start=2):
                step = i
                if i == 2:
                    self.write('SLIS:SEQ:STEP%d:TASS%d:WAV "%s","%s"' %
                               (1, track, seq_name, wav))
                    self.write('SLIS:SEQ:STEP%d:WINP "%s", %s' %
                               (1, seq_name, 'BTR'))
                    self.write('SLIS:SEQ:STEP%d:GOTO "%s", %s' %
                               (1, seq_name, goto))
                    self.write('SLIS:SEQ:STEP%d:RCO "%s", %s' %
                               (1, seq_name, repeat))
                    self.write('SLIS:SEQ:STEP%d:EJIN "%s", %s' %
                               (1, seq_name, eventinput))
                    self.write('SLIS:SEQ:STEP%d:EJUM "%s", %s' %
                               (1, seq_name, eventjump))

                self.write('SLIS:SEQ:STEP%d:TASS%d:WAV "%s","%s"' %
                           (step, track, seq_name, wav))
                self.write('SLIS:SEQ:STEP%d:WINP "%s", %s' %
                           (step, seq_name, wait))
                self.write('SLIS:SEQ:STEP%d:GOTO "%s", %s' %
                           (step, seq_name, goto))
                self.write('SLIS:SEQ:STEP%d:RCO "%s", %s' %
                           (step, seq_name, repeat))
                self.write('SLIS:SEQ:STEP%d:EJIN "%s", %s' %
                           (step, seq_name, eventinput))
                self.write('SLIS:SEQ:STEP%d:EJUM "%s", %s' %
                           (step, seq_name, eventjump))

                if i == len(wave_name) + 1:
                    if len(wave_name) % 64 != 0:
                        num = (len(wave_name) // 64 +
                               1) * 64 - len(wave_name) + 5
                    else:
                        num = 5
                    self.write('SLIS:SEQ:STEP%d:RCO "%s", %s' %
                               (step, seq_name, num))
                    self.write('SLIS:SEQ:STEP%d:GOTO "%s", %s' %
                               (step, seq_name, 'FIRST'))

    def use_sequence(self, name, channels=[1, 2]):
        for i, ch in enumerate(channels):
            self.write('SOUR%d:CASS:SEQ "%s", %d' % (ch, name, i + 1))
            self.write('*WAI')
コード例 #11
0
class Driver(BaseDriver):
    """ This class implements a Lab Brick generator"""

    support_models = [
        'LMS-103', 'LMS-123', 'LMS-203', 'LMS-802', 'LMS-163', 'LMS-232D',
        'LMS-402D', 'LMS-602D', 'LMS-451D', 'LMS-322D', 'LMS-271D', 'LMS-152D',
        'LMS-751D', 'LMS-252D', 'LMS-6123LH', 'LMS-163LH', 'LMS-802LH',
        'LMS-802DX', 'LMS-183DX'
    ]

    quants = [
        QReal(
            'Frequency',
            unit='Hz',
        ),
        QReal(
            'Power',
            unit='dBm',
        ),
        QOption('Output', options=[('OFF', False), ('ON', True)]),
        QOption('Reference', options=[('Internal', True), ('External', False)])
    ]

    def __init__(self, **kw):
        BaseDriver.__init__(self, **kw)
        self.Serial = kw['Serial']

    def performOpen(self, options={}):
        """Perform the operation of opening the instrument connection"""
        self.SG = None
        # open connection
        self.SG = LabBrick_LMS_Wrapper.LabBrick_Synthesizer(bTestMode=False)
        self.SG.initDevice(self.Serial)

    def performClose(self, bError=False, options={}):
        """Perform the close instrument connection operation"""
        # do not check for error if close was called with an error
        try:
            self.SG.closeDevice()
        except:
            # never return error here
            pass

    def performSetValue(self, quant, value, sweepRate=0.0, options={}):
        """Perform the Set Value instrument operation. This function should
        return the actual value set by the instrument"""

        # proceed depending on command
        if quant.name == 'Frequency':
            # make sure value is in range
            value = self.SG.setFrequency(value)
        elif quant.name == 'Power':
            self.SG.setPowerLevel(value)
        elif quant.name == 'Output':
            # self.SG.setRFOn(bool(value))
            options = dict(quant.options)
            self.SG.setRFOn(bool(options[value]))
        elif quant.name == 'Reference':
            # self.SG.setUseInternalRef(bool(value))
            options = dict(quant.options)
            self.SG.setUseInternalRef(bool(options[value]))
        # elif quant.name == 'External pulse modulation':
        #     self.SG.setExternalPulseMod(bool(value))
        # elif quant.name in ('Internal pulse modulation', 'Pulse time', 'Pulse period'):
        #     # special case for internal pulse modulation, set all config at once
        #     bOn = self.getValue('Internal pulse modulation')
        #     pulseTime = self.getValue('Pulse time')
        #     pulsePeriod = self.getValue('Pulse period')
        #     self.SG.setInternalPulseMod(pulseTime, pulsePeriod, bOn)
        # return value

    def performGetValue(self, quant, options={}):
        """Perform the Get Value instrument operation"""
        # proceed depending on command
        if quant.name == 'Frequency':
            value = self.SG.getFrequency()
        elif quant.name == 'Power':
            value = self.SG.getPowerLevel()
        elif quant.name == 'Output':
            value = self.SG.getRFOn()
        elif quant.name == 'Reference':
            value = self.SG.getUseInternalRef()
        # elif quant.name == 'Internal pulse modulation':
        #     value = self.SG.getInternalPulseMod()
        # elif quant.name == 'Pulse time':
        #     value = self.SG.getPulseOnTime()
        # elif quant.name == 'Pulse period':
        #     value = self.SG.getPulsePeriod()
        # elif quant.name == 'External pulse modulation':
        #     value = self.SG.getExternalPulseMod()
        # return value
        return value
コード例 #12
0
ファイル: AFG3102.py プロジェクト: feihoo87/QuLab
class Driver(BaseDriver):
    error_command = '*ESR?'
    support_models = ['AFG3102']

    quants = [
        QOption('Output',
                ch=1,
                set_cmd='OUTP%(ch)d %(option)s',
                get_cmd='OUTP%(ch)d?',
                options=[('OFF', 'OFF'), ('ON', 'ON')]),  # must set chanel
        QOption('Function',
                ch=1,
                set_cmd='SOUR%(ch)d:FUNC %(option)s',
                get_cmd='SOUR%(ch)d:FUNC?',
                options=[('Sin', 'SIN'), ('Square', 'SQU'), ('Pulse', 'PULS'),
                         ('Ramp', 'RAMP'), ('PRNoise', 'PRN'), ('DC', 'DC'),
                         ('SINC', 'SINC'), ('Gaussian', 'GAUS'),
                         ('Lorentz', 'LOR'), ('Erise', 'ERIS'),
                         ('Edecay', 'EDEC'), ('Haversine', 'HAV'),
                         ('User', 'USER'), ('User2', 'USER2')]),
        QReal('Frequency',
              unit='Hz',
              ch=1,
              set_cmd='SOUR%(ch)d:FREQ %(value)e%(unit)s',
              get_cmd='SOUR%(ch)d:FREQ?'),
        QReal('Phase',
              unit='rad',
              ch=1,
              set_cmd='SOUR%(ch)d:PHAS %(value)f%(unit)s',
              get_cmd='SOUR%(ch)d:PHAS?'),
        QReal('Pulse Delay',
              unit='s',
              ch=1,
              set_cmd='SOUR%(ch)d:PULS:DEL %(value).9e%(unit)s',
              get_cmd='SOUR%(ch)d:PULS:DEL?'),
        QReal('Pulse Period',
              unit='s',
              ch=1,
              set_cmd='SOUR%(ch)d:PULS:PER %(value).9e%(unit)s',
              get_cmd='SOUR%(ch)d:PULS:PER?'),
        QReal('Pulse Width',
              unit='s',
              ch=1,
              set_cmd='SOUR%(ch)d:PULS:WIDT %(value).9e%(unit)s',
              get_cmd='SOUR%(ch)d:PULS:WIDT?'),
        #Burst Mode
        QReal('Burst Tdelay',
              unit='s',
              ch=1,
              set_cmd='SOUR%(ch)d:BURS:TDEL %(value).9e%(unit)s',
              get_cmd='SOUR%(ch)d:BURS:TDEL?'),
        QReal('Burst Ncycles',
              ch=1,
              set_cmd='SOUR%(ch)d:BURS:NCYC %(value)d',
              get_cmd='SOUR%(ch)d:BURS:NCYC?'),
        ##
        QReal('Frequency',
              unit='Hz',
              ch=1,
              set_cmd='SOUR%(ch)d:FREQ %(value)e%(unit)s',
              get_cmd='SOUR%(ch)d:FREQ?'),
        QReal('Phase',
              unit='DEG',
              ch=1,
              set_cmd='SOUR%(ch)d:PHAS %(value)f%(unit)s',
              get_cmd='SOUR%(ch)d:PHAS?'),
        QReal('High Level',
              unit='V',
              ch=1,
              set_cmd='SOUR%(ch)d:VOLT:HIGH %(value)f%(unit)s',
              get_cmd='SOUR%(ch)d:VOLT:HIGH?'),
        QReal('Low Level',
              unit='V',
              ch=1,
              set_cmd='SOUR%(ch)d:VOLT:LOW %(value)f%(unit)s',
              get_cmd='SOUR%(ch)d:VOLT:LOW?'),
        QReal('Offset',
              unit='V',
              ch=1,
              set_cmd='SOUR%(ch)d:VOLT:OFFS %(value)f%(unit)s',
              get_cmd='SOUR%(ch)d:VOLT:OFFS?'),
        QReal('Amplitude',
              unit='VPP',
              ch=1,
              set_cmd='SOUR%(ch)d:VOLT:AMPL %(value)f%(unit)s',
              get_cmd='SOUR%(ch)d:VOLT:AMPL?'),
    ]

    def reset(self, delay1=0, delay2=0):
        #init
        self.write('*CLS')
        self.write('*RST')
        #set external clock;external source;burst mode&cycle=1&trigdelay=0
        self.write('SOURce:ROSCillator:SOURce EXT')
        self.write('TRIGger:SEQuence:SOURce EXTernal')
        self.write('SOURce1:BURSt:STATe ON')
        self.write('SOURce1:BURSt:NCYCles 1')
        self.write('SOURce1:BURSt:MODE TRIGgered')
        self.write('SOURce1:BURSt:DELay %fus' % delay1)
        self.write('SOURce2:BURSt:STATe ON')
        self.write('SOURce2:BURSt:NCYCles 1')
        self.write('SOURce2:BURSt:MODE TRIGgered')
        self.write('SOURce2:BURSt:TDELay %fns' % delay2)

    #在创建好的波形文件中,写入或者更新具体波形
    def upwave(self, points, ch=1, T0=100):
        pointslen = len(points)
        pointslen2 = 2 * pointslen
        #写入波形数据
        self.write('DATA:DEFine EMEMory,%d' % pointslen)
        self.write('DATA:POINts EMEMory, %d' % pointslen)
        message = ':DATA:DATA EMEMory,'  # % (len(str(pointslen2)),pointslen2)
        points = points.clip(-1, 1)
        values = np.zeros(pointslen).astype(np.uint16)
        #乘积选用8191是为了防止最终值大于16383
        values = (points * 8191).astype(np.uint16) + 8192  #.astype(np.uint16)
        byte = np.zeros(pointslen2).astype(np.uint8)
        #将原先的两比特数据点,分割为高低两个比特
        byte[1:pointslen2:2] = (values & 0b11111111).astype(np.uint8)
        byte[0:pointslen2:2] = ((values & 0b11111100000000) >> 8).astype(
            np.uint8)
        #write_binary_value中的message参数不要包括#42048的信息,因为pyvisa可以自动算出结果。详见pyvisa中util.py内的to_binary_block
        #AFG3102选用big_endian。这表示程序按照我给的顺序将二进制包写进去
        self.write_binary_values(message,
                                 byte,
                                 datatype='B',
                                 is_big_endian=False,
                                 termination=None,
                                 encoding=None)
        # self.write('enable' )
        self.write('TRAC:COPY USER%d,EMEM' % ch)
        self.write('SOURce%d:FUNCTION USER%d' % (ch, ch))
        #set frequency:because the wave total length is set by this parameter,typical for 1Mhz means the wave length is set to 1us!!
        self.write('SOURce%d:FREQuency:FIXed %fkHz' % (ch, 1e3 / T0))
        self.write('OUTPut%d:STATe ON' % ch)
コード例 #13
0
ファイル: TekAWG70000A.py プロジェクト: feihoo87/QuLab
class Driver(BaseDriver):
    support_models = ['AWG70001A', 'AWG70002A']

    quants = [
        # Sample Rate set_cmd is block cmd
        #
        QReal('Sample Rate',
              unit='S/s',
              set_cmd='CLOC:SRAT %(value).10e; *WAI;',
              get_cmd='CLOC:SRAT?'),
        QOption('Run Mode',
                value='CONT',
                ch=1,
                set_cmd='SOUR%(ch)d:RMOD %(option)s',
                get_cmd='SOUR%(ch)d:RMOD?',
                options=[('Continuous', 'CONT'), ('Triggered', 'TRIG'),
                         ('TContinuous', 'TCON')]),
        QOption('Clock Source',
                value='INT',
                set_cmd='CLOC:SOUR %(option)s',
                get_cmd='CLOC:SOUR?',
                options=[('Internal', 'INT'), ('External', 'EXT'),
                         ('Efixed', 'EFIX'), ('Evariable', 'EVAR')]),

        # QOption('Reference Source', set_cmd='SOUR:ROSC:SOUR %(option)s', get_cmd='SOUR:ROSC:SOUR?',
        #   options = [('Internal', 'INT'), ('External', 'EXT')]),
        QReal('Multiplier Rate ',
              value=1,
              set_cmd='CLOC:EREF:MULT %(value)d',
              get_cmd='CLOC:EREF:MULT?'),
        QReal('Divider Rate ',
              value=1,
              set_cmd='CLOC:EREF:DIV %(value)d',
              get_cmd='CLOC:EREF:DIV?'),

        # 以下四种只在 output path 为 Direct 时有效
        # Vpp range: 250-500mVpp
        QReal('Vpp',
              unit='Vpp',
              ch=1,
              set_cmd='SOUR%(ch)d:VOLT %(value)f%(unit)s',
              get_cmd='SOUR%(ch)d:VOLT?'),
        QReal('Offset',
              unit='V',
              ch=1,
              set_cmd='SOUR%(ch)d:VOLT:OFFS %(value)f%(unit)s',
              get_cmd='SOUR%(ch)d:VOLT:OFFS?'),
        QReal('Volt Low',
              unit='V',
              ch=1,
              set_cmd='SOUR%(ch)d:VOLT:LOW %(value)f%(unit)s',
              get_cmd='SOUR%(ch)d:VOLT:LOW?'),
        QReal('Volt High',
              unit='V',
              ch=1,
              set_cmd='SOUR%(ch)d:VOLT:HIGH %(value)f%(unit)s',
              get_cmd='SOUR%(ch)d:VOLT:HIGH?'),

        # output delay in time
        QReal('timeDelay',
              unit='s',
              ch=1,
              set_cmd='SOUR%(ch)d:DEL:ADJ %(value)f%(unit)s',
              get_cmd='SOUR%(ch)d:DEL:ADJ?'),
        # output delay in point
        QReal('timeDelay',
              unit='point',
              ch=1,
              set_cmd='SOUR%(ch)d:DEL:POIN %(value)d',
              get_cmd='SOUR%(ch)d:DELy:POIN?'),
        QOption('Run',
                value='Play',
                set_cmd='AWGC:%(option)s; *WAI;',
                get_cmd='AWGC:RST?',
                options=[('Play', 'RUN'), ('Stop', 'STOP')]),
        QOption('Output',
                ch=1,
                set_cmd='OUTP%(ch)d %(option)s',
                get_cmd='OUTP%(ch)d?',
                options=[('ON', 1), ('OFF', 0), (1, 'ON'), (0, 'OFF')]),
        QList('WList'),
        QList('SList'),

        # INSTrument MODE : AWG or FG
        QOption('instMode',
                value='AWG',
                set_cmd='INST:MODE %(option)s',
                get_cmd='INST:MODE?',
                options=[
                    ('AWG', 'AWG'),
                    ('FG', 'FGEN'),
                ]),
        QOption('FG Type',
                ch=1,
                value='Sin',
                set_cmd='FGEN:CHAN%(ch)d:TYPE %(option)s',
                get_cmd='FGEN:CHAN%(ch)d:TYPE?',
                options=[
                    ('Sin', 'SINE'),
                    ('Square', 'SQU'),
                    ('Triangle', 'TRI'),
                    ('Noise', 'NOIS'),
                    ('DC', 'DC'),
                    ('Gaussian', 'GAUS'),
                    ('ExpRise', 'EXPR'),
                    ('ExpDecay', 'EXPD'),
                    ('None', 'NONE'),
                ]),
        QReal('FG Amplitude',
              ch=1,
              value=0.5,
              unit='V',
              set_cmd='FGEN:CHAN%(ch)d:AMPL:VOLT %(value)f%(unit)s',
              get_cmd='FGEN:CHAN%(ch)d:AMPL:VOLT?'),

        #FG Offset -150mV~150mV, min Unit 1mV
        QReal('FG Offset',
              ch=1,
              value=0,
              unit='V',
              set_cmd='FGEN:CHAN%(ch)d:OFFS %(value)f%(unit)s',
              get_cmd='FGEN:CHAN%(ch)d:OFFS?'),
        QReal('FG Phase',
              ch=1,
              value=0,
              unit='deg',
              set_cmd='FGEN:CHAN%(ch)d:PHAS %(value)f',
              get_cmd='FGEN:CHAN%(ch)d:PHAS?'),
        QReal('FG Frequency',
              ch=1,
              value=1e6,
              unit='Hz',
              set_cmd='FGEN:CHAN%(ch)d:FREQ %(value)f%(unit)s',
              get_cmd='FGEN:CHAN%(ch)d:FREQ?'),
        QReal(
            'FG Period',
            ch=1,
            unit='s',
            # 周期与频率绑定,无法设置周期,但可读
            set_cmd='',
            get_cmd='FGEN:CHAN%(ch)d:PER?'),

        # DC Level Range: –250 mV to 250 mV
        QReal('FG DC',
              ch=1,
              value=0,
              unit='V',
              set_cmd='FGEN:CHAN%(ch)d:DCL %(value)f%(unit)s',
              get_cmd='FGEN:CHAN%(ch)d:DCL?'),
        QReal('FG High',
              ch=1,
              value=0.25,
              unit='V',
              set_cmd='FGEN:CHAN%(ch)d:HIGH %(value)f%(unit)s',
              get_cmd='FGEN:CHAN%(ch)d:HIGH?'),
        QReal('FG Low',
              ch=1,
              value=-0.25,
              unit='V',
              set_cmd='FGEN:CHAN%(ch)d:LOW %(value)f%(unit)s',
              get_cmd='FGEN:CHAN%(ch)d:LOW?'),

        #coupling mode: DIR, DCAM, AC
        QOption('FG Path',
                ch=1,
                value='Direct',
                set_cmd='FGEN:CHAN%(ch)d:PATH %(option)s',
                get_cmd='FGEN:CHAN%(ch)d:PATH?',
                options=[
                    ('Direct', 'DIR'),
                    ('DCAmplified', 'DCAM'),
                    ('AC', 'AC'),
                ]),
    ]

    def performOpen(self):
        self.waveform_list = self.get_waveform_list()
        try:  #没有sequence模块的仪器会产生一个错误
            self.sequence_list = self.get_sequence_list()
        except:
            self.sequence_list = None

    def performSetValue(self, quant, value, **kw):
        if quant.name == '':
            return
        else:
            return BaseDriver.performSetValue(self, quant, value, **kw)

    def performGetValue(self, quant, **kw):
        if quant.name == 'WList':
            self.waveform_list = self.get_waveform_list()
            return self.waveform_list
        elif quant.name == 'SList':
            self.sequence_list = self.get_sequence_list()
            return self.sequence_list
        else:
            return BaseDriver.performGetValue(self, quant, **kw)

    def get_waveform_list(self):
        return self.query('WLIS:LIST?').strip("\"\n' ").split(',')

    def get_sequence_list(self):
        ret = []
        slist_size = int(self.query("SLIS:SIZE?"))
        for i in range(slist_size):
            ret.append(self.query("SLIS:NAME? %d" % i).strip("\"\n '"))
        return ret

    def create_waveform(self, name, length, format='REAL'):
        '''format: REAL or IQ'''
        if name in self.waveform_list:
            return
        self.write('WLIS:WAV:NEW "%s",%d,%s;*WAI;' % (name, length, format))
        self.waveform_list = self.get_waveform_list()

    def remove_waveform(self, name=None, all=False):
        if all:
            self.write('WLIS:WAV:DEL ALL; *WAI;')
            self.waveform_list.clear()
        elif name not in self.waveform_list:
            return
        else:
            self.write('WLIS:WAV:DEL "%s"; *WAI;' % name)
            self.waveform_list = self.get_waveform_list()

    def get_waveform_length(self, name):
        size = int(self.query('WLIS:WAV:LENGTH? "%s"' % name))
        return size

    def use_waveform(self, name, ch=1, type=None):
        '''type: I or Q'''
        if type is not None:
            self.write('SOUR%d:CASS:WAV "%s",%s' % (ch, name, type))
        else:
            self.write('SOUR%d:CASS:WAV "%s"' % (ch, name))
        self.write('*WAI;')

    # 关于RUN的设置和状态询问,建议使用Quantity:Run的方法
    def run_state(self):
        return int(self.query('AWGC:RST?'))

    def run(self):
        self.write('AWGC:RUN')
        self.write('*WAI')

    def stop(self):
        self.write('AWGC:STOP')

    # 关于Output的设置和状态询问,建议使用Quantity:Output的方法
    def output_on(self, ch=1):
        self.write('OUTP%d:STAT 1' % ch)

    def output_off(self, ch=1):
        self.write('OUTP%d:STAT 0' % ch)

    def get_current_asset(self, ch=1):
        current_type = self.query('SOUR%d:CASS:TYPE?' % ch)
        current_asset = self.query('SOUR%d:CASS?' % ch)
        return current_type, current_asset

    def update_waveform(self, points, name='ABS', IQ='I', start=0, size=None):
        w_type = self.query('WLIS:WAV:TYPE? "%s"' % name).strip()
        if w_type == 'REAL':
            self._update_waveform_float(points, name, IQ, start, size)
        elif w_type == 'IQ':
            self._update_waveform_float(points[0], name, 'I', start, size)
            self._update_waveform_float(points[1], name, 'Q', start, size)
        self.write('*WAI;')
        # else:
        #     self._update_waveform_int(points, name, start, size)

    # def _update_waveform_int(self, points, name='ABS', start=0, size=None):
    #     """
    #     points : a 1D numpy.array which values between -1 and 1.
    #     """
    #     message = 'WLIST:WAVEFORM:DATA "%s",%d,' % (name, start)
    #     if size is not None:
    #         message = message + ('%d,' % size)
    #     points = points.clip(-1,1)
    #     values = (points * 0x1fff).astype(int) + 0x1fff
    #     self.write_binary_values(message, values, datatype=u'H',
    #                              is_big_endian=False,
    #                              termination=None, encoding=None)

    def _update_waveform_float(self,
                               points,
                               name='ABS',
                               IQ='I',
                               start=0,
                               size=None):
        message = 'WLIST:WAVEFORM:DATA:%s "%s",%d,' % (IQ, name, start)
        if size is not None:
            message = message + ('%d,' % size)
        values = points.clip(-1, 1)
        self.write_binary_values(message,
                                 values,
                                 datatype=u'f',
                                 is_big_endian=False,
                                 termination=None,
                                 encoding=None)

    # def update_marker(self, name, mk1, mk2=None, mk3=None, mk4=None, start=0, size=None):
    #     def format_marker_data(markers, bits):
    #         values = 0
    #         for i, v in markers:
    #             v = 0 if v is None else np.asarray(v)
    #             values += v << bits[i]
    #         return values
    #
    #     if self.model in ['AWG5014C']:
    #         values = format_marker_data([mk1, mk2], [5,6])
    #     elif self.model in ['AWG5208']:
    #         values = format_marker_data([mk1, mk2, mk3, mk4], [7,6,5,4])
    #     if size is None:
    #         message = 'WLIST:WAVEFORM:MARKER:DATA "%s",%d,' % (name, start)
    #     else:
    #         message = 'WLIST:WAVEFORM:MARKER:DATA "%s",%d,%d,' % (name, start, size)
    #     self.write_binary_values(message, values, datatype=u'B',
    #                              is_big_endian=False,
    #                              termination=None, encoding=None)

    def create_sequence(self, name, steps, tracks=1):
        if name in self.sequence_list:
            return
        self.write('SLIS:SEQ:NEW "%s", %d, %d; *WAI;' % (name, steps, tracks))
        self.sequence_list = self.get_sequence_list()

    def remove_sequence(self, name=None, all=False):
        if all:
            self.write('SLIS:SEQ:DEL ALL; *WAI;')
            self.sequence_list.clear()
        elif name not in self.sequence_list:
            return
        else:
            self.write('SLIS:SEQ:DEL "%s"; *WAI;' % name)
            self.sequence_list = self.get_sequence_list()

    #
    # def set_sequence_step(self, name, sub_name, step, wait='OFF', goto='NEXT', repeat=1, jump=None):
    #     """set a step of sequence
    #
    #     name: sequence name
    #     sub_name: subsequence name or list of waveforms for every tracks
    #     wait: ATRigger | BTRigger | ITRigger | OFF
    #     goto: <NR1> | LAST | FIRSt | NEXT | END
    #     repeat: ONCE | INFinite | <NR1>
    #     jump: a tuple (jump_input, jump_to)
    #         jump_input: ATRigger | BTRigger | OFF | ITRigger
    #         jump_to: <NR1> | NEXT | FIRSt | LAST | END
    #     """
    #     if isinstance(sub_name, str):
    #         self.write('SLIS:SEQ:STEP%d:TASS:SEQ "%s","%s"' % (step, name, sub_name))
    #     else:
    #         for i, wav in enumerate(sub_name):
    #             self.write('SLIS:SEQ:STEP%d:TASS%d:WAV "%s","%s"' % (step, i+1, name, wav))
    #     self.write('SLIS:SEQ:STEP%d:WINP "%s", %s' % (step, name, wait))
    #     self.write('SLIS:SEQ:STEP%d:GOTO "%s", %s' % (step, name, goto))
    #     self.write('SLIS:SEQ:STEP%d:RCO "%s", %s' % (step, name, repeat))
    #     if jump is not None:
    #         self.write('SLIS:SEQ:STEP%d:EJIN "%s", %s' % (step, name, jump[0]))
    #         self.write('SLIS:SEQ:STEP%d:EJUM "%s", %s' % (step, name, jump[1]))

    def use_sequence(self, name, ch=1, track=1, type=None):
        '''type: I or Q'''
        if type is not None:
            self.write('SOUR%d:CASS:SEQ "%s", %d, %s' %
                       (ch, name, track, type))
        else:
            self.write('SOUR%d:CASS:SEQ "%s", %d' % (ch, name, track))
        self.write('*WAI;')
コード例 #14
0
class Driver(BaseDriver):
    support_models = ['ATS9360', 'ATS9870']
    quants = [
        QOption('Clock Source',
                value='External 10MHz Ref',
                options=[('Internal', 1), ('External', 2),
                         ('Medium External', 3), ('Slow External', 4),
                         ('External AC', 5), ('External DC', 6),
                         ('External 10MHz Ref', EXTERNAL_CLOCK_10MHz_REF),
                         ('Internal Div 5', 0x10), ('Master', 0x11),
                         ('Internal Set VCO', 0x12)]),
        QOption('Sample Rate',
                value='1G',
                options=[
                    ('1k', SAMPLE_RATE_1KSPS),
                    ('2k', SAMPLE_RATE_2KSPS),
                    ('5k', SAMPLE_RATE_5KSPS),
                    ('10k', SAMPLE_RATE_10KSPS),
                    ('20k', SAMPLE_RATE_20KSPS),
                    ('50k', SAMPLE_RATE_50KSPS),
                    ('100k', SAMPLE_RATE_100KSPS),
                    ('200k', SAMPLE_RATE_200KSPS),
                    ('500k', SAMPLE_RATE_500KSPS),
                    ('1M', SAMPLE_RATE_1MSPS),
                    ('2M', SAMPLE_RATE_2MSPS),
                    ('5M', SAMPLE_RATE_5MSPS),
                    ('10M', SAMPLE_RATE_10MSPS),
                    ('20M', SAMPLE_RATE_20MSPS),
                    ('25M', SAMPLE_RATE_25MSPS),
                    ('50M', SAMPLE_RATE_50MSPS),
                    ('100M', SAMPLE_RATE_100MSPS),
                    ('125M', SAMPLE_RATE_125MSPS),
                    ('160M', SAMPLE_RATE_160MSPS),
                    ('180M', SAMPLE_RATE_180MSPS),
                    ('200M', SAMPLE_RATE_200MSPS),
                    ('250M', SAMPLE_RATE_250MSPS),
                    ('400M', SAMPLE_RATE_400MSPS),
                    ('500M', SAMPLE_RATE_500MSPS),
                    ('800M', SAMPLE_RATE_800MSPS),
                    ('1G', SAMPLE_RATE_1GSPS),
                    ('1200M', SAMPLE_RATE_1200MSPS),
                    ('1500M', SAMPLE_RATE_1500MSPS),
                    ('1600M', SAMPLE_RATE_1600MSPS),
                    ('1800M', SAMPLE_RATE_1800MSPS),
                    ('2G', SAMPLE_RATE_2GSPS),
                ]),
        QReal('Trigger Delay', value=0, unit='s'),
        QReal('Trigger Timeout', value=1, unit='s'),
        QOption('A Term',
                value='50 Ohm',
                options=[('1 MOhm', 1), ('50 Ohm', 2), ('75 Ohm', 4),
                         ('300 Ohm', 8)]),
        QOption('B Term',
                value='50 Ohm',
                options=[('1 MOhm', 1), ('50 Ohm', 2), ('75 Ohm', 4),
                         ('300 Ohm', 8)]),
        QOption('Ext Coupling', value='DC', options=[('DC', 2), ('AC', 1)]),
        QOption('A Coupling', value='DC', options=[('DC', 2), ('AC', 1)]),
        QOption('B Coupling', value='DC', options=[('DC', 2), ('AC', 1)]),
        QReal('A Range', value=1, unit='V'),
        QReal('B Range', value=1, unit='V'),
        QOption('A Bandwidth limit',
                value='Disable',
                options=[('Disable', 0), ('Enable', 1)]),
        QOption('B Bandwidth limit',
                value='Disable',
                options=[('Disable', 0), ('Enable', 1)]),
        QOption('Trigger Mode',
                value='J',
                options=[
                    ('J', 0),
                    ('K', 1),
                    ('J or K', 2),
                    ('J and K', 3),
                    ('J xor K', 4),
                    ('J and not K', 5),
                    ('not J and K', 6),
                ]),
        QReal('J Level', value=0.1, unit='V'),
        QReal('K Level', value=0.1, unit='V'),
        QOption('J Slope',
                value='Positive',
                options=[('Positive', 1), ('Negative', 2)]),
        QOption('K Slope',
                value='Positive',
                options=[('Positive', 1), ('Negative', 2)]),
        QOption('J Source',
                value='External',
                options=[('ChA', 0), ('ChB', 1), ('External', 2),
                         ('Disable', 3), ('ChC', 4), ('ChD', 5)]),
        QOption('K Source',
                value='Disable',
                options=[('ChA', 0), ('ChB', 1), ('External', 2),
                         ('Disable', 3), ('ChC', 4), ('ChD', 5)]),
    ]

    def __init__(self, **kw):
        BaseDriver.__init__(self, **kw)
        self.systemID = kw['systemID']
        self.boardID = kw['boardID']
        self.__dig = None
        self.config_updated = False
        self.dt = 1E-9

    @property
    def dig(self):
        from .AlazarTech_Wrapper import AlazarTechDigitizer
        if self.__dig is None:
            self.__dig = AlazarTechDigitizer(self.systemID, self.boardID)
        return self.__dig

    def testLED(self):
        self.dig.testLED()

    def setLEDOn(self, on=True):
        self.dig.setLEDOn(on)

    def set_configs(self):
        """Set digitizer configuration based on driver settings"""
        from .AlazarTech_Wrapper import getInputRange
        if self.config_updated:
            return
        logger.debug('set config ...')
        # clock configuration
        SourceId = self.getCmdOption('Clock Source')
        SampleRateId = self.getCmdOption('Sample Rate')
        # 10 MHz ref, use 1GHz rate + divider. NB!! divide must be 1,2,4,10
        #SampleRateId = int(1E9)
        #Decimation = int(round(1E9/lFreq[self.getValueIndex('Sample Rate')]))
        self.dig.AlazarSetCaptureClock(SourceId, SampleRateId)
        # define time step from sample rate
        lFreq = [
            1E3, 2E3, 5E3, 10E3, 20E3, 50E3, 100E3, 200E3, 500E3, 1E6, 2E6,
            5E6, 10E6, 20E6, 25E6, 50E6, 100E6, 125E6, 160E6, 180E6, 200E6,
            250E6, 400E6, 500E6, 800E6, 1E9, 1.2E9, 1.5E9, 1.6E9, 1.8E9, 2E9
        ]
        self.dt = 1 / lFreq[self.getIndex('Sample Rate')]
        #
        # configure inputs
        for ch in ['A', 'B']:
            chIds = {'A': CHANNEL_A, 'B': CHANNEL_B}
            chId = chIds[ch]
            Coupling = self.getCmdOption('%s Coupling' % ch)
            InputRange = getInputRange(self.getValue('%s Range' % ch),
                                       self.model)
            Impedance = self.getCmdOption('%s Term' % ch)
            self.dig.AlazarInputControl(chId, Coupling, InputRange, Impedance)
            # bandwidth limit
            if self.model in ['ATS9870']:
                BW = self.getCmdOption('%s Bandwidth limit' % ch)
                self.dig.AlazarSetBWLimit(chId, BW)
        Coupling = self.getCmdOption('Ext Coupling')
        self.dig.AlazarSetExternalTrigger(Coupling)
        #
        # configure trigger
        Mode = self.getCmdOption('Trigger Mode')
        JSource = self.getCmdOption('J Source')
        KSource = self.getCmdOption('J Source')
        JSlope = self.getCmdOption('J Slope')
        KSlope = self.getCmdOption('K Slope')
        JLevel, KLevel = 0, 0

        # convert relative level to U8
        for egn in ['J', 'K']:
            sour = self.getValue('%s Source' % egn)
            trigLevel = self.getValue('%s Level' % egn)
            if sour == 'ChA':
                maxLevel = getInputRange(self.getValue('A Range'),
                                         self.model,
                                         returnNum=True)
            elif sour == 'ChB':
                maxLevel = getInputRange(self.getValue('B Range'),
                                         self.model,
                                         returnNum=True)
            elif sour == 'External':
                maxLevel = 5.0
            if abs(trigLevel) > maxLevel:
                trigLevel = maxLevel * np.sign(trigLevel)
            Level = int(128 + 127 * trigLevel / maxLevel)
            if egn == 'J':
                JLevel = Level
            else:
                KLevel = Level
        # set config
        self.dig.AlazarSetTriggerOperation(Mode, TRIG_ENGINE_J, JSource,
                                           JSlope, JLevel, TRIG_ENGINE_K,
                                           KSource, KSlope, KLevel)
        #
        # set trig delay and timeout
        Delay = int(self.getValue('Trigger Delay') / self.dt)
        self.dig.AlazarSetTriggerDelay(Delay)
        timeout = self.getValue('Trigger Timeout')
        self.dig.AlazarSetTriggerTimeOut(time=timeout)
        self.config_updated = True
        logger.debug('set config ... Done')

    def performSetValue(self, quant, value, **kw):
        # if quant.name not in ['']:
        BaseDriver.performSetValue(self, quant, value, **kw)
        self.config_updated = False

    def performGetValue(self, quant, **kw):
        # self.set_configs()
        return quant.getValue(**kw)

    def errors(self):
        ret = []
        try:
            while True:
                e = self.dig._error_list.pop(0)
                ret.append(e)
        except IndexError:
            return ret
        return []

    def getTraces_DMA(self,
                      samplesPerRecord=1024,
                      pre=0,
                      repeats=1000,
                      procces=None,
                      timeout=10,
                      sum=False):
        self.set_configs()
        a, b = self.dig.get_Traces_DMA(pre, samplesPerRecord - pre, repeats,
                                       procces, timeout, sum)
        #a, b = self.dig.get_Traces_NPT(samplesPerRecord, repeats, procces, timeout)
        return np.asarray(a), np.asarray(b)

    def setHeterodyneFrequency(self, samplesPerRecord, heterodyne_freq=[]):
        Exp = []
        sampleRate = {
            '1k': 1e3,
            '2k': 2e3,
            '5k': 5e3,
            '10k': 10e3,
            '20k': 20e3,
            '50k': 50e3,
            '100k': 100e3,
            '200k': 200e3,
            '500k': 500e3,
            '1M': 1e6,
            '2M': 2e6,
            '5M': 5e6,
            '10M': 10e6,
            '20M': 20e6,
            '25M': 25e6,
            '50M': 50e6,
            '100M': 100e6,
            '125M': 125e6,
            '160M': 160e6,
            '180M': 180e6,
            '200M': 200e6,
            '250M': 250e6,
            '400M': 400e6,
            '500M': 500e6,
            '800M': 800e6,
            '1G': 1e9,
            '1200M': 1.2e9,
            '1500M': 1.5e9,
            '1600M': 1.6e9,
            '1800M': 1.8e9,
            '2G': 2e9,
        }[self.getValue('Sample Rate')]
        t = np.arange(0, samplesPerRecord, 1) / sampleRate
        for f in heterodyne_freq:
            Exp.append(np.exp(1j * 2 * np.pi * f * t))
        self._Exp = np.asarray(Exp).T

    def getFFT(self,
               samplesPerRecord=1024,
               pre=0,
               repeats=1000,
               heterodyne_freq=None,
               timeout=10):
        self.set_configs()
        n = samplesPerRecord
        if heterodyne_freq is not None:
            self.setHeterodyneFrequency(samplesPerRecord, heterodyne_freq)

        def procces(ch1, ch2, e=self._Exp):
            return ch1[:n].dot(e).T / n, ch2[:n].dot(e).T / n

        A, B = self.dig.get_Traces_DMA(pre, samplesPerRecord - pre, repeats,
                                       procces, timeout)
        return np.asarray(A), np.asarray(B)
コード例 #15
0
class Driver(BaseDriver):
    support_models = ['IT6302']

    quants = [
        QReal(
            'CH1 Voltage',
            unit='V',
            #set_cmd='SYST:REM;INST CH1;VOLT %(value).13e'
            set_cmd='INST CH1;VOLT %(value).13e',
            get_cmd='MEAS? CH1'),
        QReal(
            'CH1 Current',
            unit='A',
            #set_cmd='SYST:REM;INST CH1;CURR %(value).13e'
            set_cmd='INST CH1;CURR %(value).13e',
            get_cmd='MEAS:CURR? CH1'),
        QReal(
            'CH2 Voltage',
            unit='V',
            #set_cmd='SYST:REM;INST CH2;VOLT %(value).13e'
            set_cmd='INST CH2;VOLT %(value).13e',
            get_cmd='MEAS? CH2'),
        QReal(
            'CH2 Current',
            unit='A',
            #set_cmd='SYST:REM;INST CH2;CURR %(value).13e'
            set_cmd='INST CH2;CURR %(value).13e',
            get_cmd='MEAS:CURR? CH2'),
        QReal(
            'CH3 Voltage',
            unit='V',
            #set_cmd='SYST:REM;INST CH3;VOLT %(value).13e'
            set_cmd='INST CH3;VOLT %(value).13e',
            get_cmd='MEAS? CH3'),
        QReal(
            'CH3 Current',
            unit='A',
            #set_cmd='SYST:REM;INST CH3;CURR %(value).13e'
            set_cmd='INST CH3;CURR %(value).13e',
            get_cmd='MEAS:CURR? CH3'),
        QReal(
            'Voltage',
            unit='V',
            #set_cmd='SYST:REM;INST CH3;VOLT %(value).13e'
            set_cmd='INST CH%(ch)d;VOLT %(value).13e',
            get_cmd='MEAS? CH%(ch)d'),
        QReal(
            'Current',
            unit='A',
            #set_cmd='SYST:REM;INST CH3;CURR %(value).13e'
            set_cmd='INST CH%(ch)d;CURR %(value).13e',
            get_cmd='MEAS:CURR? CH%(ch)d'),
        QReal('Voltage Limit',
              unit='V',
              set_cmd='INST CH%(ch)d;VOLT %(value).13e',
              get_cmd='INST CH%(ch)d;VOLT?'),
        QReal('Current Limit',
              unit='A',
              set_cmd='INST CH%(ch)d;CURR %(value).13e',
              get_cmd='INST CH%(ch)d;CURR?'),
        QOption('Output',
                set_cmd='OUTP %(option)s',
                get_cmd='OUTP:STAT?',
                options=[('OFF', '0'), ('ON', '1')]),
        QOption('Combine',
                set_cmd='INST:COM:%(option)s',
                get_cmd='INST:COM?',
                options=[('Parallel', 'Parallel'), ('Series', 'Series'),
                         ('OFF', 'OFF')]),
    ]

    def performOpen(self):
        self.write('SYST:REM')

    def performClose(self):
        self.write('SYST:LOC')
コード例 #16
0
ファイル: RS_FSL.py プロジェクト: ParanoiaSYT/Qulab-backup
class Driver(BaseDriver):
    error_command = 'SYST:ERR?'
    support_models = ['FSL18']

    quants = [
        QOption('Sweep', value='ON',
            set_cmd='INIT:CONT %(option)s', options=[('OFF', 'OFF'), ('ON', 'ON')]),
        QOption('Trace Mode', value='WRIT',ch=1,
            set_cmd='DISP:TRAC%(ch)d:MODE %(option)s',get_cmd='DISP:TRAC%(ch)d:MODE?',
            options=[('Write', 'WRIT'), ('Maxhold', 'MAXH'),('Minhold','MINH'),
            ('View','VIEW'),('Average','AVER')]),

        QReal('Frequency Start', unit='Hz', set_cmd='SENS:FREQ:STAR %(value)e%(unit)s', get_cmd='SENS:FREQ:STAR?'),
        QReal('Frequency Stop', unit='Hz', set_cmd='SENS:FREQ:STOP %(value)e%(unit)s', get_cmd='SENS:FREQ:STOP?'),
        QInteger('Sweep Points',value=601, set_cmd='SENS:SWE:POIN %(value)d',get_cmd='SENS:SWE:POIN?')
    ]

    def get_Trace(self, average=1, ch=1):
        '''Get the Trace Data '''

        points=self.getValue('Sweep Points')
        #Stop the sweep
        self.setValue('Sweep', 'OFF')
        if average==1:
            self.setValue('Trace Mode','Write',ch=ch)
            self.write(':SWE:COUN 1')
        else:
            self.setValue('Trace Mode','Average',ch=ch)
            self.write(':TRAC:AVER:COUN %d' % average)
            self.write(':SWE:COUN %d' % average)
            self.write(':TRAC:AVER:RES')
        #Begin a measurement
        self.write('INIT:IMM')
        self.write('*WAI')
        count=float(self.query('SWE:COUN:CURR?'))
        while  count < average:
            count=float(self.query('SWE:COUN:CURR?'))
            time.sleep(0.01)
        #Get the data
        self.write('FORMAT:BORD NORM')
        self.write('FORMAT ASCII')
        data = self.query_ascii_values("TRAC:DATA? TRACE%d" % ch)
        # data_raw = self.query("TRAC:DATA? TRACE%d" % ch).strip('\n')
        # _data = re.split(r",",data_raw[11:])
        # data=[]
        # for d in _data[:points]:
        #     data.append(float(d))
        #Start the sweep
        self.setValue('Sweep', 'ON')
        return np.array(data)


    def get_Frequency(self):
        """Return the frequency of DSA measurement"""

        freq_star=self.getValue('Frequency Start')
        freq_stop=self.getValue('Frequency Stop')
        sweep_point=self.getValue('Sweep Points')
        return np.array(np.linspace(freq_star,freq_stop,sweep_point))

    def get_SNR(self,signalfreqlist=[],signalbandwidth=10e6,average=1, ch=1):
        '''get SNR_dB '''

        Y_unit =self.query(':UNIT:POW?;:UNIT:POW W').strip('\n')
        Frequency=self.get_Frequency()
        Spectrum=self.get_Trace(average=average, ch=ch)
        Signal_power=0
        Total_power=sum(Spectrum)
        for sf in signalfreqlist:
            for f in Frequency :
                if f > (sf-signalbandwidth/2) and f < (sf+signalbandwidth/2):
                    index = np.where(Frequency==f)
                    Signal_power = Signal_power + Spectrum[index]
        self.write(':UNIT:POW %s'%Y_unit)
        _SNR=Signal_power/(Total_power-Signal_power)
        SNR = 10*np.log10(_SNR)
        return SNR
コード例 #17
0
class Driver(BaseDriver):
    support_models = [
        'M3202A',
    ]

    quants = [
        QReal('Amplitude', value=1, unit='V', ch=0),
        #DC WaveShape
        QReal('Offset', value=0, unit='V', ch=0),
        #Function Generators(FGs) mode
        QReal('Frequency', unit='Hz', ch=0),
        QReal('Phase', value=0, unit='deg', ch=0),
        QOption('WaveShape',
                ch=0,
                value='HIZ',
                options=[('HIZ', -1), ('NoSignal', 0), ('Sin', 1),
                         ('Triangular', 2), ('Square', 4), ('DC', 5),
                         ('AWG', 6), ('PartnerCH', 8)]),
        #clock
        QReal('clockFrequency', unit='Hz'),
        QReal('clockSyncFrequency', unit='Hz'),
        # 板卡向外输出的时钟,默认状态关闭
        QOption('clockIO', value='OFF', options=[('OFF', 0), ('ON', 1)]),
        QOption('triggerIO',
                value='SyncIN',
                options=[('noSyncOUT', (0, 0)), ('SyncOUT', (0, 1)),
                         ('noSyncIN', (1, 0)), ('SyncIN', (1, 1))]),
        QOption('triggerMode',
                value='ExternalCycle',
                ch=0,
                options=[('Auto', 0), ('SWtri', 1), ('SWtriCycle', 5),
                         ('External', 2), ('ExternalCycle', 6)]),
        QOption('triExtSource',
                value='EXTERN',
                ch=0,
                options=[('EXTERN', 0), ('PXI0', 4000), ('PXI1', 4001),
                         ('PXI2', 4002), ('PXI3', 4003), ('PXI4', 4004),
                         ('PXI5', 4005), ('PXI6', 4006), ('PXI7', 4007)]),
        QOption('triggerBehavior',
                value='RISE',
                ch=0,
                options=[('NONE', 0), ('HIGH', 1), ('LOW', 2), ('RISE', 3),
                         ('FALL', 4)]),
        # Defines the delay between the trigger and the waveform launch in tens of ns
        QInteger(
            'startDelay',
            value=0,
            unit='ns',
            ch=0,
        ),
        # Number of times the waveform is repeated once launched (negative means infinite)
        QInteger(
            'cycles',
            value=0,
            ch=0,
        ),
        # Waveform prescaler value, to reduce the effective sampling rate
        QInteger(
            'prescaler',
            value=0,
            ch=0,
        ),
        QOption('Output',
                ch=0,
                value='Close',
                options=[('Stop', 0), ('Run', 1), ('Pause', 2), ('Resume', 3),
                         ('Close', -1)]),
        QList('WList', value=[]),
        QList('SList', value=[], ch=0),
    ]
    #CHs : 仪器通道
    # CHs=[0,1,2,3]
    CHs = [1, 2, 3, 4]

    # config : 用来存储参数配置,防止由于多通道引起的混乱
    config = {}

    def __init__(self, **kw):
        BaseDriver.__init__(self, **kw)
        self.chassis = kw['CHASSIS']
        self.slot = kw['SLOT']

    def newcfg(self):
        self.config = {}
        for q in self.quants:
            _cfg = {q.name: {}}
            if q.ch is not None:
                for i in self.CHs:
                    _cfg[q.name].update(
                        {i: {
                            'value': q.value,
                            'unit': q.unit
                        }})
            else:
                _cfg[q.name].update({0: {'value': q.value, 'unit': q.unit}})
            self.config.update(_cfg)
        log.info('new config!')

    def loadcfg(self, file=None):
        if file == None:
            file = self.caches_file
        with open(file, 'r', encoding='utf-8') as f:
            self.config = yaml.load(f)
        log.info('load config: %s', file)

    def savecfg(self, file=None):
        if file == None:
            file = self.caches_file
        with open(file, 'w', encoding='utf-8') as f:
            yaml.dump(self.config, f)
        log.info('save config: %s', file)

    def performOpen(self):
        #SD_AOU module
        self.AWG = inspur_sd.SD_AOU()
        self.model = self.AWG.getProductNameBySlot(self.chassis, self.slot)
        moduleID = self.AWG.openWithSlot(self.model, self.chassis, self.slot)
        if moduleID < 0:
            print("Module open error:", moduleID)
        self.caches_file = caches_dir() / (self.model + '_config_caches.yaml')
        try:
            self.loadcfg()
        except Exception:
            log.exception(Exception)
            self.newcfg()
            self.savecfg()

    def performClose(self):
        """Perform the close instrument connection operation"""
        # refer labber driver keysight_pxi_awg.py
        # do not check for error if close was called with an error
        try:
            #             print('0')
            #             print('3')
            #             print('13')
            self.setValue('clockIO', 'OFF')
            #             print('2')
            # clear old waveforms and stop awg
            self.waveformFlush()
            #             print('4')
            for ch in self.CHs:
                #                 print('5')
                self.closeCh(ch)
            # close instrument
            # self.AWG.close()
#             print('6')
            self.savecfg()
#             print('7')
        except Exception:
            #             print('1')
            # never return error here
            pass

    def closeCh(self, ch=0):
        #         print('8')
        self.AWG.AWGstop(ch)
        #         print('9')
        self.AWG.AWGflush(ch)
        #         print('10')
        self.config['SList'][ch]['value'] = []
        #         print('11')
        self.AWG.channelWaveShape(ch, -1)
        #         print('12')
        self.config['WaveShape'][ch]['value'] = 'HIZ'
        self.config['Output'][ch]['value'] = 'Close'

    def performSetValue(self, quant, value, ch=0, **kw):
        _cfg = {}
        if quant.name == 'Amplitude':
            self.AWG.channelAmplitude(ch, value)
        elif quant.name == 'Offset':
            self.AWG.channelOffset(ch, value)
        elif quant.name == 'Frequency':
            self.AWG.channelFrequency(ch, value)
        elif quant.name == 'Phase':
            self.phaseReset(ch)
            self.AWG.channelPhase(ch, value)
        elif quant.name == 'WaveShape':
            options = dict(quant.options)
            self.AWG.channelWaveShape(ch, options[value])
        elif quant.name == 'clockFrequency':
            mode = kw.get('mode', 1)
            self.AWG.clockSetFrequency(value, mode)
            ch = 0
        elif quant.name == 'clockIO':
            options = dict(quant.options)
            self.AWG.clockIOconfig(options[value])
            ch = 0
        elif quant.name == 'triggerIO':
            options = dict(quant.options)
            self.AWG.triggerIOconfigV5(*options[value])
            ch = 0
        elif quant.name == 'Output':
            if value == 'Stop':
                self.AWG.AWGstop(ch)
            elif value == 'Run':
                self.AWG.AWGstart(ch)
            elif value == 'Pause':
                self.AWG.AWGpause(ch)
            elif value == 'Resume':
                self.AWG.AWGresume(ch)
            elif value == 'Close':
                self.closeCh(ch)
        elif quant.name == 'clockSyncFrequency':
            print("clockSyncFrequency can't be set")
            return
        _cfg['value'] = value
        self.config[quant.name][ch].update(_cfg)

    def performGetValue(self, quant, ch=0, **kw):
        _cfg = {}
        if quant.name == 'clockFrequency':
            value = self.AWG.clockGetFrequency()
            ch = 0
            _cfg['value'] = value
        elif quant.name == 'clockSyncFrequency':
            value = self.AWG.clockGetSyncFrequency()
            ch = 0
            _cfg['value'] = value
        elif quant.name in ['clockIO', 'triggerIO']:
            ch = 0
        self.config[quant.name][ch].update(_cfg)
        return self.config[quant.name][ch]['value']

    def phaseReset(self, ch=0):
        self.AWG.channelPhaseReset(ch)
        _cfg = {'value': 0}
        self.config['Phase'][ch].update(_cfg)

    def clockResetPhase(self):
        # self.AWG.clockResetPhase(triggerBehavior, triggerSource, skew = 0.0)
        pass

    def newWaveform(self, file_arrayA, arrayB=None, waveformType=0):
        '''Memory usage: Waveforms created with New are stored in the PC RAM,
        not in the module onboard RAM. Therefore, the limitation in the number
        of waveforms and their sizes is given by the amount of PC RAM.'''
        # waveformType 0: Analog 16Bits, Analog normalized waveforms (-1..1) defined with doubles
        # please refer AWG Waveform types about others
        wave = inspur_sd.SD_Wave()
        if isinstance(file_arrayA, str):
            wave.newFromFile(file_arrayA)
            return wave
        else:
            # 5: DigitalType, Digital waveforms defined with integers
            if waveformType == 5:
                wave.newFromArrayInteger(waveformType, file_arrayA, arrayB)
            else:
                wave.newFromArrayDouble(waveformType, file_arrayA, arrayB)
            return wave

    def waveformLoad(self, waveform, num, paddingMode=0):
        '''num: waveform_num, 在板上内存的波形编号'''
        if num in self.config['WList'][0]['value']:
            self.AWG.waveformReLoad(waveform, num, paddingMode)
        else:
            # This function replaces a waveform located in the module onboard RAM.
            # The size of the newwaveform must be smaller than or equal to the existing waveform.
            self.AWG.waveformLoad(waveform, num, paddingMode)
            self.config['WList'][0]['value'].append(num)

    # def waveformReLoad(self, waveform, num, paddingMode = 0):
    #     '''This function replaces a waveform located in the module onboard RAM.
    #     The size of the newwaveform must be smaller than or equal to the existing waveform.'''
    #     self.AWG.waveformReLoad(waveform, num, paddingMode)

    def waveformFlush(self):
        '''This function deletes all the waveforms from the module onboard RAM
        and flushes all the AWG queues'''
        #         print('14')
        self.AWG.waveformFlush()
        #         print('15')
        self.config['WList'][0]['value'] = []
#         print('16')
#         self.config['SList'][0]['value']=[]
#         print('17')

    def AWGflush(self, ch=0):
        '''This function empties the queue of the selected Arbitrary Waveform Generator,
        Waveforms are not removed from the module onboard RAM.'''
        self.AWG.AWGflush(ch)
        self.config['SList'][0]['value'] = []

    def _getParams(self, ch):
        triggerModeIndex = self.getValue('triggerMode', ch=ch)
        triggerModeOptions = self.quantities['triggerMode'].options
        triggerMode = dict(triggerModeOptions)[triggerModeIndex]

        if triggerModeIndex in ['External', 'ExternalCycle']:

            triExtSourceIndex = self.getValue('triExtSource', ch=ch)
            triExtSourceOptions = self.quantities['triExtSource'].options
            triExtSource = dict(triExtSourceOptions)[triExtSourceIndex]
            if triExtSourceIndex in ['EXTERN']:
                # 若未设置过,则从config读取默认配置;若已设置,则结果不变
                triggerIO = self.getValue('triggerIO')
                self.setValue('triggerIO', triggerIO)

            triggerBehaviorIndex = self.getValue('triggerBehavior', ch=ch)
            triggerBehaviorOptions = self.quantities['triggerBehavior'].options
            triggerBehavior = dict(
                triggerBehaviorOptions)[triggerBehaviorIndex]

            self.AWG.AWGtriggerExternalConfig(ch, triExtSource,
                                              triggerBehavior)

        startDelay = self.getValue('startDelay', ch=ch)
        cycles = self.getValue('cycles', ch=ch)
        prescaler = self.getValue('prescaler', ch=ch)

        return triggerMode, startDelay, cycles, prescaler

    def AWGqueueWaveform(self, ch=0, waveform_num=0):
        self.setValue('WaveShape', 'AWG', ch=ch)
        Amplitude = self.getValue('Amplitude', ch=ch)
        self.setValue('Amplitude', Amplitude, ch=ch)

        triggerMode, startDelay, cycles, prescaler = self._getParams(ch)

        self.AWG.AWGqueueWaveform(ch, waveform_num, triggerMode, startDelay,
                                  cycles, prescaler)
        self.config['SList'][ch]['value'].append(waveform_num)

    def AWGrun(self,
               file_arrayA,
               arrayB=None,
               ch=0,
               waveformType=0,
               paddingMode=0):
        '''从文件或序列快速产生波形'''
        print('0')
        self.setValue('WaveShape', 'AWG', ch=ch)
        print('1')
        Amplitude = self.getValue('Amplitude', ch=ch)
        print('2')
        self.setValue('Amplitude', Amplitude, ch=ch)
        print('3')

        triggerMode, startDelay, cycles, prescaler = self._getParams(ch)
        print('4')

        if isinstance(file_arrayA, str):
            # AWGFromFile 有bug
            self.AWG.AWGFromFile(ch, file_arrayA, triggerMode, startDelay,
                                 cycles, prescaler, paddingMode)
        else:
            print('5')
            self.AWG.AWGfromArray(ch, triggerMode, startDelay, cycles,
                                  prescaler, waveformType, file_arrayA, arrayB,
                                  paddingMode)
            print('6')
        self.config['Output'][ch]['value'] = 'Run'
        print('7')
コード例 #18
0
class Driver(BaseDriver):
    error_command = 'LERR?'
    support_models = ['DG645']

    quants = [
        QReal('Trigger Rate',
              unit='Hz',
              set_cmd='TRAT %(value).6E',
              get_cmd='TRAT?'),
        QReal('T0 Amplitude',
              unit='V',
              set_cmd='LAMP 0,%(value).2f',
              get_cmd='LAMP?0'),
        QReal('T0 Offset',
              unit='V',
              set_cmd='LOFF 0,%(value).2f',
              get_cmd='LOFF?0'),
        QReal('T0 Length',
              unit='us',
              set_cmd='DLAY 1,0,%(value).6E',
              get_cmd='DLAY?1'),
        QOption('T0 Polarity',
                set_cmd='LPOL 0,%(option)s',
                get_cmd='LPOL?0',
                options=[('pos', '1'), ('neg', '0')]),
        QReal('AB Amplitude',
              unit='V',
              set_cmd='LAMP 1,%(value).2f',
              get_cmd='LAMP?1'),
        QReal('AB Offset',
              unit='V',
              set_cmd='LOFF 1,%(value).2f',
              get_cmd='LOFF?1'),
        QReal('AB Delay',
              unit='us',
              set_cmd='DLAY 2,0,%(value).6E',
              get_cmd='DLAY?2'),
        QReal('AB Length',
              unit='us',
              set_cmd='DLAY 3,2,%(value).6E',
              get_cmd='DLAY?3'),
        QReal('A Delay',
              unit='us',
              set_cmd='DLAY 2,0,%(value).6E',
              get_cmd='DLAY?2'),
        QReal('B Delay',
              unit='us',
              set_cmd='DLAY 3,0,%(value).6E',
              get_cmd='DLAY?3'),
        QOption('AB Polarity',
                set_cmd='LPOL 1,%(option)s',
                get_cmd='LPOL?1',
                options=[('pos', '1'), ('neg', '0')]),
        QReal('CD Amplitude',
              unit='V',
              set_cmd='LAMP 2,%(value).2f',
              get_cmd='LAMP?2'),
        QReal('CD Offset',
              unit='V',
              set_cmd='LOFF 2,%(value).2f',
              get_cmd='LOFF?2'),
        QReal('CD Delay',
              unit='us',
              set_cmd='DLAY 4,0,%(value).6E',
              get_cmd='DLAY?4'),
        QReal('CD Length',
              unit='us',
              set_cmd='DLAY 5,4,%(value).6E',
              get_cmd='DLAY?5'),
        QReal('C Delay',
              unit='us',
              set_cmd='DLAY 4,0,%(value).6E',
              get_cmd='DLAY?4'),
        QReal('D Delay',
              unit='us',
              set_cmd='DLAY 5,0,%(value).6E',
              get_cmd='DLAY?5'),
        QOption('CD Polarity',
                set_cmd='LPOL 2,%(option)s',
                get_cmd='LPOL?2',
                options=[('pos', '1'), ('neg', '0')]),
        QReal('EF Amplitude',
              unit='V',
              set_cmd='LAMP 3,%(value).2f',
              get_cmd='LAMP?3'),
        QReal('EF Offset',
              unit='V',
              set_cmd='LOFF 3,%(value).2f',
              get_cmd='LOFF?3'),
        QReal('EF Delay',
              unit='us',
              set_cmd='DLAY 6,0,%(value).6E',
              get_cmd='DLAY?6'),
        QReal('EF Length',
              unit='us',
              set_cmd='DLAY 7,6,%(value).6E',
              get_cmd='DLAY?7'),
        QReal('E Delay',
              unit='us',
              set_cmd='DLAY 6,0,%(value).6E',
              get_cmd='DLAY?6'),
        QReal('F Delay',
              unit='us',
              set_cmd='DLAY 7,0,%(value).6E',
              get_cmd='DLAY?7'),
        QOption('EF Polarity',
                set_cmd='LPOL 3,%(option)s',
                get_cmd='LPOL?3',
                options=[('pos', '1'), ('neg', '0')]),
        QReal('GH Amplitude',
              unit='V',
              set_cmd='LAMP 4,%(value).2f',
              get_cmd='LAMP?4'),
        QReal('GH Offset',
              unit='V',
              set_cmd='LOFF 4,%(value).2f',
              get_cmd='LOFF?4'),
        QReal('GH Delay',
              unit='us',
              set_cmd='DLAY 8,0,%(value).6E',
              get_cmd='DLAY?8'),
        QReal('GH Length',
              unit='us',
              set_cmd='DLAY 9,8,%(value).6E',
              get_cmd='DLAY?9'),
        QReal('G Delay',
              unit='us',
              set_cmd='DLAY 8,0,%(value).6E',
              get_cmd='DLAY?8'),
        QReal('H Delay',
              unit='us',
              set_cmd='DLAY 9,0,%(value).6E',
              get_cmd='DLAY?9'),
        QOption('GH Polarity',
                set_cmd='LPOL 4,%(option)s',
                get_cmd='LPOL?4',
                options=[('pos', '1'), ('neg', '0')])
    ]

    def performGetValue(self, quant, **kw):
        get_Delays = [
            'T0 Length', 'AB Delay', 'AB Length', 'A Delay', 'B Delay',
            'CD Delay', 'CD Length', 'C Delay', 'D Delay', 'EF Delay',
            'EF Length', 'E Delay', 'F Delay', 'GH Delay', 'GH Length',
            'G Delay', 'H Delay'
        ]
        if quant.name in get_Delays and quant.get_cmd is not '':
            cmd = quant._formatGetCmd(**kw)
            res = self.query_ascii_values(cmd)
            quant.value = res[1]
            return res[
                0], quant.value * 1e6  # res[0] is the chanel that related ; quant.value : 's' convert to 'us'
        else:
            return super(Driver, self).performGetValue(quant, **kw)

    def performSetValue(self, quant, value, **kw):
        set_Delays = [
            'T0 Length', 'AB Delay', 'AB Length', 'A Delay', 'B Delay',
            'CD Delay', 'CD Length', 'C Delay', 'D Delay', 'EF Delay',
            'EF Length', 'E Delay', 'F Delay', 'GH Delay', 'GH Length',
            'G Delay', 'H Delay'
        ]
        if quant.name in set_Delays and quant.set_cmd is not '':
            value = value / 1e6  # 'us' convert to 's'
            quant.value = value
            cmd = quant._formatSetCmd(value, **kw)
            self.write(cmd)
        else:
            return super(Driver, self).performSetValue(quant, value, **kw)
コード例 #19
0
ファイル: SR620.py プロジェクト: ParanoiaSYT/Qulab-backup
class Driver(BaseDriver):
    error_command = ''
    support_models = ['SR620']
    quants = [
        QVector('Data', unit=''),
        QReal('Ext Level',
              unit='V',
              set_cmd='LEVL 0,%(value)f',
              get_cmd='LEVL? 0'),
        QReal('A Level',
              unit='V',
              set_cmd='LEVL 1,%(value)f',
              get_cmd='LEVL? 1'),
        QReal('B Level',
              unit='V',
              set_cmd='LEVL 2,%(value)f',
              get_cmd='LEVL? 2'),
        QOption('Ext Term',
                set_cmd='TERM 0,%(option)s',
                get_cmd='TERM? 0',
                options=[('50 Ohm', '0'), ('1 MOhm', '1')]),
        QOption('A Term',
                set_cmd='TERM 1,%(option)s',
                get_cmd='TERM? 1',
                options=[('50 Ohm', '0'), ('1 MOhm', '1')]),
        QOption('B Term',
                set_cmd='TERM 2,%(option)s',
                get_cmd='TERM? 2',
                options=[('50 Ohm', '0'), ('1 MOhm', '1')]),
        QOption('Ext Slope',
                set_cmd='TSLP 0,%(option)s',
                get_cmd='TSLP? 0',
                options=[('Positive', '0'), ('Negative', '1')]),
        QOption('A Slope',
                set_cmd='TSLP 1,%(option)s',
                get_cmd='TSLP? 1',
                options=[('Positive', '0'), ('Negative', '1')]),
        QOption('B Slope',
                set_cmd='TSLP 2,%(option)s',
                get_cmd='TSLP? 2',
                options=[('Positive', '0'), ('Negative', '1')]),
        QOption('A Coupling',
                set_cmd='TCPL 1,%(option)s',
                get_cmd='TCPL? 1',
                options=[('DC', '0'), ('AC', '1')]),
        QOption('B Coupling',
                set_cmd='TCPL 2,%(option)s',
                get_cmd='TCPL? 2',
                options=[('DC', '0'), ('AC', '1')]),
        QOption('Mode',
                set_cmd='MODE %(option)s',
                get_cmd='MODE?',
                options=[
                    ('time', '0'),
                    ('width', '1'),
                    ('tr/tf', '2'),
                    ('freq', '3'),
                    ('period', '4'),
                    ('phase', '5'),
                    ('count', '6'),
                ]),
        QOption('Arming Mode',
                set_cmd='ARMM %s',
                get_cmd='ARMM?',
                options=[
                    ('+- time', '0'),
                    ('+ time', '1'),
                    ('1 period', '2'),
                    ('0.01 s gate', '3'),
                    ('0.1 s gate', '4'),
                    ('1.0 s gate', '5'),
                    ('ext trig +- time', '6'),
                    ('ext trig + time', '7'),
                    ('ext gate/trig holdoff', '8'),
                    ('ext 1 period', '9'),
                    ('ext 0.01 s gate', '10'),
                    ('ext 0.1 s gate', '11'),
                    ('ext 1.0 s gate', '12'),
                ]),
    ]

    def performGetValue(self, quant, **kw):
        if quant.name == 'Data':
            if 'count' in kw.keys():
                count = kw['count']
            else:
                count = 100
            return self.get_Data(count)
        else:
            return BaseDriver.performGetValue(self, quant, **kw)

    def get_Data(self, count=100):
        block = b''
        max = 5000
        loop = int(count / max)
        last = count % max
        self.write('*CLS')
        try:
            if last < count:
                for i in range(loop):
                    self.write('BDMP %d' % max)
                    block += self.__read(8 * max)
            self.write('BDMP %d' % last)
            block += self.__read(8 * last)
        except:
            raise
        mode = int(self.query('MODE?'))
        expd = int(self.query('EXPD?'))
        self.write('AUTM 1')

        factors = [
            1.05963812934E-14, 1.05963812934E-14, 1.05963812934E-14,
            1.24900090270331E-9, 1.05963812934E-14, 8.3819032E-8, 0.00390625
        ]
        ret = np.array(list(struct.unpack('<%dq' % count,
                                          block))) * factors[mode]
        if expd != 0:
            ret = ret * 1e-3
        return ret

    def __read(self, size):
        try:
            buff = self.ins.visalib.read(self.ins.session, size)[0]
        except VisaIOWarning:
            pass
        return buff
コード例 #20
0
class Driver(BaseDriver):
    error_command = ''
    support_models = ['33120A', '33220A']
    quants = [
        QReal('Frequency', unit='Hz',
          set_cmd='FREQ %(value).11E %(unit)s',
          get_cmd='FREQ?'),
        QReal('Vpp', unit='VPP',
          set_cmd='VOLT %(value).5E %(unit)s',
          get_cmd='VOLT?'),
        QReal('Offset', unit='V',
          set_cmd='VOLT:OFFS %(value).5E %(unit)s',
          get_cmd='VOLT:OFFS?'),
        QVector('Waveform', unit='V'),
        QString('Trigger',
          set_cmd='TRIG:SOUR %(value)s',
          get_cmd='TRIG:SOUR?'),
        QOption('Load',
          set_cmd=':OUTP:LOAD %(option)s',
          get_cmd='OUTP:LOAD?',
          options=[('50', '50'), ('High', 'INF')]),
        QOption('Output',
          set_cmd='APPL:DC DEF,DEF,%(option).5E',
          options=[('OFF',0)]
        )
    ]

    def performOpen(self):
        self.write('FORM:BORD NORM')
        self.waveform_list = self.query('DATA:CAT?')[1:-1].split('","')
        self.current_waveform = self.query('FUNC:SHAP?')
        if self.current_waveform == 'USER':
            self.current_waveform = self.query('FUNC:USER?')
        self.arb_waveforms = self.query('DATA:NVOL:CAT?')[1:-1].split('","')
        self.trigger_source = self.query('TRIG:SOUR?')
        self.inner_waveform = ["SINC","NEG_RAMP","EXP_RISE","EXP_FALL","CARDIAC"]

        if self.model == '33120A':
            self.max_waveform_size = 16000
            self.trigger_count  = int(float(self.query('BM:NCYC?')))
        elif self.model == '33220A':
            self.max_waveform_size = 16384
            self.trigger_count  = int(float(self.query("BURS:NCYC?")))

    def performSetValue(self, quant, value, **kw):
        if quant.name == 'Waveform':
            if len(value) > self.max_waveform_size:
                value = value[:self.max_waveform_size]
            value = np.array(value)
            vpp  = value.max() - value.min()
            offs = (value.max() + value.min())/2.0
            if vpp == 0:
                self.DC(offs)
                return
            name = kw['name'] if 'name' in kw.keys() else 'ABS'
            freq = kw['freq'] if 'freq' in kw.keys() else None
            self.update_waveform(2*(value-offs)/vpp, name=name)
            self.use_waveform(name, vpp=vpp, offs=offs, freq=freq)
        else:
            BaseDriver.performSetValue(self, quant, value, **kw)

    def __del_func(self, name):
        if name in self.arb_waveforms:
            if name == self.current_waveform:
                self.DC(0)
            self.write('DATA:DEL %s' % name)
            self.arb_waveforms.remove(name)
            self.waveform_list.remove(name)

    def update_waveform(self, values, name='ABS'):
        if self.model == '33120A':
            clip = lambda x: (2047*x).clip(-2047,2047).astype(int)
        elif self.model == '33220A':
            clip = lambda x: (8191*x).clip(-8191,8191).astype(int)
        values = clip(values)
        self.write_binary_values('DATA:DAC VOLATILE,', values,
                                 datatype='h', is_big_endian=True)
        if len(name) > 8:
            name = name[:8]
        name = name.upper()

        if len(self.arb_waveforms) >= 4:
            for wf in self.arb_waveforms:
                if wf != self.current_waveform:
                    self.__del_func(wf)

        self.write('DATA:COPY %s,VOLATILE' % name)

    def use_waveform(self, name, freq=None, vpp=None, offs=None, ch=1):
        freq_s = ("%.11E" % freq) if freq != None else "DEF"
        vpp_s  = ("%.5E"  % vpp)  if vpp  != None else "DEF"
        offs_s = ("%.5E"  % offs) if offs != None else "DEF"
        name = name.upper()
        if name in self.inner_waveform:
            self.write('APPL:%s %s,%s,%s' % (name, freq_s, vpp_s, offs_s))
        else:
            self.write('FUNC:USER %s' % name)
            self.write('APPL:USER %s,%s,%s' % (freq_s, vpp_s, offs_s))
        if self.trigger_source != 'IMM':
            self.set_trigger(source = self.trigger_source,
                             count  = self.trigger_count)
        self.current_waveform = name
        time.sleep(1)

    def DC(self, v):
        """输出直流电压"""
        self.write('APPL:DC DEF,DEF,%.5E' % v)
        self.current_waveform = 'DC'

    def off(self):
        self.DC(0)

    def set_trigger(self, source='IMM', count=1):
        """设置触发

        source : 触发源,可设为'IMM', 'EXT' 或 'BUS'
        count  : 脉冲串的个数
        """
        if source not in ['IMM', 'EXT', 'BUS']:
            return
        if count < 1 or count > 50000:
            return
        self.trigger_source = source
        self.write("TRIG:SOUR %s" % source)
        self.trigger_count = count
        if count != 1:
            self.write("BM:NCYC %d" % count)
        if source != 'IMM':
            self.write("BM:STAT ON")

    def refresh(self):
        """刷新波形"""
        if self.current_waveform == "DC":
            return
        if self.current_waveform not in self.inner_waveform:
            self.write("FUNC:SHAP USER")
        else:
            self.write("FUNC:SHAP %s" % self.current_waveform)
コード例 #21
0
ファイル: wx_AWG.py プロジェクト: ParanoiaSYT/Qulab-backup
class Driver(BaseDriver):
    support_models = ['wx2184']

    quants = [
        QReal('Sample Rate', unit='S/s',
          set_cmd=':FREQ:RAST %(value)g',
          get_cmd=':FREQ:RAST?'),

        QReal('Amp', unit='V',
           set_cmd=':VOLT:LEV:AMPL %(value)f',
           get_cmd=':VOLT:LEV:AMPL?'),

        QReal('Offset', unit='V',
           set_cmd=':VOLT:LEV:OFFS %(value)f',
           get_cmd=':VOLT:LEV:OFFS?'),

        QReal('Frequency', unit='Hz',
           set_cmd=':FREQ %(value)f',
           get_cmd=':FREQ?'),

        QReal('Phase', unit='Deg',
           set_cmd=':SIN:PHAS %(value)f',
           get_cmd=':SIN:PHAS?'),

        QOption('Output',
			set_cmd=':OUTP %(option)s',
			get_cmd=':OUTP?',
			options=[('OFF', 'OFF'), ('ON', 'ON')]),

        QInteger('Select_ch',value=1,unit='',
			set_cmd=':INST:SEL %(value)d',
			get_cmd=':INST:SEL?',
            ),
            #options=[('1', '1'), ('2', '2'), ('3', '3'), ('4', '4')]

        QInteger('Select_trac',value=1,unit='',
			set_cmd=':TRAC:SEL %(value)d',
			get_cmd=':TRAC:SEL?'),

            ]
    def dc(self,ch=1,offs=1.0):
        self.write(':INST:SEL CH%d' %ch)
        self.write(':FUNC:MODE FIX')
        self.write(':FUNC:SHAP DC')
        self.write(':DC %f' %offs)
        self.write(':OUTP ON')

    def sin(self,ch=1,freq=2e8,amp=0.5,offs=0.0,phas=0):
        self.write(':INST:SEL CH%d' %ch)
        self.write(':FUNC:MODE FIX')
        self.write(':FUNC:SHAP SIN')
        self.write(':FREQ %f' %freq)
        self.write(':VOLT:LEV:AMPL %f' %amp)
        self.write(':VOLT:LEV:OFFS %f' %offs)
        self.write(':SIN:PHAS %f' %phas)
        self.write(':OUTP ON')

    def reset(self,samplerate=2.3e9):
        self.write('*CLS')
        self.write('*RST')
        #选择特定function
        self.write(':FUNC:MODE USER')
        #设置采样率
        self.write(':FREQ:RAST %d' %samplerate)
        #设置外部时钟
        self.write(':ROSCillator:SOURce EXTernal')
        #清除原有波形
        self.write(':INST:SEL CH1')
        self.write(':TRAC:DEL:ALL')
        self.write(':INST:SEL CH3')
        self.write(':TRAC:DEL:ALL')
        #将几个通道的设置设为同一个,详见manual
        # self.write(':INST:COUPle:STATe ON')
        # self.write(':INIT:CONT OFF')
        # self.write(':TRIG:COUN 1')
        # self.write('enable')

    #创建波形文件
    def crwave(self,segment_num,sample_num):
        self.write(':TRAC:DEF %d,%d' %(segment_num,sample_num))

    #在创建好的波形文件中,写入或者更新具体波形
    def upwave(self,points,ch=1,trac=1):
        pointslen=len(points)
        pointslen2=2*pointslen
        #选择特定function
        self.write(':FUNC:MODE USER')
        #选择特定channel
        self.write(':INST:SEL %d' %ch)
        #定义特定的segment
        self.write(':TRAC:DEF %d,%d' %(trac,pointslen))
        #选择特定的segment
        self.write(':TRAC:SEL %d' %trac)
        #选择模式为SINGLE,(包括DUPLicate,SINGle等,详见manual)
        self.write(':TRAC:MODE SING' )
        #写入波形数据
        message=':TRAC:DATA'# % (len(str(pointslen2)),pointslen2)
        points = points.clip(-1,1)
        values=np.zeros(pointslen).astype(np.uint16)
        #乘积选用8191是为了防止最终值大于16383
        values = (points * 8191).astype(np.uint16)+8192 #.astype(np.uint16)
        byte=np.zeros(pointslen2).astype(np.uint8)
        #将原先的两比特数据点,分割为高低两个比特
        byte[0:pointslen2:2]=(values & 0b11111111).astype(np.uint8)
        byte[1:pointslen2:2]=((values & 0b11111100000000) >> 8).astype(np.uint8)
        #write_binary_value中的message参数不要包括#42048的信息,因为pyvisa可以自动算出结果。详见pyvisa中util.py内的to_binary_block
        #wx2184选用little_endian。这表示程序按照我给的顺序将二进制包写进去
        self.write_binary_values(message, byte, datatype='B',is_big_endian=False,termination=None, encoding=None)
        # self.write('enable' )

	#运行波形
    def ruwave(self,amp=2,offset=0,ch=1,trac=1,trigdelay=0):
        self.write(':INST:SEL %d' %ch)
        self.write(':VOLT:LEV:AMPL %f' %amp)
        self.write(':VOLT:LEV:OFFS %f' %offset)
        self.write(':TRAC:SEL %d' %trac)
        self.write(':OUTP ON')
        self.write(':INIT:CONT OFF')
        self.write(':TRIG:COUN 1')
        self.write(':TRIG:DEL %d' %trigdelay)

    def ruwave1(self,amp=2,offset=0,ch=1,trac=1):
        self.write(':INST:SEL %d' %ch)
        self.write(':VOLT:LEV:AMPL %f' %amp)
        self.write(':VOLT:LEV:OFFS %f' %offset)
        self.write(':TRAC:SEL %d' %trac)
        self.write(':OUTP ON')
        self.write(':INIT:CONT ON')

    def ruwave2(self,amp=2,ch=1,trac=1):
        self.write(':INST:SEL %d' %ch)
        self.write(':VOLT:LEV:AMPL %f' %amp)
        self.write(':TRAC:SEL %d' %trac)
        self.write(':OUTP ON')
        self.write(':INIT:CONT OFF')
        self.write(':TRIG:COUN 1')
コード例 #22
0
class Driver(BaseDriver):
    support_models = ['AWG70001A', 'AWG70002A']

    quants = [
        QReal('Sample Rate',
              unit='S/s',
              set_cmd='CLOC:SRAT %(value).10e',
              get_cmd='CLOC:SRAT?'),
        QOption('Run Mode',
                value='CONT',
                ch=1,
                set_cmd='SOUR%(ch)d:RMOD %(option)s',
                get_cmd='SOUR%(ch)d:RMOD?',
                options=[('Continuous', 'CONT'), ('Triggered', 'TRIG'),
                         ('TContinuous', 'TCON')]),
        QOption('Clock Source',
                value='INT',
                set_cmd='CLOC:SOUR %(option)s',
                get_cmd='CLOC:SOUR?',
                options=[('Internal', 'INT'), ('External', 'EXT'),
                         ('Efixed', 'EFIX'), ('Evariable', 'EVAR')]),

        # QOption('Reference Source', set_cmd='SOUR:ROSC:SOUR %(option)s', get_cmd='SOUR:ROSC:SOUR?',
        #   options = [('Internal', 'INT'), ('External', 'EXT')]),
        QReal('Multiplier Rate ',
              value=1,
              set_cmd='CLOC:EREF:MULT %(value)d',
              get_cmd='CLOC:EREF:MULT?'),
        QReal('Divider Rate ',
              value=1,
              set_cmd='CLOC:EREF:DIV %(value)d',
              get_cmd='CLOC:EREF:DIV?'),
        QReal('Amplitude',
              unit='V',
              ch=1,
              set_cmd='SOUR%(ch)d:VOLT %(value)f%(unit)s',
              get_cmd='SOUR%(ch)d:VOLT?'),
        QReal('Offset',
              unit='V',
              ch=1,
              set_cmd='SOUR%(ch)d:VOLT:OFFS %(value)f%(unit)s',
              get_cmd='SOUR%(ch)d:VOLT:OFFS?'),
        QReal('Volt Low',
              unit='V',
              ch=1,
              set_cmd='SOUR%(ch)d:VOLT:LOW %(value)f%(unit)s',
              get_cmd='SOUR%(ch)d:VOLT:LOW?'),
        QReal('Volt High',
              unit='V',
              ch=1,
              set_cmd='SOUR%(ch)d:VOLT:HIGH %(value)f%(unit)s',
              get_cmd='SOUR%(ch)d:VOLT:HIGH?'),
        # output delay in time
        QReal('timeDelay',
              unit='s',
              ch=1,
              set_cmd='SOUR%(ch)d:DEL:ADJ %(value)f%(unit)s',
              get_cmd='SOUR%(ch)d:DEL:ADJ?'),
        # output delay in point
        QReal('timeDelay',
              unit='point',
              ch=1,
              set_cmd='SOUR%(ch)d:DEL:POIN %(value)d',
              get_cmd='SOUR%(ch)d:DELy:POIN?'),
        QOption('Output',
                ch=1,
                set_cmd='OUTP%(ch)d %(option)d',
                get_cmd='OUTP%(ch)d?',
                options=[('ON', 1), ('OFF', 0), (1, 1), (0, 0)]),
        QList('WList'),
        QList('SList'),
    ]

    def performOpen(self):
        self.waveform_list = self.get_waveform_list()
        try:  #没有sequence模块的仪器会产生一个错误
            self.sequence_list = self.get_sequence_list()
        except:
            self.sequence_list = None

    def performSetValue(self, quant, value, **kw):
        if quant.name == '':
            return
        else:
            return BaseDriver.performSetValue(self, quant, value, **kw)

    def performGetValue(self, quant, **kw):
        if quant.name == 'WList':
            self.waveform_list = self.get_waveform_list()
            return self.waveform_list
        elif quant.name == 'SList':
            self.sequence_list = self.get_sequence_list()
            return self.sequence_list
        else:
            return BaseDriver.performGetValue(self, quant, **kw)

    def get_waveform_list(self):
        return self.query('WLIS:LIST?').strip("\"\n' ").split(',')

    def get_sequence_list(self):
        ret = []
        slist_size = int(self.query("SLIS:SIZE?"))
        for i in range(slist_size):
            ret.append(self.query("SLIS:NAME? %d" % i).strip("\"\n '"))
        return ret

    def create_waveform(self, name, length, format='REAL'):
        '''format: REAL or IQ'''
        if name in self.waveform_list:
            return
        self.write('WLIS:WAV:NEW "%s",%d,%s;' % (name, length, format))
        self.waveform_list = self.get_waveform_list()

    def remove_waveform(self, name=None, all=False):
        if all:
            self.write('WLIS:WAV:DEL ALL; *CLS')
            self.waveform_list.clear()
        elif name not in self.waveform_list:
            return
        else:
            self.write('WLIS:WAV:DEL "%s"; *CLS' % name)
            self.waveform_list = self.get_waveform_list()

    def use_waveform(self, name, ch=1, type=None):
        '''type: I or Q'''
        if type is not None:
            self.write('SOUR%d:CASS:WAV "%s",%s' % (ch, name, type))
        else:
            self.write('SOUR%d:CASS:WAV "%s"' % (ch, name))

    def run_state(self):
        return int(self.query('AWGC:RST?'))

    def run(self):
        self.write('AWGC:RUN')
        self.write('*WAI')

    def stop(self):
        self.write('AWGC:STOP')

    def get_current_asset(self, ch=1):
        current_type = self.query('SOUR%d:CASS:TYPE?' % ch)
        current_asset = self.query('SOUR%d:CASS?' % ch)
        return current_type, current_asset

    def update_waveform(self, points, name='ABS', IQ='I', start=0, size=None):
        w_type = self.query('WLISt:WAV:TYPE? "%s"' % name).strip()
        if w_type == 'REAL':
            self._update_waveform_float(points, name, IQ, start, size)
        elif w_type == 'IQ':
            self._update_waveform_float(points[0], name, 'I', start, size)
            self._update_waveform_float(points[1], name, 'Q', start, size)
        # else:
        #     self._update_waveform_int(points, name, start, size)

    # def _update_waveform_int(self, points, name='ABS', start=0, size=None):
    #     """
    #     points : a 1D numpy.array which values between -1 and 1.
    #     """
    #     message = 'WLIST:WAVEFORM:DATA "%s",%d,' % (name, start)
    #     if size is not None:
    #         message = message + ('%d,' % size)
    #     points = points.clip(-1,1)
    #     values = (points * 0x1fff).astype(int) + 0x1fff
    #     self.write_binary_values(message, values, datatype=u'H',
    #                              is_big_endian=False,
    #                              termination=None, encoding=None)

    def _update_waveform_float(self,
                               points,
                               name='ABS',
                               IQ='I',
                               start=0,
                               size=None):
        message = 'WLIST:WAVEFORM:DATA:%s "%s",%d,' % (IQ, name, start)
        if size is not None:
            message = message + ('%d,' % size)
        values = points.clip(-1, 1)
        self.write_binary_values(message,
                                 values,
                                 datatype=u'f',
                                 is_big_endian=False,
                                 termination=None,
                                 encoding=None)

    # def update_marker(self, name, mk1, mk2=None, mk3=None, mk4=None, start=0, size=None):
    #     def format_marker_data(markers, bits):
    #         values = 0
    #         for i, v in markers:
    #             v = 0 if v is None else np.asarray(v)
    #             values += v << bits[i]
    #         return values
    #
    #     if self.model in ['AWG5014C']:
    #         values = format_marker_data([mk1, mk2], [5,6])
    #     elif self.model in ['AWG5208']:
    #         values = format_marker_data([mk1, mk2, mk3, mk4], [7,6,5,4])
    #     if size is None:
    #         message = 'WLIST:WAVEFORM:MARKER:DATA "%s",%d,' % (name, start)
    #     else:
    #         message = 'WLIST:WAVEFORM:MARKER:DATA "%s",%d,%d,' % (name, start, size)
    #     self.write_binary_values(message, values, datatype=u'B',
    #                              is_big_endian=False,
    #                              termination=None, encoding=None)

    def create_sequence(self, name, steps, tracks=1):
        if name in self.sequence_list:
            return
        self.write('SLIS:SEQ:NEW "%s", %d, %d' % (name, steps, tracks))
        self.sequence_list = self.get_sequence_list()

    def remove_sequence(self, name=None, all=False):
        if all:
            self.write('SLIS:SEQ:DEL ALL; *CLS')
            self.sequence_list.clear()
        elif name not in self.sequence_list:
            return
        else:
            self.write('SLIS:SEQ:DEL "%s"' % name)
            self.sequence_list = self.get_sequence_list()

    #
    # def set_sequence_step(self, name, sub_name, step, wait='OFF', goto='NEXT', repeat=1, jump=None):
    #     """set a step of sequence
    #
    #     name: sequence name
    #     sub_name: subsequence name or list of waveforms for every tracks
    #     wait: ATRigger | BTRigger | ITRigger | OFF
    #     goto: <NR1> | LAST | FIRSt | NEXT | END
    #     repeat: ONCE | INFinite | <NR1>
    #     jump: a tuple (jump_input, jump_to)
    #         jump_input: ATRigger | BTRigger | OFF | ITRigger
    #         jump_to: <NR1> | NEXT | FIRSt | LAST | END
    #     """
    #     if isinstance(sub_name, str):
    #         self.write('SLIS:SEQ:STEP%d:TASS:SEQ "%s","%s"' % (step, name, sub_name))
    #     else:
    #         for i, wav in enumerate(sub_name):
    #             self.write('SLIS:SEQ:STEP%d:TASS%d:WAV "%s","%s"' % (step, i+1, name, wav))
    #     self.write('SLIS:SEQ:STEP%d:WINP "%s", %s' % (step, name, wait))
    #     self.write('SLIS:SEQ:STEP%d:GOTO "%s", %s' % (step, name, goto))
    #     self.write('SLIS:SEQ:STEP%d:RCO "%s", %s' % (step, name, repeat))
    #     if jump is not None:
    #         self.write('SLIS:SEQ:STEP%d:EJIN "%s", %s' % (step, name, jump[0]))
    #         self.write('SLIS:SEQ:STEP%d:EJUM "%s", %s' % (step, name, jump[1]))

    def use_sequence(self, name, ch=1, track=1, type=None):
        '''type: I or Q'''
        if type is not None:
            self.write('SOUR%d:CASS:SEQ "%s", %d, %s' %
                       (ch, name, track, type))
        else:
            self.write('SOUR%d:CASS:SEQ "%s", %d' % (ch, name, track))