def performGetValue(self, quant, options={}):
     """Perform the Get Value instrument operation"""
     # check type of quantity
     if quant.name in ('Ch1 - Data', 'Ch2 - Data', 'Ch3 - Data', 'Ch4 - Data'):
         # traces, get channel
         channel = int(quant.name[2])
         # check if channel is on
         if self.getValue('Ch%d - Enabled' % channel):
             # select channel and set # of bytes to send
             self.write(':DATA:SOU CH%d;:WFMO:BYT_N 2;' % channel, bCheckError=False)
             # query range and offset
             sRange = self.ask(':WFMO:XZE?;:WFMO:XIN?;:WFMO:YMU?;:WFMO:YOF?;:WFMO:YZE?;', bCheckError=False)
             lRange = sRange.split(';')
             (t0, dt, gain, ioffset, offset) = [float(s) for s in lRange]
             # get data as i16, convert to numpy array
             self.write('CURV?', bCheckError=False)
             sData = self.read(ignore_termination=True)
             # strip header to find # of points
             i0 = sData.find('#')
             nDig = int(sData[i0+1])
             nByte = int(sData[i0+2:i0+2+nDig])
             nData = nByte/2
             # get data to numpy array
             vData = np.frombuffer(sData[(i0+2+nDig):(i0+2+nDig+nByte)], 
                                   dtype='>h', count=nData)
             value = InstrumentQuantity.getTraceDict( \
                     gain*(vData - ioffset) + offset, dt=dt)
         else:
             # not enabled, return empty array
             value = InstrumentQuantity.getTraceDict([])
     else:
         # for all other cases, call VISA driver
         value = VISA_Driver.performGetValue(self, quant, options)
     return value
Пример #2
0
    def performGetValue(self, quant, options={}):
        """Perform the Get Value instrument operation"""
        # check type of quantity
        if quant.name in ('Ch1 - Data', 'Ch2 - Data', 'Ch3 - Data', 'Ch4 - Data'):
            # traces, get channel
            channel = int(quant.name[2])
            # check if channel is on
            if self.getValue('Ch%d - Enabled' % channel):
                # get waveform descriptor data
#                sDesc = self.askAndLog('C%d:WF? DESC;' % channel)
                self.write('C%d:WF? DESC;' % channel, bCheckError=False)
                sDesc = self.read(ignore_termination=True)
                # start by finding byte count, skip 9 bytes after
                indx = sDesc.find('#9')
                sDesc = sDesc[indx+2+9:]
                # strip out relevant info
                iFirst = struct.unpack('>i', sDesc[124:128])[0]
                iLast = struct.unpack('>i', sDesc[128:132])[0]
                Voffs = struct.unpack('>f', sDesc[160:164])[0]
                Vgain = struct.unpack('>f', sDesc[156:160])[0]
                dt = struct.unpack('>f', sDesc[176:180])[0]
                nPts = struct.unpack('>i', sDesc[116:120])[0]
    #            print (iFirst, iLast, Voffs, Vgain, dt, nPts)
                #
                # do a second call to get data, convert to numpy array
                self.write('C%d:WF? DAT1;' % channel, bCheckError=False)
                sData = self.read(ignore_termination=True)
                head = 16
                vData = np.fromstring(sData[(head + iFirst*2):(head + (iLast+1)*2)], 
                                      dtype='>h', count=nPts)
                value = InstrumentQuantity.getTraceDict(vData*Vgain + Voffs, dt=dt)
            else:
                # not enabled, return empty array
                value = InstrumentQuantity.getTraceDict([])
        elif quant.name == 'Trig source':
            # trig source, treat seperately
            sAns = self.askAndLog('TRSE?').strip()
            i1 = sAns.find(',SR,') + 4
            i2 = sAns.find(',HT')
            # convert response to a number
            value = quant.getValueFromCmdString(sAns[i1:i2])
        elif quant.name == 'Trig level':
            # trig options, get local trig source value
            sTrig = self.getCmdStringFromValue('Trig source')
            sAns = self.askAndLog('%s:TRLV?' % sTrig).strip()
            i1 = sAns.find('V')
            value = float(sAns[:i1])
        elif quant.name == 'Trig slope':
            # trig options, get local trig source value
            sTrig = self.getCmdStringFromValue('Trig source')
            # update visa commands
            quant.set_cmd = '%s:TRSL' % sTrig
            # run standard VISA case with updated commands
            value = VISA_Driver.performGetValue(self, quant, options)
        else:
            # for all other cases, call VISA driver
            value = VISA_Driver.performGetValue(self, quant, options)
        return value
 def getTraceDict(self):
     """Return the signal along with its time vector"""
     if self.cTrace is None:
         if self.bBufferRead:
             self.log('yo2')
             self.cTrace=InstrumentQuantity.getTraceDict(self.digitizer.capture_to_buffer(), 
                             t0=-self.nPreTriggers/self.fSamplingRate, dt=1/self.fSamplingRate)
         else:
             self.cTrace=InstrumentQuantity.getTraceDict(self.sample(), 
                             t0=-self.nPreTriggers/self.fSamplingRate, dt=1/self.fSamplingRate)                    
     return self.cTrace
 def getTraceDict(self):
     """Return the signal along with its time vector"""
     if self.cTrace is None:
         sampling_rate=self.getValue("Sampling rate")
         num_pretriggers=self.getValue("Number of pretrigger samples")
         self.checkADCOverload()
         if self.bBufferRead:
             self.cTrace=InstrumentQuantity.getTraceDict(self.digitizer.buffer_capture(), 
                             t0=-num_pretriggers/sampling_rate, dt=1/sampling_rate)
         else:
             self.cTrace=InstrumentQuantity.getTraceDict(self.digitizer.full_captmem(), 
                             t0=-num_pretriggers/sampling_rate, dt=1/sampling_rate)                    
     return self.cTrace
Пример #5
0
 def getSignalHardwareLoop(self, quant, options):
     """Get data from round-robin type averaging"""
     (seq_no, n_seq) = self.getHardwareLoopIndex(options)
     # if first sequence call, get data
     if seq_no == 0 and self.isFirstCall(options):
         nSample = int(self.getValue('Number of samples'))
         nAverage = int(self.getValue('Number of averages'))
         bDemodulation = bool(self.getValue('Enable demodulation'))
         self.lTrace = [np.array([]), np.array([]), 0.0, np.zeros(n_seq, dtype=complex)]
         # show status before starting acquisition
         self.reportStatus('Digitizer - Waiting for signal')
         ((self.lTrace[0], self.lTrace[1]), self.dt) = \
              self.dig.getRoundRobinData(nSample, n_seq, nAverage,
              bConfig=False, bArm=False, bMeasure=True,
              funcStop=self.isStopped,
              funcProgress=self._callbackProgress)
         # temporary, calculate I/Q signal here
         if bDemodulation and self.dt>0:
             self.lTrace[3] = self.getIQAmplitudes(n_seq)
     # after getting data, pick values to return
     indx = self.lSignalNames.index(quant.name)
     if quant.name in ('Ch1 - Data', 'Ch2 - Data'):
         value = InstrumentQuantity.getTraceDict(self.lTrace[indx][seq_no],
                                                 dt=self.dt)
     elif quant.name in ('Signal'):
         value = self.lTrace[3][seq_no]
     else:
         value = self.lTrace[3]
     return value
 def getTimeTrace(self, trace):
     if self.time[trace] is None:
         self.sampleAndAverageSingle(trace)
     
     value = InstrumentQuantity.getTraceDict(self.time[trace], t0=-self.samples/2/self.digitizer1.modulation_generic_sampling_frequency_get(), dt=1/self.digitizer1.modulation_generic_sampling_frequency_get())
     self.time[trace] = None
     return value
