Exemplo n.º 1
0
def tuning_raster(bdata, ephysdata, gs):
    plt.subplot(gs[0, 1])

    freqEachTrial = bdata['currentFreq']

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

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

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

    #print len(freqEachTrial), len(eventOnsetTimes)

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

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

    plt.title('Tuning Curve')
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    '''
def plot_ave_psycurve_reward_change(animal, sessions):    
    FREQCOLORS =  [colorpalette.TangoPalette['Chameleon3'],
                   colorpalette.TangoPalette['ScarletRed1'],
                   colorpalette.TangoPalette['SkyBlue2']]

    allBehavDataThisAnimal = behavioranalysis.load_many_sessions(animal,sessions)
    targetFrequency = allBehavDataThisAnimal['targetFrequency']
    choice=allBehavDataThisAnimal['choice']
    valid=allBehavDataThisAnimal['valid']& (choice!=allBehavDataThisAnimal.labels['choice']['none'])
    choiceRight = choice==allBehavDataThisAnimal.labels['choice']['right']
    currentBlock = allBehavDataThisAnimal['currentBlock']
    blockTypes = [allBehavDataThisAnimal.labels['currentBlock']['same_reward'],allBehavDataThisAnimal.labels['currentBlock']['more_left'],allBehavDataThisAnimal.labels['currentBlock']['more_right']]
    #blockTypes = [allBehavDataThisAnimal.labels['currentBlock']['more_left'],allBehavDataThisAnimal.labels['currentBlock']['more_right']]
    blockLabels = ['same_reward','more_left','more_right']
    #blockLabels = ['more_left','more_right']
    trialsEachType = behavioranalysis.find_trials_each_type(currentBlock,blockTypes)
    
    nFreqs = len(np.unique(targetFrequency))
    print '{}, freqs: {}'.format(animal, str(np.unique(targetFrequency)))
    #print trialsEachType
    nBlocks = len(blockTypes)
    #thisAnimalPos = inda
    #ax1=plt.subplot(gs[thisAnimalPos])
    #plt.clf()
    fontsize = 12
    allPline = []
    blockLegends = []
    fractionHitsEachValueAllBlocks = np.empty((nBlocks,nFreqs))

    for blockType in range(nBlocks):
        if np.any(trialsEachType[:,blockType]):
            targetFrequencyThisBlock = targetFrequency[trialsEachType[:,blockType]]    
            validThisBlock = valid[trialsEachType[:,blockType]]
            choiceRightThisBlock = choiceRight[trialsEachType[:,blockType]]
            #currentBlockValue = currentBlock[trialsEachBlock[0,block]]
            (possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue)=\
                                                                                                    behavioranalysis.calculate_psychometric(choiceRightThisBlock,targetFrequencyThisBlock,validThisBlock)

            fractionHitsEachValueAllBlocks[blockType,:] = fractionHitsEachValue

            (pline, pcaps, pbars, pdots) = extraplots.plot_psychometric(1e-3*possibleValues,fractionHitsEachValue,
                                                                ciHitsEachValue,xTickPeriod=1)

            plt.setp((pline, pcaps, pbars), color=FREQCOLORS[blockType])
            plt.setp(pdots, mfc=FREQCOLORS[blockType], mec=FREQCOLORS[blockType])
            allPline.append(pline)
            blockLegends.append(blockLabels[blockType])
            
            if blockType == nBlocks-1: 
                plt.xlabel('Frequency (kHz)',fontsize=fontsize)
                plt.ylabel('Rightward trials (%)',fontsize=fontsize)
                extraplots.set_ticks_fontsize(plt.gca(),fontsize)
                legend = plt.legend(allPline,blockLegends,loc=2)
                # Add the legend manually to the current Axes.
                ax = plt.gca().add_artist(legend)
                #plt.hold(True)
        #plt.legend(bbox_to_anchor=(1, 1), bbox_transform=plt.gcf().transFigure)
        #plt.show()
    plt.title('%s_%sto%s'%(animal,sessions[0],sessions[-1]))   
    return fractionHitsEachValueAllBlocks
Exemplo n.º 3
0
def plot_sorted_raster(spikeTimeStamps,
                       eventOnsetTimes,
                       sortArray,
                       timeRange=[-0.5, 1],
                       xlabel='Time from sound onset (sec)',
                       ylabel='Frequency (kHz)',
                       ms=4,
                       labels=None,
                       *args,
                       **kwargs):
    '''
    Function to accept spike timestamps, event onset times, and a sorting array and plot a
    raster plot sorted by the array passed

    Args:
        sortarray (array): An array of parameter values for each trial.
                           Output will be sorted by the possible values of the parameter.
                           Must be the same length as the event onset times array

    '''
    trialsEachCond = behavioranalysis.find_trials_each_type(
        sortArray, np.unique(sortArray))
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimeStamps, eventOnsetTimes, timeRange)
    pRaster, hcond, zline = extraplots.raster_plot(
        spikeTimesFromEventOnset,
        indexLimitsEachTrial,
        timeRange,
        trialsEachCond=trialsEachCond,
        labels=labels,
        *args,
        **kwargs)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.setp(pRaster, ms=ms)
Exemplo n.º 4
0
def tuning_raster(bdata, ephysdata, gs):
    plt.subplot(gs[0, 1])

    freqEachTrial = bdata['currentFreq']
    
    eventOnsetTimes = ephysData['events']['stimOn']
    spikeTimeStamps = ephysData['spikeTimes']
    timeRange = [-0.3, 0.6]

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

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

    #print len(freqEachTrial), len(eventOnsetTimes)



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


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

    plt.title('Tuning Curve')
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    '''
Exemplo n.º 5
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')
Exemplo n.º 6
0
    def plot_raster(self, spikeTimestamps, eventOnsetTimes, sortArray = [], replace = 0, timeRange = [-0.5, 1], ms = 4):
        '''
        Plot a raster given spike timestamps and event onset times
        
        This method will take the spike timestamps directly, convert them so that they are relative to the event onset times, 
        and then call the appropriate plotting code. This method should ideally be able to handle making both sortArrayed and unsortArrayed
        rasters. 
        
        sortArray (array): An array of parameter values for each trial. Output will be sorted by the possible values of the parameter

        '''
        if len(sortArray)>0:
            trialsEachCond = behavioranalysis.find_trials_each_type(sortArray, np.unique(sortArray))
        else:
            trialsEachCond = []
        
        spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(spikeTimestamps,eventOnsetTimes,timeRange)
        #pdb.set_trace()

        if replace: #Now using cla() so that it will work with subplots
            cla()
        #else:
        #    figure()

        pRaster,hcond,zline = extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond = trialsEachCond)
        setp(pRaster,ms=ms)
Exemplo n.º 7
0
def best_window_freq_tuning(spikeTimesFromEventOnset, indexLimitsEachTrial,
                            freqEachTrial):
    windowsToTry = [[0.0, 0.1], [0.0, 0.05], [0.1, 0.15]]
    numFreqs = np.unique(freqEachTrial)

    zscores = np.zeros((len(windowsToTry), len(numFreqs)))
    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)

        trialsEachFreq = behavioranalysis.find_trials_each_type(
            freqEachTrial, numFreqs)
        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]]
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, windowToUse)
    return spikeCountMat, windowToUse
Exemplo n.º 8
0
def highest_significant_sync(cell):
    try:
        sessiontypeIndex = cell['sessiontype'].index(defaultAMtype)
    except ValueError:  #The cell does not have this session type
        return None
    #Initialize a data loader for this animal
    loader = dataloader.DataLoader(cell['subject'])
    #Get the behavior data
    behavData = loader.get_session_behavior(cell['behavior'][sessiontypeIndex])
    freqEachTrial = behavData['currentFreq']
    possibleFreq = np.unique(freqEachTrial)
    ephysDir = cell['ephys'][sessiontypeIndex]
    clusterSpikeData = loader.get_session_spikes(ephysDir,
                                                 int(cell['tetrode']),
                                                 cluster=int(cell['cluster']))
    clusterSpikeTimes = clusterSpikeData.timestamps
    #Get the events for this session and calculate onset times
    eventData = loader.get_session_events(ephysDir)
    eventOnsetTimes = loader.get_event_onset_times(eventData,
                                                   minEventOnsetDiff=None)
    timeRange = [0, 0.5]
    trialsEachCond = behavioranalysis.find_trials_each_type(
        freqEachTrial, possibleFreq)
    vs_array, pval_array, ral_array = AM_vector_strength(
        clusterSpikeTimes, eventOnsetTimes, behavData, timeRange)
    if np.any(pval_array < 0.05):
        highestSync = np.max(possibleFreq[pval_array < 0.05])
    else:
        highestSync = 0
    return highestSync
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
Exemplo n.º 10
0
def freq_tuning_fit(eventOnsetTimes, spikeTimestamps, bdata, timeRange = [-0.2, 0.2], intensityInds = None):
    # determine the best frequency of the cell by fitting gaussian curve to tuning data
    gaussFits = []
    bestFreqs = []
    Rsquareds = []
    
    freqEachTrial = bdata['currentFreq']
    intensityEachTrial = bdata['currentIntensity']
    numIntensities = np.unique(intensityEachTrial)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                                                                                                        spikeTimestamps, 
                                                                                                        eventOnsetTimes,
                                                                                                        timeRange)
    trialsEachInt = behavioranalysis.find_trials_each_type(intensityEachTrial, numIntensities)
    if intensityInds is None:
        intensityInds = range(len(numIntensities))
    
    spikeCountMat, window = best_window_freq_tuning(spikeTimesFromEventOnset, indexLimitsEachTrial, freqEachTrial)
    for intensityInd in intensityInds:
        trialsThisIntensity = trialsEachInt[:,intensityInd]
        tuningSpikeRates = (spikeCountMat[trialsThisIntensity].flatten())/(window[1]-window[0])
        freqsThisIntensity = freqEachTrial[trialsThisIntensity]
        gaussFit, Rsquared = response_curve_fit(np.log2(freqsThisIntensity), tuningSpikeRates)
        bestFreq = 2**gaussFit[0] if gaussFit is not None else None
        gaussFits.append(gaussFit)
        bestFreqs.append(bestFreq)
        Rsquareds.append(Rsquared)
    
    return gaussFits, bestFreqs, Rsquareds, window
