Esempio n. 1
0
def runSpeakerCal(appObj, testMode=False):
    DebugLog.log("runSpeakerCal")
    appObj.tabWidget.setCurrentIndex(1)
    appObj.doneFlag = False
    appObj.isCollecting = True
    # trigRate = octfpga.GetTriggerRate()
    audioHW = appObj.audioHW
    outputRate = audioHW.DAQOutputRate
    inputRate = audioHW.DAQInputRate
    
    if testMode:
        testDataDir = os.path.join(appObj.basePath, 'exampledata', 'Speaker Calibration')
        filePath = os.path.join(testDataDir, 'AudioParams.pickle')
        f = open(filePath, 'rb')
        audioParams = pickle.load(f)
        f.close()
    else:
        audioParams = appObj.getAudioParams()
    numSpk = audioParams.getNumSpeakers()
    
    if not testMode:
        from DAQHardware import DAQHardware
        daq = DAQHardware()

    chanNamesIn= [ audioHW.mic_daqChan]
    micVoltsPerPascal = audioHW.micVoltsPerPascal


    spCal = None
    freq_array2 = audioParams.freq[1, :]
    try:
        frameNum = 0
        isSaveDirInit = False
        saveOpts = appObj.getSaveOpts()
        for spkNum in range(0, numSpk):
            chanNameOut = audioHW.speakerL_daqChan 
            attenLines = audioHW.attenL_daqChan
            spkIdx = 0
                
            if (numSpk == 1 and audioParams.speakerSel == Speaker.RIGHT) or spkNum == 2:
                chanNameOut = audioHW.speakerR_daqChan
                attenLines = audioHW.attenR_daqChan
                spkIdx = 1
    
            freq_array = audioParams.freq[spkIdx, :]
            if (audioParams.stimType == AudioStimType.TWO_TONE_DP) and (numSpk == 1):
                freq_array = np.concatenate((freq_array, freq_array2))
                freq_array = np.sort(freq_array)
                freq_array2 = freq_array
                
            if spCal is None:
                spCal = SpeakerCalData(np.vstack((freq_array, freq_array2)))
                
            DebugLog.log("runSpeakerCal freq_array=" + repr(freq_array))
            freq_idx = 0

            attenSig = AudioHardware.makeLM1972AttenSig(0)
            
            if not testMode:
                # daq.sendDigOutCmd(attenLines, attenSig)
                appObj.oct_hw.SetAttenLevel(0, attenLines)
            
            for freq in freq_array:
                DebugLog.log("runSpeakerCal freq=" + repr(freq))
                spkOut = makeSpeakerCalibrationOutput(freq, audioHW, audioParams)    
                npts = len(spkOut)
                t = np.linspace(0, npts/outputRate, npts)
                
                pl = appObj.plot_spkOut
                pl.clear()
                endIdx = int(5e-3 * outputRate)        # only plot first 5 ms
                pl.plot(t[0:endIdx], spkOut[0:endIdx], pen='b')
                        
                numInputSamples = int(inputRate*len(spkOut)/outputRate) 
                
                if testMode:
                    mic_data = OCTCommon.loadRawData(testDataDir, frameNum, dataType=3)                    
                else:

                    # setup the output task
                    daq.setupAnalogOutput([chanNameOut], audioHW.daqTrigChanIn, int(outputRate), spkOut)
                    daq.startAnalogOutput()
                    
                    # setup the input task
                    daq.setupAnalogInput(chanNamesIn, audioHW.daqTrigChanIn, int(inputRate), numInputSamples) 
                    daq.startAnalogInput()
                
                    # trigger the acquiisiton by sending ditital pulse
                    daq.sendDigTrig(audioHW.daqTrigChanOut)
                    
                    mic_data = daq.readAnalogInput()
                    mic_data = mic_data/micVoltsPerPascal

                
                if not testMode:
                    daq.stopAnalogInput()
                    daq.stopAnalogOutput()
                    daq.clearAnalogInput()
                    daq.clearAnalogOutput()
                
                npts = len(mic_data)
                t = np.linspace(0, npts/inputRate, npts)
                pl = appObj.plot_micRaw
                pl.clear()
                pl.plot(t, mic_data, pen='b')
                
                labelStyle = appObj.xLblStyle
                pl.setLabel('bottom', 'Time', 's', **labelStyle)
                labelStyle = appObj.yLblStyle
                pl.setLabel('left', 'Response', 'Pa', **labelStyle)
                
                micData, spCal = processSpkCalData(mic_data, freq*1000, freq_idx, audioParams, inputRate, spCal, spkIdx)
                
                pl = appObj.plot_micFFT
                pl.clear()
                df = micData.fft_freq[1] - micData.fft_freq[0]
                nf = len(micData.fft_freq)
                i1 = int(1000*freq_array[0]*0.9/df)
                i2 = int(1000*freq_array[-1]*1.1/df)
                DebugLog.log("SpeakerCalibration: df= %0.3f i1= %d i2= %d nf= %d" % (df, i1, i2, nf))
                pl.plot(micData.fft_freq[i1:i2], micData.fft_mag[i1:i2], pen='b')
                labelStyle = appObj.xLblStyle
                pl.setLabel('bottom', 'Frequency', 'Hz', **labelStyle)
                labelStyle = appObj.yLblStyle
                pl.setLabel('left', 'Magnitude', 'db SPL', **labelStyle)
                
                pl = appObj.plot_micMagResp
                pl.clear()
