Example #1
0
def laser_tuning_curve(bdata, ephysData, gs):
    plt.subplot(gs[3, 1])

    freqEachTrial = bdata['currentFreq']
    laserEachTrial = bdata['laserOn']
    intEachTrial = bdata['currentIntensity']
    
    eventOnsetTimes = ephysData['events']['stimOn']
    spikeTimeStamps = ephysData['spikeTimes']

    timeRange = [0.0, 0.1]

    possiblefreqs = np.unique(freqEachTrial)
    freqLabels = [round(x/1000, 1) for x in possiblefreqs]
    possiblelaser = np.unique(laserEachTrial)
    possibleInts = np.unique(intEachTrial)

    laserTrialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possiblefreqs, laserEachTrial, possiblelaser)
    intTrialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possiblefreqs, intEachTrial, possibleInts)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimeStamps, eventOnsetTimes, timeRange)
   

    for intInd, inten in enumerate(possibleInts):
        line = '-'
        if intInd == 0:
            line = '--'
        for indLaser in possiblelaser:
            color = 'black'
            if indLaser == 1:
                color = 'blue'

            laser = 'No Laser - '
            if indLaser == 1:
                laser = 'Laser - '
            curveName = laser + str(inten) + ' dB'

            trialsEachCond = laserTrialsEachCond[:,:,indLaser] & intTrialsEachCond[:,:,intInd]

            try:
                freq_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, indexLimitsEachTrial)
            except:
                behavIndexLimitsEachTrial = indexLimitsEachTrial[0:2,:-1]
                freq_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, behavIndexLimitsEachTrial)
            
            xpoints = [x for x in range(0, len(possiblefreqs))]
            #plt.semilogx(possiblefreqs, freq_avgs, linestyle = line, color = color, label = curveName)
            #plt.plot(xvalues, freq_avgs, linestyle = line, color = 'black', label = curveName, xlabels = possiblefreqs)
            plt.plot(xpoints, freq_avgs, linestyle = line, color = color, marker = 'o', label = curveName)
            plt.xticks(xpoints, freqLabels)
            plt.hold(True)
    plt.title('Frequency Tuning Curve - Laser Session')
    plt.legend(fontsize = 'x-small')
    plt.hold(False)
Example #2
0
def laser_tuning_curve(bdata, ephysData, gs):
    plt.subplot(gs[3, 1])

    freqEachTrial = bdata['currentFreq']
    laserEachTrial = bdata['laserOn']
    intEachTrial = bdata['currentIntensity']
    
    eventOnsetTimes = ephysData['events']['stimOn']
    spikeTimeStamps = ephysData['spikeTimes']

    timeRange = [0.0, 0.1]

    possiblefreqs = np.unique(freqEachTrial)
    freqLabels = [round(x/1000, 1) for x in possiblefreqs]
    possiblelaser = np.unique(laserEachTrial)
    possibleInts = np.unique(intEachTrial)

    laserTrialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possiblefreqs, laserEachTrial, possiblelaser)
    intTrialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possiblefreqs, intEachTrial, possibleInts)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimeStamps, eventOnsetTimes, timeRange)
   

    for intInd, inten in enumerate(possibleInts):
        line = '-'
        if intInd == 0:
            line = '--'
        for indLaser in possiblelaser:
            color = 'black'
            if indLaser == 1:
                color = 'blue'

            laser = 'No Laser - '
            if indLaser == 1:
                laser = 'Laser - '
            curveName = laser + str(inten) + ' dB'

            trialsEachCond = laserTrialsEachCond[:,:,indLaser] & intTrialsEachCond[:,:,intInd]

            try:
                freq_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, indexLimitsEachTrial)
            except:
                behavIndexLimitsEachTrial = indexLimitsEachTrial[0:2,:-1]
                freq_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, behavIndexLimitsEachTrial)
            
            xpoints = [x for x in range(0, len(possiblefreqs))]
            #plt.semilogx(possiblefreqs, freq_avgs, linestyle = line, color = color, label = curveName)
            #plt.plot(xvalues, freq_avgs, linestyle = line, color = 'black', label = curveName, xlabels = possiblefreqs)
            plt.plot(xpoints, freq_avgs, linestyle = line, color = color, marker = 'o', label = curveName)
            plt.xticks(xpoints, freqLabels)
            plt.hold(True)
    plt.title('Frequency Tuning Curve - Laser Session')
    plt.legend(fontsize = 'x-small')
    plt.hold(False)
Example #3
0
def laser_tuning_raster(bdata, ephysData, gs):
    freqEachTrial = bdata['currentFreq']
    laserEachTrial = bdata['laserOn']
    intEachTrial = bdata['currentIntensity']

    eventOnsetTimes = ephysData['events']['stimOn']
    spikeTimeStamps = ephysData['spikeTimes']

    timeRange = [-0.3, 0.6]

    possiblefreqs = np.unique(freqEachTrial)
    freqLabels = [round(x / 1000, 1) for x in possiblefreqs]
    possiblelaser = np.unique(laserEachTrial)
    possibleInts = np.unique(intEachTrial)

    #trialsEachCond = behavioranalysis.find_trials_each_type(freqEachTrial, possiblefreqs)
    laserTrialsEachCond = behavioranalysis.find_trials_each_combination(
        freqEachTrial, possiblefreqs, laserEachTrial, possiblelaser)
    intTrialsEachCond = behavioranalysis.find_trials_each_combination(
        freqEachTrial, possiblefreqs, intEachTrial, possibleInts)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimeStamps, eventOnsetTimes, timeRange)

    #plt.figure()

    for intInd, inten in enumerate(possibleInts):
        for indLaser in possiblelaser:
            #plt.subplot(2, 1, indLaser)
            plt.subplot(gs[intInd + 1, indLaser])
            if indLaser == 0:
                title = "No Laser " + str(inten) + " dB"
            else:
                title = "Laser " + str(inten) + " dB"
            trialsEachCond = laserTrialsEachCond[:, :,
                                                 indLaser] & intTrialsEachCond[:, :,
                                                                               intInd]

            pRaster, hcond, zline = extraplots.raster_plot(
                spikeTimesFromEventOnset,
                indexLimitsEachTrial,
                timeRange,
                trialsEachCond=trialsEachCond,
                labels=freqLabels)

            xlabel = 'time (s)'
            ylabel = 'Frequency (kHz)'

            plt.title(title)
            plt.xlabel(xlabel)
            plt.ylabel(ylabel)
    '''
def band_select(spikeTimeStamps, eventOnsetTimes, amplitudes, bandwidths, timeRange, fullRange = [0.0, 2.0]):
    numBands = np.unique(bandwidths)
    numAmps = np.unique(amplitudes)
    spikeArray = np.zeros((len(numBands), len(numAmps)))
    errorArray = np.zeros_like(spikeArray)
    trialsEachCond = behavioranalysis.find_trials_each_combination(bandwidths, 
                                                                   numBands, 
                                                                   amplitudes, 
                                                                   numAmps)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                                                                                                        spikeTimeStamps, 
                                                                                                        eventOnsetTimes,
                                                                                                        fullRange)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange)
    baseTimeRange = [timeRange[1]+0.5, fullRange[1]]
    baseSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, baseTimeRange)
    baselineSpikeRate = np.mean(baseSpikeCountMat)/(baseTimeRange[1]-baseTimeRange[0])
    plt.hold(True)
    for amp in range(len(numAmps)):
        trialsThisAmp = trialsEachCond[:,:,amp]
        for band in range(len(numBands)):
            trialsThisBand = trialsThisAmp[:,band]
            if spikeCountMat.shape[0] != len(trialsThisBand):
                spikeCountMat = spikeCountMat[:-1,:]
                print "FIXME: Using bad hack to make event onset times equal number of trials"
            thisBandCounts = spikeCountMat[trialsThisBand].flatten()
            spikeArray[band, amp] = np.mean(thisBandCounts)
            errorArray[band,amp] = stats.sem(thisBandCounts)
    return spikeArray, errorArray, baselineSpikeRate
Example #5
0
def plot_separated_rasters(gridspec, xcoords, ycoord, firstSort, secondSort, spikeTimestamps, eventOnsetTimes, timeRange=[-0.2,1.5], ylabel='bandwidth (octaves)', xlabel='Time from sound onset (sec)', titles=None, duplicate=False, colours=None, plotHeight=1):      
    firstSortLabels = ['{}'.format(first) for first in np.unique(firstSort)]
    numFirst = np.unique(firstSort)
    numSec = np.unique(secondSort)   
    trialsEachCond = behavioranalysis.find_trials_each_combination(firstSort,
                                                                    numFirst,
                                                                    secondSort,
                                                                    numSec)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                                                                                                        spikeTimestamps, 
                                                                                                        eventOnsetTimes,
                                                                                                        timeRange) 
    if colours is None:
        colours = [np.tile(['0.25','0.6'],len(numFirst)/2+1), np.tile(['#4e9a06','#8ae234'],len(numFirst)/2+1)]
    for ind, secondArrayVal in enumerate(numSec):
        plt.subplot(gridspec[ycoord+ind*plotHeight:ycoord+ind*plotHeight+plotHeight, xcoords[0]:xcoords[1]])
        trialsThisSecondVal = trialsEachCond[:, :, ind]
        # a dumb workaround specifically for plotting harmonic sessions
        if duplicate:
            for ind2, first in enumerate(numFirst):
                if not any(trialsThisSecondVal[:,ind2]):
                    trialsThisSecondVal[:,ind2]=trialsEachCond[:,ind2,ind+1]
        pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,
                                                        indexLimitsEachTrial,
                                                        timeRange,
                                                        trialsEachCond=trialsThisSecondVal,
                                                        labels=firstSortLabels,
                                                        colorEachCond = colours[ind])
        plt.setp(pRaster, ms=4)        
        plt.ylabel(ylabel)
        if ind == len(numSec) - 1:
            plt.xlabel(xlabel)
        if titles is not None:
            plt.title(titles[ind])
Example #6
0
def band_discrim_byside(behavData):
    ax = plt.gca()
    ax.cla()
    possibleRewardSide = np.unique(behavData['rewardSide'])
    possibleBands = np.unique(behavData['currentBand'])
    possibleColors = plt.cm.rainbow(np.linspace(0,1,len(possibleBands)))
    trialsEachCond = behavioranalysis.find_trials_each_combination(behavData['currentBand'], 
                                                                   possibleBands, 
                                                                   behavData['rewardSide'], 
                                                                   possibleRewardSide)
    valid = behavData['valid'].astype(bool)
    rightChoice = behavData['choice']==behavData.labels['choice']['right']
    
    patches=[]
    for indb, thisBand in enumerate(possibleBands):
        thisColor = possibleColors[indb]
        trialsThisBand = trialsEachCond[:,indb,:]
        thisBandPerformance = []
        for indr in range(len(possibleRewardSide)):
            trialsThisSide = trialsThisBand[:,indr]
            validThisSide = np.sum(trialsThisSide.astype(int)[valid])
            rightThisSide = np.sum(trialsThisSide.astype(int)[rightChoice])
            #pdb.set_trace()
            thisBandPerformance.append(100.0*rightThisSide/validThisSide)
        plt.plot([0,1], thisBandPerformance, color=thisColor, marker='o', lw=3, ms=10)
        patches.append(mpatches.Patch(color=thisColor, label=str(thisBand)))
    plt.ylim((0,100))
    plt.xlim((-0.2,1.2))
    plt.ylabel("% rightward")
    labels = ['no tone','tone']
    plt.xticks([0,1], labels)
    plt.legend(handles=patches, borderaxespad=0.3,prop={'size':12}, loc='best')
Example #7
0
def band_SNR_laser_psychometric(animal, sessions, trialTypes='laserSide', paradigm='2afc', xlabel=True, ylabel=True):
    loader = dataloader.DataLoader(animal)
    validPerSNR = None
    rightPerSNR = None
    for ind, session in enumerate(sessions):
        behavFile = loadbehavior.path_to_behavior_data(animal,paradigm,session)
        behavData = loader.get_session_behavior(behavFile)
        ax = plt.gca()
        ax.cla()
        possibleSNRs = np.unique(behavData['currentSNR'])
        laserTrialTypes = np.unique(behavData[trialTypes])
        trialsEachCond = behavioranalysis.find_trials_each_combination(behavData['currentSNR'], possibleSNRs, 
                                                                        behavData[trialTypes], laserTrialTypes)
        valid = behavData['valid'].astype(bool)
        rightChoice = behavData['choice']==behavData.labels['choice']['right']
        if validPerSNR is None:
            validPerSNR = np.zeros((len(laserTrialTypes),len(possibleSNRs)))
            rightPerSNR = np.zeros((len(laserTrialTypes),len(possibleSNRs)))
        for las in range(len(laserTrialTypes)):
            trialsThisLaser = trialsEachCond[:,:,las]
            for inds in range(len(possibleSNRs)):
                trialsThisSNR = trialsThisLaser[:,inds]
                validThisSNR = np.sum(trialsThisSNR.astype(int)[valid])
                rightThisSNR = np.sum(trialsThisSNR.astype(int)[rightChoice])
                validPerSNR[las,inds] += validThisSNR
                rightPerSNR[las,inds] += rightThisSNR
    return validPerSNR, rightPerSNR, possibleSNRs, laserTrialTypes
Example #8
0
def laser_tuning_raster(bdata, ephysData, gs):
    freqEachTrial = bdata['currentFreq']
    laserEachTrial = bdata['laserOn']
    intEachTrial = bdata['currentIntensity']
    
    eventOnsetTimes = ephysData['events']['stimOn']
    spikeTimeStamps = ephysData['spikeTimes']

    timeRange = [-0.3, 0.6]

    possiblefreqs = np.unique(freqEachTrial)
    freqLabels = [round(x/1000, 1) for x in possiblefreqs]
    possiblelaser = np.unique(laserEachTrial)
    possibleInts = np.unique(intEachTrial)

    #trialsEachCond = behavioranalysis.find_trials_each_type(freqEachTrial, possiblefreqs)
    laserTrialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possiblefreqs, laserEachTrial, possiblelaser)
    intTrialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possiblefreqs, intEachTrial, possibleInts)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimeStamps, eventOnsetTimes, timeRange)

    #plt.figure()

    for intInd, inten in enumerate(possibleInts):
        for indLaser in possiblelaser:
            #plt.subplot(2, 1, indLaser)
            plt.subplot(gs[intInd+1, indLaser])
            if indLaser == 0:
                title = "No Laser " + str(inten) + " dB"
            else:
                title = "Laser " + str(inten) + " dB"
            trialsEachCond = laserTrialsEachCond[:,:,indLaser] & intTrialsEachCond[:,:,intInd]

            pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange,
                                                       trialsEachCond=trialsEachCond, labels=freqLabels)


            xlabel = 'time (s)'
            ylabel = 'Frequency (kHz)'

            plt.title(title)
            plt.xlabel(xlabel)
            plt.ylabel(ylabel)
    '''
Example #9
0
def calculate_tuning_curve_inputs(spikeTimeStamps, eventOnsetTimes, firstSort, secondSort, timeRange, baseRange=[-1.1,-0.1], errorType = 'sem', info='full'):
    fullTimeRange = [min(min(timeRange),min(baseRange)), max(max(timeRange),max(baseRange))]
    
    numFirst = np.unique(firstSort)
    numSec = np.unique(secondSort)
    duration = timeRange[1]-timeRange[0]
    spikeArray = np.zeros((len(numFirst), len(numSec)))
    errorArray = np.zeros_like(spikeArray)
    trialsEachCond = behavioranalysis.find_trials_each_combination(firstSort, 
                                                                   numFirst, 
                                                                   secondSort, 
                                                                   numSec)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                                                                                                        spikeTimeStamps, 
                                                                                                        eventOnsetTimes,
                                                                                                        fullTimeRange)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange)
    baseSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange)
    baselineSpikeRate = np.mean(baseSpikeCountMat)/(baseRange[1]-baseRange[0])
    if errorType == 'sem':
        baselineError = stats.sem(baseSpikeCountMat)/(baseRange[1]-baseRange[0])
    elif errorType == 'std':
        baselineError = np.std(baseSpikeCountMat)/(baseRange[1]-baseRange[0])
    
    for sec in range(len(numSec)):
        trialsThisSec = trialsEachCond[:,:,sec]
        for first in range(len(numFirst)):
            trialsThisFirst = trialsThisSec[:,first]
            if spikeCountMat.shape[0] != len(trialsThisFirst):
                spikeCountMat = spikeCountMat[:-1,:]
            if any(trialsThisFirst):
                thisFirstCounts = spikeCountMat[trialsThisFirst].flatten()
                spikeArray[first,sec] = np.mean(thisFirstCounts)/duration
                if errorType == 'sem':
                    errorArray[first,sec] = stats.sem(thisFirstCounts)/duration
                elif errorType == 'std':
                    errorArray[first,sec] = np.std(thisFirstCounts)/duration
            else:
                spikeArray[first,sec] = np.nan
                errorArray[first,sec] = np.nan
    if info=='full':
        tuningDict = {'responseArray':spikeArray,
                      'errorArray':errorArray,
                      'baselineSpikeRate':baselineSpikeRate,
                      'baselineSpikeError':baselineError,
                      'spikeCountMat':spikeCountMat,
                      'trialsEachCond':trialsEachCond}
    elif info=='plotting':
        tuningDict = {'responseArray':spikeArray,
                      'errorArray':errorArray,
                      'baselineSpikeRate':baselineSpikeRate,
                      'baselineSpikeError':baselineError}
    else:
        raise NameError('That is not an info type you degenerate')
    return tuningDict