Пример #7
0
 def performGetValue(self, quant, options={}):
     """Perform the Get Value instrument operation"""
     try:
         # proceed depending on command
         if quant.name == 'RF Frequency':
             value = self.digitizer1.rf_centre_frequency_get()
         elif quant.name == 'Max input level':
             value = self.digitizer1.rf_rf_input_level_get()
         elif quant.name == 'Sampling rate':
             value = self.digitizer1.modulation_generic_sampling_frequency_get()
         elif quant.name == 'Number of samples':
             value = self.nSamples
         elif quant.name == 'Output power':
             value = self.sigGen.rf_current_level_get()
         elif quant.name == 'Remove DC offset':
             value = self.digitizer1.rf_remove_dc_offset_get()
         elif quant.name == 'Trigger Source':
             value = self.digitizer1.trigger_source_get()
             value = quant.getValueString(value)
         elif quant.name == 'Number of triggers':
             value = self.nTriggers
         elif quant.name == 'Number of segments':
             value = self.nSegments
         elif quant.name == 'Number of lags':
             value = self.nLags
         elif quant.name == 'Prefilter':
             value = self.dPrefilter    
         elif quant.name == 'Power1Mean':
             value = self.getTraceAvg(0)
         elif quant.name == 'Power2Mean':
             value = self.getTraceAvg(1)
         elif quant.name == 'Noise1Mean':
             value = self.getNoiseAvg(0)
         elif quant.name == 'Noise2Mean':
             value = self.getNoiseAvg(1)
         elif quant.name == 'Power1Var':
             value = self.getTraceAvg(2)
         elif quant.name == 'Power2Var':
             value = self.getTraceAvg(3)
         elif quant.name == 'Covariance':
             value = self.getTraceAvg(4)
         elif quant.name == 'g2 Correlation':
             value = InstrumentQuantity.getTraceDict(self.getCorrelation(), t0=-self.nLags/self.digitizer1.modulation_generic_sampling_frequency_get(), dt=1/self.digitizer1.modulation_generic_sampling_frequency_get())
         elif quant.name == 'Trace 1':
             value = self.getTrace(0)
         elif quant.name == 'Trace 2':
             value = self.getTrace(1)    
         return value
     except afDigitizerWrapper.Error as e:
         # re-cast errors as a generic communication error
         msg = str(e)
         raise InstrumentDriver.CommunicationError(msg)
 def performGetValue(self, quant, options={}):
     """Perform the Get Value instrument operation"""
     # check type of quantity
     if quant.name == 'Ch1 - Data':
         if self.data is None:
             self.sample()
         value = InstrumentQuantity.getTraceDict(self.data, t0=self.xdisp, dt=self.xincr)
         self.log(str(self.data))
         self.log(str(self.xdisp))
         self.log(str(self.xincr))
         self.data = None
     
     elif quant.name == 'Power1Mean':
         if self.P1Mean is None:
             self.Psi()
         
         value = self.P1Mean
         self.P1Mean = None
     
     elif quant.name == 'Power2Mean':
         if self.P2Mean is None:
             self.Psi()
         
         value = self.P2Mean
         self.P2Mean = None
     
     elif quant.name == 'RF Frequency 1':
         value = self.f1
         
     elif quant.name == 'RF Frequency 2':
         value = self.f2
     
     elif quant.name == 'Psi':
         if self.psi is None:
             self.IQ_demodulate()
         value = self.psi
         self.psi = None
         
     elif quant.name == 'Covar':
         if self.covar is None:
             self.Psi()
         value = self.covar.reshape([1, -1])[0]
         self.covar = None
     
     else:
         value = VISA_Driver.performGetValue(self, quant, options=options)
          
     return value
Пример #9
0
 def fftFilter(self):
     freq = self.getValue('Modulation frequency')
     traceIn = self.getValue('Input data')
     if traceIn is None:
         return complex(0.0)
     X = traceIn['y']     
     dt = traceIn['dt']
     t0 = traceIn['t0']
     # avoid exceptions if no time step is given
     if dt==0:
         dt = 1.0
     
     Y = np.fft.fftshift(np.fft.fft(X))
     f = np.fft.fftshift(np.fft.fftfreq(len(X), dt))
     Yf = Y
     Yf[f==freq] = 0
     Yf[f==-freq] = 0
     Yf[f==50E6] = 0
     Yf[f==-50E6] = 0
     Xf = np.fft.ifft(np.fft.ifftshift(Yf))
     return InstrumentQuantity.getTraceDict(Xf, t0, dt)
Пример #10
0
 def getTraceDict(self, vSignal):
     dSampFreq = self.getValue('Sampling rate')
     nPreTriggerSamples = int(self.getValue('Number of pretrigger samples'))
     return InstrumentQuantity.getTraceDict(vSignal, t0=-nPreTriggerSamples/dSampFreq, dt=1/dSampFreq)
    def performGetValue(self, quant, options={}):
        """Perform the Get Value instrument operation"""
        # check type of quantity
