Ejemplo n.º 1
0
    def _readConfig(self):
        try:
            filepath = os.path.join(self.configPath, 'AudioHardware.txt')
            audioHW = AudioHardware.readAudioHWConfig(filepath)

        except:
            print("Could not read in audio hardware config")
            audioHW = AudioHardware.AudioHardware()

        self.audioHW = audioHW

        try:
            filepath = os.path.join(self.configPath, 'Bioamp.txt')
            bioamp = Bioamp.readBioampConfig(filepath)
        except:
            print("Could not read in bioamp config")
            bioamp = Bioamp.Bioamp()

        self.bioamp = bioamp

        # load in last speeaker calibration
        filename = 'speaker_cal_last.pickle'
        try:
            filepath = os.path.join(self.configPath, filename)
            spCal = SpeakerCalibration.loadSpeakerCal(filepath)
            self.audioHW.loadSpeakerCalFromProcData(spCal)
        except:
            print("Could not read speaker calibration")

        micFilePath = os.path.join(self.configPath, 'microphones.txt')
        if os.path.exists(micFilePath):
            (micNameArray, micRespArray) = CMPCommon.readMicResponseFile(
                micFilePath)  # defined in OCTCommon.py
        else:
            micRespArray = []
            micNameArray = []

        # insert defaults
        micRespArray.insert(0, None)
        micNameArray.insert(0, 'Flat')

        self.micRespArray = micRespArray
        self.micNameArray = micNameArray

        for name in micNameArray:
            self.microphone_comboBox.addItem(name)

        micName = self.audioHW.micName
        print('CMPWindowClass.__init__: micName= %s' % micName)
        try:
            idx = micNameArray.index(micName)
        except ValueError:
            QtGui.QMessageBox.critical(
                self, "Could not find mic response",
                "Could not find mic response '%s', defaulting to flat response "
                % micName)
            idx = 0
        self.microphone_comboBox.setCurrentIndex(idx)
        self.audioHW.micResponse = micRespArray[idx]
Ejemplo n.º 2
0
    def _readConfig(self):
        try:
            filepath = os.path.join(self.configPath, 'AudioHardware.txt')
            audioHW = AudioHardware.readAudioHWConfig(filepath)
            
        except:
            print("Could not read in audio hardware config")
            audioHW = AudioHardware.AudioHardware()
            
        self.audioHW = audioHW
        
        try:
            filepath = os.path.join(self.configPath, 'Bioamp.txt')
            bioamp = Bioamp.readBioampConfig(filepath)
        except:
            print("Could not read in bioamp config")
            bioamp = Bioamp.Bioamp()
            
        self.bioamp = bioamp
        
        # load in last speeaker calibration
        filename = 'speaker_cal_last.pickle'
        try:
            filepath = os.path.join(self.configPath, filename)
            spCal = SpeakerCalibration.loadSpeakerCal(filepath)
            self.audioHW.loadSpeakerCalFromProcData(spCal)
        except:
            print("Could not read speaker calibration")
        
        micFilePath = os.path.join(self.configPath, 'microphones.txt')
        if os.path.exists(micFilePath):
            (micNameArray, micRespArray) = CMPCommon.readMicResponseFile(micFilePath)   # defined in OCTCommon.py
        else:
            micRespArray = []
            micNameArray = []
        
        # insert defaults
        micRespArray.insert(0, None)
        micNameArray.insert(0, 'Flat')
        
        self.micRespArray = micRespArray
        self.micNameArray = micNameArray
        
        for name in micNameArray:
            self.microphone_comboBox.addItem(name)

        micName = self.audioHW.micName
        print('CMPWindowClass.__init__: micName= %s' % micName)
        try:
            idx = micNameArray.index(micName)
        except ValueError:
            QtGui.QMessageBox.critical (self, "Could not find mic response", "Could not find mic response '%s', defaulting to flat response " % micName)
            idx = 0
        self.microphone_comboBox.setCurrentIndex(idx)
        self.audioHW.micResponse = micRespArray[idx]
Ejemplo n.º 3
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()
Ejemplo n.º 4
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()