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
def at_best_freq(spikeTimeStamps, eventOnsetTimes, charFreq, frequencies, timeRange=[0.0,0.1], fullRange = [0.0, 0.7]):
    atBestFreq = False
    numFreqs = np.unique(frequencies)
    spikeArray = np.zeros(len(numFreqs))
    trialsEachCond = behavioranalysis.find_trials_each_type(frequencies, numFreqs)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                                                                                                        spikeTimeStamps, 
                                                                                                        eventOnsetTimes,
                                                                                                        fullRange)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange)
    baseTimeRange = [timeRange[1]+0.2, fullRange[1]]
    baseSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, baseTimeRange)
    baselineSpikeRate = np.mean(baseSpikeCountMat)/(baseTimeRange[1]-baseTimeRange[0])
    baselineSpikeSDev = np.std(baseSpikeCountMat)/(baseTimeRange[1]-baseTimeRange[0])
    for freq in range(len(numFreqs)):
        trialsThisFreq = trialsEachCond[:,freq]
        if spikeCountMat.shape[0] != len(trialsThisFreq):
            spikeCountMat = spikeCountMat[:-1,:]
            print "FIXME: Using bad hack to make event onset times equal number of trials"
        thisFreqCounts = spikeCountMat[trialsThisFreq].flatten()
        spikeArray[freq] = np.mean(thisFreqCounts)/(timeRange[1]-timeRange[0])
    bestFreqIndex = np.argmax(spikeArray)
    bestFreq = numFreqs[bestFreqIndex]
    minIndex = bestFreqIndex-1 if bestFreqIndex>0 else 0
    maxIndex = bestFreqIndex+1 if bestFreqIndex<(len(numFreqs)-1) else len(numFreqs)-1
    bestFreqs = [numFreqs[minIndex], numFreqs[maxIndex]]
    if charFreq >= bestFreqs[0] and charFreq <= bestFreqs[1]:
        if np.max(spikeArray) > (baselineSpikeRate + baselineSpikeSDev):
            atBestFreq = True
    return atBestFreq, bestFreq
def laser_response(spikeTimeStamps, eventOnsetTimes, timeRange=[0.0, 0.1], baseRange=[0.5, 0.6]):
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimeStamps, eventOnsetTimes, [min(timeRange),max(baseRange)])
    zStatsEachRange,pValueEachRange,maxZvalue = spikesanalysis.response_score(spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange, timeRange)
    baseSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange)
    baselineSpikeRate = np.mean(baseSpikeCountMat)/(baseRange[1]-baseRange[0])
    laserSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange)
    laserSpikeRate = np.mean(laserSpikeCountMat)/(timeRange[1]-timeRange[0])
    return (laserSpikeRate > baselineSpikeRate and pValueEachRange[0] < 0.00001)
Beispiel #4
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 onset_sustained_spike_proportion(spikeTimeStamps, eventOnsetTimes, onsetTimeRange=[0.0,0.05], sustainedTimeRange=[0.2,1.0]):
    fullTimeRange = [onsetTimeRange[0], sustainedTimeRange[1]]
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(spikeTimeStamps, 
                                                                                                                       eventOnsetTimes, 
                                                                                                                       fullTimeRange)
        
    onsetSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, onsetTimeRange)
    sustainedSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, sustainedTimeRange)
    fullSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, fullTimeRange)
    propOnset = 1.0*sum(onsetSpikeCountMat)/sum(fullSpikeCountMat)
    propSustained = 1.0*sum(sustainedSpikeCountMat)/sum(fullSpikeCountMat)
    return propOnset, propSustained
Beispiel #6
0
def laser_response(eventOnsetTimes, spikeTimeStamps, timeRange=[0.0, 0.1], baseRange=[-0.2, -0.1]):
    fullTimeRange = [min(min(timeRange),min(baseRange)), max(max(timeRange),max(baseRange))]
    
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(spikeTimeStamps, 
                                                                                                                   eventOnsetTimes, 
                                                                                                                   fullTimeRange)
    baseSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange)
    baselineSpikeRate = np.mean(baseSpikeCountMat)/(baseRange[1]-baseRange[0])
    baselineSpikeRateSTD = np.std(baseSpikeCountMat)/(baseRange[1]-baseRange[0])
    laserSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange)
    laserSpikeRate = np.mean(laserSpikeCountMat)/(timeRange[1]-timeRange[0])
    laserpVal = stats.ranksums(laserSpikeCountMat, baseSpikeCountMat)[1]
    laserstdFromBase = (laserSpikeRate - baselineSpikeRate)/baselineSpikeRateSTD

    return laserpVal, laserstdFromBase
def hist_sound_allFreq_switching():
    rightward = bdata['choice']==bdata.labels['choice']['right']
    leftward = bdata['choice']==bdata.labels['choice']['left']
    invalid = bdata['outcome']==bdata.labels['outcome']['invalid']
    correct = bdata['outcome']==bdata.labels['outcome']['correct']
    correctRightward = rightward & correct
    correctLeftward = leftward & correct

    possibleFreq = np.unique(bdata['targetFrequency'])

    Freq = possibleFreq[Frequency]
    oneFreq = bdata['targetFrequency'] == Freq

    trialsToUseRight = rightward & oneFreq
    trialsToUseLeft = leftward & oneFreq

    lowFreq = ((bdata['targetFrequency'] == possibleFreq[0]) & correct)
    highFreq = ((bdata['targetFrequency'] == possibleFreq[2]) & correct)

    trialsEachCond = np.c_[highFreq,trialsToUseLeft,trialsToUseRight,lowFreq]; colorEachCond = ['b','r','g','y']

    timeVec = np.arange(timeRange[0],timeRange[-1],binWidth)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,timeVec)

    smoothWinSize = 3
    extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=trialsEachCond,
                         colorEachCond=colorEachCond,linestyle=None,linewidth=2,downsamplefactor=1)

    plt.xlabel('Time from sound onset (s)')
    plt.ylabel('Firing rate (spk/sec)')
def hist_movement_allFreq_switching(ax):
    rightward = bdata['choice']==bdata.labels['choice']['right']
    leftward = bdata['choice']==bdata.labels['choice']['left']
    invalid = bdata['outcome']==bdata.labels['outcome']['invalid']
    correct = bdata['outcome']==bdata.labels['outcome']['correct']
    correctRightward = rightward & correct
    correctLeftward = leftward & correct

    possibleFreq = np.unique(bdata['targetFrequency'])

    Freq = possibleFreq[Frequency]
    oneFreq = bdata['targetFrequency'] == Freq

    trialsToUseRight = rightward & oneFreq
    trialsToUseLeft = leftward & oneFreq

    lowFreq = ((bdata['targetFrequency'] == possibleFreq[0]) & correct)
    highFreq = ((bdata['targetFrequency'] == possibleFreq[2]) & correct)

    trialsEachCond = np.c_[lowFreq,trialsToUseRight,trialsToUseLeft,highFreq]; colorEachCond = ['y','g','r','b']

    timeVec = np.arange(timeRange[0],timeRange[-1],binWidth)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromMovementOnset,indexLimitsEachMovementTrial,timeVec)

    smoothWinSize = 3
    extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=trialsEachCond,
                         colorEachCond=colorEachCond,linestyle=None,linewidth=2,downsamplefactor=1)

    ax.axvline(x=0, ymin=0, ymax=1, color='r')
def hist_movement_psycurve(Frequency):
    rightward = bdata['choice']==bdata.labels['choice']['right']
    leftward = bdata['choice']==bdata.labels['choice']['left']
    invalid = bdata['outcome']==bdata.labels['outcome']['invalid']

    possibleFreq = np.unique(bdata['targetFrequency'])

    Freq = possibleFreq[Frequency]
    oneFreq = bdata['targetFrequency'] == Freq

    trialsToUseRight = rightward & oneFreq
    trialsToUseLeft = leftward & oneFreq

    trialsEachCond = np.c_[trialsToUseLeft,trialsToUseRight]; colorEachCond = ['r','g']

    timeVec = np.arange(timeRange[0],timeRange[-1],binWidth)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromMovementOnset,indexLimitsEachMovementTrial,timeVec)

    smoothWinSize = 3
    extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=trialsEachCond,
                         colorEachCond=colorEachCond,linestyle=None,linewidth=3,downsamplefactor=1)

    plt.xlabel('Time from center poke out (s)')
    plt.ylabel('Firing rate (spk/sec)')


    '''
def hist_sound_block_switching():
    correct = bdata['outcome']==bdata.labels['outcome']['correct']

    possibleFreq = np.unique(bdata['targetFrequency'])

    Freq = possibleFreq[Frequency]
    oneFreq = bdata['targetFrequency'] == Freq

    correctOneFreq = oneFreq & correct
    trialsEachBlock = bdata.blocks['trialsEachBlock']
    correctTrialsEachBlock = trialsEachBlock & correctOneFreq[:,np.newaxis]
    correctBlockSizes = sum(correctTrialsEachBlock)
    if (correctBlockSizes[-1] < minBlockSize): #Just a check to see if last block is too small to plot
        blockSizes = sum(trialsEachBlock)
        numBlocks = len(trialsEachBlock[0])
        sumBlocks = sum(blockSizes)
        newTrialsLastBlock = np.zeros((blockSizes[-1],numBlocks), dtype=np.bool)
        correctTrialsEachBlock[(sumBlocks-blockSizes[-1]):] = newTrialsLastBlock #if the last block is too small, make the condition for the last trial all false
        #correctTrialsEachBlock = trialsEachBlock & correctOneFreq[:,np.newaxis]

    trialsEachCond = correctTrialsEachBlock;

    if bdata['currentBlock'][0]==bdata.labels['currentBlock']['low_boundary']:
        colorEachBlock = 4*['g','r']
    else:
        colorEachBlock = 4*['r','g']
    timeVec = np.arange(timeRange[0],timeRange[-1],binWidth)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,timeVec)

    smoothWinSize = 3
    extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=trialsEachCond,
                         colorEachCond=colorEachBlock,linestyle=None,linewidth=2,downsamplefactor=1)

    plt.xlabel('Time from sound onset (s)')
    plt.ylabel('Firing rate (spk/sec)')
Beispiel #11
0
def laser_response(ephysData, baseRange = [-0.05,-0.04], responseRange = [0.0, 0.01]):
    fullTimeRange = [baseRange[0], responseRange[1]]
    eventOnsetTimes = ephysData['events']['laserOn']
    spikeTimestamps = ephysData['spikeTimes']
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = \
            spikesanalysis.eventlocked_spiketimes(spikeTimestamps,
                                                      eventOnsetTimes,
                                                      fullTimeRange)
    baseSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,
                                                                 indexLimitsEachTrial,
                                                                 baseRange)
    laserSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,
                                                                  indexLimitsEachTrial,
                                                                  responseRange)
    [testStatistic, pVal] = stats.ranksums(laserSpikeCountMat, baseSpikeCountMat)
    return testStatistic, pVal
def noise_raster(ephysData, gs):
    plt.subplot(gs[0, 1])

    eventOnsetTimes = ephysData['events']['stimOn']
    spikeTimeStamps = ephysData['spikeTimes']
    timeRange = [-0.3, 0.6]
    baseTimeRange = [-0.15, -0.05]

    trialsEachCond = []

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

    baseSpikeMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, baseTimeRange)
    base_avg = np.mean(baseSpikeMat) / (baseTimeRange[1] - baseTimeRange[0])
    base_sem = stats.sem(baseSpikeMat) / (baseTimeRange[1] - baseTimeRange[0])

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

    title = "Noise Bursts (Base FR: {} +/- {} spikes/s)".format(round(base_avg, 2), round(base_sem, 2)) 
    #title = "Noise Bursts (Base FR: {} spikes/s)".format(round(base_avg, 2)) 
    #title = "Noise Bursts"
    xlabel = 'Time from sound onset (s)'
    ylabel = 'Trial'

    plt.title(title, fontsize = 'medium')
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)

    '''
Beispiel #13
0
def plot_sorted_psth(spikeTimeStamps, eventOnsetTimes, sortArray, timeRange=[-0.5,1], binsize = 50, lw=2, plotLegend=False, *args, **kwargs):
    '''
    Function to accept spike timestamps, event onset times, and a sorting array and plot a
    PSTH sorted by the sorting array

    Args:
        binsize (float) = size of bins for PSTH in ms
    '''
    binsize = binsize/1000.0
    # If a sort array is supplied, find the trials that correspond to each value of the array
    if len(sortArray) > 0:
        trialsEachCond = behavioranalysis.find_trials_each_type(
            sortArray, np.unique(sortArray))
    else:
        trialsEachCond = []
    # Align spiketimestamps to the event onset times for plotting
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimeStamps, eventOnsetTimes, [timeRange[0]-binsize, timeRange[1]])
    binEdges = np.around(np.arange(timeRange[0]-binsize, timeRange[1]+2*binsize, binsize), decimals=2)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges)
    pPSTH = extraplots.plot_psth(spikeCountMat/binsize, 1, binEdges[:-1], trialsEachCond, *args, **kwargs)
    plt.setp(pPSTH, lw=lw)
    plt.hold(True)
    zline = plt.axvline(0,color='0.75',zorder=-10)
    plt.xlim(timeRange)

    if plotLegend:
        if len(sortArray)>0:
            sortElems = np.unique(sortArray)
            for ind, pln in enumerate(pPSTH):
                pln.set_label(sortElems[ind])
            # ax = plt.gca()
            # plt.legend(mode='expand', ncol=3, loc='best')
            plt.legend(ncol=3, loc='best')
Beispiel #14
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)
Beispiel #15
0
def stim_response(ephysData, baseRange = [-0.05,-0.04], responseRange = [0.0, 0.01], stimType = 'laser'):
    fullTimeRange = [baseRange[0], responseRange[1]]
    if stimType == 'laser':
        eventOnsetTimes = ephysData['events']['laserOn']
    elif stimType == 'sound':
        eventOnsetTimes = get_sound_onset_times(ephysData, 'bandwidth')
    spikeTimestamps = ephysData['spikeTimes']
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = \
            spikesanalysis.eventlocked_spiketimes(spikeTimestamps,
                                                      eventOnsetTimes,
                                                      fullTimeRange)
    baseSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,
                                                                 indexLimitsEachTrial,
                                                                 baseRange)
    laserSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,
                                                                  indexLimitsEachTrial,
                                                                  responseRange)
    [testStatistic, pVal] = stats.ranksums(laserSpikeCountMat, baseSpikeCountMat)
    return testStatistic, pVal
Beispiel #16
0
def best_window_freq_tuning(spikeTimesFromEventOnset,indexLimitsEachTrial, trialsEachFreq, windowsToTry = [[0.0,0.1],[0.0,0.05],[0.1,0.15]]):
    zscores = np.zeros((len(windowsToTry),trialsEachFreq.shape[1]))

    for ind, window in enumerate(windowsToTry):
        duration = window[1]-window[0]
        baseTimeRange = [-0.1-duration, -0.1]
        spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, window)
        baseSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, baseTimeRange)
        
        for ind2 in range(len(numFreqs)):
            trialsThisFreq = trialsEachFreq[:,ind2]
            spikeCountsThisFreq = spikeCountMat[trialsThisFreq]
            baseCountsThisFreq = baseSpikeCountMat[trialsThisFreq]
            zScore, pVal = stats.ranksums(spikeCountsThisFreq, baseCountsThisFreq)
            zscores[ind,ind2] = zScore

    maxInd = np.unravel_index(zscores.argmax(), zscores.shape)
    windowToUse = windowsToTry[maxInd[0]]
    return windowToUse
Beispiel #17
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 laser_response(cell, timeRange=[0.0, 0.1], baseRange=[0.5, 0.6]):
    cellInfo = get_cell_info(cell)
    loader = dataloader.DataLoader(cell['subject'])
    if len(cellInfo['laserIndex'])>0:
        eventData = loader.get_session_events(cellInfo['ephysDirs'][cellInfo['laserIndex'][-1]])
        spikeData = loader.get_session_spikes(cellInfo['ephysDirs'][cellInfo['laserIndex'][-1]], cellInfo['tetrode'], cluster=cellInfo['cluster'])
        eventOnsetTimes = loader.get_event_onset_times(eventData)
        spikeTimestamps = spikeData.timestamps
        spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimestamps, eventOnsetTimes, [min(timeRange),max(baseRange)])
        zStatsEachRange,pValueEachRange,maxZvalue = spikesanalysis.response_score(spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange, timeRange)
        baseSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange)
        baselineSpikeRate = np.mean(baseSpikeCountMat)/(baseRange[1]-baseRange[0])
        laserSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange)
        laserSpikeRate = np.mean(laserSpikeCountMat)/(timeRange[1]-timeRange[0])
        laserResponse = (laserSpikeRate > baselineSpikeRate and pValueEachRange[0] < 0.00001)
    else:
        laserResponse = False

    return laserResponse