#        if quant.name in ('Zero-span mode',):
        if quant.name in ('Range type',):
            # check if span is zero
            span = self.readValueFromOther('Span')
            if span == 0:
                value = 'Zero-span mode'
            else:
                # return old value if not in zero span
                value = quant.getValueString()
                if value == 'Zero-span mode':
                    value = 'Center - Span'
        elif quant.name in ('Signal', 'Signal - Zero span'):
            # if not in continous mode, trig from computer
            bWaitTrace = self.getValue('Wait for new trace')
            bAverage = self.getValue('Average')
            # wait for trace, either in averaging or normal mode
            if bWaitTrace:
                if bAverage:
                    # clear averages
                    self.writeAndLog(':SENS:AVER:CLE;')
                self.writeAndLog(':ABOR;:INIT:CONT OFF;:INIT:IMM;*OPC')
                # wait some time before first check
                self.thread().msleep(30)
                bDone = False
                while (not bDone) and (not self.isStopped()):
                    # check if done
                    stb = int(self.askAndLog('*ESR?'))
                    bDone = (stb & 1) > 0
                    if not bDone:
                        self.thread().msleep(50)
                # if stopped, don't get data
                if self.isStopped():
                    self.writeAndLog('*CLS;:INIT:CONT ON;')
                    return []
            # get data as float32, convert to numpy array
            self.write(':FORM REAL,32;TRAC:DATA? TRACE1', bCheckError=False)
            sData = self.read(ignore_termination=True)
            if bWaitTrace and not bAverage:
                self.writeAndLog(':INIT:CONT ON;')
            # strip header to find # of points
            i0 = sData.find('#')
            nDig = int(sData[i0+1])
            nByte = int(sData[i0+2:i0+2+nDig])
            nPts = nByte/4
            # get data to numpy array
            vData = np.frombuffer(sData[(i0+2+nDig):(i0+2+nDig+nByte)], 
                                  dtype='>f', count=nPts)
            # get start/stop frequencies
            startFreq = self.readValueFromOther('Start frequency')
            stopFreq = self.readValueFromOther('Stop frequency')
            sweepType = self.readValueFromOther('Sweep type')
            # if log scale, take log of start/stop frequencies
            if sweepType == 'Log':
                startFreq = np.log10(startFreq)
                stopFreq = np.log10(stopFreq)
            # check if return trace or trace average
            if quant.name == 'Signal - Zero span':
                # return average
                value = np.average(vData)
            else:
                # create a trace dict
                value = InstrumentQuantity.getTraceDict(vData, t0=startFreq,
                                               dt=(stopFreq-startFreq)/(nPts-1))
        elif quant.name in ('Wait for new trace',):
            # do nothing, return local value
            value = quant.getValue()
        else:
            # for all other cases, call VISA driver
            value = VISA_Driver.performGetValue(self, quant, options)
        return value
 def performGetValue(self, quant, options={}):
     """Perform the Get Value instrument operation"""
     # check type of quantity
     if quant.name in ('S11 - Enabled', 'S21 - Enabled', 'S12 - Enabled',
                       'S22 - Enabled'):
         # update list of channels in use
         self.getActiveMeasurements()
         # get selected parameter
         param = quant.name[:3]
         value = (param in self.dMeasParam)
     elif quant.name in ('S11', 'S21', 'S12', 'S22'):
         # check if channel is on
         if quant.name not in self.dMeasParam:
             # get active measurements again, in case they changed
             self.getActiveMeasurements()
         if quant.name in self.dMeasParam:
             if self.getModel() in ('E5071C',):
                 # new trace handling, use trace numbers
                 self.writeAndLog("CALC:PAR%d:SEL" % self.dMeasParam[quant.name])
             else:
                 # old parameter handing, select parameter (use last in list)
                 sName = self.dMeasParam[quant.name][-1]
                 self.writeAndLog("CALC:PAR:SEL '%s'" % sName)
             # if not in continous mode, trig from computer
             bWaitTrace = self.getValue('Wait for new trace')
             bAverage = self.getValue('Average')
             # wait for trace, either in averaging or normal mode
             if bWaitTrace:
                 if bAverage:
                     # set channels 1-4 to set event when average complete (bit 1 start)
                     self.writeAndLog(':SENS:AVER:CLE;:STAT:OPER:AVER1:ENAB 30;:ABOR;:SENS:AVER:CLE;')
                 else:
                     self.writeAndLog(':ABOR;:INIT:CONT OFF;:INIT:IMM;')
                     self.writeAndLog('*OPC') 
                 # wait some time before first check
                 self.thread().msleep(30)
                 bDone = False
                 while (not bDone) and (not self.isStopped()):
                     # check if done
                     if bAverage:
                         sAverage = self.askAndLog('STAT:OPER:AVER1:COND?')
                         bDone = int(sAverage)>0
                     else:
                         stb = int(self.askAndLog('*ESR?'))
                         bDone = (stb & 1) > 0
                     if not bDone:
                         self.thread().msleep(100)
                 # if stopped, don't get data
                 if self.isStopped():
                     self.writeAndLog('*CLS;:INIT:CONT ON;')
                     return []
             # get data as float32, convert to numpy array
             if self.getModel() in ('E5071C',):
                 # new trace handling, use trace numbers
                 self.write(':FORM:DATA REAL32;:CALC:SEL:DATA:SDAT?', bCheckError=False)
             else:
                 # old parameter handing
                 self.write(':FORM REAL,32;CALC:DATA? SDATA', bCheckError=False)
             sData = self.read(ignore_termination=True)
             if bWaitTrace and not bAverage:
                 self.writeAndLog(':INIT:CONT ON;')
             # strip header to find # of points
             i0 = sData.find('#')
             nDig = int(sData[i0+1])
             nByte = int(sData[i0+2:i0+2+nDig])
             nData = nByte/4
             nPts = nData/2
             # get data to numpy array
             vData = np.frombuffer(sData[(i0+2+nDig):(i0+2+nDig+nByte)], 
                                   dtype='>f', count=nData)
             # data is in I0,Q0,I1,Q1,I2,Q2,.. format, convert to complex
             mC = vData.reshape((nPts,2))
             vComplex = mC[:,0] + 1j*mC[:,1]
             # get start/stop frequencies
             startFreq = self.readValueFromOther('Start frequency')
             stopFreq = self.readValueFromOther('Stop frequency')
             sweepType = self.readValueFromOther('Sweep type')
             # if log scale, take log of start/stop frequencies
             if sweepType == 'Log':
                 startFreq = np.log10(startFreq)
                 stopFreq = np.log10(stopFreq)
             # create a trace dict
             value = InstrumentQuantity.getTraceDict(vComplex, t0=startFreq,
                                            dt=(stopFreq-startFreq)/(nPts-1))
         else:
             # not enabled, return empty array
             value = InstrumentQuantity.getTraceDict([])
     elif quant.name in ('Wait for new trace',):
         # do nothing, return local value
         value = quant.getValue()
     else:
         # for all other cases, call VISA driver
         value = VISA_Driver.performGetValue(self, quant, options)
     return value
