Example #1
0
class Driver(SerialDriver):
    support_models = ['DAT64H']

    quants = [
        QReal('ATT',
              value=0,
              unit='dB',
              set_cmd='ATT %(value).1f',
              get_cmd='ATT?'),
        QOption('Display',
                set_cmd='*DISPLAY %(option)s',
                options=[('OFF', 'OFF'), ('ON', 'ON')]),
    ]
Example #2
0
class Driver(visaDriver):
    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',
                options=[('OFF', 'OFF'), ('ON', 'ON')]),
    ]
Example #3
0
class Driver(visaDriver):
    __log__=log
    support_models = ['DP832']
    '''Rigol DP800 series DC source'''

    CHs=[1,2,3]
    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')]),
    ]
Example #4
0
class Driver(BaseDriver):
    __log__ = log
    support_models = []

    quants = [
        QReal('Frequency',
              unit='Hz',
              set_cmd='FREQ %(value).9e Hz',
              get_cmd='FREQ?'),
        QReal('Power',
              unit='dBm',
              set_cmd='LEVEL %(value).5e dBm',
              get_cmd='LEVEL?'),
        QOption('Output',
                set_cmd='LEVEL:STATE %(option)s',
                options=[('OFF', 'OFF'), ('ON', 'ON')]),
    ]

    CHs = [1]

    def __init__(self, addr, **kw):
        super().__init__(addr, **kw)
        self.port = kw.get('port', 2000)

    @contextmanager
    def _socket(self):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.connect((self.addr, self.port))
            yield s

    def write(self, cmd):
        if isinstance(cmd, str):
            cmd = cmd.encode()
        with self._socket() as s:
            s.send(cmd)
            log.debug(f"{self.addr}:{self.port} << {cmd}")

    def query(self, cmd):
        if isinstance(cmd, str):
            cmd = cmd.encode()
        with self._socket() as s:
            s.send(cmd)
            log.debug(f"{self.addr}:{self.port} << {cmd}")
            ret = s.recv(1024).decode()
            log.debug(f"{self.addr}:{self.port} >> {ret}")
            return ret
Example #5
0
class Driver(visaDriver):
    error_command = ':SYST:ERR?'
    support_models = ['RSA5126B']

    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')]),
        QReal('Frequency Start',
              unit='Hz',
              set_cmd='SENS:SPEC:FREQ:STAR %(value)e%(unit)s',
              get_cmd='SENS:SPEC:FREQ:STAR?'),
        QReal('Frequency Stop',
              unit='Hz',
              set_cmd='SENS:SPEC:FREQ:STOP %(value)e%(unit)s',
              get_cmd='SENS:SPEC:FREQ:STOP?'),
        # QInteger('Sweep Points',value=601, set_cmd=':SWE:POIN %(value)d',get_cmd=':SWE:POIN?')
    ]
Example #6
0
class Driver(visaDriver):
    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)