Exemplo n.º 11
0
def plot_example(subplotSpec, exampleName):

    # lowFreq = 4
    # highFreq = 128
    # nFreqLabels = 3

    # freqs = np.logspace(np.log10(lowFreq),np.log10(highFreq),nFreqLabels)
    # freqs = np.round(freqs, decimals=1)

    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)
    ax = plt.gca()
    ax.set_xticks([0, 0.5])
    ax.set_xlabel('Time from sound onset (s)')
    ax.set_ylabel('AM Rate (Hz)')
    # ax.set_yticks(freqs)
    # ax.set_yticklabels(freqs)
    plt.setp(pRaster, ms=2)
Exemplo n.º 12
0
    def plot_raster(self, spikeTimestamps, eventOnsetTimes, sortArray = [], replace = 0, timeRange = [-0.5, 1], ms = 4):
        '''
        Plot a raster given spike timestamps and event onset times
        
        This method will take the spike timestamps directly, convert them so that they are relative to the event onset times, 
        and then call the appropriate plotting code. This method should ideally be able to handle making both sortArrayed and unsortArrayed
        rasters. 
        
        sortArray (array): An array of parameter values for each trial. Output will be sorted by the possible values of the parameter

        '''
        if len(sortArray)>0:
            trialsEachCond = behavioranalysis.find_trials_each_type(sortArray, np.unique(sortArray))
        else:
            trialsEachCond = []
        
        spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(spikeTimestamps,eventOnsetTimes,timeRange)
        #pdb.set_trace()

        if replace: #Now using cla() so that it will work with subplots
            cla()
        #else:
        #    figure()

        pRaster,hcond,zline = extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond = trialsEachCond)
        setp(pRaster,ms=ms)
Exemplo n.º 13
0
def tuning_test_raster(bdata, ephysData, gs):
    plt.subplot(gs[11:15, 0])

    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 Test (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)
    '''
Exemplo n.º 14
0
def one_axis_tc_or_rlf(spikeTimestamps,
                       eventOnsetTimes,
                       sortArray,
                       timeRange=[0, 0.1]):
    trialsEachCond = behavioranalysis.find_trials_each_type(
        sortArray, np.unique(sortArray))
    spikeArray = avg_spikes_in_event_locked_timerange_each_cond(
        spikeTimestamps, trialsEachCond, eventOnsetTimes, timeRange)
    plt.plot(spikeArray, ls='-', lw=2, c='0.25')
Exemplo n.º 15
0
def one_axis_tc_or_rlf(spikeTimestamps,
                       eventOnsetTimes,
                       sortArray,
                       timeRange=[0, 0.1]):
    trialsEachCond = behavioranalysis.find_trials_each_type(
        sortArray, np.unique(sortArray))
    spikeArray = avg_spikes_in_event_locked_timerange_each_cond(
        spikeTimestamps, trialsEachCond, eventOnsetTimes, timeRange)
    plt.plot(spikeArray, ls='-', lw=2, c='0.25')
def plot_tuning_raster(animal, ephysSession, behavSession, tetrode, cluster, intensity=50, timeRange = [-0.5,1]):
    '''
    Function to plot a tuning raster sorted by frequency. 
    :param arg1: A string of the file name of the tuning curve ephys session, this is the full filename, in {date}_XX-XX-XX format.
    :param arg2: A string of the file name of the tuning curve behavior session, this is the full filename in '{animal}_{paradigm}_{date}{behavsuffix}.h5' format.
    :param arg3: An int in range(1,9) for tetrode number.
    :param arg4: An int for cluster number.
    :param arg5: An int for the intensity in (dB) to plot, default is 50(dB), which is the stimulus intensity used in 2afc task.
    :param arg6: A list of floats for the start and the end of the time period around sound-onset to plot raster.
    '''
    
    bdata = load_behavior_basic(animal,behavSession)
    
    spikeData = load_spike_data(animal, ephysSession, tetrode, cluster)
    spikeTimestamps = spikeData.timestamps
    eventData = load_event_data(animal, ephysSession)
    eventOnsetTimes = np.array(eventData.timestamps)
    soundOnsetEvents = (eventData.eventID==1) & (eventData.eventChannel==soundTriggerChannel)
    eventOnsetTimes = eventOnsetTimes[soundOnsetEvents]
    
    freqEachTrial = bdata['currentFreq']
    intensityEachTrial = bdata['currentIntensity']
    possibleFreq = np.unique(freqEachTrial)
    possibleIntensity = np.unique(intensityEachTrial)
    if len(possibleIntensity) != 1:
        intensity = intensity 
        ###Just select the trials with a given intensity###
        trialsThisIntensity = [intensityEachTrial==intensity]
        freqEachTrial = freqEachTrial[trialsThisIntensity]
        intensityEachTrial = intensityEachTrial[trialsThisIntensity]
        eventOnsetTimes = eventOnsetTimes[trialsThisIntensity]
    
    #print len(intensityEachTrial),len(eventOnsetTimes),len(spikeTimestamps)

    freqLabels = ['{0:.1f}'.format(freq/1000.0) for freq in possibleFreq]
    #intensityLabels = ['{:.0f} dB'.format(intensity) for intensity in possibleIntensity]        
    
    ### FIXME: this is a bad hack for when ephys is one trial more than behavior file ###
    if len(eventOnsetTimes)==len(intensityEachTrial)+1:
        eventOnsetTimes=eventOnsetTimes[:-1]
    #print len(intensityEachTrial),len(eventOnsetTimes),len(spikeTimestamps)
    
    trialsEachFreq = behavioranalysis.find_trials_each_type(freqEachTrial,possibleFreq)
    
    (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
            spikesanalysis.eventlocked_spiketimes(spikeTimestamps,eventOnsetTimes,timeRange)
    
    pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,
                                                   indexLimitsEachTrial,
                                                   timeRange,
                                                   trialsEachCond=trialsEachFreq,
                                                   labels=freqLabels)
    plt.xlabel('Time from sound onset')
    plt.xlim(timeRange[0]+0.1,timeRange[1])
    plotTitle = 'Tt'+str(tetrode)+'c'+str(cluster)+' tuning with 50dB chords'  
    plt.title(plotTitle,fontsize=10)
Exemplo n.º 17
0
def plot_tuning_raster(cellObj, sessionType='tc', intensity=50, timeRange = [-0.5,1]):
    '''
    Function to plot a tuning raster sorted by frequency. 
    :param arg1: Cell object from ephyscore.
    :param arg2: A string for the session type, for tuning it should be 'tc'.
    :param arg3: An int for the intensity in (dB) to plot, default is 50(dB), which is the stimulus intensity used in 2afc task.
    :param arg4: A list of floats for the start and the end of the time period around sound-onset to plot raster.
    '''
    sessionInd = cellObj.get_session_inds(sessionType)[0]
    bdata = cellObj.load_behavior_by_index(sessionInd)
    ephysData = cellObj.load_ephys_by_index(sessionInd) 
    eventsDict = ephysData['events']
    spikeTimestamps = ephysData['spikeTimes']
    soundOnsetTimes = eventsDict['{}On'.format(soundChannelType)]
    freqEachTrial = bdata['currentFreq']
    intensityEachTrial = bdata['currentIntensity']
    possibleFreq = np.unique(freqEachTrial)
    possibleIntensity = np.unique(intensityEachTrial)
    if len(possibleIntensity) != 1:
        intensity = intensity 
        ###Just select the trials with a given intensity###
        trialsThisIntensity = [intensityEachTrial==intensity]
        freqEachTrial = freqEachTrial[trialsThisIntensity]
        intensityEachTrial = intensityEachTrial[trialsThisIntensity]
        soundOnsetTimes = soundOnsetTimes[trialsThisIntensity]
    
    #print len(intensityEachTrial),len(eventOnsetTimes),len(spikeTimestamps)

    freqLabels = ['{0:.1f}'.format(freq/1000.0) for freq in possibleFreq]
    #intensityLabels = ['{:.0f} dB'.format(intensity) for intensity in possibleIntensity]        
    
    ### FIXME: this is a bad hack for when ephys is one trial more than behavior file ###
    if len(soundOnsetTimes)==len(freqEachTrial)+1:
        soundOnsetTimes=soundOnsetTimes[:-1]
        print('Tuning behavior is one trial less than ephys!')
        ### FIXME: this is a bad hack for when behavior is one trial more than ephys file ###
    if len(soundOnsetTimes)==len(freqEachTrial)-1:
        freqEachTrial=freqEachTrial[:-1]
        print('Tuning behavior is one trial more than ephys!')
    #print len(freqEachTrial),len(eventOnsetTimes),len(spikeTimestamps)
    
    trialsEachFreq = behavioranalysis.find_trials_each_type(freqEachTrial,possibleFreq)
    
    (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
            spikesanalysis.eventlocked_spiketimes(spikeTimestamps,soundOnsetTimes,timeRange)
    
    pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,
                                                   indexLimitsEachTrial,
                                                   timeRange,
                                                   trialsEachCond=trialsEachFreq,
                                                   labels=freqLabels)
    plt.xlabel('Time from sound onset')
    plt.xlim(timeRange[0]+0.1,timeRange[1])
    plotTitle = 'tuning with 50dB chords'  
    plt.title(plotTitle,fontsize=10)
Exemplo n.º 18
0
def plot_bandwidth_noise_amps_comparison(cell, bandIndex=None):
    cellInfo = get_cell_info(cell)
    loader = dataloader.DataLoader(cell['subject'])
    if bandIndex is None:
        try:
            bandIndex = cellInfo['bandIndex'][0]
        except IndexError:
            print 'no bandwidth session'
            pass
    plt.clf()
    gs = gridspec.GridSpec(1, 2)
    eventData = loader.get_session_events(cellInfo['ephysDirs'][bandIndex])
    spikeData = loader.get_session_spikes(cellInfo['ephysDirs'][bandIndex], cellInfo['tetrode'], cluster=cellInfo['cluster'])
    eventOnsetTimes = loader.get_event_onset_times(eventData)
    spikeTimestamps = spikeData.timestamps
    timeRange = [-0.2, 1.5]
    bandBData = loader.get_session_behavior(cellInfo['behavDirs'][bandIndex])  
    bandEachTrial = bandBData['currentBand']
    secondSort = bandBData['currentAmp']
    secondSortLabels = ['{} dB'.format(amp) for amp in np.unique(secondSort)]
    plt.subplot(gs[0,0])
    spikeArray, errorArray, baseSpikeRate = band_select(spikeTimestamps, eventOnsetTimes, secondSort, bandEachTrial, timeRange = [0.0, 1.0])
    spikeArray = spikeArray[:,-1].reshape((7,1))
    errorArray = errorArray[:,-1].reshape((7,1))
    band_select_plot(spikeArray, errorArray, np.unique(bandEachTrial), linecolours=['0.25'], errorcolours=['0.6'])
    plt.title('Bandwidth tuning')
    
    ampsBData = loader.get_session_behavior(cellInfo['behavDirs'][cellInfo['ampsIndex'][-1]])
    ampEachTrial = ampsBData['currentIntensity']
    
    eventData = loader.get_session_events(cellInfo['ephysDirs'][cellInfo['ampsIndex'][-1]])
    spikeData = loader.get_session_spikes(cellInfo['ephysDirs'][cellInfo['ampsIndex'][-1]], cellInfo['tetrode'], cluster=cellInfo['cluster'])
    eventOnsetTimes = loader.get_event_onset_times(eventData)
    spikeTimestamps = spikeData.timestamps
    timeRange = [-0.2, 1.0]
    
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                                                                                                spikeTimestamps, eventOnsetTimes, timeRange)
    numRates = np.unique(ampEachTrial)
    trialsEachCond = behavioranalysis.find_trials_each_type(ampEachTrial, numRates)
    plt.subplot(gs[0,1])
    spikeArray, errorArray, baseSpikeRate = band_select(spikeTimestamps, eventOnsetTimes, ampsBData['currentFreq'], ampEachTrial, timeRange = [0.0, 0.5])
    band_select_plot(spikeArray, errorArray, np.unique(ampEachTrial), linecolours=['0.25'], errorcolours=['0.6'])
    plt.xlabel('white noise intensity (dB)')
    plt.ylabel('Average num spikes')
    plt.title('Intensity tuning')
    fig_path = '/home/jarauser/Pictures/cell reports'
    fig_name = '{0}_{1}_{2}um_TT{3}Cluster{4}_noiseAmps.png'.format(cellInfo['subject'], cellInfo['date'], cellInfo['depth'], cellInfo['tetrode'], cellInfo['cluster'])
    full_fig_path = os.path.join(fig_path, fig_name)
    fig = plt.gcf()
    fig.set_size_inches(9, 4)
    fig.savefig(full_fig_path, format = 'png', bbox_inches='tight')
Exemplo n.º 19
0
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)
    '''