def am_raster(bdata, ephysData, gs):
    plt.subplot(gs[1, 1])

    freqEachTrial = bdata['currentFreq']
    
    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]

    trialsEachCond = behavioranalysis.find_trials_each_type(freqEachTrial, possiblefreqs)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
            spikeTimeStamps, eventOnsetTimes, timeRange)
    #print len(freqEachTrial), len(eventOnsetTimes)

    baseSpikeMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, baseTimeRange)
    base_avg = np.mean(baseSpikeMat) / (baseTimeRange[1] - baseTimeRange[0])
    base_sem = stats.sem(baseSpikeMat) / (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 (Base FR: {} +/- {} spikes/s)".format(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)
    '''
Beispiel #20
0
def sound_response_any_stimulus(eventOnsetTimes, spikeTimeStamps, trialsEachCond, timeRange=[0.0,1.0], baseRange=[-1.1,-0.1]):
    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)
        
    minpVal = np.inf
    maxzscore = -np.inf
    for cond in range(trialsEachCond.shape[1]):
        trialsThisCond = trialsEachCond[:,cond]
        if stimSpikeCountMat.shape[0] == len(trialsThisCond)+1:
            stimSpikeCountMat = stimSpikeCountMat[:-1,:]
        if any(trialsThisCond):
            thisFirstStimCounts = stimSpikeCountMat[trialsThisCond].flatten()
            thisStimBaseSpikeCouns = baseSpikeCountMat[trialsThisCond].flatten()
            thiszscore, pValThisFirst = stats.ranksums(thisFirstStimCounts, thisStimBaseSpikeCouns)
            if pValThisFirst < minpVal:
                minpVal = pValThisFirst
            if thiszscore > maxzscore:
                maxzscore = thiszscore
    return maxzscore, minpVal
Beispiel #21
0
def modulation_index_switching():
    global spikeTimesFromEventOnset
    global indexLimitsEachTrial
    global bdata
    global titleText
    stimulusRange = [0.0,0.1] #This is the length of the stimulus in seconds
    Frequency = 1 #This is the middle frequency


    rightward = bdata['choice']==bdata.labels['choice']['right']
    leftward = bdata['choice']==bdata.labels['choice']['left']
    invalid = bdata['outcome']==bdata.labels['outcome']['invalid']
    correct = bdata['outcome']==bdata.labels['outcome']['correct']
    correctRightward = rightward & correct
    correctLeftward = leftward & correct

    possibleFreq = np.unique(bdata['targetFrequency'])
    oneFreq = bdata['targetFrequency'] == possibleFreq[Frequency]

    trialsToUseRight = correctRightward & oneFreq
    trialsToUseLeft = correctLeftward & oneFreq


    trialsEachCond = [trialsToUseRight,trialsToUseLeft]


    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,stimulusRange)
    spikeCountEachTrial = spikeCountMat.flatten()
    spikeAvgRight = sum(spikeCountEachTrial[trialsToUseRight])/float(sum(trialsToUseRight))
    spikeAvgLeft = sum(spikeCountEachTrial[trialsToUseLeft])/float(sum(trialsToUseLeft))
    if ((spikeAvgRight + spikeAvgLeft) == 0):
        modInd = 0
    else:
        modInd = (spikeAvgRight - spikeAvgLeft)/(spikeAvgRight + spikeAvgLeft)

    mod_sig = spikesanalysis.evaluate_modulation(spikeTimesFromEventOnset,indexLimitsEachTrial,stimulusRange,trialsEachCond)

    titleText = 'Modulation Index: '+str(round(modInd,3))+', significance (p value): '+ str(round(mod_sig[1],3))
def hist_sound_psycurve(Frequency,ax):
    rightward = bdata['choice']==bdata.labels['choice']['right']
    leftward = bdata['choice']==bdata.labels['choice']['left']
    invalid = bdata['outcome']==bdata.labels['outcome']['invalid']

    possibleFreq = np.unique(bdata['targetFrequency'])

    Freq = possibleFreq[Frequency]
    oneFreq = bdata['targetFrequency'] == Freq

    trialsToUseRight = rightward & oneFreq
    trialsToUseLeft = leftward & oneFreq

    trialsEachCond = np.c_[trialsToUseLeft,trialsToUseRight]; colorEachCond = ['r','g']

    timeVec = np.arange(timeRange[0],timeRange[-1],binWidth)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,timeVec)

    smoothWinSize = 3
    extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=trialsEachCond,
                         colorEachCond=colorEachCond,linestyle=None,linewidth=3,downsamplefactor=1)

    ax.axvspan(0.0, 0.1, color=[0.8,0.8,0.8], alpha=0.5, lw=0)
def plot_rew_change_per_cell(oneCell,trialLimit=[],alignment='sound'):
    '''
    Plots raster and PSTH for one cell during reward_change_freq_dis task, split by block; alignment parameter should be set to either 'sound', 'center-out', or 'side-in'.
    '''    
    bdata = load_behav_per_cell(oneCell)
    (spikeTimestamps,waveforms,eventOnsetTimes,eventData) = load_ephys_per_cell(oneCell)

    # -- Check to see if ephys has skipped trials, if so remove trials from behav data 
    soundOnsetEvents = (eventData.eventID==1) & (eventData.eventChannel==soundTriggerChannel)
    soundOnsetTimeEphys = eventOnsetTimes[soundOnsetEvents]
    soundOnsetTimeBehav = bdata['timeTarget']

    # Find missing trials
    missingTrials = behavioranalysis.find_missing_trials(soundOnsetTimeEphys,soundOnsetTimeBehav)
    # Remove missing trials
    bdata.remove_trials(missingTrials)

    currentBlock = bdata['currentBlock']
    blockTypes = [bdata.labels['currentBlock']['same_reward'],bdata.labels['currentBlock']['more_left'],bdata.labels['currentBlock']['more_right']]
    #blockLabels = ['more_left', 'more_right']
    if(not len(trialLimit)):
        validTrials = np.ones(len(currentBlock),dtype=bool)
    else:
        validTrials = np.zeros(len(currentBlock),dtype=bool)
        validTrials[trialLimit[0]:trialLimit[1]] = 1

    trialsEachType = behavioranalysis.find_trials_each_type(currentBlock,blockTypes)
    
        
    if alignment == 'sound':
        soundOnsetEvents = (eventData.eventID==1) & (eventData.eventChannel==soundTriggerChannel)
        EventOnsetTimes = eventOnsetTimes[soundOnsetEvents]
    elif alignment == 'center-out':
        soundOnsetEvents = (eventData.eventID==1) & (eventData.eventChannel==soundTriggerChannel)
        EventOnsetTimes = eventOnsetTimes[soundOnsetEvents]
        diffTimes=bdata['timeCenterOut']-bdata['timeTarget']
        EventOnsetTimes+=diffTimes
    elif alignment == 'side-in':
        soundOnsetEvents = (eventData.eventID==1) & (eventData.eventChannel==soundTriggerChannel)
        EventOnsetTimes = eventOnsetTimes[soundOnsetEvents]
        diffTimes=bdata['timeSideIn']-bdata['timeTarget']
        EventOnsetTimes+=diffTimes

    freqEachTrial = bdata['targetFrequency']
    possibleFreq = np.unique(freqEachTrial)
    
    rightward = bdata['choice']==bdata.labels['choice']['right']
    leftward = bdata['choice']==bdata.labels['choice']['left']
    invalid = bdata['outcome']==bdata.labels['outcome']['invalid']
        
    correct = bdata['outcome']==bdata.labels['outcome']['correct'] 
    incorrect = bdata['outcome']==bdata.labels['outcome']['error']  

    ######Split left and right trials into correct and  incorrect categories to look at error trials#########
    rightcorrect = rightward&correct&validTrials
    leftcorrect = leftward&correct&validTrials
    #righterror = rightward&incorrect&validTrials
    #lefterror = leftward&incorrect&validTrials

    rightcorrectBlockSameReward = rightcorrect&trialsEachType[:,0]
    rightcorrectBlockMoreLeft = rightcorrect&trialsEachType[:,1] 
    rightcorrectBlockMoreRight = rightcorrect&trialsEachType[:,2]
    leftcorrectBlockSameReward = leftcorrect&trialsEachType[:,0]
    leftcorrectBlockMoreLeft = leftcorrect&trialsEachType[:,1]
    leftcorrectBlockMoreRight = leftcorrect&trialsEachType[:,2]

    trialsEachCond = np.c_[leftcorrectBlockMoreLeft,rightcorrectBlockMoreLeft,leftcorrectBlockMoreRight,rightcorrectBlockMoreRight,leftcorrectBlockSameReward,rightcorrectBlockSameReward] 


    colorEachCond = ['g','r','m','b','y','darkgray']
    #trialsEachCond = np.c_[invalid,leftcorrect,rightcorrect,lefterror,righterror] 
    #colorEachCond = ['0.75','g','r','b','m'] 

    (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
spikesanalysis.eventlocked_spiketimes(spikeTimestamps,EventOnsetTimes,timeRange)
    
    ###########Plot raster and PSTH#################
    plt.figure()
    ax1 = plt.subplot2grid((8,5), (0, 0), rowspan=4,colspan=5)
    extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange,trialsEachCond=trialsEachCond,colorEachCond=colorEachCond,fillWidth=None,labels=None)
    plt.ylabel('Trials')
    plt.xlim(timeRange)

    plt.title('{0}_{1}_TT{2}_c{3}_{4}'.format(oneCell.animalName,oneCell.behavSession,oneCell.tetrode,oneCell.cluster,alignment))

    timeVec = np.arange(timeRange[0],timeRange[-1],binWidth)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,timeVec)
    smoothWinSize = 3
    ax2 = plt.subplot2grid((8,5), (4, 0),colspan=5,rowspan=2,sharex=ax1)
    extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=trialsEachCond,colorEachCond=colorEachCond,linestyle=None,linewidth=3,downsamplefactor=1)
    plt.xlabel('Time from {0} onset (s)'.format(alignment))
    plt.ylabel('Firing rate (spk/sec)')
   
    # -- Plot ISI histogram --
    plt.subplot2grid((8,5), (6,0), rowspan=1, colspan=2)
    spikesorting.plot_isi_loghist(spikeTimestamps)
    plt.ylabel('c%d'%oneCell.cluster,rotation=0,va='center',ha='center')
    plt.xlabel('')

    # -- Plot waveforms --
    plt.subplot2grid((8,5), (7,0), rowspan=1, colspan=3)
    spikesorting.plot_waveforms(waveforms)

    # -- Plot projections --
    plt.subplot2grid((8,5), (6,2), rowspan=1, colspan=3)
    spikesorting.plot_projections(waveforms)

    # -- Plot events in time --
    plt.subplot2grid((8,5), (7,3), rowspan=1, colspan=2)
    spikesorting.plot_events_in_time(spikeTimestamps)

    plt.subplots_adjust(wspace = 0.7)
    
    #plt.show()
    #fig_path = 
    #fig_name = 'TT{0}Cluster{1}{2}.png'.format(tetrode, cluster, '_2afc plot_each_type')
    #full_fig_path = os.path.join(fig_path, fig_name)
    #print full_fig_path
    plt.gcf().set_size_inches((8.5,11))
Beispiel #24
0
            frequenciesEachTrialA, arrayOfFrequenciesA)

        ax14 = plt.subplot2grid((4, 8), (0, 3), colspan=2)
        (pRaster, hcond,
         zline) = extraplots.raster_plot(spikeTimesFromEventOnsetA,
                                         indexLimitsEachTrialA,
                                         timeRange,
                                         trialsEachCondA,
                                         labels=labelsForYaxis)
        plt.setp(pRaster, ms=1)
        plt.xlabel('Time From Event Onset [s]', fontsize=9)
        plt.ylabel('Frequency [kHz]', fontsize=9)
        """
        --- PSTH ---
        """
        spikeCountMatFirstOddballA = spikesanalysis.spiketimes_to_spikecounts(
            spikeTimesFromEventOnsetA, firstOddballIndexLimitsA, timeVec)
        spikeCountMatSecondOddballA = spikesanalysis.spiketimes_to_spikecounts(
            spikeTimesFromEventOnsetA, secondOddballIndexLimitsA, timeVec)
        spikeCountMatThirdOddballA = spikesanalysis.spiketimes_to_spikecounts(
            spikeTimesFromEventOnsetA, thirdOddballIndexLimitsA, timeVec)
        spikeCountMatFirstStdA = spikesanalysis.spiketimes_to_spikecounts(
            spikeTimesFromEventOnsetA, firstStandardIndexLimitsA, timeVec)
        spikeCountMatSecondStdA = spikesanalysis.spiketimes_to_spikecounts(
            spikeTimesFromEventOnsetA, secondStandardIndexLimitsA, timeVec)
        spikeCountMatThirdStdA = spikesanalysis.spiketimes_to_spikecounts(
            spikeTimesFromEventOnsetA, thirdStandardIndexLimitsA, timeVec)

        ax9 = plt.subplot2grid((4, 8), (3, 2))
        extraplots.plot_psth(spikeCountMatFirstOddballA / binWidth,
                             smoothWinSizePsth,
                             timeVec,
Beispiel #25
0
    def cluster_color_psth(self, sessionList, plotType=None, site=-1, experiment=-1, tuningTimeRange = [0.0,0.1]):
        '''
        Display cluster waveforms and a PSTH or tuning curve for each cluster.
        Performs multisession clustering for each tetrode recorded at the site.
        Args:
            sessionList (list of indices): The indices of the sessions to be included in the multisession clustering.
            plotType (list of str): A list the same length as sessionList, containing the type of plot for that session.
                                    Current valid plotTypes are: 'psth', 'tuning'
            site (index): The index of the site to pull sessions from.
            experiment (index): The index of the experiment to get the site from.
            tuningTimeRange (list of float): List containing [start, stop] times relative to event onset over which to
                                             average spikes for tuning curve.
        Returns nothing, but .clu files and multisession cluster reports will be created.
        '''

        if not isinstance(sessionList, list):
            sessionList = list(sessionList)
        if plotType is None:
            plotType = ['psth']*len(sessionList)

        #Cluster the site, all tetrodes
        #TODO: Make sure this function is using nice new cms with numclusters=6
        self.cluster_array_multisession(sessionList, site=site, experiment=experiment)


        allSessionObj = [self.get_session_obj(session, experiment, site) for session in sessionList]
        allTetrodes=[so.tetrodes for so in allSessionObj]

        # allEventOnsetTimes = [self.loader.get_event_onset_times(ed) for ed in allEventData]

        siteObj = self.get_site_obj(site=site, experiment=experiment)
        allSessionType = [siteObj.session_types()[ind] for ind in sessionList]

        self.fig = plt.gcf()
        self.fig.clf()
        self.fig.set_facecolor('w')

        from matplotlib import gridspec
        gs = gridspec.GridSpec(2*len(allTetrodes[0]), 6+6*len(sessionList))
        gs.update(wspace=0.5, hspace=0.5)

        nClusters=6 #FIXME hardcoded number of clusters to plot

        from jaratoolbox import colorpalette
        cp = colorpalette.TangoPalette
        colors = [cp['SkyBlue1'], cp['Chameleon1'], cp['Orange1'],
                  cp['Plum1'], cp['ScarletRed1'], cp['Aluminium4']]

        for indSession, sessionObj in enumerate(allSessionObj):

            # sessionObj = allSessionObj[indSession]
            # sessionDir = allSessionDir[indSession]
            sessionDir = sessionObj.ephys_dir()

            # eventData = allEventData[indSession]
            # eventOnsetTimes = allEventOnsetTimes[indSession]

            tetrodes = allTetrodes[indSession]

            if plotType[indSession] == 'tuning':

                if sessionObj.behavsuffix is None:
                    raise AttributeError('There is no behavior suffix recorded for this session') #TODO: add session info
                behavClass = loadbehavior.BehaviorData
                dateStr = ''.join(sessionObj.date.split('-'))
                fullSessionStr = '{}{}'.format(dateStr, sessionObj.behavsuffix)
                behavDataFilePath = loadbehavior.path_to_behavior_data(sessionObj.subject,
                                                                    sessionObj.paradigm,
                                                                    fullSessionStr)
                bdata = behavClass(behavDataFilePath,readmode='full')
                #FIXME: Hardcoded variable name to sort by for tuning
                freqEachTrial = bdata['currentFreq']
                freqLabels = ["%.1f"%freq for freq in np.unique(freqEachTrial)/1000]

            for indt, tetrode in enumerate(tetrodes):

                colStart = 6+(6*indSession)
                colEnd = colStart+6
                psth_ax = plt.subplot(gs[indt*2:(indt*2)+2, colStart:colEnd])

                for indc, cluster in enumerate(range(1, nClusters+1)):

                    ephysData = ephyscore.load_ephys(sessionObj.subject, sessionObj.paradigm, sessionDir, tetrode, cluster)
                    spikeTimestamps = ephysData['spikeTimes']
                    eventOnsetTimes = ephysData['events']['stimOn']

                    clusterColor = colors[indc]
                    # spikeData= self.loader.get_session_spikes(sessionDir, tetrode, cluster)
                    # spikeTimestamps = spikeData.timestamps
                    timeRange = [-0.2, 1]
                    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                        spikeTimestamps, eventOnsetTimes, timeRange)


                    if plotType[indSession] == 'psth':
                        binEdges = np.linspace(-0.2, 1, 100)
                        spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,
                                                                                 indexLimitsEachTrial,
                                                                                 binEdges)
                        # import ipdb; ipdb.set_trace()
                        smoothWinSize = 3
                        winShape = np.concatenate((np.zeros(smoothWinSize),np.ones(smoothWinSize))) # Square (causal)
                        winShape = winShape/np.sum(winShape)

                        binsStartTime=binEdges[:-1]

                        binSize = binEdges[1]-binEdges[0]
                        thisPSTH = np.mean(spikeCountMat/binSize,axis=0)
                        smoothPSTH = np.convolve(thisPSTH,winShape,mode='same')
                        downsamplefactor=1
                        sSlice = slice(0,len(smoothPSTH),downsamplefactor)
                        psth_ax.plot(binsStartTime[sSlice],smoothPSTH[sSlice], color = clusterColor, lw=2)
                        psth_ax.set_xlim(timeRange)
                    elif plotType[indSession] == 'tuning':
                        trialsEachCond = behavioranalysis.find_trials_each_type(freqEachTrial, np.unique(freqEachTrial))
                        # spikeArray = dataplotter.avg_spikes_in_event_locked_timerange_each_cond(spikeTimestamps, trialsEachCond, eventOnsetTimes, timeRange=tuningTimeRange)
                        spikeArray = self.avg_spikes_in_event_locked_timerange_each_cond(spikeTimestamps, trialsEachCond, eventOnsetTimes, timeRange=tuningTimeRange)
                        psth_ax.plot(spikeArray, ls='-', lw=2, color = clusterColor)
                        psth_ax.set_xticks(range(len(np.unique(freqEachTrial))))
                        psth_ax.set_xticklabels(freqLabels,fontsize=8)
                    psth_ax.hold(1)
                    psth_ax.axvline(x=0, color='k')
                    if indt==0:
                        psth_ax.set_title(allSessionType[indSession])

                    crow = indc/3 + (indt*2)
                    ccolStart = (indc%3)*2
                    ccolEnd = ccolStart+2

                    if indSession==0:
                        cluster_ax = plt.subplot(gs[crow, ccolStart:ccolEnd])
                        # print 'r{}c{} : Cluster {}, {} spikes'.format(crow, ccolStart, cluster, len(spikeData.timestamps))
                        plot_colored_waveforms(ephysData['samples'], clusterColor, ax=cluster_ax)

        plt.show()
def calculate_monotonicity_index(eventOnsetTimes, currentFreq,
                                 currentIntensity, uniqueIntensity, spikeTimes,
                                 cf):
    """

    Args:
        eventOnsetTimes (np.array): Same size as the number of trials with each value being the time sound detector turned on
        currentFreq (np.array): Same size as number of trials presented with each value being a specific frequency for that trial
        currentIntensity (np.array): Same size as number of trials presented with each value being a specific intensity for that trial
        uniqueIntensity (np.array): Uses currentIntensity to find how many unique intensity values were presented and store each unique value in ascending order
        spikeTimes (np.array): Each value is a time when a spike occurred; obtained from ephys data
        cf (float): Characteristic frequency of the cell, calculated by analyzing lowest threshold value for a cell

    Returns:
        monoIndex (float): Index value for monotonicity of a cell, between 0 and 1
        overallMaxSpikes (float): Mean number of spikes at the intensity that had the most spikes for a stimulus
    """

    # if len(eventOnsetTimes) != len(freqEachTrial):
    #     eventOnsetTimes = eventOnsetTimes[:-1]
    #     if len(eventOnsetTimes) != len(freqEachTrial):
    #         continue
    # cfTrials = currentFreq == dbRow['cf']  # cf is characteristic frequency
    cfTrials = currentFreq == cf
    eventsThisFreq = eventOnsetTimes[cfTrials]
    intenThisFreq = currentIntensity[cfTrials]

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

    meanSpikesAllInten = np.empty(len(uniqueIntensity))
    maxSpikesAllInten = np.empty(len(uniqueIntensity))
    baseSpikesAllInten = np.empty(len(uniqueIntensity))
    for indInten, inten in enumerate(uniqueIntensity):
        # print inten
        trialsThisIntensity = intenThisFreq == inten
        eventsThisCombo = eventsThisFreq[trialsThisIntensity]

        (spikeTimesFromEventOnset, trialIndexForEachSpike,
         indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(
             spikeTimes, eventsThisCombo, alignmentRange)
        nspkBase = spikesanalysis.spiketimes_to_spikecounts(
            spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange)
        nspkResp = spikesanalysis.spiketimes_to_spikecounts(
            spikeTimesFromEventOnset, indexLimitsEachTrial, responseRange)

        spikesThisInten = nspkResp[:, 0]
        baselineThisInten = nspkBase[:, 0]
        # print spikesThisInten
        try:
            meanSpikesThisInten = np.mean(spikesThisInten)
            meanBaselineSpikesThisInten = np.mean(baselineThisInten)
            maxSpikesThisInten = np.max(spikesThisInten)
        except ValueError:
            meanSpikesThisInten = 0
            maxSpikesThisInten = 0
            meanBaselineSpikesThisInten = 0

        meanSpikesAllInten[indInten] = meanSpikesThisInten
        maxSpikesAllInten[indInten] = maxSpikesThisInten
        baseSpikesAllInten[indInten] = meanBaselineSpikesThisInten

    baseline = np.mean(baseSpikesAllInten)
    monoIndex = (meanSpikesAllInten[-1] -
                 baseline) / (np.max(meanSpikesAllInten) - baseline)

    overallMaxSpikes = np.max(maxSpikesAllInten)

    return monoIndex, overallMaxSpikes
        timeRange: (list or np.array) two-element array specifying time-range to extract around event.

        spikeTimesFromEventOnset: 1D array with time of spikes locked to event.
    o    trialIndexForEachSpike: 1D array with the trial corresponding to each spike.
           The first spike index is 0.
        indexLimitsEachTrial: [2,nTrials] range of spikes for each trial. Note that
           the range is from firstSpike to lastSpike+1 (like in python slices)
        spikeIndices
    '''

    sortedIndexForEachSpike = sortingInds[trialIndexForEachSpike] #Takes values of trialIndexForEachSpike and finds value of sortingInds at that index and makes array. This array gives an array with the sorted index of each trial for each spike


    # -- Calculate tuning --
    responseRange = [0.010,0.10] #range of time to count spikes in after event onset
    nSpikes = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,responseRange) #array of the number of spikes in range for each trial
    '''Count number of spikes on each trial in a given time range.

           spikeTimesFromEventOnset: vector of spikes timestamps with respect
             to the onset of the event.
           indexLimitsEachTrial: each column contains [firstInd,lastInd+1] of the spikes on a trial.
           timeRange: time range to evaluate. Spike times exactly at the limits are not counted.

           returns nSpikes
    '''
    meanSpikesEachFrequency = np.empty(len(possibleFreq)) #make empty array of same size as possibleFreq

    # -- This part will be replace by something like behavioranalysis.find_trials_each_type --
    trialsEachFreq = []
    for indf,oneFreq in enumerate(possibleFreq):
        trialsEachFreq.append(np.flatnonzero(freqEachTrial==oneFreq)) #finds indices of each frequency. Appends them to get an array of indices of trials sorted by freq