Example #7
0
class Driver(BaseDriver):

    __log__=log
    
    support_models = ['M3202A', ]

    quants = [
        QReal('Amplitude', value=1, unit='V', ch=1),
        #DC WaveShape
        QReal('Offset', value=0, unit='V', ch=1),
        #Function Generators(FGs) mode
        QReal('Frequency', unit='Hz', ch=1),
        QReal('Phase', value=0, unit='deg', ch=1),

        QOption('WaveShape', ch=1, 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=1,
                             options = [('Auto',         0),
                                        ('SWtri',        1),
                                        ('SWtriCycle',   5),
                                        ('External',     2),
                                        ('ExternalCycle',6)]),
        QOption('triExtSource', value='EXTERN', ch=1,
                             options = [('EXTERN', 0),
                                        ('PXI0', 4000),
                                        ('PXI1', 4001),
                                        ('PXI2', 4002),
                                        ('PXI3', 4003),
                                        ('PXI4', 4004),
                                        ('PXI5', 4005),
                                        ('PXI6', 4006),
                                        ('PXI7', 4007)]),
        QOption('triggerBehavior', value='RISE', ch=1,
                             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=1, ),
        # Number of times the waveform is repeated once launched (negative means infinite)
        QInteger('cycles', value=0, ch=1,),
        # Waveform prescaler value, to reduce the effective sampling rate
        QInteger('prescaler', value=0, ch=1,),

        QOption('Output', ch=1, value='Close', options = [('Stop', 0),  ('Run', 1),
                                                          ('Pause', 2), ('Resume', 3),
                                                          ('Close', -1)]),
        QList('WList', value=[]),
        QList('SList', value=[], ch=1),
    ]
    #CHs : 仪器通道
    CHs=[1,2,3,4]

    def __init__(self, addr, **kw):
        super().__init__(self, addr, **kw)

    def performOpen(self):
        #SD_AOU module
        dict_parse=self._parse_addr(self.addr)
        CHASSIS=dict_parse.get('CHASSIS') #default 1
        SLOT=dict_parse.get('SLOT')
        self.handle = keysightSD1.SD_AOU()
        self.model = self.handle.getProductNameBySlot(CHASSIS,SLOT)
        moduleID = self.handle.openWithSlot(self.model, CHASSIS, SLOT)
        if moduleID < 0:
        	print("Module open error:", moduleID)

    def _parse_addr(self,addr):
        re_addr = re.compile(
            r'^(PXI)[0-9]?::CHASSIS([0-9]*)::SLOT([0-9]*)::FUNC([0-9]*)::INSTR$')
        m = re_addr.search(addr)
        if m is None:
            raise Error('Address error!')
        CHASSIS = int(pxi.group(2))
        SLOT = int(pxi.group(3))
        return dict(CHASSIS=CHASSIS,SLOT=SLOT)

    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:
            self.setValue('clockIO','OFF')
            # clear old waveforms and stop awg
            self.waveformFlush()
            for ch in self.CHs:
                self.closeCh(ch)
            # close instrument
            # self.handle.close()
        except Exception:
            # never return error here
            pass

    def closeCh(self,ch=1):
        self.handle.AWGstop(ch)
        self.handle.AWGflush(ch)
        self.config['SList'][ch]['value']=[]
        self.handle.channelWaveShape(ch, -1)
        self.config['WaveShape'][ch]['value']='HIZ'
        self.config['Output'][ch]['value']='Close'

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


    def performGetValue(self, quant, **kw):
        if quant.name == 'clockFrequency':
            return self.handle.clockGetFrequency() 
        elif quant.name == 'clockSyncFrequency':
            return self.handle.clockGetSyncFrequency()
        else:
            return super().performGetValue(quant, **kw)

    def phaseReset(self,ch=1):
        self.handle.channelPhaseReset(ch)

    def clockResetPhase(self):
        # self.handle.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 = keysightSD1.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']['global']['value']:
            self.handle.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.handle.waveformLoad(waveform, num, paddingMode)
            self.config['WList']['global']['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.handle.waveformReLoad(waveform, num, paddingMode)

    def waveformFlush(self):
        '''This function deletes all the waveforms from the module onboard RAM
        and flushes all the AWG queues'''
        self.handle.waveformFlush()
        self.config['WList']['global']['value']=[]
        for ch in self.CHs:
            self.config['SList'][ch]['value']=[]

    def AWGflush(self,ch=1):
        '''This function empties the queue of the selected Arbitrary Waveform Generator,
        Waveforms are not removed from the module onboard RAM.'''
        self.handle.AWGflush(ch)
        self.config['SList'][ch]['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.handle.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=1, 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.handle.AWGqueueWaveform(ch, waveform_num, triggerMode, startDelay, cycles, prescaler)
        self.config['SList'][ch]['value'].append(waveform_num)

    def AWGrun(self, file_arrayA, arrayB=None, ch=1, waveformType=0, paddingMode = 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)

        if isinstance(file_arrayA, str):
            # AWGFromFile 有bug
            self.handle.AWGFromFile(ch, file_arrayA, triggerMode, startDelay, cycles, prescaler, paddingMode)
        else:
            self.handle.AWGfromArray(ch, triggerMode, startDelay, cycles, prescaler, waveformType, file_arrayA, arrayB, paddingMode)
        self.config['Output'][ch]['value']='Run'
Example #8
0
class Driver(visaDriver):
    __log__ = log
    error_command = '*ESR?'
    support_models = ['AFG3102']

    CHs = [1, 2]
    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)
Example #9
0
class Driver(visaDriver):
    __log__ = log
    support_models = ['AWG70001A', 'AWG70002A']

    CHs = [1, 2]
    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):
        super(Driver, self).performOpen()
        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):
        super(Driver, self).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 super(Driver, self).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;')