def sound_response_any_stimulus(eventOnsetTimes,
                                spikeTimeStamps,
                                bdata,
                                timeRange=[0.0, 1.0],
                                baseRange=[-1.1, -0.1],
                                sessionType='bandwidth',
                                sessionIndex=None):
    fullTimeRange = [
        min(min(timeRange), min(baseRange)),
        max(max(timeRange), max(baseRange))
    ]

    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimeStamps, eventOnsetTimes, fullTimeRange)
    stimSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange)
    baseSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange)
    baseSpikeCountMat = baseSpikeCountMat.flatten()

    if sessionType == 'bandwidth':
        firstSort = bdata['currentBand']
        numFirst = np.unique(firstSort)
        secondSort = bdata['currentAmp']
        numSec = np.unique(secondSort)
    elif sessionType == 'laserBandwidth':
        firstSort = bdata['currentBand']
        numFirst = np.unique(firstSort)
        secondSort = bdata['laserTrial']
        numSec = np.unique(secondSort)

    totalConds = len(numFirst) * len(numSec)
    trialsEachCond = behavioranalysis.find_trials_each_combination(
        firstSort, numFirst, secondSort, numSec)

    minpVal = np.inf

    for sec in range(len(numSec)):
        trialsThisSec = trialsEachCond[:, :, sec]
        for first in range(len(numFirst)):
            trialsThisFirst = trialsThisSec[:, first]
            if stimSpikeCountMat.shape[0] == len(trialsThisFirst) + 1:
                stimSpikeCountMat = stimSpikeCountMat[:-1, :]
                #print "FIXME: Using bad hack to make event onset times equal number of trials"
            elif stimSpikeCountMat.shape[0] != len(trialsThisFirst):
                print "STOP NO THIS IS BAD"
                raise ValueError
            if any(trialsThisFirst):
                thisFirstStimCounts = stimSpikeCountMat[
                    trialsThisFirst].flatten()
                pValThisFirst = stats.ranksums(
                    thisFirstStimCounts, baseSpikeCountMat)[1] * totalConds
                if pValThisFirst < minpVal:
                    minpVal = pValThisFirst
    return minpVal
def plot_laser_bandwidth_summary(cell, bandIndex):
    cellInfo = get_cell_info(cell)
    loader = dataloader.DataLoader(cell['subject'])
    plt.clf()
    gs = gridspec.GridSpec(2, 4)
    eventData = loader.get_session_events(cellInfo['ephysDirs'][bandIndex])
    spikeData = loader.get_session_spikes(cellInfo['ephysDirs'][bandIndex], cellInfo['tetrode'], cluster=cellInfo['cluster'])
    eventOnsetTimes = loader.get_event_onset_times(eventData)
    spikeTimestamps = spikeData.timestamps
    timeRange = [-0.2, 1.5]
    bandBData = loader.get_session_behavior(cellInfo['behavDirs'][bandIndex])  
    bandEachTrial = bandBData['currentBand']
    laserTrial = bandBData['laserTrial']
    numBands = np.unique(bandEachTrial)
    numLas = np.unique(laserTrial)
            
    firstSortLabels = ['{}'.format(band) for band in np.unique(bandEachTrial)]
    secondSortLabels = ['no laser','laser']      
    trialsEachCond = behavioranalysis.find_trials_each_combination(bandEachTrial, 
                                                                           numBands, 
                                                                           laserTrial, 
                                                                           numLas)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                                                                                                        spikeTimestamps, 
                                                                                                        eventOnsetTimes,
                                                                                                        timeRange) 
    colours = [np.tile(['0.25','0.6'],len(numBands)/2+1), np.tile(['#4e9a06','#8ae234'],len(numBands)/2+1)]
    for ind, secondArrayVal in enumerate(numLas):
        plt.subplot(gs[ind, 0:2])
        trialsThisSecondVal = trialsEachCond[:, :, ind]
        pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,
                                                        indexLimitsEachTrial,
                                                        timeRange,
                                                        trialsEachCond=trialsThisSecondVal,
                                                        labels=firstSortLabels,
                                                        colorEachCond = colours[ind])
        plt.setp(pRaster, ms=4)        
        #plt.title(secondSortLabels[ind])
        plt.ylabel('bandwidth (octaves)')
        if ind == len(numLas) - 1:
            plt.xlabel("Time from sound onset (sec)")
    
           
    # -- plot Yashar plots for bandwidth data --
    plt.subplot(gs[0:, 2:])
    spikeArray, errorArray, baseSpikeRate = band_select(spikeTimestamps, eventOnsetTimes, laserTrial, bandEachTrial, timeRange = [0.0, 1.0])
    band_select_plot(spikeArray, errorArray, baseSpikeRate, numBands, legend=True, labels=secondSortLabels, linecolours=['0.25','#4e9a06'], errorcolours=['0.6','#8ae234'])
    fig_path = '/home/jarauser/Pictures/cell reports'
    fig_name = '{0}_{1}_{2}um_TT{3}Cluster{4}.svg'.format(cellInfo['subject'], cellInfo['date'], cellInfo['depth'], cellInfo['tetrode'], cellInfo['cluster'])
    full_fig_path = os.path.join(fig_path, fig_name)
    fig = plt.gcf()
    fig.set_size_inches(16, 8)
    fig.savefig(full_fig_path, format = 'svg', bbox_inches='tight')
def calculate_tuning_curve_inputs(spikeTimeStamps,
                                  eventOnsetTimes,
                                  firstSort,
                                  secondSort,
                                  timeRange,
                                  baseRange=[-1.1, -0.1]):
    fullTimeRange = [
        min(min(timeRange), min(baseRange)),
        max(max(timeRange), max(baseRange))
    ]

    numFirst = np.unique(firstSort)
    numSec = np.unique(secondSort)
    duration = timeRange[1] - timeRange[0]
    spikeArray = np.zeros((len(numFirst), len(numSec)))
    errorArray = np.zeros_like(spikeArray)
    trialsEachCond = behavioranalysis.find_trials_each_combination(
        firstSort, numFirst, secondSort, numSec)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimeStamps, eventOnsetTimes, fullTimeRange)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange)
    baseSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange)
    baselineSpikeRate = np.mean(baseSpikeCountMat) / (baseRange[1] -
                                                      baseRange[0])
    baselineError = stats.sem(baseSpikeCountMat) / (baseRange[1] -
                                                    baseRange[0])

    for sec in range(len(numSec)):
        trialsThisSec = trialsEachCond[:, :, sec]
        for first in range(len(numFirst)):
            trialsThisFirst = trialsThisSec[:, first]
            if spikeCountMat.shape[0] != len(trialsThisFirst):
                spikeCountMat = spikeCountMat[:-1, :]
            if any(trialsThisFirst):
                thisFirstCounts = spikeCountMat[trialsThisFirst].flatten()
                spikeArray[first, sec] = np.mean(thisFirstCounts) / duration
                errorArray[first, sec] = stats.sem(thisFirstCounts) / duration
            else:
                spikeArray[first, sec] = np.nan
                errorArray[first, sec] = np.nan
    tuningDict = {
        'responseArray': spikeArray,
        'errorArray': errorArray,
        'baselineSpikeRate': baselineSpikeRate,
        'baselineSpikeError': baselineError,
        'spikeCountMat': spikeCountMat,
        'trialsEachCond': trialsEachCond,
        'timeRange': timeRange
    }
    return tuningDict
Example #13
0
def plot_separated_rasters(gridspec,
                           xcoords,
                           ycoord,
                           firstSort,
                           secondSort,
                           spikeTimestamps,
                           eventOnsetTimes,
                           timeRange=[-0.2, 1.5],
                           ylabel='bandwidth (octaves)',
                           xlabel='Time from sound onset (sec)',
                           titles=None,
                           duplicate=False,
                           colours=None,
                           plotHeight=1):
    firstSortLabels = ['{}'.format(first) for first in np.unique(firstSort)]
    numFirst = np.unique(firstSort)
    numSec = np.unique(secondSort)
    trialsEachCond = behavioranalysis.find_trials_each_combination(
        firstSort, numFirst, secondSort, numSec)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimestamps, eventOnsetTimes, timeRange)
    if colours is None:
        colours = [
            np.tile(['0.25', '0.6'],
                    len(numFirst) / 2 + 1),
            np.tile(['#4e9a06', '#8ae234'],
                    len(numFirst) / 2 + 1)
        ]
    for ind, secondArrayVal in enumerate(numSec):
        plt.subplot(gridspec[ycoord + ind * plotHeight:ycoord +
                             ind * plotHeight + plotHeight,
                             xcoords[0]:xcoords[1]])
        trialsThisSecondVal = trialsEachCond[:, :, ind]
        # a dumb workaround specifically for plotting harmonic sessions
        if duplicate:
            for ind2, first in enumerate(numFirst):
                if not any(trialsThisSecondVal[:, ind2]):
                    trialsThisSecondVal[:, ind2] = trialsEachCond[:, ind2,
                                                                  ind + 1]
        pRaster, hcond, zline = extraplots.raster_plot(
            spikeTimesFromEventOnset,
            indexLimitsEachTrial,
            timeRange,
            trialsEachCond=trialsThisSecondVal,
            labels=firstSortLabels,
            colorEachCond=colours[ind])
        plt.setp(pRaster, ms=4)
        plt.ylabel(ylabel)
        if ind == len(numSec) - 1:
            plt.xlabel(xlabel)
        if titles is not None:
            plt.title(titles[ind])
Example #14
0
def tuning_curve(bdata, ephysData, gs):
    plt.subplot(gs[3, 0])

    freqEachTrial = bdata['currentFreq']
    intEachTrial = bdata['currentIntensity']
    
    eventOnsetTimes = ephysData['events']['stimOn']
    spikeTimeStamps = ephysData['spikeTimes']

    timeRange = [0.0, 0.1]

    possiblefreqs = np.unique(freqEachTrial)
    freqLabels = [round(x/1000, 1) for x in possiblefreqs]
    possibleInts = np.unique(intEachTrial)

    intTrialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possiblefreqs, intEachTrial, possibleInts)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
            spikeTimeStamps, eventOnsetTimes, timeRange)

    for intInd, inten in enumerate(possibleInts):
        line = '-'
        if intInd == 0 and len(possibleInts) > 1:
            line = '--'
        curveName = str(inten) + ' dB'

        trialsEachCond = intTrialsEachCond[:,:,intInd]

        try:
            freq_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, indexLimitsEachTrial)
        except:
            behavIndexLimitsEachTrial = indexLimitsEachTrial[0:2,:-1]
            freq_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, behavIndexLimitsEachTrial)
        
        xpoints = [x for x in range(0, len(possiblefreqs))]
        xpointticks = [x for x in range(1, len(possiblefreqs), 2)]
        freqticks = [freqLabels[x] for x in range(1, len(freqLabels), 2)]
        #plt.semilogx(possiblefreqs, freq_avgs, linestyle = line, color = 'black', label = curveName)
        #plt.plot(log(possiblefreqs), freq_avgs, linestyle = line, color = 'black', label = curveName, xlabels = possiblefreqs)
        plt.plot(xpoints, freq_avgs, linestyle = line, color = 'black', marker = 'o', label = curveName)
        plt.xticks(xpointticks, freqticks)
        plt.hold(True)

    xlabel = 'Frequency (kHz)'
    ylabel = 'Firing Rate (spikes/s)'
    
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.title('Frequency Tuning Curve')
    plt.legend(fontsize = 'x-small', loc = 'upper left')
    plt.hold(False)
def bandwidth_raster_inputs(eventOnsetTimes, spikeTimestamps, bandEachTrial, ampEachTrial, timeRange = [-0.2, 1.5]):          
    numBands = np.unique(bandEachTrial)
    numAmps = np.unique(ampEachTrial)
            
    firstSortLabels = ['{}'.format(band) for band in numBands]
            
    trialsEachCond = behavioranalysis.find_trials_each_combination(bandEachTrial, 
                                                                           numBands, 
                                                                           ampEachTrial, 
                                                                           numAmps)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                                                                                                        spikeTimestamps, 
                                                                                                        eventOnsetTimes,
                                                                                                        timeRange) 

    return spikeTimesFromEventOnset, indexLimitsEachTrial, trialsEachCond, firstSortLabels
def find_trials_each_combination_three_params(parameter1,parameterPossibleValues1,parameter2,parameterPossibleValues2,parameter3,parameterPossibleValues3):
    '''
    Returns a boolean 4D array of size [nTrials,nValues1,nValues2,nValues3]. True for each combination.
    '''
    if len(parameter1)!=len(parameter2):
        raise ValueError('parameters must be vectors of same size.')
    nTrials = len(parameter1)
    nValues1 = len(parameterPossibleValues1)
    nValues2 = len(parameterPossibleValues2)
    nValues3 = len(parameterPossibleValues3)
    trialsEachComb = np.zeros((nTrials,nValues1,nValues2,nValues3),dtype=bool)
    trialsEachComb12 = behavioranalysis.find_trials_each_combination(parameter1, parameterPossibleValues1, parameter2, parameterPossibleValues2)
    trialsEachType3 = behavioranalysis.find_trials_each_type(parameter3,parameterPossibleValues3)
    for ind3 in range(nValues3):
        trialsEachComb[:,:,:,ind3] = trialsEachComb12 & trialsEachType3[:,ind3][:,np.newaxis,np.newaxis]
    return trialsEachComb
def band_psychometric(animal, sessions, trialTypes=['currentSNR']):
    ''' 
    Produces the number of valid trials and number of trials where animal went to the right for each condition.
    Can sort by up to three parameters.
    
    Input:
        animal = name of animal whose behaviour is to be used (string)
        sessions = file names of sessions to be used (list of strings)
        trialTypes = names of parameters in behavData to be used for sorting trials (list of strings, up to 3 parameters)
        
    Output:
        validPerCond = 1D to 3D array (depending on number of parameters given) giving number of valid trials for each condition
        rightPerCond = like validPerCond, only trials where animal went to the right
        possibleParams = possible values each parameter takes
    '''
    behavData = behavioranalysis.load_many_sessions(animal, sessions)
    
    firstSort = behavData[trialTypes[0]]
    possibleFirstSort = np.unique(firstSort)
    
    possibleSecondSort = None
    possibleThirdSort = None
    
    if len(trialTypes) > 1:
        secondSort = behavData[trialTypes[1]]
        possibleSecondSort = np.unique(secondSort)

    if len(trialTypes) > 2:
        thirdSort = behavData[trialTypes[2]]
        possibleThirdSort = np.unique(thirdSort)
        
    valid = behavData['valid'].astype(bool)
    rightChoice = behavData['choice']==behavData.labels['choice']['right']
    
    if len(trialTypes) == 3:
        trialsEachComb = find_trials_each_combination_three_params(firstSort, possibleFirstSort, secondSort, possibleSecondSort, thirdSort, possibleThirdSort)
    elif len(trialTypes) == 2:
        trialsEachComb = behavioranalysis.find_trials_each_combination(firstSort, possibleFirstSort, secondSort, possibleSecondSort)
    elif len(trialTypes) == 1:
        trialsEachComb = behavioranalysis.find_trials_each_type(firstSort, possibleFirstSort)
    
    validPerCond, rightPerCond = compute_psychometric_inputs(valid, rightChoice, trialsEachComb)
    
    possibleParams = [possibleFirstSort, possibleSecondSort, possibleThirdSort]
    possibleParams = [param for param in possibleParams if param is not None]
    return validPerCond, rightPerCond, possibleParams
Example #18
0
def band_select_plot(spikeTimeStamps, eventOnsetTimes, amplitudes, bandwidths, timeRange, fullRange = [0.0, 2.0], title=None):
    numBands = np.unique(bandwidths)
    numAmps = np.unique(amplitudes)
    spikeArray = np.zeros((len(numBands), len(numAmps)))
    errorArray = np.zeros_like(spikeArray)
    trialsEachCond = behavioranalysis.find_trials_each_combination(bandwidths, 
                                                                   numBands, 
                                                                   amplitudes, 
                                                                   numAmps)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                                                                                                        spikeTimeStamps, 
                                                                                                        eventOnsetTimes,
                                                                                                        fullRange)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange)
    baseTimeRange = [timeRange[1]+0.5, fullRange[1]]
    baseSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, baseTimeRange)
    baselineSpikeRate = np.mean(baseSpikeCountMat)/(baseTimeRange[1]-baseTimeRange[0])
    plt.hold(True)
    for amp in range(len(numAmps)):
        trialsThisAmp = trialsEachCond[:,:,amp]
        for band in range(len(numBands)):
            trialsThisBand = trialsThisAmp[:,band]
            if spikeCountMat.shape[0] != len(trialsThisBand):
                spikeCountMat = spikeCountMat[:-1,:]
                print "FIXME: Using bad hack to make event onset times equal number of trials"
            thisBandCounts = spikeCountMat[trialsThisBand].flatten()
            spikeArray[band, amp] = np.mean(thisBandCounts)
            errorArray[band,amp] = stats.sem(thisBandCounts)
    xrange = range(len(numBands))
    plt.plot(xrange, baselineSpikeRate*(timeRange[1]-timeRange[0])*np.ones(len(numBands)), color = '0.75', linewidth = 2)
    plt.plot(xrange, spikeArray[:,0].flatten(), '-o', color = '#4e9a06', linewidth = 3)
    plt.fill_between(xrange, spikeArray[:,0].flatten() - errorArray[:,0].flatten(), 
                     spikeArray[:,0].flatten() + errorArray[:,0].flatten(), alpha=0.2, edgecolor = '#8ae234', facecolor='#8ae234')
    plt.plot(range(len(numBands)), spikeArray[:,1].flatten(), '-o', color = '#5c3566', linewidth = 3)
    plt.fill_between(xrange, spikeArray[:,1].flatten() - errorArray[:,1].flatten(), 
                     spikeArray[:,1].flatten() + errorArray[:,1].flatten(), alpha=0.2, edgecolor = '#ad7fa8', facecolor='#ad7fa8')
    ax = plt.gca()
    ax.set_xticklabels(numBands)
    plt.xlabel('bandwidth (octaves)')
    plt.ylabel('Average num spikes')
    #patch1 = mpatches.Patch(color='#5c3566', label='0.8')
    #patch2 = mpatches.Patch(color='#4e9a06', label='0.2')
    #plt.legend(handles=[patch1, patch2], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    if title:
        plt.title(title)