Beispiel #28
0
    bandTimeRange = [-0.3, 1.5]
    bandEventOnsetTimes = bandEventData.get_event_onset_times()
    bandSpikeTimestamps = bandSpikeData.timestamps
    bandTrialsEachCond = behavioranalysis.find_trials_each_combination(
        bandEachTrial, numBands, secondSort, numSec)
    bandSpikeTimesFromEventOnset, trialIndexForEachSpike, bandIndexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        bandSpikeTimestamps, bandEventOnsetTimes, bandTimeRange)

    # --- produce input for bandwidth tuning curve ---
    #soundDuration = 1.0
    #print('WARNING! The sound duration is HARDCODED ({0} sec)'.format(soundDuration))
    soundDuration = bdata['stimDur'][-1]
    print('Sound duration from behavior data: {0} sec'.format(soundDuration))
    timeRange = [0.0, soundDuration]
    bandSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        bandSpikeTimesFromEventOnset, bandIndexLimitsEachTrial, timeRange)
    spikeArray = np.zeros((len(numBands), len(numSec)))  # Average firing rate
    errorArray = np.zeros_like(spikeArray)
    for thisSecVal in range(len(numSec)):
        trialsThisSecVal = bandTrialsEachCond[:, :, thisSecVal]
        for band in range(len(numBands)):
            trialsThisBand = trialsThisSecVal[:, band]
            if bandSpikeCountMat.shape[0] != len(trialsThisBand):
                bandSpikeCountMat = bandSpikeCountMat[:-1, :]
            if any(trialsThisBand):
                thisBandCounts = bandSpikeCountMat[trialsThisBand].flatten()
                spikeArray[
                    band, thisSecVal] = np.mean(thisBandCounts) / soundDuration
                errorArray[band, thisSecVal] = stats.sem(
                    thisBandCounts
                ) / soundDuration  # Error is standard error of the mean
def calculate_onset_to_sustained_ratio(eventOnsetTimes, spikeTimes,
                                       currentFreq, currentIntensity, cf,
                                       respLatency):
    """

    Args:
        eventOnsetTimes (np.array): Same size as the number of trials with each value being the time sound detector turned on
        currentFreq (np.array): Same size as number of trials presented with each value being a specific frequency for that trial
        currentIntensity (np.array): Same size as number of trials presented with each value being a specific intensity for that trial
        uniqueIntensity (np.array): Uses currentIntensity to find how many unique intensity values were presented and store each unique value in ascending order
        spikeTimes (np.array): Each value is a time when a spike occurred; obtained from ephys data
        respLatency (float): Time in seconds that the cell takes to respond to the stimulus being presented
    Returns:
        onsetRate (float): The number of spikes that happen within the response time range
        sustainedRate (float): The number of spikes that happen within the sustained time range
        baseRate (float): The number of spikes that happen within the baseline time range

    """
    cfTrials = currentFreq == cf
    eventsThisFreq = eventOnsetTimes[cfTrials]
    intenThisFreq = currentIntensity[cfTrials]

    # Get only the trials with the CF and the top 5 intensities
    uniqIntensity = np.unique(intenThisFreq)
    if len(uniqIntensity) > 4:
        intenToUse = uniqIntensity[-5:]
    else:
        intenToUse = uniqIntensity

    # Boolean of which trials from this frequency were high intensity
    highIntenTrials = np.in1d(intenThisFreq, intenToUse)

    # Filter the events this frequency to just take the ones from high intensity
    eventsThisFreqHighIntensity = eventsThisFreq[highIntenTrials]

    if not respLatency > 0:
        print("Negative latency!! Skipping")
        onsetRate = np.nan
        sustainedRate = np.nan
        baseRate = np.nan
        return onsetRate, sustainedRate, baseRate

    baseRange = [-0.1, -0.05]
    # responseRange = [0, 0.05, 0.1]
    responseRange = [respLatency, respLatency + 0.05, 0.1 + respLatency]
    # if dbRow['brainArea']=='rightAC':
    #     # responseRange = [0.02, 0.07, 0.12]
    #     responseRange = [0.02, 0.07, 0.1]
    # elif dbRow['brainArea']=='rightThal':
    #     # responseRange = [0.005, 0.015, 0.105]
    #     responseRange = [0.005, 0.015, 0.1]

    alignmentRange = [baseRange[0], responseRange[-1]]

    # Align spikes just to the selected event onset times
    (spikeTimesFromEventOnset, trialIndexForEachSpike,
     indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(
         spikeTimes, eventsThisFreqHighIntensity, alignmentRange)

    nspkBase = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange)

    nspkResp = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, responseRange)

    avgResponse = nspkResp.mean(axis=0)
    onsetSpikes = avgResponse[0]
    sustainedSpikes = avgResponse[1]
    onsetRate = onsetSpikes / (responseRange[1] - responseRange[0])
    sustainedRate = sustainedSpikes / (responseRange[2] - responseRange[1])

    baseSpikes = nspkBase.mean()
    baseRate = baseSpikes / (baseRange[1] - baseRange[0])

    return onsetRate, sustainedRate, baseRate
Beispiel #30
0
def raster_sound_psycurve(animalName):
    oneCell = allcells.cellDB[cellID]
    if (behavSession != oneCell.behavSession):


        subject = oneCell.animalName
        behavSession = oneCell.behavSession
        ephysSession = oneCell.ephysSession
        ephysRoot = os.path.join(ephysRootDir,subject)

        # -- Load Behavior Data --
        behaviorFilename = loadbehavior.path_to_behavior_data(subject,experimenter,paradigm,behavSession)
        bdata = loadbehavior.BehaviorData(behaviorFilename)
        numberOfTrials = len(bdata['choice'])

        # -- Load event data and convert event timestamps to ms --
        ephysDir = os.path.join(ephysRoot, ephysSession)
        eventFilename=os.path.join(ephysDir, 'all_channels.events')
        events = loadopenephys.Events(eventFilename) # Load events data
        eventTimes=np.array(events.timestamps)/SAMPLING_RATE #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and 

        soundOnsetEvents = (events.eventID==1) & (events.eventChannel==soundTriggerChannel)


        eventOnsetTimes = eventTimes[soundOnsetEvents]

        rightward = bdata['choice']==bdata.labels['choice']['right']
        leftward = bdata['choice']==bdata.labels['choice']['left']
        invalid = bdata['outcome']==bdata.labels['outcome']['invalid']

        possibleFreq = np.unique(bdata['targetFrequency'])
        numberOfFrequencies = len(possibleFreq)



    # -- Load Spike Data From Certain Cluster --
    spkData = ephyscore.CellData(oneCell)
    spkTimeStamps = spkData.spikes.timestamps

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

    for Frequency in range(numberOfFrequencies):

        Freq = possibleFreq[Frequency]
        oneFreq = bdata['targetFrequency'] == Freq

        trialsToUseRight = rightward & oneFreq
        trialsToUseLeft = leftward & oneFreq

        trialsEachCond = np.c_[trialsToUseLeft,trialsToUseRight]; colorEachCond = ['r','g']

        plt.clf()
        ax1 =  plt.subplot2grid((3,1), (0, 0), rowspan=2)
        extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange,trialsEachCond=trialsEachCond,colorEachCond=colorEachCond,fillWidth=None,labels=None)

        plt.ylabel('Trials')

        timeVec = np.arange(timeRange[0],timeRange[-1],binWidth)
        spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,timeVec)

        smoothWinSize = 3
        ax2 = plt.subplot2grid((3,1), (2, 0), sharex=ax1)

        extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=trialsEachCond,
                             colorEachCond=colorEachCond,linestyle=None,linewidth=3,downsamplefactor=1)

        plt.xlabel('Time from sound onset (s)')
        plt.ylabel('Firing rate (spk/sec)')
        
        if ((Frequency == numberOfFrequencies/2) or (Frequency == (numberOfFrequencies/2 - 1))):
                freqFile = 'Center_Frequencies'
        else:
                freqFile = 'Outside_Frequencies'
        tetrodeClusterName = 'T'+str(oneCell.tetrode)+'c'+str(oneCell.cluster)
        plt.gcf().set_size_inches((8.5,11))
        figformat = 'png' #'png' #'pdf' #'svg'
        filename = 'rast_%s_%s_%s_%s.%s'%(subject,behavSession,Freq,tetrodeClusterName,figformat)
        fulloutputDir = outputDir+subject+'/'+ freqFile +'/'
        fullFileName = os.path.join(fulloutputDir,filename)

        directory = os.path.dirname(fulloutputDir)
        if not os.path.exists(directory):
            os.makedirs(directory)
        print 'saving figure to %s'%fullFileName
        plt.gcf().savefig(fullFileName,format=figformat)
Beispiel #31
0
    labelsForYaxis = ['%.1f' % f for f in arrayOfFrequenciesOddkHz]
    trialsEachCondOdd = behavioranalysis.find_trials_each_type(
        frequenciesEachTrialOdd, arrayOfFrequenciesOdd)
    '''
    PSTH
    '''
    # Parameters
    binWidth = 0.010  # seconds
    timeVec = np.arange(timeRange[0], timeRange[-1], binWidth)
    smoothWinSizePsth = 5
    lwPsth = 2
    downsampleFactorPsth = 1

    iletLowFreqOddInStdPara = indexLimitsEachTrialStd[:, trialsEachCondStd[:,
                                                                           0]]
    spikeCountMatLowFreqOddInStdPara = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnsetStd, iletLowFreqOddInStdPara, timeVec)

    iletHighFreqStdInStdPara = indexLimitsEachTrialStd[:, trialsEachCondStd[:,
                                                                            1]]
    spikeCountMatHighFreqStdInStdPara = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnsetStd, iletHighFreqStdInStdPara, timeVec)

    iletLowFreqStdInOddPara = indexLimitsEachTrialOdd[:, trialsEachCondOdd[:,
                                                                           0]]
    spikeCountMatLowFreqStdInOddPara = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnsetOdd, iletLowFreqStdInOddPara, timeVec)

    iletHighFreqOddInOddPara = indexLimitsEachTrialOdd[:, trialsEachCondOdd[:,
                                                                            1]]
    spikeCountMatHighFreqOddInOddPara = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnsetOdd, iletHighFreqOddInOddPara, timeVec)
Beispiel #32
0
def am_raster(bdata, ephysData, gs):
    freqEachTrial = bdata['currentFreq']
    laserEachTrial = bdata['laserOn']
    #intEachTrial = bdata['currentIntensity']

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

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

    possiblefreqs = np.unique(freqEachTrial)
    #freqLabels = [round(x/1000, 1) for x in possiblefreqs]
    freqLabels = [round(x, 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 * 5:5 + indLaser * 5, 3:5])
        if indLaser == 0:
            title = "No Laser AM"
        else:
            title = "Laser AM"
        trialsEachCond = laserTrialsEachCond[:, :, indLaser]
        '''
        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])
        '''
        trialsThisLaser = np.all([bdata['laserOn'] == indLaser], axis=0)
        baseSpikeMatThisCond = baseSpikeMat[trialsThisLaser == True]

        base_avg = np.mean(baseSpikeMatThisCond) / (baseTimeRange[1] -
                                                    baseTimeRange[0])
        base_sem = stats.sem(baseSpikeMat) / (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 = 'AM Rate (Hz)'

        plt.title(title, fontsize='medium')
        plt.xlabel(xlabel)
        plt.ylabel(ylabel)
    '''
Beispiel #33
0
def plot_gaussian(cell, gs):
    laserTuningSessionInds = cell.get_session_inds('laserTuningCurve')

    if len(laserTuningSessionInds) != 0:
        for sessionInd in laserTuningSessionInds:
            bdata = cell.load_behavior_by_index(sessionInd)
            ephysData = cell.load_ephys_by_index(sessionInd)
    else:
        return

    freqEachTrial = bdata['currentFreq']
    laserEachTrial = bdata['laserOn']
    intEachTrial = bdata['currentIntensity']

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

    timeRange = [-0.3, 0.6]
    baseTimeRange = [0.0, 0.1]
    alignmentRange = [baseTimeRange[0], timeRange[1]]

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

    #Init list to hold the optimized parameters for the gaussian for each intensity and laser
    popts = []
    Rsquareds = []

    #Init arrays to hold the baseline and response spike counts per condition
    allLaserIntenBase = np.array([])
    allLaserIntenResp = np.empty(
        (len(possiblelaser), len(possibleInts), len(possiblefreqs)))
    allLaserIntenRespMedian = np.empty(
        (len(possiblelaser), len(possibleInts), len(possiblefreqs)))

    for indlaser, laser in enumerate(possiblelaser):
        for indinten, inten in enumerate(possibleInts):
            spks = np.array([])
            freqs = np.array([])
            base = np.array([])
            for indfreq, freq in enumerate(possiblefreqs):
                selectinds = np.flatnonzero((freqEachTrial == freq)
                                            & (intEachTrial == inten)
                                            & (laserEachTrial == laser))
                selectedOnsetTimes = eventOnsetTimes[selectinds]
                (spikeTimesFromEventOnset, trialIndexForEachSpike,
                 indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(
                     spikeTimeStamps, selectedOnsetTimes, alignmentRange)
                nspkBase = spikesanalysis.spiketimes_to_spikecounts(
                    spikeTimesFromEventOnset, indexLimitsEachTrial,
                    baseTimeRange)
                nspkResp = spikesanalysis.spiketimes_to_spikecounts(
                    spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange)
                base = np.concatenate([base, nspkBase.ravel()])
                spks = np.concatenate([spks, nspkResp.ravel()])
                # inds = np.concatenate([inds, np.ones(len(nspkResp.ravel()))*indfreq])
                freqs = np.concatenate(
                    [freqs, np.ones(len(nspkResp.ravel())) * freq])
                allLaserIntenBase = np.concatenate(
                    [allLaserIntenBase, nspkBase.ravel()])
                allLaserIntenResp[indlaser, indinten,
                                  indfreq] = np.mean(nspkResp)
                allLaserIntenRespMedian[indlaser, indinten,
                                        indfreq] = np.median(nspkResp)

            try:
                popt, pcov = optimize.curve_fit(
                    gaussian,  #Fit the curve for this intensity
                    np.log2(freqs),
                    spks,
                    p0=[
                        1,
                        np.log2(possiblefreqs[7]), 1,
                        allLaserIntenBase.mean()
                    ],
                    #bounds=([0, np.log2(possiblefreqs[0]), 0, 0],
                    #        [inf, np.log2(possiblefreqs[-1]), inf, inf])
                )
                popts.append(popt)  #Save the curve paramaters

                ## Calculate the R**2 value for the fit
                fittedSpks = gaussian(np.log2(freqs), *popt)
                residuals = spks - fittedSpks
                SSresidual = np.sum(residuals**2)
                SStotal = np.sum((spks - np.mean(spks))**2)
                Rsquared = 1 - (SSresidual / SStotal)
                Rsquareds.append(Rsquared)

            except RuntimeError:
                '''
                failed=True
                print "RUNTIME ERROR, Cell {}".format(indIter)
                runtimeErrorInds.append(indIter)
                thresholds[indIter] = None
                cfs[indIter] = None
                lowerFreqs[indIter] = None
                upperFreqs[indIter] = None
                '''
                print "RUNTIME ERROR, Cell {}".format(indIter)
                popts.append([np.nan, np.nan, np.nan, np.nan])
                Rsquareds.append(np.nan)
                continue

            #plt.figure()
            #print(gaussian(popt[1], *popt))
            #plt.plot(np.log2(freqs), gaussian(np.log2(freqs), *popt))
            #plt.show()

    print(popts)
    print(Rsquareds)
Beispiel #34
0
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[10:15, 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)
Beispiel #35
0
def tuning_curve(bdata, ephysData, gs):
    plt.subplot(gs[10:15, 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 * 2),
                         freq_avgs + (freq_sems * 2),
                         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)
Beispiel #36
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)
    '''
Beispiel #37
0
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]

        if spikeCountMat.shape[0] != len(trialsThisSecondVal):
            spikeCountMat = spikeCountMat[:-1, :]
            baseSpikeCountMat = baseSpikeCountMat[:-1, :]

        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