Example #10
0
class Driver(BaseDriver):
    error_command = 'SYST:ERR?'
    support_models = ['FSL18']
    # R&S 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
Example #11
0
class Driver(visaDriver):
    __log__ = log
    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')
Example #12
0
class Driver(visaDriver):
    __log__=log
    support_models = ['AWG5014C', 'AWG5208']
    CHs=[1,2,3,4]

    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?'),
        # 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):
        super(Driver,self).performOpen()
        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):
        super(Driver,self).performSetValue(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 super(Driver,self).performGetValue(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.write(':WLIS:WAV:DEL "%s"; *CLS' % name)
        self.waveform_list.remove(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)

    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)

    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 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)

    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.write('SLIS:SEQ:DEL "%s"' % name)
        self.sequence_list.remove(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 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))
Example #13
0
class Driver(visaDriver):
    __log__=log
    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):
        super(Driver,self).performOpen()
        self.write('SYST:REM')

    def performClose(self):
        self.write('SYST:LOC')
Example #14
0
class Driver(visaDriver):
    __log__ = log
    support_models = [
        'E8363B', 'E8363C', 'E5071C', 'E5080A', 'ZNB20-2Port', 'N5232A'
    ]

    quants = [
        QReal('Power',
              value=-20,
              unit='dBm',
              set_cmd='SOUR:POW %(value)e%(unit)s',
              get_cmd='SOUR:POW?'),
        # QOption('PowerMode',
        #         value='OFF',
        #         ch=1,
        #         set_cmd='SOUR%(ch)s:POW:MODE %(option)s',
        #         get_cmd='SOUR%(ch)s:POW:MODE?',
        #         options=[('OFF', 'OFF'), ('ON', 'ON')]),
        QReal('Bandwidth',
              value=1000,
              unit='Hz',
              ch=1,
              set_cmd='SENS%(ch)d:BAND %(value)e%(unit)s',
              get_cmd='SENS%(ch)d:BAND?'),
        QReal('Frequency center',
              value=5e9,
              ch=1,
              unit='Hz',
              set_cmd='SENS%(ch)d:FREQ:CENT %(value)e%(unit)s',
              get_cmd='SENS%(ch)d:FREQ:CENT?'),
        QReal('Frequency span',
              value=2e9,
              ch=1,
              unit='Hz',
              set_cmd='SENS%(ch)d:FREQ:SPAN %(value)e%(unit)s',
              get_cmd='SENS%(ch)d:FREQ:SPAN?'),
        QReal('Frequency start',
              value=4e9,
              ch=1,
              unit='Hz',
              set_cmd='SENS%(ch)d:FREQ:STAR %(value)e%(unit)s',
              get_cmd='SENS%(ch)d:FREQ:STAR?'),
        QReal('Frequency stop',
              value=6e9,
              ch=1,
              unit='Hz',
              set_cmd='SENS%(ch)d:FREQ:STOP %(value)e%(unit)s',
              get_cmd='SENS%(ch)d:FREQ:STOP?'),
        QVector('Frequency', unit='Hz', ch=1),
        QVector('Trace', ch=1),
        QVector('S', ch=1),
        QOption('Sweep',
                value='ON',
                set_cmd='INIT:CONT %(option)s',
                options=[('OFF', 'OFF'), ('ON', 'ON')]),
        QInteger('Number of points',
                 value=201,
                 ch=1,
                 unit='',
                 set_cmd='SENS%(ch)d:SWE:POIN %(value)d',
                 get_cmd='SENS%(ch)d: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='',
                ch=1,
                set_cmd='SENS%(ch)d:SWE:TYPE %(option)s',
                get_cmd='SENS%(ch)d: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 performOpen(self):
        super().performOpen()
        self.set_timeout(15)
        self.pna_select(ch=1)

    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')
            self.write(':FORM:DATA REAL,32')
            cmd = ("CALC%d:DATA? FDATA" %
                   ch) if formated else ("CALC%d:DATA? SDATA" % ch)
        #data = np.asarray(self.query_ascii_values(cmd))
        data = np.asarray(self.query_binary_values(cmd, is_big_endian=True))
        self.write('FORMAT ASCII')
        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 S(self, i=1, j=1, ch=1, mname="MyMeas"):
        self.create_measurement(name=mname, param=f"S{i}{j}", ch=ch)
        self.write('CALC%d:PAR:SEL "%s"' % (ch, mname))
        #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:SDATA?" % ch)
        else:
            self.write('FORMAT ASCII')
            cmd = ("CALC%d:DATA? SDATA" % ch)
        #Start the sweep
        self.setValue('Sweep', 'ON')

        data = np.asarray(self.query_ascii_values(cmd))
        data = data[::2] + 1j * data[1::2]
        return data

    def get_measurements(self, ch=1):
        if self.model in ['E5071C']:
            return
        if self.model in ['E8363C', 'E8363B', 'E5080A', 'N5232A']:
            quote = '" '
        elif self.model in ['ZNB20-2Port']:
            quote = "' "
        msg = self.query('CALC%d:PAR:CAT?' % ch).strip(quote)
        meas = msg.split(',')
        return meas[::2], meas[1::2]

    def create_measurement(self, name='MyMeas', param='S11', ch=1):
        mname, params = self.get_measurements(ch=ch)
        if name in mname:
            self.write('CALC%d:PAR:DEL "%s"' % (ch, name))
        self.write('CALC%d:PAR:DEF "%s",%s' % (ch, "MyMeas", param))

    def pna_select(self, ch=1):
        '''Select the measurement'''
        if self.model in ['E5071C']:
            return
        mname, params = self.get_measurements(ch=ch)
        measname = mname[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 in ['E8363C', 'E5080A']:
            cmd = 'CALC%d:X?' % ch
            self.write(':FORM:DATA REAL,32')
            data = self.query_binary_values(cmd, is_big_endian=True)
            # self.write('FORMAT ASCII')
            return np.asarray(data)
        if self.model in ['E8363B', 'N5232A']:
            freq_star = self.getValue('Frequency start', ch=1)
            freq_stop = self.getValue('Frequency stop', ch=1)
            num_of_point = self.getValue('Number of points', ch=1)
            return np.array(np.linspace(freq_star, freq_stop, num_of_point))
        elif self.model in ['ZNB20-2Port']:
            cmd = 'CALC%d:DATA:STIM?' % ch
            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))
Example #15
0
class Driver(visaDriver):
    __log__ = log
    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 super(Driver, self).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
Example #16
0
class Driver(visaDriver):
    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')]),
    ]