Example #19
0
    def plot_sorted_tuning_raster(self, session, tetrode, behavFileIdentifier, cluster = None, replace=0, timeRange = [-0.5, 1], ms = 1):
        '''
        '''
        bdata = self.get_session_behav_data(session,behavFileIdentifier)

        freqEachTrial = bdata['currentFreq']
        possibleFreq = np.unique(freqEachTrial)

        intensityEachTrial = bdata['currentIntensity']
        possibleIntensity = np.unique(intensityEachTrial)


        trialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possibleFreq, intensityEachTrial, possibleIntensity)

        spikeData = self.get_session_spike_data_one_tetrode(session, tetrode)

        eventData = self.get_session_event_data(session)
        eventOnsetTimes = self.get_event_onset_times(eventData)
        spikeTimestamps=spikeData.timestamps


        spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(spikeTimestamps,eventOnsetTimes,timeRange)

        freqLabels = ['{0:.1f}'.format(freq/1000.0) for freq in possibleFreq]
        plotTitle = self.get_session_plot_title(session)

        fig = plt.figure()
        for indIntensity, intensity in enumerate(possibleIntensity[::-1]):

            if indIntensity == 0:
                fig.add_subplot(len(possibleIntensity), 1, indIntensity+1)
                plt.title(plotTitle)
            else:
                fig.add_subplot(len(possibleIntensity), 1, indIntensity+1, sharex=fig.axes[0], sharey=fig.axes[0])

            trialsThisIntensity = trialsEachCond[:, :, len(possibleIntensity)-indIntensity-1] #FIXME: There must be a better way to flip so high intensity is on top

            pRaster,hcond,zline = extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond = trialsThisIntensity, labels = freqLabels)
            plt.setp(pRaster,ms=ms)
            plt.ylabel('{:.0f} dB'.format(intensity))

            if indIntensity == len(possibleIntensity)-1:
                plt.xlabel("time (sec)")

        fig.show()
Example #20
0
def sound_response_any_stimulus(eventOnsetTimes, spikeTimeStamps, bdata, timeRange=[0.0,1.0], baseRange=[-1.1,-0.1], sessionType='bandwidth', sessionIndex=None):
    fullTimeRange = [min(min(timeRange),min(baseRange)), max(max(timeRange),max(baseRange))]
    
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(spikeTimeStamps, 
                                                                                                                   eventOnsetTimes, 
                                                                                                                   fullTimeRange)
    stimSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange)
    baseSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange)
    baseSpikeCountMat = baseSpikeCountMat.flatten()
    
    if sessionType == 'bandwidth': 
        firstSort = bdata['currentBand']
        numFirst = np.unique(firstSort)
        secondSort = bdata['currentAmp']
        numSec = np.unique(secondSort)
    elif sessionType == 'laserBandwidth':
        firstSort = bdata['currentBand']
        numFirst = np.unique(firstSort)
        secondSort = bdata['laserTrial']
        numSec = np.unique(secondSort)
    
    totalConds = len(numFirst)*len(numSec)
    trialsEachCond = behavioranalysis.find_trials_each_combination(firstSort,numFirst,secondSort,numSec)
    
    minpVal = np.inf
    
    for sec in range(len(numSec)):
        trialsThisSec = trialsEachCond[:,:,sec]
        for first in range(len(numFirst)):
            trialsThisFirst = trialsThisSec[:,first]
            if stimSpikeCountMat.shape[0] == len(trialsThisFirst)+1:
                stimSpikeCountMat = stimSpikeCountMat[:-1,:]
                #print "FIXME: Using bad hack to make event onset times equal number of trials"
            elif stimSpikeCountMat.shape[0] != len(trialsThisFirst):
                print "STOP NO THIS IS BAD"
                raise ValueError
            if any(trialsThisFirst):
                thisFirstStimCounts = stimSpikeCountMat[trialsThisFirst].flatten()
                pValThisFirst = stats.ranksums(thisFirstStimCounts, baseSpikeCountMat)[1]*totalConds
                if pValThisFirst < minpVal:
                    minpVal = pValThisFirst
    return minpVal
def calculate_tuning_curve_inputs(spikeCountEachTrial, firstSort, secondSort):
    '''Calculates average firing rates for each condition required to plot a tuning curve for a given session.
    
    Inputs:
        spikeCountEachTrial: array of length N trials indicating the number of spikes that occurred during each trial
        firstSort: array of length N trials indicating value of first parameter for each trial (ex. bandwidths)
        secondSort: array of length N trials indicating value of second parameter for each trial (ex. amplitudes)
        
    Outputs:
        responseArray: array of size (N unique first parameter, N unique second parameter) indicating average spike counts for all trials with each combination of the two parameters
        errorArray: like responseArray, indicating s.e.m. for each value in responseArray
    '''
    numFirst = np.unique(firstSort)
    numSec = np.unique(secondSort)
    
    trialsEachCond = behavioranalysis.find_trials_each_combination(firstSort, 
                                                                   numFirst, 
                                                                   secondSort, 
                                                                   numSec)

    spikeArray = np.zeros((len(numFirst), len(numSec)))
    errorArray = np.zeros_like(spikeArray)
    
    for sec in range(len(numSec)):
        trialsThisSec = trialsEachCond[:,:,sec]
        for first in range(len(numFirst)):
            trialsThisFirst = trialsThisSec[:,first]
            if spikeCountEachTrial.shape[0] != len(trialsThisFirst):
                spikeCountEachTrial = spikeCountEachTrial[:-1,:]
            if any(trialsThisFirst):
                thisFirstCounts = spikeCountEachTrial[trialsThisFirst].flatten()
                spikeArray[first,sec] = np.mean(thisFirstCounts)
                errorArray[first,sec] = stats.sem(thisFirstCounts)
            else:
                spikeArray[first,sec] = np.nan
                errorArray[first,sec] = np.nan
    return spikeArray, errorArray
Example #22
0
def plot_one_int_bandwidth_summary(cell, bandIndex, intIndex=-1):
    plt.clf()
    gs = gridspec.GridSpec(1,3)
    gs.update(left=0.15, right=0.85, top = 0.90, wspace=0.2, hspace=0.5)
    
    tetrode=int(cell['tetrode'])
    cluster=int(cell['cluster'])
    
    #create cell object for loading data
    cellObj = ephyscore.Cell(cell)
    
    #load bandwidth data
    bandEphysData, bandBData = cellObj.load_by_index(bandIndex)
    bandEventOnsetTimes = ephysanalysis.get_sound_onset_times(bandEphysData, 'bandwidth')
    bandSpikeTimestamps = bandEphysData['spikeTimes']
    
    bandEachTrial = bandBData['currentBand']
    secondSort = bandBData['currentAmp']
    numBands = np.unique(bandEachTrial)
    numSec = np.unique(secondSort)
    
    timeRange = [-0.2, 1.5]
    
    #plot raster of the high amp bandwidth trials
    plt.subplot(gs[0,0])     
    colours = np.tile(['#5c3566','#ad7fa8'],len(numBands)/2+1)
    trialsEachCond = behavioranalysis.find_trials_each_combination(bandEachTrial,
                                                                    numBands,
                                                                    secondSort,
                                                                    numSec)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                                                                                                        bandSpikeTimestamps, 
                                                                                                        bandEventOnsetTimes,
                                                                                                        timeRange) 

    trialsOneAmp = trialsEachCond[:, :, intIndex]
    firstSortLabels = ['{}'.format(band) for band in numBands]
    pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,
                                                        indexLimitsEachTrial,
                                                        timeRange,
                                                        trialsEachCond=trialsOneAmp,
                                                        labels=firstSortLabels,
                                                        colorEachCond = colours)
    plt.setp(pRaster, ms=3)
    plt.ylabel('Bandwidth (octaves)')
    plt.xlabel('Time from sound onset (s)')
    #plot bandwidth tuning curves
    plt.subplot(gs[0,2])
    sustainedTimeRange = [0.2,1.0]
    tuningDict = ephysanalysis.calculate_tuning_curve_inputs(bandSpikeTimestamps, bandEventOnsetTimes, secondSort, bandEachTrial, sustainedTimeRange, info='plotting')
    plot_tuning_curve(tuningDict['responseArray'][intIndex,:].reshape([7,1]), tuningDict['errorArray'][intIndex,:].reshape([7,1]), numBands, tuningDict['baselineSpikeRate'], linecolours=['#5c3566'], errorcolours=['#ad7fa8'])
    plt.title('Average sustained response (200-1000 ms)', fontsize=10)

    plt.subplot(gs[0,1])
    onsetTimeRange = [0.0, 0.05]
    tuningDict2 = ephysanalysis.calculate_tuning_curve_inputs(bandSpikeTimestamps, bandEventOnsetTimes, secondSort, bandEachTrial, onsetTimeRange, info='plotting')
    plot_tuning_curve(tuningDict2['responseArray'][intIndex,:].reshape([7,1]), tuningDict2['errorArray'][intIndex,:].reshape([7,1]), numBands, tuningDict2['baselineSpikeRate'], linecolours=['#5c3566'], errorcolours=['#ad7fa8'])
    plt.title('Average onset response (0-50 ms)', fontsize=10)
    
    #save report
    charfreq = str(np.unique(bandBData['charFreq'])[0]/1000)
    modrate = str(np.unique(bandBData['modRate'])[0])
    plt.suptitle('{0}, {1}, {2}um, Tetrode {3}, Cluster {4}, {5}kHz, {6}Hz modulation'.format(cell['subject'], 
                                                                                            cell['date'], 
                                                                                            int(cell['depth']), 
                                                                                            tetrode, 
                                                                                            cluster, 
                                                                                            charfreq, 
                                                                                            modrate))
    
    fig_path = '/home/jarauser/Pictures/cell reports'
    fig_name = 'bandwidth_high_amp_response_{0}_{1}_{2}um_TT{3}Cluster{4}.png'.format(cell['subject'], cell['date'], int(cell['depth']), tetrode, cluster)
    full_fig_path = os.path.join(fig_path, fig_name)
    fig = plt.gcf()
    fig.set_size_inches(14, 3)
    fig.savefig(full_fig_path, format = 'png', bbox_inches='tight')
Example #23
0
def plot_bandwidth_report(mouse, date, site, siteName):
    sessions = site.get_session_ephys_filenames()
    behavFilename = site.get_session_behav_filenames()
    ei = ephysinterface.EphysInterface(mouse, date, '', 'bandwidth_am')
    bdata = ei.loader.get_session_behavior(behavFilename[3][-4:-3])
    charfreq = str(np.unique(bdata['charFreq'])[0] / 1000)
    modrate = str(np.unique(bdata['modRate'])[0])
    ei2 = ephysinterface.EphysInterface(mouse, date, '', 'am_tuning_curve')
    bdata2 = ei2.loader.get_session_behavior(behavFilename[1][-4:-3])
    bdata3 = ei2.loader.get_session_behavior(behavFilename[2][-4:-3])
    currentFreq = bdata2['currentFreq']
    currentBand = bdata['currentBand']
    currentAmp = bdata['currentAmp']
    currentInt = bdata2['currentIntensity']
    currentRate = bdata3['currentFreq']

    #for tetrode in site.tetrodes:
    for tetrode in [2]:
        oneTT = sitefuncs.cluster_site(site, siteName, tetrode)
        dataSpikes = ei.loader.get_session_spikes(sessions[3], tetrode)
        dataSpikes2 = ei2.loader.get_session_spikes(sessions[1], tetrode)
        #clusters = np.unique(dataSpikes.clusters)
        clusters = [8]
        for cluster in clusters:
            plt.clf()

            # -- plot bandwidth rasters --
            eventData = ei.loader.get_session_events(sessions[3])
            spikeData = ei.loader.get_session_spikes(sessions[3],
                                                     tetrode,
                                                     cluster=cluster)
            eventOnsetTimes = ei.loader.get_event_onset_times(eventData)
            spikeTimestamps = spikeData.timestamps
            timeRange = [-0.2, 1.5]

            numBands = np.unique(currentBand)
            numAmps = np.unique(currentAmp)

            firstSortLabels = [
                '{}'.format(band) for band in np.unique(currentBand)
            ]
            secondSortLabels = [
                'Amplitude: {}'.format(amp) for amp in np.unique(currentAmp)
            ]

            trialsEachCond = behavioranalysis.find_trials_each_combination(
                currentBand, numBands, currentAmp, numAmps)
            spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                spikeTimestamps, eventOnsetTimes, timeRange)
            for ind, secondArrayVal in enumerate(numAmps):
                plt.subplot2grid((12, 15), (5 * ind, 0), rowspan=4, colspan=7)
                trialsThisSecondVal = trialsEachCond[:, :, ind]
                pRaster, hcond, zline = extraplots.raster_plot(
                    spikeTimesFromEventOnset,
                    indexLimitsEachTrial,
                    timeRange,
                    trialsEachCond=trialsThisSecondVal,
                    labels=firstSortLabels)
                plt.setp(pRaster, ms=4)

                plt.title(secondSortLabels[ind])
                plt.ylabel('bandwidth (octaves)')
                if ind == len(np.unique(currentAmp)) - 1:
                    plt.xlabel("Time from sound onset (sec)")

            # -- plot Yashar plots for bandwidth data --
            plt.subplot2grid((12, 15), (10, 0), rowspan=2, colspan=3)
            band_select_plot(spikeTimestamps,
                             eventOnsetTimes,
                             currentAmp,
                             currentBand, [0.0, 1.0],
                             title='bandwidth selectivity')
            plt.subplot2grid((12, 15), (10, 3), rowspan=2, colspan=3)
            band_select_plot(spikeTimestamps,
                             eventOnsetTimes,
                             currentAmp,
                             currentBand, [0.2, 1.0],
                             title='first 200ms excluded')

            # -- plot frequency tuning heat map --
            plt.subplot2grid((12, 15), (5, 7), rowspan=4, colspan=4)

            eventData = ei2.loader.get_session_events(sessions[1])
            spikeData = ei2.loader.get_session_spikes(sessions[1],
                                                      tetrode,
                                                      cluster=cluster)
            eventOnsetTimes = ei2.loader.get_event_onset_times(eventData)
            spikeTimestamps = spikeData.timestamps

            dataplotter.two_axis_heatmap(
                spikeTimestamps=spikeTimestamps,
                eventOnsetTimes=eventOnsetTimes,
                firstSortArray=currentInt,
                secondSortArray=currentFreq,
                firstSortLabels=[
                    "%.1f" % inten for inten in np.unique(currentInt)
                ],
                secondSortLabels=[
                    "%.1f" % freq for freq in np.unique(currentFreq) / 1000.0
                ],
                xlabel='Frequency (kHz)',
                ylabel='Intensity (dB SPL)',
                plotTitle='Frequency Tuning Curve',
                flipFirstAxis=True,
                flipSecondAxis=False,
                timeRange=[0, 0.1])
            plt.ylabel('Intensity (dB SPL)')
            plt.xlabel('Frequency (kHz)')
            plt.title('Frequency Tuning Curve')

            # -- plot frequency tuning raster --
            plt.subplot2grid((12, 15), (0, 7), rowspan=4, colspan=4)
            freqLabels = [
                "%.1f" % freq for freq in np.unique(currentFreq) / 1000.0
            ]
            dataplotter.plot_raster(spikeTimestamps,
                                    eventOnsetTimes,
                                    sortArray=currentFreq,
                                    timeRange=[-0.1, 0.5],
                                    labels=freqLabels)
            plt.xlabel('Time from sound onset (sec)')
            plt.ylabel('Frequency (kHz)')
            plt.title('Frequency Tuning Raster')

            # -- plot AM PSTH --
            eventData = ei2.loader.get_session_events(sessions[2])
            spikeData = ei2.loader.get_session_spikes(sessions[2],
                                                      tetrode,
                                                      cluster=cluster)
            eventOnsetTimes = ei2.loader.get_event_onset_times(eventData)
            spikeTimestamps = spikeData.timestamps
            timeRange = [-0.2, 1.5]

            spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                spikeTimestamps, eventOnsetTimes, timeRange)
            colourList = ['b', 'g', 'y', 'orange', 'r']
            numRates = np.unique(currentRate)
            trialsEachCond = behavioranalysis.find_trials_each_type(
                currentRate, numRates)
            binEdges = np.around(np.arange(-0.2, 0.85, 0.05), decimals=2)
            spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
                spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges)
            plt.subplot2grid((12, 15), (5, 11), rowspan=4, colspan=4)
            pPSTH = extraplots.plot_psth(spikeCountMat / 0.05,
                                         1,
                                         binEdges[:-1],
                                         trialsEachCond,
                                         colorEachCond=colourList)
            plt.setp(pPSTH)
            plt.xlabel('Time from sound onset (sec)')
            plt.ylabel('Firing rate (Hz)')
            plt.title('AM PSTH')

            # -- plot AM raster --
            plt.subplot2grid((12, 15), (0, 11), rowspan=4, colspan=4)
            rateLabels = ["%.1f" % rate for rate in np.unique(currentRate)]
            dataplotter.plot_raster(spikeTimestamps,
                                    eventOnsetTimes,
                                    sortArray=currentRate,
                                    timeRange=[-0.2, 0.8],
                                    labels=rateLabels,
                                    colorEachCond=colourList)
            plt.xlabel('Time from sound onset (sec)')
            plt.ylabel('Modulation Rate (Hz)')
            plt.title('AM Raster')

            # -- show cluster analysis --
            tsThisCluster = oneTT.timestamps[oneTT.clusters == cluster]
            wavesThisCluster = oneTT.samples[oneTT.clusters == cluster]

            # -- Plot ISI histogram --
            plt.subplot2grid((12, 15), (10, 6), rowspan=2, colspan=3)
            spikesorting.plot_isi_loghist(tsThisCluster)
            plt.ylabel('c%d' % cluster, rotation=0, va='center', ha='center')
            plt.xlabel('')

            # -- Plot waveforms --
            plt.subplot2grid((12, 15), (10, 9), rowspan=2, colspan=3)
            spikesorting.plot_waveforms(wavesThisCluster)

            # -- Plot projections --
            plt.subplot2grid((12, 15), (10, 12), rowspan=1, colspan=3)
            spikesorting.plot_projections(wavesThisCluster)

            # -- Plot events in time --
            plt.subplot2grid((12, 15), (11, 12), rowspan=1, colspan=3)
            spikesorting.plot_events_in_time(tsThisCluster)

            plt.subplots_adjust(wspace=1.5)
            plt.suptitle(
                '{0}, {1}, {2}, Tetrode {3}, Cluster {4}, {5}kHz, {6}Hz modulation'
                .format(mouse, date, siteName, tetrode, cluster, charfreq,
                        modrate))
            fig_path = oneTT.clustersDir
            fig_name = 'TT{0}Cluster{1}.png'.format(tetrode, cluster)
            full_fig_path = os.path.join(fig_path, fig_name)
            fig = plt.gcf()
            fig.set_size_inches(24, 12)
            fig.savefig(full_fig_path, format='png', bbox_inches='tight')
