예제 #1
0
    def getSaveOpts(self):
        saveOpts = CMPCommon.SaveOpts()
        saveOpts.saveBaseDir = self.saveDir_lineEdit.text()
        saveOpts.saveRaw = self.saveRaw_checkBox.isChecked()
        saveOpts.note = self.note_lineEdit.text()

        return saveOpts
예제 #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]
예제 #3
0
    def getFrequencySetup(self):
        fSetup = CMPCommon.blankRecord()
        fSetup.freqLow = self.freqLow_dblSpinBox.value() * 1000
        fSetup.freqHigh = self.freqHigh_dblSpinBox.value() * 1000
        fSetup.numSteps = self.freqNumSteps_spinBox.value()
        fSetup.spacing = self.freqSpacing_comboBox.currentIndex()
        fSetup.speaker = self.speaker_comboBox.currentIndex()

        return fSetup
예제 #4
0
 def getFrequencySetup(self):
     fSetup = CMPCommon.blankRecord()
     fSetup.freqLow = self.freqLow_dblSpinBox.value()*1000
     fSetup.freqHigh = self.freqHigh_dblSpinBox.value()*1000
     fSetup.numSteps = self.freqNumSteps_spinBox.value()
     fSetup.spacing = self.freqSpacing_comboBox.currentIndex()
     fSetup.speaker = self.speaker_comboBox.currentIndex()
     
     return fSetup
예제 #5
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]
예제 #6
0
    def newSaveFile(self):
        saveDir = self.saveDir_lineEdit.text()
        if self.excelWB is not None:
            self.excelWB.close()

        d = datetime.datetime.now()
        timeStr = d.strftime('%Y-%m-%d %H_%M_%S')
        filename = 'PyCMP ' + timeStr + '.xlsx'
        filepath = os.path.join(saveDir, filename)
        self.excelWB = CMPCommon.initExcelWorkbook(filepath)
        self.saveFile_lineEdit.setText(filename)

        filename = 'PyCMP ' + timeStr + '.txt'
        filepath = os.path.join(saveDir, filename)
        self.saveFileTxt_filepath = filepath
예제 #7
0
 def newSaveFile(self):
     saveDir = self.saveDir_lineEdit.text()
     if self.excelWB is not None:
         self.excelWB.close()
         
     d = datetime.datetime.now()
     timeStr = d.strftime('%Y-%m-%d %H_%M_%S')
     filename = 'PyCMP ' + timeStr + '.xlsx'
     filepath = os.path.join(saveDir, filename)    
     self.excelWB = CMPCommon.initExcelWorkbook(filepath)
     self.saveFile_lineEdit.setText(filename)
     
     filename = 'PyCMP ' + timeStr + '.txt'
     filepath = os.path.join(saveDir, filename)
     self.saveFileTxt_filepath = filepath
예제 #8
0
파일: CM.py 프로젝트: udayragakiran/PyCMP
def saveCMDataXLS(CMdata, trialDuration, trialReps, ws, saveOpts):
    try:
        numFreq = len(CMdata.freqArray)
        ws.write(2, 0, "Trial duration")
        ws.write(2, 1, "%0.3g" % trialDuration)
        ws.write(3, 0, "Trial reps")
        ws.write(3, 1, "%d" % trialReps)

        # writeExcelFreqAmpHeader(ws, freq, amp, row=0, col=1):
        row = 6
        ws.write(row, 0, 'Response  (uV)')
        CMPCommon.writeExcelFreqAmpHeader(ws, CMdata.freqArray,
                                          CMdata.ampArray, row + 1, 0)
        data = CMdata.CMResp * 1e9
        data = np.round(data) / 1e3  # convert to uV
        CMPCommon.writeExcel2DData(ws, data, row + 2, 1)

        row = row + numFreq + 2
        ws.write(row, 0, 'Noise Mean (uV)')
        CMPCommon.writeExcelFreqAmpHeader(ws, CMdata.freqArray,
                                          CMdata.ampArray, row + 1, 0)
        data = CMdata.noise_mean * 1e9
        data = np.round(data) / 1e3  # convert to uV
        CMPCommon.writeExcel2DData(ws, data, row + 2, 1)

        row = row + numFreq + 2
        ws.write(row, 0, 'Noise Stdev (uV)')
        CMPCommon.writeExcelFreqAmpHeader(ws, CMdata.freqArray,
                                          CMdata.ampArray, row + 1, 0)
        data = CMdata.noise_std * 1e9
        data = np.round(data) / 1e3  # round and convert to uV
        CMPCommon.writeExcel2DData(ws, CMdata.noise_mean, row + 2, 1)

        # save tracings if user has checked box
        if saveOpts.saveTracings:
            row = row + numFreq + 3
            ws.write(row, 0, 't (ms)')
            col = 2
            for t in CMdata.t:
                t = t * 1e6
                t = np.round(t) / 1e3  # convert to ms
                ws.write(row, col, t)
                col += 1

            row += 2
            ws.write(row, 0, 'Freq')
            ws.write(row, 1, 'Amp')
            ws.write(row, 2, 'Averaged Bioamp Tracing (uV)')
            freqArray = CMdata.freqArray
            ampArray = CMdata.ampArray
            row += 1
            for f_idx in range(0, len(freqArray)):
                for a_idx in range(0, len(ampArray)):
                    f = freqArray[f_idx]
                    a = ampArray[a_idx]
                    ws.write(row, 0, f)
                    ws.write(row, 1, a)
                    tr = CMdata.tracings[f_idx, a_idx, :]
                    tr = tr * 1e9
                    tr = np.round(
                        tr) / 1e3  # round to nearest nv and conver tto uV
                    col = 2
                    for pt in tr:
                        ws.write(row, col, pt)
                        col += 1
                    row += 1

            row += 2
            ws.write(row, 0, 'Freq')
            ws.write(row, 1, 'Amp')
            ws.write(row, 2, 'Averaged Mic Tracing (uPa)')
            freqArray = CMdata.freqArray
            ampArray = CMdata.ampArray
            row += 1
            for f_idx in range(0, len(freqArray)):
                for a_idx in range(0, len(ampArray)):
                    f = freqArray[f_idx]
                    a = ampArray[a_idx]
                    ws.write(row, 0, f)
                    ws.write(row, 1, a)
                    tr = CMdata.micTracings[f_idx, a_idx, :]
                    tr = tr * 1e9
                    tr = np.round(
                        tr) / 1e3  # round to nearest nv and conver tto uV
                    col = 2
                    for pt in tr:
                        ws.write(row, col, pt)
                        col += 1
                    row += 1

    except:
        print('CM.saveCMDataXLS: Exception writing data to file')
        traceback.print_exc()
예제 #9
0
파일: ABR.py 프로젝트: udayragakiran/PyCMP
def runABR(appObj, testMode=False):
    print("runABR")
    
    appObj.tabWidget.setCurrentIndex(3)
    appObj.doneFlag = False
    appObj.isCollecting = True
    # trigRate = octfpga.GetTriggerRate()
    audioHW = appObj.audioHW
    bioamp = appObj.bioamp
    outputRate = audioHW.DAQOutputRate
    inputRate = audioHW.DAQInputRate

    # freq_array2 = audioParams.freq[1, :]
    freqArray = appObj.getFrequencyArray()
    ABRparams = ABRParams(appObj)
    
    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:
        # freqArray = appObj.getFrequencyArray()
        i1 = appObj.ABR_freqLow_comboBox.currentIndex()
        i2 = appObj.ABR_freqHigh_comboBox.currentIndex()
        print("runABR: i1= ", i1, "i2= ", i2)
        ampLow = appObj.ABRampLow_spinBox.value()
        ampHigh = appObj.ABRampHigh_spinBox.value()
        ampDelta = appObj.ABRampDelta_spinBox.value()
        
        # ampArray = np.arange(ampLow, ampHigh, ampDelta)
        #numSteps = np.floor((ampHigh - ampLow)/ampDelta) + 1
        #ampArray = np.linspace(ampLow, ampHigh, numSteps)
        if ampLow == ampHigh:
            ampArray = np.array([ampLow])
        else:
            ampArray = np.arange(ampLow, ampHigh, ampDelta)
            if ampArray[-1] != ampHigh:
                ampArray = np.hstack((ampArray, ampHigh))
        
        freqArray = freqArray[i1:i2+1]
    
    if ABRparams.click:
        freqArray = freqArray[0:1]  # only use single freqeucny
        clickRMS = appObj.ABRclick_RMS
        
    # numSpk = audioParams.getNumSpeakers()
    if not testMode:
        from DAQHardware import DAQHardware
        daq = DAQHardware()

    chanNamesIn= [ audioHW.mic_daqChan, bioamp.daqChan]
    micVoltsPerPascal = audioHW.micVoltsPerPascal
    
    

    # set input rate to three times the highest output frequency, to allow plus a 
    
#    inputRate = 3*freqArray[-1]
#    print("runABR: outputRate= ", outputRate, " inputRate= ", inputRate)
#    inputRate = np.max((inputRate, 6e3))   # inpute rate should be at least 6 kHz because ABR responses occur 0.3 - 3 kHz
#    inputRate = outputRate / int(np.floor(outputRate / inputRate))  # pick closest input rate that evenly divides output rate
#    print("runABR: inputRate(final)= ", inputRate)
    
    try:
        frameNum = 0
        numFrames = len(freqArray)*len(ampArray)
        isSaveDirInit = False
        chanNameOut = audioHW.speakerL_daqChan 
        attenLines = audioHW.attenL_daqChan
        
        freq_idx = 0
        ABRdata = None
        appObj.status_label.setText("Running")
        appObj.progressBar.setValue(0)
        
        for freq in freqArray:
            spkOut_trial = makeABROutput(freq, ABRparams, audioHW)
            npts = len(spkOut_trial)
            spkOut = np.tile(spkOut_trial, ABRparams.nReps)
            # invert every other trial, necessary for ABR/CAP output 
            for n in range(1, ABRparams.nReps, 2):
                idx1 = n*npts
                idx2 = (n+1)*npts
                spkOut[idx1:idx2] = -spkOut[idx1:idx2]