Пример #13
0
 def getTraceDict(self, vSignal):
     dSampFreq = self.getValue('Sampling rate')
     return InstrumentQuantity.getTraceDict(vSignal, t0=0, dt=1/dSampFreq)
 def getTraceDict(self, vSignal):
     return InstrumentQuantity.getTraceDict(vSignal, t0=0, dt=1/self.dSampFreq)
 def performGetValue(self, quant, options={}):
     """Perform the Get Value instrument operation"""
     # check type of quantity
     if quant.name in ("S11 - Enabled", "S21 - Enabled", "S12 - Enabled", "S22 - Enabled"):
         # update list of channels in use
         self.getActiveMeasurements()
         # get selected parameter
         param = quant.name[:3]
         value = param in self.dMeasParam
     elif quant.name in ("S11", "S21", "S12", "S22"):
         # check if channel is on
         if quant.name not in self.dMeasParam:
             # get active measurements again, in case they changed
             self.getActiveMeasurements()
         if quant.name in self.dMeasParam:
             # get trace name from parameter (use last trace in list)
             sName = self.dMeasParam[quant.name][-1]
             self.writeAndLog("CALC:PAR:SEL '%s'" % sName)
             # if not in continous mode, trig from computer
             bWaitTrace = self.getValue("Wait for new trace")
             bAverage = self.getValue("Average")
             # wait for trace, either in averaging or normal mode
             if bWaitTrace:
                 if bAverage:
                     nAverage = self.getValue("# of averages")
                     self.writeAndLog(":SENS:AVER:CLE;:ABOR;")
                 else:
                     self.writeAndLog(":ABOR;:INIT:CONT OFF;:INIT:IMM;*OPC")
                 # wait some time before first check
                 self.thread().msleep(30)
                 bDone = False
                 while (not bDone) and (not self.isStopped()):
                     # check if done
                     if bAverage:
                         sAverage = self.askAndLog("SENS:AVER:COUN:CURR?")
                         bDone = int(sAverage) >= nAverage
                     else:
                         stb = int(self.askAndLog("*ESR?"))
                         bDone = (stb & 1) > 0
                     if not bDone:
                         self.thread().msleep(100)
                 # if stopped, don't get data
                 if self.isStopped():
                     self.writeAndLog("*CLS;:INIT:CONT ON;")
                     return []
             # get data as float32, convert to numpy array
             self.write(":FORM REAL,32;CALC:DATA? SDATA", bCheckError=False)
             sData = self.read(ignore_termination=True)
             if bWaitTrace and not bAverage:
                 self.writeAndLog(":INIT:CONT ON;")
             # strip header to find # of points
             i0 = sData.find("#")
             nDig = int(sData[i0 + 1])
             nByte = int(sData[i0 + 2 : i0 + 2 + nDig])
             nData = nByte / 4
             nPts = nData / 2
             # get data to numpy array
             vData = np.frombuffer(sData[(i0 + 2 + nDig) : (i0 + 2 + nDig + nByte)], dtype=">f", count=nData)
             # data is in I0,Q0,I1,Q1,I2,Q2,.. format, convert to complex
             mC = vData.reshape((nPts, 2))
             vComplex = mC[:, 0] + 1j * mC[:, 1]
             # get start/stop frequencies
             startFreq = self.readValueFromOther("Start frequency")
             stopFreq = self.readValueFromOther("Stop frequency")
             sweepType = self.readValueFromOther("Sweep type")
             # if log scale, take log of start/stop frequencies
             if sweepType == "Log":
                 startFreq = np.log10(startFreq)
                 stopFreq = np.log10(stopFreq)
             # create a trace dict
             value = InstrumentQuantity.getTraceDict(vComplex, t0=startFreq, dt=(stopFreq - startFreq) / (nPts - 1))
         else:
             # not enabled, return empty array
             value = InstrumentQuantity.getTraceDict([])
     elif quant.name in ("Wait for new trace",):
         # do nothing, return local value
         value = quant.getValue()
     else:
         # for all other cases, call VISA driver
         value = VISA_Driver.performGetValue(self, quant, options)
     return value
    def performGetValue(self, quant, options={}):
        """Perform the Get Value instrument operation"""
        try:
            # proceed depending on command
            if quant.name == 'RF Frequency 1':
                value = self.f[0]
            elif quant.name == 'RF Frequency 2':
                value = self.f[1]
            elif quant.name == 'RF Frequency 3':
                value = self.f[2]
            elif quant.name == 'Max input level':
                value = self.digitizer1.rf_rf_input_level_get()
            elif quant.name == 'Sampling rate':
                value = self.digitizer1.modulation_generic_sampling_frequency_get()
            elif quant.name == 'Number of samples':
                value = self.samples

            elif quant.name == 'Remove DC offset':
                value = self.digitizer1.rf_remove_dc_offset_get()
            elif quant.name == 'Trigger Source':
                value = self.digitizer1.trigger_source_get()
                value = quant.getValueString(value)
            elif quant.name == 'Number of triggers':
                value = self.triggers
            elif quant.name == 'Power1Mean':
                if self.powerMean[0] == 0:
                    self.sampleAndAverageSingle(0)
                value = self.powerMean[0]
                self.powerMean[0] = 0
            elif quant.name == 'Power2Mean':
                if self.powerMean[1] == 0:
                    self.sampleAndAverageSingle(1)
                value = self.powerMean[1]
                self.powerMean[1] = 0
            elif quant.name == 'Power3Mean':
                if self.powerMean[2] == 0:
                    self.sampleAndAverageSingle(2)
                value = self.powerMean[2]
                self.powerMean[2] = 0
            elif quant.name == 'Psi12':
                if self.Psi[0,1] == 0:
                    self.sampleAndAverage(0,1)
                value = self.Psi[0,1]
                self.Psi[0,1] = 0
            elif quant.name == 'Psi13':
                if self.Psi[0,2] == 0:
                    self.sampleAndAverage(0,2)
                value = self.Psi[0,2]
                self.Psi[0,2] = 0
            elif quant.name == 'Psi23':
                if self.Psi[1,2] == 0:
                    self.sampleAndAverage(1,2)
                value = self.Psi[1,2]
                self.Psi[1,2] = 0
            elif quant.name =='OMS1':
                if self.oms[0] == 0:
                    self.sampleAndAverageSingle(0)
                value = self.oms[0]
                self.oms[0] = 0
            elif quant.name =='OMS2':
                if self.oms[1] == 0:
                    self.sampleAndAverageSingle(1)
                value = self.oms[1]
                self.oms[1] = 0
            elif quant.name =='OMS3':
                if self.oms[2] == 0:
                    self.sampleAndAverageSingle(2)
                value = self.oms[2]
                self.oms[2] = 0           
            elif quant.name == 'Covar':
                if 0 in self.covar:
                    self.sampleAndAverage(0, 1)
                    self.sampleAndAverage(0, 2)
                    self.sampleAndAverage(1, 2)
                value = self.covar
                self.covar = [0]*48
            elif quant.name == 'Time1':
                value = self.getTimeTrace(0)
            elif quant.name == 'Time2':
                value = self.getTimeTrace(1) 
            elif quant.name == 'Time3':
                value = self.getTimeTrace(2)
                
            elif quant.name == 'IITime12':
                if self.IITime == []:
                    self.sampleAndAverage(0,1)
                value = InstrumentQuantity.getTraceDict(self.IITime, t0=-self.samples/2/self.digitizer1.modulation_generic_sampling_frequency_get(), dt=1/self.digitizer1.modulation_generic_sampling_frequency_get())
                self.IITime = []
                
            return value
        except afDigitizerWrapper.Error as e:
            # re-cast errors as a generic communication error
            msg = str(e)
            raise InstrumentDriver.CommunicationError(msg)