Exemplo n.º 20
0
def find_trials_each_combination_three_params(parameter1,parameterPossibleValues1,parameter2,parameterPossibleValues2,parameter3,parameterPossibleValues3):
    '''
    Returns a boolean 4D array of size [nTrials,nValues1,nValues2,nValues3]. True for each combination.
    '''
    if len(parameter1)!=len(parameter2):
        raise ValueError('parameters must be vectors of same size.')
    nTrials = len(parameter1)
    nValues1 = len(parameterPossibleValues1)
    nValues2 = len(parameterPossibleValues2)
    nValues3 = len(parameterPossibleValues3)
    trialsEachComb = np.zeros((nTrials,nValues1,nValues2,nValues3),dtype=bool)
    trialsEachComb12 = behavioranalysis.find_trials_each_combination(parameter1, parameterPossibleValues1, parameter2, parameterPossibleValues2)
    trialsEachType3 = behavioranalysis.find_trials_each_type(parameter3,parameterPossibleValues3)
    for ind3 in range(nValues3):
        trialsEachComb[:,:,:,ind3] = trialsEachComb12 & trialsEachType3[:,ind3][:,np.newaxis,np.newaxis]
    return trialsEachComb
Exemplo n.º 21
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')
Exemplo n.º 22
0
def am_dependence(spikesEachTrial, rateEachTrial):
    '''
    Calculate the average firing rate of a cell during the 0.5sec AM sound.
    Perform a linear regression on average firing rate and AM rate, and
    return the correlation coefficient for the regression.
    '''

    try:
        sessiontypeIndex = cell['sessiontype'].index(defaultAMtype)
    except ValueError:  #The cell does not have this session type
        return None

    #Initialize a data loader for this animal
    loader = dataloader.DataLoader(cell['subject'])

    #Get the behavior data
    behavData = loader.get_session_behavior(cell['behavior'][sessiontypeIndex])
    freqEachTrial = behavData['currentFreq']

    possibleFreq = np.unique(freqEachTrial)

    ephysDir = cell['ephys'][sessiontypeIndex]
    clusterSpikeData = loader.get_session_spikes(ephysDir,
                                                 int(cell['tetrode']),
                                                 cluster=int(cell['cluster']))
    clusterSpikeTimes = clusterSpikeData.timestamps

    #Get the events for this session and calculate onset times
    eventData = loader.get_session_events(ephysDir)
    eventOnsetTimes = loader.get_event_onset_times(eventData,
                                                   minEventOnsetDiff=None)

    timeRange = [0, 0.5]

    trialsEachCond = behavioranalysis.find_trials_each_type(
        freqEachTrial, possibleFreq)

    spikeArray = dataplotter.avg_spikes_in_event_locked_timerange_each_cond(
        clusterSpikeTimes, trialsEachCond, eventOnsetTimes, timeRange)

    slope, intercept, r_value, p_value, std_err = stats.linregress(
        spikeArray, possibleFreq)

    if not frArray:
        return r_value
    else:
        return r_value, spikeArray, possibleFreq
Exemplo n.º 23
0
def band_psychometric(animal, sessions, trialTypes=['currentSNR']):
    ''' 
    Produces the number of valid trials and number of trials where animal went to the right for each condition.
    Can sort by up to three parameters.
    
    Input:
        animal = name of animal whose behaviour is to be used (string)
        sessions = file names of sessions to be used (list of strings)
        trialTypes = names of parameters in behavData to be used for sorting trials (list of strings, up to 3 parameters)
        
    Output:
        validPerCond = 1D to 3D array (depending on number of parameters given) giving number of valid trials for each condition
        rightPerCond = like validPerCond, only trials where animal went to the right
        possibleParams = possible values each parameter takes
    '''
    behavData = behavioranalysis.load_many_sessions(animal, sessions)
    
    firstSort = behavData[trialTypes[0]]
    possibleFirstSort = np.unique(firstSort)
    
    possibleSecondSort = None
    possibleThirdSort = None
    
    if len(trialTypes) > 1:
        secondSort = behavData[trialTypes[1]]
        possibleSecondSort = np.unique(secondSort)

    if len(trialTypes) > 2:
        thirdSort = behavData[trialTypes[2]]
        possibleThirdSort = np.unique(thirdSort)
        
    valid = behavData['valid'].astype(bool)
    rightChoice = behavData['choice']==behavData.labels['choice']['right']
    
    if len(trialTypes) == 3:
        trialsEachComb = find_trials_each_combination_three_params(firstSort, possibleFirstSort, secondSort, possibleSecondSort, thirdSort, possibleThirdSort)
    elif len(trialTypes) == 2:
        trialsEachComb = behavioranalysis.find_trials_each_combination(firstSort, possibleFirstSort, secondSort, possibleSecondSort)
    elif len(trialTypes) == 1:
        trialsEachComb = behavioranalysis.find_trials_each_type(firstSort, possibleFirstSort)
    
    validPerCond, rightPerCond = compute_psychometric_inputs(valid, rightChoice, trialsEachComb)
    
    possibleParams = [possibleFirstSort, possibleSecondSort, possibleThirdSort]
    possibleParams = [param for param in possibleParams if param is not None]
    return validPerCond, rightPerCond, possibleParams
Exemplo n.º 24
0
def plot_raster(spikeTimestamps, eventOnsetTimes, sortArray = [], timeRange = [-0.5, 1], ms = 4, labels=None):
    '''
    Args:
        sortarray (array): an array of parameter values for each trial. output will be sorted by the possible values of the parameter. Must be the same length as the event onset times array

    '''
    if len(sortArray)>0:
        trialsEachCond = behavioranalysis.find_trials_each_type(sortArray, np.unique(sortArray))
        if not labels:
            labels=['%.1f' % f for f in np.unique(sortArray)]
    else:
        trialsEachCond = []

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

    pRaster,hcond,zline = extraplots.raster_plot(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange, trialsEachCond = trialsEachCond, labels=labels)
    plt.setp(pRaster,ms=ms)
Exemplo n.º 25
0
def plot_raster(spikeTimestamps,
                eventOnsetTimes,
                sortArray=[],
                timeRange=[-0.5, 1],
                ms=4,
                labels=None,
                *args,
                **kwargs):
    '''
    Function to accept spike timestamps, event onset times, and an optional sorting array and plot a
    raster plot (sorted if the sorting array is passed)

    This function does not replicate functionality. It allows you to pass spike timestamps and event
    onset times, which are simple to get, as well as an array of any values that can be used to sort the
    raster. This function wraps three other good functions and provides a way to use them easily

    Args:
        sortarray (array): An array of parameter values for each trial.
                           Output will be sorted by the possible values of the parameter.
                           Must be the same length as the event onset times array

    '''
    # 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))
        if not labels:
            labels = ['%.1f' % f for f in np.unique(sortArray)]
    else:
        trialsEachCond = []
    # Align spiketimestamps to the event onset times for plotting
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimestamps, eventOnsetTimes, timeRange)
    #Plot the raster, which will sort if trialsEachCond is supplied
    pRaster, hcond, zline = extraplots.raster_plot(
        spikeTimesFromEventOnset,
        indexLimitsEachTrial,
        timeRange,
        trialsEachCond=trialsEachCond,
        labels=labels,
        *args,
        **kwargs)
    #Set the marker size for better viewing
    plt.setp(pRaster, ms=ms)