Beispiel #38
0
                            newTime=time.time(); print 'Elapsed time: {0:0.2f}  LOADED EVLOCKED DATA'.format(newTime-zeroTime); zeroTime=newTime; sys.stdout.flush()  ### PROFILER

                        else:
                            newTime=time.time(); print 'Elapsed time: {0:0.2f}  LOADED EPHYS/BEHAV one cell'.format(newTime-zeroTime); zeroTime=newTime; sys.stdout.flush()  ### PROFILER

                            (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
                                spikesanalysis.eventlocked_spiketimes(spkTimeStamps,EventOnsetTimes,timeRange)

                            #---- Save intermediate results somewhere, next time can just load it ----
                            np.savez(outputFullPath, spikeTimesFromEventOnset=spikeTimesFromEventOnset,
                                     trialIndexForEachSpike=trialIndexForEachSpike,
                                     indexLimitsEachTrial=indexLimitsEachTrial, timeRange=timeRange, alignment=alignment)
                            print 'Saved event-locked data to {0}'.format(outputFullPath)
                            newTime=time.time(); print 'Elapsed time: {0:0.2f}  Calculated EVLOCKED DATA'.format(newTime-zeroTime); zeroTime=newTime; sys.stdout.flush()  ### PROFILER

                        spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,countTimeRange)  #spike counts in the window of interest for modulation
                        spikeCountEachTrial = spikeCountMat.flatten() #spikeCountMat contains num of spikes in countTimeRange, each column is each trial, only one row because only given one time bin(countTimeRange)

                        freqLabels = ['Low','High']
                        for indf,freq in enumerate([lowFreq, highFreq]):

                            !!!### HERE GET SPIKE COUNT AVE BY BLOCK IN THIS WINDOW
                            trialsMoreLeft = trialsEachType[:,1] & freq & correct 
                            trialsMoreRight = trialsEachType[:,2] & freq & correct 
                            trialsEachCond = [trialsMoreRight,trialsMoreLeft]

                            # -- Calculate modulation index and significance p value -- #
                            spikeAvgRight = np.average(spikeCountEachTrial[trialsMoreRight])
                            spikeAvgLeft = np.average(spikeCountEachTrial[trialsMoreLeft])
                            if ((spikeAvgRight + spikeAvgLeft) == 0):
                                modIndex = 0.0
Beispiel #39
0
def evaluate_2afc_sound_response_celldb(cellDb):
    '''
    Analyse 2afc sound response: calculate sound response Z score for each freq, store frequencies presented and corresponding Z scores.
    '''
    if not ('behavZscore' in cellDb.columns):
        print 'Calculating sound response Z scores for 2afc session'

        behavDict = {
            'behavFreqs': [],
            'behavZscore': [],
            'behavPval': [],
            'behavRespIndex': [],
            'behavAveResp': []
        }
        #movementModI = np.zeros(len(cellDb)) #default value 0
        #movementModS = np.ones(len(cellDb)) #default value 1

        for indCell, cell in cellDb.iterrows():
            cellObj = ephyscore.Cell(cell)
            sessiontype = 'behavior'  #2afc behavior
            #ephysData, bata = cellObj.load(sessiontype)
            sessionInd = cellObj.get_session_inds(sessiontype)[0]
            bdata = cellObj.load_behavior_by_index(sessionInd)
            possibleFreq = np.unique(bdata['targetFrequency'])
            numFreqs = len(possibleFreq)

            try:
                ephysData = cellObj.load_ephys_by_index(sessionInd)
            except (ValueError, IOError) as error:
                print(error)
                spikeData = (0, 0)
                behavDict['behavFreqs'].append(possibleFreq)
                behavDict['behavZscore'].append(np.zeros(numFreqs))
                behavDict['behavPval'].append(np.ones(numFreqs))
                behavDict['behavRespIndex'].append(np.zeros(numFreqs))
                behavDict['behavAveResp'].append(np.zeros(numFreqs))
                continue

            eventsDict = ephysData['events']
            spikeTimestamps = ephysData['spikeTimes']

            if spikeTimestamps.ndim == 0:  #There is only one spike, ! spikesanalysis.eventlocked_spiketimes cannot handle only one spike !
                behavDict['behavFreqs'].append(possibleFreq)
                behavDict['behavZscore'].append(np.zeros(numFreqs))
                behavDict['behavPval'].append(np.ones(numFreqs))
                behavDict['behavRespIndex'].append(np.zeros(numFreqs))
                behavDict['behavAveResp'].append(np.zeros(numFreqs))
                continue

            soundOnsetTimes = eventsDict['{}On'.format(soundChannelType)]
            soundOnsetTimeBehav = bdata['timeTarget']

            # -- Check to see if ephys and behav recordings have same number of trials, remove missing trials from behav file -- #
            # Find missing trials
            missingTrials = behavioranalysis.find_missing_trials(
                soundOnsetTimes, soundOnsetTimeBehav)
            # Remove missing trials
            bdata.remove_trials(missingTrials)

            if len(soundOnsetTimes) != len(
                    bdata['timeTarget']
            ):  #some error not handled by remove missing trials
                behavDict['behavFreqs'].append(possibleFreq)
                behavDict['behavZscore'].append(np.zeros(numFreqs))
                behavDict['behavPval'].append(np.ones(numFreqs))
                behavDict['behavRespIndex'].append(np.zeros(numFreqs))
                behavDict['behavAveResp'].append(np.zeros(numFreqs))
                continue

            # -- Calculate Z score of sound response for each frequency -- #
            zScores = []
            pVals = []
            responseEachFreq = []
            responseInds = []

            for freq in possibleFreq:
                # -- Only use valid trials of one frequency to estimate response index -- #
                oneFreqTrials = (bdata['targetFrequency']
                                 == freq) & bdata['valid'].astype('bool')
                oneFreqSoundOnsetTimes = soundOnsetTimes[oneFreqTrials]
                (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
                    spikesanalysis.eventlocked_spiketimes(spikeTimestamps,oneFreqSoundOnsetTimes,timeRange)
                # Generate the spkCountMatrix where each row is one trial, each column is a time bin to count spikes in, in this case one time bin for baseline and one time bin for sound period
                #pdb.set_trace()
                nspkBase = spikesanalysis.spiketimes_to_spikecounts(
                    spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange)
                nspkResp = spikesanalysis.spiketimes_to_spikecounts(
                    spikeTimesFromEventOnset, indexLimitsEachTrial, respRange)
                print nspkBase.shape, nspkResp.shape

                # Calculate response index (S-B)/(S+B) where S and B are ave response during the sound window and baseline window, respectively
                responseIndex = (np.mean(nspkResp) - np.mean(nspkBase)) / (
                    np.mean(nspkResp) + np.mean(nspkBase))
                responseInds.append(responseIndex)
                responseEachFreq.append(np.mean(
                    nspkResp))  #Store mean response to each stim frequency
                print 'ave firing rate for baseline and sound periods are', np.mean(
                    nspkBase), np.mean(
                        nspkResp), 'response index is', responseIndex

                # Calculate statistic using ranksums test
                zStat, pValue = stats.ranksums(nspkResp, nspkBase)
                print zStat, pValue
                zScores.append(zStat)
                pVals.append(pValue)

            behavDict['behavFreqs'].append(possibleFreq)
            behavDict['behavZscore'].append(zScores)
            behavDict['behavPval'].append(pVals)
            behavDict['behavRespIndex'].append(responseInds)
            behavDict['behavAveResp'].append(responseEachFreq)

    return behavDict
                                                                        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)

    #Filter and average the response spikes by the condition matrix
    conditionMatShape = np.shape(trialsEachCondition)
    numRepeats = np.product(conditionMatShape[1:])
    nSpikesMat = np.reshape(nspkResp.squeeze().repeat(numRepeats), conditionMatShape)
    spikesFilteredByTrialType = nSpikesMat * trialsEachCondition
    avgRespArray = np.sum(spikesFilteredByTrialType, 0) / np.sum(
        trialsEachCondition, 0).astype('float')

    thresholdFRA=0.2
    thresholdResponse = nspkBase.mean() + thresholdFRA*(avgRespArray.max()-nspkBase.mean())
def plot_gaussian(cell, gs):
    laserTuningSessionInds = cell.get_session_inds('laserTuningCurve')

    if len(laserTuningSessionInds) != 0:
        for sessionInd in laserTuningSessionInds:
            bdata = cell.load_behavior_by_index(sessionInd)
            ephysData = cell.load_ephys_by_index(sessionInd)
    else:
        return

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

    timeRange = [-0.3, 0.6]
    baseTimeRange = [0.0, 0.1]
    alignmentRange = [baseTimeRange[0], timeRange[1]]   

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

    #Init list to hold the optimized parameters for the gaussian for each intensity and laser
    popts = []
    Rsquareds = []

    #Init arrays to hold the baseline and response spike counts per condition
    allLaserIntenBase = np.array([])
    allLaserIntenResp = np.empty((len(possiblelaser), len(possibleInts), len(possiblefreqs)))
    allLaserIntenRespMedian = np.empty((len(possiblelaser), len(possibleInts), len(possiblefreqs)))

    for indlaser, laser in enumerate(possiblelaser):
        for indinten, inten in enumerate(possibleInts):
            spks = np.array([])
            freqs = np.array([])
            base = np.array([])
            for indfreq, freq in enumerate(possiblefreqs):
                selectinds = np.flatnonzero((freqEachTrial==freq)&(intEachTrial==inten)&(laserEachTrial==laser))
                selectedOnsetTimes = eventOnsetTimes[selectinds]
                (spikeTimesFromEventOnset,
                trialIndexForEachSpike,
                indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(spikeTimeStamps,
                                                                            selectedOnsetTimes,
                                                                            alignmentRange)
                nspkBase = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,
                                                                    indexLimitsEachTrial,
                                                                    baseTimeRange)
                nspkResp = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,
                                                                    indexLimitsEachTrial,
                                                                    timeRange)
                base = np.concatenate([base, nspkBase.ravel()])
                spks = np.concatenate([spks, nspkResp.ravel()])
                # inds = np.concatenate([inds, np.ones(len(nspkResp.ravel()))*indfreq])
                freqs = np.concatenate([freqs, np.ones(len(nspkResp.ravel()))*freq])
                allLaserIntenBase = np.concatenate([allLaserIntenBase, nspkBase.ravel()])
                allLaserIntenResp[indlaser, indinten, indfreq] = np.mean(nspkResp)
                allLaserIntenRespMedian[indlaser, indinten, indfreq] = np.median(nspkResp)

            try:
                popt, pcov = optimize.curve_fit(gaussian, #Fit the curve for this intensity
                                                np.log2(freqs),
                                                spks,
                                                p0=[1, np.log2(possiblefreqs[7]), 1, allLaserIntenBase.mean()],
                                                #bounds=([0, np.log2(possiblefreqs[0]), 0, 0],
                                                #        [inf, np.log2(possiblefreqs[-1]), inf, inf])
                                                )
                popts.append(popt) #Save the curve paramaters

                ## Calculate the R**2 value for the fit
                fittedSpks = gaussian(np.log2(freqs), *popt)
                residuals = spks - fittedSpks
                SSresidual = np.sum(residuals**2)
                SStotal = np.sum((spks-np.mean(spks))**2)
                Rsquared = 1-(SSresidual/SStotal)
                Rsquareds.append(Rsquared)

            except RuntimeError:
                '''
                failed=True
                print "RUNTIME ERROR, Cell {}".format(indIter)
                runtimeErrorInds.append(indIter)
                thresholds[indIter] = None
                cfs[indIter] = None
                lowerFreqs[indIter] = None
                upperFreqs[indIter] = None
                '''
                print "RUNTIME ERROR, Cell {}".format(indIter)
                popts.append([np.nan, np.nan, np.nan, np.nan])
                Rsquareds.append(np.nan)
                continue
            
            #plt.figure()
            #print(gaussian(popt[1], *popt))
            #plt.plot(np.log2(freqs), gaussian(np.log2(freqs), *popt))
            #plt.show()



    print(popts)
    print(Rsquareds)
                    (binsize / 1000.0)
                ])

            binEdges = np.around(np.arange(
                noiseTimeRange[0] - (binsize / 1000.0),
                noiseTimeRange[1] + 2 * (binsize / 1000.0),
                (binsize / 1000.0)),
                                 decimals=2)

            if thisCellTypePSTHs is None:
                thisCellTypePSTHs = []
                thisCellTypeLaserPSTHs = []
                thisCellTypePSTHs2 = []
                thisCellTypeLaserPSTHs2 = []
            noiseSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
                noiseSpikeTimesFromEventOnset, noiseIndexLimitsEachTrial,
                binEdges)
            laserSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
                laserSpikeTimesFromEventOnset, laserIndexLimitsEachTrial,
                binEdges)

            thisNoisePSTH = np.mean(noiseSpikeCountMat, axis=0)
            thisLaserPSTH = np.mean(laserSpikeCountMat, axis=0)

            if (thisNoisePSTH[0] != 0) and (thisLaserPSTH[0] != 0):
                thisNoisePSTH1 = thisNoisePSTH / thisNoisePSTH[
                    0]  #normalise so baseline is 1
                thisLaserPSTH1 = thisLaserPSTH / thisLaserPSTH[0]

                thisCellTypePSTHs.append(thisNoisePSTH1)
                thisCellTypeLaserPSTHs.append(thisLaserPSTH1)
Beispiel #43
0
     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 = best_window_freq_tuning(spikeTimesFromEventOnset, indexLimitsEachTrial, trialsEachFreqHighInt)
     spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, tuningWindow)
     tuningSpikeRates = (spikeCountMat[trialsHighInt].flatten())/(tuningWindow[1]-tuningWindow[0])
     freqsThisIntensity = freqEachTrial[trialsHighInt]
     freqFit, thisRsquared = gaussian_tuning_fit(np.log2(freqsThisIntensity), tuningSpikeRates)
     if freqFit is not None:
         bestFreq = 2**freqFit[0]
         bandIndex, octavesFromBest = best_index(cellObj, bestFreq, sessionType)
     else:
         freqFit = np.zeros(4)
         bestFreq = np.nan
         bandIndex = np.nan
         octavesFromBest = np.nan
 gaussFit.append(freqFit)
 tuningTimeRange.append(tuningWindow)
 Rsquared[indRow] = thisRsquared
 prefFreq[indRow] = bestFreq
Beispiel #44
0
def plot_rew_change_byblock_per_cell(oneCell,
                                     trialLimit=[],
                                     alignment='sound',
                                     choiceSide='both'):
    '''
    Plots ephys data during behavior (reward_change_freq_discrim paradigm), data split according to the block in behavior and the choice (left or right). only plotting correct trials.
    oneCell is an CellInfo object as in celldatabase.
    'trialLimit' (e.g. [0, 600]) is the indecies of trials wish to be plotted.
    'choiceSide' is a string, either 'left' or 'right', to plot leftward and rightward trials, respectively. If not provided, will plot both sides.
    'alignment' selects which event to align spike data to, should be 'sound', 'center-out', or 'side-in'.
    '''

    SAMPLING_RATE = 30000.0
    soundTriggerChannel = 0  # channel 0 is the sound presentation, 1 is the trial
    binWidth = 0.010  # Size of each bin in histogram in seconds

    #timeRange = [-0.2,0.8] # In seconds. Time range for rastor plot to plot spikes (around some event onset as 0)
    #timeRange = [-0.25,1.0]
    timeRange = [-0.4, 1.2]

    bdata = load_behav_per_cell(oneCell)
    currentBlock = bdata['currentBlock']

    if currentBlock[0] == bdata.labels['currentBlock']['more_left']:
        startMoreLeft = True
    else:
        startMoreLeft = False
    blockTypes = [
        bdata.labels['currentBlock']['more_left'],
        bdata.labels['currentBlock']['more_right']
    ]
    if (not len(trialLimit)):
        validTrials = np.ones(len(currentBlock), dtype=bool)
    else:
        validTrials = np.zeros(len(currentBlock), dtype=bool)
        validTrials[trialLimit[0]:trialLimit[1]] = 1

    bdata.find_trials_each_block()
    trialsEachBlock = bdata.blocks['trialsEachBlock']
    #print trialsEachBlock
    nBlocks = bdata.blocks['nBlocks']

    #blockLabels = ['more_left', 'more_right']
    rightward = bdata['choice'] == bdata.labels['choice']['right']
    leftward = bdata['choice'] == bdata.labels['choice']['left']
    invalid = bdata['outcome'] == bdata.labels['outcome']['invalid']
    correct = bdata['outcome'] == bdata.labels['outcome']['correct']
    incorrect = bdata['outcome'] == bdata.labels['outcome']['error']
    ######Split left and right trials into correct and  incorrect categories to look at error trials#########
    rightcorrect = rightward & correct & validTrials
    leftcorrect = leftward & correct & validTrials
    #righterror = rightward&incorrect&validTrials
    #lefterror = leftward&incorrect&validTrials

    ####construct trialsEachCond and colorEachCond for ploting####
    for block in range(nBlocks):
        rightcorrectThisBlock = rightcorrect & trialsEachBlock[:, block]
        leftcorrectThisBlock = leftcorrect & trialsEachBlock[:, block]
        #trialTypeVec = leftcorrect*1+rightcorrect*2
        #trialTypePossibleValues = [1,2] #1 stands for left correct, 2 stands for right correct

        #trialsEachTypeEachBlock = behavioranalysis.find_trials_each_type_each_block(trialTypeVec, trialTypePossibleValues,currentBlock,blockTypes)

        if block == 0:
            #trialsEachCond=np.c_[leftcorrectThisBlock,rightcorrectThisBlock]
            if choiceSide == 'right':
                trialsEachCond = np.c_[rightcorrectThisBlock]
            elif choiceSide == 'left':
                trialsEachCond = np.c_[leftcorrectThisBlock]
            elif choiceSide == 'both':
                trialsEachCond = np.c_[leftcorrectThisBlock,
                                       rightcorrectThisBlock]

        else:
            if choiceSide == 'right':
                trialsEachCond = np.c_[trialsEachCond, rightcorrectThisBlock]
            elif choiceSide == 'left':
                trialsEachCond = np.c_[trialsEachCond, leftcorrectThisBlock]
            elif choiceSide == 'both':
                trialsEachCond = np.c_[trialsEachCond, leftcorrectThisBlock,
                                       rightcorrectThisBlock]

        if choiceSide == 'right':
            if startMoreLeft:
                colorEachCond = ['r', 'b', 'r', 'b', 'r', 'b', 'r', 'b']
            else:
                colorEachCond = ['b', 'r', 'b', 'r', 'b', 'r', 'b', 'r']
        elif choiceSide == 'left':
            if startMoreLeft:
                colorEachCond = ['g', 'm', 'g', 'm', 'g', 'm', 'g', 'm']
            else:
                colorEachCond = ['m', 'g', 'm', 'g', 'm', 'g', 'm', 'g']
        elif choiceSide == 'both':
            if startMoreLeft:
                colorEachCond = [
                    'g', 'r', 'm', 'b', 'g', 'r', 'm', 'b', 'g', 'r', 'm', 'b',
                    'g', 'r', 'm', 'b', 'g', 'r', 'm', 'b', 'g', 'r', 'm', 'b',
                    'g', 'r', 'm', 'b'
                ]
            else:
                colorEachCond = [
                    'm', 'b', 'g', 'r', 'm', 'b', 'g', 'r', 'm', 'b', 'g', 'r',
                    'm', 'b', 'g', 'r', 'm', 'b', 'g', 'r', 'm', 'b', 'g', 'r',
                    'm', 'b', 'g', 'r'
                ]

    (spikeTimestamps, waveforms, eventOnsetTimes,
     eventData) = load_ephys_per_cell(oneCell)

    if alignment == 'sound':
        soundOnsetEvents = (eventData.eventID == 1) & (eventData.eventChannel
                                                       == soundTriggerChannel)
        EventOnsetTimes = eventOnsetTimes[soundOnsetEvents]
    elif alignment == 'center-out':
        soundOnsetEvents = (eventData.eventID == 1) & (eventData.eventChannel
                                                       == soundTriggerChannel)
        EventOnsetTimes = eventOnsetTimes[soundOnsetEvents]
        diffTimes = bdata['timeCenterOut'] - bdata['timeTarget']
        EventOnsetTimes += diffTimes
    elif alignment == 'side-in':
        soundOnsetEvents = (eventData.eventID == 1) & (eventData.eventChannel
                                                       == soundTriggerChannel)
        EventOnsetTimes = eventOnsetTimes[soundOnsetEvents]
        diffTimes = bdata['timeSideIn'] - bdata['timeTarget']
        EventOnsetTimes += diffTimes

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

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

    plt.figure()
    ###########Plot raster and PSTH#################
    ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2)
    pRaster, hcond, zline = extraplots.raster_plot(
        spikeTimesFromEventOnset,
        indexLimitsEachTrial,
        timeRange,
        trialsEachCond=trialsEachCond,
        colorEachCond=colorEachCond,
        fillWidth=None,
        labels=None)
    #plt.setp(pRaster, ms=0.8)
    plt.ylabel('Trials')
    plt.xlim(timeRange)
    fig_title = '{0}_{1}_TT{2}_c{3}_{4}_{5}'.format(oneCell.animalName,
                                                    oneCell.behavSession,
                                                    oneCell.tetrode,
                                                    oneCell.cluster, alignment,
                                                    choiceSide)
    plt.title(fig_title)

    timeVec = np.arange(timeRange[0], timeRange[-1], binWidth)

    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, timeVec)
    smoothWinSize = 3
    ax2 = plt.subplot2grid((3, 1), (2, 0), sharex=ax1)
    extraplots.plot_psth(spikeCountMat / binWidth,
                         smoothWinSize,
                         timeVec,
                         trialsEachCond=trialsEachCond,
                         colorEachCond=colorEachCond,
                         linestyle=None,
                         linewidth=1.5,
                         downsamplefactor=1)

    plt.xlabel('Time from sound onset (s)')
    plt.ylabel('Firing rate (spk/sec)')
    #plt.show()

    #fig_path=
    #full_fig_path = os.path.join(fig_path, fig_title)
    #print full_fig_path
    #plt.tight_layout()
    plt.gcf().set_size_inches((8.5, 11))