#            plt.figure(5)
#            plt.clf()
#            plt.plot(spkOut)
            tOut = np.linspace(0, npts/outputRate, npts)
            print("runABR npts=%d len(spkOut_trial)= %d len(tOut)= %d" % (npts, len(spkOut_trial), len(tOut)))
            amp_idx = 0
            ptsPerRep = int(inputRate*ABRparams.trialDur)
            
            for amp in ampArray:
                print("runABR freq=" + repr(freq), " amp= ", + amp, " freq_idx= ", freq_idx, " amp_idx= ", amp_idx)
                if ABRparams.click:
                    clickRMS = appObj.ABRclick_RMS
                    attenLvl = 0
                    vOut = 10**((amp - clickRMS)/20)
                    minV = audioHW.speakerOutputRng[0]
                    if vOut < minV:
                        attenLvl = int(round(20*np.log10(minV/vOut)))
                        vOut = minV
                else:
                    vOut, attenLvl = audioHW.getCalibratedOutputVoltageAndAttenLevel(freq, amp, 0)
                
                print("runABR vOut= ", vOut, " atenLvl=", attenLvl)
                
                if vOut > audioHW.speakerOutputRng[1]:
                    print("runABR vOut= ", vOut, "  out of range")
                    continue
                elif attenLvl > audioHW.maxAtten:
                    print("runABR attenLvl= ", attenLvl, "  gerater than maximum attenuation")
                    continue
                    
                # attenSig = AudioHardware.makeLM1972AttenSig(0)
                if not testMode:
                    AudioHardware.Attenuator.setLevel(attenLvl, attenLines)
                    # daq.sendDigOutABRd(attenLines, attenSig)
                    # appObj.oct_hw.SetAttenLevel(0, attenLines)
                
                pl = appObj.ABR_output
                pl.clear()
                endIdx = int(5e-3 * outputRate)        # only plot first 5 ms
                #pl.plot(t[0:endIdx], spkOut[0:endIdx], pen='b')
                pl.plot(tOut, spkOut_trial, pen='b')
                
                labelStyle = appObj.xLblStyle
                pl.setLabel('bottom', 'Time', 's', **labelStyle)
                labelStyle = appObj.yLblStyle
                pl.setLabel('left', 'Output', 'V', **labelStyle)
                
                numInputSamples = ABRparams.nReps*int(inputRate*len(spkOut_trial)/outputRate)
                
                if testMode:
                    # mic_data = OCTCommon.loadRawData(testDataDir, frameNum, dataType=3)                    
                    pass
                else:
    
                    # setup the output task
                    daq.setupAnalogOutput([chanNameOut], audioHW.daqTrigChanIn, int(outputRate), vOut*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)
                    
                    timeout = numInputSamples/inputRate + 2
                    dataIn = daq.readAnalogInput(timeout)
                    mic_data = dataIn[0, :]
                    bioamp_data = dataIn[1, :]
                    
                    mic_data = mic_data/micVoltsPerPascal
                    bioamp_data = bioamp_data/bioamp.gain
                
                    daq.waitDoneInput()
                    daq.stopAnalogInput()
                    daq.clearAnalogInput()
                    
                    daq.waitDoneOutput(stopAndClear=True)
                
#                npts = len(mic_data)
#                t = np.linspace(0, npts/inputRate, npts)
#                pl = appObj.ABR_micInput
#                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)
    
    # def processABRData(mic_data, bioamp_data, nReps, freq, amp_idx, inputRate, ABRdataIn):            
                ABRptData, ABRdata = processABRData(mic_data, bioamp_data, freq, freq_idx, amp_idx, freqArray, ampArray, inputRate, ABRdata, ABRparams)

                print("runABR: plotting data")
                plotABRdata(appObj, ABRptData, ABRdata)
                
    #                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)
                idx1 = round(inputRate*ABRparams.stimOffset)
                idx2 = idx1 + round(inputRate*ABRparams.stimDur)
                
                mic_data = mic_data[idx1:idx2] 
                rms = np.mean(mic_data ** 2) ** 0.5
                rms = 20*np.log10(rms/2e-5)
                
                appObj.ABR_rms_label.setText("%0.1f dB" % rms)                    
                
                QtGui.QApplication.processEvents() # check for GUI events, such as button presses
                
                # if done flag, break out of loop
                if appObj.doneFlag:
                    break
                
                frameNum += 1
                amp_idx += 1
                appObj.progressBar.setValue(frameNum/numFrames)
                
            # if done flag, break out of loop
            if appObj.doneFlag:
                break
            
            freq_idx += 1


        saveOpts = appObj.getSaveOpts()
        workbook = appObj.excelWB
        note = saveOpts.note
        number = appObj.ABRnumber
        name = 'ABR'
        d = datetime.datetime.now()
        timeStr = d.strftime('%H_%M_%S')
        excelWS = CMPCommon.initExcelSpreadsheet(workbook, name, number, timeStr, note)
    
        appObj.ABRnumber += 1                
        #saveOpts.saveTracings = appObj.ABR_saveTracings_checkBox.isChecked()
        saveOpts.saveTracings = True
        saveDir = appObj.saveDir_lineEdit.text()
        saveABRDataXLS(ABRdata, ABRparams, excelWS, saveOpts)
        #saveABRData(ABRdata, trialDur, nReps, appObj.saveFileTxt_filepath, saveOpts, timeStr)
        
        plotName = 'ABR %d %s %s' % (number, timeStr, saveOpts.note)
        saveABRDataFig(ABRdata, ABRparams, saveDir, plotName, timeStr)
        saveABRDataPickle(ABRdata, ABRparams, plotName, saveOpts, timeStr)
            
    except Exception as ex:
        traceback.print_exc(file=sys.stdout)
        QtGui.QMessageBox.critical (appObj, "Error", "Error during collection. Check command line output for details")           
        
    # update the audio hardware speaker calibration                     
    appObj.isCollecting = False
    QtGui.QApplication.processEvents() # check for GUI events, such as button presses
    appObj.finishCollection()
예제 #10
0
    path, fName = os.path.split(filepath)
    print("loading ", fName)
    r = re.split(' ', fName)
    all_types.append(r[0])
    all_numbers.append(int(r[1]))
    filepath = os.path.join(dataDir, fName)
    f = open(filepath, 'rb')
    data = pickle.load(f)
    f.close()
    all_data.append(data)

d = datetime.datetime.now()
timeStr = d.strftime('%Y-%m-%d %H_%M_%S')
filename = 'PyCMP ' + timeStr + '.xlsx'
filepath = os.path.join(dataDir, filename)
wb = CMPCommon.initExcelWorkbook(filepath)

for data, name, number in zip(all_data, all_types, all_numbers):
    try:
        saveOpts = CMPCommon.SaveOpts()
        print('writing ', name, ' ', number, ' to Excel spreadsheet')

        if name == 'CM':
            saveOpts.saveTracings = data.tracings is not None

            timeStr = data.timeStamp
            ws = CMPCommon.initExcelSpreadsheet(wb, name, number, timeStr,
                                                data.note)
            CM.saveCMDataXLS(data, data.trialDuration, data.trialReps, ws,
                             saveOpts)
        elif name == 'DPOAE':