def am_example(cell, timeRange=[-0.2, 0.7]):

    #Plot histograms of spikes relative to stimulus period?
    plotCycleHists = False

    spikeData, eventData = celldatabase.get_session_ephys(cell, 'am')
    eventOnsetTimes = eventData.get_event_onset_times(eventID=1, eventChannel=0)
    eventOnsetTimes = spikesanalysis.minimum_event_onset_diff(eventOnsetTimes, minEventOnsetDiff=0.7)
    bdata = celldatabase.get_session_bdata(cell, 'am')
    colors = get_colors(len(np.unique(bdata['currentFreq'])))
    #Raster
    plt.clf()
    if plotCycleHists:
        plt.subplot2grid((11, 3), (0, 0), rowspan=11, colspan=2)
    else:
        plt.subplot(111)
    ms=6 #4
    sortArray = bdata['currentFreq']
    trialsEachCond = behavioranalysis.find_trials_each_type(
        sortArray, np.unique(sortArray))
    labels = ['%.1f' % f for f in np.unique(sortArray)]
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeData.timestamps, eventOnsetTimes, timeRange)
    pRaster, hcond, zline = extraplots.raster_plot(
        spikeTimesFromEventOnset,
        indexLimitsEachTrial,
        timeRange,
        trialsEachCond=trialsEachCond,
        labels=labels,
        colorEachCond=colors)
    plt.setp(pRaster, ms=ms)
    fontsize = 20
    plt.ylabel('AM rate', fontsize=fontsize)
    plt.xlabel('Time from stimulus onset (s)', fontsize=fontsize)

    if plotCycleHists:
        #Want to plot a hist of spike times from 0 to 2pi
        # ax3 = plt.subplot(313)
        plt.hold(True)
        for indFreq, (freq, spikeTimesThisFreq, trialIndicesThisFreq) in enumerate(spiketimes_each_frequency(spikeTimesFromEventOnset, trialIndexForEachSpike, sortArray)):
            radsPerSec=freq*2*np.pi
            spikeRads = (spikeTimesThisFreq*radsPerSec)%(2*np.pi)
            ax = plt.subplot2grid((11, 3), (10-indFreq, 2))
            ax.hist(spikeRads, bins=50, color=colors[indFreq], histtype='step')
Exemplo n.º 27
0
def plot_sorted_raster(spikeTimeStamps, eventOnsetTimes, sortArray, timeRange=[-0.5, 1],xlabel='Time from sound onset (sec)',ylabel='Frequency (kHz)',ms=4,labels=None,*args,**kwargs):
    '''
    Function to accept spike timestamps, event onset times, and a sorting array and plot a
    raster plot sorted by the array passed

    Args:
        sortarray (array): An array of parameter values for each trial.
                           Output will be sorted by the possible values of the parameter.
                           Must be the same length as the event onset times array

    '''
    trialsEachCond = behavioranalysis.find_trials_each_type(sortArray, np.unique(sortArray))
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimeStamps, eventOnsetTimes, timeRange)
    pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange,
                                                   trialsEachCond=trialsEachCond,labels=labels, *args, **kwargs)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.setp(pRaster, ms=ms)
Exemplo n.º 28
0
def time_differences_by_trial(animal, sessions, sortBy, paradigm = '2afc', triggers = ['Cin', 'Cout']):
    loader = dataloader.DataLoader(animal)
    timeDiff = []
    import pdb
    for ind,session in enumerate(sessions):
        behavFile = loadbehavior.path_to_behavior_data(animal,paradigm,session)
        behavData = loader.get_session_behavior(behavFile)
        possibleSort = np.unique(behavData[sortBy])
        if ind == 0:
            for sort in range(len(possibleSort)):
                timeDiff.append([])
        trialsEachCond = behavioranalysis.find_trials_each_type(behavData[sortBy], possibleSort)
        eventCode = np.array(behavData.events['eventCode'])
        eventTime = behavData.events['eventTime']
        nextState = behavData.events['nextState']
        trialEnd = np.where(nextState==behavData.stateMatrix['statesNames']['startTrial'])[0][1:]
        try:
            start = np.where(eventCode==behavData.stateMatrix['eventsNames'][triggers[0]])[0]
        except KeyError:
            start = np.where(nextState==behavData.stateMatrix['statesNames'][triggers[0]])[0]+1
        try:
            stop = np.where(eventCode==behavData.stateMatrix['eventsNames'][triggers[1]])[0]
        except KeyError:
            stop = np.where(nextState==behavData.stateMatrix['statesNames'][triggers[1]])[0]+1
        for ind in range(len(possibleSort)):
            trialsThisCond = trialsEachCond[:,ind]
            if len(trialsThisCond) > len(trialEnd):
                trialsThisCond = trialsThisCond[:-1]
            trialEndThisCond = trialEnd[trialsThisCond]
            startThisCond = np.zeros(sum(trialsThisCond))
            stopThisCond = np.zeros(sum(trialsThisCond))
            #pdb.set_trace()
            for i in range(len(trialEndThisCond)):
                startThisCond[i] = max(j for j in start if j < trialEndThisCond[i])
                stopThisCond[i] = min(k for k in stop if k > startThisCond[i])
            startThisCond = startThisCond.astype(int)
            stopThisCond = stopThisCond.astype(int)
            startTime = eventTime[startThisCond]
            stopTime = eventTime[stopThisCond]
            diffThisCond = stopTime - startTime
            #pdb.set_trace()
            timeDiff[ind].extend(diffThisCond)
    return timeDiff, possibleSort
Exemplo n.º 29
0
def time_differences_by_trial(animal, sessions, sortBy, paradigm = '2afc', triggers = ['Cin', 'Cout']):
    timeDiff = []
    import pdb
    for ind,session in enumerate(sessions):
        behavFile = os.path.join(settings.BEHAVIOR_PATH,animal,animal+'_2afc_'+session+'.h5')
        behavData = loadbehavior.BehaviorData(behavFile,readmode='full')
        possibleSort = np.unique(behavData[sortBy])
        while len(possibleSort)>len(timeDiff):
            timeDiff.append([])
            print len(timeDiff)
        trialsEachCond = behavioranalysis.find_trials_each_type(behavData[sortBy], possibleSort)
        eventCode = np.array(behavData.events['eventCode'])
        eventTime = behavData.events['eventTime']
        nextState = behavData.events['nextState']
        trialEnd = np.where(nextState==behavData.stateMatrix['statesNames']['startTrial'])[0][1:]
        try:
            start = np.where(eventCode==behavData.stateMatrix['eventsNames'][triggers[0]])[0]
        except KeyError:
            start = np.where(nextState==behavData.stateMatrix['statesNames'][triggers[0]])[0]+1
        try:
            stop = np.where(eventCode==behavData.stateMatrix['eventsNames'][triggers[1]])[0]
        except KeyError:
            stop = np.where(nextState==behavData.stateMatrix['statesNames'][triggers[1]])[0]+1
        for ind2 in range(len(possibleSort)):
            trialsThisCond = trialsEachCond[:,ind2]
            if len(trialsThisCond) > len(trialEnd):
                trialsThisCond = trialsThisCond[:-1]
            trialEndThisCond = trialEnd[trialsThisCond]
            startThisCond = np.zeros(sum(trialsThisCond))
            stopThisCond = np.zeros(sum(trialsThisCond))
            #pdb.set_trace()
            for i in range(len(trialEndThisCond)):
                startThisCond[i] = max(j for j in start if j < trialEndThisCond[i])
                stopThisCond[i] = min(k for k in stop if k > startThisCond[i])
            startThisCond = startThisCond.astype(int)
            stopThisCond = stopThisCond.astype(int)
            startTime = eventTime[startThisCond]
            stopTime = eventTime[stopThisCond]
            diffThisCond = stopTime - startTime
            #pdb.set_trace()
            timeDiff[ind2].extend(diffThisCond)
    return timeDiff, possibleSort
Exemplo n.º 30
0
def plot_raster(spikeTimestamps,
                eventOnsetTimes,
                sortArray=[],
                timeRange=[-0.5, 1],
                ms=4,
                labels=None,
                *args,
                **kwargs):
    '''
    Function to accept spike timestamps, event onset times, and an optional sorting array and plot a
    raster plot (sorted if the sorting array is passed)

    This function does not replicate functionality. It allows you to pass spike timestamps and event
    onset times, which are simple to get, as well as an array of any values that can be used to sort the
    raster. This function wraps three other good functions and provides a way to use them easily

    Args:
        sortarray (array): An array of parameter values for each trial.
                           Output will be sorted by the possible values of the parameter.
                           Must be the same length as the event onset times array

    '''
    # 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))
        if not labels:
            labels = ['%.1f' % f for f in np.unique(sortArray)]
    else:
        trialsEachCond = []
    # Align spiketimestamps to the event onset times for plotting
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimestamps, eventOnsetTimes, timeRange)
    #Plot the raster, which will sort if trialsEachCond is supplied
    pRaster, hcond, zline = extraplots.raster_plot(
        spikeTimesFromEventOnset,
        indexLimitsEachTrial,
        timeRange,
        trialsEachCond=trialsEachCond,
        labels=labels, *args, **kwargs)
    #Set the marker size for better viewing
    plt.setp(pRaster, ms=ms)
Exemplo n.º 31
0
def compute_psycurve(bdata):
    targetFrequency=bdata['targetFrequency']
    valid=bdata['valid']
    choice=bdata['choice']
    intensities=bdata['targetIntensity']
    choiceRight = choice==bdata.labels['choice']['right']

    #Find trials at each frequency
    possibleFreq = np.unique(targetFrequency)
    nFreq = len(possibleFreq) 
    trialsEachFreq = behavioranalysis.find_trials_each_type(targetFrequency,possibleFreq)

    #Preallocate arrays
    fractionRightEachFreq=np.empty(nFreq)
    confLimitsEachFreq=np.empty([2, nFreq]) #Upper and lower confidence limits
    nTrialsEachFreq = np.empty(nFreq)
    nRightwardEachFreq = np.empty(nFreq)

    #Compute the number right and c.i for each freq.
    for indf,thisFreq in enumerate(possibleFreq): 

        nTrialsThisFreq = sum(valid & trialsEachFreq[:,indf])
        nRightwardThisFreq =  sum(valid & choiceRight & trialsEachFreq[:,indf])
        conf = np.array(proportion_confint(nRightwardThisFreq, nTrialsThisFreq, method = 'wilson'))

        nTrialsEachFreq[indf] = nTrialsThisFreq
        nRightwardEachFreq[indf] = nRightwardThisFreq
        confLimitsEachFreq[0, indf] = conf[0] # Lower ci
        confLimitsEachFreq[1, indf] = conf[1] # Upper ci

    #Compute %right (c.i. are already in percent)
    fractionRightEachFreq = nRightwardEachFreq/nTrialsEachFreq.astype(float)

    #plot(possibleFreq,fractionRightEachFreq,'-o')
    #gca().set_xscale('log')

    #Find lengths of whiskers for plotting function
    upperWhisker = confLimitsEachFreq[1, :] - fractionRightEachFreq
    lowerWhisker = fractionRightEachFreq - confLimitsEachFreq[0,:]

    return nRightwardEachFreq, nTrialsEachFreq, fractionRightEachFreq, upperWhisker, lowerWhisker