def calculate_latency(eventOnsetTimes, currentFreq, uniqFreq, currentIntensity,
                      uniqueIntensity, spikeTimes, indRow):
    """

    Args:
        eventOnsetTimes (np.array): Same size as the number of trials with each value being the time sound detector turned on
        currentFreq (np.array): Same size as number of trials presented with each value being a specific frequency for that trial
        currentIntensity (np.array): Same size as number of trials presented with each value being a specific intensity for that trial
        uniqueIntensity (np.array): Uses currentIntensity to find how many unique intensity values were presented and store each unique value
        uniqFreq (np.array): Uses currentFreq to find how many unique frequency values were presented and store each unique value
        spikeTimes (np.array): Each value is a time when a spike occurred; obtained from ephys data
        indRow (int): Row number of cell in database(DataFrame)

    Returns:
        respLatency (float): Time, in seconds, from when the stimulus is presented and the cell responds

    """

    trialsEachCondition = behavioranalysis.find_trials_each_combination(
        currentIntensity, uniqueIntensity, currentFreq, uniqFreq)

    baseRange = [-0.1, 0]
    responseRange = [0, 0.1]
    alignmentRange = [-0.2, 0.2]
    thresholdFRA = 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)

    # Filter and average the response spikes by the condition matrix
    conditionMatShape = np.shape(trialsEachCondition)
    numRepeats = np.product(conditionMatShape[1:])
    nSpikesMat = np.reshape(nspkResp.squeeze().repeat(numRepeats),
                            conditionMatShape)
    spikesFilteredByTrialType = nSpikesMat * trialsEachCondition
    avgRespArray = np.sum(spikesFilteredByTrialType, 0) / np.sum(
        trialsEachCondition, 0).astype('float')

    thresholdResponse = nspkBase.mean() + thresholdFRA * (avgRespArray.max() -
                                                          nspkBase.mean())

    if not np.any(avgRespArray > thresholdResponse):
        print("Nothing above the threshold")
        respLatency = np.nan
        return respLatency

    # Determine trials that come from a I/F pair with a response above the threshold
    fra = avgRespArray > thresholdResponse
    selectedTrials = np.any(trialsEachCondition[:, fra], axis=1)

    # -- Calculate response latency --
    indexLimitsSelectedTrials = indexLimitsEachTrial[:, selectedTrials]
    timeRangeForLatency = [-0.1, 0.1]
    try:
        (respLatency,
         interim) = spikesanalysis.response_latency(spikeTimesFromEventOnset,
                                                    indexLimitsSelectedTrials,
                                                    timeRangeForLatency,
                                                    threshold=0.5,
                                                    win=signal.hanning(11))
        # TODO capture the exception outside in the database file itself
    except IndexError:
        print("Index error for cell {}".format(
            indRow))  # If there are no spikes in the timeRangeForLatency
        respLatency = np.nan

    print('Response latency: {:0.1f} ms'.format(1e3 * respLatency))

    return respLatency
Beispiel #46
0
def plot_rew_change_per_cell(oneCell, trialLimit=[], alignment='sound'):
    '''
    Plots raster and PSTH for one cell during reward_change_freq_dis task, split by block; alignment parameter should be set to either 'sound', 'center-out', or 'side-in'.
    '''
    bdata = load_behav_per_cell(oneCell)
    currentBlock = bdata['currentBlock']
    blockTypes = [
        bdata.labels['currentBlock']['more_left'],
        bdata.labels['currentBlock']['more_right']
    ]
    #blockLabels = ['more_left', 'more_right']
    if (not len(trialLimit)):
        validTrials = np.ones(len(currentBlock), dtype=bool)
    else:
        validTrials = np.zeros(len(currentBlock), dtype=bool)
        validTrials[trialLimit[0]:trialLimit[1]] = 1

    trialsEachType = behavioranalysis.find_trials_each_type(
        currentBlock, blockTypes)
    (spikeTimestamps, waveforms, eventOnsetTimes,
     eventData) = load_ephys_per_cell(oneCell)

    if alignment == 'sound':
        soundOnsetEvents = (eventData.eventID == 1) & (eventData.eventChannel
                                                       == soundTriggerChannel)
        EventOnsetTimes = eventOnsetTimes[soundOnsetEvents]
    elif alignment == 'center-out':
        soundOnsetEvents = (eventData.eventID == 1) & (eventData.eventChannel
                                                       == soundTriggerChannel)
        EventOnsetTimes = eventOnsetTimes[soundOnsetEvents]
        diffTimes = bdata['timeCenterOut'] - bdata['timeTarget']
        EventOnsetTimes += diffTimes
    elif alignment == 'side-in':
        soundOnsetEvents = (eventData.eventID == 1) & (eventData.eventChannel
                                                       == soundTriggerChannel)
        EventOnsetTimes = eventOnsetTimes[soundOnsetEvents]
        diffTimes = bdata['timeSideIn'] - bdata['timeTarget']
        EventOnsetTimes += diffTimes

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

    rightward = bdata['choice'] == bdata.labels['choice']['right']
    leftward = bdata['choice'] == bdata.labels['choice']['left']
    invalid = bdata['outcome'] == bdata.labels['outcome']['invalid']

    correct = bdata['outcome'] == bdata.labels['outcome']['correct']
    incorrect = bdata['outcome'] == bdata.labels['outcome']['error']

    ######Split left and right trials into correct and  incorrect categories to look at error trials#########
    rightcorrect = rightward & correct & validTrials
    leftcorrect = leftward & correct & validTrials
    #righterror = rightward&incorrect&validTrials
    #lefterror = leftward&incorrect&validTrials

    rightcorrectBlockMoreLeft = rightcorrect & trialsEachType[:, 0]
    rightcorrectBlockMoreRight = rightcorrect & trialsEachType[:, 1]
    leftcorrectBlockMoreLeft = leftcorrect & trialsEachType[:, 0]
    leftcorrectBlockMoreRight = leftcorrect & trialsEachType[:, 1]

    trialsEachCond = np.c_[leftcorrectBlockMoreLeft, rightcorrectBlockMoreLeft,
                           leftcorrectBlockMoreRight,
                           rightcorrectBlockMoreRight]

    colorEachCond = ['g', 'r', 'm', 'b']
    #trialsEachCond = np.c_[invalid,leftcorrect,rightcorrect,lefterror,righterror]
    #colorEachCond = ['0.75','g','r','b','m']

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

    ###########Plot raster and PSTH#################
    plt.figure()
    ax1 = plt.subplot2grid((8, 5), (0, 0), rowspan=4, colspan=5)
    extraplots.raster_plot(spikeTimesFromEventOnset,
                           indexLimitsEachTrial,
                           timeRange,
                           trialsEachCond=trialsEachCond,
                           colorEachCond=colorEachCond,
                           fillWidth=None,
                           labels=None)
    plt.ylabel('Trials')
    plt.xlim(timeRange)

    plt.title('{0}_{1}_TT{2}_c{3}_{4}'.format(oneCell.animalName,
                                              oneCell.behavSession,
                                              oneCell.tetrode, oneCell.cluster,
                                              alignment))

    timeVec = np.arange(timeRange[0], timeRange[-1], binWidth)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, timeVec)
    smoothWinSize = 3
    ax2 = plt.subplot2grid((8, 5), (4, 0), colspan=5, rowspan=2, sharex=ax1)
    extraplots.plot_psth(spikeCountMat / binWidth,
                         smoothWinSize,
                         timeVec,
                         trialsEachCond=trialsEachCond,
                         colorEachCond=colorEachCond,
                         linestyle=None,
                         linewidth=3,
                         downsamplefactor=1)
    plt.xlabel('Time from {0} onset (s)'.format(alignment))
    plt.ylabel('Firing rate (spk/sec)')

    # -- Plot ISI histogram --
    plt.subplot2grid((8, 5), (6, 0), rowspan=1, colspan=2)
    spikesorting.plot_isi_loghist(spikeTimestamps)
    plt.ylabel('c%d' % oneCell.cluster, rotation=0, va='center', ha='center')
    plt.xlabel('')

    # -- Plot waveforms --
    plt.subplot2grid((8, 5), (7, 0), rowspan=1, colspan=3)
    spikesorting.plot_waveforms(waveforms)

    # -- Plot projections --
    plt.subplot2grid((8, 5), (6, 2), rowspan=1, colspan=3)
    spikesorting.plot_projections(waveforms)

    # -- Plot events in time --
    plt.subplot2grid((8, 5), (7, 3), rowspan=1, colspan=2)
    spikesorting.plot_events_in_time(spikeTimestamps)

    plt.subplots_adjust(wspace=0.7)

    #plt.show()
    #fig_path =
    #fig_name = 'TT{0}Cluster{1}{2}.png'.format(tetrode, cluster, '_2afc plot_each_type')
    #full_fig_path = os.path.join(fig_path, fig_name)
    #print full_fig_path
    plt.gcf().set_size_inches((8.5, 11))
Beispiel #47
0
def rasterBlock(oneCell):
    subject = oneCell.animalName
    behavSession = oneCell.behavSession
    ephysSession = oneCell.ephysSession
    ephysRoot = os.path.join(ephysRootDir, subject)

    # -- Load Behavior Data --
    behaviorFilename = loadbehavior.path_to_behavior_data(
        subject, experimenter, paradigm, behavSession)
    bdata = loadbehavior.FlexCategBehaviorData(behaviorFilename)
    bdata.find_trials_each_block()

    # -- Load event data and convert event timestamps to ms --
    ephysDir = os.path.join(ephysRoot, ephysSession)
    eventFilename = os.path.join(ephysDir, 'all_channels.events')
    events = loadopenephys.Events(eventFilename)  # Load events data
    eventTimes = np.array(events.timestamps) / SAMPLING_RATE

    soundOnsetEvents = (events.eventID == 1) & (events.eventChannel
                                                == soundTriggerChannel)

    # -- Load Spike Data From Certain Cluster --
    spkData = ephyscore.CellData(oneCell)
    spkTimeStamps = spkData.spikes.timestamps

    eventOnsetTimes = eventTimes[soundOnsetEvents]

    correct = bdata['outcome'] == bdata.labels['outcome']['correct']

    possibleFreq = np.unique(bdata['targetFrequency'])
    oneFreq = bdata['targetFrequency'] == possibleFreq[middleFreq]

    correctOneFreq = oneFreq & correct
    correctTrialsEachBlock = bdata.blocks[
        'trialsEachBlock'] & correctOneFreq[:, np.newaxis]

    #trialsEachCond = np.c_[invalid,leftward,rightward]; colorEachCond = ['0.75','g','r']
    #trialsEachCond = np.c_[leftward,rightward]; colorEachCond = ['0.5','0.7','0']
    trialsEachCond = correctTrialsEachBlock

    if bdata['currentBlock'][0] == bdata.labels['currentBlock'][
            'low_boundary']:
        colorEachBlock = 3 * ['g', 'r']
    else:
        colorEachBlock = 3 * ['r', 'g']


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

    #plot(spikeTimesFromEventOnset,trialIndexForEachSpike,'.')

    plt.clf()
    ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2)
    extraplots.raster_plot(spikeTimesFromEventOnset,
                           indexLimitsEachTrial,
                           timeRange,
                           trialsEachCond=correctTrialsEachBlock,
                           colorEachCond=colorEachBlock,
                           fillWidth=None,
                           labels=None)
    #plt.yticks([0,trialsEachCond.sum()])
    #ax1.set_xticklabels([])
    plt.ylabel('Trials')

    timeVec = np.arange(timeRange[0], timeRange[-1], binWidth)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, timeVec)

    smoothWinSize = 3
    ax2 = plt.subplot2grid((3, 1), (2, 0), sharex=ax1)

    extraplots.plot_psth(spikeCountMat / binWidth,
                         smoothWinSize,
                         timeVec,
                         trialsEachCond=correctTrialsEachBlock,
                         colorEachCond=colorEachBlock,
                         linestyle=None,
                         linewidth=3,
                         downsamplefactor=1)

    plt.xlabel('Time from sound onset (s)')
    plt.ylabel('Firing rate (spk/sec)')

    #plt.show()

    nameFreq = str(possibleFreq[middleFreq])
    tetrodeClusterName = 'T' + str(oneCell.tetrode) + 'c' + str(
        oneCell.cluster)
    plt.gcf().set_size_inches((8.5, 11))
    figformat = 'png'  #'png' #'pdf' #'svg'
    filename = 'block_%s_%s_%s_%s.%s' % (
        subject, behavSession, tetrodeClusterName, nameFreq, figformat)
    fulloutputDir = outputDir + subject + '/'
    fullFileName = os.path.join(fulloutputDir, filename)

    directory = os.path.dirname(fulloutputDir)
    if not os.path.exists(directory):
        os.makedirs(directory)
    print 'saving figure to %s' % fullFileName
    plt.gcf().savefig(fullFileName, format=figformat)