#                pl.plot(1000*spCal.freq[spkIdx, :], spCal.magResp[spkIdx, :], pen="b", symbol='o')
                pl.plot(freq_array, spCal.magResp[spkIdx, :], pen="b", symbol='o')
                labelStyle = appObj.xLblStyle
                pl.setLabel('bottom', 'Frequency', 'Hz', **labelStyle)
                labelStyle = appObj.yLblStyle
                pl.setLabel('left', 'Magnitude', 'db SPL', **labelStyle)
                
                freq_idx += 1
                
                if appObj.getSaveState():
                    if not isSaveDirInit:
                        saveDir = OCTCommon.initSaveDir(saveOpts, 'Speaker Calibration', audioParams=audioParams)
                        isSaveDirInit = True
    
                    if saveOpts.saveRaw:
                        OCTCommon.saveRawData(mic_data, saveDir, frameNum, dataType=3)
                    
                QtGui.QApplication.processEvents() # check for GUI events, such as button presses
                
                # if done flag, break out of loop
                if appObj.doneFlag:
                    break
                
                frameNum += 1

                
            # if done flag, break out of loop
            if appObj.doneFlag:
                break
                
        if not appObj.doneFlag:
            saveDir = appObj.settingsPath
            saveSpeakerCal(spCal, saveDir)
            appObj.audioHW.loadSpeakerCalFromProcData(spCal)
            appObj.spCal = spCal            
            
    except Exception as ex:
        traceback.print_exc(file=sys.stdout)
        QtGui.QMessageBox.critical (appObj, "Error", "Error during scan. Check command line output for details")           
        
    8# update the audio hardware speaker calibration                     
    appObj.isCollecting = False
    QtGui.QApplication.processEvents() # check for GUI events, such as button presses
    appObj.finishCollection()


    