Exemplo n.º 32
0
def band_SNR_psychometric(animal, sessions, paradigm = '2afc'):
    loader = dataloader.DataLoader(animal)
    validPerSNR = None
    rightPerSNR = None
    for ind,session in enumerate(sessions):
        behavFile = loadbehavior.path_to_behavior_data(animal,paradigm,session)
        behavData = loader.get_session_behavior(behavFile)
        possibleSNRs = np.unique(behavData['currentSNR'])
        trialsEachCond = behavioranalysis.find_trials_each_type(behavData['currentSNR'], possibleSNRs)
        valid = behavData['valid'].astype(bool)
        rightChoice = behavData['choice']==behavData.labels['choice']['right']
        if validPerSNR is None:
            validPerSNR = np.zeros(len(possibleSNRs))
            rightPerSNR = np.zeros(len(possibleSNRs))
        for inds in range(len(possibleSNRs)):
            trialsThisSNR = trialsEachCond[:,inds]
            validThisSNR = np.sum(trialsThisSNR.astype(int)[valid]) 
            rightThisSNR = np.sum(trialsThisSNR.astype(int)[rightChoice])
            validPerSNR[inds] += validThisSNR
            rightPerSNR[inds] += rightThisSNR
    return validPerSNR, rightPerSNR, possibleSNRs
Exemplo n.º 33
0
def inactivated_cells_baselines(spikeTimeStamps,
                                eventOnsetTimes,
                                laserEachTrial,
                                baselineRange=[-0.05, 0.0]):
    '''For cells recorded during inhibitory cell inactivation, calculates baseline firing rate with and without laser.
    
    Inputs:
        spikeTimeStamps: array of timestamps indicating when spikes occurred
        eventOnsetTimes: array of timestamps indicating sound onsets
        firstSort: array of length N trials indicating whether laser was presented for each trial
        baselineRange: time range (relative to sound onset) to be used as baseline, list of [start time, end time]
        
    Outputs:
        baselineSpikeRates: array of length (N laser trial types), indicating baseline firing rate for each type of laser trial
        baselineSEMs: like baselineSpikeRates, gives s.e.m. for each value in baselineSpikeRates
    '''
    bandSpikeTimesFromEventOnset, trialIndexForEachSpike, bandIndexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimeStamps, eventOnsetTimes, baselineRange)

    numLaser = np.unique(laserEachTrial)
    baselineDuration = baselineRange[1] - baselineRange[0]
    baselineSpikeRates = np.zeros(len(numLaser))
    baselineSEMs = np.zeros_like(baselineSpikeRates)
    trialsEachLaser = behavioranalysis.find_trials_each_type(
        laserEachTrial, numLaser)
    baselineSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        bandSpikeTimesFromEventOnset, bandIndexLimitsEachTrial, baselineRange)

    for las in range(len(numLaser)):
        trialsThisLaser = trialsEachLaser[:, las]
        if baselineSpikeCountMat.shape[0] != len(trialsThisLaser):
            baselineSpikeCountMat = baselineSpikeCountMat[:-1, :]
        baselineCounts = baselineSpikeCountMat[trialsThisLaser].flatten()
        baselineMean = np.mean(baselineCounts) / baselineDuration
        baselineSEM = stats.sem(baselineCounts) / baselineDuration

        baselineSpikeRates[las] = baselineMean
        baselineSEMs[las] = baselineSEM

    return baselineSpikeRates, baselineSEMs
Exemplo n.º 34
0
def best_window_freq_tuning(spikeTimesFromEventOnset,indexLimitsEachTrial, freqEachTrial):
    windowsToTry = [[0.0,0.1],[0.0,0.05],[0.1,0.15]]
    numFreqs = np.unique(freqEachTrial)
    
    zscores = np.zeros((len(windowsToTry),len(numFreqs)))
    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)
        
        trialsEachFreq = behavioranalysis.find_trials_each_type(freqEachTrial, numFreqs)
        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]]
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, windowToUse)
    return spikeCountMat, windowToUse
Exemplo n.º 35
0
def freq_tuning_fit(eventOnsetTimes,
                    spikeTimestamps,
                    bdata,
                    timeRange=[-0.2, 0.2],
                    intensityInds=None):
    # determine the best frequency of the cell by fitting gaussian curve to tuning data
    gaussFits = []
    bestFreqs = []
    Rsquareds = []

    freqEachTrial = bdata['currentFreq']
    intensityEachTrial = bdata['currentIntensity']
    numIntensities = np.unique(intensityEachTrial)
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
        spikeTimestamps, eventOnsetTimes, timeRange)
    trialsEachInt = behavioranalysis.find_trials_each_type(
        intensityEachTrial, numIntensities)
    if intensityInds is None:
        intensityInds = range(len(numIntensities))

    spikeCountMat, window = best_window_freq_tuning(spikeTimesFromEventOnset,
                                                    indexLimitsEachTrial,
                                                    freqEachTrial)
    for intensityInd in intensityInds:
        trialsThisIntensity = trialsEachInt[:, intensityInd]
        tuningSpikeRates = (spikeCountMat[trialsThisIntensity].flatten()) / (
            window[1] - window[0])
        freqsThisIntensity = freqEachTrial[trialsThisIntensity]
        gaussFit, Rsquared = response_curve_fit(np.log2(freqsThisIntensity),
                                                tuningSpikeRates)
        bestFreq = 2**gaussFit[0] if gaussFit is not None else None
        gaussFits.append(gaussFit)
        bestFreqs.append(bestFreq)
        Rsquareds.append(Rsquared)

    return gaussFits, bestFreqs, Rsquareds, window
Exemplo n.º 36
0
    # FIXME: I'm rounding the stimOnset. Not sure if this is the best option
    rangeLims = int(np.round(stimOnset)) + np.array(responseWindow)
    frameRange = np.arange(rangeLims[0], rangeLims[1])
    ftraceEachTrial[:, indEvent] = np.mean(ftraces[:, frameRange], axis=1)

# -- Load behavior --
behavFilename = loadbehavior.path_to_behavior_data(subject, paradigm,
                                                   behavSession)
bdata = loadbehavior.BehaviorData(behavFilename)
currentFreq = bdata['currentFreq']
if nEvents != len(currentFreq):
    currentFreq = currentFreq[:
                              nEvents]  #Events will stop sooner than behavior.
possibleFreq = np.unique(currentFreq)
nFreq = len(possibleFreq)
trialsEachType = behavioranalysis.find_trials_each_type(
    currentFreq, possibleFreq)

# -- Calculate response each freq --
respEachFreqMean = np.empty([nCells, nFreq])
respEachFreqStDev = np.empty([nCells, nFreq])
nTrialsEachFreq = np.sum(trialsEachType, axis=0)
for indf, oneFreq in enumerate(possibleFreq):
    trialsThisFreq = trialsEachType[:, indf]
    respEachFreqMean[:, indf] = np.mean(ftraceEachTrial[:, trialsThisFreq],
                                        axis=1)
    respEachFreqStDev[:, indf] = np.std(ftraceEachTrial[:, trialsThisFreq],
                                        axis=1)
respEachFreqSEM = respEachFreqStDev / np.sqrt(nTrialsEachFreq)

# -- Plot ophys --
# HighF: 78, 52, 77, 60, 113, 107, 226, 368
Exemplo n.º 37
0
def inactivation_base_stats(db, filename=''):
    laserTestStatistic = np.empty(len(db))
    laserPVal = np.empty(len(db))

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

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

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

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

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

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

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

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

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

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

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

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

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

    return db
Exemplo n.º 38
0
    if oneCell.get_session_inds('standard') != []:
        try:
            ephysDataStd, bdataStd = oneCell.load('standard')
        except ValueError as verror:
            continue

    spikeTimesStd = ephysDataStd['spikeTimes']
    eventOnsetTimesStd = ephysDataStd['events']['stimOn']
    if len(eventOnsetTimesStd) == len(bdataStd['currentFreq']) + 1:
        eventOnsetTimesStd = eventOnsetTimesStd[:-1]
    (spikeTimesFromEventOnsetStd,trialIndexForEachSpikeStd,indexLimitsEachTrialStd) = \
            spikesanalysis.eventlocked_spiketimes(spikeTimesStd, eventOnsetTimesStd, timeRange)
    frequenciesEachTrialStd = bdataStd['currentFreq']
    arrayOfFrequenciesStd = np.unique(bdataStd['currentFreq'])

    trialsEachCondStd = behavioranalysis.find_trials_each_type(
        frequenciesEachTrialStd, arrayOfFrequenciesStd)

    # -- Oddball session --
    if oneCell.get_session_inds('oddball') != []:
        try:
            ephysDataOdd, bdataOdd = oneCell.load('oddball')
        except ValueError as verror:
            continue

    spikeTimesOdd = ephysDataOdd['spikeTimes']
    eventOnsetTimesOdd = ephysDataOdd['events']['stimOn']
    if len(eventOnsetTimesOdd) == len(bdataOdd['currentFreq']) + 1:
        eventOnsetTimesOdd = eventOnsetTimesOdd[:-1]
    (spikeTimesFromEventOnsetOdd, trialIndexForEachSpikeOdd,
     indexLimitsEachTrialOdd) = spikesanalysis.eventlocked_spiketimes(
         spikeTimesOdd, eventOnsetTimesOdd, timeRange)