Beispiel #48
0
                   fontsize=fontSizeLabels,
                   labelpad=labelDis)
        plt.title('Tuning curve', fontsize=fontSizeLabels)

        # -- Plot tuning PSTH -- #
        ax2 = plt.subplot(gs00[2, :])
        freqScaleFactor = 3  #factor to reduce number of frequencies plotted by
        possibleFreq = possibleFreq[
            1::freqScaleFactor]  #select just a subset of frequencies to plot
        labels = ['%.1f' % f for f in np.unique(possibleFreq) / 1000.0]
        numFreqs = len(possibleFreq)
        trialsEachFreq = behavioranalysis.find_trials_each_type(
            freqEachTrial, possibleFreq)

        timeVec = np.arange(timeRange[0], timeRange[-1], binWidth)
        spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
            spikeTimesFromEventOnset, indexLimitsEachTrial, timeVec)
        cm_subsection = np.linspace(0.0, 1.0, numFreqs)
        colorEachCond = [colormapTuning(x) for x in cm_subsection]
        pPSTH = extraplots.plot_psth(spikeCountMat / binWidth,
                                     smoothWinSizePsth,
                                     timeVec,
                                     trialsEachCond=trialsEachFreq,
                                     colorEachCond=colorEachCond,
                                     linestyle=None,
                                     linewidth=lwPsth,
                                     downsamplefactor=downsampleFactorPsth)

        for ind, line in enumerate(pPSTH):
            plt.setp(line, label=labels[ind])
        plt.legend(loc='upper right',
                   fontsize=fontSizeTicks,
Beispiel #49
0
def plot_tuning_PSTH_one_intensity(oneCell,
                                   intensity=50.0,
                                   timeRange=[-0.5, 1],
                                   binWidth=0.010,
                                   halfFreqs=True):
    #calls load_remote_tuning_data(oneCell) to get the data, then plot raster
    eventOnsetTimes, spikeTimestamps, bdata = load_remote_tuning_data(
        oneCell, BEHAVDIR_MOUNTED, EPHYSDIR_MOUNTED)
    freqEachTrial = bdata['currentFreq']
    intensityEachTrial = bdata['currentIntensity']
    possibleIntensity = np.unique(intensityEachTrial)
    if len(possibleIntensity) != 1:
        intensity = intensity  #50dB is the stimulus intensity used in 2afc task
        ###Just select the trials with a given intensity###
        trialsThisIntensity = [intensityEachTrial == intensity]
        freqEachTrial = freqEachTrial[trialsThisIntensity]
        intensityEachTrial = intensityEachTrial[trialsThisIntensity]
        eventOnsetTimes = eventOnsetTimes[trialsThisIntensity]
    possibleFreq = np.unique(freqEachTrial)
    if halfFreqs:
        possibleFreq = possibleFreq[
            1::3]  #slice to get every other frequence presented
    numFreqs = len(possibleFreq)
    #print len(intensityEachTrial),len(eventOnsetTimes),len(spikeTimestamps)
    trialsEachFreq = behavioranalysis.find_trials_each_type(
        freqEachTrial, possibleFreq)
    #pdb.set_trace()  #for debug

    #colormap = plt.cm.gist_ncar
    #colorEachFreq = [colormap(i) for i in np.linspace(0, 0.9, numFreqs)]
    #from jaratoolbox.colorpalette import TangoPalette as Tango
    #colorEachFreq = [Tango['Aluminium3'], Tango['Orange2'],Tango['Chameleon1'],Tango['Plum1'],Tango['Chocolate1'],Tango['SkyBlue2'],Tango['ScarletRed1'],'k']
    #Creat colorEachCond from color map
    from matplotlib import cm
    cm_subsection = np.linspace(0.0, 1.0, numFreqs)
    colorEachFreq = [cm.winter(x) for x in cm_subsection]

    #Create legend
    import matplotlib.patches as mpatches
    handles = []
    for (freq, color) in zip(possibleFreq, colorEachFreq):
        patch = mpatches.Patch(color=color, label=str(freq) + ' Hz')
        handles.append(patch)

    (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
        spikesanalysis.eventlocked_spiketimes(spikeTimestamps,eventOnsetTimes,timeRange)
    timeVec = np.arange(timeRange[0], timeRange[-1], binWidth)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, timeVec)
    smoothWinSize = 3
    #plt.figure()
    extraplots.plot_psth(spikeCountMat / binWidth,
                         smoothWinSize,
                         timeVec,
                         trialsEachCond=trialsEachFreq,
                         colorEachCond=colorEachFreq,
                         linestyle=None,
                         linewidth=2,
                         downsamplefactor=1)
    extraplots.set_ticks_fontsize(ax=plt.gca(), fontSize=14)
    plt.xlim(timeRange[0] + 0.1, timeRange[1])
    plt.legend(handles=handles, loc=2)
    plt.xlabel('Time from sound onset (s)', fontsize=18)
    plt.ylabel('Firing rate (spk/sec)', fontsize=18)
Beispiel #50
0
def plot_blind_cell_quality(cell):
    plt.clf()
    gs = gridspec.GridSpec(5, 6)

    #create cell object for loading data
    cellObj = ephyscore.Cell(cell)
    # -- plot laser pulse raster --
    laserEphysData, noBehav = cellObj.load('laserPulse')
    laserEventOnsetTimes = laserEphysData['events']['laserOn']
    laserSpikeTimestamps = laserEphysData['spikeTimes']
    timeRange = [-0.1, 0.4]

    plt.subplot(gs[0:2, 0:3])
    laserSpikeTimesFromEventOnset, trialIndexForEachSpike, laserIndexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        laserSpikeTimestamps, laserEventOnsetTimes, timeRange)
    pRaster, hcond, zline = extraplots.raster_plot(
        laserSpikeTimesFromEventOnset, laserIndexLimitsEachTrial, timeRange)
    plt.xlabel('Time from laser onset (sec)')
    plt.title('Laser Pulse Raster')

    # -- plot laser pulse psth --
    plt.subplot(gs[2:4, 0:3])
    binsize = 10 / 1000.0
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        laserSpikeTimestamps, laserEventOnsetTimes,
        [timeRange[0] - binsize, timeRange[1]])
    binEdges = np.around(np.arange(timeRange[0] - binsize,
                                   timeRange[1] + 2 * binsize, binsize),
                         decimals=2)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges)
    pPSTH = extraplots.plot_psth(spikeCountMat / binsize, 1, binEdges[:-1])
    plt.xlim(timeRange)
    plt.xlabel('Time from laser onset (sec)')
    plt.ylabel('Firing Rate (Hz)')
    plt.title('Laser Pulse PSTH')

    # -- didn't record laser trains for some earlier sessions --
    if len(cellObj.get_session_inds('laserTrain')) > 0:
        # -- plot laser train raster --
        laserTrainEphysData, noBehav = cellObj.load('laserTrain')
        laserTrainEventOnsetTimes = laserTrainEphysData['events']['laserOn']
        laserTrainSpikeTimestamps = laserTrainEphysData['spikeTimes']
        laserTrainEventOnsetTimes = spikesanalysis.minimum_event_onset_diff(
            laserTrainEventOnsetTimes, 0.5)
        timeRange = [-0.2, 1.0]

        plt.subplot(gs[0:2, 3:])
        spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
            laserTrainSpikeTimestamps, laserTrainEventOnsetTimes, timeRange)
        pRaster, hcond, zline = extraplots.raster_plot(
            spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange)
        plt.xlabel('Time from laser onset (sec)')
        plt.title('Laser Train Raster')

        # -- plot laser train psth --
        plt.subplot(gs[2:4, 3:])
        binsize = 10 / 1000.0
        spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
            laserTrainSpikeTimestamps, laserTrainEventOnsetTimes,
            [timeRange[0] - binsize, timeRange[1]])
        binEdges = np.around(np.arange(timeRange[0] - binsize,
                                       timeRange[1] + 2 * binsize, binsize),
                             decimals=2)
        spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
            spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges)
        pPSTH = extraplots.plot_psth(spikeCountMat / binsize, 1, binEdges[:-1])
        plt.xlim(timeRange)
        plt.xlabel('Time from laser onset (sec)')
        plt.ylabel('Firing Rate (Hz)')
        plt.title('Laser Train PSTH')

    # -- show cluster analysis --
    #tsThisCluster, wavesThisCluster, recordingNumber = celldatabase.load_all_spikedata(cell)
    # -- Plot ISI histogram --
    plt.subplot(gs[4, 0:2])
    spikesorting.plot_isi_loghist(tsThisCluster)

    # -- Plot waveforms --
    plt.subplot(gs[4, 2:4])
    spikesorting.plot_waveforms(wavesThisCluster)

    # -- Plot events in time --
    plt.subplot(gs[4, 4:6])
    spikesorting.plot_events_in_time(tsThisCluster)
def plot_rew_change_byblock_per_cell(oneCell,trialLimit=[],alignment='sound',choiceSide='both'):
    '''
    Plots ephys data during behavior (reward_change_freq_discrim paradigm), data split according to the block in behavior and the choice (left or right). only plotting correct trials.
    oneCell is an CellInfo object as in celldatabase.
    'trialLimit' (e.g. [0, 600]) is the indecies of trials wish to be plotted.
    'choiceSide' is a string, either 'left' or 'right', to plot leftward and rightward trials, respectively. If not provided, will plot both sides.
    'alignment' selects which event to align spike data to, should be 'sound', 'center-out', or 'side-in'.
    '''
    
    SAMPLING_RATE=30000.0
    soundTriggerChannel = 0 # channel 0 is the sound presentation, 1 is the trial
    binWidth = 0.010 # Size of each bin in histogram in seconds

    #timeRange = [-0.2,0.8] # In seconds. Time range for rastor plot to plot spikes (around some event onset as 0)
    #timeRange = [-0.25,1.0]
    timeRange = [-0.4,1.2]
    
    bdata = load_behav_per_cell(oneCell)
    (spikeTimestamps,waveforms,eventOnsetTimes,eventData)=load_ephys_per_cell(oneCell)

    # -- Check to see if ephys has skipped trials, if so remove trials from behav data 
    soundOnsetEvents = (eventData.eventID==1) & (eventData.eventChannel==soundTriggerChannel)
    soundOnsetTimeEphys = eventOnsetTimes[soundOnsetEvents]
    soundOnsetTimeBehav = bdata['timeTarget']

    # Find missing trials
    missingTrials = behavioranalysis.find_missing_trials(soundOnsetTimeEphys,soundOnsetTimeBehav)
    # Remove missing trials
    bdata.remove_trials(missingTrials)
                
    currentBlock = bdata['currentBlock']
    
    if(not len(trialLimit)):
        validTrials = np.ones(len(currentBlock),dtype=bool)
    else:
        validTrials = np.zeros(len(currentBlock),dtype=bool)
        validTrials[trialLimit[0]:trialLimit[1]] = 1

    bdata.find_trials_each_block()
    trialsEachBlock = bdata.blocks['trialsEachBlock']
    #print trialsEachBlock
    nBlocks = bdata.blocks['nBlocks']

    #blockLabels = ['more_left', 'more_right']
    rightward = bdata['choice']==bdata.labels['choice']['right']
    leftward = bdata['choice']==bdata.labels['choice']['left']
    invalid = bdata['outcome']==bdata.labels['outcome']['invalid']
    correct = bdata['outcome']==bdata.labels['outcome']['correct'] 
    incorrect = bdata['outcome']==bdata.labels['outcome']['error'] 
    ######Split left and right trials into correct and  incorrect categories to look at error trials#########
    rightcorrect = rightward&correct&validTrials
    leftcorrect = leftward&correct&validTrials
    #righterror = rightward&incorrect&validTrials
    #lefterror = leftward&incorrect&validTrials
    colorEachCond=[]
    
    ####construct trialsEachCond and colorEachCond for ploting####
    for block in range(nBlocks):
        rightcorrectThisBlock = rightcorrect&trialsEachBlock[:,block]
        leftcorrectThisBlock = leftcorrect&trialsEachBlock[:,block]
        #trialTypeVec = leftcorrect*1+rightcorrect*2
        #trialTypePossibleValues = [1,2] #1 stands for left correct, 2 stands for right correct

        firstIndexThisBlock=np.nonzero(trialsEachBlock[:,block])[0][0]
        if currentBlock[firstIndexThisBlock]==bdata.labels['currentBlock']['more_left']:
            if choiceSide=='right':
                colorThisCond='r'
            elif choiceSide=='left':
                colorThisCond='g'
            elif choiceSide=='both':
                colorThisCond=['g','r']
        if currentBlock[firstIndexThisBlock]==bdata.labels['currentBlock']['more_right']:
            if choiceSide=='right':
                colorThisCond='b'
            elif choiceSide=='left':
                colorThisCond='m'
            elif choiceSide=='both':
                colorThisCond=['m','b']
        if currentBlock[firstIndexThisBlock]==bdata.labels['currentBlock']['same_reward']:
            if choiceSide=='right':
                colorThisCond='darkgray'
            elif choiceSide=='left':
                colorThisCond='y'
            elif choiceSide=='both':
                colorThisCond=['y','darkgray']

        #trialsEachTypeEachBlock = behavioranalysis.find_trials_each_type_each_block(trialTypeVec, trialTypePossibleValues,currentBlock,blockTypes)
        
        if block==0:
            #trialsEachCond=np.c_[leftcorrectThisBlock,rightcorrectThisBlock] 
            if choiceSide=='right':
                trialsEachCond=np.c_[rightcorrectThisBlock]
            elif choiceSide=='left':
                trialsEachCond=np.c_[leftcorrectThisBlock]              
            elif choiceSide=='both':
                trialsEachCond=np.c_[leftcorrectThisBlock,rightcorrectThisBlock]

        else:
            if choiceSide=='right':
                trialsEachCond=np.c_[trialsEachCond,rightcorrectThisBlock]
            elif choiceSide=='left':
                trialsEachCond=np.c_[trialsEachCond,leftcorrectThisBlock]              
            elif choiceSide=='both':
                trialsEachCond=np.c_[trialsEachCond,leftcorrectThisBlock,rightcorrectThisBlock]

        colorEachCond.append(colorThisCond)


    if alignment == 'sound':
        soundOnsetEvents = (eventData.eventID==1) & (eventData.eventChannel==soundTriggerChannel)
        EventOnsetTimes = eventOnsetTimes[soundOnsetEvents]
    elif alignment == 'center-out':
        soundOnsetEvents = (eventData.eventID==1) & (eventData.eventChannel==soundTriggerChannel)
        EventOnsetTimes = eventOnsetTimes[soundOnsetEvents]
        diffTimes=bdata['timeCenterOut']-bdata['timeTarget']
        EventOnsetTimes+=diffTimes
    elif alignment == 'side-in':
        soundOnsetEvents = (eventData.eventID==1) & (eventData.eventChannel==soundTriggerChannel)
        EventOnsetTimes = eventOnsetTimes[soundOnsetEvents]
        diffTimes=bdata['timeSideIn']-bdata['timeTarget']
        EventOnsetTimes+=diffTimes
            
    freqEachTrial = bdata['targetFrequency']
    possibleFreq = np.unique(freqEachTrial)
            
    (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
    spikesanalysis.eventlocked_spiketimes(spikeTimestamps,EventOnsetTimes,timeRange)

    plt.figure()
    ###########Plot raster and PSTH#################
    ax1 =  plt.subplot2grid((3,1), (0, 0), rowspan=2)
    pRaster,hcond,zline =extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange,trialsEachCond=trialsEachCond,
                       colorEachCond=colorEachCond,fillWidth=None,labels=None)
    #plt.setp(pRaster, ms=0.8)
    plt.ylabel('Trials')
    plt.xlim(timeRange)
    fig_title='{0}_{1}_TT{2}_c{3}_{4}_{5}'.format(oneCell.animalName,oneCell.behavSession,oneCell.tetrode,oneCell.cluster,alignment,choiceSide)
    plt.title(fig_title)

    timeVec = np.arange(timeRange[0],timeRange[-1],binWidth)

    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,timeVec)
    smoothWinSize = 3
    ax2 = plt.subplot2grid((3,1), (2, 0), sharex=ax1)
    extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=trialsEachCond,
                     colorEachCond=colorEachCond,linestyle=None,linewidth=1.5,downsamplefactor=1)

    plt.xlabel('Time from sound onset (s)')
    plt.ylabel('Firing rate (spk/sec)')
    #plt.show()
    
    #fig_path= 
    #full_fig_path = os.path.join(fig_path, fig_title)
    #print full_fig_path
    #plt.tight_layout()
    plt.gcf().set_size_inches((8.5,11))
Beispiel #52
0
def plot_bandwidth_report(cell, bandIndex, type='normal'):
    plt.clf()
    if bandIndex is None:
        print 'No bandwidth session given'
        return

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

    #change dimensions of report to add laser trials if they exist
    if len(cellObj.get_session_inds('laserPulse')) > 0:
        laser = True
        gs = gridspec.GridSpec(13, 6)
    else:
        laser = False
        gs = gridspec.GridSpec(9, 6)
    offset = 4 * laser
    gs.update(left=0.15, right=0.85, top=0.96, wspace=0.7, hspace=1.0)

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

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

    timeRange = [-0.2, 1.5]
    bandEachTrial = bandBData['currentBand']
    numBands = np.unique(bandEachTrial)

    #change the trial type that the bandwidth session is split by so we can use this report for Arch-inactivation experiments
    #also changes the colours to be more thematically appropriate! (in Anna's opinion)
    if type == 'laser':
        secondSort = bandBData['laserTrial']
        secondSortLabels = ['no laser', 'laser']
        colours = ['k', '#c4a000']
        errorColours = ['0.5', '#fce94f']
        gaussFitCol = 'gaussFit'
        tuningR2Col = 'tuningFitR2'
    elif type == 'normal':
        secondSort = bandBData['currentAmp']
        secondSortLabels = [
            '{} dB'.format(amp) for amp in np.unique(secondSort)
        ]
        colours = ['#4e9a06', '#5c3566']
        errorColours = ['#8ae234', '#ad7fa8']
        gaussFitCol = 'gaussFit'
        tuningR2Col = 'tuningFitR2'

    charfreq = str(np.unique(bandBData['charFreq'])[0] / 1000)
    modrate = str(np.unique(bandBData['modRate'])[0])
    numBands = np.unique(bandEachTrial)

    # -- plot rasters of the bandwidth trials --
    rasterColours = [
        np.tile([colours[0], errorColours[0]],
                len(numBands) / 2 + 1),
        np.tile([colours[1], errorColours[1]],
                len(numBands) / 2 + 1)
    ]
    plot_separated_rasters(gs, [0, 3],
                           5 + offset,
                           bandEachTrial,
                           secondSort,
                           bandSpikeTimestamps,
                           bandEventOnsetTimes,
                           colours=rasterColours,
                           titles=secondSortLabels,
                           plotHeight=2)

    # -- plot bandwidth tuning curves --
    plt.subplot(gs[5 + offset:, 3:])
    timeRange = [0.2, 1.0]  # if type=='normal' else [0.1, 1.1]
    baseRange = [-1.1, -0.3]
    tuningDict = ephysanalysis.calculate_tuning_curve_inputs(
        bandSpikeTimestamps,
        bandEventOnsetTimes,
        bandEachTrial,
        secondSort,
        timeRange,
        info='plotting')
    plot_tuning_curve(tuningDict['responseArray'],
                      tuningDict['errorArray'],
                      numBands,
                      tuningDict['baselineSpikeRate'],
                      linecolours=colours,
                      errorcolours=errorColours)

    # load tuning ephys and behaviour data
    tuningEphysData, tuningBData = cellObj.load('tuningCurve')
    tuningEventOnsetTimes = ephysanalysis.get_sound_onset_times(
        tuningEphysData, 'tuningCurve')
    tuningSpikeTimestamps = tuningEphysData['spikeTimes']

    # -- plot frequency tuning at intensity used in bandwidth trial with gaussian fit --

    # high amp bandwidth trials used to select appropriate frequency
    maxAmp = max(np.unique(bandBData['currentAmp']))
    if maxAmp < 1:
        maxAmp = 66.0  #HARDCODED dB VALUE FOR SESSIONS DONE BEFORE NOISE CALIBRATION

    # find tone intensity that corresponds to tone sessions in bandwidth trial
    toneInt = maxAmp - 15.0  #HARDCODED DIFFERENCE IN TONE AND NOISE AMP BASED ON OSCILLOSCOPE READINGS FROM RIG 2

    freqEachTrial = tuningBData['currentFreq']

    plt.subplot(gs[2 + offset:4 + offset, 0:3])
    plot_tuning_fitted_gaussian(tuningSpikeTimestamps,
                                tuningEventOnsetTimes,
                                tuningBData,
                                toneInt,
                                cell[gaussFitCol],
                                cell[tuningR2Col],
                                timeRange=cell['tuningTimeRange'])

    # -- plot frequency tuning raster --
    plt.subplot(gs[0 + offset:2 + offset, 0:3])
    freqLabels = ["%.1f" % freq for freq in np.unique(freqEachTrial) / 1000.0]
    plot_sorted_raster(tuningSpikeTimestamps,
                       tuningEventOnsetTimes,
                       freqEachTrial,
                       timeRange=[-0.2, 0.6],
                       labels=freqLabels)
    plt.title('Frequency Tuning Raster')

    # -- plot AM PSTH --
    amEphysData, amBData = cellObj.load('AM')
    amEventOnsetTimes = ephysanalysis.get_sound_onset_times(amEphysData, 'AM')
    amSpikeTimestamps = amEphysData['spikeTimes']
    rateEachTrial = amBData['currentFreq']
    timeRange = [-0.2, 1.5]
    colourList = ['b', 'g', 'y', 'orange', 'r']

    plt.subplot(gs[2 + offset:4 + offset, 3:])
    plot_sorted_psth(amSpikeTimestamps,
                     amEventOnsetTimes,
                     rateEachTrial,
                     timeRange=[-0.2, 0.8],
                     binsize=25,
                     colorEachCond=colourList)
    plt.xlabel('Time from sound onset (sec)')
    plt.ylabel('Firing rate (Hz)')
    plt.title('AM PSTH')

    # -- plot AM raster --
    plt.subplot(gs[0 + offset:2 + offset, 3:])
    rateLabels = ["%.0f" % rate for rate in np.unique(rateEachTrial)]
    plot_sorted_raster(amSpikeTimestamps,
                       amEventOnsetTimes,
                       rateEachTrial,
                       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')

    # -- plot laser pulse and laser train data (if available) --
    if laser:
        # -- plot laser pulse raster --
        laserEphysData, noBehav = cellObj.load('laserPulse')
        laserEventOnsetTimes = laserEphysData['events']['laserOn']
        laserSpikeTimestamps = laserEphysData['spikeTimes']
        timeRange = [-0.1, 0.4]

        plt.subplot(gs[0:2, 0:3])
        laserSpikeTimesFromEventOnset, trialIndexForEachSpike, laserIndexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
            laserSpikeTimestamps, laserEventOnsetTimes, timeRange)
        pRaster, hcond, zline = extraplots.raster_plot(
            laserSpikeTimesFromEventOnset, laserIndexLimitsEachTrial,
            timeRange)
        plt.xlabel('Time from laser onset (sec)')
        plt.title('Laser Pulse Raster')

        # -- plot laser pulse psth --
        plt.subplot(gs[2:4, 0:3])
        binsize = 10 / 1000.0
        spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
            laserSpikeTimestamps, laserEventOnsetTimes,
            [timeRange[0] - binsize, timeRange[1]])
        binEdges = np.around(np.arange(timeRange[0] - binsize,
                                       timeRange[1] + 2 * binsize, binsize),
                             decimals=2)
        spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
            spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges)
        pPSTH = extraplots.plot_psth(spikeCountMat / binsize, 1, binEdges[:-1])
        plt.xlim(timeRange)
        plt.xlabel('Time from laser onset (sec)')
        plt.ylabel('Firing Rate (Hz)')
        plt.title('Laser Pulse PSTH')

        # -- didn't record laser trains for some earlier sessions --
        if len(cellObj.get_session_inds('laserTrain')) > 0:
            # -- plot laser train raster --
            laserTrainEphysData, noBehav = cellObj.load('laserTrain')
            laserTrainEventOnsetTimes = laserTrainEphysData['events'][
                'laserOn']
            laserTrainSpikeTimestamps = laserTrainEphysData['spikeTimes']
            laserTrainEventOnsetTimes = spikesanalysis.minimum_event_onset_diff(
                laserTrainEventOnsetTimes, 0.5)
            timeRange = [-0.2, 1.0]

            plt.subplot(gs[0:2, 3:])
            spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                laserTrainSpikeTimestamps, laserTrainEventOnsetTimes,
                timeRange)
            pRaster, hcond, zline = extraplots.raster_plot(
                spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange)
            plt.xlabel('Time from laser onset (sec)')
            plt.title('Laser Train Raster')

            # -- plot laser train psth --
            plt.subplot(gs[2:4, 3:])
            binsize = 10 / 1000.0
            spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                laserTrainSpikeTimestamps, laserTrainEventOnsetTimes,
                [timeRange[0] - binsize, timeRange[1]])
            binEdges = np.around(np.arange(timeRange[0] - binsize,
                                           timeRange[1] + 2 * binsize,
                                           binsize),
                                 decimals=2)
            spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
                spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges)
            pPSTH = extraplots.plot_psth(spikeCountMat / binsize, 1,
                                         binEdges[:-1])
            plt.xlim(timeRange)
            plt.xlabel('Time from laser onset (sec)')
            plt.ylabel('Firing Rate (Hz)')
            plt.title('Laser Train PSTH')

    # -- show cluster analysis --
    #tsThisCluster, wavesThisCluster, recordingNumber = celldatabase.load_all_spikedata(cell)
    # -- Plot ISI histogram --
    plt.subplot(gs[4 + offset, 0:2])
    spikesorting.plot_isi_loghist(bandSpikeTimestamps)

    # -- Plot waveforms --
    plt.subplot(gs[4 + offset, 2:4])
    spikesorting.plot_waveforms(bandEphysData['samples'])

    # -- Plot events in time --
    plt.subplot(gs[4 + offset, 4:6])
    spikesorting.plot_events_in_time(bandSpikeTimestamps)
    title = '{0}, {1}, {2}um, Tetrode {3}, Cluster {4}, {5}kHz, {6}Hz modulation'.format(
        cell['subject'], cell['date'], cell['depth'], tetrode, cluster,
        charfreq, modrate)

    plt.suptitle(title)

    fig_path = '/home/jarauser/Pictures/cell reports'
    fig_name = '{0}_{1}_{2}um_TT{3}Cluster{4}.png'.format(
        cell['subject'], cell['date'], cell['depth'], tetrode, cluster)
    full_fig_path = os.path.join(fig_path, fig_name)
    fig = plt.gcf()
    fig.set_size_inches(20, 25)
    fig.savefig(full_fig_path, format='png', bbox_inches='tight')