Esempio n. 2
0
def runSpeakerCalTest(appObj):
    DebugLog.log("runSpeakerCal")
    appObj.tabWidget.setCurrentIndex(1)
    appObj.doneFlag = False
    appObj.isCollecting = True
    # trigRate = octfpga.GetTriggerRate()
    audioHW = appObj.audioHW
    outputRate = audioHW.DAQOutputRate
    inputRate = audioHW.DAQInputRate

    audioParams = appObj.getAudioParams()
    numSpk = audioParams.getNumSpeakers()
    daq = DAQHardware()
    chanNamesIn = [audioHW.mic_daqChan]
    micVoltsPerPascal = audioHW.micVoltsPerPascal

    # spCal = SpeakerCalData(audioParams)
    try:
        testMode = appObj.oct_hw.IsDAQTestingMode()
        frameNum = 0
        isSaveDirInit = False
        saveOpts = appObj.getSaveOpts()

        if audioParams.speakerSel == Speaker.LEFT:
            chanNameOut = audioHW.speakerL_daqChan
            attenLines = audioHW.attenL_daqChan
            spkIdx = 0
        else:
            chanNameOut = audioHW.speakerR_daqChan
            attenLines = audioHW.attenR_daqChan
            spkIdx = 1

        freq_array = audioParams.freq[spkIdx, :]
        if (audioParams.stimType == AudioStimType.TWO_TONE_DP) and (numSpk == 1):
            freq2 = audioParams.freq[1, :]
            freq_array = np.concatenate((freq_array, freq2))
            freq_array = np.sort(freq_array)

        DebugLog.log("freq_array=" + repr(freq_array))
        amp_array = audioParams.amp
        numAmp = len(amp_array)
        numFreq = len(freq_array)
        magResp = np.zeros((numFreq, numAmp))
        magResp[:, :] = np.nan
        phaseResp = np.zeros((numFreq, numAmp))
        phaseResp[:, :] = np.nan
        THD = np.zeros((numFreq, numAmp))
        THD[:, :] = np.nan

        for freq_idx in range(0, numFreq):
            for amp_idx in range(0, numAmp):
                freq = freq_array[freq_idx]
                amp = amp_array[amp_idx]

                spkOut, attenLvl = makeSpkCalTestOutput(freq, amp, audioHW, audioParams, spkIdx)
                DebugLog.log("runSpeakerCalTest freq= %0.3f kHz amp= %d attenLvl= %d" % (freq, amp, attenLvl))

                if spkOut is None:
                    DebugLog.log("runSpeakerCalTest freq= %0.3f kHz cannot output %d dB" % (freq, amp))
                    frameNum = frameNum + 1
                    continue

                npts = len(spkOut)
                t = np.linspace(0, npts / outputRate, npts)

                pl = appObj.plot_spkOut
                pl.clear()
                endIdx = int(5e-3 * outputRate)  # only plot first 5 ms
                pl.plot(t[0:endIdx], spkOut[0:endIdx], pen="b")

                attenSig = AudioHardware.makeLM1972AttenSig(attenLvl)
                numInputSamples = int(inputRate * len(spkOut) / outputRate)

                if not testMode:
                    # daq.sendDigOutCmd(attenLines, attenSig)
                    appObj.oct_hw.SetAttenLevel(attenLvl, attenLines)

                    # setup the output task
                    daq.setupAnalogOutput([chanNameOut], audioHW.daqTrigChanIn, int(outputRate), spkOut)
                    daq.startAnalogOutput()

                    # setup the input task
                    daq.setupAnalogInput(chanNamesIn, audioHW.daqTrigChanIn, int(inputRate), numInputSamples)
                    daq.startAnalogInput()

                    # trigger the acquiisiton by sending ditital pulse
                    daq.sendDigTrig(audioHW.daqTrigChanOut)

                    mic_data = daq.readAnalogInput()
                    mic_data = mic_data / micVoltsPerPascal

                    daq.waitDoneInput()
                    daq.waitDoneOutput()
                    daq.stopAnalogInput()
                    daq.stopAnalogOutput()
                    daq.clearAnalogInput()
                    daq.clearAnalogOutput()
                else:
                    mic_data = GetTestData(frameNum)

                npts = len(mic_data)
                t = np.linspace(0, npts / inputRate, npts)
                pl = appObj.plot_micRaw
                pl.clear()
                pl.plot(t, mic_data, pen="b")

                labelStyle = appObj.xLblStyle
                pl.setLabel("bottom", "Time", "s", **labelStyle)
                labelStyle = appObj.yLblStyle
                pl.setLabel("left", "Response", "Pa", **labelStyle)

                micData, magResp, phaseResp, THD = processSpkCalTestData(
                    mic_data, freq * 1000, freq_idx, amp_idx, audioParams, inputRate, magResp, phaseResp, THD
                )

                pl = appObj.plot_micFFT
                pl.clear()
                df = micData.fft_freq[1] - micData.fft_freq[0]
                nf = len(micData.fft_freq)
                i1 = int(1000 * freq_array[0] * 0.9 / df)
                i2 = int(1000 * freq_array[-1] * 1.1 / df)
                DebugLog.log("SpeakerCalibration: df= %0.3f i1= %d i2= %d nf= %d" % (df, i1, i2, nf))
                pl.plot(micData.fft_freq[i1:i2], micData.fft_mag[i1:i2], pen="b")
                labelStyle = appObj.xLblStyle
                pl.setLabel("bottom", "Frequency", "Hz", **labelStyle)
                labelStyle = appObj.yLblStyle
                pl.setLabel("left", "Magnitude", "db SPL", **labelStyle)

                pl = appObj.plot_micMagResp
                pl.clear()

                for a_idx in range(0, numAmp):
                    pen = (a_idx, numAmp)
                    pl.plot(1000 * freq_array, magResp[:, a_idx], pen=pen, symbol="o")

                labelStyle = appObj.xLblStyle
                pl.setLabel("bottom", "Frequency", "Hz", **labelStyle)
                labelStyle = appObj.yLblStyle
                pl.setLabel("left", "Magnitude", "db SPL", **labelStyle)

                pl = appObj.plot_speakerDistortion
                pl.clear()

                for a_idx in range(0, numAmp):
                    pen = (a_idx, numAmp)
                    pl.plot(1000 * freq_array, THD[:, a_idx], pen=pen, symbol="o")

                labelStyle = appObj.xLblStyle
                pl.setLabel("bottom", "Frequency", "Hz", **labelStyle)
                labelStyle = appObj.yLblStyle
                pl.setLabel("left", "Magnitude", "db SPL", **labelStyle)

                if appObj.getSaveState():
                    if not isSaveDirInit:
                        saveDir = OCTCommon.initSaveDir(saveOpts, "Speaker Cal Test", audioParams=audioParams)
                        isSaveDirInit = True

                    if saveOpts.saveRaw:
                        OCTCommon.saveRawData(mic_data, saveDir, frameNum, dataType=3)

                frameNum = frameNum + 1

                QtGui.QApplication.processEvents()  # check for GUI events, such as button presses

                # if done flag, break out of loop
                if appObj.doneFlag:
                    break

            # if done flag, break out of loop
            if appObj.doneFlag:
                break

    except Exception as ex:
        traceback.print_exc(file=sys.stdout)
        QtGui.QMessageBox.critical(appObj, "Error", "Error during scan. Check command line output for details")

    8  # update the audio hardware speaker calibration
    appObj.isCollecting = False
    QtGui.QApplication.processEvents()  # check for GUI events, such as button presses
    appObj.finishCollection()