def plot_ave_psycurve_reward_change(animal, sessions):
    FREQCOLORS = [
        '0.3', colorpalette.TangoPalette['Orange2'],
        colorpalette.TangoPalette['SkyBlue2']
    ]

    allBehavDataThisAnimal = behavioranalysis.load_many_sessions(
        animal, sessions)
    targetFrequency = allBehavDataThisAnimal['targetFrequency']
    choice = allBehavDataThisAnimal['choice']
    valid = allBehavDataThisAnimal['valid'] & (
        choice != allBehavDataThisAnimal.labels['choice']['none'])
    choiceRight = choice == allBehavDataThisAnimal.labels['choice']['right']
    currentBlock = allBehavDataThisAnimal['currentBlock']
    blockTypes = [
        allBehavDataThisAnimal.labels['currentBlock']['same_reward'],
        allBehavDataThisAnimal.labels['currentBlock']['more_left'],
        allBehavDataThisAnimal.labels['currentBlock']['more_right']
    ]
    #blockTypes = [allBehavDataThisAnimal.labels['currentBlock']['more_left'],allBehavDataThisAnimal.labels['currentBlock']['more_right']]
    blockLabels = ['same_reward', 'more_left', 'more_right']
    #blockLabels = ['more_left','more_right']
    trialsEachType = behavioranalysis.find_trials_each_type(
        currentBlock, blockTypes)

    nFreqs = len(np.unique(targetFrequency))
    #print trialsEachType
    nBlocks = len(blockTypes)
    #thisAnimalPos = inda
    #ax1=plt.subplot(gs[thisAnimalPos])
    #plt.clf()
    fontsize = 12
    allPline = []
    blockLegends = []
    fractionHitsEachValueAllBlocks = np.empty((nBlocks, nFreqs))

    for blockType in range(nBlocks):
        if np.any(trialsEachType[:, blockType]):
            targetFrequencyThisBlock = targetFrequency[
                trialsEachType[:, blockType]]
            validThisBlock = valid[trialsEachType[:, blockType]]
            choiceRightThisBlock = choiceRight[trialsEachType[:, blockType]]
            #currentBlockValue = currentBlock[trialsEachBlock[0,block]]
            (possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue)=\
            behavioranalysis.calculate_psychometric(choiceRightThisBlock,targetFrequencyThisBlock,validThisBlock)

            logPossibleValues = np.log2(possibleValues)
            lowerFreqConstraint = logPossibleValues[1]
            upperFreqConstraint = logPossibleValues[-2]
            maxFreq = max(logPossibleValues)
            minFreq = min(logPossibleValues)

            constraints = ('Uniform({}, {})'.format(lowerFreqConstraint,
                                                    upperFreqConstraint),
                           'Uniform(0,5)', 'Uniform(0,1)', 'Uniform(0,1)')
            estimate = extrastats.psychometric_fit(logPossibleValues,
                                                   nTrialsEachValue,
                                                   nHitsEachValue, constraints)

            fractionHitsEachValueAllBlocks[
                blockType, :] = fractionHitsEachValue

            upperWhisker = ciHitsEachValue[1, :] - fractionHitsEachValue
            lowerWhisker = fractionHitsEachValue - ciHitsEachValue[0, :]

            xRange = logPossibleValues[-1] - logPossibleValues[1]
            fitxvals = np.linspace(logPossibleValues[0] - 0.1 * xRange,
                                   logPossibleValues[-1] + 0.1 * xRange, 40)
            fityvals = extrastats.psychfun(fitxvals, *estimate)

            # (pline, pcaps, pbars, pdots) = extraplots.plot_psychometric(1e-3*possibleValues,fractionHitsEachValue,  ciHitsEachValue,xTickPeriod=1)

            ax = plt.gca()
            ax.hold(True)
            (pline, pcaps, pbars) = ax.errorbar(
                logPossibleValues,
                100 * fractionHitsEachValue,
                yerr=[100 * lowerWhisker, 100 * upperWhisker],
                ecolor=FREQCOLORS[blockType],
                fmt=None,
                clip_on=False)

            pdots = ax.plot(logPossibleValues,
                            100 * fractionHitsEachValue,
                            'o',
                            ms=6,
                            mec='None',
                            mfc=FREQCOLORS[blockType],
                            clip_on=False)
            if blockType == 0:
                pfit = ax.plot(fitxvals,
                               100 * fityvals,
                               color=FREQCOLORS[blockType],
                               lw=2,
                               clip_on=False,
                               linestyle='--')
            else:
                pfit = ax.plot(fitxvals,
                               100 * fityvals,
                               color=FREQCOLORS[blockType],
                               lw=2,
                               clip_on=False)

            # plt.setp((pline, pcaps, pbars), color=FREQCOLORS[blockType])
            # plt.setp((pline, pbars), color=FREQCOLORS[blockType])
            # plt.setp(pdots, mfc=FREQCOLORS[blockType], mec=FREQCOLORS[blockType])
            allPline.append(pline)
            blockLegends.append(blockLabels[blockType])

            if blockType == nBlocks - 1:
                plt.xlabel('Frequency (kHz)', fontsize=fontsize)
                plt.ylabel('Rightward trials (%)', fontsize=fontsize)
                extraplots.set_ticks_fontsize(plt.gca(), fontsize)
                ax.set_xticks(logPossibleValues)
                tickLabels = [''] * len(possibleValues)
                tickLabels[0] = 6.2
                tickLabels[-1] = 19.2
                ax.set_xticklabels(tickLabels)
                ax.axhline(y=50, linestyle='-', color='0.7')
                extraplots.boxoff(ax)
                # legend = plt.legend(allPline,blockLegends,loc=2) #Add the legend manually to the current Axes.
                # ax = plt.gca().add_artist(legend)
                #plt.hold(True)
        #plt.legend(bbox_to_anchor=(1, 1), bbox_transform=plt.gcf().transFigure)
        #plt.show()
    # plt.title('%s %s-%s'%(animal,sessions[0],sessions[-1]))
    return fractionHitsEachValueAllBlocks
Exemplo n.º 40
0
     tuningWindow = [0,0]
     octavesFromBest = np.nan
     bandIndex = np.nan
 else:
     tuningEventOnsetTimes = 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 = 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