def inactivation_base_stats(db):
    '''
    This function takes as argument a pandas DataFrame and adds new columns.
    The filename should be the full path to where the database will be saved. If a filename is not specified, the database will not be saved.
    
    This function computed basic statistics for all clusters (e.g. laser responsiveness, sound responsiveness, preferred frequency).
    '''

    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)
            if spikeCountMat.shape[0] == len(trialsHighInt) + 1:
                spikeCountMat = spikeCountMat[:-1, :]
            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

    return db
def photoID_base_stats(db, filename=''):
    '''
    This function takes as argument a pandas DataFrame and adds new columns.
    The filename should be the full path to where the database will be saved. If a filename is not specified, the database will not be saved.
    
    This function computed basic statistics for all clusters (e.g. laser responsiveness, sound responsiveness, preferred frequency).
    '''
    soundLoc = []
    NaKpeakLatency = np.empty(len(db))

    laserTestStatistic = np.empty(len(db))
    laserPVal = np.empty(len(db))
    laserTrainTestStatistic = np.empty(len(db))
    laserTrainPVal = np.empty(len(db))
    laserChangeFR = 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))
    AMRate = 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, useModifiedClusters=True)
        print "Now processing", dbRow['subject'], dbRow['date'], dbRow[
            'depth'], dbRow['tetrode'], dbRow['cluster']

        # --- Determine if sound presentation was ipsi or contra to recording location ---
        soundSide = dbRow['info'][2]
        recordingSide = dbRow['brainArea']

        if (soundSide == 'sound_left' and recordingSide == 'left_AC') or (
                soundSide == 'sound_right' and recordingSide == 'right_AC'):
            soundLoc.append('ipsi')
        else:
            soundLoc.append('contra')

        # --- Determine time difference between Na and K peak (spike width) ---
        peakTimes = dbRow['spikePeakTimes']
        latency = peakTimes[2] - peakTimes[1]
        NaKpeakLatency[indRow] = latency

        # --- Determine laser responsiveness of each cell (using laser pulse) ---
        try:
            laserEphysData, noBehav = cellObj.load('laserPulse')
        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)
        laserTestStatistic[indRow] = testStatistic
        laserPVal[indRow] = pVal
        laserChangeFR[indRow] = changeFR

        # --- Determine laser responsiveness of each cell (using laser train) ---
        try:
            laserTrainEphysData, noBehav = cellObj.load('laserTrain')
        except IndexError:
            print "No laser train session for this cell"
            testStatistic = np.nan
            pVal = np.nan
        else:
            testStatistic, pVal, changeFR = funcs.laser_response(
                laserTrainEphysData)
        laserTrainTestStatistic[indRow] = testStatistic
        laserTrainPVal[indRow] = pVal

        # --- Determine sound responsiveness during bandwidth sessions and other statistics about bandwidth session---
        try:
            bandEphysData, bandBehavData = cellObj.load('bandwidth')
        except IndexError:
            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
            AM = np.nan
        else:
            bandEventOnsetTimes = funcs.get_sound_onset_times(
                bandEphysData, 'bandwidth')
            bandSpikeTimestamps = bandEphysData['spikeTimes']
            bandEachTrial = bandBehavData['currentBand']
            secondSort = bandBehavData['currentAmp']
            numBands = np.unique(bandEachTrial)
            numSec = np.unique(secondSort)
            AM = np.unique(bandBehavData['modRate'])

            trialsEachComb = behavioranalysis.find_trials_each_combination(
                bandEachTrial, numBands, secondSort, numSec)
            trialsEachBaseCond = trialsEachComb[:, :,
                                                -1]  #using high amp trials for photoidentified, no laser for inactivation
            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(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
        AMRate[indRow] = AM

        # --- 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.nan, 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)
            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, 'bandwidth')
            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['soundLocation'] = soundLoc
    db['spikeWidth'] = NaKpeakLatency
    db['AMRate'] = AMRate

    db['laserPVal'] = laserPVal
    db['laserUStat'] = laserTestStatistic
    db['laserTrainPVal'] = laserTrainPVal
    db['laserTrainUStat'] = laserTrainTestStatistic
    db['laserChangeFR'] = laserChangeFR

    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