Example #17
0
class Driver(wxDriver):
    __log__ = log
    support_models = ['wx2184']

    quants = [
        # Arb waveforms frequency
        QReal('Sample Rate',
              value=1e9,
              unit='Sa/s',
              set_cmd=':FREQ:RAST %(value)e',
              get_cmd=':FREQ:RAST?'),

        # Amp, Offset 要在选择通道后设置,每个通道独立
        QReal('Amp',
              value=1,
              unit='Vpp',
              ch=1,
              set_cmd=':INST:SEL %(ch)d;:VOLT:LEV:AMPL %(value)f',
              get_cmd=':INST:SEL %(ch)d;:VOLT:LEV:AMPL?'),
        QReal('Offset',
              value=0,
              unit='V',
              ch=1,
              set_cmd=':INST:SEL %(ch)d;:VOLT:LEV:OFFS %(value)f',
              get_cmd=':INST:SEL %(ch)d;:VOLT:LEV:OFFS?'),

        # 任意波须选USER模式
        QOption('Function Mode',
                value='Fixed',
                ch=1,
                set_cmd=':INST:SEL %(ch)d;:FUNC:MODE %(option)s',
                get_cmd=':INST:SEL %(ch)d;:FUNC:MODE?',
                options=[('Fixed', 'FIX'), ('User', 'USER'),
                         ('Sequence', 'SEQ'), ('ASequence', 'ASEQ'),
                         ('Modulation', 'MOD'), ('Pulse', 'PULS'),
                         ('Patten', 'PATT')]),

        ## Function Shape: 只在Fixed模式下才能设置
        QOption('Function Shape',
                value='Sin',
                ch=1,
                set_cmd=':INST:SEL %(ch)d;:FUNC:SHAP %(option)s',
                get_cmd=':INST:SEL %(ch)d;:FUNC:SHAP?',
                options=[('Sin', 'SIN'), ('Triangle', 'TRI'),
                         ('Square', 'SQU'), ('Ramp', 'RAMP'), ('Sinc', 'SINC'),
                         ('Gaussian', 'GAUS'), ('Exponential', 'EXP'),
                         ('Noise', 'NOIS'), ('DC', 'DC')]),

        ## Trace Mode: 只在USER模式,即任意波模式下才能设置
        QOption('Trace Mode',
                value='Single',
                ch=1,
                set_cmd=':INST:SEL %(ch)d;:TRAC:MODE %(option)s',
                get_cmd=':INST:SEL %(ch)d;:TRAC:MODE?',
                options=[
                    ('Single', 'SING'),
                    ('Duplicate', 'DUPL'),
                    ('Zerode', 'ZER'),
                    ('Combined', 'COMB'),
                ]),

        ## Continuous Mode: 关闭连续模式即为触发模式
        QOption('Continuous Mode',
                value='OFF',
                set_cmd=':INIT:CONT %(option)s',
                get_cmd=':INIT:CONT?',
                options=[('OFF', 0), ('ON', 1)]),

        # QInteger('Current CH',value=1,
        #         set_cmd=':INST:SEL %(value)d',
        #         get_cmd=':INST:SEL?',),
        # QInteger('Current Trace',value=1,ch=1,
        #         set_cmd=':INST:SEL %(ch)d;:TRAC:SEL %(value)d',
        #         get_cmd=':INST:SEL %(ch)d;:TRAC:SEL?'),
        QOption('Output',
                value='OFF',
                ch=1,
                set_cmd=':INST:SEL %(ch)d;:OUTP %(option)s',
                get_cmd=':INST:SEL %(ch)d;:OUTP?',
                options=[('OFF', 'OFF'), ('ON', 'ON')]),
    ]

    CHs = [1, 2, 3, 4]

    def performOpen(self, ):
        super().performOpen()
        self.setValue('Continuous Mode', 'OFF')
        # self.write(':INIT:GATE:STAT OFF')
        for ch in self.CHs:
            self.setValue('Function Mode', 'User', ch=ch)
            self.setValue('Trace Mode', 'Duplicate', ch=ch)

    def crwave(self, ch, segment, length):
        '''创建波形,1/2通道共用内存,3/4通道共用内存,两者独立编号

        Parameters:
            ch: 通道编号,1/2共用内存,3/4共用内存
            segment: 在内存中的片段编号,范围1-32000,即trace编号
            length: 波形长度(点数),范围192-16(32)e6,必须为16的整数倍,否则报错
        '''
        self.write(':INST:SEL %s' % ch)
        self.write(':TRAC:DEF %d,%d' % (segment, length))

    def delwave(self, ch, segment=1, all=False):
        self.write(':INST:SEL %s' % ch)
        if all:
            self.write(':TRAC:DEL:ALL')
        else:
            self.write(':TRAC:DEL %d' % segment)

    def upwave(self, points, ch=1, trace=1):
        self.write(':INST:SEL %d;:TRAC:SEL %d' % (ch, trace))
        points = points.clip(-1, 1)
        wav = self.build_wave(points)
        self.handle.send_binary_data(':TRAC:DATA', wav)

    # def upwave(self, points, ch=1, trace=1):
    #     self.setValue('Current Trace',trace,ch=ch)
    #     message = ':TRAC:DATA'
    #     values = points.clip(-1, 1)
    #     self.write_binary_values(message,
    #                              values,
    #                              datatype=u'f',
    #                              is_big_endian=False,
    #                              termination=None,
    #                              encoding=None)

    def usewave(self, ch=1, trace=1):
        self.write(':INST:SEL %d;:TRAC:SEL %d' % (ch, trace))