Пример #17
0
    def performGetValue(self, quant, options={}):
        """Perform the Get Value instrument operation"""
        # check type of quantity
        #        if quant.name in ('Zero-span mode',)
        time.sleep(0.1)
        if quant.name == "Reset Device To Default":
            return False
        if quant.name in ("Measurement Group"):
            dict = ["FFT", "Correlation", "Octave", "Swept Sine", "Order", "Time Histogram"]

            time.sleep(0.1)
            value = self.askAndLog("MGRP ? 0")
            time.sleep(0.1)
            return value + " " + dict[int(value)]
        if quant.name in ("FFT", "Correlation", "Octave", "Swept Sine", "Order", "Time Histogram"):
            dict = [
                "FFT 1",
                "FFT 2",
                "Power Spectrum 1",
                "Power Spectrum 2",
                "Time 1",
                "Time 2",
                "Windowed Time 1",
                "Windowed Time 2",
                "Orbit",
                "Coherence",
                "Cross Spectrum",
                "Frequency Response",
                "Capture Buffer 1",
                "Capture Buffer 2",
                "FFT User Function 1",
                "FFT User Function 2",
                "FFT User Function 3",
                "FFT User Function 4",
                "FFT User Function 5",
                "Auto Correlation 1",
                "Auto Correlation 2",
                "Cross Correlation",
                "Time 1",
                "Time 2",
                "Windowed Time 1",
                "Windowed Time 2",
                "Capture Buffer 1",
                "Capture Buffer 2",
                "Correlation Function 1",
                "Correlation Function 2",
                "Correlation Function 3",
                "Correlation Function 4",
                "Correlation Function 5",
                "Octave 1",
                "Octave 2",
                "Capture 1Capture 2",
                "Octave User Function 1",
                "Octave User Function 2",
                "Octave User Function 3",
                "Octave User Function 4",
                "Octave User Function 5",
                "Spectrum 1",
                "Spectrum 2",
                "Normalized Variance 1",
                "Normalized Variance 2",
                "Cross Spectrum",
                "Frequency Response",
                "Swept Sine User Function 1",
                "Swept Sine User Function 2",
                "Swept Sine User Function 3",
                "Swept Sine User Function 4",
                "Swept Sine User Function 5",
                "Linear Spectrum 1",
                "Linear Spectrum 2",
                "Power Spectrum 1",
                "Power Spectrum 2",
                "Time 1",
                "Time 2",
                "Windowed Time 1",
                "Windowed Time 2",
                "RPM Profile",
                "Orbit",
                "Track 1",
                "Track 2",
                "Capture Buffer 1",
                "Capture Buffer 2",
                "Order User Function 1",
                "Order User Function 2",
                "Order User Function 3",
                "Order User Function 4",
                "Order User Function 5",
                "Histogram 1",
                "Histogram 2",
                "PDF 1",
                "PDF 2",
                "CDF 1",
                "CDF 2",
                "Time 1",
                "Time 2",
                "Capture Buffer 1",
                "Capture Buffer 2",
                "Histogram User Function 1",
                "Histogram User Function 2",
                "Histogram User Function 3",
                "Histogram User Function 4",
                "Histogram User Function 5",
            ]
            time.sleep(0.1)
            value = self.askAndLog("MEAS ? 0")
            time.sleep(0.1)
            return value + " " + dict[int(value)]
        if quant.name in ("View Type"):
            dict = [
                "Log Magnitude",
                "Linear Magnitude",
                "Magnitude Squared",
                "Real Part",
                "Imaginary Part",
                "Phase",
                "Unwrapped Phase",
                "Nyquist",
                "Nichols",
            ]
            value = self.askAndLog("VIEW ? 0")
            time.sleep(0.1)
            return value + " " + dict[int(value)]
        if quant.name in ("Unit dB"):
            dict = ["Off", "dB", "dBm", "dBspl"]
            value = self.askAndLog("UNDB ? 0")
            time.sleep(0.1)
            return value + " " + dict[int(value)]
        if quant.name in ("Unit pk"):
            dict = ["Off", "pk", "rms", "pp"]
            value = self.askAndLog("UNPK ? 0")
            time.sleep(0.1)
            # self.writeAndLog(value)
            return value + " " + dict[int(value)]
        if quant.name in ("Unit psd"):
            dict = ["Off", "psd"]
            value = self.askAndLog("PSDU ? 0")
            time.sleep(0.1)
            self.writeAndLog(value)
            return value + " " + dict[int(value)]
        if quant.name in ("phase units"):
            dict = ["Degrees", "Radians"]
            value = self.askAndLog("UNPH ? 0")
            time.sleep(0.1)
            return value + " " + dict[int(value)]
        if quant.name in ("SS Start Frequency"):
            return self.askAndLog("SSTR ? 0")
        if quant.name in ("SS Stop Frequency"):
            return self.askAndLog("SSTP ? 0")
        if quant.name in ("SS Continuous Scan"):
            dict = [False, True]
            value = self.askAndLog("SRPT ? 0")
            return dict[int(value)]
        if quant.name in ("SS Sweep Type"):
            return self.askAndLog("SSTY ? 0")
        if quant.name in ("SS Number Of Points"):
            return self.askAndLog("SNPS ? 0")
        if quant.name in ("SS Auto Resolution"):
            dict = [False, True]
            value = self.askAndLog("SARS ? 0")
            return dict[int(value)]
        if quant.name in ("SS Maximum Skips"):
            return self.askAndLog("SSKP ? 0")
        if quant.name in ("SS Faster Threshold"):
            return self.askAndLog("SFST ? 0")
        if quant.name in ("SS Lower Threshold"):
            return self.askAndLog("SSLO ? 0")
        if quant.name in ("SS Auto Level Reference*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            dict = ["Off", "Channel 1", "Channel 2"]
            value = self.askAndLog("SSAL?")
            return value + " " + dict[int(value)]
        if quant.name in ("SS Amplitude*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            return self.askAndLog("SSAM ?")
        if quant.name in ("SS Ideal Reference*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            return self.askAndLog("SSRF ?")
        if quant.name == "SS Source Ramping*":
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            return self.askAndLog("SRMP ?")
        if quant.name == "SS Source Ramping Rate*":
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            return self.askAndLog("SRAT ?")
        if quant.name in ("SS Reference Upper Limit*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            return self.askAndLog("SSUL ?")
        if quant.name in ("SS Reference Lower Limit*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            return self.askAndLog("SSLL ?")
        if quant.name in ("SS Maximum Level*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            return self.askAndLog("SMAX ?")
        if quant.name in ("SS Offset*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            return self.askAndLog("SOFF ?")
        if quant.name in ("SS Settle Time"):
            return self.askAndLog("SSTM ? 0")
        if quant.name in ("SS Settle Cycles"):
            return self.askAndLog("SSCY ? 0")
        if quant.name in ("SS Integration Time"):
            return self.askAndLog("SITM ? 0")
        if quant.name in ("SS Integration Cycles"):
            return self.askAndLog("SICY ? 0")
        if quant.name in ("Source On/Off"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            if int(self.askAndLog("SRCO ?")) == 1:
                return True
            return False
        if quant.name in ("Source Type"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            dict = ["0 Sine", "1 Chirp", "2 Noise", "3 Arbitrary"]
            value = self.askAndLog("STYP?")
            return value + " " + dict[int(value)]
        if quant.name in ("FC Frequency Span"):
            return self.askAndLog("FSPN ? 0")
        if quant.name in ("FC Resolution"):
            dict = ["100", "200", "400", "800"]
            value = self.askAndLog("FLIN ? 0")
            return value + " " + dict[int(value)]
        if quant.name in ("FC Base Frequency"):
            dict = ["100 kHz", "102.4 kHz"]
            value = self.askAndLog("FBAS ? 0")
            return value + " " + dict[int(value)]
        if quant.name in ("F Center Frequency"):
            return self.askAndLog("FCTR ? 0")
        if quant.name in ("F Unsettle Measurement"):
            return False  #
        if quant.name in ("FC Compute Average"):
            if int(self.askAndLog("FAVG ? 0")) == 1:
                return True
            return False
        if quant.name in ("FC Type Of Averaging"):
            dict = ["None", "Vector", "RMS", "Peak Hold"]
            value = self.askAndLog("FAVM ? 0")
            return value + " " + dict[int(value)]
        if quant.name in ("FC FFT Average Type"):
            dict = ["Linear/Fixed Length", "Exponential/Continuous"]
            value = self.askAndLog("FAVT ? 0")
            return value + " " + dict[int(value)]
        if quant.name in ("FC Number Of Averages"):
            return self.askAndLog("FAVN ? 0")
        if quant.name in ("F Time Record Increment"):
            return self.askAndLog("FOVL ? 0")
        if quant.name in ("FC Overload Reject"):
            return self.askAndLog("FREJ ? 0")
        if quant.name in ("FC Trigger Average Mode"):
            dict = ["Time Records", "Averages"]
            value = self.askAndLog("TAVM ? 0")
            return value + " " + dict[int(value)]
        if quant.name in ("FC Average Preview*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            dict = ["Off", "Manual", "Timed"]
            value = self.askAndLog("PAVO ?")
            return value + " " + dict[int(value)]
        if quant.name in ("FC Preview Time*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            return self.askAndLog("PAVT ? 0")
        if quant.name in ("Analyzer Configuration*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            dict = ["Independent Channels", "Dual Channels"]
            value = self.askAndLog("LINK ?")
            return value + " " + dict[int(value)]
        if quant.name in ("Input Auto Offset*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            if int(self.askAndLog("IAOM ?")) == 1:
                return True
            return False
        if quant.name in ("Ch1 Input Mode*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            dict = ["A (single-ended)", "A-B (differential)"]
            value = self.askAndLog("I1MD ?")
            return value + " " + dict[int(value)]
        if quant.name in ("Ch1 Input Grounding*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            dict = ["Float", "Ground"]
            value = self.askAndLog("I1GD ?")
            return value + " " + dict[int(value)]
        if quant.name in ("Ch1 Input Coupling*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            dict = ["DC", "AC", "ICP"]
            value = self.askAndLog("I1CP ?")
            return value + " " + dict[int(value)]
        if quant.name in ("Ch1 Anti-Aliasing Filter*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            if int(self.askAndLog("I1AF ?")) == 1:
                return True
            return False
        if quant.name in ("Ch1 A-Weighting Filter*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            if int(self.askAndLog("I1AW ?")) == 1:
                return True
            return False
        if quant.name in ("Ch2 Input Mode*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            dict = ["A (single-ended)", "A-B (differential)"]
            value = self.askAndLog("I2MD ?")
            return value + " " + dict[int(value)]
        if quant.name in ("Ch2 Input Grounding*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            dict = ["Float", "Ground"]
            value = self.askAndLog("I2GD ?")
            return value + " " + dict[int(value)]
        if quant.name in ("Ch2 Input Coupling*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            dict = ["DC", "AC", "ICP"]
            value = self.askAndLog("I2CP ?")
            return value + " " + dict[int(value)]
        if quant.name in ("Ch2 Anti-Aliasing Filter*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            if int(self.askAndLog("I2AF ?")) == 1:
                return True
            return False
        if quant.name in ("Ch2 A-Weighting Filter*"):
            return self.getValue(quant.name)  # return internal value, since SSAL? not working in Labber
            if int(self.askAndLog("I2AW ?")) == 1:
                return True
            return False
        if quant.name in ("Start New Measurement"):
            return True

        if quant.name in ("Signal"):
            # self.writeAndLog('SVTR 0, 1') # save trace from display 0 to trace 1
            # self.write('TLOD ? 1') # get trace 1
            # self.write('TGET ? 1') # get trace 1, multiples of 4-byte binary, start: bin 0, followed by floating point numbers
            # self.write('DSPY ? 0') # read data as ASCII, separated by commas
            # 	if sData[i] == -3.4028235e+38:
            # 		nirvana = sData.pop(i)
            # 		self.writeAndLog(str(sData[i]))
            # self.writeAndLog(str(sData))
            sData = self.askAndLog("DSPY ? 0")
            sData = sData.split(",")
            for i in xrange(len(sData)):
                sData[i] = float(sData[i])
            xData = sData
            if self.getValue("Measurement Group") == "3 Swept Sine":
                del sData[-1]
                while -3.4028235e38 in xData:
                    xData.remove(-3.4028235e38)
                while 0 in sData:
                    xData.remove(0)
                xData = np.asarray(xData)
                startFreq = self.getValue("SS Start Frequency")
                stopFreq = self.getValue("SS Stop Frequency")
                nPts = self.getValue("SS Number Of Points")
            if self.getValue("Measurement Group") == "0 FFT":
                while -3.4028235e38 in xData:
                    xData.remove(-3.4028235e38)
                while 0 in sData:
                    xData.remove(0)
                xData = np.asarray(xData)
                startFreq = self.getValue("F Center Frequency") - self.getValue("FC Frequency Span") / 2.0
                stopFreq = self.getValue("F Center Frequency") + self.getValue("FC Frequency Span") / 2.0
                nPts = len(sData)
            if self.getValue("Measurement Group") == "1 Correlation":
                # while -3.4028235e+38 in xData:
                # xData.remove(-3.4028235e+38)
                # while 0 in sData:
                # xData.remove(0)
                xData = np.asarray(xData)
                startFreq = 0
                stopFreq = self.getValue("FC Frequency Span")
                nPts = len(sData)

            value = InstrumentQuantity.getTraceDict(xData, t0=startFreq, dt=(stopFreq - startFreq) / (nPts - 1))
            return value
        else:
            self.writeAndLog("ERROR ERROR ERROR: " + str(quant.name))
            return None
            # for all other cases, call VISA driver
            # value = VISA_Driver.performGetValue(self, quant, options)
        return value
Пример #18
0
 def performGetValue(self, quant, options={}):
     """Perform the Get Value instrument operation"""
     aqType = self.getValue('Acquisition type')
     if quant.name == 'Acquisition type':
         value = quant.getValueFromCmdString(str(self.dig.getMode()[0]))
     elif quant.name == 'Number of samples':
         if aqType == 'Normal':
             value = float(self.dig.getMemory()[0])
         else:
             value = float(self.dig.getAvgConfig(1, 'NbrSamples'))
     elif quant.name == 'Number of segments':
         if aqType == 'Normal':
             value = float(self.dig.getMemory()[1])
         else:
             value = float(self.dig.getAvgConfig(1, 'NbrSegments'))
     elif quant.name == 'Number of averages':
         value = float(self.dig.getAvgConfig(1, 'NbrWaveforms'))
     elif quant.name == 'Sample interval':
         value = float(self.dig.getHorizontal()[0])
     elif quant.name == 'Delay time':
         if aqType == 'Normal':
             value = float(self.dig.getHorizontal()[1])
         else:
             # convert from delay in points to delay in time
             sampInterval = self.getValue('Sample interval')
             value = sampInterval * self.dig.getAvgConfig(1, 'StartDelay')
     elif quant.name == 'Trig source':
         pattern = abs(self.dig.getTrigClass()[0])
         dPattern = {0x00000001L: 1, 0x00000002L: 2, 0x80000000L: -1}
         value = quant.getValueFromCmdString(str(dPattern[pattern]))
     elif quant.name == 'Trig coupling':
         # get from current trig source
         trigSource = int(self.getCmdStringFromValue('Trig source'))
         value = quant.getValueFromCmdString( \
                 str(self.dig.getTrigSource(trigSource)[0]))
     elif quant.name == 'Trig slope':
         # get from current trig source
         trigSource = int(self.getCmdStringFromValue('Trig source'))
         value = quant.getValueFromCmdString( \
                 str(self.dig.getTrigSource(trigSource)[1]))
     elif quant.name == 'Trig level':
         # get from current trig source
         trigSource = int(self.getCmdStringFromValue('Trig source'))
         trigLevel = self.dig.getTrigSource(trigSource)[2]
         # if Ch1/Ch2, trig level is percentage of full range
         if trigSource == 1:
             fullRange = float(self.getCmdStringFromValue('Ch1 - Range'))
             offset = float(self.getValue('Ch1 - Offset'))
             value = offset + fullRange*trigLevel/100.0
         elif trigSource == 2:
             fullRange = float(self.getCmdStringFromValue('Ch2 - Range'))
             offset = float(self.getValue('Ch2 - Offset'))
             value = offset + fullRange*trigLevel/100.0
         else:
             # trig level is in millivolt
             value = trigLevel/1000.0
     elif quant.name in ('10 MHz Reference'):
         # get values from relevant quants and set all
         value = quant.getValueFromCmdString(str(self.dig.getExtClock()[0]))
     elif quant.name == 'Ch1 - Enabled':
         # do nothing for enabling/disabling
         value = quant.getValue()
     elif quant.name == 'Ch1 - Coupling':
         value = quant.getValueFromCmdString(str(self.dig.getVertical(1)[2]))
     elif quant.name == 'Ch1 - Bandwidth':
         value = quant.getValueFromCmdString(str(self.dig.getVertical(1)[3]))
     elif quant.name == 'Ch1 - Range':
         value = quant.getValueFromCmdString('%.2f' % self.dig.getVertical(1)[0])
     elif quant.name == 'Ch1 - Offset':
         value = - self.dig.getVertical(1)[1]
     elif quant.name == 'Ch2 - Enabled':
         # do nothing
         value = quant.getValue()
     elif quant.name == 'Ch2 - Coupling':
         value = quant.getValueFromCmdString(str(self.dig.getVertical(2)[2]))
     elif quant.name == 'Ch2 - Bandwidth':
         value = quant.getValueFromCmdString(str(self.dig.getVertical(2)[3]))
     elif quant.name == 'Ch2 - Range':
         value = quant.getValueFromCmdString('%.2f' % self.dig.getVertical(2)[0])
     elif quant.name == 'Ch2 - Offset':
         value = - self.dig.getVertical(2)[1]
     # signals
     elif quant.name in self.lSignalNames:
         indx = self.lSignalNames.index(quant.name)
         # check if first call, if so get new traces
         if self.isFirstCall(options):
             self.getTraces()
         # return correct data
         if quant.name in ('Ch1 - Data', 'Ch2 - Data'):
             value = InstrumentQuantity.getTraceDict(self.lTrace[indx], dt=self.dt)
         else:
             value = self.lTrace[indx]
     elif quant.name in ('Modulation frequency', 'Skip start', 'Length',
                         'Use Ch2 as reference', 'Enable demodulation'):
         # just return the quantity value
         value = quant.getValue()
     return value
Пример #19
0
	def performGetValue(self, quant, options={}):
		"""Perform the Get Value instrument operation"""
		# check type of quantity
		#if quant.name in ('Zero-span mode',):
		if quant.name in ('Range type',):
			# check if span is zero
			span = self.readValueFromOther('Span')
			if span == 0:
				value = 'Zero-span mode'
			else:
				# return old value if not in zero span
				value = quant.getValueString()
				if value == 'Zero-span mode':
					value = 'Center - Span'
		elif quant.name in ('Signal', 'Signal - Zero span'):
			# if not in continous mode, trig from computer
			bWaitTrace = self.getValue('Wait for new trace')
			bAverage = self.getValue('Average')
			# wait for trace, either in averaging or normal mode
			if bAverage:
				# clear averages
				self.writeAndLog(':SENS:AVER:CLE;')
				self.writeAndLog(':ABOR;:INIT:CONT OFF;:INIT:IMM;*OPC')
				# wait some time before first check
				self.thread().msleep(30)
				bDone = False
				while (not bDone) and (not self.isStopped()):
					# check if done
					stb = int(self.askAndLog('*ESR?'))
					bDone = (stb & 1) > 0
					if not bDone:
						self.thread().msleep(50)
				# if stopped, don't get data
				if self.isStopped():
					self.writeAndLog('*CLS;:INIT:CONT ON;')
					return []
			# get data as float32, convert to numpy array
			self.write(':FORM REAL,32;TRAC:DATA? TRACE1', bCheckError=False)
			sData = self.read(ignore_termination=True)
			if bWaitTrace and not bAverage:
				self.writeAndLog(':INIT:CONT ON;')
			# strip header to find # of points
			i0 = sData.find('#')
			nDig = int(sData[i0+1])
			nByte = int(sData[i0+2:i0+2+nDig])
			nPts = nByte/4
			# get data to numpy array
			vData = np.frombuffer(sData[(i0+2+nDig):(i0+2+nDig+nByte)],
											dtype='>f', count=nPts)
			# get start/stop frequencies
			startFreq = self.readValueFromOther('Start frequency')
			stopFreq = self.readValueFromOther('Stop frequency')
            # sweepType = self.readValueFromOther('Sweep type')
            # # if log scale, take log of start/stop frequencies
            # if sweepType == 'Log':
                # startFreq = np.log10(startFreq)
                # stopFreq = np.log10(stopFreq)
            # check if return trace or trace average
			if quant.name == 'Signal - Zero span':
				# return average
				value = np.average(vData)
			else:
				# create a trace dict
				value = InstrumentQuantity.getTraceDict(vData, t0=startFreq, 
																		  dt=(stopFreq-startFreq)/(nPts-1))
		elif quant.name in ('Signal - CW'):
			# if not in continous mode, trig from computer
			bWaitTrace = self.getValue('Wait for new trace')
			bAverage = self.getValue('Average CW')
			# wait for trace, either in averaging or normal mode
			if bAverage:
				# clear averages
				self.writeAndLog(':WAV:AVER:CLE;')
				self.writeAndLog(':ABOR;:INIT:CONT OFF;:INIT:IMM;*OPC')
				# wait some time before first check
				self.thread().msleep(30)
				bDone = False
				while (not bDone) and (not self.isStopped()):
					# check if done
					stb = int(self.askAndLog('*ESR?'))
					bDone = (stb & 1) > 0
					if not bDone:
						self.thread().msleep(50)
				# if stopped, don't get data
				if self.isStopped():
					self.writeAndLog('*CLS;:INIT:CONT ON;')
					return []
			# get data as float32, convert to numpy array
			sTraceNum = self.getTraceDict(quant)
			sWrite = ':FORM REAL,32;READ:WAV'+sTraceNum+'?'
			self.write(sWrite, bCheckError=False)
			sData = self.read(ignore_termination=True)
			if bWaitTrace and not bAverage:
				self.writeAndLog(':INIT:CONT ON;')
			# strip header to find # of points
			i0 = sData.find('#')
			nDig = int(sData[i0+1])
			nByte = int(sData[i0+2:i0+2+nDig])
			nPts = nByte/4
			# get data to numpy array
			vData = np.frombuffer(sData[(i0+2+nDig):(i0+2+nDig+nByte)],
											dtype='>f', count=nPts)
			# get start/stop frequencies
			#duration = self.readValueFromOther('Measurement Time IQ')
			sampleFreq = self.readValueFromOther('Sample Rate CW')
            # sweepType = self.readValueFromOther('Sweep type')
            # # if log scale, take log of start/stop frequencies
            # if sweepType == 'Log':
                # startFreq = np.log10(startFreq)
                # stopFreq = np.log10(stopFreq)
            # check if return trace or trace average
			# create a trace dict
			if self.getValue('Trace type CW') == 'unprocessed IQ trace data (V)':
				#the trace is complex.  I values are even indices while Q values are odd indices.
				realData = vData[0:nPts:2]
				imagData = vData[1:nPts:2]
				cData = realData +1j*imagData
				samplePeriod = (2/sampleFreq)
			else:
				#the trace is a simple vector.
				cData = vData +1j*np.zeros(vData.shape)
				samplePeriod = (1/sampleFreq)
			
			value = InstrumentQuantity.getTraceDict(cData, t0=0.0, dt=samplePeriod)
			
		elif quant.name in ('Signal - CS'):
			# if not in continous mode, trig from computer
			bWaitTrace = self.getValue('Wait for new trace')
			bAverage = self.getValue('Average CS')
			# wait for trace, either in averaging or normal mode
			if bAverage:
				# clear averages
				self.writeAndLog(':SPEC:AVER:CLE;')
				self.writeAndLog(':ABOR;:INIT:CONT OFF;:INIT:IMM;*OPC')
				# wait some time before first check
				self.thread().msleep(30)
				bDone = False
				while (not bDone) and (not self.isStopped()):
					# check if done
					stb = int(self.askAndLog('*ESR?'))
					bDone = (stb & 1) > 0
					if not bDone:
						self.thread().msleep(50)
				# if stopped, don't get data
				if self.isStopped():
					self.writeAndLog('*CLS;:INIT:CONT ON;')
					return []
			# get data as float32, convert to numpy array
			sTraceNum = self.getTraceDict(quant)
			sWrite = ':FORM REAL,32;READ:SPEC'+sTraceNum+'?'
			self.write(sWrite, bCheckError=False)
			sData = self.read(ignore_termination=True)
			if bWaitTrace and not bAverage:
				self.writeAndLog(':INIT:CONT ON;')
			# strip header to find # of points
			i0 = sData.find('#')
			nDig = int(sData[i0+1])
			nByte = int(sData[i0+2:i0+2+nDig])
			nPts = nByte/4
			# get data to numpy array
			vData = np.frombuffer(sData[(i0+2+nDig):(i0+2+nDig+nByte)],
											dtype='>f', count=nPts)
			# get start/stop frequencies
			#duration = self.readValueFromOther('Measurement Time IQ')
			centerFreq = self.getValue('Center frequency CS')
			span = self.getValue('Span CS')
			startFreq = centerFreq - span/2
			stopFreq = centerFreq + span/2
            # sweepType = self.readValueFromOther('Sweep type')
            # # if log scale, take log of start/stop frequencies
            # if sweepType == 'Log':
                # startFreq = np.log10(startFreq)
                # stopFreq = np.log10(stopFreq)
            # check if return trace or trace average
			# create a trace dict
			if self.getValue('Trace type CS') in ('unprocessed IQ trace data (V)', 'processed I/Q trace vs. time'):
				#the trace is complex.  I values are even indices while Q values are odd indices.
				realData = vData[0:nPts:2]
				imagData = vData[1:nPts:2]
				cData = realData +1j*imagData
				nPts_new = nPts/2
			else:
				#the trace is a simple vector.
				cData = vData +1j*np.zeros(vData.shape)
				nPts_new = nPts
				
			if self.getValue('Trace type CS') in ('log-mag vs. Freq.', 'avged log-mag vs. Freq.', 'phase of FFT vs. Freq.', 'linear spectrum (V RMS)', 'avged linear spectrum (V RMS)'):
				startValue=startFreq
				delta=(stopFreq-startFreq)/(nPts_new-1)
			else:
				startValue=0
				delta = 1
				
				
			value = InstrumentQuantity.getTraceDict(cData, t0=startValue, 
																		  dt=delta)
			
		elif quant.name in ('Wait for new trace',):
			# do nothing, return local value
			value = quant.getValue()
		elif quant.name in ('Trace type CS', 'Trace type CW', 'Measurement Type'):
			value = self.getValue(quant.name)
		else:
			# for all other cases, call VISA driver
			value = VISA_Driver.performGetValue(self, quant, options)
		return value
    def performGetValue(self, quant, options={}):
        """Perform the Get Value instrument operation"""
        self.log(options)
        self.log(self.isFirstCall(options))

        attr=getattr(self, quant.name, None)
        if attr is not None:
            return attr.receive()
        elif quant.name == "Output enabled":
            return bool(int(self.askVNA(":OUTP?")))
        elif quant.name in self.S_enabled_names:            
            key=quant.name[:3]#('S11 - Enabled', 'S21 - Enabled', 'S12 - Enabled', 'S22 - Enabled'):
            return self.S_enabled[key]
            #return self.getValue(quant.name)                  
                # update list of channels in use
                #self.getActiveMeasurements()
                # get selected parameter
                #param = quant.name[:3]
                #value = param in self.dMeasParam
        elif quant.name in self.measDict: #('S11', 'S21', 'S12', 'S22'):
            if self.isFirstCall(options):
                #resets cData on first call
                self.cData=None
            if quant.name not in self.cData:
                #resets cData if parameter not in data
                self.acquire_data()
            data=self.cData.get(quant.name, [])
            #if data==[]:
            #    return InstrumentQuantity.getTraceDict()
            #if quant.name in self.cData:
            self.log(InstrumentQuantity.getTraceDict.__doc__)
            return InstrumentQuantity.getTraceDict(data, t0=self.t0, dt=self.dt)
            #else:
                    # not enabled, return empty array
                #    value = InstrumentQuantity.getTraceDict([])
                #return self.cData[quant.name]
                    #if options.get("call_no", 0)==0:
                    #self.dMeasParam={}
                    # check if channel is on
                    #if quant.name not in self.dMeasParam:
                    # get active measurements again, in case they changed
                #    self.getActiveMeasurements()
                #if quant.name in self.dMeasParam:
                #    if self.getModel() in ('E5071C',):
                        # new trace handling, use trace numbers
                #        self.writeVNA("CALC:PAR%d:SEL" % self.dMeasParam[quant.name])
                #    else:
                        # old parameter handing, select parameter (use last in list)
                #        sName = self.dMeasParam[quant.name][-1]
                #        self.writeVNA("CALC:PAR:SEL '%s'" % sName)
                    # if not in continous mode, trig from computer
                #    bWaitTrace = self.getValue('Wait for new trace')
                #    bAverage = self.getValue('Average')
                    # wait for trace, either in averaging or normal mode
                #    if bWaitTrace:
                #        if bAverage:
                            # set channels 1-4 to set event when average complete (bit 1 start)
                #            self.writeVNA(':SENS:AVER:CLE;:STAT:OPER:AVER1:ENAB 30;:ABOR;:SENS:AVER:CLE;')
                #        else:
                #            self.writeVNA(':ABOR;:INIT:CONT OFF;:INIT:IMM;')
                #            self.writeVNA('*OPC')
                        # wait some time before first check
                #        self.thread().msleep(30)
                #        bDone = False
                #        while (not bDone) and (not self.isStopped()):
                            # check if done
                #            if bAverage:
                #                sAverage = self.askVNA('STAT:OPER:AVER1:COND?')
                #                bDone = int(sAverage)>0
                #            else:
                #                stb = int(self.askVNA('*ESR?'))
                #                bDone = (stb & 1) > 0
                #            if not bDone:
                #                self.thread().msleep(100)
                        # if stopped, don't get data
                #        if self.isStopped():
                #            self.writeVNA('*CLS;:INIT:CONT ON;')
                #            return []
                    # get data as float32, convert to numpy array
                #    if self.getModel() in ('E5071C',):
                #        # new trace handling, use trace numbers
                #        self.writeVNA(':FORM:DATA REAL32;:CALC:SEL:DATA:SDAT?')#, bCheckError=False)
                #    else:
                        # old parameter handing
               #         self.writeVNA(':FORM REAL,32;CALC:DATA? SDATA')#, bCheckError=False)
               #     sData = self.readVNA()#ignore_termination=True)
               #     self.log(sData)
               #     if bWaitTrace and not bAverage:
               #         self.writeVNA(':INIT:CONT ON;')
                    # strip header to find # of points
               #     i0 = sData.find('#')
               #     nDig = int(sData[i0+1])
               #     nByte = int(sData[i0+2:i0+2+nDig])
               #     nData = nByte/4
               #     nPts = nData/2
                    # get data to numpy array
               #     vData = np.frombuffer(sData[(i0+2+nDig):(i0+2+nDig+nByte)],
               #                           dtype='>f', count=nData)
                    # data is in I0,Q0,I1,Q1,I2,Q2,.. format, convert to complex
#                    mC = vData.reshape((nPts,2))
#                    vComplex = mC[:,0] + 1j*mC[:,1]
#                    # get start/stop frequencies
#                    startFreq = self.fStartFrequency #self.readValueFromOther('Start frequency')
#                    stopFreq = self.fStopFrereadValueFromOther('Stop frequency')
#                    sweepType = self.readValueFromOther('Sweep type')
#                    # if log scale, take log of start/stop frequencies
#                    if sweepType == 'Log':
#                        startFreq = np.log10(startFreq)
#                        stopFreq = np.log10(stopFreq)
#                    # create a trace dict
#                    value = InstrumentQuantity.getTraceDict(vComplex, t0=startFreq,
#                                                   dt=(stopFreq-startFreq)/(nPts-1))
#                else:
#                    # not enabled, return empty array
#                    value = InstrumentQuantity.getTraceDict([])
            #elif quant.name in ('Wait for new trace',):
                # do nothing, return local value
            #    value = quant.getValue()
            #else:
                # for all other cases, call VISA driver
            #    value = VISA_Driver.performGetValue(self, quant, options)
        return value
Пример #21
0
 def getTraceDict(self, vSignal):
     dSampFreq = self.digitizer1.modulation_generic_sampling_frequency_get()
     return InstrumentQuantity.getTraceDict(vSignal, t0=0, dt=1/dSampFreq)