Beispiel #55
0
def evaluate_tuning_sound_response_celldb(cellDb):
    '''
    Analyse tuning curve data: calculate sound response Z score for each freq, store frequencies presented and corresponding Z scores. 
    '''
    if not ('tuningZscore' in cellDb.columns):
        print 'Calculating sound response Z scores for tuning curve'
        # -- Aalyse tuning curve and 2afc data -- #
        tuningDict = {
            'tuningFreqs': [],
            'tuningZscore': [],
            'tuningPval': [],
            'tuningRespIndex': [],
            'tuningAveResp': []
        }

        for indCell, cell in cellDb.iterrows():
            cellObj = ephyscore.Cell(cell)
            sessiontype = 'tc'  #tuningcurve
            #ephysData, bata = cellObj.load(sessiontype)
            sessionInd = cellObj.get_session_inds(sessiontype)[0]
            bdata = cellObj.load_behavior_by_index(sessionInd)
            possibleFreq = np.unique(bdata['currentFreq'])
            numFreqs = len(possibleFreq)

            try:
                ephysData = cellObj.load_ephys_by_index(sessionInd)
            except (ValueError, IOError) as error:
                print(error)
                spikeData = (0, 0)
                tuningDict['tuningFreqs'].append(possibleFreq)
                tuningDict['tuningZscore'].append(np.zeros(numFreqs))
                tuningDict['tuningPval'].append(np.ones(numFreqs))
                tuningDict['tuningRespIndex'].append(np.zeros(numFreqs))
                tuningDict['tuningAveResp'].append(np.zeros(numFreqs))
                continue

            eventsDict = ephysData['events']
            spikeTimestamps = ephysData['spikeTimes']

            if spikeTimestamps.ndim == 0:  #There is only one spike, ! spikesanalysis.eventlocked_spiketimes cannot handle only one spike !
                tuningDict['tuningFreqs'].append(possibleFreq)
                tuningDict['tuningZscore'].append(np.zeros(numFreqs))
                tuningDict['tuningPval'].append(np.ones(numFreqs))
                tuningDict['tuningRespIndex'].append(np.zeros(numFreqs))
                tuningDict['tuningAveResp'].append(np.zeros(numFreqs))
                continue

            soundOnsetTimes = eventsDict['{}On'.format(soundChannelType)]

            if len(soundOnsetTimes) != len(bdata['currentFreq']):
                # This is a hack for when ephys is one trial longer than behavior
                if len(soundOnsetTimes) == len(bdata['currentFreq']) + 1:
                    soundOnsetTimes = soundOnsetTimes[:-1]
                else:
                    tuningDict['tuningFreqs'].append(possibleFreq)
                    tuningDict['tuningZscore'].append(np.zeros(numFreqs))
                    tuningDict['tuningPval'].append(np.ones(numFreqs))
                    tuningDict['tuningRespIndex'].append(np.zeros(numFreqs))
                    tuningDict['tuningAveResp'].append(np.zeros(numFreqs))

                    continue  #skip all subsequent analysis if the two files did not recorded same number of trials

            # -- Calculate Z score of sound response for each frequency -- #
            zScores = []
            pVals = []
            responseEachFreq = []
            responseInds = []
            for freq in possibleFreq:
                oneFreqTrials = bdata['currentFreq'] == freq
                oneFreqSoundOnsetTimes = soundOnsetTimes[oneFreqTrials]
                (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
                    spikesanalysis.eventlocked_spiketimes(spikeTimestamps,oneFreqSoundOnsetTimes,timeRange)
                # Generate the spkCountMatrix where each row is one trial, each column is a time bin to count spikes in, in this case only one time bin
                nspkBase = spikesanalysis.spiketimes_to_spikecounts(
                    spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange)
                nspkResp = spikesanalysis.spiketimes_to_spikecounts(
                    spikeTimesFromEventOnset, indexLimitsEachTrial, respRange)
                print nspkBase.shape, nspkResp.shape

                # Calculate response index (S-B)/(S+B) where S and B are ave response during the sound window and baseline window, respectively
                responseIndex = (np.mean(nspkResp) - np.mean(nspkBase)) / (
                    np.mean(nspkResp) + np.mean(nspkBase))
                responseInds.append(responseIndex)
                responseEachFreq.append(np.mean(
                    nspkResp))  #Store mean response to each stim frequency
                print 'ave firing rate for baseline and sound periods are', np.mean(
                    nspkBase), np.mean(
                        nspkResp), 'response index is', responseIndex

                # Calculate statistic using ranksums test
                [zStat, pValue] = stats.ranksums(nspkResp, nspkBase)
                zScores.append(zStat)
                pVals.append(pValue)

            tuningDict['tuningFreqs'].append(possibleFreq)
            tuningDict['tuningZscore'].append(zScores)
            tuningDict['tuningPval'].append(pVals)
            tuningDict['tuningRespIndex'].append(responseInds)
            tuningDict['tuningAveResp'].append(responseEachFreq)

    return tuningDict
def calculate_phase_discrim_accuracy(spikeTimes,
                                     eventOnsetTimes,
                                     currentFreq,
                                     uniqFreq,
                                     shuffle=False):
    SHUFFLE = shuffle

    # Timerange for alignment?
    timeRange = [
        0.05, 0.5
    ]  # Ignoring onset responses TODO: Is this the best way to do this??

    phaseDiscrimAccuracy = {}
    for thisFreq in uniqFreq:

        # Only use events for this frequency
        eventsThisFreq = eventOnsetTimes[currentFreq == thisFreq]

        (spikeTimesFromEventOnset, trialIndexForEachSpike,
         indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(
             spikeTimes, eventsThisFreq, timeRange)

        # This is really all we need to do to bin things by phase.
        radsPerSec = thisFreq * 2 * np.pi
        spikeRads = (spikeTimesFromEventOnset * radsPerSec) % (2 * np.pi)

        strength, phase = signal.vectorstrength(spikeTimesFromEventOnset,
                                                1.0 / thisFreq)
        phase = (phase + 2 * np.pi) % (2 * np.pi)

        shiftedRads = ((spikeRads - phase) + 2.25 * np.pi)
        if any(shiftedRads < 0):
            raise ValueError("Some shifted rads below 0")
        # shiftedRads = ((spikeRads - phase) + 2.25*np.pi)%(2*np.pi)
        spikeRads = shiftedRads % (2 * np.pi)

        nBins = 4
        binEdges = np.arange(0, 2.01 * np.pi, 2 * np.pi /
                             nBins)  # The 2.01 makes it actually include 2pi
        spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
            spikeRads, indexLimitsEachTrial, binEdges)

        spikeCountMatCopy = copy.deepcopy(spikeCountMat)
        spikeCountMatShuffle = np.empty(np.shape(spikeCountMatCopy))
        for indMatRow in range(np.shape(spikeCountMatCopy)[0]):
            numRolls = np.random.choice(range(np.shape(spikeCountMatCopy)[1]))
            # numRolls = 0
            spikeCountMatShuffle[indMatRow, :] = np.roll(
                spikeCountMatCopy[indMatRow, :], numRolls)
        if SHUFFLE:
            spikeCountMat = spikeCountMatShuffle

        binMeans = np.mean(spikeCountMat, axis=0)
        prefInd = np.argmax(binMeans)
        nonPrefInd = np.argmin(binMeans)

        spikesPref = spikeCountMat[:, prefInd]
        spikesNonPref = spikeCountMat[:, nonPrefInd]

        maxAccuracy, threshold = linear_discriminator(spikesPref,
                                                      spikesNonPref)

        # dataframe.set_value(indRow, 'phaseAccuracy_{}Hz'.format(int(thisFreq)), maxAccuracy)
        phaseDiscrimAccuracy[int(thisFreq)] = maxAccuracy
    return phaseDiscrimAccuracy
Beispiel #57
0
def plot_pinp_report(dbRow, saveDir=None, useModifiedClusters=True):
    #Init cell object
    cell = ephyscore.Cell(dbRow, useModifiedClusters=useModifiedClusters)

    plt.clf()
    gs = gridspec.GridSpec(11, 6)
    gs.update(left=0.15, right=0.95, bottom=0.15, wspace=1, hspace=1)

    if 'noiseburst' in dbRow['sessionType']:  #DONE
        ax0 = plt.subplot(gs[0:2, 0:3])
        ephysData, bdata = cell.load('noiseburst')
        eventOnsetTimes = ephysData['events']['stimOn']
        timeRange = [-0.3, 0.5]
        (spikeTimesFromEventOnset, trialIndexForEachSpike,
         indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(
             ephysData['spikeTimes'], eventOnsetTimes, timeRange)
        pRaster, hCond, zLine = extraplots.raster_plot(
            spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange)
        plt.setp(pRaster, ms=1)
        ax0.set_xlim(timeRange)
        ax0.set_xticks([])

        #Laser pulse psth
        ax1 = plt.subplot(gs[4:6, 0:3])
        win = np.array([0, 0.25, 0.75, 1, 0.75, 0.25,
                        0])  # scipy.signal.hanning(7)
        win = win / np.sum(win)
        binEdges = np.arange(timeRange[0], timeRange[-1], 0.001)
        timeVec = binEdges[
            1:]  # FIXME: is this the best way to define the time axis?
        spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
            spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges)
        avResp = np.mean(spikeCountMat, axis=0)
        smoothPSTH = np.convolve(avResp, win, mode='same')
        plt.plot(timeVec, smoothPSTH, 'k-', mec='none', lw=2)
        ax1.set_xlim(timeRange)
        ax1.set_xlabel('Time from noise onset (s)')

    if 'laserpulse' in dbRow['sessionType']:  #DONE
        #Laser pulse raster
        ax0 = plt.subplot(gs[2:4, 0:3])
        ephysData, bdata = cell.load('laserpulse')
        eventOnsetTimes = ephysData['events']['stimOn']
        timeRange = [-0.3, 0.5]
        (spikeTimesFromEventOnset, trialIndexForEachSpike,
         indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(
             ephysData['spikeTimes'], eventOnsetTimes, timeRange)
        pRaster, hCond, zLine = extraplots.raster_plot(
            spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange)
        plt.setp(pRaster, ms=1)
        ax0.set_xlim(timeRange)
        ax0.set_xticks([])

        #Laser pulse psth
        ax1 = plt.subplot(gs[4:6, 0:3])
        win = np.array([0, 0.25, 0.75, 1, 0.75, 0.25,
                        0])  # scipy.signal.hanning(7)
        win = win / np.sum(win)
        binEdges = np.arange(timeRange[0], timeRange[-1], 0.001)
        timeVec = binEdges[
            1:]  # FIXME: is this the best way to define the time axis?
        spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
            spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges)
        avResp = np.mean(spikeCountMat, axis=0)
        smoothPSTH = np.convolve(avResp, win, mode='same')
        plt.plot(timeVec, smoothPSTH, 'k-', mec='none', lw=2)
        ax1.set_xlim(timeRange)
        ax1.set_xlabel('Time from laser pulse onset (s)')

    if 'lasertrain' in dbRow['sessionType']:  #DONE
        #Laser train raster
        ax2 = plt.subplot(gs[2:4, 3:6])
        ephysData, bdata = cell.load('lasertrain')
        eventOnsetTimes = ephysData['events']['stimOn']
        eventOnsetTimes = spikesanalysis.minimum_event_onset_diff(
            eventOnsetTimes, 0.5)

        timeRange = [-0.5, 1]
        pulseTimes = [0, 0.2, 0.4, 0.6, 0.8]

        (spikeTimesFromEventOnset, trialIndexForEachSpike,
         indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(
             ephysData['spikeTimes'], eventOnsetTimes, timeRange)

        pRaster, hCond, zLine = extraplots.raster_plot(
            spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange)
        plt.setp(pRaster, ms=1)
        ax2.set_xlim(timeRange)
        ax2.set_xticks(pulseTimes)

        #Laser train psth
        ax3 = plt.subplot(gs[4:6, 3:6])
        win = np.array([0, 0.25, 0.75, 1, 0.75, 0.25,
                        0])  # scipy.signal.hanning(7)
        win = win / np.sum(win)
        binEdges = np.arange(timeRange[0], timeRange[-1], 0.001)
        timeVec = binEdges[
            1:]  # FIXME: is this the best way to define the time axis?
        spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
            spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges)
        avResp = np.mean(spikeCountMat, axis=0)
        smoothPSTH = np.convolve(avResp, win, mode='same')
        plt.plot(timeVec, smoothPSTH, 'k-', mec='none', lw=2)
        ax3.set_xlim(timeRange)
        ax3.set_xticks(pulseTimes)
        ax3.set_xlabel('Time from first pulse onset (s)')

    #Sorted tuning raster
    if 'tc' in dbRow['sessionType']:  #DONE
        ax4 = plt.subplot(gs[6:8, 0:3])
        ephysData, bdata = cell.load('tc')
        eventOnsetTimes = ephysData['events']['stimOn']
        timeRange = [-0.5, 1]
        (spikeTimesFromEventOnset, trialIndexForEachSpike,
         indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(
             ephysData['spikeTimes'], eventOnsetTimes, timeRange)
        freqEachTrial = bdata['currentFreq']
        possibleFreq = np.unique(freqEachTrial)
        freqLabels = ['{0:.1f}'.format(freq / 1000.0) for freq in possibleFreq]
        trialsEachCondition = behavioranalysis.find_trials_each_type(
            freqEachTrial, possibleFreq)

        pRaster, hCond, zLine = extraplots.raster_plot(
            spikeTimesFromEventOnset,
            indexLimitsEachTrial,
            timeRange,
            trialsEachCond=trialsEachCondition,
            labels=freqLabels)
        plt.setp(pRaster, ms=1)
        ax4.set_ylabel('Frequency (kHz)')

        #TC heatmap
        ax5 = plt.subplot(gs[8:10, 0:3])

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

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

        #Init arrays to hold the baseline and response spike counts per condition
        allIntenBase = np.array([])
        allIntenResp = np.empty((len(possibleIntensity), len(possibleFreq)))

        spikeTimes = ephysData['spikeTimes']

        for indinten, inten in enumerate(possibleIntensity):
            spks = np.array([])
            freqs = np.array([])
            base = np.array([])
            for indfreq, freq in enumerate(possibleFreq):
                selectinds = np.flatnonzero((freqEachTrial == freq)
                                            & (intensityEachTrial == inten))
                selectedOnsetTimes = eventOnsetTimes[selectinds]
                (spikeTimesFromEventOnset, trialIndexForEachSpike,
                 indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(
                     spikeTimes, selectedOnsetTimes, alignmentRange)
                nspkBase = spikesanalysis.spiketimes_to_spikecounts(
                    spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange)
                nspkResp = spikesanalysis.spiketimes_to_spikecounts(
                    spikeTimesFromEventOnset, indexLimitsEachTrial,
                    responseRange)
                base = np.concatenate([base, nspkBase.ravel()])
                spks = np.concatenate([spks, nspkResp.ravel()])
                # inds = np.concatenate([inds, np.ones(len(nspkResp.ravel()))*indfreq])
                freqs = np.concatenate(
                    [freqs, np.ones(len(nspkResp.ravel())) * freq])
                allIntenBase = np.concatenate([allIntenBase, nspkBase.ravel()])
                allIntenResp[indinten, indfreq] = np.mean(nspkResp)

        lowFreq = possibleFreq.min()
        highFreq = possibleFreq.max()
        nFreqLabels = 3

        freqTickLocations = np.linspace(0, len(possibleFreq), nFreqLabels)
        freqs = np.logspace(np.log10(lowFreq), np.log10(highFreq), nFreqLabels)
        freqs = np.round(freqs, decimals=1)

        nIntenLabels = 3
        intensities = np.linspace(possibleIntensity.min(),
                                  possibleIntensity.max(), nIntenLabels)
        intenTickLocations = np.linspace(0,
                                         len(possibleIntensity) - 1,
                                         nIntenLabels)

        plt.imshow(np.flipud(allIntenResp),
                   interpolation='nearest',
                   cmap='Blues')
        ax5.set_yticks(intenTickLocations)
        ax5.set_yticklabels(intensities[::-1])
        ax5.set_xticks(freqTickLocations)
        freqLabels = ['{0:.1f}'.format(freq) for freq in freqs]
        # ax.set_xticklabels(freqLabels, rotation='vertical')
        ax5.set_xticklabels(freqLabels)
        ax5.set_xlabel('Frequency (kHz)')
        plt.ylabel('Intensity (db SPL)')

        if not pd.isnull(dbRow['threshold']):
            plt.hold(1)
            indThresh = (len(possibleIntensity) - 1) - np.where(
                dbRow['threshold'] == possibleIntensity)[0]
            indCF = np.where(dbRow['cf'] == possibleFreq)[0]
            # import ipdb; ipdb.set_trace()
            ax5.plot(indCF, indThresh, 'r*')
            plt.suptitle('Threshold: {}'.format(dbRow['threshold']))

        if not pd.isnull(dbRow['upperFreq']):
            plt.hold(1)
            threshPlus10 = indThresh - (10 / np.diff(possibleIntensity)[0])
            upperFraction = (np.log2(dbRow['upperFreq']) - np.log2(
                possibleFreq[0])) / (np.log2(possibleFreq[-1]) -
                                     np.log2(possibleFreq[0]))
            indUpper = upperFraction * (len(possibleFreq) - 1)

            lowerFraction = (np.log2(dbRow['lowerFreq']) - np.log2(
                possibleFreq[0])) / (np.log2(possibleFreq[-1]) -
                                     np.log2(possibleFreq[0]))
            indLower = lowerFraction * (len(possibleFreq) - 1)

            # import ipdb; ipdb.set_trace()
            ax5.plot(indUpper, threshPlus10, 'b*')
            ax5.plot(indLower, threshPlus10, 'b*')

    if 'am' in dbRow['sessionType']:  #DONE
        #Sorted am raster
        # ax6 = plt.subplot(gs[4:6, 3:6])
        ax6spec = gs[6:8, 3:6]
        ephysData, bdata = cell.load('am')
        eventOnsetTimes = ephysData['events']['stimOn']

        colors = get_colors(len(np.unique(bdata['currentFreq'])))

        timeRange = [-0.5, 1]
        (spikeTimesFromEventOnset, trialIndexForEachSpike,
         indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(
             ephysData['spikeTimes'], eventOnsetTimes, timeRange)
        # extraplots.raster_plot(spikeTimesFromEventOnset,
        #                        indexLimitsEachTrial,
        #                        timeRange,
        #                        trialsEachCond=bdata['currentFreq'],
        #                        colorsEachCond=colors)
        plot_example_with_rate(ax6spec,
                               spikeTimesFromEventOnset,
                               indexLimitsEachTrial,
                               bdata['currentFreq'],
                               colorEachCond=colors,
                               maxSyncRate=cell.dbRow['highestSyncCorrected'])

        #AM cycle average hist
        psthLineWidth = 2
        ax7 = plt.subplot(gs[8:10, 3:6])

        colorEachCond = colors
        plt.hold(True)
        sortArray = bdata['currentFreq']
        for indFreq, (freq, spikeTimesThisFreq,
                      trialIndicesThisFreq) in enumerate(
                          spiketimes_each_frequency(spikeTimesFromEventOnset,
                                                    trialIndexForEachSpike,
                                                    sortArray)):
            radsPerSec = freq * 2 * np.pi
            spikeRads = (spikeTimesThisFreq * radsPerSec) % (2 * np.pi)
            ax7.hist(spikeRads,
                     bins=20,
                     color=colors[indFreq],
                     histtype='step')

        #AM psth
        # psthLineWidth = 2
        # ax7 = plt.subplot(gs[6:8, 3:6])

        # colorEachCond = colors
        # binsize = 50
        # sortArray = bdata['currentFreq']
        # binsize = binsize/1000.0
        # # If a sort array is supplied, find the trials that correspond to each value of the array
        # trialsEachCond = behavioranalysis.find_trials_each_type(sortArray, np.unique(sortArray))

        # (spikeTimesFromEventOnset,
        # trialIndexForEachSpike,
        # indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(ephysData['spikeTimes'],
        #                                                              eventOnsetTimes,
        #                                                              [timeRange[0]-binsize,
        #                                                               timeRange[1]])

        # binEdges = np.around(np.arange(timeRange[0]-binsize, timeRange[1]+2*binsize, binsize), decimals=2)
        # spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges)
        # pPSTH = extraplots.plot_psth(spikeCountMat/binsize, 1, binEdges[:-1], trialsEachCond, colorEachCond=colors)
        # plt.setp(pPSTH, lw=psthLineWidth)
        # plt.hold(True)
        # zline = plt.axvline(0,color='0.75',zorder=-10)
        # plt.xlim(timeRange)

    (timestamps, samples, recordingNumber) = cell.load_all_spikedata()

    #ISI loghist
    ax8 = plt.subplot(gs[10, 0:2])
    if timestamps is not None:
        try:
            spikesorting.plot_isi_loghist(timestamps)
        except:
            # raise AttributeError
            print "problem with isi vals"

    #Waveforms
    ax9 = plt.subplot(gs[10, 2:4])
    if len(samples) > 0:
        spikesorting.plot_waveforms(samples)

    #Events in time
    ax10 = plt.subplot(gs[10, 4:6])
    if timestamps is not None:
        try:
            spikesorting.plot_events_in_time(timestamps)
        except:
            print "problem with isi vals"

    fig = plt.gcf()
    fig.set_size_inches(8.5 * 2, 11 * 2)

    figName = '{}_{}_{}um_TT{}c{}.png'.format(dbRow['subject'], dbRow['date'],
                                              int(dbRow['depth']),
                                              int(dbRow['tetrode']),
                                              int(dbRow['cluster']))

    plt.suptitle(figName[:-4])

    if saveDir is not None:
        figPath = os.path.join(saveDir, figName)
        plt.savefig(figPath)
Beispiel #58
0
def plot_example_with_rate(subplotSpec, exampleName, color='k'):
    fig = plt.gcf()

    sub_gs = gridspec.GridSpecFromSubplotSpec(1, 4, subplot_spec=subplotSpec, wspace=-0.45, hspace=0.0)

    specRaster = sub_gs[0:2]
    axRaster = plt.Subplot(fig, specRaster)
    fig.add_subplot(axRaster)

    spikeTimes = exampleSpikeTimes[exampleName]
    indexLimitsEachTrial = exampleIndexLimitsEachTrial[exampleName]
    timeRange = [-0.2, 0.7]
    freqEachTrial = exampleFreqEachTrial[exampleName]
    possibleFreq = np.unique(freqEachTrial)
    freqLabels = ['{0:.0f}'.format(freq) for freq in possibleFreq]
    trialsEachCondition = behavioranalysis.find_trials_each_type(freqEachTrial, possibleFreq)
    pRaster, hCond, zline = extraplots.raster_plot(spikeTimes, indexLimitsEachTrial,
                                                   timeRange, trialsEachCondition, labels=freqLabels)
    plt.setp(pRaster, ms=figparams.rasterMS)

    blankLabels = ['']*11
    for labelPos in [0, 5, 10]:
        blankLabels[labelPos] = freqLabels[labelPos]

    axRaster.set_yticklabels(blankLabels)

    ax = plt.gca()
    ax.set_xticks([0, 0.5])
    ax.set_xlabel('Time from\nsound onset (s)', fontsize=fontSizeLabels, labelpad=-1)
    ax.set_ylabel('AM rate (Hz)', fontsize=fontSizeLabels, labelpad=-5)

    # ax.annotate('A', xy=(labelPosX[0],labelPosY[0]), xycoords='figure fraction',
    #             fontsize=fontSizePanel, fontweight='bold')

    countRange = [0.1, 0.5]
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimes, indexLimitsEachTrial, countRange)
    numSpikesInTimeRangeEachTrial = np.squeeze(spikeCountMat)

    numSpikesInTimeRangeEachTrial = np.squeeze(np.diff(indexLimitsEachTrial,
                                                       axis=0))

    if len(numSpikesInTimeRangeEachTrial) == len(freqEachTrial)+1:
        numSpikesInTimeRangeEachTrial = numSpikesInTimeRangeEachTrial[:-1]
    conditionMatShape = np.shape(trialsEachCondition)
    numRepeats = np.product(conditionMatShape[1:])
    nSpikesMat = np.reshape(numSpikesInTimeRangeEachTrial.repeat(numRepeats),
                            conditionMatShape)
    spikesFilteredByTrialType = nSpikesMat * trialsEachCondition
    avgSpikesArray = np.sum(spikesFilteredByTrialType, 0) / np.sum(
        trialsEachCondition, 0).astype('float')/np.diff(np.array(countRange))
    stdSpikesArray = np.std(spikesFilteredByTrialType, 0)/np.diff(np.array(countRange))

    specRate = sub_gs[3]
    axRate = plt.Subplot(fig, specRate)
    fig.add_subplot(axRate)

    nRates = len(possibleFreq)
    # plt.hold(True)
    plt.plot(avgSpikesArray, range(nRates), 'ro-', mec='none', ms=6, lw=3, color=color)
    plt.plot(avgSpikesArray-stdSpikesArray, range(len(possibleFreq)), 'k:')
    plt.plot(avgSpikesArray+stdSpikesArray, range(len(possibleFreq)), 'k:')
    axRate.set_ylim([-0.5, nRates-0.5])
    axRate.set_yticks(range(nRates))
    axRate.set_yticklabels([])

    # ax = plt.gca()
    axRate.set_xlabel('Firing rate\n(spk/s)', fontsize = fontSizeLabels, labelpad=-1)
    extraplots.boxoff(axRate)
    # extraplots.boxoff(ax, keep='right')
    return axRaster, axRate
        spkTimeStamps = spkData.spikes.timestamps


        clusterNumber = (oneCell.tetrode-1)*clusNum+(oneCell.cluster-1)
        for Freq in possibleFreq:
            oneFreq = targetFreqs == Freq

            trialsToUseRight = rightward & oneFreq
            trialsToUseLeft = leftward & oneFreq

            #print 'behavior ',behavSession,' tetrode ',oneCell.tetrode,' cluster ',oneCell.cluster,'freq',Freq

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

            spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,countTimeRange)

            spikeCountEachTrial = spikeCountMat.flatten()
            spikeAvgRight = sum(spikeCountEachTrial[trialsToUseRight])/float(sum(trialsToUseRight))
            spikeAvgLeft = sum(spikeCountEachTrial[trialsToUseLeft])/float(sum(trialsToUseLeft))


            if ((spikeAvgRight + spikeAvgLeft) == 0):
                modIDict[behavSession][Freq][clusterNumber]=0.0
            else:
                modIDict[behavSession][Freq][clusterNumber]=((spikeAvgRight - spikeAvgLeft)/(spikeAvgRight + spikeAvgLeft))
            #print spikeAvgRight,' ', spikeAvgLeft, ' ',modIDict[behavSession][Freq][clusterNumber]

    except:
        if (oneCell.behavSession not in badSessionList):
            badSessionList.append(oneCell.behavSession)
Beispiel #60
0
def plot_example_with_rate(subplotSpec,
                           spikeTimes,
                           indexLimitsEachTrial,
                           freqEachTrial,
                           color='k',
                           colorEachCond=None,
                           maxSyncRate=None):
    fig = plt.gcf()

    gs = gridspec.GridSpecFromSubplotSpec(1,
                                          4,
                                          subplot_spec=subplotSpec,
                                          wspace=-0.45,
                                          hspace=0.0)

    specRaster = gs[0:2]
    axRaster = plt.Subplot(fig, specRaster)
    fig.add_subplot(axRaster)

    # spikeTimes = exampleSpikeTimes[exampleName]
    # indexLimitsEachTrial = exampleIndexLimitsEachTrial[exampleName]
    timeRange = [-0.2, 0.7]
    # freqEachTrial = exampleFreqEachTrial[exampleName]
    possibleFreq = np.unique(freqEachTrial)
    freqLabels = ['{0:.1f}'.format(freq) for freq in possibleFreq]
    trialsEachCondition = behavioranalysis.find_trials_each_type(
        freqEachTrial, possibleFreq)
    pRaster, hCond, zline = extraplots.raster_plot(spikeTimes,
                                                   indexLimitsEachTrial,
                                                   timeRange,
                                                   trialsEachCondition,
                                                   labels=freqLabels,
                                                   colorEachCond=colorEachCond)
    axYTicks = plt.gca().get_yticklabels()
    if (maxSyncRate is not None) and (maxSyncRate !=
                                      0.0) and not np.isnan(maxSyncRate):
        indMaxSync = np.where(possibleFreq == maxSyncRate)
        axYTicks[int(indMaxSync[0])].set_color('red')
    plt.setp(pRaster, ms=2)
    ax = plt.gca()
    ax.set_xticks([0, 0.5])
    ax.set_xlabel('Time from\nsound onset (s)')
    ax.set_ylabel('AM Rate (Hz)')

    # ax.annotate('A', xy=(labelPosX[0],labelPosY[0]), xycoords='figure fraction',
    #             fontsize=fontSizePanel, fontweight='bold')

    countRange = [0.1, 0.5]
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimes, indexLimitsEachTrial, countRange)
    numSpikesInTimeRangeEachTrial = np.squeeze(spikeCountMat)

    numSpikesInTimeRangeEachTrial = np.squeeze(
        np.diff(indexLimitsEachTrial, axis=0))

    if len(numSpikesInTimeRangeEachTrial) == len(freqEachTrial) + 1:
        numSpikesInTimeRangeEachTrial = numSpikesInTimeRangeEachTrial[:-1]
    conditionMatShape = np.shape(trialsEachCondition)
    numRepeats = np.product(conditionMatShape[1:])
    nSpikesMat = np.reshape(numSpikesInTimeRangeEachTrial.repeat(numRepeats),
                            conditionMatShape)
    spikesFilteredByTrialType = nSpikesMat * trialsEachCondition
    avgSpikesArray = np.sum(spikesFilteredByTrialType, 0) / np.sum(
        trialsEachCondition, 0).astype('float') / np.diff(np.array(countRange))
    stdSpikesArray = np.std(spikesFilteredByTrialType, 0) / np.diff(
        np.array(countRange))

    specRate = gs[3]
    axRate = plt.Subplot(fig, specRate)
    fig.add_subplot(axRate)

    nRates = len(possibleFreq)
    plt.hold(True)
    plt.plot(avgSpikesArray,
             range(nRates),
             'ro-',
             mec='none',
             ms=7,
             lw=3,
             color=color)
    plt.plot(avgSpikesArray - stdSpikesArray, range(len(possibleFreq)), 'k:')
    plt.plot(avgSpikesArray + stdSpikesArray, range(len(possibleFreq)), 'k:')
    axRate.set_ylim([-0.5, nRates - 0.5])
    axRate.set_yticks(range(nRates))
    axRate.set_yticklabels([])

    #ax = plt.gca()
    axRate.set_xlabel('Firing rate\n(spk/s)')
    extraplots.boxoff(axRate)
    # extraplots.boxoff(ax, keep='right')
    return (axRaster, axRate)