def setupDaqTasks(self): self.magnetVControlTask = daq.AoTask('Magnet voltage control task') self.magnetVControlTask.addChannel(self.magnetVoltageControlChannel) self.disableFeedbackTask = daq.DoTask('Feedback disable task') self.disableFeedbackTask.addChannel(self.doLineDisableFeedback) self.resetIntegratorTask = daq.DoTask('Reset control') self.resetIntegratorTask.addChannel(self.doLineResetIntegrator) self.outputVoltageControlTask = daq.AoTask( 'Supply voltage control task') self.outputVoltageControlTask.addChannel( self.outputVoltageControlChannel) timing = daq.Timing(rate=50000, samplesPerChannel=self.samplesPerChannel) timing.setSampleMode(timing.SampleMode.FINITE) aiTask = daq.AiTask('AI Task FET Output') aiTask.addChannel(self.fetOutputMonitorChannel) aiTask.configureTiming(timing) self.aiTaskFetOutput = aiTask aiTask = daq.AiTask('AI Task Current Coarse') aiTask.addChannel(self.currentChannelCoarse) aiTask.configureTiming(timing) self.aiTaskCurrentCoarse = aiTask aiTask = daq.AiTask('AI Task Current Fine') aiTask.addChannel(self.currentChannelFine) aiTask.configureTiming(timing) self.aiTaskCurrentFine = aiTask aiTask = daq.AiTask('AI Task Magnet Voltage') aiTask.addChannel(self.magnetVoltageChannel) aiTask.configureTiming(timing) self.aiTaskMagnetVoltage = aiTask
def run(self): self.stopRequested = False hwm = 3 # Half-water mark (i.e. the number of chunks we try to keep buffered) try: queue = Queue.Queue() self.__logger.debug('Producer starting') d = daq.Device(self.deviceName) chunkSize = self.chunkSize timing = daq.Timing(rate = self.sampleRate, samplesPerChannel = chunkSize) timing.setSampleMode(timing.SampleMode.CONTINUOUS) aoChannel = daq.AoChannel('%s/%s' % (self.deviceName, self.aoChannel), self.aoRange.min, self.aoRange.max) aiChannel = daq.AiChannel('%s/%s' % (self.deviceName, self.aiChannel), self.aiRange.min, self.aiRange.max) aiChannel.setTerminalConfiguration(self.aiTerminalConfig) aoTask = daq.AoTask('MultiToneAO') aoTask.addChannel(aoChannel) aoTask.configureTiming(timing) aoTask.configureOutputBuffer((2*hwm)*chunkSize) aoTask.disableRegeneration() if 'ai/StartTrigger' in d.findTerminals(): aoTask.digitalEdgeStartTrigger('/%s/ai/StartTrigger' % self.deviceName) # The cheap USB DAQ doesn't support this?! self.__logger.info("Configured digital edge start trigger for aoTask") aoTask.setUsbTransferRequestSize('%s/%s' % (self.deviceName, self.aoChannel), 2**16) aiTask = daq.AiTask('MultiToneAI') aiTask.addChannel(aiChannel) aiTask.configureInputBuffer((2*hwm)*chunkSize) aiTask.configureTiming(timing) aiTask.setUsbTransferRequestSize('%s/%s' % (self.deviceName, self.aiChannel), 2**16) aiTask.commit() aoTask.commit() decimator = DecimatorCascade(self.inputDecimation, self.chunkSize) # Set up cascade of half-band decimators before the lock-in stage chunkNumber = 0 chunkTime = float(chunkSize/self.sampleRate) self.__logger.info("Chunk size: %d", self.chunkSize) self.__logger.debug("Chunk time: %f s" , chunkTime) started = False tStart = time.time() + hwm * chunkTime # Fictitious future start time while not self.stopRequested: if queue.qsize() < hwm: # Need to generate more samples offset, amplitudes, wave = self.generator.generateSamples() t = tStart+chunkNumber*chunkTime # Time of first sample in the chunk queue.put((offset, amplitudes, t)) aoTask.writeData(wave); chunkNumber += 1 self.chunkProduced.emit(chunkNumber, t) elif not started: # Need to start the tasks self.__logger.debug("Starting aoTask") aoTask.start(); t = time.time() self.__logger.debug("Starting aiTask") aiTask.start() started = True if aiTask.samplesAvailable() >= chunkSize: # Can process data tAcquired = time.time() data = aiTask.readData(chunkSize) d = data[0] minimum = np.min(d); maximum = np.max(d); mean = np.sum(d)/d.shape[0]; std = np.std(d) overload = maximum > self.aiRange.max or minimum < self.aiRange.min if overload: #self.__logger.info("Overload") bad = (d>self.aiRange.max) | (d<self.aiRange.min) nBad = np.count_nonzero(bad) self.__logger.info("Input overload detected for %d samples", nBad) self.inputOverload.emit() samples = decimator.decimate(d) offset, amplitudes, tGenerated = queue.get() #print('Offset', offset,'Amplitudes', amplitudes) self.dataReady.emit(samples, np.asarray([tGenerated, tAcquired, minimum, maximum, mean, std, offset]), amplitudes) except Exception: exceptionString = traceback.format_exc() self.__logger.exception('Exception in DaqThread') self.error.emit(exceptionString) finally: del d aoTask = daq.AoTask('ReturnToZero') aoTask.addChannel(aoChannel) aoTask.writeData([0], autoStart = True) self.__logger.info("DAQ AO set to zero.")
def run(self): self.stopRequested = False self.abortRequested = False chunkSize = 2**16 preLoads = 6 try: d = daq.Device(self.deviceName) timing = daq.Timing(rate = self.sampleRate, samplesPerChannel = chunkSize) timing.setSampleMode(timing.SampleMode.CONTINUOUS) aoChannel = daq.AoChannel('%s/%s' % (self.deviceName, self.aoChannel), self.aoRange.min, self.aoRange.max) aiChannel = daq.AiChannel('%s/%s' % (self.deviceName, self.aiChannel), self.aiRange.min, self.aiRange.max) #print 'Ai terminal config', self.aiTerminalConfig, type(self.aiTerminalConfig) aiChannel.setTerminalConfiguration(self.aiTerminalConfig) sampleRate = self.sampleRate for fGoal, settlePeriods, measurePeriods in zip(self.fGoals, self.settlePeriods, self.measurePeriods): if self.stopRequested: break measureSamples = int(np.round(measurePeriods*sampleRate/fGoal)) # Figure out how many samples f = measurePeriods*sampleRate/measureSamples# Now the correct frequency for that number of samples #fs.append(f) phaseStep = TwoPi*f/sampleRate settleSamples = int(sampleRate * settlePeriods/f) startPhase = - settleSamples*phaseStep totalSamples = settleSamples + measureSamples print("fGoal, f, periods, phaseStep, settle samples, measure samples, total samples", fGoal, f, measurePeriods, phaseStep, settleSamples, measureSamples, totalSamples) g = SineWaveformGenerator(amplitude=self.amplitude, offset=self.offset, phaseStep=phaseStep, startingPhase=startPhase) g.setNumberOfSamples(totalSamples) aoTask = daq.AoTask('AO') aoTask.addChannel(aoChannel) aoTask.configureTiming(timing) aoTask.configureOutputBuffer(preLoads*chunkSize) aoTask.disableRegeneration() if 'ai/StartTrigger' in d.findTerminals(): aoTask.digitalEdgeStartTrigger('/%s/ai/StartTrigger' % self.deviceName) # The cheap USB DAQ doesn't support this?! samplesRead = 0 aiTask = daq.AiTask('AI') aiTask.addChannel(aiChannel) aiTask.configureTiming(timing) phaseSet = [] for i in range(preLoads): phases, wave = g.generateSamples(chunkSize) if wave is not None: phaseSet.append(phases) aoTask.writeData(wave) aiTask.setUsbTransferRequestSize(aiChannel.physicalChannel, 2*chunkSize) aoTask.setUsbTransferRequestSize(aoChannel.physicalChannel, 2*chunkSize) #print('Chunksize:', chunkSize) aoTask.start() aiTask.start() while not self.stopRequested: phases, wave = g.generateSamples(chunkSize) if wave is not None: aoTask.writeData(wave) phaseSet.append(phases) samplesRemaining = totalSamples-samplesRead if samplesRemaining > 0: data = aiTask.readData(min(chunkSize, samplesRemaining)) samples = data[0] nNewSamples = len(samples) samplesRead += nNewSamples phases = phaseSet.pop(0) #print(phases.shape, len(phaseSet)) if samplesRead <= settleSamples: pass elif samplesRead > settleSamples+chunkSize: # Entire chunk is good self.waveformAvailable.emit(phases, samples) elif samplesRead > settleSamples: # Special case for first chunk i = settleSamples - samplesRead self.waveformAvailable.emit(phases[i:], samples[i:]) else: break del aiTask; aiTask = None del aoTask; aoTask = None if g.samplesGenerated != totalSamples: warnings.warn('Not all samples were generated') # if lia.nSamples != measureSamples: # warnings.warn('Did not record expected number of samples') phase, V = g.nextSample() aoTask = daq.AoTask('AO_Final') # Now write one last sample that is back at the offset aoTask.addChannel(aoChannel) aoTask.writeData(V, autoStart = True) if abs(V[0]-self.offset) > 1E-3: warnings.warn('Output and end was not zero as expected.') t = time.time() self.waveformComplete.emit(t, f) except Exception: exceptionString = traceback.format_exc() self.error.emit(exceptionString) finally: del d
def run(self): self.sweepCount = 0 self.stopRequested = False self.abortRequested = False try: d = daq.Device(self.deviceName) d.findTerminals() nSamples = len(self.wave) timing = daq.Timing(rate=self.sampleRate, samplesPerChannel=nSamples) timing.setSampleMode(timing.SampleMode.FINITE) dt = 1. / self.sampleRate print "Samples:", len(self.wave) aoChannel = daq.AoChannel( '%s/%s' % (self.deviceName, self.aoChannel), self.aoRange.min, self.aoRange.max) aoTask = daq.AoTask('AO') aoTask.addChannel(aoChannel) aoTask.configureTiming(timing) #aoTask.configureOutputBuffer(2*len(self.wave)) aoTask.digitalEdgeStartTrigger( '/%s/ai/StartTrigger' % self.deviceName) # The cheap USB DAQ doesn't support this?! if self.aiDriveChannel is not None: # Record drive signal on a different AI channel first aiChannel = daq.AiChannel( '%s/%s' % (self.deviceName, self.aiDriveChannel), self.aoRange.min, self.aoRange.max) aiChannel.setTerminalConfiguration(self.aiTerminalConfig) aiTask = daq.AiTask('AI') aiTask.addChannel(aiChannel) aiTask.configureTiming(timing) aoTask.writeData(self.wave) aoTask.start() aiTask.start() t = time.time() # Time of the start of the sweep while aiTask.samplesAvailable( ) < nSamples and not self.abortRequested: self.msleep(10) data = aiTask.readData(nSamples) self.driveDataReady.emit(t, dt, data[0]) aiTask.stop() try: aoTask.stop() except: pass del aiTask del aiChannel aiChannel = daq.AiChannel( '%s/%s' % (self.deviceName, self.aiChannel), self.aiRange.min, self.aiRange.max) aiChannel.setTerminalConfiguration(self.aiTerminalConfig) aiTask = daq.AiTask('AI') aiTask.addChannel(aiChannel) aiTask.configureTiming(timing) import sys #print('Before DAQ loop:',sys.getrefcount(self.wave)) while not self.stopRequested: if self.auxAoRamper is not None: self.auxAoRamper.rampTo(self.newAuxAoVoltage) VauxAo = self.auxAoRamper.voltage() else: VauxAo = 0 aoTask.writeData(self.wave) #print('After DAQ write:',sys.getrefcount(self.wave)) if self.squid is not None: print "Resetting SQUID:", self.squid.resetPfl() print "Done" self.msleep(100) aoTask.start() aiTask.start() t = time.time() # Time of the start of the sweep while aiTask.samplesAvailable( ) < nSamples and not self.abortRequested: self.msleep(10) data = aiTask.readData(nSamples) self.dataReady.emit(t, VauxAo, dt, data[0]) self.sweepCount += 1 aiTask.stop() try: aoTask.stop() except: pass #print('Before wave delete:',sys.getrefcount(self.wave)) del self.wave # Not sure why this is needed, but get's rid of our giant memory leak. #print('After wave delete:',sys.getrefcount(self.wave)) aiTask.clear() aoTask.clear() except Exception: exceptionString = traceback.format_exc() self.error.emit(exceptionString) finally: del d