예제 #11
0
def runDPOAE(appObj, testMode=False):
    print("runDPOAE")

    try:
        appObj.tabWidget.setCurrentIndex(2)
        appObj.doneFlag = False
        appObj.isCollecting = True
        # trigRate = octfpga.GetTriggerRate()
        audioHW = appObj.audioHW
        bioamp = appObj.bioamp
        outputRate = audioHW.DAQOutputRate
        inputRate = audioHW.DAQInputRate

        # freq_array2 = audioParams.freq[1, :]
        freqArray = appObj.getFrequencyArray()

        if testMode:
            testDataDir = os.path.join(appObj.basePath, 'exampledata', 'DPOAE')
    #        filePath = os.path.join(testDataDir, 'AudioParams.pickle')
    #        f = open(filePath, 'rb')
    #        audioParams = pickle.load(f)
    #        f.close()
        else:
            # freqArray = appObj.getFrequencyArray()
            i1 = appObj.DPOAE_freqLow_comboBox.currentIndex()
            i2 = appObj.DPOAE_freqHigh_comboBox.currentIndex()
            print("runDPOAE: i1= ", i1, "i2= ", i2)

            ampLow = appObj.DPOAE_ampLow_spinBox.value()
            ampHigh = appObj.DPOAE_ampHigh_spinBox.value()
            ampDelta = appObj.DPOAE_ampDelta_spinBox.value()

            # ampArray = np.arange(ampLow, ampHigh, ampDelta)
            #numSteps = np.floor((ampHigh - ampLow)/ampDelta) + 1
            #ampArray = np.linspace(ampLow, ampHigh, numSteps)
            ampArray = np.arange(ampLow, ampHigh, ampDelta)
            if ampArray[-1] != ampHigh:
                ampArray = np.hstack((ampArray, ampHigh))

            freqArray = freqArray[i1:i2 + 1]

        # numSpk = audioParams.getNumSpeakers()
        if not testMode:
            from DAQHardware import DAQHardware
            daq = DAQHardware()

        chanNamesIn = [audioHW.mic_daqChan, bioamp.daqChan]
        micVoltsPerPascal = audioHW.micVoltsPerPascal
        trialDur = appObj.DPOAE_stimDuration_dblSpinBox.value() * 1e-3
        # nReps = appObj.DPOAEtrialReps_spinBox.value()

        # set input rate multiple the highest output frequency, a little more than Nyquest so stim frequency is more towards center
        inputRate = 4 * freqArray[-1]
        inputRate = outputRate / int(
            np.floor(outputRate / inputRate)
        )  # pick closest input rate that evenly divides output rate

        frameNum = 0
        isSaveDirInit = False

        attenLines1 = audioHW.attenL_daqChan
        attenLines2 = audioHW.attenR_daqChan

        freq_idx = 0
        DPOAEdata = None
        numSpk = appObj.speaker_comboBox.currentIndex() + 1
        chanNameOut = audioHW.speakerL_daqChan
        if numSpk > 1:
            chanNameOut = [audioHW.speakerL_daqChan, audioHW.speakerR_daqChan]
        print("runDPOAE numSpk=", numSpk)

        for freq in freqArray:
            sp1, sp2 = makeDPOAEOutput(freq, trialDur, audioHW)
            # spkOut = np.tile(spkOut_trial, nReps)

            npts = len(sp1)
            tOut = np.linspace(0, npts / outputRate, npts)
            print("runDPOAE npts=%d len(spkOut)= %d len(tOut)= %d" %
                  (npts, len(sp1), len(tOut)))
            amp_idx = 0
            # ptsPerRep = inputRate

            for amp in ampArray:
                print("runDPOAE freq=" + repr(freq), " amp= ", +amp,
                      " freq_idx= ", freq_idx, " amp_idx= ", amp_idx)
                vOut1, attenLvl1 = audioHW.getCalibratedOutputVoltageAndAttenLevel(
                    freq, amp, 0)
                spkNum = numSpk - 1
                vOut2, attenLvl2 = audioHW.getCalibratedOutputVoltageAndAttenLevel(
                    freq / 1.22, amp, spkNum)
                if vOut1 > 0 and vOut2 > 0:
                    # attenSig = AudioHardware.makeLM1972AttenSig(0)
                    if not testMode:
                        if numSpk > 1:
                            audioHW.setAttenuatorLevel(attenLvl1, attenLvl2,
                                                       daq)
                        else:
                            if attenLvl1 > attenLvl2:
                                dbDiff = attenLvl1 - attenLvl2
                                attenLvl1 = attenLvl2
                                vOut2 = vOut2 * (10**(dbDiff / 20))
                            elif attenLvl1 < attenLvl2:
                                dbDiff = attenLvl2 - attenLvl1
                                attenLvl2 = attenLvl1
                                vOut1 = vOut1 * (10**(dbDiff / 20))

                            audioHW.setAttenuatorLevel(attenLvl1,
                                                       audioHW.maxAtten, daq)

                        # daq.sendDigOutDPOAEd(attenLines, attenSig)
                        # appObj.oct_hw.SetAttenLevel(0, attenLines)

                    pl = appObj.DPOAE_output
                    pl.clear()
                    endIdx = int(5e-3 * outputRate)  # only plot first 5 ms
                    #pl.plot(t[0:endIdx], spkOut[0:endIdx], pen='b')
                    pl.plot(tOut, sp1 + sp2, pen='b')

                    labelStyle = appObj.xLblStyle
                    pl.setLabel('bottom', 'Time', 's', **labelStyle)
                    labelStyle = appObj.yLblStyle
                    pl.setLabel('left', 'Output', 'V', **labelStyle)

                    numInputSamples = int(inputRate * len(sp1) / outputRate)

                    if testMode:
                        # mic_data = OCTCommon.loadRawData(testDataDir, frameNum, dataType=3)
                        pass
                    else:

                        # setup the output task
                        if numSpk > 1:
                            spkOut = np.vstack((vOut1 * sp1, vOut2 * sp2))
                        else:
                            spkOut = vOut1 * sp1 + vOut2 * sp2

                        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)

                        dataIn = daq.readAnalogInput()
                        mic_data = dataIn[0, :]

                        mic_data = mic_data / micVoltsPerPascal

                        daq.stopAnalogInput()
                        daq.stopAnalogOutput()
                        daq.clearAnalogInput()
                        daq.clearAnalogOutput()

                    npts = len(mic_data)
                    t = np.linspace(0, npts / inputRate, npts)
                    pl = appObj.spCal_micInput
                    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)

                    DPOAEptData, DPOAEdata = processDPOAEData(
                        mic_data, freq, freq_idx, amp_idx, freqArray, ampArray,
                        inputRate, DPOAEdata)

                    print("runDPOAE: plotting data")
                    plotDPOAEdata(appObj, DPOAEptData, DPOAEdata)

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

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

                frameNum += 1
                amp_idx += 1

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

            freq_idx += 1

        saveOpts = appObj.getSaveOpts()
        workbook = appObj.excelWB
        note = saveOpts.note
        number = appObj.DPOAEnumber
        name = 'DPOAE'
        d = datetime.datetime.now()
        timeStr = d.strftime('%H_%M_%S')

        saveOpts.saveMicData = appObj.DPOAE_saveMicData_checkBox.isChecked()
        saveOpts.saveMicFFT = appObj.DPOAE_saveMicFFT_checkBox.isChecked()
        saveDir = appObj.saveDir_lineEdit.text()

        plotName = 'DPOAE %d %s %s' % (number, timeStr, saveOpts.note)
        plotFilePath = saveDPOAEDataFig(DPOAEdata, trialDur, saveDir, plotName,
                                        timeStr)

        reply = QtGui.QMessageBox.question(
            appObj, 'Save', "Keep data?",
            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
            QtGui.QMessageBox.Yes)
        if reply == QtGui.QMessageBox.Yes:
            excelWS = CMPCommon.initExcelSpreadsheet(workbook, name, number,
                                                     timeStr, note)
            saveDPOAEDataXLS(DPOAEdata, trialDur, excelWS, saveOpts)
            #saveDPOAEData(DPOAEdata, trialDur, nReps, appObj.saveFileTxt_filepath, saveOpts, timeStr)

            saveDPOAEDataPickle(DPOAEdata, trialDur, plotName, saveOpts,
                                timeStr)
            appObj.DPOAEnumber += 1

        else:
            os.remove(plotFilePath)

    except Exception as ex:
        traceback.print_exc(file=sys.stdout)
        QtGui.QMessageBox.critical(
            appObj, "Error",
            "Error during collection. 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()
예제 #12
0
파일: ABR.py 프로젝트: udayragakiran/PyCMP
def saveABRDataXLS(ABRdata, ABRparams, ws, saveOpts):
    try:
        numFreq = len(ABRdata.freqArray)
        ws.write(2, 0, "Trial duration")
        ws.write(2, 1, "%0.3g" % ABRparams.trialDur)
        ws.write(3, 0, "Stim duration")
        ws.write(3, 1, "%0.3g" % ABRparams.stimDur)
        ws.write(4, 0, "Stim offset")
        ws.write(4, 1, "%0.3g" % ABRparams.stimOffset)
        ws.write(5, 0, "Stim envelope")
        ws.write(5, 1, "%0.3g" % ABRparams.stimEnv)
        ws.write(6, 0, "Trial reps")
        ws.write(6, 1, "%d" % ABRparams.nReps)
        ws.write(7, 0, "Click")
        ws.write(7, 1,  repr(ABRparams.click))
        
       
        # writeExcelFreqAmpHeader(ws, freq, amp, row=0, col=1):
        row = 9
        ws.write(row, 0, 'Response')
        CMPCommon.writeExcelFreqAmpHeader(ws, ABRdata.freqArray, ABRdata.ampArray, row+1, 0)
        CMPCommon.writeExcel2DData(ws, np.round(1e9*ABRdata.ABRResp)/1e3, row+2, 1)

        row = row + numFreq + 2     
        ws.write(row, 0, 'Noise SD')
        CMPCommon.writeExcelFreqAmpHeader(ws, ABRdata.freqArray, ABRdata.ampArray, row+1, 0)
        CMPCommon.writeExcel2DData(ws, np.round(1e9*ABRdata.noise_std)/1e3, row+2, 1)
        
#        row = row + numFreq + 2       
#        ws.write(row, 0, 'Noise Stdev')
#        CMPCommon.writeExcelFreqAmpHeader(ws, ABRdata.freqArray, ABRdata.ampArray, row+1, 0)
#        CMPCommon.writeExcel2DData(ws, ABRdata.noise_mean, row+2, 1)
        
        # save tracings if user has checked box        
        if saveOpts.saveTracings:
            row = row + numFreq + 3
            ws.write(row, 0, 't (ms)')
            col = 2
            for t in ABRdata.t:
                t = round(t*1e6)/1e3
                ws.write(row, col, t)
                col += 1
                
            row += 2
            ws.write(row, 0, 'Freq')
            ws.write(row, 1, 'Amp')
            ws.write(row, 2, 'Averaged Tracing')
            freqArray = ABRdata.freqArray
            ampArray = ABRdata.ampArray
            row += 1
            for f_idx in range(0, len(freqArray)):
                for a_idx in range(0, len(ampArray)):
                    f = freqArray[f_idx]
                    a = ampArray[a_idx]
                    ws.write(row, 0, f)
                    ws.write(row, 1, a)
                    tr = ABRdata.tracings[f_idx, a_idx, :]
                    col = 2
                    for pt in tr:
                        pt = round(pt*1e9)/1e3 # round to nearest nV and conver to uV 
                        ws.write(row, col, pt)
                        col += 1
                    row += 1

    except:
        print('ABR.saveABRDataXLS: Exception writing data to file')        
        traceback.print_exc()
예제 #13
0
def saveDPOAEDataXLS(DPOAEdata, trialDuration, ws, saveOpts):
    try:
        numFreq = len(DPOAEdata.freqArray)
        ws.write(2, 0, "Trial duration")
        ws.write(2, 1, "%0.3g" % trialDuration)
        #ws.write(3, 0, "Trial reps")
        #ws.write(3, 1, "%d" % trialReps)

        # writeExcelFreqAmpHeader(ws, freq, amp, row=0, col=1):
        row = 4
        ws.write(row, 0, 'DP Response')
        CMPCommon.writeExcelFreqAmpHeader(ws, DPOAEdata.freqArray,
                                          DPOAEdata.ampArray, row + 1, 0)
        CMPCommon.writeExcel2DData(ws, DPOAEdata.DPResp, row + 2, 1)

        row = row + numFreq + 2
        ws.write(row, 0, 'F2 Response')
        CMPCommon.writeExcelFreqAmpHeader(ws, DPOAEdata.freqArray,
                                          DPOAEdata.ampArray, row + 1, 0)
        CMPCommon.writeExcel2DData(ws, DPOAEdata.F2Resp, row + 2, 1)

        row = row + numFreq + 2
        ws.write(row, 0, 'F1 Response')
        CMPCommon.writeExcelFreqAmpHeader(ws, DPOAEdata.freqArray,
                                          DPOAEdata.ampArray, row + 1, 0)
        CMPCommon.writeExcel2DData(ws, DPOAEdata.F1Resp, row + 2, 1)

        row = row + numFreq + 2
        ws.write(row, 0, 'Noise Mean')
        CMPCommon.writeExcelFreqAmpHeader(ws, DPOAEdata.freqArray,
                                          DPOAEdata.ampArray, row + 1, 0)
        CMPCommon.writeExcel2DData(ws, DPOAEdata.noise_std, row + 2, 1)

        row = row + numFreq + 2
        ws.write(row, 0, 'Noise Stdev')
        CMPCommon.writeExcelFreqAmpHeader(ws, DPOAEdata.freqArray,
                                          DPOAEdata.ampArray, row + 1, 0)
        CMPCommon.writeExcel2DData(ws, DPOAEdata.noise_mean, row + 2, 1)

        freqArray = DPOAEdata.freqArray
        ampArray = DPOAEdata.ampArray
        row = row + numFreq + 1

        # save tracings if user has checked box
        if saveOpts.saveMicData:
            ws.write(row, 0, 'Averaged Mic')
            row += 1
            ws.write(row, 1, 'Freq (kHz) / Amp')
            ws.write(row, 0, 't (ms)')
            col = 0
            row += 1
            r = row + 1
            for t in DPOAEdata.t:
                ws.write(r, col, t * 1000)
                r += 1

#            ws.write(row+1, 1, 'Amp')
            col = 1
            for f_idx in range(0, len(freqArray)):
                for a_idx in range(0, len(ampArray)):
                    f = freqArray[f_idx]
                    a = ampArray[a_idx]
                    f_div_1k = f / 1000
                    ws.write(row, col, "%0.3g" % f_div_1k + '/' + "%0.3g" % a)
                    r = row + 1
                    tr = DPOAEdata.mic_data[f_idx, a_idx, :]
                    tr = np.round(tr * 1000) / 1000
                    for pt in tr:
                        if not (np.isinf(pt) or np.isnan(pt)):
                            ws.write(r, col, pt)
                        r += 1
                    col += 1
            row = r

        if saveOpts.saveMicFFT:
            ws.write(row, 0, 'Mic FFT Mag (dB SPL)')
            row += 1
            ws.write(row, 1, 'Freq (kHz) / Amp')
            ws.write(row, 0, 'f (kHz)')
            col = 0
            row += 1
            r = row + 1
            for f in DPOAEdata.mic_freq:
                ws.write(r, col, f / 1000)
                r += 1

            col = 1
            for f_idx in range(0, len(freqArray)):
                for a_idx in range(0, len(ampArray)):
                    f = freqArray[f_idx]
                    a = ampArray[a_idx]
                    f_div_1k = f / 1000
                    ws.write(row, col, "%0.3g" % f_div_1k + '/' + "%0.3g" % a)
                    tr = DPOAEdata.mic_fft_mag[f_idx, a_idx, :]
                    tr = np.round(tr * 100) / 100
                    r = row + 1
                    for pt in tr:
                        if not (np.isinf(pt) or np.isnan(pt)):
                            ws.write(r, col, pt)
                        r += 1
                    col += 1
    except:
        print('DPOAE.saveDPOAEDataXLS: Exception writing data to file')
        traceback.print_exc()
예제 #14
0
파일: CM.py 프로젝트: udayragakiran/PyCMP
def runCM(appObj, testMode=False):
    print("runCM")
    
    appObj.tabWidget.setCurrentIndex(4)
    appObj.doneFlag = False
    appObj.isCollecting = True
    # trigRate = octfpga.GetTriggerRate()
    audioHW = appObj.audioHW
    bioamp = appObj.bioamp
    outputRate = audioHW.DAQOutputRate
    inputRate = audioHW.DAQInputRate

    # freq_array2 = audioParams.freq[1, :]
    freqArray = appObj.getFrequencyArray()
    
    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:
        # freqArray = appObj.getFrequencyArray()
        i1 = appObj.CM_freqLow_comboBox.currentIndex()
        i2 = appObj.CM_freqHigh_comboBox.currentIndex()
        print("runCM: i1= ", i1, "i2= ", i2)

        ampLow = appObj.CMampLow_spinBox.value()
        ampHigh = appObj.CMampHigh_spinBox.value()
        ampDelta = appObj.CMampDelta_spinBox.value()
        
        # ampArray = np.arange(ampLow, ampHigh, ampDelta)
        #numSteps = np.floor((ampHigh - ampLow)/ampDelta) + 1
        #ampArray = np.linspace(ampLow, ampHigh, numSteps)
        ampArray = np.arange(ampLow, ampHigh, ampDelta)
        if ampArray[-1] != ampHigh:
            ampArray = np.hstack((ampArray, ampHigh))
        
        freqArray = freqArray[i1:i2+1]

    # numSpk = audioParams.getNumSpeakers()
    if not testMode:
        from DAQHardware import DAQHardware
        daq = DAQHardware()

    chanNamesIn= [ audioHW.mic_daqChan, bioamp.daqChan]
    micVoltsPerPascal = audioHW.micVoltsPerPascal
    trialDur = appObj.CMstimDuration_dblSpinBox.value() * 1e-3
    stimOffset = appObj.CMstimOffset_dblSpinBox.value() * 1e-3
    nReps = appObj.CMtrialReps_spinBox.value()

    # set input rate to three times the highest output frequency, to allow plus a 
    
    #inputRate = 3*freqArray[-1]
    # inputRate = outputRate / int(np.floor(outputRate / inputRate))  # pick closest input rate that evenly divides output rate
    
    
    try:
        frameNum = 0
        isSaveDirInit = False
        chanNameOut = audioHW.speakerL_daqChan 
        attenLines = audioHW.attenL_daqChan
        
        freq_idx = 0
        CMdata = None
        
        for freq in freqArray:
            spkOut_trial = makeCMOutput(freq, trialDur, stimOffset, audioHW)
            spkOut = np.tile(spkOut_trial, nReps)
            
            npts = len(spkOut_trial)
            tOut = np.linspace(0, npts/outputRate, npts)
            print("runCM npts=%d len(spkOut_trial)= %d len(tOut)= %d" % (npts, len(spkOut_trial), len(tOut)))
            amp_idx = 0
            ptsPerRep = inputRate
            
            for amp in ampArray:
                print("runCM freq=" + repr(freq), " amp= ", + amp, " freq_idx= ", freq_idx, " amp_idx= ", amp_idx)
                vOut, attenLvl = audioHW.getCalibratedOutputVoltageAndAttenLevel(freq, amp, 0)
                
                # attenSig = AudioHardware.makeLM1972AttenSig(0)
                if not testMode:
                    # AudioHardware.Attenuator.setLevel(attenLvl, attenLines)
                    audioHW.setAttenuatorLevel(attenLvl, audioHW.maxAtten, daq)
                    # daq.sendDigOutCmd(attenLines, attenSig)
                    # appObj.oct_hw.SetAttenLevel(0, attenLines)
                
                pl = appObj.spCal_output
                pl.clear()
                endIdx = int(5e-3 * outputRate)        # only plot first 5 ms
                #pl.plot(t[0:endIdx], spkOut[0:endIdx], pen='b')
                pl.plot(tOut, spkOut_trial, pen='b')
                
                labelStyle = appObj.xLblStyle
                pl.setLabel('bottom', 'Time', 's', **labelStyle)
                labelStyle = appObj.yLblStyle
                pl.setLabel('left', 'Output', 'V', **labelStyle)
                        
                
                numInputSamples = nReps*int(inputRate*len(spkOut_trial)/outputRate)
                
                
                if testMode:
                    # mic_data = OCTCommon.loadRawData(testDataDir, frameNum, dataType=3)                    
                    pass
                else:
    
                    # setup the output task
                    daq.setupAnalogOutput([chanNameOut], audioHW.daqTrigChanIn, int(outputRate), vOut*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)
                    
                    timeout = numInputSamples/inputRate + 2
                    dataIn = daq.readAnalogInput(timeout)
                    mic_data = dataIn[0, :]
                    bioamp_data = dataIn[1, :]
                    
                    mic_data = mic_data/micVoltsPerPascal
                    bioamp_data = bioamp_data/bioamp.gain
                
                    daq.waitDoneOutput(stopAndClear=True)
                    daq.stopAnalogInput()
                    daq.clearAnalogInput()
                
                npts = len(mic_data)
                t = np.linspace(0, npts/inputRate, npts)
                pl = appObj.spCal_micInput
                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)
    
    # def processCMData(mic_data, bioamp_data, nReps, freq, amp_idx, inputRate, CMdataIn):            
                CMptData, CMdata = processCMData(mic_data, bioamp_data, nReps, freq, freq_idx, amp_idx, freqArray, ampArray, inputRate, CMdata)

                print("runCM: plotting data")
                plotCMdata(appObj, CMptData, CMdata)
                
    #                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
                amp_idx += 1
                
            # if done flag, break out of loop
            if appObj.doneFlag:
                break
            
            freq_idx += 1


        saveOpts = appObj.getSaveOpts()
        workbook = appObj.excelWB
        note = saveOpts.note
        number = appObj.CMnumber
        name = 'CM'
        d = datetime.datetime.now()
        timeStr = d.strftime('%H_%M_%S')
        excelWS = CMPCommon.initExcelSpreadsheet(workbook, name, number, timeStr, note)
    
        appObj.CMnumber += 1                
        saveOpts.saveTracings = appObj.CM_saveTracings_checkBox.isChecked(  )
        saveDir = appObj.saveDir_lineEdit.text()
        saveCMDataXLS(CMdata, trialDur, nReps, excelWS, saveOpts)
        #saveCMData(CMdata, trialDur, nReps, appObj.saveFileTxt_filepath, saveOpts, timeStr)
        
        plotName = 'CM %d %s %s' % (number, timeStr, saveOpts.note)
        saveCMDataFig(CMdata, trialDur, nReps, saveDir, plotName, timeStr)
        saveCMDataPickle(CMdata, trialDur, nReps, plotName, saveOpts, timeStr)
            
    except Exception as ex:
        traceback.print_exc(file=sys.stdout)
        QtGui.QMessageBox.critical (appObj, "Error", "Error during collection. 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()
예제 #15
0
def runDPOAE(appObj, testMode=False):
    print("runDPOAE")
    
    try:
        appObj.tabWidget.setCurrentIndex(2)
        appObj.doneFlag = False
        appObj.isCollecting = True
        # trigRate = octfpga.GetTriggerRate()
        audioHW = appObj.audioHW
        bioamp = appObj.bioamp
        outputRate = audioHW.DAQOutputRate
        inputRate = audioHW.DAQInputRate
    
        # freq_array2 = audioParams.freq[1, :]
        freqArray = appObj.getFrequencyArray()
        
        if testMode:
            testDataDir = os.path.join(appObj.basePath, 'exampledata', 'DPOAE')
    #        filePath = os.path.join(testDataDir, 'AudioParams.pickle')
    #        f = open(filePath, 'rb')
    #        audioParams = pickle.load(f)
    #        f.close()
        else:
            # freqArray = appObj.getFrequencyArray()
            i1 = appObj.DPOAE_freqLow_comboBox.currentIndex()
            i2 = appObj.DPOAE_freqHigh_comboBox.currentIndex()
            print("runDPOAE: i1= ", i1, "i2= ", i2)
    
            ampLow = appObj.DPOAE_ampLow_spinBox.value()
            ampHigh = appObj.DPOAE_ampHigh_spinBox.value()
            ampDelta = appObj.DPOAE_ampDelta_spinBox.value()
            
            # ampArray = np.arange(ampLow, ampHigh, ampDelta)
            #numSteps = np.floor((ampHigh - ampLow)/ampDelta) + 1
            #ampArray = np.linspace(ampLow, ampHigh, numSteps)
            ampArray = np.arange(ampLow, ampHigh, ampDelta)
            if ampArray[-1] != ampHigh:
                ampArray = np.hstack((ampArray, ampHigh))
            
            freqArray = freqArray[i1:i2+1]
    
        # numSpk = audioParams.getNumSpeakers()
        if not testMode:
            from DAQHardware import DAQHardware
            daq = DAQHardware()
    
        chanNamesIn= [ audioHW.mic_daqChan, bioamp.daqChan]
        micVoltsPerPascal = audioHW.micVoltsPerPascal
        trialDur = appObj.DPOAE_stimDuration_dblSpinBox.value() * 1e-3
        # nReps = appObj.DPOAEtrialReps_spinBox.value()
    
        # set input rate multiple the highest output frequency, a little more than Nyquest so stim frequency is more towards center 
        inputRate = 4*freqArray[-1]
        inputRate = outputRate / int(np.floor(outputRate / inputRate))  # pick closest input rate that evenly divides output rate
        
        frameNum = 0
        isSaveDirInit = False

        attenLines1 = audioHW.attenL_daqChan
        attenLines2 = audioHW.attenR_daqChan
        
        freq_idx = 0
        DPOAEdata = None
        numSpk = appObj.speaker_comboBox.currentIndex()+1
        chanNameOut = audioHW.speakerL_daqChan 
        if numSpk > 1:
            chanNameOut = [audioHW.speakerL_daqChan, audioHW.speakerR_daqChan ]
        print("runDPOAE numSpk=", numSpk)
        
        for freq in freqArray:
            sp1, sp2 = makeDPOAEOutput(freq, trialDur, audioHW)
            # spkOut = np.tile(spkOut_trial, nReps)
            
            npts = len(sp1)
            tOut = np.linspace(0, npts/outputRate, npts)
            print("runDPOAE npts=%d len(spkOut)= %d len(tOut)= %d" % (npts, len(sp1), len(tOut)))
            amp_idx = 0
            # ptsPerRep = inputRate
            
            for amp in ampArray:
                print("runDPOAE freq=" + repr(freq), " amp= ", + amp, " freq_idx= ", freq_idx, " amp_idx= ", amp_idx)
                vOut1, attenLvl1 = audioHW.getCalibratedOutputVoltageAndAttenLevel(freq, amp, 0)
                spkNum = numSpk - 1
                vOut2, attenLvl2 = audioHW.getCalibratedOutputVoltageAndAttenLevel(freq/1.22, amp, spkNum)
                if vOut1 > 0 and vOut2 > 0:
                    # attenSig = AudioHardware.makeLM1972AttenSig(0)
                    if not testMode:
                        if numSpk > 1:
                            audioHW.setAttenuatorLevel(attenLvl1, attenLvl2, daq)
                        else:
                            if attenLvl1 > attenLvl2:
                                dbDiff = attenLvl1 - attenLvl2
                                attenLvl1 = attenLvl2
                                vOut2 = vOut2*(10**(dbDiff/20))
                            elif attenLvl1 < attenLvl2:
                                dbDiff = attenLvl2 - attenLvl1
                                attenLvl2 = attenLvl1
                                vOut1 = vOut1*(10**(dbDiff/20))
                                
                            audioHW.setAttenuatorLevel(attenLvl1, audioHW.maxAtten, daq)
                            
                        # daq.sendDigOutDPOAEd(attenLines, attenSig)
                        # appObj.oct_hw.SetAttenLevel(0, attenLines)
                    
                    pl = appObj.DPOAE_output
                    pl.clear()
                    endIdx = int(5e-3 * outputRate)        # only plot first 5 ms
                    #pl.plot(t[0:endIdx], spkOut[0:endIdx], pen='b')
                    pl.plot(tOut, sp1 + sp2, pen='b')
                    
                    labelStyle = appObj.xLblStyle
                    pl.setLabel('bottom', 'Time', 's', **labelStyle)
                    labelStyle = appObj.yLblStyle
                    pl.setLabel('left', 'Output', 'V', **labelStyle)
                    
                    numInputSamples = int(inputRate*len(sp1)/outputRate)
                    
                    if testMode:
                        # mic_data = OCTCommon.loadRawData(testDataDir, frameNum, dataType=3)                    
                        pass
                    else:
        
                        # setup the output task
                        if numSpk > 1:
                            spkOut = np.vstack((vOut1*sp1, vOut2*sp2))
                        else:
                            spkOut = vOut1*sp1 + vOut2*sp2
                            
                        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)
                        
                        dataIn = daq.readAnalogInput()
                        mic_data = dataIn[0, :]
                        
                        mic_data = mic_data/micVoltsPerPascal
                    
                        daq.stopAnalogInput()
                        daq.stopAnalogOutput()
                        daq.clearAnalogInput()
                        daq.clearAnalogOutput()
                    
                    npts = len(mic_data)
                    t = np.linspace(0, npts/inputRate, npts)
                    pl = appObj.spCal_micInput
                    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)
        
                    DPOAEptData, DPOAEdata = processDPOAEData(mic_data, freq, freq_idx, amp_idx, freqArray, ampArray, inputRate, DPOAEdata)
    
                    print("runDPOAE: plotting data")
                    plotDPOAEdata(appObj, DPOAEptData, DPOAEdata)
                    
                QtGui.QApplication.processEvents() # check for GUI events, such as button presses
                
                # if done flag, break out of loop
                if appObj.doneFlag:
                    break
                
                frameNum += 1
                amp_idx += 1
                
            # if done flag, break out of loop
            if appObj.doneFlag:
                break
            
            freq_idx += 1


        saveOpts = appObj.getSaveOpts()
        workbook = appObj.excelWB
        note = saveOpts.note
        number = appObj.DPOAEnumber
        name = 'DPOAE'
        d = datetime.datetime.now()
        timeStr = d.strftime('%H_%M_%S')
        
        saveOpts.saveMicData = appObj.DPOAE_saveMicData_checkBox.isChecked()
        saveOpts.saveMicFFT = appObj.DPOAE_saveMicFFT_checkBox.isChecked()
        saveDir = appObj.saveDir_lineEdit.text()
        
        plotName = 'DPOAE %d %s %s' % (number, timeStr, saveOpts.note)
        plotFilePath = saveDPOAEDataFig(DPOAEdata, trialDur, saveDir, plotName, timeStr)
        
        reply = QtGui.QMessageBox.question(appObj, 'Save', "Keep data?" , QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.Yes)
        if reply == QtGui.QMessageBox.Yes:
            excelWS = CMPCommon.initExcelSpreadsheet(workbook, name, number, timeStr, note)
            saveDPOAEDataXLS(DPOAEdata, trialDur, excelWS, saveOpts)
            #saveDPOAEData(DPOAEdata, trialDur, nReps, appObj.saveFileTxt_filepath, saveOpts, timeStr)
            
            saveDPOAEDataPickle(DPOAEdata, trialDur, plotName, saveOpts, timeStr)
            appObj.DPOAEnumber += 1                
            
        else:
            os.remove(plotFilePath)
            
    except Exception as ex:
        traceback.print_exc(file=sys.stdout)
        QtGui.QMessageBox.critical (appObj, "Error", "Error during collection. 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()
예제 #16
0
파일: ABR.py 프로젝트: udayragakiran/PyCMP
def saveABRDataXLS(ABRdata, ABRparams, ws, saveOpts):
    try:
        numFreq = len(ABRdata.freqArray)
        ws.write(2, 0, "Trial duration")
        ws.write(2, 1, "%0.3g" % ABRparams.trialDur)
        ws.write(3, 0, "Stim duration")
        ws.write(3, 1, "%0.3g" % ABRparams.stimDur)
        ws.write(4, 0, "Stim offset")
        ws.write(4, 1, "%0.3g" % ABRparams.stimOffset)
        ws.write(5, 0, "Stim envelope")
        ws.write(5, 1, "%0.3g" % ABRparams.stimEnv)
        ws.write(6, 0, "Trial reps")
        ws.write(6, 1, "%d" % ABRparams.nReps)
        ws.write(7, 0, "Click")
        ws.write(7, 1, repr(ABRparams.click))

        # writeExcelFreqAmpHeader(ws, freq, amp, row=0, col=1):
        row = 9
        ws.write(row, 0, 'Response')
        CMPCommon.writeExcelFreqAmpHeader(ws, ABRdata.freqArray,
                                          ABRdata.ampArray, row + 1, 0)
        CMPCommon.writeExcel2DData(ws,
                                   np.round(1e9 * ABRdata.ABRResp) / 1e3,
                                   row + 2, 1)

        row = row + numFreq + 2
        ws.write(row, 0, 'Noise SD')
        CMPCommon.writeExcelFreqAmpHeader(ws, ABRdata.freqArray,
                                          ABRdata.ampArray, row + 1, 0)
        CMPCommon.writeExcel2DData(ws,
                                   np.round(1e9 * ABRdata.noise_std) / 1e3,
                                   row + 2, 1)

        #        row = row + numFreq + 2
        #        ws.write(row, 0, 'Noise Stdev')
        #        CMPCommon.writeExcelFreqAmpHeader(ws, ABRdata.freqArray, ABRdata.ampArray, row+1, 0)
        #        CMPCommon.writeExcel2DData(ws, ABRdata.noise_mean, row+2, 1)

        # save tracings if user has checked box
        if saveOpts.saveTracings:
            row = row + numFreq + 3
            ws.write(row, 0, 't (ms)')
            col = 2
            for t in ABRdata.t:
                t = round(t * 1e6) / 1e3
                ws.write(row, col, t)
                col += 1

            row += 2
            ws.write(row, 0, 'Freq')
            ws.write(row, 1, 'Amp')
            ws.write(row, 2, 'Averaged Tracing')
            freqArray = ABRdata.freqArray
            ampArray = ABRdata.ampArray
            row += 1
            for f_idx in range(0, len(freqArray)):
                for a_idx in range(0, len(ampArray)):
                    f = freqArray[f_idx]
                    a = ampArray[a_idx]
                    ws.write(row, 0, f)
                    ws.write(row, 1, a)
                    tr = ABRdata.tracings[f_idx, a_idx, :]
                    col = 2
                    for pt in tr:
                        pt = round(
                            pt *
                            1e9) / 1e3  # round to nearest nV and conver to uV
                        ws.write(row, col, pt)
                        col += 1
                    row += 1

    except:
        print('ABR.saveABRDataXLS: Exception writing data to file')
        traceback.print_exc()
예제 #17
0
파일: ABR.py 프로젝트: udayragakiran/PyCMP
def runABR(appObj, testMode=False):
    print("runABR")

    appObj.tabWidget.setCurrentIndex(3)
    appObj.doneFlag = False
    appObj.isCollecting = True
    # trigRate = octfpga.GetTriggerRate()
    audioHW = appObj.audioHW
    bioamp = appObj.bioamp
    outputRate = audioHW.DAQOutputRate
    inputRate = audioHW.DAQInputRate

    # freq_array2 = audioParams.freq[1, :]
    freqArray = appObj.getFrequencyArray()
    ABRparams = ABRParams(appObj)

    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:
        # freqArray = appObj.getFrequencyArray()
        i1 = appObj.ABR_freqLow_comboBox.currentIndex()
        i2 = appObj.ABR_freqHigh_comboBox.currentIndex()
        print("runABR: i1= ", i1, "i2= ", i2)
        ampLow = appObj.ABRampLow_spinBox.value()
        ampHigh = appObj.ABRampHigh_spinBox.value()
        ampDelta = appObj.ABRampDelta_spinBox.value()

        # ampArray = np.arange(ampLow, ampHigh, ampDelta)
        #numSteps = np.floor((ampHigh - ampLow)/ampDelta) + 1
        #ampArray = np.linspace(ampLow, ampHigh, numSteps)
        if ampLow == ampHigh:
            ampArray = np.array([ampLow])
        else:
            ampArray = np.arange(ampLow, ampHigh, ampDelta)
            if ampArray[-1] != ampHigh:
                ampArray = np.hstack((ampArray, ampHigh))

        freqArray = freqArray[i1:i2 + 1]

    if ABRparams.click:
        freqArray = freqArray[0:1]  # only use single freqeucny
        clickRMS = appObj.ABRclick_RMS

    # numSpk = audioParams.getNumSpeakers()
    if not testMode:
        from DAQHardware import DAQHardware
        daq = DAQHardware()

    chanNamesIn = [audioHW.mic_daqChan, bioamp.daqChan]
    micVoltsPerPascal = audioHW.micVoltsPerPascal

    # set input rate to three times the highest output frequency, to allow plus a

    #    inputRate = 3*freqArray[-1]
    #    print("runABR: outputRate= ", outputRate, " inputRate= ", inputRate)
    #    inputRate = np.max((inputRate, 6e3))   # inpute rate should be at least 6 kHz because ABR responses occur 0.3 - 3 kHz
    #    inputRate = outputRate / int(np.floor(outputRate / inputRate))  # pick closest input rate that evenly divides output rate
    #    print("runABR: inputRate(final)= ", inputRate)

    try:
        frameNum = 0
        numFrames = len(freqArray) * len(ampArray)
        isSaveDirInit = False
        chanNameOut = audioHW.speakerL_daqChan
        attenLines = audioHW.attenL_daqChan

        freq_idx = 0
        ABRdata = None
        appObj.status_label.setText("Running")
        appObj.progressBar.setValue(0)

        for freq in freqArray:
            spkOut_trial = makeABROutput(freq, ABRparams, audioHW)
            npts = len(spkOut_trial)
            spkOut = np.tile(spkOut_trial, ABRparams.nReps)
            # invert every other trial, necessary for ABR/CAP output
            for n in range(1, ABRparams.nReps, 2):
                idx1 = n * npts
                idx2 = (n + 1) * npts
                spkOut[idx1:idx2] = -spkOut[idx1:idx2]
#            plt.figure(5)
#            plt.clf()
#            plt.plot(spkOut)
            tOut = np.linspace(0, npts / outputRate, npts)
            print("runABR npts=%d len(spkOut_trial)= %d len(tOut)= %d" %
                  (npts, len(spkOut_trial), len(tOut)))
            amp_idx = 0
            ptsPerRep = int(inputRate * ABRparams.trialDur)

            for amp in ampArray:
                print("runABR freq=" + repr(freq), " amp= ", +amp,
                      " freq_idx= ", freq_idx, " amp_idx= ", amp_idx)
                if ABRparams.click:
                    clickRMS = appObj.ABRclick_RMS
                    attenLvl = 0
                    vOut = 10**((amp - clickRMS) / 20)
                    minV = audioHW.speakerOutputRng[0]
                    if vOut < minV:
                        attenLvl = int(round(20 * np.log10(minV / vOut)))
                        vOut = minV
                else:
                    vOut, attenLvl = audioHW.getCalibratedOutputVoltageAndAttenLevel(
                        freq, amp, 0)

                print("runABR vOut= ", vOut, " atenLvl=", attenLvl)

                if vOut > audioHW.speakerOutputRng[1]:
                    print("runABR vOut= ", vOut, "  out of range")
                    continue
                elif attenLvl > audioHW.maxAtten:
                    print("runABR attenLvl= ", attenLvl,
                          "  gerater than maximum attenuation")
                    continue

                # attenSig = AudioHardware.makeLM1972AttenSig(0)
                if not testMode:
                    AudioHardware.Attenuator.setLevel(attenLvl, attenLines)
                    # daq.sendDigOutABRd(attenLines, attenSig)
                    # appObj.oct_hw.SetAttenLevel(0, attenLines)

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

                labelStyle = appObj.xLblStyle
                pl.setLabel('bottom', 'Time', 's', **labelStyle)
                labelStyle = appObj.yLblStyle
                pl.setLabel('left', 'Output', 'V', **labelStyle)

                numInputSamples = ABRparams.nReps * int(
                    inputRate * len(spkOut_trial) / outputRate)

                if testMode:
                    # mic_data = OCTCommon.loadRawData(testDataDir, frameNum, dataType=3)
                    pass
                else:

                    # setup the output task
                    daq.setupAnalogOutput([chanNameOut], audioHW.daqTrigChanIn,
                                          int(outputRate), vOut * 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)

                    timeout = numInputSamples / inputRate + 2
                    dataIn = daq.readAnalogInput(timeout)
                    mic_data = dataIn[0, :]
                    bioamp_data = dataIn[1, :]

                    mic_data = mic_data / micVoltsPerPascal
                    bioamp_data = bioamp_data / bioamp.gain

                    daq.waitDoneInput()
                    daq.stopAnalogInput()
                    daq.clearAnalogInput()

                    daq.waitDoneOutput(stopAndClear=True)


#                npts = len(mic_data)
#                t = np.linspace(0, npts/inputRate, npts)
#                pl = appObj.ABR_micInput
#                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)

# def processABRData(mic_data, bioamp_data, nReps, freq, amp_idx, inputRate, ABRdataIn):
                ABRptData, ABRdata = processABRData(mic_data, bioamp_data,
                                                    freq, freq_idx, amp_idx,
                                                    freqArray, ampArray,
                                                    inputRate, ABRdata,
                                                    ABRparams)

                print("runABR: plotting data")
                plotABRdata(appObj, ABRptData, ABRdata)

                #                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)
                idx1 = round(inputRate * ABRparams.stimOffset)
                idx2 = idx1 + round(inputRate * ABRparams.stimDur)

                mic_data = mic_data[idx1:idx2]
                rms = np.mean(mic_data**2)**0.5
                rms = 20 * np.log10(rms / 2e-5)

                appObj.ABR_rms_label.setText("%0.1f dB" % rms)

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

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

                frameNum += 1
                amp_idx += 1
                appObj.progressBar.setValue(frameNum / numFrames)

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

            freq_idx += 1

        saveOpts = appObj.getSaveOpts()
        workbook = appObj.excelWB
        note = saveOpts.note
        number = appObj.ABRnumber
        name = 'ABR'
        d = datetime.datetime.now()
        timeStr = d.strftime('%H_%M_%S')
        excelWS = CMPCommon.initExcelSpreadsheet(workbook, name, number,
                                                 timeStr, note)

        appObj.ABRnumber += 1
        #saveOpts.saveTracings = appObj.ABR_saveTracings_checkBox.isChecked()
        saveOpts.saveTracings = True
        saveDir = appObj.saveDir_lineEdit.text()
        saveABRDataXLS(ABRdata, ABRparams, excelWS, saveOpts)
        #saveABRData(ABRdata, trialDur, nReps, appObj.saveFileTxt_filepath, saveOpts, timeStr)

        plotName = 'ABR %d %s %s' % (number, timeStr, saveOpts.note)
        saveABRDataFig(ABRdata, ABRparams, saveDir, plotName, timeStr)
        saveABRDataPickle(ABRdata, ABRparams, plotName, saveOpts, timeStr)

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

    # update the audio hardware speaker calibration
    appObj.isCollecting = False
    QtGui.QApplication.processEvents(
    )  # check for GUI events, such as button presses
    appObj.finishCollection()
예제 #18
0
def saveDPOAEDataXLS(DPOAEdata, trialDuration, ws, saveOpts):
    try:
        numFreq = len(DPOAEdata.freqArray)
        ws.write(2, 0, "Trial duration")
        ws.write(2, 1, "%0.3g" % trialDuration)
        #ws.write(3, 0, "Trial reps")
        #ws.write(3, 1, "%d" % trialReps)
       
        # writeExcelFreqAmpHeader(ws, freq, amp, row=0, col=1):
        row = 4
        ws.write(row, 0, 'DP Response')
        CMPCommon.writeExcelFreqAmpHeader(ws, DPOAEdata.freqArray, DPOAEdata.ampArray, row+1, 0)
        CMPCommon.writeExcel2DData(ws, DPOAEdata.DPResp, row+2, 1)

        row = row + numFreq + 2     
        ws.write(row, 0, 'F2 Response')
        CMPCommon.writeExcelFreqAmpHeader(ws, DPOAEdata.freqArray, DPOAEdata.ampArray, row+1, 0)
        CMPCommon.writeExcel2DData(ws, DPOAEdata.F2Resp, row+2, 1)

        row = row + numFreq + 2     
        ws.write(row, 0, 'F1 Response')
        CMPCommon.writeExcelFreqAmpHeader(ws, DPOAEdata.freqArray, DPOAEdata.ampArray, row+1, 0)
        CMPCommon.writeExcel2DData(ws, DPOAEdata.F1Resp, row+2, 1)

        row = row + numFreq + 2     
        ws.write(row, 0, 'Noise Mean')
        CMPCommon.writeExcelFreqAmpHeader(ws, DPOAEdata.freqArray, DPOAEdata.ampArray, row+1, 0)
        CMPCommon.writeExcel2DData(ws, DPOAEdata.noise_std, row+2, 1)
        
        row = row + numFreq + 2       
        ws.write(row, 0, 'Noise Stdev')
        CMPCommon.writeExcelFreqAmpHeader(ws, DPOAEdata.freqArray, DPOAEdata.ampArray, row+1, 0)
        CMPCommon.writeExcel2DData(ws, DPOAEdata.noise_mean, row+2, 1)

        freqArray = DPOAEdata.freqArray
        ampArray = DPOAEdata.ampArray
        row = row + numFreq + 1
        
        # save tracings if user has checked box        
        if saveOpts.saveMicData:
            ws.write(row, 0, 'Averaged Mic')
            row += 1
            ws.write(row, 1, 'Freq (kHz) / Amp')
            ws.write(row, 0, 't (ms)')
            col = 0
            row += 1
            r = row + 1
            for t in DPOAEdata.t:
                ws.write(r, col, t*1000)
                r += 1
            
#            ws.write(row+1, 1, 'Amp')
            col = 1
            for f_idx in range(0, len(freqArray)):
                for a_idx in range(0, len(ampArray)):
                    f = freqArray[f_idx]
                    a = ampArray[a_idx]
                    f_div_1k = f/1000
                    ws.write(row, col, "%0.3g" % f_div_1k + '/' + "%0.3g" % a)
                    r = row + 1
                    tr = DPOAEdata.mic_data[f_idx, a_idx, :]
                    tr = np.round(tr*1000)/1000
                    for pt in tr:
                        if not (np.isinf(pt) or np.isnan(pt)):
                            ws.write(r, col, pt)
                        r += 1
                    col += 1
            row = r
            
        if saveOpts.saveMicFFT:
            ws.write(row, 0, 'Mic FFT Mag (dB SPL)')
            row += 1
            ws.write(row, 1, 'Freq (kHz) / Amp')
            ws.write(row, 0, 'f (kHz)')
            col = 0
            row += 1
            r = row+1
            for f in DPOAEdata.mic_freq:
                ws.write(r, col, f/1000)
                r += 1
                
            col = 1
            for f_idx in range(0, len(freqArray)):
                for a_idx in range(0, len(ampArray)):
                    f = freqArray[f_idx]
                    a = ampArray[a_idx]
                    f_div_1k = f/1000
                    ws.write(row, col, "%0.3g" % f_div_1k + '/' + "%0.3g" % a)
                    tr = DPOAEdata.mic_fft_mag[f_idx, a_idx, :]
                    tr = np.round(tr*100)/100
                    r = row + 1
                    for pt in tr:
                        if not (np.isinf(pt) or np.isnan(pt)):
                            ws.write(r, col, pt)
                        r += 1
                    col += 1
    except:
        print('DPOAE.saveDPOAEDataXLS: Exception writing data to file')        
        traceback.print_exc()
예제 #19
0
파일: CM.py 프로젝트: udayragakiran/PyCMP
def runCM(appObj, testMode=False):
    print("runCM")

    appObj.tabWidget.setCurrentIndex(4)
    appObj.doneFlag = False
    appObj.isCollecting = True
    # trigRate = octfpga.GetTriggerRate()
    audioHW = appObj.audioHW
    bioamp = appObj.bioamp
    outputRate = audioHW.DAQOutputRate
    inputRate = audioHW.DAQInputRate

    # freq_array2 = audioParams.freq[1, :]
    freqArray = appObj.getFrequencyArray()

    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:
        # freqArray = appObj.getFrequencyArray()
        i1 = appObj.CM_freqLow_comboBox.currentIndex()
        i2 = appObj.CM_freqHigh_comboBox.currentIndex()
        print("runCM: i1= ", i1, "i2= ", i2)

        ampLow = appObj.CMampLow_spinBox.value()
        ampHigh = appObj.CMampHigh_spinBox.value()
        ampDelta = appObj.CMampDelta_spinBox.value()

        # ampArray = np.arange(ampLow, ampHigh, ampDelta)
        #numSteps = np.floor((ampHigh - ampLow)/ampDelta) + 1
        #ampArray = np.linspace(ampLow, ampHigh, numSteps)
        ampArray = np.arange(ampLow, ampHigh, ampDelta)
        if ampArray[-1] != ampHigh:
            ampArray = np.hstack((ampArray, ampHigh))

        freqArray = freqArray[i1:i2 + 1]

    # numSpk = audioParams.getNumSpeakers()
    if not testMode:
        from DAQHardware import DAQHardware
        daq = DAQHardware()

    chanNamesIn = [audioHW.mic_daqChan, bioamp.daqChan]
    micVoltsPerPascal = audioHW.micVoltsPerPascal
    trialDur = appObj.CMstimDuration_dblSpinBox.value() * 1e-3
    stimOffset = appObj.CMstimOffset_dblSpinBox.value() * 1e-3
    nReps = appObj.CMtrialReps_spinBox.value()

    # set input rate to three times the highest output frequency, to allow plus a

    #inputRate = 3*freqArray[-1]
    # inputRate = outputRate / int(np.floor(outputRate / inputRate))  # pick closest input rate that evenly divides output rate

    try:
        frameNum = 0
        isSaveDirInit = False
        chanNameOut = audioHW.speakerL_daqChan
        attenLines = audioHW.attenL_daqChan

        freq_idx = 0
        CMdata = None

        for freq in freqArray:
            spkOut_trial = makeCMOutput(freq, trialDur, stimOffset, audioHW)
            spkOut = np.tile(spkOut_trial, nReps)

            npts = len(spkOut_trial)
            tOut = np.linspace(0, npts / outputRate, npts)
            print("runCM npts=%d len(spkOut_trial)= %d len(tOut)= %d" %
                  (npts, len(spkOut_trial), len(tOut)))
            amp_idx = 0
            ptsPerRep = inputRate

            for amp in ampArray:
                print("runCM freq=" + repr(freq), " amp= ", +amp,
                      " freq_idx= ", freq_idx, " amp_idx= ", amp_idx)
                vOut, attenLvl = audioHW.getCalibratedOutputVoltageAndAttenLevel(
                    freq, amp, 0)

                # attenSig = AudioHardware.makeLM1972AttenSig(0)
                if not testMode:
                    # AudioHardware.Attenuator.setLevel(attenLvl, attenLines)
                    audioHW.setAttenuatorLevel(attenLvl, audioHW.maxAtten, daq)
                    # daq.sendDigOutCmd(attenLines, attenSig)
                    # appObj.oct_hw.SetAttenLevel(0, attenLines)

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

                labelStyle = appObj.xLblStyle
                pl.setLabel('bottom', 'Time', 's', **labelStyle)
                labelStyle = appObj.yLblStyle
                pl.setLabel('left', 'Output', 'V', **labelStyle)

                numInputSamples = nReps * int(
                    inputRate * len(spkOut_trial) / outputRate)

                if testMode:
                    # mic_data = OCTCommon.loadRawData(testDataDir, frameNum, dataType=3)
                    pass
                else:

                    # setup the output task
                    daq.setupAnalogOutput([chanNameOut], audioHW.daqTrigChanIn,
                                          int(outputRate), vOut * 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)

                    timeout = numInputSamples / inputRate + 2
                    dataIn = daq.readAnalogInput(timeout)
                    mic_data = dataIn[0, :]
                    bioamp_data = dataIn[1, :]

                    mic_data = mic_data / micVoltsPerPascal
                    bioamp_data = bioamp_data / bioamp.gain

                    daq.waitDoneOutput(stopAndClear=True)
                    daq.stopAnalogInput()
                    daq.clearAnalogInput()

                npts = len(mic_data)
                t = np.linspace(0, npts / inputRate, npts)
                pl = appObj.spCal_micInput
                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)

                # def processCMData(mic_data, bioamp_data, nReps, freq, amp_idx, inputRate, CMdataIn):
                CMptData, CMdata = processCMData(mic_data, bioamp_data, nReps,
                                                 freq, freq_idx, amp_idx,
                                                 freqArray, ampArray,
                                                 inputRate, CMdata)

                print("runCM: plotting data")
                plotCMdata(appObj, CMptData, CMdata)

                #                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
                amp_idx += 1

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

            freq_idx += 1

        saveOpts = appObj.getSaveOpts()
        workbook = appObj.excelWB
        note = saveOpts.note
        number = appObj.CMnumber
        name = 'CM'
        d = datetime.datetime.now()
        timeStr = d.strftime('%H_%M_%S')
        excelWS = CMPCommon.initExcelSpreadsheet(workbook, name, number,
                                                 timeStr, note)

        appObj.CMnumber += 1
        saveOpts.saveTracings = appObj.CM_saveTracings_checkBox.isChecked()
        saveDir = appObj.saveDir_lineEdit.text()
        saveCMDataXLS(CMdata, trialDur, nReps, excelWS, saveOpts)
        #saveCMData(CMdata, trialDur, nReps, appObj.saveFileTxt_filepath, saveOpts, timeStr)

        plotName = 'CM %d %s %s' % (number, timeStr, saveOpts.note)
        saveCMDataFig(CMdata, trialDur, nReps, saveDir, plotName, timeStr)
        saveCMDataPickle(CMdata, trialDur, nReps, plotName, saveOpts, timeStr)

    except Exception as ex:
        traceback.print_exc(file=sys.stdout)
        QtGui.QMessageBox.critical(
            appObj, "Error",
            "Error during collection. 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()
예제 #20
0
    path, fName = os.path.split(filepath)
    print("loading ", fName)
    r = re.split(' ', fName)
    all_types.append(r[0])
    all_numbers.append(int(r[1]))
    filepath = os.path.join(dataDir, fName)
    f = open(filepath, 'rb')
    data = pickle.load(f)
    f.close()
    all_data.append(data)

d = datetime.datetime.now()
timeStr = d.strftime('%Y-%m-%d %H_%M_%S')
filename = 'PyCMP ' + timeStr + '.xlsx'
filepath = os.path.join(dataDir, filename)
wb = CMPCommon.initExcelWorkbook(filepath)

for data, name, number in zip(all_data, all_types, all_numbers):
    try:
        saveOpts = CMPCommon.SaveOpts()
        print('writing ', name, ' ', number, ' to Excel spreadsheet')
        
        if name == 'CM':
            saveOpts.saveTracings = data.tracings is not None
                
            timeStr = data.timeStamp
            ws = CMPCommon.initExcelSpreadsheet(wb, name, number, timeStr, data.note)
            CM.saveCMDataXLS(data, data.trialDuration, data.trialReps, ws, saveOpts)
        elif name == 'DPOAE':
            saveOpts.saveMicData = data.mic_data is not None
            saveOpts.saveMicFFT = data.mic_fft_mag is not None
예제 #21
0
파일: CM.py 프로젝트: udayragakiran/PyCMP
def saveCMDataXLS(CMdata, trialDuration, trialReps, ws, saveOpts):
    try:
        numFreq = len(CMdata.freqArray)
        ws.write(2, 0, "Trial duration")
        ws.write(2, 1, "%0.3g" % trialDuration)
        ws.write(3, 0, "Trial reps")
        ws.write(3, 1, "%d" % trialReps)
       
        # writeExcelFreqAmpHeader(ws, freq, amp, row=0, col=1):
        row = 6
        ws.write(row, 0, 'Response  (uV)')
        CMPCommon.writeExcelFreqAmpHeader(ws, CMdata.freqArray, CMdata.ampArray, row+1, 0)
        data = CMdata.CMResp * 1e9  
        data = np.round(data)/1e3 # convert to uV
        CMPCommon.writeExcel2DData(ws, data, row+2, 1)

        row = row + numFreq + 2     
        ws.write(row, 0, 'Noise Mean (uV)')
        CMPCommon.writeExcelFreqAmpHeader(ws, CMdata.freqArray, CMdata.ampArray, row+1, 0)
        data = CMdata.noise_mean * 1e9  
        data = np.round(data)/1e3 # convert to uV
        CMPCommon.writeExcel2DData(ws, data, row+2, 1)
        
        row = row + numFreq + 2       
        ws.write(row, 0, 'Noise Stdev (uV)')
        CMPCommon.writeExcelFreqAmpHeader(ws, CMdata.freqArray, CMdata.ampArray, row+1, 0)
        data = CMdata.noise_std * 1e9  
        data = np.round(data)/1e3 # round and convert to uV
        CMPCommon.writeExcel2DData(ws, CMdata.noise_mean, row+2, 1)
        
        # save tracings if user has checked box        
        if saveOpts.saveTracings:
            row = row + numFreq + 3
            ws.write(row, 0, 't (ms)')
            col = 2
            for t in CMdata.t:
                t = t*1e6 
                t = np.round(t)/1e3 # convert to ms
                ws.write(row, col, t)
                col += 1
                
            row += 2
            ws.write(row, 0, 'Freq')
            ws.write(row, 1, 'Amp')
            ws.write(row, 2, 'Averaged Bioamp Tracing (uV)')
            freqArray = CMdata.freqArray
            ampArray = CMdata.ampArray
            row += 1
            for f_idx in range(0, len(freqArray)):
                for a_idx in range(0, len(ampArray)):
                    f = freqArray[f_idx]
                    a = ampArray[a_idx]
                    ws.write(row, 0, f)
                    ws.write(row, 1, a)
                    tr = CMdata.tracings[f_idx, a_idx, :]
                    tr = tr*1e9
                    tr = np.round(tr)/1e3  # round to nearest nv and conver tto uV
                    col = 2
                    for pt in tr:
                        ws.write(row, col, pt)
                        col += 1
                    row += 1
                    
            row += 2
            ws.write(row, 0, 'Freq')
            ws.write(row, 1, 'Amp')
            ws.write(row, 2, 'Averaged Mic Tracing (uPa)')
            freqArray = CMdata.freqArray
            ampArray = CMdata.ampArray
            row += 1
            for f_idx in range(0, len(freqArray)):
                for a_idx in range(0, len(ampArray)):
                    f = freqArray[f_idx]
                    a = ampArray[a_idx]
                    ws.write(row, 0, f)
                    ws.write(row, 1, a)
                    tr = CMdata.micTracings[f_idx, a_idx, :]
                    tr = tr*1e9
                    tr = np.round(tr)/1e3  # round to nearest nv and conver tto uV
                    col = 2
                    for pt in tr:
                        ws.write(row, col, pt)
                        col += 1
                    row += 1                    

    except:
        print('CM.saveCMDataXLS: Exception writing data to file')        
        traceback.print_exc()