Example #24
0
def tuning_raster(bdata, ephysData, gs):
    #plt.subplot(gs[1, 1])

    freqEachTrial = bdata['currentFreq']
    intEachTrial = bdata['currentIntensity']
    
    eventOnsetTimes = ephysData['events']['stimOn']
    spikeTimeStamps = ephysData['spikeTimes']

    timeRange = [-0.3, 0.6]
    baseTimeRange = [-0.15, -0.05]

    possiblefreqs = np.unique(freqEachTrial)
    freqLabels = [round(x/1000, 1) for x in possiblefreqs]
    possibleInts = np.unique(intEachTrial)

    intTrialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possiblefreqs, intEachTrial, possibleInts)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
            spikeTimeStamps, eventOnsetTimes, timeRange)
    #print len(freqEachTrial), len(eventOnsetTimes)

    baseSpikeMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, baseTimeRange)    

    for intInd, inten in enumerate(possibleInts):
        ax = plt.subplot(gs[intInd*5:5+(intInd*5),1])

        trialsEachCond = intTrialsEachCond[:,:,intInd]

        trialsThisInt = np.all([bdata['currentIntensity']==inten], axis=0)
        baseSpikeMatThisCond = baseSpikeMat[trialsThisIntLaser==True]

        base_avg = np.mean(baseSpikeMatThisCond) / (baseTimeRange[1] - baseTimeRange[0])
        base_sem = stats.sem(baseSpikeMatThisCond) / (baseTimeRange[1] - baseTimeRange[0])

        #    for freqInd, freq in enumerate(possiblefreqs):
        #        freq_spikecounts = spikeMat[trialsEachCond[:,freqInd]==True]
        #        freq_avg = np.mean(freq_spikecounts) / (soundTimeRange[1] - soundTimeRange[0])
        #        freq_avgs.append(freq_avg)
        '''
        try:
            base_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, baseIndexLimitsEachTrial)
        except:
            behavBaseIndexLimitsEachTrial = baseIndexLimitsEachTrial[0:2,:-1]
            base_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, behavBaseIndexLimitsEachTrial)
        
        base_avg = np.mean(base_avgs)
        base_frs = np.divide(base_avg, baseTimeRange[1] - baseTimeRange[0])
        #print(base_avg)
        '''

        title = "Tuning Curve {} dB (Base FR: {} +/- {} spikes/s)".format(str(inten), round(base_avg, 2), round(base_sem, 2)) 
        #title = "Tuning Curve (Base FR: {} spikes/s)".format(round(base_avg, 2)) 

        pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange,
                                                       trialsEachCond=trialsEachCond, labels=freqLabels)


        xlabel = 'Time from sound onset (s)'
        ylabel = 'Frequency (kHz)'

        plt.title(title, fontsize = 'medium')
        plt.xlabel(xlabel)
        plt.ylabel(ylabel)
    '''
def bandwidth_suppression_from_peak(spikeTimeStamps,
                                    eventOnsetTimes,
                                    firstSort,
                                    secondSort,
                                    timeRange=[0.2, 1.0],
                                    baseRange=[-1.0, -0.2],
                                    subtractBaseline=False,
                                    zeroBWBaseline=True):
    '''Calculates suppression stats from raw data (no model).
    
    Inputs:
        spikeTimeStamps: array of timestamps indicating when spikes occurred
        eventOnsetTimes: array of timestamps indicating sound onsets
        firstSort: array of length N trials indicating value of first parameter for each trial (ex. bandwidths)
        secondSort: array of length N trials indicating value of second parameter for each trial. Second parameter should be manipulation being done (ex. laser), as it is used to calculate separate indices and baselines.
        timeRange: time period over which to calculate cell responses
        subtractBaseline: boolean, whether baseline firing rate should be subtracted from responses when calculating stats
        
    Output:
        suppressionIndex: suppression index for cell for each condition (e.g. for each amplitude, for each laser trial type)
        suppressionpVal: p value for each value in suppressionIndex
        facilitationIndex: facilitation index for cell for each condition
        facilitationpVal: p value for each value in facilitationIndex
        peakInd: index of responseArray containing largest firing rate (to calculate preferred bandwidth)
        spikeArray: array of size N condition 1 x N condition 2, average spike rates for each condition used to calculate suppression stats
    '''
    fullTimeRange = [baseRange[0], timeRange[1]]
    trialsEachCond = behavioranalysis.find_trials_each_combination(
        firstSort, np.unique(firstSort), secondSort, np.unique(secondSort))
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimeStamps, eventOnsetTimes, fullTimeRange)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange)
    baseSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange)

    trialsEachSecondSort = behavioranalysis.find_trials_each_type(
        secondSort, np.unique(secondSort))

    spikeArray, errorArray = calculate_tuning_curve_inputs(
        spikeCountMat, firstSort, secondSort)
    spikeArray = spikeArray / (timeRange[1] - timeRange[0]
                               )  #convert spike counts to firing rate

    suppressionIndex = np.zeros(spikeArray.shape[1])
    facilitationIndex = np.zeros_like(suppressionIndex)
    peakInds = np.zeros_like(suppressionIndex)

    suppressionpVal = np.zeros_like(suppressionIndex)
    facilitationpVal = np.zeros_like(suppressionIndex)

    for ind in range(len(suppressionIndex)):
        trialsThisSecondVal = trialsEachSecondSort[:, ind]

        thisCondResponse = spikeArray[:, ind]
        thisCondBaseline = np.mean(
            baseSpikeCountMat[trialsThisSecondVal].flatten()) / (baseRange[1] -
                                                                 baseRange[0])

        if zeroBWBaseline:
            thisCondResponse[0] = thisCondBaseline

        if not subtractBaseline:
            thisCondBaseline = 0

        spikeArray[:, ind] = thisCondResponse

        suppressionIndex[ind] = (max(thisCondResponse) - thisCondResponse[-1]
                                 ) / (max(thisCondResponse) - thisCondBaseline)
        facilitationIndex[ind] = (max(thisCondResponse) -
                                  thisCondResponse[0]) / (
                                      max(thisCondResponse) - thisCondBaseline)

        peakInd = np.argmax(thisCondResponse)
        peakInds[ind] = peakInd

        fullTrialsThisSecondVal = trialsEachCond[:, :, ind]

        if zeroBWBaseline:
            if peakInd == 0:
                peakSpikeCounts = baseSpikeCountMat[
                    trialsThisSecondVal].flatten()
            else:
                peakSpikeCounts = spikeCountMat[
                    fullTrialsThisSecondVal[:, peakInd]].flatten()
            zeroBWSpikeCounts = baseSpikeCountMat[trialsThisSecondVal].flatten(
            )
        else:
            peakSpikeCounts = spikeCountMat[
                fullTrialsThisSecondVal[:, peakInd]].flatten()
            zeroBWSpikeCounts = spikeCountMat[
                fullTrialsThisSecondVal[:, 0]].flatten()

        whiteNoiseSpikeCounts = spikeCountMat[
            fullTrialsThisSecondVal[:, -1]].flatten()

        suppressionpVal[ind] = stats.ranksums(peakSpikeCounts,
                                              whiteNoiseSpikeCounts)[1]
        facilitationpVal[ind] = stats.ranksums(peakSpikeCounts,
                                               zeroBWSpikeCounts)[1]

    return suppressionIndex, suppressionpVal, facilitationIndex, facilitationpVal, peakInds, spikeArray
Example #26
0
    def plot_session_tc_heatmap(self, session, tetrode, behavFileIdentifier, replace = 0, cluster = None, norm=False, clim = None):

        '''
        Wrapper to plot a TC heatmap for a single session/tetrode

        Extracts the data from a single tetrode in a recording session, and uses the data to call plot_tc_heatmap.
        The session can either be the actual session name as a string, or an integer that will be used the select
        a session from the sorted list of sessions in the ephys directory for this recording day. Also takes the
        unique identifier for the behavior data file. Can select only the spikes belonging to a single cluster
        if clustering has been done on an ephys session.

        Args:
            session (str or int): Either the session name as a string or an int that will be used to select the session from
                                  the sorted list of sessions in the current directory.
            tetrode (int): The number of the tetrode to plot
            behavFileIdentifier (str): The unique portion of the behavior data filename used to identify it.
            cluster (int): Optional, the number of the cluster to plot. Leave unset to analyze the entire site.
            norm (bool): Whether or not to normalize to the maximum spike rate for the color axis

        Examples:

        With a specified session and the behavior file 'animal000_behavior_paradigm_20150624a.h5'

        >>>experiment.plot_session_tc_heatmap('2015-06-24_15-32-16', 6, 'a')

        To use the last recorded ephys session (the -1 index in the sorted list)

        >>>experiment.plot_session_tc_heatmap(-1, 6, 'a')
        '''

        #Get the ephys and event data
        spikeData = self.get_session_spike_data_one_tetrode(session, tetrode)
        eventData = self.get_session_event_data(session)
        plotTitle = self.get_session_plot_title(session)

        #Get the behavior data and extract the freq and intensity each trial
        bdata = self.get_session_behav_data(session, behavFileIdentifier)
        freqEachTrial = bdata['currentFreq']
        possibleFreq = np.unique(freqEachTrial)
        intensityEachTrial = bdata['currentIntensity']
        possibleIntensity = np.unique(intensityEachTrial)

        #Calculate event onset times from the event data
        eventOnsetTimes = self.get_event_onset_times(eventData)

        #Extract the timestamps from the spikeData object, limit to a single cluster if needed
        spikeTimestamps = spikeData.timestamps
        if cluster:
            spikeTimestamps = spikeTimestamps[spikeData.clusters==cluster]

        #Call the plotting code with the data
        #self.plot_tc_heatmap_old(spikeTimestamps, eventOnsetTimes, freqEachTrial, intensityEachTrial, replace = replace, norm = norm, clim=clim)

        print "Ephys events: {}".format(len(eventOnsetTimes))
        print "Behavior trials: {}".format(len(freqEachTrial))

        trialsEachCond = behavioranalysis.find_trials_each_combination(intensityEachTrial, possibleIntensity, freqEachTrial, possibleFreq)

        timeRange = [0, 0.1]
        spikeArray = self.avg_spikes_in_event_locked_timerange_each_cond(spikeTimestamps, trialsEachCond, eventOnsetTimes, timeRange)

        self.plot_TCarray_as_heatmap(spikeArray, possibleFreq, possibleIntensity, timeRange)
     sustainedTestStatistic = np.nan
     sustainedpVal = np.nan
 else:
     bandEventOnsetTimes = get_sound_onset_times(
         bandEphysData, 'bandwidth')
     bandSpikeTimestamps = bandEphysData['spikeTimes']
     bandEachTrial = bandBehavData['currentBand']
     if subType == 'chr2':
         secondSort = bandBehavData['currentAmp']
         cond = -1
     if subType == 'archt':
         secondSort = bandBehavData['laserTrial']
         cond = 0
     numBands = np.unique(bandEachTrial)
     numSec = np.unique(secondSort)
     trialsEachComb = behavioranalysis.find_trials_each_combination(
         bandEachTrial, numBands, secondSort, numSec)
     trialsEachBaseCond = trialsEachComb[:, :,
                                         cond]  #using high amp trials for photoidentified, no laser for inactivation
     testStatistic, pVal = sound_response_any_stimulus(
         bandEventOnsetTimes, bandSpikeTimestamps,
         trialsEachBaseCond, [0.0, 1.0], [-1.2, -0.2])
     onsetTestStatistic, onsetpVal = sound_response_any_stimulus(
         bandEventOnsetTimes, bandSpikeTimestamps,
         trialsEachBaseCond, [0.0, 0.05], [-0.25, 0.2])
     sustainedTestStatistic, sustainedpVal = sound_response_any_stimulus(
         bandEventOnsetTimes, bandSpikeTimestamps,
         trialsEachBaseCond, [0.2, 1.0], [-1.0, 0.2])
     pVal *= len(numSec)  #correction for multiple comparisons
     onsetpVal *= len(numSec)
     sustainedpVal *= len(numSec)
 soundResponseTestStatistic[indRow] = testStatistic
Example #28
0
def two_axis_sorted_raster(
        spikeTimestamps,
        eventOnsetTimes,
        firstSortArray,
        secondSortArray,
        firstSortLabels=None,
        secondSortLabels=None,
        xLabel=None,
        yLabel=None,
        plotTitle=None,
        flipFirstAxis=False,
        flipSecondAxis=True,  #Useful for making the highest intensity plot on top
        timeRange=[-0.5, 1],
        ms=4):
    '''
    This function takes two arrays and uses them to sort spikes into trials by combinaion, and then plots the spikes in raster form.

    The first sort array will be used to sort each raster plot, and there will be a separate raster plot for each possible value of the
    second sort array. This method was developed for plotting frequency-intensity tuning curve data in raster form, in which case the
    frequency each trial is passed as the first sort array, and the intensity each trial is passed as the second sort array.

    Args:
        spikeTimestamps (array): An array of spike timestamps to plot
        eventOnsetTimes (array): An array of event onset times. Spikes will be plotted in raster form relative to these times
        firstSortArray (array): An array of parameter values for each trial. Must be the same length as eventOnsetTimes.
        secondSortArray (array): Another array of paramenter values the same length as eventOnsetTimes.
                                 Better if this array has less possible values.
        firstSortLabels (list): A list containing strings to use as labels for the first sort array.
                                Must contain one item for each possible value of the first sort array.
        secondSortLabels (list): Same idea as above, must contain one element for each possible value of the second sort array.
        xLabel (str): A string to use for the x label of the bottom raster plot
        flipFirstAxis (bool): Whether to flip the first sorting axis.
                              Will result in trials with high values for the first sort array appearing on the bottom of each raster.
        flipSecondAxis (bool): Will result in trials with high values for the second sorting array appearing in the top raster plot
        timeRange (list): A list containing the range of times relative to the event onset times that will be plotted
        ms (int): The marker size to use for the raster plots
    '''
    if not firstSortLabels:
        firstSortLabels = []
    if not secondSortLabels:
        secondSortLabels = []
    if not xLabel:
        xlabel = ''
    if not yLabel:
        ylabel = ''
    if not plotTitle:
        plotTitle = ''
    #Set first and second possible val arrays and invert them if desired for plotting
    firstPossibleVals = np.unique(firstSortArray)
    secondPossibleVals = np.unique(secondSortArray)
    if flipFirstAxis:
        firstPossibleVals = firstPossibleVals[::-1]
        firstSortLabels = firstSortLabels[::-1]
    if flipSecondAxis:
        secondPossibleVals = secondPossibleVals[::-1]
        secondSortLabels = secondSortLabels[::-1]
    #Find the trials that correspond to each pair of sorting values
    trialsEachCond = behavioranalysis.find_trials_each_combination(
        firstSortArray, firstPossibleVals, secondSortArray, secondPossibleVals)
    #Calculate the spike times relative to event onset times
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimestamps, eventOnsetTimes, timeRange)
    #Grab the current figure and clear it for plotting
    fig = plt.gcf()
    plt.clf()
    #Make a new plot for each unique value of the second sort array, and then plot a raster on that plot sorted by this second array
    for ind, secondArrayVal in enumerate(secondPossibleVals):
        if ind == 0:
            fig.add_subplot(len(secondPossibleVals), 1, ind + 1)
            plt.title(plotTitle)
        else:
            fig.add_subplot(len(secondPossibleVals),
                            1,
                            ind + 1,
                            sharex=fig.axes[0],
                            sharey=fig.axes[0])
        trialsThisSecondVal = trialsEachCond[:, :, ind]
        pRaster, hcond, zline = extraplots.raster_plot(
            spikeTimesFromEventOnset,
            indexLimitsEachTrial,
            timeRange,
            trialsEachCond=trialsThisSecondVal,
            labels=firstSortLabels)
        plt.setp(pRaster, ms=ms)
        if secondSortLabels:
            plt.ylabel(secondSortLabels[ind])
        if ind == len(secondPossibleVals) - 1:
            plt.xlabel(xLabel)
def laser_tuning_raster(cell, gs):

    laserSessionInds = cell.get_session_inds('laserTuningCurve')
    for count, sessionInd in enumerate(laserSessionInds):

        bdata = cell.load_behavior_by_index(sessionInd)
        ephysData = cell.load_ephys_by_index(sessionInd)

        freqEachTrial = bdata['currentFreq']
        laserEachTrial = bdata['laserOn']
        intEachTrial = bdata['currentIntensity']
        
        eventOnsetTimes = ephysData['events']['stimOn']
        spikeTimeStamps = ephysData['spikeTimes']

        timeRange = [-0.3, 0.6]
        baseTimeRange = [-0.15, -0.05]
        
        possiblefreqs = np.unique(freqEachTrial)
        freqLabels = [round(x/1000, 1) for x in possiblefreqs]
        possiblelaser = np.unique(laserEachTrial)
        possibleInts = np.unique(intEachTrial)

        laserOnsetTimes = ephysData['events']['laserOn']
        laserOffsetTimes = ephysData['events']['laserOff']
        laserDuration = laserOffsetTimes - laserOnsetTimes
        meanLaser = round(laserDuration.mean(), 2)
        #print(meanLaser)
        laserEventOnsetTimes = eventOnsetTimes[laserEachTrial == True]
        if len(laserOnsetTimes) > len(laserEventOnsetTimes):
            laserStartTimes = laserOnsetTimes[:-1] - laserEventOnsetTimes
        elif len(laserEventOnsetTimes) > len(laserOnsetTimes):
            laserStartTimes = laserOnsetTimes - laserEventOnsetTimes[:-1]
        else:
            laserStartTimes = laserOnsetTimes - laserEventOnsetTimes
        laserStart = round(laserStartTimes.mean(), 2)
        #print(laserStart)
        #trialsEachCond = behavioranalysis.find_trials_each_type(freqEachTrial, possiblefreqs)

        laserTrialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possiblefreqs, laserEachTrial, possiblelaser)
        intTrialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possiblefreqs, intEachTrial, possibleInts)
        spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
            spikeTimeStamps, eventOnsetTimes, timeRange)
        #plt.figure()
        
        baseSpikeMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, baseTimeRange)
                
        for intInd, inten in enumerate(possibleInts):
            for indLaser in possiblelaser:
                #plt.subplot(2, 1, indLaser)
                ax = plt.subplot(gs[indLaser, intInd + (count * 2) + 1])
                if indLaser == 0:
                    title = "No Laser " + str(inten) + " dB"
                else:
                    title = "Laser " + str(inten) + " dB"
                trialsEachCond = laserTrialsEachCond[:,:,indLaser] & intTrialsEachCond[:,:,intInd]
                '''
                try:
                    base_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, baseIndexLimitsEachTrial)
                except:
                    behavBaseIndexLimitsEachTrial = baseIndexLimitsEachTrial[0:2,:-1]
                    base_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, behavBaseIndexLimitsEachTrial)

                base_avg = np.mean(base_avgs)
                base_frs = np.divide(base_avg, baseTimeRange[1] - baseTimeRange[0])
                '''
                trialsThisIntLaser = np.all([bdata['laserOn']==indLaser, bdata['currentIntensity']==inten], axis=0)
                baseSpikeMatThisCond = baseSpikeMat[trialsThisIntLaser==True]

                base_avg = np.mean(baseSpikeMatThisCond) / (baseTimeRange[1] - baseTimeRange[0])
                base_sem = stats.sem(baseSpikeMatThisCond) / (baseTimeRange[1] - baseTimeRange[0])

                title += " (Base FR: {} +/- {} spikes/s)".format(round(base_avg, 2), round(base_sem, 2))
                #title += " (Base FR: {} spikes/s)".format(round(base_avg, 2)) 
                pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange,
                                                           trialsEachCond=trialsEachCond, labels=freqLabels)

                if indLaser == 1:
                    laserbar = patches.Rectangle((laserStart, sum(sum(trialsEachCond)) + 2), meanLaser, 5, color="b", clip_on=False)
                    #laserbar = patches.Rectangle((-0.05, 10), 2.0, 5, color="b")
                    ax.add_patch(laserbar)

                xlabel = 'Time from sound onset (s)'
                ylabel = 'Frequency (kHz)'

                plt.title(title, fontsize = 'medium')
                plt.xlabel(xlabel)
                plt.ylabel(ylabel)
        '''