Exemplo n.º 41
0
def plot_bandwidth_report(cell, bandIndex):
    cellInfo = get_cell_info(cell)
    #pdb.set_trace()
    loader = dataloader.DataLoader(cell['subject'])
    
    if len(cellInfo['laserIndex'])>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)
     
     # -- plot bandwidth rasters --
    plt.clf()
    eventData = loader.get_session_events(cellInfo['ephysDirs'][bandIndex])
    spikeData = loader.get_session_spikes(cellInfo['ephysDirs'][bandIndex], cellInfo['tetrode'], cluster=cellInfo['cluster'])
    eventOnsetTimes = loader.get_event_onset_times(eventData)
    spikeTimestamps = spikeData.timestamps
    timeRange = [-0.2, 1.5]
    bandBData = loader.get_session_behavior(cellInfo['behavDirs'][bandIndex])  
    bandEachTrial = bandBData['currentBand']
    ampEachTrial = bandBData['currentAmp']
    charfreq = str(np.unique(bandBData['charFreq'])[0]/1000)
    modrate = str(np.unique(bandBData['modRate'])[0])
    numBands = np.unique(bandEachTrial)
    numAmps = np.unique(ampEachTrial)
            
    firstSortLabels = ['{}'.format(band) for band in np.unique(bandEachTrial)]
    secondSortLabels = ['Amplitude: {}'.format(amp) for amp in np.unique(ampEachTrial)]      
    spikeTimesFromEventOnset, indexLimitsEachTrial, trialsEachCond, firstSortLabels = bandwidth_raster_inputs(eventOnsetTimes, spikeTimestamps, bandEachTrial, ampEachTrial)
    colours = [np.tile(['#4e9a06','#8ae234'],len(numBands)/2+1), np.tile(['#5c3566','#ad7fa8'],len(numBands)/2+1)]
    for ind, secondArrayVal in enumerate(numAmps):
        plt.subplot(gs[5+2*ind+offset:7+2*ind+offset, 0:3])
        trialsThisSecondVal = trialsEachCond[:, :, ind]
        pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,
                                                        indexLimitsEachTrial,
                                                        timeRange,
                                                        trialsEachCond=trialsThisSecondVal,
                                                        labels=firstSortLabels,
                                                        colorEachCond = colours[ind])
        plt.setp(pRaster, ms=4)        
        plt.title(secondSortLabels[ind])
        plt.ylabel('bandwidth (octaves)')
        if ind == len(np.unique(ampEachTrial)) - 1:
            plt.xlabel("Time from sound onset (sec)")
    
           
    # -- plot Yashar plots for bandwidth data --
    plt.subplot(gs[5+offset:, 3:])
    spikeArray, errorArray, baseSpikeRate = band_select(spikeTimestamps, eventOnsetTimes, ampEachTrial, bandEachTrial, timeRange = [0.0, 1.0])
    band_select_plot(spikeArray, errorArray, baseSpikeRate, numBands, legend=True)
            
    # -- plot frequency tuning heat map -- 
    tuningBData = loader.get_session_behavior(cellInfo['behavDirs'][cellInfo['tuningIndex'][-1]])
    freqEachTrial = tuningBData['currentFreq']
    intEachTrial =  tuningBData['currentIntensity']
            
    eventData = loader.get_session_events(cellInfo['ephysDirs'][cellInfo['tuningIndex'][-1]])
    spikeData = loader.get_session_spikes(cellInfo['ephysDirs'][cellInfo['tuningIndex'][-1]], cellInfo['tetrode'], cluster=cellInfo['cluster'])
    eventOnsetTimes = loader.get_event_onset_times(eventData)
    spikeTimestamps = spikeData.timestamps
    
    plt.subplot(gs[2+offset:4+offset, 0:3])       
    dataplotter.two_axis_heatmap(spikeTimestamps=spikeTimestamps,
                                    eventOnsetTimes=eventOnsetTimes,
                                    firstSortArray=intEachTrial,
                                    secondSortArray=freqEachTrial,
                                    firstSortLabels=["%.0f" % inten for inten in np.unique(intEachTrial)],
                                    secondSortLabels=["%.1f" % freq for freq in np.unique(freqEachTrial)/1000.0],
                                    xlabel='Frequency (kHz)',
                                    ylabel='Intensity (dB SPL)',
                                    plotTitle='Frequency Tuning Curve',
                                    flipFirstAxis=False,
                                    flipSecondAxis=False,
                                    timeRange=[0, 0.1])
    plt.ylabel('Intensity (dB SPL)')
    plt.xlabel('Frequency (kHz)')
    plt.title('Frequency Tuning Curve')
            
    # -- plot frequency tuning raster --
    plt.subplot(gs[0+offset:2+offset, 0:3])
    freqLabels = ["%.1f" % freq for freq in np.unique(freqEachTrial)/1000.0]
    dataplotter.plot_raster(spikeTimestamps, eventOnsetTimes, sortArray=freqEachTrial, timeRange=[-0.1, 0.5], labels=freqLabels)
    plt.xlabel('Time from sound onset (sec)')
    plt.ylabel('Frequency (kHz)')
    plt.title('Frequency Tuning Raster')
            
    # -- plot AM PSTH --
    amBData = loader.get_session_behavior(cellInfo['behavDirs'][cellInfo['amIndex'][-1]])
    rateEachTrial = amBData['currentFreq']
    
    eventData = loader.get_session_events(cellInfo['ephysDirs'][cellInfo['amIndex'][-1]])
    spikeData = loader.get_session_spikes(cellInfo['ephysDirs'][cellInfo['amIndex'][-1]], cellInfo['tetrode'], cluster=cellInfo['cluster'])
    eventOnsetTimes = loader.get_event_onset_times(eventData)
    spikeTimestamps = spikeData.timestamps
    timeRange = [-0.2, 1.5]
    
    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                                                                                                spikeTimestamps, eventOnsetTimes, timeRange)
    colourList = ['b', 'g', 'y', 'orange', 'r']
    numRates = np.unique(rateEachTrial)
    trialsEachCond = behavioranalysis.find_trials_each_type(rateEachTrial, numRates)
    plt.subplot(gs[2+offset:4+offset, 3:])
    dataplotter.plot_psth(spikeTimestamps, eventOnsetTimes, 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)]
    dataplotter.plot_raster(spikeTimestamps, eventOnsetTimes, sortArray=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 -- 
        plt.subplot(gs[0:2, 0:3])
        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
        timeRange = [-0.1, 0.4]
        dataplotter.plot_raster(spikeTimestamps, eventOnsetTimes, timeRange=timeRange)
        plt.xlabel('Time from sound onset (sec)')
        plt.title('Laser Pulse Raster')
        
        # -- plot laser pulse psth --
        plt.subplot(gs[2:4, 0:3])
        dataplotter.plot_psth(spikeTimestamps, eventOnsetTimes, timeRange = timeRange, binsize = 10)
        plt.xlabel('Time from sound onset (sec)')
        plt.ylabel('Firing Rate (Hz)')
        plt.title('Laser Pulse PSTH')
        
        # -- didn't record laser trains for some earlier sessions --
        if len(cellInfo['laserTrainIndex']) > 0:
            # -- plot laser train raster --
            plt.subplot(gs[0:2, 3:])
            eventData = loader.get_session_events(cellInfo['ephysDirs'][cellInfo['laserTrainIndex'][-1]])
            spikeData = loader.get_session_spikes(cellInfo['ephysDirs'][cellInfo['laserTrainIndex'][-1]], cellInfo['tetrode'], cluster=cellInfo['cluster'])
            eventOnsetTimes = loader.get_event_onset_times(eventData)
            spikeTimestamps = spikeData.timestamps
            timeRange = [-0.2, 1.0]
            dataplotter.plot_raster(spikeTimestamps, eventOnsetTimes, timeRange=timeRange)
            plt.xlabel('Time from sound onset (sec)')
            plt.title('Laser Train Raster')
            
            # -- plot laser train psth --
            plt.subplot(gs[2:4, 3:])
            dataplotter.plot_psth(spikeTimestamps, eventOnsetTimes, timeRange = timeRange, binsize = 10)
            plt.xlabel('Time from sound onset (sec)')
            plt.ylabel('Firing Rate (Hz)')
            plt.title('Laser Train PSTH')
        
    # -- show cluster analysis --
    tsThisCluster, wavesThisCluster = load_cluster_waveforms(cellInfo)
    
    # -- Plot ISI histogram --
    plt.subplot(gs[4+offset, 0:2])
    spikesorting.plot_isi_loghist(tsThisCluster)
    plt.ylabel('c%d'%cellInfo['cluster'],rotation=0,va='center',ha='center')
    plt.xlabel('')

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

    # -- Plot events in time --
    plt.subplot(gs[4+offset, 4:6])
    spikesorting.plot_events_in_time(tsThisCluster)

    plt.suptitle('{0}, {1}, {2}um, Tetrode {3}, Cluster {4}, {5}kHz, {6}Hz modulation'.format(cellInfo['subject'], 
                                                                                            cellInfo['date'], 
                                                                                            cellInfo['depth'], 
                                                                                            cellInfo['tetrode'], 
                                                                                            cellInfo['cluster'], 
                                                                                            charfreq, 
                                                                                            modrate))
    
    fig_path = '/home/jarauser/Pictures/cell reports'
    fig_name = '{0}_{1}_{2}um_TT{3}Cluster{4}.png'.format(cellInfo['subject'], cellInfo['date'], cellInfo['depth'], cellInfo['tetrode'], cellInfo['cluster'])
    full_fig_path = os.path.join(fig_path, fig_name)
    fig = plt.gcf()
    fig.set_size_inches(20, 25)
    fig.savefig(full_fig_path, format = 'png', bbox_inches='tight')
ax=subplot(111)
ax.plot(fr_array, 'k-', linewidth=3)
ax.set_xticks(range(len(possibleFreq)))
ax.set_xticklabels(['{:3.0f}'.format(x) for x in possibleFreq])
ax.set_xlabel('Modulation Frequency')
ax.set_ylabel('Average Firing Rate (spks/sec)')



#############################################################################
timeRange=[0, 0.5]
spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(spikeTimestamps,eventOnsetTimes,timeRange)

from jaratoolbox import behavioranalysis

trialsEachType = behavioranalysis.find_trials_each_type(currentFreq, np.unique(currentFreq))

#I want to get the raster for one frequency. I am certain I am re-inventing
#the wheel here but it has been a while. 

#Trials where the freq was 4


#Indices of spikes that came from that trial




# np.flatnonzero(trialIndexForEachSpike==8)

# #Spiketimes from event onset for trial 8
Exemplo n.º 43
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()
Exemplo n.º 44
0
behavioranalysis.behavior_summary(animalName,session)

sys.exit()

behavFile = loadbehavior.path_to_behavior_data(animalName,experimenter,paradigm,session)
bdata = loadbehavior.FlexCategBehaviorData(behavFile)

targetFrequency = bdata['targetFrequency']
choice=bdata['choice']
valid=bdata['valid']& (choice!=bdata.labels['choice']['none'])
choiceRight = choice==bdata.labels['choice']['right']

possibleFreq = np.unique(targetFrequency)
nFreq = len(possibleFreq) 
trialsEachFreq = behavioranalysis.find_trials_each_type(targetFrequency,possibleFreq)

(possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue)=\
   behavioranalysis.calculate_psychometric(choiceRight,targetFrequency,valid)

(pline, pcaps, pbars, pdots) = extraplots.plot_psychometric(possibleValues,fractionHitsEachValue,ciHitsEachValue)

'''
upperWhisker = ciHitsEachValue[1,:]-fractionHitsEachValue
lowerWhisker = fractionHitsEachValue-ciHitsEachValue[0,:]

(pline, pcaps, pbars) = errorbar(possibleValues, 100*fractionHitsEachValue, 
                                 yerr = [100*lowerWhisker, 100*upperWhisker],color='k')
plot(possibleValues, 100*fractionHitsEachValue, 'o',mec='none',mfc='k',ms=8)
setp(pline,lw=2)
axhline(y=50, color = '0.5',ls='--')
    soundOnsetTimeBehav = bdata['timeTarget']

    diffTimes = bdata['timeCenterOut'] - bdata['timeTarget']
    #movementOnsetTimeEphys = soundOnsetTimeEphys + diffTimes

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

    # -- Calculate and store intermediate data for tuning raster -- #
    freqEachTrial = bdata['targetFrequency']
    valid = bdata['valid'].astype('bool')
    possibleFreq = np.unique(freqEachTrial)
    trialsEachFreq = behavioranalysis.find_trials_each_type(
        freqEachTrial, possibleFreq)
    trialsEachFreq = trialsEachFreq & valid[:, np.
                                            newaxis]  #Use only valid trials where sound is played in full

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

    ### Save raster data ###
    #outputDir = os.path.join(settings.FIGURESDATA, figparams.STUDY_NAME)
    outputFile = 'example_freq_tuning_2afc_raster_{}_{}_T{}_c{}.npz'.format(
        oneCell.animalName, oneCell.behavSession, oneCell.tetrode,
        oneCell.cluster)
    outputFullPath = os.path.join(dataDir, outputFile)
    np.savez(outputFullPath,
             spikeTimestamps=spikeTimestamps,
             eventOnsetTimes=eventOnsetTimes,
Exemplo n.º 46
0
plt.figure()
for indSubject, subject in enumerate(subjects):
	for indSession, session in enumerate(sessions):	
		plt.subplot(len(subjects), 1, indSubject+1)
		bdata = behavioranalysis.load_many_sessions(subject, [session])

		targetIntensity = bdata['targetIntensity']
		valid = bdata['valid']
		choice = bdata['choice']

		#Is this the correct thing to get to calculate psychometrics?
		choiceRight = choice==bdata.labels['choice']['right']
		targetFreq = bdata['targetFrequency']

		possibleInt = np.unique(targetIntensity)
		trialsEachInt = behavioranalysis.find_trials_each_type(targetIntensity,possibleInt)

		trialsInds = {}
		allPlines = []
		for indInt, inten in enumerate(possibleInt):
			trialsInds[inten] = valid&(bdata['targetIntensity']==inten)
			(possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue)=\
			behavioranalysis.calculate_psychometric(choiceRight, targetFreq, trialsInds[inten])

			(pline, pcaps, pbars, pdots) = extraplots.plot_psychometric(1e-3*possibleValues,fractionHitsEachValue,ciHitsEachValue,xTickPeriod=1)

			allPlines.append(pline)

			plt.title(subject+' - '+session, fontsize=fontsize)
			plt.xlabel('Frequency (kHz)',fontsize=fontsize)
			plt.ylabel('Rightward trials (%)',fontsize=fontsize)
Exemplo n.º 47
0
        spikeData.samples=spikeData.samples[spikeData.clusters==cluster]
        spikeData.timestamps=spikeData.timestamps[spikeData.clusters==cluster]
    
    # convert to seconds and millivolts
    spikeData.samples = spikeData.samples.astype(float)-2**15
    spikeData.samples = (1000.0/spikeData.gain[0,0]) * spikeData.samples
    spikeData.timestamps = spikeData.timestamps/spikeData.samplingRate
    eventData.timestamps = eventData.timestamps/eventData.samplingRate
    return eventData, spikeData
    
def load_behaviour_data(subject, fileName):
    behavFile = os.path.join(settings.BEHAVIOR_PATH,subject,fileName)
    bdata = loadbehavior.BehaviorData(behavFile,readmode='full')
    return bdata

# LOAD YOUR SHIT
eventData, spikeData = load_ephys_data(SUBJECT, EPHYSSESSION, tetrode, cluster)
eventOnsetTimes = eventData.get_event_onset_times()
spikeTimeStamps = spikeData.timestamps
tuningBData = load_behaviour_data(SUBJECT, BEHAVIORSESSION)   

freqEachTrial = tuningBData['currentFreq']

trialsEachCond = behavioranalysis.find_trials_each_type(freqEachTrial, np.unique(freqEachTrial))
spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
    spikeTimeStamps, eventOnsetTimes, timeRange)
pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange,
                                               trialsEachCond=trialsEachCond, *args, **kwargs)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.setp(pRaster, ms=ms)
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))
def get_trials_each_cond_reward_change(animal, behavSession, ephysSession, tetrode, cluster, freqToPlot, byBlock, colorCondDict):
    '''Function to generate selection vector showing which trials to plot for each behavior conditions and the color to use in the plot label.
    :param arg1: A string of the file name of the 2afc behavior session, this is the full filename in '{animal}_{paradigm}_{date}{behavsuffix}.h5' format.
    :param arg2: A string of the file name of the 2afc ephys session, this is the full filename, in {date}_XX-XX-XX format.
    :param arg3: An int in range(1,9) for tetrode number.
    :param arg4: An int for cluster number.
    :param arg5: A string indicating which frequency to plot, value of 'low' or 'high'.
    :param arg6: Boolean indicating whether to split the plot by behavior blocks. 
    :param arg7: A dictionary indicating which color label each behavior condition gets in the final plot.
    
    :return: bData object, trialsEachCond, colorsEachCond
    '''
    
    bdata = load_n_remove_missing_trials_2afc_behav(animal, behavSession, ephysSession, tetrode, cluster)

    # -- Select trials to plot from behavior file -- #
    correct = bdata['outcome']==bdata.labels['outcome']['correct']
    possibleFreq = np.unique(bdata['targetFrequency'])
    numFreqs = len(possibleFreq)
    currentBlock = bdata['currentBlock']
    # -- Select trials to plot based on desired frequencies to plot and whether to plot by block -- #
    ### Recordings during reward change usually have 2 frequencies, low freq means go to left, right freq means go to right ###
    if freqToPlot == 'low':
        freq = possibleFreq[0] 

    elif freqToPlot == 'high':
        freq = possibleFreq[1]

    oneFreq = bdata['targetFrequency'] == freq #vector for selecing trials presenting this frequency
    correctOneFreq = oneFreq  & correct 

    # -- Find trials each block (if plotting mid frequency by block) or find trials each type (e.g. low-boundary, high-boundary; if not plotting by block) -- #
    if byBlock:
        bdata.find_trials_each_block()
        numBlocks = bdata.blocks['nBlocks']
        trialsEachBlock = bdata.blocks['trialsEachBlock']
        correctTrialsEachBlock = trialsEachBlock & correctOneFreq[:,np.newaxis]
        correctBlockSizes = sum(correctTrialsEachBlock)
        if (correctBlockSizes[-1] < minBlockSize): #A check to see if last block is too small to plot
            correctTrialsEachBlock = correctTrialsEachBlock[:,:-1]
            numBlocks -= 1
        trialsEachCond = correctTrialsEachBlock
        
        colorEachCond = np.empty(numBlocks, dtype=object)
        labelEachCond = np.empty(numBlocks, dtype=object)
        #pdb.set_trace()
        for blockNum in range(numBlocks):
            currentBlockLabel = currentBlock[trialsEachBlock[:,blockNum]][0]
            if freqToPlot == 'low':
                if currentBlockLabel == bdata.labels['currentBlock']['same_reward']:
                    colorEachCond[blockNum] = colorCondDict['sameRewardLowFreq']
                    labelEachCond[blockNum] = 'low freq same reward'
                elif currentBlockLabel == bdata.labels['currentBlock']['more_left']:
                    colorEachCond[blockNum] = colorCondDict['leftMoreLowFreq'] 
                    labelEachCond[blockNum] = 'low freq left more'
                elif currentBlockLabel == bdata.labels['currentBlock']['more_right']:   
                    colorEachCond[blockNum] = colorCondDict['rightMoreLowFreq']
                    labelEachCond[blockNum] = 'low freq right more'
            elif freqToPlot == 'high':
                if currentBlockLabel == bdata.labels['currentBlock']['same_reward']:
                    colorEachCond[blockNum] = colorCondDict['sameRewardHighFreq']
                    labelEachCond[blockNum] = 'high freq same reward'
                elif currentBlockLabel == bdata.labels['currentBlock']['more_left']:
                    colorEachCond[blockNum] = colorCondDict['leftMoreHighFreq'] 
                    labelEachCond[blockNum] = 'high freq left more'
                elif currentBlockLabel == bdata.labels['currentBlock']['more_right']:   
                    colorEachCond[blockNum] = colorCondDict['rightMoreHighFreq']
                    labelEachCond[blockNum] = 'high freq right more'

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

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

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

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

            plt.subplots_adjust(wspace = 1.5)
            plt.suptitle('{0}, {1}, {2}, Tetrode {3}, Cluster {4}, {5}kHz, {6}Hz modulation'.format(mouse, date, siteName, tetrode, cluster, charfreq, modrate))
            fig_path = oneTT.clustersDir
            fig_name = 'TT{0}Cluster{1}.png'.format(tetrode, cluster)
            full_fig_path = os.path.join(fig_path, fig_name)
            fig = plt.gcf()
            fig.set_size_inches(24, 12)
            fig.savefig(full_fig_path, format = 'png', bbox_inches='tight')
                print possibleFreq
                numberOfFrequencies = len(possibleFreq)
                numberOfTrials = len(bdata['choice'])
                targetFreqs = bdata['targetFrequency']
                currentBlock = bdata['currentBlock']

                #######20160324 Implemented trialLimit constraint to exclude blocks with few trials at the end of a behav session 
                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

                blockTypes = [bdata.labels['currentBlock']['same_reward'],bdata.labels['currentBlock']['more_left'],bdata.labels['currentBlock']['more_right']]
                #blockLabels = ['same_reward','more_left', 'more_right']
                trialsEachType = behavioranalysis.find_trials_each_type(currentBlock,blockTypes) #trialsEachType is an array of dimension nTrials*nblockTypes where boolean vector (in a column) indicates which trials are in each type of block

                for possFreq in possibleFreq:
                    modIDict[behavSession][possFreq] = np.zeros([clusNum*numTetrodes]) #0 being no modIndex
                    modSigDict[behavSession][possFreq] = np.ones([clusNum*numTetrodes]) #1 being no significance test

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

            clusterNumber = (oneCell.tetrode-1)*clusNum+(oneCell.cluster-1)
            for Freq in possibleFreq:
                oneFreq = targetFreqs == Freq
                if Freq <= 9500:  #Arbitrary boundary based on behavior sessions so far. This is a 'low' freq - going left trial 
                    trialsToUseMoreReward = trialsEachType[:,1]&oneFreq&correct&validTrials #trialsEachType[:,1] are all the 'more_left' trials.
Exemplo n.º 52
0
    freqEachTrial = freqEachTrial[:nTrials]
    intensityEachTrial = intensityEachTrial[:nTrials]
    eventOnsetTimes = eventOnsetTimes[:nTrials]


possibleFreq = np.unique(freqEachTrial)
possibleIntensity = np.unique(intensityEachTrial)

# -- Find trials for each frequency and sort them --
if selectedIntensity is None:
    selectedTrials = np.ones(nTrials,dtype=bool)
else:
    selectedTrials = (intensityEachTrial==selectedIntensity)

freqEachTrial = freqEachTrial[selectedTrials]
trialsEachFreq = behavioranalysis.find_trials_each_type(freqEachTrial,possibleFreq)
###trialsEachFreq &= selectedTrials[:,np.newaxis]
numTrialsEachFreq = trialsEachFreq.sum(axis=0)
sortedTrials = np.nonzero(trialsEachFreq.T)[1] # The second array contains the sorted indexes
sortingInds = np.argsort(sortedTrials) # gives array of indices that would sort the sortedTrials

eventOnsetTimes = eventOnsetTimes[selectedTrials]


for indt,tetrodeID in enumerate(tetrodes):

    spikesFilename = os.path.join(fullephysDir, 'Tetrode{0}.spikes'.format(tetrodeID)) # make a path to ephys spike data of specified tetrode tetrodeID
    sp = loadopenephys.DataSpikes(spikesFilename) # load spike data from specified tetrode tetrodeID
    spkTimeStamps = np.array(sp.timestamps)/SAMPLING_RATE # array of timestamps for each spike in seconds (thats why you divide by sampling rate)
    (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
        spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange)
nAnimals = len(subjects)
gs = gridspec.GridSpec(nAnimals, 1)#changed from nAnimals to plot one animal with multiple sessions
gs.update(hspace=0.5,wspace=0.4)
plt.clf()

for inda, thisAnimal in enumerate(subjects):
    allBehavDataThisAnimal = behavioranalysis.load_many_sessions(thisAnimal,sessions)
    
    targetFrequency = allBehavDataThisAnimal['targetFrequency']
    choice=allBehavDataThisAnimal['choice']
    valid=allBehavDataThisAnimal['valid']& (choice!=allBehavDataThisAnimal.labels['choice']['none'])
    choiceRight = choice==allBehavDataThisAnimal.labels['choice']['right']
    currentBlock = allBehavDataThisAnimal['currentBlock']
    blockTypes = [allBehavDataThisAnimal.labels['currentBlock']['same_reward'],allBehavDataThisAnimal.labels['currentBlock']['more_left'],allBehavDataThisAnimal.labels['currentBlock']['more_right']]
    blockLabels = ['same_reward','more_left', 'more_right']
    trialsEachType = behavioranalysis.find_trials_each_type(currentBlock,blockTypes)
    
    #print trialsEachType
    nBlocks = len(blockTypes)
    thisAnimalPos = inda
    ax1=plt.subplot(gs[thisAnimalPos])
    fontsize = 12
    allPline = []
    legendLabels = []
    for blockType in range(nBlocks):
        targetFrequencyThisBlock = targetFrequency[trialsEachType[:,blockType]]    
        validThisBlock = valid[trialsEachType[:,blockType]]
        choiceRightThisBlock = choiceRight[trialsEachType[:,blockType]]
        #currentBlockValue = currentBlock[trialsEachBlock[0,block]]
        (possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue)=\
                                                                                                behavioranalysis.calculate_psychometric(choiceRightThisBlock,targetFrequencyThisBlock,validThisBlock)
Exemplo n.º 54
0
#ex0624.plot_sorted_tuning_raster('15-31-48', 6, 'a', ms=4)

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

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

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

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

spikeTimestamps=spikeData.timestamps


timeRange = [0, 0.1]

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