Esempio n. 3
0
def runDispersion(appObj):
    DebugLog.log("runDispersion")
    appObj.tabWidget.setCurrentIndex(5)
    appObj.doneFlag = False
    appObj.isCollecting = True
    # trigRate = octfpga.GetTriggerRate()
    mirrorDriver = appObj.mirrorDriver
    
    # set the mirror position to (0,0)
    chanNames = [mirrorDriver.X_daqChan, mirrorDriver.Y_daqChan]
    data = np.zeros(2)
    if not appObj.oct_hw.IsDAQTestingMode():
        from DAQHardware import DAQHardware
        daq = DAQHardware()
        daq.writeValues(chanNames, data)
    
    pd_background = None
    
    fpgaOpts = appObj.oct_hw.fpgaOpts
    numklinpts = fpgaOpts.numKlinPts
    if fpgaOpts.InterpDownsample > 0:
        numklinpts =  numklinpts // 2
    
    # keep looping until we are signlaed to stop by GUI (flag set in appObj)
    try:
        frameNum = 0
        saveDirInit = False
        testDataDir = os.path.join(appObj.basePath, 'exampledata', 'Dispersion')
        dispData = DispersionData(fpgaOpts)
        klin = None # initialze klin to None so it will be computed first iteration
        savedFPGADisp = False
        
        while not appObj.doneFlag: 
            # setup and grab the OCT data - this will also fire the mirror output
            numTrigs = appObj.disp_numTrigs_spinBox.value()
            processMode = OCTCommon.ProcessMode(appObj.processMode_comboBox.currentIndex())
                
            # get proessing optiosn from GUI        
            PD_LP_fc = appObj.disp_pd_lpfilter_cutoff_dblSpinBox.value()
            PD_HP_fc = appObj.disp_pd_hpfilter_cutoff_dblSpinBox.value()
            PDfiltCutoffs = [PD_LP_fc, PD_HP_fc]
            magWin_LPfilterCutoff = appObj.disp_magwin_lpfilter_cutoff_dblSpinBox.value()
            
            dispData.mziFilter = appObj.mziFilter.value()
            dispData.magWin_LPfilterCutoff = magWin_LPfilterCutoff
            dispData.PDfilterCutoffs = PDfiltCutoffs
            
            collectBG = appObj.disp_collectBG_pushButton.isChecked()
            
            pd_background = dispData.phDiode_background                
    
            if processMode == OCTCommon.ProcessMode.FPGA:
                if appObj.oct_hw.IsOCTTestingMode():
                    pd_data = OCTCommon.loadRawData(testDataDir, frameNum % 19, dataType=1)
                    numklinpts = 1400
                else:
                    err, pd_data = appObj.oct_hw.AcquireOCTDataInterpPD(numTrigs)
                    DebugLog.log("runDispersion(): AcquireOCTDataInterpPD() err = %d" % err)
                    # process the data
                dispData = processData(pd_data, dispData, numklinpts, PDfiltCutoffs, magWin_LPfilterCutoff, pd_background, collectBG)

            elif processMode == OCTCommon.ProcessMode.SOFTWARE:
                if appObj.oct_hw.IsOCTTestingMode():
                    ch0_data,ch1_data=JSOraw.getSavedRawData(numTrigs,appObj.dispData.requestedSamplesPerTrig,appObj.savedDataBuffer)
                else:
                    # def AcquireOCTDataRaw(self, numTriggers, samplesPerTrig=-1, Ch0Shift=-1, startTrigOffset=0):
                    samplesPerTrig = fpgaOpts.SamplesPerTrig*2 + fpgaOpts.Ch0Shift*2
                    err, ch0_data,ch1_data = appObj.oct_hw.AcquireOCTDataRaw(numTrigs, samplesPerTrig)

                pdData,mziData,actualSamplesPerTrig = JSOraw.channelShift(ch0_data,ch1_data,dispData)    # shift the two channels to account for delays in the sample data compared to the MZI data 
                mzi_hilbert, mzi_mag, mzi_ph, k0 = JSOraw.processMZI(mziData, dispData)                # calculate k0 from the phase of the MZI data
                k0Cleaned = JSOraw.cleank0(k0, dispData) # Adjust the k0 curves so that the unwrapping all starts at the same phase    
                pd_data, klin = JSOraw.processPD(pdData, k0Cleaned, dispData, klin)  # Interpolate the PD data based upon the MZI data
                dispData.Klin = klin
                dispData = processUniqueDispersion(pd_data, dispData, pd_background, collectBG)
            else:
                QtGui.QMessageBox.critical (appObj, "Error", "Unsuppoted processing mode for current hardware")
                
            # plot the data
            plotDispData(appObj, dispData, PDfiltCutoffs)
            
            if appObj.getSaveState():
                dispFilePath = saveDispersionData(dispData, appObj.settingsPath)
            
                saveOpts = appObj.getSaveOpts()
                if saveOpts.saveRaw:
                    if not saveDirInit:
                        saveDir = OCTCommon.initSaveDir(saveOpts, 'Dispersion')
                        saveDirInit = True
                    
                    OCTCommon.saveRawData(pd_data, saveDir, frameNum, dataType=1)
                if processMode == OCTCommon.ProcessMode.FPGA:
                    appObj.dispDataFPGA = dispData
                    dispFilePathFPGA = dispFilePath
                    savedFPGADisp = True
                else:
                    appObj.dispData = dispData
                
            frameNum += 1
            QtGui.QApplication.processEvents() # check for GUI events, particularly the "done" flag
            
        if savedFPGADisp:
            DebugLog.log("runDispersion(): loading dispersion file into FPGA")
            appObj.loadDispersionIntoFPGA(dispFilePathFPGA, appObj.oct_hw.fpgaOpts)
            
    except Exception as ex:
        # raise ex
        traceback.print_exc(file=sys.stdout)
        QtGui.QMessageBox.critical (appObj, "Error", "Error during scan. Check command line output for details")
    finally:
        appObj.isCollecting = False
        QtGui.QApplication.processEvents() # check for GUI events
        appObj.finishCollection()