testspikes = spikeTimesFromEventOnset[np.in1d(trialIndexForEachSpike, trialsThisCombo)]
freq4inds = trialIndexForEachSpike[np.in1d(trialIndexForEachSpike, trialsThisCombo)]










#A potentially flawed idea that I might come back to. It is not as helpful with this idea as I thought it would be
#Copies of two functions from dataplotter that should help with the analysis of TCs

trialsEachCond = behavioranalysis.find_trials_each_combination(currentIntensity, possibleIntensity, currentFreq, possibleFreq)
conditionMatShape = np.shape(trialsEachCond)



timeRange = [0, 0.1]
spikeTimestamps = spikeData.timestamps
eventOnsetTimes = loader.get_event_onset_times(eventData)

if len(eventOnsetTimes) != np.shape(trialsEachCond)[0]:
    eventOnsetTimes = eventOnsetTimes[:-1]

spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
    spikeTimestamps, eventOnsetTimes, timeRange)

numSpikesInTimeRangeEachTrial = np.squeeze(np.diff(indexLimitsEachTrial,
Example #31
0
def two_axis_heatmap(
        spikeTimestamps,
        eventOnsetTimes,
        firstSortArray,  #Should be intensity in F/I TC (Y axis)
        secondSortArray,  #Should be frequency in F/I TC (X Axis)
        firstPossibleVals=None,
        secondPossibleVals=None,
        firstSortLabels=None,
        secondSortLabels=None,
        xlabel=None,
        ylabel=None,
        plotTitle=None,
        flipFirstAxis=True,  #Useful for making the highest intensity plot on top
        flipSecondAxis=False,
        timeRange=[0, 0.1],
        cmap='Blues'):
    '''
    This function takes two arrays and uses them to sort spikes into trials by combinaion,
    and then plots the average number of spikes after the stim in heatmap form.
    The first sort array should be the intensity in a F/I tuning curve,
    and the second sort array should be the frequency.

    Args:
        spikeTimestamps (array): An array of spike timestamps to plot
        eventOnsetTimes (array): An array of event onset times.
                                 Spikes will be plotted in raster form relative to these times
        firstSortArray (array): An array of parameter values for each trial.
                                Must be the same length as eventOnsetTimes.
        secondSortArray (array): Another array of paramenter values the same length as eventOnsetTimes.
                                 Better if this array has less possible values.
        firstSortLabels (list): A list containing strings to use as labels for the first sort array.
                                Must contain one item for each possible value of the first sort array.
        secondSortLabels (list): Same idea as above, must contain one element for each possible value of the second sort array.
        xLabel (str): A string to use for the x label of the bottom raster plot
        flipFirstAxis (bool): Whether to flip the first sorting axis.
                              Will result in trials with high values for the first sort array appearing on the bottom of each raster.
        flipSecondAxis (bool): Will result in trials with high values for the second sorting array appearing in the top raster plot
        timeRange (list): A list containing the range of times relative to the stimulus onset over which the spike average will be computed
    '''
    if not firstSortLabels:
        firstSortLabels = []
    if not secondSortLabels:
        secondSortLabels = []
    if not xlabel:
        xlabel = ''
    if not ylabel:
        ylabel = ''
    if not plotTitle:
        plotTitle = ''
    if not firstPossibleVals:
        firstPossibleVals = np.unique(firstSortArray)
    if not secondPossibleVals:
        secondPossibleVals = np.unique(secondSortArray)
    if firstSortLabels == None:
        firstSortLabels = []
    if secondSortLabels == None:
        secondSortLabels = []
    if xlabel == None:
        xlabel = ''
    if ylabel == None:
        ylabel = ''
    cbarLabel = 'Avg spikes in time range: {}'.format(timeRange)
    if flipFirstAxis:
        firstPossibleVals = firstPossibleVals[::-1]
        firstSortLabels = firstSortLabels[::-1]
    if flipSecondAxis:
        secondPossibleVals = secondPossibleVals[::-1]
        secondSortLabels = secondSortLabels[::-1]
    #Find trials each combination
    trialsEachCond = behavioranalysis.find_trials_each_combination(
        firstSortArray, firstPossibleVals, secondSortArray, secondPossibleVals)
    #Make an aray of the average number of spikes in the timerange after the stim for each condition
    spikeArray = avg_spikes_in_event_locked_timerange_each_cond(
        spikeTimestamps, trialsEachCond, eventOnsetTimes, timeRange)
    #Plot the array as a heatmap

    ax, cax, cbar = plot_array_as_heatmap(spikeArray,
                                          xlabel=xlabel,
                                          ylabel=ylabel,
                                          xtickLabels=secondSortLabels,
                                          ytickLabels=firstSortLabels,
                                          cbarLabel=cbarLabel,
                                          cmap=cmap)
    return ax, cax, cbar
Example #32
0
    if inda == nAnimals - 1:
        xlabel('Target frequency', fontsize=fontSize)

    ax1 = subplot2grid((nAnimals, 3), (inda, 1))
    axhline(50, ls='--', color='0.6')
    axhline(75, ls='--', color='0.8')
    plot(100 * fractionCorrectEachCue, 'og-', mec='none')
    ylim([0, 100])
    xlim([-0.5, len(possibleCue) - 0.5])
    #ylabel('Correct (%)',fontsize=fontSize)
    if inda == nAnimals - 1:
        xlabel('Cue frequency', fontsize=fontSize)
    if inda == 0:
        title(session)

    tec = behavioranalysis.find_trials_each_combination(
        targetFrequency, possibleTarget, cueFrequency, possibleCue)
    nTrialsEachComb = tec.sum(axis=0)
    nCorrectEachComb = np.sum(tec & correct[:, np.newaxis, np.newaxis], axis=0)
    fractionCorrectEachComb = nCorrectEachComb.astype(float) / nTrialsEachComb
    ax2 = subplot2grid((nAnimals, 3), (inda, 2))
    if 1:
        imshow(100 * fractionCorrectEachComb, cmap='PiYG', vmin=0, vmax=100)
        cbar = colorbar()
        cbar.set_ticks([0, 25, 50, 75, 100])
        cbar.set_label('Correct (%)', rotation=270, fontsize=fontSize)
        plt.setp(cbar.ax.get_yticklabels(), fontsize=smallFontSize)
    else:
        imshow(nTrialsEachComb, cmap='jet', vmin=0)
        cbar = colorbar()
    for indt in range(len(possibleTarget)):
        for indc in range(len(possibleCue)):
Example #33
0
    cellInd, dbRow = celldatabase.find_cell(db, **oneCell)
    cell = ephyscore.Cell(dbRow)

    bandEphysData, bandBData = cell.load_by_index(int(
        dbRow['bestBandSession']))
    bandEventOnsetTimes = bandEphysData['events']['soundDetectorOn']
    bandEventOnsetTimes = spikesanalysis.minimum_event_onset_diff(
        bandEventOnsetTimes, minEventOnsetDiff=0.2)
    bandSpikeTimestamps = bandEphysData['spikeTimes']

    bandEachTrial = bandBData['currentBand']
    numBands = np.unique(bandEachTrial)
    LaserEachTrial = bandBData['laserTrial']
    numLaser = np.unique(LaserEachTrial)

    bandTrialsEachCond = behavioranalysis.find_trials_each_combination(
        bandEachTrial, numBands, LaserEachTrial, numLaser)

    bandTimeRange = [-0.5, 1.5]
    binsize = 50  #in milliseconds

    bandSpikeTimesFromEventOnset, trialIndexForEachSpike, bandIndexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        bandSpikeTimestamps, bandEventOnsetTimes,
        [bandTimeRange[0] - binsize, bandTimeRange[1]])

    binEdges = np.around(np.arange(bandTimeRange[0] - (binsize / 1000.0),
                                   bandTimeRange[1] + 2 * (binsize / 1000.0),
                                   (binsize / 1000.0)),
                         decimals=2)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        bandSpikeTimesFromEventOnset, bandIndexLimitsEachTrial, binEdges)
Example #34
0
def band_select_plot(spikeTimeStamps,
                     eventOnsetTimes,
                     amplitudes,
                     bandwidths,
                     timeRange,
                     fullRange=[0.0, 2.0],
                     title=None):
    numBands = np.unique(bandwidths)
    numAmps = np.unique(amplitudes)
    spikeArray = np.zeros((len(numBands), len(numAmps)))
    errorArray = np.zeros_like(spikeArray)
    trialsEachCond = behavioranalysis.find_trials_each_combination(
        bandwidths, numBands, amplitudes, numAmps)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimeStamps, eventOnsetTimes, fullRange)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange)
    baseTimeRange = [timeRange[1] + 0.5, fullRange[1]]
    baseSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, baseTimeRange)
    baselineSpikeRate = np.mean(baseSpikeCountMat) / (baseTimeRange[1] -
                                                      baseTimeRange[0])
    plt.hold(True)
    for amp in range(len(numAmps)):
        trialsThisAmp = trialsEachCond[:, :, amp]
        for band in range(len(numBands)):
            trialsThisBand = trialsThisAmp[:, band]
            if spikeCountMat.shape[0] != len(trialsThisBand):
                spikeCountMat = spikeCountMat[:-1, :]
                print "FIXME: Using bad hack to make event onset times equal number of trials"
            thisBandCounts = spikeCountMat[trialsThisBand].flatten()
            spikeArray[band, amp] = np.mean(thisBandCounts)
            errorArray[band, amp] = stats.sem(thisBandCounts)
    xrange = range(len(numBands))
    plt.plot(xrange,
             baselineSpikeRate * (timeRange[1] - timeRange[0]) *
             np.ones(len(numBands)),
             color='0.75',
             linewidth=2)
    plt.plot(xrange,
             spikeArray[:, 0].flatten(),
             '-o',
             color='#4e9a06',
             linewidth=3)
    plt.fill_between(xrange,
                     spikeArray[:, 0].flatten() - errorArray[:, 0].flatten(),
                     spikeArray[:, 0].flatten() + errorArray[:, 0].flatten(),
                     alpha=0.2,
                     edgecolor='#8ae234',
                     facecolor='#8ae234')
    plt.plot(range(len(numBands)),
             spikeArray[:, 1].flatten(),
             '-o',
             color='#5c3566',
             linewidth=3)
    plt.fill_between(xrange,
                     spikeArray[:, 1].flatten() - errorArray[:, 1].flatten(),
                     spikeArray[:, 1].flatten() + errorArray[:, 1].flatten(),
                     alpha=0.2,
                     edgecolor='#ad7fa8',
                     facecolor='#ad7fa8')
    ax = plt.gca()
    ax.set_xticklabels(numBands)
    plt.xlabel('bandwidth (octaves)')
    plt.ylabel('Average num spikes')
    #patch1 = mpatches.Patch(color='#5c3566', label='0.8')
    #patch2 = mpatches.Patch(color='#4e9a06', label='0.2')
    #plt.legend(handles=[patch1, patch2], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    if title:
        plt.title(title)
Example #35
0
laserAccuracy = None
controlAccuracy = None

laserBias = None
controlBias = None

for indMouse, mouse in enumerate(PV_CHR2_MICE):

    laserSessions = studyparams.miceDict[mouse]['3mW laser']
    laserBehavData = behavioranalysis.load_many_sessions(mouse, laserSessions)

    numLasers = np.unique(laserBehavData['laserSide'])
    numBands = np.unique(laserBehavData['currentBand'])

    trialsEachCond = behavioranalysis.find_trials_each_combination(
        laserBehavData['laserSide'], numLasers, laserBehavData['currentBand'],
        numBands)

    # -- compute accuracies and bias for each bandwidth --

    for indBand in range(len(numBands)):
        trialsEachLaser = trialsEachCond[:, :, indBand]

        # -- sort trials by laser presentation, compute accuracy as percent correct trials out of all valid trials --
        valid = laserBehavData['valid'].astype(bool)
        correct = laserBehavData['outcome'] == laserBehavData.labels[
            'outcome']['correct']

        laserValid = valid[trialsEachLaser[:, 1]]
        laserCorrect = correct[trialsEachLaser[:, 1]]
Example #36
0
    eventOnsetTimes = ephysData['events']['soundDetectorOn']

    eventOnsetTimes = spikesanalysis.minimum_event_onset_diff(
        eventOnsetTimes, minEventOnsetDiff=0.2)
    spikeTimes = ephysData['spikeTimes']
    freqEachTrial = bdata['currentFreq']
    possibleFreq = np.unique(freqEachTrial)
    intensityEachTrial = bdata['currentIntensity']
    possibleIntensity = np.unique(intensityEachTrial)

    #FIXME: I need to remove the last event here if there is an extra one
    if len(eventOnsetTimes) == len(freqEachTrial) + 1:
        eventOnsetTimes = eventOnsetTimes[:-1]

    trialsEachCondition = behavioranalysis.find_trials_each_combination(
        intensityEachTrial, possibleIntensity, freqEachTrial, possibleFreq)

    baseRange = [-0.1, 0]
    responseRange = [0, 0.1]
    alignmentRange = [-0.2, 0.2]

    #Align all spikes to events
    (spikeTimesFromEventOnset, trialIndexForEachSpike,
     indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(
         spikeTimes, eventOnsetTimes, alignmentRange)

    #Count spikes in baseline and response ranges
    nspkBase = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange)
    nspkResp = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, responseRange)
def laser_tuning_curve(cell, gs):
    #plt.subplot(gs[3, 1])
    laserSessionInds = cell.get_session_inds('laserTuningCurve')
    for count, sessionInd in enumerate(laserSessionInds):

        bdata = cell.load_behavior_by_index(sessionInd)
        ephysData = cell.load_ephys_by_index(sessionInd)

        freqEachTrial = bdata['currentFreq']
        laserEachTrial = bdata['laserOn']
        intEachTrial = bdata['currentIntensity']
        
        eventOnsetTimes = ephysData['events']['stimOn']
        spikeTimeStamps = ephysData['spikeTimes']

        timeRange = [-0.3, 0.6]
        soundTimeRange = [0.0, 0.1]

        possiblefreqs = np.unique(freqEachTrial)
        freqLabels = [round(x/1000, 1) for x in possiblefreqs]
        possiblelaser = np.unique(laserEachTrial)
        possibleInts = np.unique(intEachTrial)

        laserTrialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possiblefreqs, laserEachTrial, possiblelaser)
        intTrialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possiblefreqs, intEachTrial, possibleInts)
        spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
            spikeTimeStamps, eventOnsetTimes, timeRange)

        for intInd, inten in enumerate(possibleInts):
            plt.subplot(gs[2,intInd+(count * 2)+1])
            line = '-'
            #if intInd == 0:
            #    line = '--'
            for indLaser in possiblelaser:
                color = 'black'
                if indLaser == 1:
                    color = 'blue'

                laser = 'No Laser'
                if indLaser == 1:
                    laser = 'Laser'
                curveName = laser + str(inten) + ' dB'

                trialsEachCond = laserTrialsEachCond[:,:,indLaser] & intTrialsEachCond[:,:,intInd]
                spikeMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, soundTimeRange)
                freq_avgs = np.empty(len(possiblefreqs))
                freq_sems = np.empty(len(possiblefreqs))
                for freqInd, freq in enumerate(possiblefreqs):
                    freq_spikecounts = spikeMat[trialsEachCond[:,freqInd]==True]
                    freq_avg = np.mean(freq_spikecounts) / (soundTimeRange[1] - soundTimeRange[0])
                    freq_avgs[freqInd] = freq_avg
                    freq_sem = stats.sem(freq_spikecounts) / (soundTimeRange[1] - soundTimeRange[0])
                    freq_sems[freqInd] = freq_sem
                '''
                try:
                    freq_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, indexLimitsEachTrial)
                    base_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, baseIndexLimitsEachTrial)
                except:
                    behavIndexLimitsEachTrial = indexLimitsEachTrial[0:2,:-1]
                    freq_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, behavIndexLimitsEachTrial)
                
                freq_frs = np.divide(freq_avgs, timeRange[1]-timeRange[0])
                #print(freq_avgs, freq_frs) 
                '''
                xpoints = [x for x in range(0, len(possiblefreqs))]
                xpointticks = [x for x in range(1, len(possiblefreqs), 2)]
                freqticks = [freqLabels[x] for x in range(1, len(freqLabels), 2)]
                #plt.semilogx(possiblefreqs, freq_avgs, linestyle = line, color = color, label = curveName)
                #plt.plot(xvalues, freq_avgs, linestyle = line, color = 'black', label = curveName, xlabels = possiblefreqs)
                #plt.plot(xpoints, freq_avgs, linestyle = line, color = color, marker = 'o', label = laser)
                #plt.errorbar(xpoints, freq_avgs, yerr = freq_stds, linestyle = line, color = color, marker = 'o', label = laser)
                plt.plot(xpoints, freq_avgs, linestyle = line, color = color, marker = 'o', label = laser)
                #plt.fill_between(xpoints, freq_avgs - freq_sems, freq_avgs + freq_sems, alpha = 0.1, color = color)
                plt.xticks(xpointticks, freqticks)
                plt.hold(True)
                
            xlabel = 'Frequency (kHz)'
            ylabel = 'Firing rate (spikes/s)'
            title = str(inten) + ' dB Tuning curve (time range: {})'.format(soundTimeRange)

            plt.xlabel(xlabel)
            plt.ylabel(ylabel)
            plt.title(title, fontsize = 'medium')
            plt.legend(fontsize = 'x-small', loc = 'upper right', frameon=False, framealpha=100, markerscale=0.5)
        plt.hold(False)
            ttEphysData, ttBehavData = oneCell.load(session)
        except IndexError:
            print("No {} in this site".format(session))
        except ValueError:
            print("No spikes in this site")
            df.at[indIter, "tuningTestBase"] = np.NaN
            df.at[indIter, "tuningTestResp"] = np.NaN
        else:
            ttBaseRange = [-0.1, 0]

            # Extracting information from ephys and behavior data to do calculations later with
            currentFreq = ttBehavData['currentFreq']
            currentIntensity = ttBehavData['currentIntensity']
            uniqFreq = np.unique(currentFreq)
            uniqueIntensity = np.unique(currentIntensity)
            ttTrialsEachCond = behavioranalysis.find_trials_each_combination(
                currentFreq, uniqFreq, currentIntensity, uniqueIntensity)

            ttSpikeTimes = ttEphysData['spikeTimes']
            ttEventOnsetTimes = ttEphysData['events']['soundDetectorOn']
            ttEventOnsetTimes = spikesanalysis.minimum_event_onset_diff(
                ttEventOnsetTimes, minEventOnsetDiff=0.2)

            if len(ttEventOnsetTimes) == (len(currentFreq) + 1):
                ttEventOnsetTimes = ttEventOnsetTimes[0:-1]
                print(
                    "Correcting ephys data to be same length as behavior data")
                toCalculate = True
            elif len(ttEventOnsetTimes) == len(currentFreq):
                print("Data is already the same length")
                toCalculate = True
            else:
def tuning_curve(bdata, ephysData, gs):
    plt.subplot(gs[2, 1])

    freqEachTrial = bdata['currentFreq']
    intEachTrial = bdata['currentIntensity']
    
    eventOnsetTimes = ephysData['events']['stimOn']
    spikeTimeStamps = ephysData['spikeTimes']

    timeRange = [-0.3, 0.6]
    soundTimeRange = [0.0, 0.1]

    possiblefreqs = np.unique(freqEachTrial)
    freqLabels = [round(x/1000, 1) for x in possiblefreqs]
    possibleInts = np.unique(intEachTrial)

    intTrialsEachCond = behavioranalysis.find_trials_each_combination(freqEachTrial, possiblefreqs, intEachTrial, possibleInts)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
            spikeTimeStamps, eventOnsetTimes, timeRange)
    for intInd, inten in enumerate(possibleInts):
        line = '-'
        if intInd == 0 and len(possibleInts) > 1:
            line = '--'
        curveName = str(inten) + ' dB'
        trialsEachCond = intTrialsEachCond[:,:,intInd]
        spikeMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, soundTimeRange)
        freq_avgs = np.empty(len(possiblefreqs))
        freq_sems = np.empty(len(possiblefreqs))
        for freqInd, freq in enumerate(possiblefreqs):
            freq_spikecounts = spikeMat[trialsEachCond[:,freqInd]==True]
            freq_avg = np.mean(freq_spikecounts) / (soundTimeRange[1] - soundTimeRange[0])
            freq_avgs[freqInd] = freq_avg
            freq_sem = stats.sem(freq_spikecounts) / (soundTimeRange[1] - soundTimeRange[0])
            freq_sems[freqInd] = freq_sem
        #print(spikeMat)
        #print(freq_avgs)
        '''
        try:
            freq_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, indexLimitsEachTrial)
        except:
            behavIndexLimitsEachTrial = indexLimitsEachTrial[0:2,:-1]
            freq_avgs = spikesanalysis.avg_num_spikes_each_condition(trialsEachCond, behavIndexLimitsEachTrial)
        
        freq_frs = np.divide(freq_avgs, timeRange[1]-timeRange[0])
        '''

        xpoints = [x for x in range(0, len(possiblefreqs))]
        xpointticks = [x for x in range(1, len(possiblefreqs), 2)]
        freqticks = [freqLabels[x] for x in range(1, len(freqLabels), 2)]
        #plt.semilogx(possiblefreqs, freq_avgs, linestyle = line, color = 'black', label = curveName)
        #plt.plot(log(possiblefreqs), freq_avgs, linestyle = line, color = 'black', label = curveName, xlabels = possiblefreqs)
        #plt.plot(xpoints, freq_avgs, linestyle = line, color = 'black', marker = 'o', label = curveName)
        #plt.errorbar(xpoints, freq_avgs, yerr = freq_stds, linestyle = line, color = 'black', marker = 'o', label = curveName)
        plt.plot(xpoints, freq_avgs, linestyle = line, color = 'black', marker = 'o', label = curveName)
        #plt.fill_between(xpoints, freq_avgs - freq_sems, freq_avgs + freq_sems, alpha = 0.1, color = 'black')
        plt.xticks(xpointticks, freqticks)
        plt.hold(True)

    xlabel = 'Frequency (kHz)'
    ylabel = 'Firing rate (spikes/s)'
    title = 'Tuning curve (time range: {})'.format(soundTimeRange)

    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.title(title, fontsize = 'medium')
    plt.legend(fontsize = 'x-small', loc = 'upper right', frameon=False, framealpha=100, markerscale=0.5)
    plt.hold(False)
Example #40
0
     onsetpVal = np.nan
     sustainedTestStatistic = np.nan
     sustainedpVal = np.nan
 else:
     bandEventOnsetTimes = get_sound_onset_times(bandEphysData, 'bandwidth')
     bandSpikeTimestamps = bandEphysData['spikeTimes']
     bandEachTrial = bandBehavData['currentBand']
     if subType == 'chr2':
         secondSort = bandBehavData['currentAmp']
         cond = -1
     if subType == 'archt':
         secondSort = bandBehavData['laserTrial']
         cond = 0
     numBands = np.unique(bandEachTrial)
     numSec = np.unique(secondSort)
     trialsEachComb = behavioranalysis.find_trials_each_combination(bandEachTrial, numBands, secondSort, numSec)
     trialsEachBaseCond = trialsEachComb[:,:,cond] #using high amp trials for photoidentified, no laser for inactivation
     testStatistic, pVal = sound_response_any_stimulus(bandEventOnsetTimes, bandSpikeTimestamps, trialsEachBaseCond, [0.0, 1.0], [-1.2,-0.2])
     onsetTestStatistic, onsetpVal = sound_response_any_stimulus(bandEventOnsetTimes, bandSpikeTimestamps, trialsEachBaseCond, [0.0,0.05], [-0.25,0.2])
     sustainedTestStatistic, sustainedpVal = sound_response_any_stimulus(bandEventOnsetTimes, bandSpikeTimestamps, trialsEachBaseCond, [0.2,1.0], [-1.0,0.2])
     pVal *= len(numSec) #correction for multiple comparisons
     onsetpVal *= len(numSec)
     sustainedpVal *= len(numSec)
 soundResponseTestStatistic[indRow] = testStatistic
 soundResponsePVal[indRow] = pVal
 onsetSoundResponseTestStatistic[indRow] = onsetTestStatistic
 onsetSoundResponsePVal[indRow] = onsetpVal
 sustainedSoundResponseTestStatistic[indRow] = sustainedTestStatistic
 sustainedSoundResponsePVal[indRow] = sustainedpVal
 
 # --- Determine frequency tuning of cells ---
Example #41
0
    def plot_two_axis_sorted_raster(self, session, tetrode, experiment=-1, site=-1, firstSort='currentFreq', secondSort='currentIntensity', cluster = None, replace=0, timeRange = [-0.5, 1], ms = 1, firstLabels=None, secondLabels=None, yLabel=None, plotTitle=None):
        '''
        Plot rasters sorted by 2 arrays.
        By default, sorts by frequency and intensity to copy functionality of old plot_sorted_tuning_raster method.
        However, can specify different arrays to sort by.
        '''
        sessionObj = self.get_session_obj(session, experiment, site)
        sessionDir = sessionObj.ephys_dir()
        behavFile = sessionObj.behav_filename()
        bdata = self.loader.get_session_behavior(behavFile)
        plotTitle = sessionDir
        eventData = self.loader.get_session_events(sessionDir)
        spikeData = self.loader.get_session_spikes(sessionDir, tetrode, cluster)
        eventOnsetTimes = self.loader.get_event_onset_times(eventData)
        spikeTimestamps=spikeData.timestamps
        firstSortArray = bdata[firstSort]
        secondSortArray = bdata[secondSort]

        if not firstLabels:
            possibleFirst = np.unique(firstSortArray)
            if firstSort == 'currentFreq':
                firstLabels = ['{0:.1f}'.format(freq/1000.0) for freq in possibleFirst]
            else:
                firstLabels = ['{}'.format(val) for val in possibleFirst]

        if not secondLabels:
            possibleSecond = np.unique(secondSortArray)
            if secondSort == 'currentIntensity':
                secondLabels = ['{:.0f} dB'.format(intensity) for intensity in possibleSecond]
            else:
                secondLabels = ['{}'.format(val) for val in possibleSecond]

        xLabel="Time from sound onset (sec)"

        if replace:
            fig = plt.gcf()
            plt.clf()
        else:
            fig = plt.figure()

        # dataplotter.two_axis_sorted_raster(spikeTimestamps,
        #                                    eventOnsetTimes,
        #                                    firstSortArray,
        #                                    secondSortArray,
        #                                    firstLabels,
        #                                    secondLabels,
        #                                    xLabel,
        #                                    yLabel,
        #                                    plotTitle,
        #                                    flipFirstAxis=False,
        #                                    flipSecondAxis=True,
        #                                    timeRange=timeRange,
        #                                    ms=ms)

        # We flip the second axis so that high intensities appear at the top
        flipFirstAxis=False
        flipSecondAxis=True

        if not firstSortLabels:
            firstSortLabels = []
        if not secondSortLabels:
            secondSortLabels = []
        if not xLabel:
            xlabel = ''
        if not yLabel:
            ylabel = ''
        if not plotTitle:
            plotTitle = ''
        #Set first and second possible val arrays and invert them if desired for plotting
        firstPossibleVals = np.unique(firstSortArray)
        secondPossibleVals = np.unique(secondSortArray)
        if flipFirstAxis:
            firstPossibleVals = firstPossibleVals[::-1]
            firstSortLabels = firstSortLabels[::-1]
        if flipSecondAxis:
            secondPossibleVals = secondPossibleVals[::-1]
            secondSortLabels = secondSortLabels[::-1]
        #Find the trials that correspond to each pair of sorting values
        trialsEachCond = behavioranalysis.find_trials_each_combination(
            firstSortArray, firstPossibleVals, secondSortArray, secondPossibleVals)
        #Calculate the spike times relative to event onset times
        spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
            spikeTimestamps, eventOnsetTimes, timeRange)
        #Grab the current figure and clear it for plotting
        fig = plt.gcf()
        plt.clf()
        plt.suptitle(plotTitle)

        #Make a new plot for each unique value of the second sort array, and then plot a raster on that plot sorted by this second array
        for ind, secondArrayVal in enumerate(secondPossibleVals):
            if ind == 0:
                fig.add_subplot(len(secondPossibleVals), 1, ind + 1)
                plt.title(plotTitle)
            else:
                fig.add_subplot(
                    len(secondPossibleVals),
                    1,
                    ind + 1,
                    sharex=fig.axes[0],
                    sharey=fig.axes[0])
            trialsThisSecondVal = trialsEachCond[:, :, ind]
            pRaster, hcond, zline = extraplots.raster_plot(
                spikeTimesFromEventOnset,
                indexLimitsEachTrial,
                timeRange,
                trialsEachCond=trialsThisSecondVal,
                labels=firstSortLabels)
            plt.setp(pRaster, ms=ms)
            if secondSortLabels:
                # plt.ylabel(secondSortLabels[ind])
                plt.title(secondSortLabels[ind])
            if ind == len(secondPossibleVals) - 1:
                plt.xlabel(xLabel)
            if yLabel:
                plt.ylabel(yLabel)

        plt.show()
Example #42
0
def plot_one_int_bandwidth_summary(cell, bandIndex, intIndex=-1):
    plt.clf()
    gs = gridspec.GridSpec(1, 3)
    gs.update(left=0.15, right=0.85, top=0.90, wspace=0.2, hspace=0.5)

    tetrode = int(cell['tetrode'])
    cluster = int(cell['cluster'])

    #create cell object for loading data
    cellObj = ephyscore.Cell(cell)

    #load bandwidth data
    bandEphysData, bandBData = cellObj.load_by_index(bandIndex)
    bandEventOnsetTimes = ephysanalysis.get_sound_onset_times(
        bandEphysData, 'bandwidth')
    bandSpikeTimestamps = bandEphysData['spikeTimes']

    bandEachTrial = bandBData['currentBand']
    secondSort = bandBData['currentAmp']
    numBands = np.unique(bandEachTrial)
    numSec = np.unique(secondSort)

    timeRange = [-0.2, 1.5]

    #plot raster of the high amp bandwidth trials
    plt.subplot(gs[0, 0])
    colours = np.tile(['#5c3566', '#ad7fa8'], len(numBands) / 2 + 1)
    trialsEachCond = behavioranalysis.find_trials_each_combination(
        bandEachTrial, numBands, secondSort, numSec)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        bandSpikeTimestamps, bandEventOnsetTimes, timeRange)

    trialsOneAmp = trialsEachCond[:, :, intIndex]
    firstSortLabels = ['{}'.format(band) for band in numBands]
    pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,
                                                   indexLimitsEachTrial,
                                                   timeRange,
                                                   trialsEachCond=trialsOneAmp,
                                                   labels=firstSortLabels,
                                                   colorEachCond=colours)
    plt.setp(pRaster, ms=3)
    plt.ylabel('Bandwidth (octaves)')
    plt.xlabel('Time from sound onset (s)')
    #plot bandwidth tuning curves
    plt.subplot(gs[0, 2])
    sustainedTimeRange = [0.2, 1.0]
    tuningDict = ephysanalysis.calculate_tuning_curve_inputs(
        bandSpikeTimestamps,
        bandEventOnsetTimes,
        secondSort,
        bandEachTrial,
        sustainedTimeRange,
        info='plotting')
    plot_tuning_curve(tuningDict['responseArray'][intIndex, :].reshape([7, 1]),
                      tuningDict['errorArray'][intIndex, :].reshape([7, 1]),
                      numBands,
                      tuningDict['baselineSpikeRate'],
                      linecolours=['#5c3566'],
                      errorcolours=['#ad7fa8'])
    plt.title('Average sustained response (200-1000 ms)', fontsize=10)

    plt.subplot(gs[0, 1])
    onsetTimeRange = [0.0, 0.05]
    tuningDict2 = ephysanalysis.calculate_tuning_curve_inputs(
        bandSpikeTimestamps,
        bandEventOnsetTimes,
        secondSort,
        bandEachTrial,
        onsetTimeRange,
        info='plotting')
    plot_tuning_curve(tuningDict2['responseArray'][intIndex, :].reshape([7,
                                                                         1]),
                      tuningDict2['errorArray'][intIndex, :].reshape([7, 1]),
                      numBands,
                      tuningDict2['baselineSpikeRate'],
                      linecolours=['#5c3566'],
                      errorcolours=['#ad7fa8'])
    plt.title('Average onset response (0-50 ms)', fontsize=10)

    #save report
    charfreq = str(np.unique(bandBData['charFreq'])[0] / 1000)
    modrate = str(np.unique(bandBData['modRate'])[0])
    plt.suptitle(
        '{0}, {1}, {2}um, Tetrode {3}, Cluster {4}, {5}kHz, {6}Hz modulation'.
        format(cell['subject'], cell['date'], int(cell['depth']), tetrode,
               cluster, charfreq, modrate))

    fig_path = '/home/jarauser/Pictures/cell reports'
    fig_name = 'bandwidth_high_amp_response_{0}_{1}_{2}um_TT{3}Cluster{4}.png'.format(
        cell['subject'], cell['date'], int(cell['depth']), tetrode, cluster)
    full_fig_path = os.path.join(fig_path, fig_name)
    fig = plt.gcf()
    fig.set_size_inches(14, 3)
    fig.savefig(full_fig_path, format='png', bbox_inches='tight')
        bandSpikeTimesFromEventOnset, trialIndexForEachSpike, bandIndexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
            bandSpikeTimestamps, bandEventOnsetTimes, fullTimeRange)

        onsetSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
            bandSpikeTimesFromEventOnset, bandIndexLimitsEachTrial,
            onsetTimeRange)
        sustainedSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
            bandSpikeTimesFromEventOnset, bandIndexLimitsEachTrial,
            sustainedTimeRange)

        bandEachTrial = bandBData['currentBand']
        ampEachTrial = bandBData['currentAmp']
        numBands = np.unique(bandEachTrial)
        numAmps = np.unique(ampEachTrial)

        bandTrialsEachCond = behavioranalysis.find_trials_each_combination(
            bandEachTrial, numBands, ampEachTrial, numAmps)

        trialsHighAmp = bandTrialsEachCond[:, :,
                                           -1]  #only using high amplitude trials (-1 in list of amps)
        # find high bandwidth trials
        trialsHighBands = None
        for band in highBands:
            if trialsHighBands is None:
                trialsHighBands = trialsHighAmp[:, band]
            else:
                trialsHighBands = trialsHighBands | trialsHighAmp[:, band]

        # Average firing rate for high amplitude trials
        if onsetSpikeCountMat.shape[0] == len(trialsHighBands) + 1:
            onsetSpikeCountMat = onsetSpikeCountMat[:-1, :]
        highBandOnsetSpikeCounts = onsetSpikeCountMat[trialsHighBands]
Example #44
0
def two_axis_heatmap(spikeTimestamps,
                     eventOnsetTimes,
                     firstSortArray, #Should be intensity in F/I TC (Y axis)
                     secondSortArray, #Should be frequency in F/I TC (X Axis)
                     firstPossibleVals=None,
                     secondPossibleVals=None,
                     firstSortLabels=None,
                     secondSortLabels=None,
                     xlabel=None,
                     ylabel=None,
                     plotTitle=None,
                     flipFirstAxis=True, #Useful for making the highest intensity plot on top
                     flipSecondAxis=False,
                     timeRange=[0, 0.1],
                     cmap='Blues'):
    '''
    This function takes two arrays and uses them to sort spikes into trials by combinaion,
    and then plots the average number of spikes after the stim in heatmap form.
    The first sort array should be the intensity in a F/I tuning curve,
    and the second sort array should be the frequency.

    Args:
        spikeTimestamps (array): An array of spike timestamps to plot
        eventOnsetTimes (array): An array of event onset times.
                                 Spikes will be plotted in raster form relative to these times
        firstSortArray (array): An array of parameter values for each trial.
                                Must be the same length as eventOnsetTimes.
        secondSortArray (array): Another array of paramenter values the same length as eventOnsetTimes.
                                 Better if this array has less possible values.
        firstSortLabels (list): A list containing strings to use as labels for the first sort array.
                                Must contain one item for each possible value of the first sort array.
        secondSortLabels (list): Same idea as above, must contain one element for each possible value of the second sort array.
        xLabel (str): A string to use for the x label of the bottom raster plot
        flipFirstAxis (bool): Whether to flip the first sorting axis.
                              Will result in trials with high values for the first sort array appearing on the bottom of each raster.
        flipSecondAxis (bool): Will result in trials with high values for the second sorting array appearing in the top raster plot
        timeRange (list): A list containing the range of times relative to the stimulus onset over which the spike average will be computed
    '''
    if not firstSortLabels:
        firstSortLabels = []
    if not secondSortLabels:
        secondSortLabels = []
    if not xlabel:
        xlabel = ''
    if not ylabel:
        ylabel = ''
    if not plotTitle:
        plotTitle = ''
    if not firstPossibleVals:
        firstPossibleVals = np.unique(firstSortArray)
    if not secondPossibleVals:
        secondPossibleVals = np.unique(secondSortArray)
    if firstSortLabels == None:
        firstSortLabels = []
    if secondSortLabels == None:
        secondSortLabels = []
    if xlabel == None:
        xlabel = ''
    if ylabel == None:
        ylabel = ''
    cbarLabel = 'Avg spikes in time range: {}'.format(timeRange)
    if flipFirstAxis:
        firstPossibleVals = firstPossibleVals[::-1]
        firstSortLabels = firstSortLabels[::-1]
    if flipSecondAxis:
        secondPossibleVals = secondPossibleVals[::-1]
        secondSortLabels = secondSortLabels[::-1]
    #Find trials each combination
    trialsEachCond = behavioranalysis.find_trials_each_combination(
        firstSortArray, firstPossibleVals, secondSortArray, secondPossibleVals)
    #Make an aray of the average number of spikes in the timerange after the stim for each condition
    spikeArray = avg_spikes_in_event_locked_timerange_each_cond(
        spikeTimestamps, trialsEachCond, eventOnsetTimes, timeRange)
    #Plot the array as a heatmap

    ax, cax, cbar = plot_array_as_heatmap(spikeArray,
                                          xlabel=xlabel,
                                          ylabel=ylabel,
                                          xtickLabels=secondSortLabels,
                                          ytickLabels=firstSortLabels,
                                          cbarLabel=cbarLabel,
                                          cmap=cmap)
    return ax, cax, cbar
Example #45
0
def plot_bandwidth_report(mouse, date, site, siteName):
    sessions = site.get_session_ephys_filenames()
    behavFilename = site.get_session_behav_filenames()
    ei = ephysinterface.EphysInterface(mouse, date, '', 'bandwidth_am')
    bdata = ei.loader.get_session_behavior(behavFilename[3][-4:-3])
    charfreq = str(np.unique(bdata['charFreq'])[0]/1000)
    modrate = str(np.unique(bdata['modRate'])[0])
    ei2 = ephysinterface.EphysInterface(mouse, date, '', 'am_tuning_curve')
    bdata2 = ei2.loader.get_session_behavior(behavFilename[1][-4:-3])  
    bdata3 = ei2.loader.get_session_behavior(behavFilename[2][-4:-3])  
    currentFreq = bdata2['currentFreq']
    currentBand = bdata['currentBand']
    currentAmp = bdata['currentAmp']
    currentInt = bdata2['currentIntensity']
    currentRate = bdata3['currentFreq']
      
    #for tetrode in site.tetrodes:
    for tetrode in [2]:
        oneTT = sitefuncs.cluster_site(site, siteName, tetrode)
        dataSpikes = ei.loader.get_session_spikes(sessions[3], tetrode)
        dataSpikes2 = ei2.loader.get_session_spikes(sessions[1], tetrode)
        #clusters = np.unique(dataSpikes.clusters)
        clusters = [8]
        for cluster in clusters:
            plt.clf()
            
            # -- plot bandwidth rasters --
            eventData = ei.loader.get_session_events(sessions[3])
            spikeData = ei.loader.get_session_spikes(sessions[3], tetrode, cluster=cluster)
            eventOnsetTimes = ei.loader.get_event_onset_times(eventData)
            spikeTimestamps = spikeData.timestamps
            timeRange = [-0.2, 1.5]
            
            numBands = np.unique(currentBand)
            numAmps = np.unique(currentAmp)
            
            firstSortLabels = ['{}'.format(band) for band in np.unique(currentBand)]
            secondSortLabels = ['Amplitude: {}'.format(amp) for amp in np.unique(currentAmp)]
            
            trialsEachCond = behavioranalysis.find_trials_each_combination(currentBand, 
                                                                           numBands, 
                                                                           currentAmp, 
                                                                           numAmps)
            spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                                                                                                        spikeTimestamps, 
                                                                                                        eventOnsetTimes,
                                                                                                        timeRange)
            for ind, secondArrayVal in enumerate(numAmps):
                plt.subplot2grid((12, 15), (5*ind, 0), rowspan = 4, colspan = 7)
                trialsThisSecondVal = trialsEachCond[:, :, ind]
                pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,
                                                                indexLimitsEachTrial,
                                                                timeRange,
                                                                trialsEachCond=trialsThisSecondVal,
                                                                labels=firstSortLabels)
                plt.setp(pRaster, ms=4)
                
                plt.title(secondSortLabels[ind])
                plt.ylabel('bandwidth (octaves)')
                if ind == len(np.unique(currentAmp)) - 1:
                    plt.xlabel("Time from sound onset (sec)")
            
            # -- plot Yashar plots for bandwidth data --
            plt.subplot2grid((12,15), (10,0), rowspan = 2, colspan = 3)
            band_select_plot(spikeTimestamps, eventOnsetTimes, currentAmp, currentBand, [0.0, 1.0], title='bandwidth selectivity')
            plt.subplot2grid((12,15), (10,3), rowspan = 2, colspan = 3)
            band_select_plot(spikeTimestamps, eventOnsetTimes, currentAmp, currentBand, [0.2, 1.0], title='first 200ms excluded')
            
            # -- plot frequency tuning heat map -- 
            plt.subplot2grid((12, 15), (5, 7), rowspan = 4, colspan = 4)
            
            eventData = ei2.loader.get_session_events(sessions[1])
            spikeData = ei2.loader.get_session_spikes(sessions[1], tetrode, cluster=cluster)
            eventOnsetTimes = ei2.loader.get_event_onset_times(eventData)
            spikeTimestamps = spikeData.timestamps
            
            dataplotter.two_axis_heatmap(spikeTimestamps=spikeTimestamps,
                                            eventOnsetTimes=eventOnsetTimes,
                                            firstSortArray=currentInt,
                                            secondSortArray=currentFreq,
                                            firstSortLabels=["%.1f" % inten for inten in np.unique(currentInt)],
                                            secondSortLabels=["%.1f" % freq for freq in np.unique(currentFreq)/1000.0],
                                            xlabel='Frequency (kHz)',
                                            ylabel='Intensity (dB SPL)',
                                            plotTitle='Frequency Tuning Curve',
                                            flipFirstAxis=True,
                                            flipSecondAxis=False,
                                            timeRange=[0, 0.1])
            plt.ylabel('Intensity (dB SPL)')
            plt.xlabel('Frequency (kHz)')
            plt.title('Frequency Tuning Curve')
            
            # -- plot frequency tuning raster --
            plt.subplot2grid((12,15), (0, 7), rowspan = 4, colspan = 4)
            freqLabels = ["%.1f" % freq for freq in np.unique(currentFreq)/1000.0]
            dataplotter.plot_raster(spikeTimestamps, eventOnsetTimes, sortArray=currentFreq, timeRange=[-0.1, 0.5], labels=freqLabels)
            plt.xlabel('Time from sound onset (sec)')
            plt.ylabel('Frequency (kHz)')
            plt.title('Frequency Tuning Raster')
            
            # -- plot AM PSTH --
            eventData = ei2.loader.get_session_events(sessions[2])
            spikeData = ei2.loader.get_session_spikes(sessions[2], tetrode, cluster=cluster)
            eventOnsetTimes = ei2.loader.get_event_onset_times(eventData)
            spikeTimestamps = spikeData.timestamps
            timeRange = [-0.2, 1.5]
            
            spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                                                                                                        spikeTimestamps, 
                                                                                                        eventOnsetTimes,
                                                                                                        timeRange)
            colourList = ['b', 'g', 'y', 'orange', 'r']
            numRates = np.unique(currentRate)
            trialsEachCond = behavioranalysis.find_trials_each_type(currentRate, 
                                                                           numRates)
            binEdges = np.around(np.arange(-0.2, 0.85, 0.05), decimals=2)
            spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges)
            plt.subplot2grid((12,15), (5, 11), rowspan = 4, colspan = 4)
            pPSTH = extraplots.plot_psth(spikeCountMat/0.05, 1, binEdges[:-1], trialsEachCond, colorEachCond=colourList)
            plt.setp(pPSTH)
            plt.xlabel('Time from sound onset (sec)')
            plt.ylabel('Firing rate (Hz)')
            plt.title('AM PSTH')
            
            # -- plot AM raster --
            plt.subplot2grid((12,15), (0, 11), rowspan = 4, colspan = 4)
            rateLabels = ["%.1f" % rate for rate in np.unique(currentRate)]
            dataplotter.plot_raster(spikeTimestamps, eventOnsetTimes, sortArray=currentRate, timeRange=[-0.2, 0.8], labels=rateLabels, colorEachCond=colourList)
            plt.xlabel('Time from sound onset (sec)')
            plt.ylabel('Modulation Rate (Hz)')
            plt.title('AM Raster')
            
            # -- show cluster analysis --
            tsThisCluster = oneTT.timestamps[oneTT.clusters==cluster]
            wavesThisCluster = oneTT.samples[oneTT.clusters==cluster]
            
            # -- Plot ISI histogram --
            plt.subplot2grid((12,15), (10,6), rowspan=2, colspan=3)
            spikesorting.plot_isi_loghist(tsThisCluster)
            plt.ylabel('c%d'%cluster,rotation=0,va='center',ha='center')
            plt.xlabel('')

            # -- Plot waveforms --
            plt.subplot2grid((12,15), (10,9), rowspan=2, colspan=3)
            spikesorting.plot_waveforms(wavesThisCluster)

            # -- Plot projections --
            plt.subplot2grid((12,15), (10,12), rowspan=1, colspan=3)
            spikesorting.plot_projections(wavesThisCluster)

            # -- Plot events in time --
            plt.subplot2grid((12,15), (11,12), rowspan=1, colspan=3)
            spikesorting.plot_events_in_time(tsThisCluster)

            plt.subplots_adjust(wspace = 1.5)
            plt.suptitle('{0}, {1}, {2}, Tetrode {3}, Cluster {4}, {5}kHz, {6}Hz modulation'.format(mouse, date, siteName, tetrode, cluster, charfreq, modrate))
            fig_path = oneTT.clustersDir
            fig_name = 'TT{0}Cluster{1}.png'.format(tetrode, cluster)
            full_fig_path = os.path.join(fig_path, fig_name)
            fig = plt.gcf()
            fig.set_size_inches(24, 12)
            fig.savefig(full_fig_path, format = 'png', bbox_inches='tight')
Example #46
0
def two_axis_sorted_raster(spikeTimestamps,
                           eventOnsetTimes,
                           firstSortArray,
                           secondSortArray,
                           firstSortLabels=None,
                           secondSortLabels=None,
                           xLabel=None,
                           yLabel=None,
                           plotTitle=None,
                           flipFirstAxis=False,
                           flipSecondAxis=True, #Useful for making the highest intensity plot on top
                           timeRange=[-0.5, 1],
                           ms=4):
    '''
    This function takes two arrays and uses them to sort spikes into trials by combinaion, and then plots the spikes in raster form.

    The first sort array will be used to sort each raster plot, and there will be a separate raster plot for each possible value of the
    second sort array. This method was developed for plotting frequency-intensity tuning curve data in raster form, in which case the
    frequency each trial is passed as the first sort array, and the intensity each trial is passed as the second sort array.

    Args:
        spikeTimestamps (array): An array of spike timestamps to plot
        eventOnsetTimes (array): An array of event onset times. Spikes will be plotted in raster form relative to these times
        firstSortArray (array): An array of parameter values for each trial. Must be the same length as eventOnsetTimes.
        secondSortArray (array): Another array of paramenter values the same length as eventOnsetTimes.
                                 Better if this array has less possible values.
        firstSortLabels (list): A list containing strings to use as labels for the first sort array.
                                Must contain one item for each possible value of the first sort array.
        secondSortLabels (list): Same idea as above, must contain one element for each possible value of the second sort array.
        xLabel (str): A string to use for the x label of the bottom raster plot
        flipFirstAxis (bool): Whether to flip the first sorting axis.
                              Will result in trials with high values for the first sort array appearing on the bottom of each raster.
        flipSecondAxis (bool): Will result in trials with high values for the second sorting array appearing in the top raster plot
        timeRange (list): A list containing the range of times relative to the event onset times that will be plotted
        ms (int): The marker size to use for the raster plots
    '''
    if not firstSortLabels:
        firstSortLabels = []
    if not secondSortLabels:
        secondSortLabels = []
    if not xLabel:
        xlabel = ''
    if not yLabel:
        ylabel = ''
    if not plotTitle:
        plotTitle = ''
    #Set first and second possible val arrays and invert them if desired for plotting
    firstPossibleVals = np.unique(firstSortArray)
    secondPossibleVals = np.unique(secondSortArray)
    if flipFirstAxis:
        firstPossibleVals = firstPossibleVals[::-1]
        firstSortLabels = firstSortLabels[::-1]
    if flipSecondAxis:
        secondPossibleVals = secondPossibleVals[::-1]
        secondSortLabels = secondSortLabels[::-1]
    #Find the trials that correspond to each pair of sorting values
    trialsEachCond = behavioranalysis.find_trials_each_combination(
        firstSortArray, firstPossibleVals, secondSortArray, secondPossibleVals)
    #Calculate the spike times relative to event onset times
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimestamps, eventOnsetTimes, timeRange)
    #Grab the current figure and clear it for plotting
    fig = plt.gcf()
    plt.clf()
    #Make a new plot for each unique value of the second sort array, and then plot a raster on that plot sorted by this second array
    for ind, secondArrayVal in enumerate(secondPossibleVals):
        if ind == 0:
            fig.add_subplot(len(secondPossibleVals), 1, ind + 1)
            plt.title(plotTitle)
        else:
            fig.add_subplot(
                len(secondPossibleVals),
                1,
                ind + 1,
                sharex=fig.axes[0],
                sharey=fig.axes[0])
        trialsThisSecondVal = trialsEachCond[:, :, ind]
        pRaster, hcond, zline = extraplots.raster_plot(
            spikeTimesFromEventOnset,
            indexLimitsEachTrial,
            timeRange,
            trialsEachCond=trialsThisSecondVal,
            labels=firstSortLabels)
        plt.setp(pRaster, ms=ms)
        if secondSortLabels:
            plt.ylabel(secondSortLabels[ind])
        if ind == len(secondPossibleVals) - 1:
            plt.xlabel(xLabel)
Example #47
0
def inactivation_base_stats(db, filename=''):
    laserTestStatistic = np.empty(len(db))
    laserPVal = np.empty(len(db))

    soundResponseTestStatistic = np.empty(len(db))
    soundResponsePVal = np.empty(len(db))
    onsetSoundResponseTestStatistic = np.empty(len(db))
    onsetSoundResponsePVal = np.empty(len(db))
    sustainedSoundResponseTestStatistic = np.empty(len(db))
    sustainedSoundResponsePVal = np.empty(len(db))

    gaussFit = []
    tuningTimeRange = []
    Rsquared = np.empty(len(db))
    prefFreq = np.empty(len(db))
    octavesFromPrefFreq = np.empty(len(db))
    bestBandSession = np.empty(len(db))

    for indRow, (dbIndex, dbRow) in enumerate(db.iterrows()):
        cellObj = ephyscore.Cell(dbRow)
        print "Now processing", dbRow['subject'], dbRow['date'], dbRow[
            'depth'], dbRow['tetrode'], dbRow['cluster']

        # --- Determine laser responsiveness of each cell (using first 100 ms of noise-in-laser trials) ---
        try:
            laserEphysData, noBehav = cellObj.load('lasernoisebursts')
        except IndexError:
            print "No laser pulse session for this cell"
            testStatistic = np.nan
            pVal = np.nan
            changeFR = np.nan
        else:
            testStatistic, pVal, changeFR = funcs.laser_response(
                laserEphysData,
                baseRange=[-0.3, -0.2],
                responseRange=[0.0, 0.1])
        laserTestStatistic[indRow] = testStatistic
        laserPVal[indRow] = pVal

        # --- Determine sound responsiveness during bandwidth sessions and calculate baseline firing rates with and without laser---
        #done in a kind of stupid way because regular and control sessions are handled the same way
        if any(session in dbRow['sessionType']
               for session in ['laserBandwidth', 'laserBandwidthControl']):
            if 'laserBandwidth' in dbRow['sessionType']:
                bandEphysData, bandBehavData = cellObj.load('laserBandwidth')
                behavSession = 'laserBandwidth'
                db.at[dbIndex, 'controlSession'] = 0
            elif 'laserBandwidthControl' in dbRow['sessionType']:
                bandEphysData, bandBehavData = cellObj.load(
                    'laserBandwidthControl')
                behavSession = 'laserBandwidthControl'
                db.at[dbIndex, 'controlSession'] = 1
            bandEventOnsetTimes = funcs.get_sound_onset_times(
                bandEphysData, 'bandwidth')
            bandSpikeTimestamps = bandEphysData['spikeTimes']
            bandEachTrial = bandBehavData['currentBand']
            secondSort = bandBehavData['laserTrial']
            numBands = np.unique(bandEachTrial)
            numSec = np.unique(secondSort)

            trialsEachComb = behavioranalysis.find_trials_each_combination(
                bandEachTrial, numBands, secondSort, numSec)
            trialsEachBaseCond = trialsEachComb[:, :,
                                                0]  #using no laser trials to determine sound responsiveness
            testStatistic, pVal = funcs.sound_response_any_stimulus(
                bandEventOnsetTimes, bandSpikeTimestamps, trialsEachBaseCond,
                [0.0, 1.0], [-1.2, -0.2])
            onsetTestStatistic, onsetpVal = funcs.sound_response_any_stimulus(
                bandEventOnsetTimes, bandSpikeTimestamps, trialsEachBaseCond,
                [0.0, 0.05], [-0.25, 0.2])
            sustainedTestStatistic, sustainedpVal = funcs.sound_response_any_stimulus(
                bandEventOnsetTimes, bandSpikeTimestamps, trialsEachBaseCond,
                [0.2, 1.0], [-1.0, 0.2])
            pVal *= len(numBands)  #correction for multiple comparisons
            onsetpVal *= len(numBands)
            sustainedpVal *= len(numBands)
            #pdb.set_trace()

            #find baselines with and without laser
            baselineRange = [-0.05, 0.0]
            baselineRates, baselineSEMs = funcs.inactivated_cells_baselines(
                bandSpikeTimestamps, bandEventOnsetTimes, secondSort,
                baselineRange)
            db.at[dbIndex, 'baselineFRnoLaser'] = baselineRates[0]
            db.at[dbIndex, 'baselineFRLaser'] = baselineRates[1]
            db.at[dbIndex, 'baselineFRnoLaserSEM'] = baselineSEMs[0]
            db.at[dbIndex, 'baselineFRLaserSEM'] = baselineSEMs[1]
            db.at[dbIndex,
                  'baselineChangeFR'] = baselineRates[1] - baselineRates[0]
        else:
            print "No bandwidth session for this cell"
            testStatistic = np.nan
            pVal = np.nan
            onsetTestStatistic = np.nan
            onsetpVal = np.nan
            sustainedTestStatistic = np.nan
            sustainedpVal = np.nan
            #pdb.set_trace()

        soundResponseTestStatistic[indRow] = testStatistic
        soundResponsePVal[indRow] = pVal
        onsetSoundResponseTestStatistic[indRow] = onsetTestStatistic
        onsetSoundResponsePVal[indRow] = onsetpVal
        sustainedSoundResponseTestStatistic[indRow] = sustainedTestStatistic
        sustainedSoundResponsePVal[indRow] = sustainedpVal

        # --- Determine frequency tuning of cells ---
        try:
            tuningEphysData, tuningBehavData = cellObj.load('tuningCurve')
        except IndexError:
            print "No tuning session for this cell"
            freqFit = np.full(4, np.nan)
            thisRsquared = np.nan
            bestFreq = np.nan
            tuningWindow = np.full(2, np.nan)
            octavesFromBest = np.nan
            bandIndex = np.nan
        else:
            tuningEventOnsetTimes = funcs.get_sound_onset_times(
                tuningEphysData, 'tuningCurve')
            tuningSpikeTimestamps = tuningEphysData['spikeTimes']
            freqEachTrial = tuningBehavData['currentFreq']
            intensityEachTrial = tuningBehavData['currentIntensity']
            numFreqs = np.unique(freqEachTrial)
            numIntensities = np.unique(intensityEachTrial)
            timeRange = [-0.2, 0.2]
            spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                tuningSpikeTimestamps, tuningEventOnsetTimes, timeRange)
            trialsEachType = behavioranalysis.find_trials_each_type(
                intensityEachTrial, numIntensities)
            trialsHighInt = trialsEachType[:, -1]
            trialsEachComb = behavioranalysis.find_trials_each_combination(
                freqEachTrial, numFreqs, intensityEachTrial, numIntensities)
            trialsEachFreqHighInt = trialsEachComb[:, :, -1]
            tuningWindow = funcs.best_window_freq_tuning(
                spikeTimesFromEventOnset, indexLimitsEachTrial,
                trialsEachFreqHighInt)
            tuningWindow = np.array(tuningWindow)
            spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
                spikeTimesFromEventOnset, indexLimitsEachTrial, tuningWindow)
            tuningSpikeRates = (spikeCountMat[trialsHighInt].flatten()) / (
                tuningWindow[1] - tuningWindow[0])
            freqsThisIntensity = freqEachTrial[trialsHighInt]
            freqFit, thisRsquared = funcs.gaussian_tuning_fit(
                np.log2(freqsThisIntensity), tuningSpikeRates)
            if freqFit is not None:
                bestFreq = 2**freqFit[0]
                bandIndex, octavesFromBest = funcs.best_index(
                    cellObj, bestFreq, behavSession)
            else:
                freqFit = np.full(4, np.nan)
                bestFreq = np.nan
                bandIndex = np.nan
                octavesFromBest = np.nan
        gaussFit.append(freqFit)
        tuningTimeRange.append(tuningWindow)
        Rsquared[indRow] = thisRsquared
        prefFreq[indRow] = bestFreq
        octavesFromPrefFreq[indRow] = octavesFromBest
        bestBandSession[indRow] = bandIndex

    db['laserPVal'] = laserPVal
    db['laserUStat'] = laserTestStatistic

    db['soundResponseUStat'] = soundResponseTestStatistic
    db['soundResponsePVal'] = soundResponsePVal
    db['onsetSoundResponseUStat'] = onsetSoundResponseTestStatistic
    db['onsetSoundResponsePVal'] = onsetSoundResponsePVal
    db['sustainedSoundResponseUStat'] = sustainedSoundResponseTestStatistic
    db['sustainedSoundResponsePVal'] = sustainedSoundResponsePVal

    db['gaussFit'] = gaussFit
    db['tuningTimeRange'] = tuningTimeRange
    db['tuningFitR2'] = Rsquared
    db['prefFreq'] = prefFreq
    db['octavesFromPrefFreq'] = octavesFromPrefFreq
    db['bestBandSession'] = bestBandSession

    if len(filename) != 0:
        celldatabase.save_hdf(db, filename)
        print filename + " saved"

    return db
testspikes = spikeTimesFromEventOnset[np.in1d(trialIndexForEachSpike, trialsThisCombo)]
freq4inds = trialIndexForEachSpike[np.in1d(trialIndexForEachSpike, trialsThisCombo)]










#A potentially flawed idea that I might come back to. It is not as helpful with this idea as I thought it would be
#Copies of two functions from dataplotter that should help with the analysis of TCs

trialsEachCond = behavioranalysis.find_trials_each_combination(currentIntensity, possibleIntensity, currentFreq, possibleFreq)
conditionMatShape = np.shape(trialsEachCond)



timeRange = [0, 0.1]
spikeTimestamps = spikeData.timestamps
eventOnsetTimes = loader.get_event_onset_times(eventData)

if len(eventOnsetTimes) != np.shape(trialsEachCond)[0]:
    eventOnsetTimes = eventOnsetTimes[:-1]

spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
    spikeTimestamps, eventOnsetTimes, timeRange)

numSpikesInTimeRangeEachTrial = np.squeeze(np.diff(indexLimitsEachTrial,
#ex0624.plot_sorted_tuning_raster('15-31-48', 6, 'a', ms=4)

import numpy as np
from jaratoolbox import extraplots
from jaratoolbox import behavioranalysis
from jaratoolbox import spikesanalysis
import matplotlib
import matplotlib.pyplot as plt

bdata = ex0624.get_session_behav_data('15-31-48','a')
freqEachTrial = bdata['currentFreq']
intensityEachTrial = bdata['currentIntensity']
possibleFreq = np.unique(freqEachTrial)
possibleIntensity = np.unique(intensityEachTrial)
trialsEachCond = behavioranalysis.find_trials_each_combination(intensityEachTrial, possibleIntensity, freqEachTrial, possibleFreq)
trialsEachCondFreq = behavioranalysis.find_trials_each_type(freqEachTrial, possibleFreq)
trialsEachCondInt = behavioranalysis.find_trials_each_type(intensityEachTrial, possibleIntensity)

spikeData = ex0624.get_session_spike_data_one_tetrode('15-31-48', 6)
eventData = ex0624.get_session_event_data('15-31-48')
eventOnsetTimes = ex0624.get_event_onset_times(eventData)

eventOnsetTimes = eventOnsetTimes[:-1] #FIXME: WHY IS THIS NECESSARY????!!

spikeTimestamps=spikeData.timestamps


timeRange = [0, 0.1]

spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(spikeTimestamps,
Example #50
0
        tuningEventOnsetTimes, minEventOnsetDiff=0.2)
    tuningSpikeTimestamps = tuningEphysData['spikeTimes']

    freqEachTrial = tuningBData['currentFreq']
    numFreqs = np.unique(freqEachTrial)
    intEachTrial = tuningBData['currentIntensity']

    rasterTimeRange = [-0.3, 0.5]
    tuningTimeRange = dbRow['tuningTimeRange']
    baselineTimeRange = [-0.5, -0.1]
    fullRange = [
        min(rasterTimeRange + tuningTimeRange + baselineTimeRange),
        max(rasterTimeRange + tuningTimeRange + baselineTimeRange)
    ]

    trialsEachCond = behavioranalysis.find_trials_each_combination(
        freqEachTrial, numFreqs, intEachTrial, np.unique(intEachTrial))
    trialsHighInt = trialsEachCond[:, :,
                                   -1]  #only interested in loudest tones as they correspond to high amp bandwidth trials

    # --- computes inputs to frequency tuning curve ---
    tuningSpikeTimesFromEventOnset, trialIndexForEachSpike, tuningIndexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        tuningSpikeTimestamps, tuningEventOnsetTimes, fullRange)

    tuningSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        tuningSpikeTimesFromEventOnset, tuningIndexLimitsEachTrial,
        tuningTimeRange)
    responseArray, errorArray = funcs.calculate_tuning_curve_inputs(
        tuningSpikeCountMat, freqEachTrial, intEachTrial)
    responseArray = responseArray[:, -1] / (
        tuningTimeRange[1] - tuningTimeRange[0]
    )  #just the high intensity freq trials