Esempio n. 1
0
def nice_psycurve_settings(ax, fitcolor=None, fontsize=20, lineweight=3, fitlineinds=[3]):

    '''
    A hack for setting some psycurve axes properties, especially the weight of the line and the xticks
    I made this because I am using the fxn plot_psycurve_fit_and_data, which obscures handles to things
    that I later need (like the lines, etc. ) This function will be useless if I make plots in a better way. 

    '''

    extraplots.boxoff(ax)
    extraplots.set_ticks_fontsize(ax, fontsize)


    for lineind in fitlineinds:
        fitline = ax.lines[lineind]
        plt.setp(fitline, lw=lineweight)

    if fitcolor:
        plt.setp(fitline, color=fitcolor)

    xticklabels = [item.get_text() for item in ax.get_xticklabels()]
    xticks = ax.get_xticks()
    newXtickLabels = np.logspace(xticks[0], xticks[-1], 3, base=2)

    ax.set_xticks(np.log2(np.array(newXtickLabels)))
    if min(newXtickLabels) > 1000:
        ax.set_xticklabels(['{:.3}'.format(x/1000.0) for x in newXtickLabels])
    else:
        ax.set_xticklabels(['{:.3}'.format(x) for x in newXtickLabels])
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
Esempio n. 3
0
def plot_dynamics(behavData, winsize=40, fontsize=12):
    '''
    Plot performance in time for one session.
    First argument is an object created by loadbehavior.BehaviorData (or subclasses)
    '''
    ax = plt.gca()
    ax.cla()
    lineWidth = 2
    possibleRewardSide = np.unique(behavData['rewardSide'])
    possibleColors = ['b', 'r']
    rightChoice = behavData['choice'] == behavData.labels['choice']['right']

    hPlots = []
    plt.hold(True)
    valid = behavData['valid'].astype(bool)
    for indr, thisSide in enumerate(possibleRewardSide):
        thisColor = possibleColors[indr]
        trialsThisSide = (behavData['rewardSide'] == thisSide)
        choiceVecThisSide = np.ma.masked_array(rightChoice[valid])
        choiceVecThisSide.mask = ~trialsThisSide[valid]
        movAvChoice = extrafuncs.moving_average_masked(choiceVecThisSide,
                                                       winsize)
        hp, = plt.plot(range(0, len(movAvChoice)),
                       100 * movAvChoice,
                       lw=lineWidth,
                       color=thisColor)
        hPlots.append(hp)
    plt.ylim([-5, 105])
    plt.axhline(50, color='0.5', ls='--')
    plt.ylabel('% rightward', fontsize=fontsize)
    plt.xlabel('Trial', fontsize=fontsize)
    extraplots.set_ticks_fontsize(ax, fontsize)
    #plt.draw()
    #plt.show()
    return hPlots
def plot_reactiontime_dynamics(bData, winsize=40, fontsize=12):
    '''
    This function plots a running average for the reaction time based on trial outcomes or which side the animal actually choosed ('choice'). 
    *Invalid trials does not have choice time since timeSideIn is NaN.
    Reaction time is defined as the time it took from hearing sound stimulus to deciding to act (removing head from center port).
    '''
    lineWidth = 2
    reactionTime = bData['timeCenterOut'] - bData['timeTarget']
    correctTrials = bData['outcome'] == bData.labels['outcome']['correct']
    errorTrials = bData['outcome'] == bData.labels['outcome']['error']
    #    invalidTrials = bData['outcome']==bData.labels['outcome']['invalid']
    #Cannot use rewardSide here since some trials will be invalid and contain NaN 'timeSideIn'
    leftTrials = bData['choice'] == bData.labels['choice']['left']
    #Cannot use ~leftTrials for indexing since will include trials where choice is none and timeSideIn will be NaN
    rightTrials = bData['choice'] == bData.labels['choice']['right']

    reactionTCorrect = np.ma.masked_array(reactionTime[correctTrials])
    movAvReactionTime_correct = extrafuncs.moving_average_masked(
        reactionTCorrect, winsize)
    reactionTError = np.ma.masked_array(reactionTime[errorTrials])
    movAvReactionTime_error = extrafuncs.moving_average_masked(
        reactionTError, winsize)
    reactionTLeft = np.ma.masked_array(reactionTime[leftTrials])
    movAvReactionTime_left = extrafuncs.moving_average_masked(
        reactionTLeft, winsize)
    reactionTRight = np.ma.masked_array(reactionTime[rightTrials])
    movAvReactionTime_right = extrafuncs.moving_average_masked(
        reactionTRight, winsize)

    line1, = plt.plot(movAvReactionTime_correct,
                      lw=lineWidth,
                      color='m',
                      alpha=1,
                      label='correct')
    #plt.hold(1)
    line2, = plt.plot(movAvReactionTime_error,
                      lw=lineWidth,
                      color='b',
                      alpha=1,
                      label='error')
    #plt.hold(1)
    line3, = plt.plot(movAvReactionTime_left,
                      lw=lineWidth,
                      color='g',
                      label='left')
    #plt.hold(1)
    line4, = plt.plot(movAvReactionTime_right,
                      lw=lineWidth,
                      color='r',
                      label='right')
    #plt.hold(1)
    #plt.ylim([0,2.5])
    #plt.ylabel('Reaction time(s)',fontsize=fontsize)
    plt.xlabel('Trial number', fontsize=fontsize)
    plt.legend([line1, line2, line3, line4],
               ['correct', 'error', 'left', 'right'],
               loc=1)
    ax = plt.gca()
    ax.set_ylabel('Reaction time(s)', fontsize=fontsize, labelpad=1)
    extraplots.set_ticks_fontsize(ax, fontsize)
def plot_ITI_dynamics(bData, winsize=40, fontsize=12):
    '''
    Plot speed of performance (in intertrial intervals) in time for one session. Plots left- and right- rewardSide trials separately. 
    First argument is an object created by loadbehavior.BehaviorData (or subclasses)
    '''
    lineWidth = 2
    trialStarts = bData['timeTrialStart']
    interTrialIntervals = np.hstack((0, np.diff(trialStarts)))

    #Running average of ITI for the left- or right-rewarded trials, including invalid and error trials too
    #    ITIVec = np.ma.masked_array(interTrialIntervals)
    leftTrials = bData['rewardSide'] == bData.labels['rewardSide']['left']

    leftTrialITIs = np.ma.masked_array(interTrialIntervals[leftTrials])
    movAvITI_left = extrafuncs.moving_average_masked(leftTrialITIs, winsize)
    rightTrialITIs = np.ma.masked_array(interTrialIntervals[~leftTrials])
    movAvITI_right = extrafuncs.moving_average_masked(rightTrialITIs, winsize)
    #plt.plot(range(0,len(leftTrials)),100*movAvChoice_left,
    #             lw=lineWidth,color='g')
    line1 = plt.plot(movAvITI_left, lw=lineWidth, color='g')
    #plt.hold(1)
    line2 = plt.plot(movAvITI_right, lw=lineWidth, color='r')
    #plt.hold(1)
    #(line1, line2) = plt.plot(range(0,len(leftTrials)), movAvITI_left, range(0,len(~leftTrials)), movAvITI_right)
    #plt.setp((line1,line2), color=('g','b'), linewidth=2.0)
    #plt.legend([line1, line2], ['Leftward trials', 'Rightward trials'])

    #plt.ylabel('Intertrial Interval(s)',fontsize=fontsize)
    plt.xlabel('Trial number', fontsize=fontsize)
    #plt.title('Intertrial Interval')
    plt.ylim(0, 30)
    ax = plt.gca()
    ax.set_ylabel('Intertrial Interval(s)', fontsize=fontsize, labelpad=1)
    extraplots.set_ticks_fontsize(ax, fontsize)
def plot_bars(ax, dataMat, label):
    for indSubject, subject in enumerate(subjects):
        for indCond, condition in enumerate(conditions):
            sessionsThisCondThisSubject = dataMat[indSubject, :, indCond]
            ax.plot(np.zeros(len(sessionsThisCondThisSubject)) + (indSubject + 0.5*width + indCond*width) + pointShift,
                    sessionsThisCondThisSubject, marker='o', linestyle='none', mec=condColors[indCond], mfc='none')
            ax.hold(1)

    rects1 = ax.bar(ind, dataMat[:, :, 0].mean(1)-0.5, width, bottom=0.5, edgecolor='k', facecolor='w', lw=2, label='Saline')
    rects2 = ax.bar(ind+width+0.015, dataMat[:, :, 1].mean(1)-0.5, width, bottom=0.5, edgecolor=muscimolColor, lw=2, facecolor='w', label='Muscimol')

    ax.set_xticks(ind + width)
    ax.set_xticklabels(np.arange(6)+1, fontsize=fontSizeLabels)
    ax.set_xlabel('Mouse', fontsize=fontSizeLabels)
    ax.axhline(y=0.5, color='0.5', linestyle='-')
    # ax.set_ylim([0.45, 1])
    ax.set_xlim([ind[0]-0.5*width, ind[-1]+2.5*width ])
    ax.set_ylabel('Number of trials', fontsize=fontSizeLabels)
    # ax.set_yticks([0.5, 1])

    extraplots.set_ticks_fontsize(plt.gca(),fontSizeTicks)
    extraplots.boxoff(ax)

    ax.legend(bbox_to_anchor=(0.95, 0.6),
            loc=3,
            numpoints=1,
            fontsize=fontSizeLabels,
            ncol=1,
            columnspacing=1.5,
            frameon=False)

    for i in [1, 3, 4]:
        extraplots.significance_stars([i+0.5*width,i+1.5*width], 1000, 50, starSize=6, gapFactor=0.4, color='0.5')
Esempio n. 7
0
def plot_dynamics_2afc(behavData,winsize=40,fontsize=12):
    '''
    Plot performance in time for one session for left and right trials.
    First argument is an object created by loadbehavior.BehaviorData (or subclasses)
    '''
    ax = plt.gca()
    ax.cla()
    lineWidth = 2
    possibleRewardSide = np.unique(behavData['rewardSide'])
    possibleColors = ['b','r']
    rightChoice = behavData['choice']==behavData.labels['choice']['right']

    hPlots = []
    plt.hold(True)
    valid = behavData['valid'].astype(bool)
    for indr,thisSide in enumerate(possibleRewardSide):
        thisColor = possibleColors[indr]
        trialsThisSide = (behavData['rewardSide']==thisSide)
        choiceVecThisSide = np.ma.masked_array(rightChoice[valid])
        choiceVecThisSide.mask = ~trialsThisSide[valid]
        movAvChoice = extrafuncs.moving_average_masked(choiceVecThisSide,winsize)
        hp, = plt.plot(range(0,len(movAvChoice)),100*movAvChoice,
                       lw=lineWidth,color=thisColor)
        hPlots.append(hp)
    plt.ylim([-5,105])
    plt.axhline(50,color='0.5',ls='--')
    plt.ylabel('% rightward',fontsize=fontsize)
    plt.xlabel('Trial',fontsize=fontsize)
    extraplots.set_ticks_fontsize(ax,fontsize)
    #plt.draw()
    #plt.show()
    return hPlots
def plot_ITI_dynamics(bData, winsize=40, fontsize=12):
    '''
    Plot speed of performance (in intertrial intervals) in time for one session. Plots left- and right- rewardSide trials separately. 
    First argument is an object created by loadbehavior.BehaviorData (or subclasses)
    '''
    lineWidth = 2
    trialStarts = bData['timeTrialStart']
    interTrialIntervals = np.hstack((0,np.diff(trialStarts)))

    #Running average of ITI for the left- or right-rewarded trials, including invalid and error trials too 
#    ITIVec = np.ma.masked_array(interTrialIntervals)
    leftTrials = bData['rewardSide']==bData.labels['rewardSide']['left']
    
    leftTrialITIs = np.ma.masked_array(interTrialIntervals[leftTrials])
    movAvITI_left = extrafuncs.moving_average_masked(leftTrialITIs, winsize)
    rightTrialITIs = np.ma.masked_array(interTrialIntervals[~leftTrials])
    movAvITI_right = extrafuncs.moving_average_masked(rightTrialITIs, winsize)
    #plt.plot(range(0,len(leftTrials)),100*movAvChoice_left,
    #             lw=lineWidth,color='g')
    line1 = plt.plot(movAvITI_left,lw=lineWidth,color='g')
    #plt.hold(1)
    line2 = plt.plot(movAvITI_right,lw=lineWidth,color='r')
    #plt.hold(1)
    #(line1, line2) = plt.plot(range(0,len(leftTrials)), movAvITI_left, range(0,len(~leftTrials)), movAvITI_right)
    #plt.setp((line1,line2), color=('g','b'), linewidth=2.0)
    #plt.legend([line1, line2], ['Leftward trials', 'Rightward trials'])
    
    #plt.ylabel('Intertrial Interval(s)',fontsize=fontsize)
    plt.xlabel('Trial number',fontsize=fontsize)
    #plt.title('Intertrial Interval')
    plt.ylim(0,30)
    ax = plt.gca()
    ax.set_ylabel('Intertrial Interval(s)',fontsize=fontsize,labelpad=1)
    extraplots.set_ticks_fontsize(ax,fontsize)
Esempio n. 9
0
def plot_ITI_dynamics(bData, winsize=40, fontsize=12):
    '''
    Plot speed of performance (in intertrial intervals) in time for one session. Plots left- and right- rewardSide trials separately. 
    First argument is an object created by loadbehavior.BehaviorData (or subclasses)
    '''
    lineWidth = 2
    trialStarts = bData['timeTrialStart']
    interTrialIntervals = np.hstack((0,np.diff(trialStarts)))
    leftTrialIndex, = np.nonzero(bData['rewardSide']==bData.labels['rewardSide']['left'])
    #leftTrialIndex = bData['rewardSide'].index(bData.labels['rewardSide']['left'])
    plt.plot(interTrialIntervals, marker='.',linestyle='None',color='r')
    plt.plot(leftTrialIndex, interTrialIntervals[leftTrialIndex], marker='.',linestyle='None',color='g')
    
    '''
    leftTrialITIs=interTrialIntervals.copy()
    leftTrialITIs[~leftTrials]=0
    plt.plot(leftTrialITIs, marker='.',linestyle='None',color='g')
    
    rightTrialITIs = interTrialIntervals.copy() 
    rightTrialITIs[leftTrials]=0
    plt.plot(rightTrialITIs,marker='.',linestyle='None',color='r')
    #plt.hold(1)
    #(line1, line2) = plt.plot(range(0,len(leftTrials)), movAvITI_left, range(0,len(~leftTrials)), movAvITI_right)
    #plt.setp((line1,line2), color=('g','b'), linewidth=2.0)
    #plt.legend([line1, line2], ['Leftward trials', 'Rightward trials'])
    '''
    #plt.ylabel('Intertrial Interval(s)',fontsize=fontsize)
    plt.xlabel('Trial number',fontsize=fontsize)
    #plt.title('Intertrial Interval')
    plt.ylim(0,30)
    ax = plt.gca()
    ax.set_ylabel('Intertrial Interval(s)',fontsize=fontsize,labelpad=1)
    extraplots.set_ticks_fontsize(ax,fontsize)
Esempio n. 10
0
def plot_switching_PSTH(oneCell,
                        freqToPlot='middle',
                        alignment='sound',
                        timeRange=[-0.5, 1],
                        byBlock=True,
                        binWidth=0.010):
    # -- calls load_remote_2afc_data(oneCell) to get the data, then plot raster -- #
    (eventData, spikeData, oldBdata) = load_remote_2afc_data(oneCell)
    spikeTimestamps = spikeData.timestamps
    # -- Get trialsEachCond and colorEachCond for plotting -- #
    (bdata, trialsEachCond,
     colorEachCond) = get_trials_each_cond_switching(oneCell=oneCell,
                                                     freqToPlot=freqToPlot,
                                                     byBlock=byBlock)

    # -- Calculate eventOnsetTimes based on alignment parameter -- #
    eventOnsetTimes = np.array(eventData.timestamps)
    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

    (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
spikesanalysis.eventlocked_spiketimes(spikeTimestamps,EventOnsetTimes,timeRange)
    timeVec = np.arange(timeRange[0], timeRange[-1], binWidth)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, timeVec)
    smoothWinSize = 3
    #plt.figure()
    extraplots.plot_psth(spikeCountMat / binWidth,
                         smoothWinSize,
                         timeVec,
                         trialsEachCond=trialsEachCond,
                         colorEachCond=colorEachCond,
                         linestyle=None,
                         linewidth=2,
                         downsamplefactor=1)
    plt.xlabel('Time from {0} (s)'.format(alignment))
    plt.xlim(timeRange[0] + 0.1, timeRange[1])
    plt.ylabel('Firing rate (spk/sec)')
    plt.fill([0, 0.1, 0.1, 0],
             [plt.ylim()[0],
              plt.ylim()[0],
              plt.ylim()[1],
              plt.ylim()[1]],
             color='0.75')
    extraplots.set_ticks_fontsize(plt.gca(), fontSize=16)
def plot_dynamics(behavData, winsize=40, fontsize=12, soundfreq=None):
    '''
    Plot performance in time for one session.
    First argument is an object created by loadbehavior.BehaviorData (or subclasses)
    '''
    ax = plt.gca()
    ax.cla()
    lineWidth = 2
    if not np.any(soundfreq):
        possibleFreq = np.unique(behavData['targetFrequency'])
    else:
        possibleFreq = soundfreq
    print possibleFreq
    possibleColors = FREQCOLORS + ['k', 'm', 'c', 'b', 'r', 'g']
    colorEachFreq = dict(zip(possibleFreq, possibleColors))

    behavData.find_trials_each_block()

    nBlocks = behavData.blocks['nBlocks']
    trialsEachBlock = behavData.blocks['trialsEachBlock']
    validEachBlock = trialsEachBlock & (
        behavData['valid'][:, np.newaxis].astype(bool))
    nValidEachBlock = np.sum(validEachBlock, axis=0)
    lastValidEachBlock = np.cumsum(
        nValidEachBlock)  # Actually, these values correspond to lastIndex+1
    firstValidEachBlock = np.concatenate(([0], lastValidEachBlock[:-1]))
    rightChoice = behavData['choice'] == behavData.labels['choice']['right']

    hPlots = []
    curveLegends = list(possibleFreq)
    plt.hold(True)
    for indb in range(nBlocks):
        trialsThisBlock = trialsEachBlock[:, indb]
        validThisBlock = validEachBlock[:, indb]
        for indf, thisFreq in enumerate(possibleFreq):
            thisColor = colorEachFreq[thisFreq]
            trialsThisFreq = (behavData['targetFrequency'] == thisFreq)
            choiceVecThisFreq = np.ma.masked_array(rightChoice[validThisBlock])
            choiceVecThisFreq.mask = ~trialsThisFreq[validThisBlock]
            movAvChoice = extrafuncs.moving_average_masked(
                choiceVecThisFreq, winsize)
            hp, = plt.plot(range(firstValidEachBlock[indb],
                                 lastValidEachBlock[indb]),
                           100 * movAvChoice,
                           lw=lineWidth,
                           color=thisColor)
            hPlots.append(hp)

    plt.ylim([-5, 105])
    plt.axhline(50, color='0.5', ls='--')
    plt.ylabel('% rightward', fontsize=fontsize)
    plt.xlabel('Trial', fontsize=fontsize)
    extraplots.set_ticks_fontsize(ax, fontsize)
    #legend = plt.legend(hPlots,curveLegends,loc=2)
    #ax = plt.gca().add_artist(legend)
    plt.draw()
    plt.show()
    return hPlots
def plot_bars(ax, dataMat, label):
    for indSubject, subject in enumerate(subjects):
        for indCond, condition in enumerate(conditions):
            sessionsThisCondThisSubject = dataMat[indSubject, :, indCond]
            ax.plot(np.zeros(len(sessionsThisCondThisSubject)) +
                    (indSubject + 0.5 * width + indCond * width) + pointShift,
                    sessionsThisCondThisSubject,
                    marker='o',
                    linestyle='none',
                    mec=condColors[indCond],
                    mfc='none')
            ax.hold(1)

    rects1 = ax.bar(ind,
                    dataMat[:, :, 0].mean(1) - 0.5,
                    width,
                    bottom=0.5,
                    edgecolor='k',
                    facecolor='w',
                    lw=2,
                    label='Saline')
    rects2 = ax.bar(ind + width + 0.015,
                    dataMat[:, :, 1].mean(1) - 0.5,
                    width,
                    bottom=0.5,
                    edgecolor=muscimolColor,
                    lw=2,
                    facecolor='w',
                    label='Muscimol')

    ax.set_xticks(ind + width)
    ax.set_xticklabels(np.arange(6) + 1, fontsize=fontSizeLabels)
    ax.set_xlabel('Mouse', fontsize=fontSizeLabels)
    ax.axhline(y=0.5, color='0.5', linestyle='-')
    # ax.set_ylim([0.45, 1])
    ax.set_xlim([ind[0] - 0.5 * width, ind[-1] + 2.5 * width])
    ax.set_ylabel('Number of trials', fontsize=fontSizeLabels)
    # ax.set_yticks([0.5, 1])

    extraplots.set_ticks_fontsize(plt.gca(), fontSizeTicks)
    extraplots.boxoff(ax)

    ax.legend(bbox_to_anchor=(0.95, 0.6),
              loc=3,
              numpoints=1,
              fontsize=fontSizeLabels,
              ncol=1,
              columnspacing=1.5,
              frameon=False)

    for i in [1, 3, 4]:
        extraplots.significance_stars([i + 0.5 * width, i + 1.5 * width],
                                      1000,
                                      50,
                                      starSize=6,
                                      gapFactor=0.4,
                                      color='0.5')
Esempio n. 13
0
def plot_str_report(cell, saveDir):
    plt.clf()
    #first 4 rows are not needed
    # gs = gridspec.GridSpec(9, 6)
    gs = gridspec.GridSpec(5, 6)
    gs.update(left=0.15, right=0.95, bottom=0.15, wspace=1, hspace=1)

    # #Laser pulse raster
    # ax0 = plt.subplot(gs[0:2, 0:3])
    # if 'laserpulse' in cell['sessiontype']:
    #     spikeData, eventData = dataloader.get_session_ephys(cell, 'laserpulse')
    #     eventOnsetTimes = eventData.get_event_onset_times()
    #     if spikeData.timestamps is not None:
    #         timeRange = [-0.5, 1]
    #         (spikeTimesFromEventOnset,
    #          trialIndexForEachSpike,
    #          indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(spikeData.timestamps,
    #                                                                        eventOnsetTimes,
    #                                                                        timeRange)
    #         (pRaster,
    #          hcond,
    #          zline) = extraplots.raster_plot(spikeTimesFromEventOnset,
    #                                          indexLimitsEachTrial,
    #                                          timeRange)

    #         ms = 2
    #         plt.setp(pRaster, ms=ms)

    #     plt.title('Laser Pulse')
    # #Laser pulse psth
    # ax1 = plt.subplot(gs[2:4, 0:3])
    # if 'laserpulse' in cell['sessiontype']:
    #     spikeData, eventData = dataloader.get_session_ephys(cell, 'laserpulse')
    #     if spikeData.timestamps is not None:
    #         # dataplotter.plot_psth(spikeData.timestamps, eventOnsetTimes, plotLegend=0)

    #         timeRange = [-0.5, 1]
    #         binsize = 0.02
    #         lw=2

    #         (spikeTimesFromEventOnset,
    #         trialIndexForEachSpike,
    #         indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(spikeData.timestamps,
    #                                                                      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])
    #         plt.setp(pPSTH, lw=lw)
    #         plt.hold(True)
    #         zline = plt.axvline(0,color='0.75',zorder=-10)
    #         plt.xlim(timeRange)

            extraplots.set_ticks_fontsize(ax1, 9)
def multisession_isi_loghist(timeStamps, nBins=350, fontsize=8):
    '''
    Plot histogram of inter-spike interval (in msec, log scale)

    NOTE:
    Nick: I needed to make a copy of this function from jaratoolbox.spikesorting
    because if the acquisition system is ever stopped and restarted between sessions,
    then the timestamps will not be sequential. The easiest fix is to ignore any ISIs
    that are less than 0. The more complicated way would be to ignore the ISIs at the
    boundaries of the sessions. 

    FIXME: I am doing the easy fix for now (2016-10-19)

    Parameters
    ----------
    timeStamps : array (float in sec)
    '''
    fontsizeLegend = fontsize
    xLims = [1e-1, 1e4]
    ax = plt.gca()
    ISI = np.diff(timeStamps)
    if np.any(ISI < 0):
        ISI = ISI[ISI > 0]  #NOTE: The change is here
    if len(ISI) == 0:  # Hack in case there is only one spike
        ISI = np.array(10)
    logISI = np.log10(ISI)
    [ISIhistogram, ISIbinsLog] = np.histogram(logISI, bins=nBins)
    ISIbins = 1000 * (10**ISIbinsLog[:-1])  # Conversion to msec
    fractionViolation = np.mean(ISI < 1e-3)  # Assumes ISI in usec
    fractionViolation2 = np.mean(ISI < 2e-3)  # Assumes ISI in usec

    hp, = plt.semilogx(ISIbins, ISIhistogram, color='k')
    plt.setp(hp, lw=0.5, color='k')
    yLims = plt.ylim()
    plt.xlim(xLims)
    plt.text(0.15,
             0.85 * yLims[-1],
             'N={0}'.format(len(timeStamps)),
             fontsize=fontsizeLegend,
             va='top')
    plt.text(0.15,
             0.6 * yLims[-1],
             '{0:0.2%}\n{1:0.2%}'.format(fractionViolation,
                                         fractionViolation2),
             fontsize=fontsizeLegend,
             va='top')
    #plt.text(0.15,0.6*yLims[-1],'%0.2f%%\n%0.2f%%'%(percentViolation,percentViolation2),
    #         fontsize=fontsizeLegend,va='top')
    #'VerticalAlignment','top','HorizontalAlignment','left','FontSize',FontSizeAxes);
    ax.xaxis.grid(True)
    ax.yaxis.grid(False)
    plt.xlabel('Interspike interval (ms)')
    ax.set_yticks(plt.ylim())
    extraplots.set_ticks_fontsize(ax, fontsize)
    return (hp, ISIhistogram, ISIbins)
Esempio n. 15
0
def plot_dynamics(behavData,winsize=40,fontsize=12,soundfreq=None):
    '''
    Plot performance in time for one session.
    First argument is an object created by loadbehavior.BehaviorData (or subclasses)
    '''
    ax = plt.gca()
    ax.cla()
    lineWidth = 2
    if not np.any(soundfreq):
        possibleFreq = np.unique(behavData['targetFrequency'])
    else:
        possibleFreq = soundfreq
    print possibleFreq
    possibleColors = FREQCOLORS + ['k','m','c', 'b','r','g']
    colorEachFreq = dict(zip(possibleFreq,possibleColors))

    behavData.find_trials_each_block()

    nBlocks = behavData.blocks['nBlocks']
    trialsEachBlock = behavData.blocks['trialsEachBlock']
    validEachBlock = trialsEachBlock & (behavData['valid'][:,np.newaxis].astype(bool))
    nValidEachBlock = np.sum(validEachBlock,axis=0)
    lastValidEachBlock = np.cumsum(nValidEachBlock) # Actually, these values correspond to lastIndex+1
    firstValidEachBlock = np.concatenate(([0],lastValidEachBlock[:-1]))
    rightChoice = behavData['choice']==behavData.labels['choice']['right']

    hPlots = []
    curveLegends=list(possibleFreq)
    plt.hold(True)
    for indb in range(nBlocks):
        trialsThisBlock = trialsEachBlock[:,indb]
        validThisBlock = validEachBlock[:,indb]
        for indf,thisFreq in enumerate(possibleFreq):
            thisColor = colorEachFreq[thisFreq]
            trialsThisFreq = (behavData['targetFrequency']==thisFreq)
            choiceVecThisFreq = np.ma.masked_array(rightChoice[validThisBlock])
            choiceVecThisFreq.mask = ~trialsThisFreq[validThisBlock]
            movAvChoice = extrafuncs.moving_average_masked(choiceVecThisFreq,winsize)
            hp, = plt.plot(range(firstValidEachBlock[indb],lastValidEachBlock[indb]),100*movAvChoice,
                           lw=lineWidth,color=thisColor)
            hPlots.append(hp)
    
    plt.ylim([-5,105])
    plt.axhline(50,color='0.5',ls='--')
    plt.ylabel('% rightward',fontsize=fontsize)
    plt.xlabel('Trial',fontsize=fontsize)
    extraplots.set_ticks_fontsize(ax,fontsize)
    legend = plt.legend(hPlots,curveLegends,loc=2)
    ax = plt.gca().add_artist(legend)
    plt.draw()
    plt.show()
    return hPlots
Esempio n. 16
0
def plot_choicetime_dynamics(bData, winsize=40, fontsize=12):
    '''
    This function plots a running average for the choice time based on trial outcomes or which side the animal actually choosed ('choice'). 
    *Invalid trials does not have choice time since timeSideIn is NaN.
    Choice time is defined as the time it took to get to the side ports to retrieve water from the time of leaving center port.
    '''
    lineWidth = 2

    choiceTime = bData['timeSideIn']-bData['timeCenterOut']
    correctTrials = bData['outcome']==bData.labels['outcome']['correct']
    errorTrials = bData['outcome']==bData.labels['outcome']['error']
#    invalidTrials = bData['outcome']==bData.labels['outcome']['invalid']
#Cannot use rewardSide here since some trials will be invalid and contain NaN 'timeSideIn'
    leftTrials = bData['choice']==bData.labels['choice']['left']
#Cannot use ~leftTrials for indexing since will include trials where choice is none and timeSideIn will be NaN
    rightTrials = bData['choice']==bData.labels['choice']['right']

    #choiceTCorrect = np.ma.masked_array(choiceTime[correctTrials])
    #movAvChoiceTime_correct = extrafuncs.moving_average_masked(choiceTCorrect, winsize)
    #choiceTError = np.ma.masked_array(choiceTime[errorTrials])
    #movAvChoiceTime_error = extrafuncs.moving_average_masked(choiceTError, winsize)
    bData.find_trials_each_block()
    trialsEachBlock = bData.blocks['trialsEachBlock']
    nBlocks = bData.blocks['nBlocks']
    choiceTLeft = np.ma.masked_array(choiceTime[leftTrials])
    choiceTRight = np.ma.masked_array(choiceTime[rightTrials])
    for block in range(nBlocks):
        choiceTimeThisBlock = choiceTime[trialsEachBlock[:,block]]
        leftTrialsThisBlock = leftTrials[trialsEachBlock[:,block]]
        rightTrialsThisBlock = rightTrials[trialsEachBlock[:,block]]
        choiceTLeftThisBlock = np.ma.masked_array(choiceTimeThisBlock[leftTrialsThisBlock])
        choiceTRightThisBlock = np.ma.masked_array(choiceTimeThisBlock[rightTrialsThisBlock])
        #choiceTLeftThisBlock = choiceTLeft[trialsEachBlock[:,block]]
        #choiceTRightThisBlock = choiceTRight[trialsEachBlock[:,block]]
        movAvChoiceTime_right = extrafuncs.moving_average_masked(choiceTRightThisBlock, winsize)
        movAvChoiceTime_left = extrafuncs.moving_average_masked(choiceTLeftThisBlock, winsize)
        #plt.plot(movAvChoiceTime_correct,lw=lineWidth,color='m',alpha=1)
        #plt.hold(1)
        #plt.plot(movAvChoiceTime_error,lw=lineWidth,color='b',alpha=1)
        xValues = range(block*150,block*150+len(movAvChoiceTime_left))
        plt.plot(xValues,movAvChoiceTime_left,lw=lineWidth,color='g')
        xValues = range(block*150,block*150+len(movAvChoiceTime_right))
        plt.plot(xValues,movAvChoiceTime_right,lw=lineWidth,color='r')
        #plt.hold(1)
        #plt.ylim([0,2.5])
        #plt.axhline(50,color='0.5',ls='--')
        #plt.ylabel('Choice time(s)',fontsize=fontsize)
    plt.xlabel('Trial number',fontsize=fontsize)
    ax = plt.gca()
    extraplots.set_ticks_fontsize(ax,fontsize)
    ax.set_ylabel('Choice time(s)',fontsize=fontsize,labelpad=1)
def plot_reactiontime_dynamics(bData, winsize=40, fontsize=12):
    '''
    This function plots a running average for the reaction time based on trial outcomes or which side the animal actually choosed ('choice'). 
    *Invalid trials does not have choice time since timeSideIn is NaN.
    Reaction time is defined as the time it took from hearing sound stimulus to deciding to act (removing head from center port).
    '''
    lineWidth = 2
    reactionTime = bData['timeCenterOut']-bData['timeTarget']
    correctTrials = bData['outcome']==bData.labels['outcome']['correct']
    errorTrials = bData['outcome']==bData.labels['outcome']['error']
#    invalidTrials = bData['outcome']==bData.labels['outcome']['invalid']
#Cannot use rewardSide here since some trials will be invalid and contain NaN 'timeSideIn'
    leftTrials = bData['choice']==bData.labels['choice']['left']
#Cannot use ~leftTrials for indexing since will include trials where choice is none and timeSideIn will be NaN
    rightTrials = bData['choice']==bData.labels['choice']['right']
    
    bData.find_trials_each_block()
    trialsEachBlock = bData.blocks['trialsEachBlock']
    nBlocks = bData.blocks['nBlocks']

    #reactionTCorrect = np.ma.masked_array(reactionTime[correctTrials])
    #movAvReactionTime_correct = extrafuncs.moving_average_masked(reactionTCorrect, winsize)
    #reactionTError = np.ma.masked_array(reactionTime[errorTrials])
    #movAvReactionTime_error = extrafuncs.moving_average_masked(reactionTError, winsize)
    
    reactionTLeft = np.ma.masked_array(reactionTime[leftTrials])
    reactionTRight = np.ma.masked_array(reactionTime[rightTrials])

    for block in range(nBlocks):
        reactionTimeThisBlock = reactionTime[trialsEachBlock[:,block]]
        leftTrialsThisBlock = leftTrials[trialsEachBlock[:,block]]
        rightTrialsThisBlock = rightTrials[trialsEachBlock[:,block]]
        reactionTLeftThisBlock = np.ma.masked_array(reactionTimeThisBlock[leftTrialsThisBlock])
        reactionTRightThisBlock = np.ma.masked_array(reactionTimeThisBlock[rightTrialsThisBlock])
        movAvReactionTime_left = extrafuncs.moving_average_masked(reactionTLeftThisBlock, winsize)
        movAvReactionTime_right = extrafuncs.moving_average_masked(reactionTRightThisBlock, winsize)
   
        #line1,=plt.plot(movAvReactionTime_correct,lw=lineWidth,color='m',alpha=1,label='correct')
        #line2,=plt.plot(movAvReactionTime_error,lw=lineWidth,color='b',alpha=1,label='error')
        xValues = range(block*150,block*150+len(movAvReactionTime_left))
        line3,=plt.plot(xValues,movAvReactionTime_left,lw=lineWidth,color='g',label='left')
        xValues = range(block*150,block*150+len(movAvReactionTime_right))
        line4,=plt.plot(xValues,movAvReactionTime_right,lw=lineWidth,color='r',label='right')
       
        #plt.ylim([0,2.5])
        
    plt.xlabel('Trial number',fontsize=fontsize)
    plt.legend([line3,line4],['left','right'],loc=1)
    ax = plt.gca()
    ax.set_ylabel('Reaction time(s)',fontsize=fontsize,labelpad=1)
    extraplots.set_ticks_fontsize(ax,fontsize)
Esempio n. 18
0
def plot_summary(behavData,fontsize=12,soundfreq=None):
    '''
    Show summary of performance.
    First argument is an object created by loadbehavior.BehaviorData (or subclasses)
    '''
    correct = behavData['outcome']==behavData.labels['outcome']['correct']
    early = behavData['outcome']==behavData.labels['outcome']['invalid']
    #possibleFreq = np.unique(behavData['targetFrequency'])
    if soundfreq is None:
        possibleFreq = np.unique(behavData['targetFrequency'])
    else:
        possibleFreq = soundfreq
    possibleBlockID = np.unique(behavData['currentBlock'])
    trialsEachType = find_trials_each_type_each_block(behavData['targetFrequency'],possibleFreq,
                                                      behavData['currentBlock'],possibleBlockID)
    validTrialsEachType = trialsEachType & behavData['valid'][:,np.newaxis,np.newaxis].astype(bool)
    correctTrialsEachType = validTrialsEachType & correct[:,np.newaxis,np.newaxis]
    nCorrectEachType = np.sum(correctTrialsEachType,axis=0)
    nValidEachType = np.sum(validTrialsEachType,axis=0)

    #perfEachType = np.where(nValidEachType>0, nCorrectEachType/nValidEachType.astype(float), np.nan)
    perfEachType = nCorrectEachType/nValidEachType.astype(float)

    # --- Plot results ---
    itemsToPlot = nValidEachType.flatten()>0  #~np.isnan(perfEachType.flatten())
    perfToPlot = perfEachType.flatten()[itemsToPlot] # Show only 2 freq for each block type
    freqLabels = np.repeat(possibleFreq,len(possibleBlockID))[itemsToPlot]
    nValidCounts = nValidEachType.flatten()[itemsToPlot]
    xPos = [0,1,3,4][:len(perfToPlot)]
    ax = plt.gca()
    ax.set_xlim([-1,5])
    ax.set_ylim([0,100])
    plt.hold(True)
    hline50 = plt.axhline(50,linestyle=':',color='k',zorder=-1)
    hline75 = plt.axhline(75,linestyle=':',color='k',zorder=-1)
    hbars = plt.bar(xPos,100*perfToPlot,align='center',fc=[0.8,0.8,0.8],ec='k')
    for thispos,thistext in zip(xPos,nValidCounts):
        plt.text(thispos,10,str(thistext),ha='center',fontsize=fontsize)
    ax.set_ylabel('% correct',fontsize=fontsize)
    ax.set_xticks(xPos)
    ax.set_xticklabels(freqLabels/1000)

    titleStr = '{0} [{1}] {2}\n'.format(behavData.session['subject'],behavData.session['date'],
                                        behavData.session['hostname'])
    titleStr += '{0} valid, {1:.0%} early'.format(sum(nValidCounts),np.mean(early))
    ax.set_title(titleStr,fontweight='bold',fontsize=fontsize,y=0.95)
    ax.set_xlabel('Frequency (kHz)',fontsize=fontsize)
    extraplots.set_ticks_fontsize(ax,fontsize)
    plt.draw()
    plt.show()
Esempio n. 19
0
def muscimol_plot_sound_type(animal, muscimolSessions, salineSessions, soundType, fontsize=12):

    '''
    DEPRECATED - this is a bad function
    Plot the average psycurve for muscimol sessions in red on top of the average saline psycurve in black.
    Psycurves are limited by the sound type.
    '''

    muscimolData = behavioranalysis.load_many_sessions(animal, muscimolSessions)

    trialsSoundTypeMus = muscimolData['soundType']==muscimolData.labels['soundType'][soundType]
    rightTrialsMus = (muscimolData['choice']==muscimolData.labels['choice']['right'])[trialsSoundTypeMus]
    freqEachTrialMus = muscimolData['targetFrequency'][trialsSoundTypeMus]
    validMus = muscimolData['valid'][trialsSoundTypeMus]


    (possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue)=\
       calculate_psychometric(rightTrialsMus,freqEachTrialMus,validMus)
    (plineM, pcapsM, pbarsM, pdotsM) = extraplots.plot_psychometric(1e-3*possibleValues,fractionHitsEachValue,
                                                                ciHitsEachValue,xTickPeriod=1)
    plt.xlabel('Frequency (kHz)',fontsize=fontsize)
    plt.ylabel('Rightward trials (%)',fontsize=fontsize)
    extraplots.set_ticks_fontsize(plt.gca(),fontsize)




    setp(plineM, color='r')
    setp(pcapsM, color='r')
    setp(pbarsM, color='r')
    setp(pdotsM, markerfacecolor='r')

    salineData = behavioranalysis.load_many_sessions(animal, salineSessions)

    trialsSoundTypeSal = salineData['soundType']==salineData.labels['soundType'][soundType]
    rightTrialsSal = (salineData['choice']==salineData.labels['choice']['right'])[trialsSoundTypeSal]
    freqEachTrialSal = salineData['targetFrequency'][trialsSoundTypeSal]
    validSal = salineData['valid'][trialsSoundTypeSal]


    (possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue)=\
       calculate_psychometric(rightTrialsSal,freqEachTrialSal,validSal)
    (plineS, pcapsS, pbarsS, pdotsS) = extraplots.plot_psychometric(1e-3*possibleValues,fractionHitsEachValue,
                                                                ciHitsEachValue,xTickPeriod=1)


    title("{}, {}".format(animal, soundType))
def plot_isi_loghist(timeStamps, nBins=350, fontsize=8):
    '''
    Plot histogram of inter-spike interval (in msec, log scale)

    Parameters
    ----------
    timeStamps : array (float in sec)
    '''
    fontsizeLegend = fontsize
    xLims = [1e-1, 1e4]
    ax = plt.gca()
    ISI = np.diff(timeStamps)
    if np.any(ISI < 0):
        raise 'Times of events are not ordered (or there is at least one repeated).'
    if len(ISI) == 0:  # Hack in case there is only one spike
        ISI = np.array(10)
    logISI = np.log10(ISI)
    [ISIhistogram, ISIbinsLog] = np.histogram(logISI, bins=nBins)
    ISIbins = 1000 * (10**ISIbinsLog[:-1])  # Conversion to msec
    fractionViolation = np.mean(ISI < 1e-3)  # Assumes ISI in usec
    fractionViolation2 = np.mean(ISI < 2e-3)  # Assumes ISI in usec

    hp, = plt.semilogx(ISIbins, ISIhistogram, color='k')
    plt.setp(hp, lw=0.5, color='k')
    yLims = plt.ylim()
    plt.xlim(xLims)
    plt.text(0.15,
             0.85 * yLims[-1],
             'N={0}'.format(len(timeStamps)),
             fontsize=fontsizeLegend,
             va='top')
    plt.text(0.15,
             0.6 * yLims[-1],
             '{0:0.2%}\n{1:0.2%}'.format(fractionViolation,
                                         fractionViolation2),
             fontsize=fontsizeLegend,
             va='top')
    #plt.text(0.15,0.6*yLims[-1],'%0.2f%%\n%0.2f%%'%(percentViolation,percentViolation2),
    #         fontsize=fontsizeLegend,va='top')
    #'VerticalAlignment','top','HorizontalAlignment','left','FontSize',FontSizeAxes);
    ax.xaxis.grid(True)
    ax.yaxis.grid(False)
    plt.xlabel('Interspike interval (ms)')
    ax.set_yticks(plt.ylim())
    extraplots.set_ticks_fontsize(ax, fontsize)
    return (hp, ISIhistogram, ISIbins)
Esempio n. 21
0
def psycurveLinear(bdata):
    from jaratoolbox import extraplots
    fontsize=FONTSIZE
    if 'targetPercentage' in bdata.viewkeys():
        targetPercentage = bdata['targetPercentage']
    else:
        targetPercentage = bdata['targetFrequency'] # I used name 'frequency' initially
    choiceRight = bdata['choice']==bdata.labels['choice']['right']
    valid=bdata['valid']& (bdata['choice']!=bdata.labels['choice']['none'])
    (possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue)=\
           behavioranalysis.calculate_psychometric(choiceRight,targetPercentage,valid)
    (pline, pcaps, pbars, pdots) = extraplots.plot_psychometric(1e-3*possibleValues,fractionHitsEachValue,
                                                                    ciHitsEachValue,xTickPeriod=1, xscale='linear')
    plt.xlabel('Stimulus',fontsize=fontsize)
    plt.ylabel('Rightward trials (%)',fontsize=fontsize)
    extraplots.set_ticks_fontsize(plt.gca(),fontsize)
    plt.gcf().set_size_inches([8,6])
Esempio n. 22
0
def plot_multiple_psycurves(bdataList, colorsList, fontsize=12):

    '''
    Nick 2016-05-20

    Plots psychometric curves for bdata objects in different colors on the same plot

    Args:

    bdataList (list of jaratoolbox.loadbehavior.LoadBehaviorData objects): list of bdata to plot
    colorsList (list of str): list of color strings the same length as bdataList ('k', 'b', etc.)
    fontsize (int): Size of the label font for the figure
    '''

    plt.hold(1)
    for ind, bdata in enumerate(bdataList):
        rightTrials = bdata['choice']==bdata.labels['choice']['right']
        freqEachTrial = bdata['targetFrequency']
        valid = bdata['valid']

        (possibleValues,
         fractionHitsEachValue,
         ciHitsEachValue,
         nTrialsEachValue,
         nHitsEachValue)= calculate_psychometric(rightTrials,
                                                 freqEachTrial,
                                                 valid)

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

        plt.xlabel('Frequency (kHz)',fontsize=fontsize)
        plt.ylabel('Rightward trials (%)',fontsize=fontsize)
        extraplots.set_ticks_fontsize(plt.gca(),fontsize)

        plt.setp(pline, color=colorsList[ind])
        plt.setp(pcaps, color=colorsList[ind])
        plt.setp(pbars, color=colorsList[ind])
        plt.setp(pdots, markerfacecolor=colorsList[ind])
Esempio n. 23
0
def plot_frequency_psycurve(bdata,fontsize=12):
    '''
    Show psychometric curve (for frequency)
    '''
    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 = find_trials_each_type(targetFrequency,possibleFreq)
    (possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue)=\
       calculate_psychometric(choiceRight,targetFrequency,valid)
    (pline, pcaps, pbars, pdots) = extraplots.plot_psychometric(1e-3*possibleValues,fractionHitsEachValue,
                                                                ciHitsEachValue,xTickPeriod=1)
    plt.xlabel('Frequency (kHz)',fontsize=fontsize)
    plt.ylabel('Rightward trials (%)',fontsize=fontsize)
    extraplots.set_ticks_fontsize(plt.gca(),fontsize)
    return (pline, pcaps, pbars, pdots)
Esempio n. 24
0
def plot_events_in_time(timeStamps,nBins=50,fontsize=8):
    '''
    Plot histogram of inter-spike interval (in msec, log scale)

    Parameters
    ----------
    timeStamps : array (float in sec)
    '''
    ax = plt.gca()
    timeBinEdges = np.linspace(timeStamps[0],timeStamps[-1],nBins) # in microsec
    # FIXME: Limits depend on the time of the first spike (not of recording)
    (nEvents,binEdges) = np.histogram(timeStamps,bins=timeBinEdges)
    hp, = plt.plot((binEdges-timeStamps[0])/60.0, np.r_[nEvents,0], drawstyle='steps-post')
    plt.setp(hp,lw=1,color='k')
    plt.xlabel('Time (min)')
    plt.axis('tight')
    ax.set_yticks(plt.ylim())
    extraplots.boxoff(ax)
    extraplots.set_ticks_fontsize(ax,fontsize)
    return hp
Esempio n. 25
0
def plot_frequency_psycurve_soundtype(bdata, soundType, fontsize=12):
    '''
    Show psychometric curve (for any arbitrary sound type)
    '''

    trialsSoundType = bdata['soundType']==bdata.labels['soundType'][soundType]
    choice = bdata['choice']
    choiceRight = choice==bdata.labels['choice']['right']
    choiceRightSoundType = choiceRight[trialsSoundType]
    targetFrequencySoundType = bdata['targetFrequency'][trialsSoundType]
    valid = bdata['valid']
    validSoundType = valid[trialsSoundType]
    (possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue)=\
        behavioranalysis.calculate_psychometric(choiceRightSoundType,targetFrequencySoundType,validSoundType)
    (pline, pcaps, pbars, pdots) = extraplots.plot_psychometric(1e-3*possibleValues,
                                                                fractionHitsEachValue,
                                                                ciHitsEachValue,
                                                                xTickPeriod=1)
    plt.xlabel('Frequency (kHz)',fontsize=fontsize)
    plt.ylabel('Rightward trials (%)',fontsize=fontsize)
    extraplots.set_ticks_fontsize(plt.gca(),fontsize)
    return (pline, pcaps, pbars, pdots)
def plot_frequency_psycurve_soundtype(bdata, soundType, fontsize=12):
    '''
    Show psychometric curve (for any arbitrary sound type)
    '''

    trialsSoundType = bdata['soundType']==bdata.labels['soundType'][soundType]
    choice = bdata['choice']
    choiceRight = choice==bdata.labels['choice']['right']
    choiceRightSoundType = choiceRight[trialsSoundType]
    targetFrequencySoundType = bdata['targetFrequency'][trialsSoundType]
    valid = bdata['valid']
    validSoundType = valid[trialsSoundType]
    (possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue)=\
        behavioranalysis.calculate_psychometric(choiceRightSoundType,targetFrequencySoundType,validSoundType)
    (pline, pcaps, pbars, pdots) = extraplots.plot_psychometric(1e-3*possibleValues,
                                                                fractionHitsEachValue,
                                                                ciHitsEachValue,
                                                                xTickPeriod=1)
    plt.xlabel('Frequency (kHz)',fontsize=fontsize)
    plt.ylabel('Rightward trials (%)',fontsize=fontsize)
    extraplots.set_ticks_fontsize(plt.gca(),fontsize)
    return (pline, pcaps, pbars, pdots)
def multisession_events_in_time(timeStamps, nBins=50, fontsize=8):
    '''
    Plot the spike timestamps throughout the recording session.

    IF the acquisition system is restarted at a site, then the timestamps will
    also reset and cause a failure in the traditional implementation of this method
    (spikesorting.plot_events_in_time). This method finds any negative ISIs (which mark
    the spot where the timestamps were reset), adds the value of the ts immediatly before
    the reset to all remaining timestamps, and plots a red line at this time point to indicate
    that there is an uncertain amount of time between the spikes before and after this point. 

    TODO: Still need to implement the fix I described above and then use the method in the
    multisession report

    Parameters
    ----------
    timeStamps : array (float in sec)
    '''

    # ISI = np.diff(timeStamps)
    # if np.any(ISI<0):

    ax = plt.gca()
    timeBinEdges = np.linspace(timeStamps[0], timeStamps[-1],
                               nBins)  # in microsec
    # FIXME: Limits depend on the time of the first spike (not of recording)
    (nEvents, binEdges) = np.histogram(timeStamps, bins=timeBinEdges)
    hp, = plt.plot((binEdges - timeStamps[0]) / 60.0,
                   np.r_[nEvents, 0],
                   drawstyle='steps-post')
    plt.setp(hp, lw=1, color='k')
    plt.xlabel('Time (min)')
    plt.axis('tight')
    ax.set_yticks(plt.ylim())
    extraplots.boxoff(ax)
    extraplots.set_ticks_fontsize(ax, fontsize)
    return hp
        validThisBlock = valid[trialsEachType[:,blockType]]
        choiceRightThisBlock = choiceRight[trialsEachType[:,blockType]]
        #currentBlockValue = currentBlock[trialsEachBlock[0,block]]
        (possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue)=\
                                                                                                behavioranalysis.calculate_psychometric(choiceRightThisBlock,targetFrequencyThisBlock,validThisBlock)
        (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)
     
        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,blockLabels,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'%(thisAnimal,sessions[0],sessions[-1]))   

outputDir='/home/billywalker/data/behavior_reports' 
animalStr = '-'.join(subjects)
sessionStr = '-'.join(sessions)
plt.gcf().set_size_inches((8.5,11))
figformat = 'png' 
filename = 'behavior_summary_%s_%s.%s'%(animalStr,sessionStr,figformat)
fullFileName = os.path.join(outputDir,filename)
Esempio n. 29
0
    plt.plot(xvals, schedData[featureToPlot], 'o', mfc='none', mec=pointsColor)
    thisMedian = dataMedian[featureToPlot][schedName]
    plt.bar(schedMapping[schedName],
            thisMedian,
            width=0.75,
            lw=2,
            fc=barFaceColor,
            ec=barEdgeColor)

#plt.ylabel(featureToPlot, fontsize=labelFontSize)
plt.ylabel('Performance (%)', fontsize=labelsFontSize)

ax0.set_xticks(np.arange(nSched))
ax0.set_xticklabels(schedSorted, fontsize=labelsFontSize)
if featureToPlot == 'Difference':
    plt.ylim([-20, 50])
else:
    plt.ylim([50, 100])
extraplots.boxoff(ax0)
extraplots.set_ticks_fontsize(ax0, ticksFontSize)

plt.show()

SAVEFIG = 1
if SAVEFIG:
    figname = 'behavior_effect_{}'.format(featureToPlot)
    extraplots.save_figure(figname,
                           'svg', [4.5, 3],
                           facecolor='w',
                           outputDir='/tmp/')
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
Esempio n. 31
0
def plot_switching_raster(oneCell,
                          freqToPlot='middle',
                          alignment='sound',
                          timeRange=[-0.5, 1],
                          byBlock=True):
    '''
    Plots raster for 2afc switching task with different alignment at time 0 and different choices for what frequencies to include in the plot.
    Arguments:
        oneCell is a CellInfo object.
        freqToPlot is a string; 'middle' means plotting only the middle frequency, 'all' means plotting all three frequenciens.
        alignment should be a string with possible values: 'sound', 'center-out','side-in'.
        timeRange is a list of two floats, indicating the start and end of plot range.
        byBlock is a boolean, indicates whether to split the plot into behavior blocks.
    '''

    # -- calls load_remote_2afc_data(oneCell) to get the data, then plot raster -- #
    (eventData, spikeData, oldBdata) = load_remote_2afc_data(oneCell)
    spikeTimestamps = spikeData.timestamps
    # -- Get trialsEachCond and colorEachCond for plotting -- #
    (bdata, trialsEachCond, colorEachCond) = get_trials_each_cond_switching(
        oneCell=oneCell, freqToPlot=freqToPlot,
        byBlock=byBlock)  #bdata generated here removed missing trials

    # -- Calculate eventOnsetTimes based on alignment parameter -- #
    eventOnsetTimes = np.array(eventData.timestamps)
    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

    # -- Calculate matrix of spikes per trial for plotting -- #
    (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
spikesanalysis.eventlocked_spiketimes(spikeTimestamps,EventOnsetTimes,timeRange)

    # -- Plot raster -- #
    #plt.figure()
    extraplots.raster_plot(spikeTimesFromEventOnset,
                           indexLimitsEachTrial,
                           timeRange,
                           trialsEachCond=trialsEachCond,
                           colorEachCond=colorEachCond,
                           fillWidth=None,
                           labels=None)
    #plt.ylim()
    plt.xlabel('Time from {} (s)'.format(alignment), fontsize=18)
    plt.ylabel('Trials', fontsize=18)
    plt.xlim(timeRange[0] + 0.1, timeRange[1])
    plt.title('{0}_{1}_T{2}c{3}_{4}_{5} frequency'.format(
        oneCell.animalName, oneCell.behavSession, oneCell.tetrode,
        oneCell.cluster, alignment, freqToPlot))
    #plt.fill([0,0.1,0.1,0],[plt.ylim()[0],plt.ylim()[0],plt.ylim()[1],plt.ylim()[1]],color='0.75')
    extraplots.set_ticks_fontsize(plt.gca(), fontSize=16)
Esempio n. 32
0
def plot_tuning_PSTH_one_intensity(oneCell,
                                   intensity=50.0,
                                   timeRange=[-0.5, 1],
                                   binWidth=0.010,
                                   halfFreqs=True):
    #calls load_remote_tuning_data(oneCell) to get the data, then plot raster
    eventOnsetTimes, spikeTimestamps, bdata = load_remote_tuning_data(
        oneCell, BEHAVDIR_MOUNTED, EPHYSDIR_MOUNTED)
    freqEachTrial = bdata['currentFreq']
    intensityEachTrial = bdata['currentIntensity']
    possibleIntensity = np.unique(intensityEachTrial)
    if len(possibleIntensity) != 1:
        intensity = intensity  #50dB is the stimulus intensity used in 2afc task
        ###Just select the trials with a given intensity###
        trialsThisIntensity = [intensityEachTrial == intensity]
        freqEachTrial = freqEachTrial[trialsThisIntensity]
        intensityEachTrial = intensityEachTrial[trialsThisIntensity]
        eventOnsetTimes = eventOnsetTimes[trialsThisIntensity]
    possibleFreq = np.unique(freqEachTrial)
    if halfFreqs:
        possibleFreq = possibleFreq[
            1::3]  #slice to get every other frequence presented
    numFreqs = len(possibleFreq)
    #print len(intensityEachTrial),len(eventOnsetTimes),len(spikeTimestamps)
    trialsEachFreq = behavioranalysis.find_trials_each_type(
        freqEachTrial, possibleFreq)
    #pdb.set_trace()  #for debug

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

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

    (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
        spikesanalysis.eventlocked_spiketimes(spikeTimestamps,eventOnsetTimes,timeRange)
    timeVec = np.arange(timeRange[0], timeRange[-1], binWidth)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, timeVec)
    smoothWinSize = 3
    #plt.figure()
    extraplots.plot_psth(spikeCountMat / binWidth,
                         smoothWinSize,
                         timeVec,
                         trialsEachCond=trialsEachFreq,
                         colorEachCond=colorEachFreq,
                         linestyle=None,
                         linewidth=2,
                         downsamplefactor=1)
    extraplots.set_ticks_fontsize(ax=plt.gca(), fontSize=14)
    plt.xlim(timeRange[0] + 0.1, timeRange[1])
    plt.legend(handles=handles, loc=2)
    plt.xlabel('Time from sound onset (s)', fontsize=18)
    plt.ylabel('Firing rate (spk/sec)', fontsize=18)
Esempio n. 33
0
        zscore = wilcoxen[0]
        pval = wilcoxen[1]

        pvalmat[indinten, indfreq] = pval
        zscoremat[indinten, indfreq] = zscore

figure()
a = pvalmat < 0.05
imshow(flipud(a), cmap='Blues', interpolation='none', aspect='auto')

figure()
imshow(flipud(zscoremat > 3), interpolation='none', aspect='auto')

figure()
clusterfuncs.plot_cluster_tuning(figdb[4], 'TuningCurve')
annotate('*', xy=(100, 1), xytext=(0, 0), color='r')

freqLabels = ["%.1f" % freq for freq in possibleFreq / 1000.0]

thalTCax.set_xticks([2, 4, 6, 8, 10, 12, 14])
thalTCax.set_xticklabels([])
thalTCax.set_ylabel('Intensity (db SPL)', fontsize=10)
extraplots.set_ticks_fontsize(thalTCax, 10)
cbar.set_ticks([4.0, 12.0])
cbar.ax.set_yticklabels([40, 120], fontsize=10)
cbar.ax.set_ylabel('Firing rate (Hz)', rotation=270, fontsize=10, labelpad=-5)
thalTCax.set_xticks(np.linspace(1, 15, 5))
thalTCax.set_xticklabels([2, 4, 8, 16, 32])
extraplots.set_ticks_fontsize(thalTCax, 10)
thalTCax.set_xlabel('Sound Frequency (kHz)', fontsize=10, labelpad=2)
Esempio n. 34
0
freqs = np.round(freqs, decimals=1)

nIntenLabels = 3
intensities = np.linspace(15, 70, nIntenLabels)
intenTickLocations = np.linspace(0, 11, nIntenLabels)

# ===========================Create and save figures=============================
# ---- TC Heatmap example 1 ----
if PANELS[0]:
    exampleKey = 'D1'
    exDataFR = exData[exampleKey]/0.1
    cax = dOne.imshow(np.flipud(exDataFR), interpolation='nearest', cmap=d1ColorMap)
    cbar = plt.colorbar(cax, ax=dOne, format='%d')
    maxFR = np.max(exDataFR.ravel())
    cbar.set_label('Firing rate\n(spk/s)', fontsize=fontSizeLabels, labelpad=-10)
    extraplots.set_ticks_fontsize(cbar.ax, fontSizeTicks)
    cbar.set_ticks([0, maxFR])
    cax.set_clim([0, maxFR])

    dOne.set_yticks(intenTickLocations)
    dOne.set_yticklabels(intensities[::-1])
    dOne.set_xticks(freqTickLocations)
    freqLabels = ['{0:.1f}'.format(freq) for freq in freqs]
    dOne.set_xticklabels(freqLabels)
    dOne.set_xlabel('Frequency (kHz)', fontsize=fontSizeLabels)
    dOne.set_ylabel('Intensity (dB SPL)', fontsize=fontSizeLabels)
    extraplots.set_ticks_fontsize(dOne, fontSizeTicks)

# ---- TC Heatmap example 2 ----
if PANELS[1]:
    exampleKey = 'nD1'
Esempio n. 35
0
ax0.set_ylabel('Reaction time (s)', fontsize=fontSizeLabels)
ax0.set_xlim([0.8, 2.2])
ax0.set_xticks([1, 2])
ax0.set_xticklabels([])
ax0.set_yticks([0, 0.1, 0.2])
ax0.set_ylim([-0.03, 0.23])
ax0.set_title('Leftward trials', fontsize=fontSizeLabels + 1)
plt.sca(ax0)
extraplots.significance_stars([1, 2],
                              0.2,
                              0.01,
                              starSize=12,
                              starString='n.s.',
                              gapFactor=0.2,
                              color='0.5')
extraplots.set_ticks_fontsize(ax0, fontSizeTicks)
extraplots.boxoff(ax0)
zScore, pVal = stats.wilcoxon(allMiceMeanLeftMore, allMiceMeanRightMore)
print('reaction time leftward p={}'.format(pVal))

ax1.annotate('C',
             xy=(labelPosX[2], labelPosY[0]),
             xycoords='figure fraction',
             fontsize=fontSizePanel,
             fontweight='bold')
allMiceMeanLeftMore = []
allMiceMeanRightMore = []
for (animal, shape) in animalShapes.items():
    reactionTimeRightwardLeftMore = summary[animal +
                                            '_reactionTimeRightChoiceMoreLeft']
    meanReactionTimeRightwardLeftMore = np.mean(reactionTimeRightwardLeftMore)
Esempio n. 36
0
    def generate_main_report(self, siteName):
        '''
        Generate the reports for all of the sessions in this site. This is where we should interface with
        the multiunit clustering code, since all of the sessions that need to be clustered together have
        been defined at this point.

        FIXME: This method should be able to load some kind of report template perhaps, so that the
        types of reports we can make are not a limited. For instance, what happens when we just have
        rasters for a site and no tuning curve? Implementing this is a lower priority for now.

        Incorporated lan's code for plotting the cluster reports directly on the main report
        '''
        #FIXME: import another piece of code to do this?
        #FIXME: OR, break into two functions: one that will do the multisite clustering, and one that
        #knows the type of report that we want. The first one can probably be a method of MSTC, the other
        #should either live in extraplots or should go in someone's directory

        for tetrode in self.goodTetrodes:
            oneTT = cms2.MultipleSessionsToCluster(self.animalName, self.get_session_filenames(), tetrode, '{}_{}'.format(self.date, siteName))
            oneTT.load_all_waveforms()

            #Do the clustering if necessary.
            clusterFile = os.path.join(oneTT.clustersDir,'Tetrode%d.clu.1'%oneTT.tetrode)
            if os.path.isfile(clusterFile):
                oneTT.set_clusters_from_file()
            else:
                oneTT.create_multisession_fet_files()
                oneTT.run_clustering()
                oneTT.set_clusters_from_file()

            oneTT.save_single_session_clu_files()
            possibleClusters = np.unique(oneTT.clusters)

            ee = EphysExperiment(self.animalName, self.date, experimenter = self.experimenter)

            #Iterate through the clusters, making a new figure for each cluster.
            #for indClust, cluster in enumerate([3]):
            for indClust, cluster in enumerate(possibleClusters):


                mainRasterInds = self.get_session_inds_one_type(plotType='raster', report='main')
                mainRasterSessions = [self.get_session_filenames()[i] for i in mainRasterInds]
                mainRasterTypes = [self.get_session_types()[i] for i in mainRasterInds]

                mainTCinds = self.get_session_inds_one_type(plotType='tc_heatmap', report='main')
                mainTCsessions = [self.get_session_filenames()[i] for i in mainTCinds]

                mainTCbehavIDs = [self.get_session_behavIDs()[i] for i in mainTCinds]
                mainTCtypes = [self.get_session_types()[i] for i in mainTCinds]

                plt.figure() #The main report for this cluster/tetrode/session

                for indRaster, rasterSession in enumerate(mainRasterSessions):
                    plt.subplot2grid((6, 6), (indRaster, 0), rowspan = 1, colspan = 3)
                    ee.plot_session_raster(rasterSession, tetrode, cluster = cluster, replace = 1, ms=1)
                    plt.ylabel('{}\n{}'.format(mainRasterTypes[indRaster], rasterSession.split('_')[1]), fontsize = 10)
                    ax=plt.gca()
                    extraplots.set_ticks_fontsize(ax,6)

                #We can only do one main TC for now.
                if len(mainTCsessions)>0:
                    plt.subplot2grid((6, 6), (0, 3), rowspan = 3, colspan = 3)
                    #tcIndex = site.get_session_types().index('tuningCurve')
                    tcSession = mainTCsessions[0]
                    tcBehavID = mainTCbehavIDs[0]
                    ee.plot_session_tc_heatmap(tcSession, tetrode, tcBehavID, replace = 1, cluster = cluster)
                    plt.title("{0}\nBehavFileID = '{1}'".format(tcSession, tcBehavID), fontsize = 10)

                nSpikes = len(oneTT.timestamps)
                nClusters = len(possibleClusters)
                #spikesEachCluster = np.empty((nClusters, nSpikes),dtype = bool)
                #if oneTT.clusters == None:
                    #oneTT.set_clusters_from_file()
                #for indc, clusterID in enumerate (possibleClusters):
                    #spikesEachCluster[indc, :] = (oneTT.clusters==clusterID)

                tsThisCluster = oneTT.timestamps[oneTT.clusters==cluster]
                wavesThisCluster = oneTT.samples[oneTT.clusters==cluster]
                # -- Plot ISI histogram --
                plt.subplot2grid((6,6), (4,0), rowspan=1, colspan=3)
                spikesorting.plot_isi_loghist(tsThisCluster)
                plt.ylabel('c%d'%cluster,rotation=0,va='center',ha='center')
                plt.xlabel('')

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

                # -- Plot projections --
                plt.subplot2grid((6,6), (4,3), rowspan=1, colspan=3)
                spikesorting.plot_projections(wavesThisCluster)

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

                plt.subplots_adjust(wspace = 0.7)
                fig_path = oneTT.clustersDir
                fig_name = 'TT{0}Cluster{1}.png'.format(tetrode, cluster)
                full_fig_path = os.path.join(fig_path, fig_name)
                print full_fig_path
                #plt.tight_layout()
                plt.savefig(full_fig_path, format = 'png')
                #plt.show()
                plt.close()


            plt.figure()
            oneTT.save_multisession_report()
            plt.close()
Esempio n. 37
0
            blankLabels[labelPos] = freqLabels[labelPos]

        axAMRaster.set_yticklabels(blankLabels)

        axAMRaster.set_xticks([0, 0.5])
        axAMRaster.set_xlabel('Time from\nsound onset (s)',
                              fontsize=fontSizeLabels,
                              labelpad=-1)
        axAMRaster.set_ylabel('AM rate (Hz)',
                              fontsize=fontSizeLabels,
                              labelpad=-5)
        axAMRaster.set_title('AM Raster')
        # axRate.set_xlim([0, 30])
        # axRate.set_xticks([0, 30])
        # extraplots.set_ticks_fontsize(axRate, fontSizeTicks)
        extraplots.set_ticks_fontsize(axAMRaster, fontSizeTicks)

    # -----------tuningCurve------------
    if "tuningCurve" in sessions:
        # Loading data for session
        tuningEphysData, tuningBehavData = oneCell.load('tuningCurve')

        # General variables for calculations
        tuningSpikeTimes = tuningEphysData['spikeTimes']
        tuningOnsetTime = tuningEphysData['events']['soundDetectorOn']
        tuningCurrentFreq = tuningBehavData['currentFreq']
        trialsEachType = behavioranalysis.find_trials_each_type(
            tuningCurrentFreq, np.unique(tuningCurrentFreq))
        tuningUniqFreq = np.unique(tuningCurrentFreq)
        b = np.array(["%.0f" % i for i in tuningUniqFreq
                      ])  # this is unique frequencies, but rounded off
Esempio n. 38
0
            axRaster.set_xticklabels('')
        else:
            plt.xlabel('Time from laser onset (s)', fontsize=fontSizeLabels)
        plt.ylabel('Trial', fontsize=fontSizeLabels)

        yLims = np.array(plt.ylim())
        rect = patches.Rectangle((0, yLims[1] * 1.03),
                                 0.1,
                                 yLims[1] * 0.04,
                                 linewidth=1,
                                 edgecolor=laserColor,
                                 facecolor=laserColor,
                                 clip_on=False)
        axRaster.add_patch(rect)

    extraplots.set_ticks_fontsize(axRaster, fontSizeTicks)

# --- histograms of spike widths as well as waveforms for all recorded Exc., PV, SOM cells
if PANELS[1]:
    # all waveforms
    waveformsDataFullPath = os.path.join(dataDir, waveformsFileName)
    spikeShapeData = np.load(waveformsDataFullPath)
    ExcSpikeShapes = spikeShapeData['ExcNormSpikeShapes']
    ExcMedianSpikeShape = spikeShapeData['ExcMedianSpikeShape']
    PVspikeShapes = spikeShapeData['PVnormSpikeShapes']
    PVmedianSpikeShape = spikeShapeData['PVmedianSpikeShape']
    SOMspikeShapes = spikeShapeData['SOMnormSpikeShapes']
    SOMmedianSpikeShape = spikeShapeData['SOMmedianSpikeShape']

    ExcSpikeWidths = spikeShapeData['ExcSpikeWidths']
    PVspikeWidths = spikeShapeData['PVspikeWidths']
Esempio n. 39
0
def nick_lan_main_report(siteObj, show=False, save=True, saveClusterReport=True):
    for tetrode in siteObj.goodTetrodes:
        oneTT = cms2.MultipleSessionsToCluster(
            siteObj.animalName,
            siteObj.get_session_filenames(),
            tetrode,
            '{}at{}um'.format(
                siteObj.date,
                siteObj.depth))
        oneTT.load_all_waveforms()

        # Do the clustering if necessary.
        clusterFile = os.path.join(
            oneTT.clustersDir,
            'Tetrode%d.clu.1' %
            oneTT.tetrode)
        if os.path.isfile(clusterFile):
            oneTT.set_clusters_from_file()
        else:
            oneTT.create_multisession_fet_files()
            oneTT.run_clustering()
            oneTT.set_clusters_from_file()

        oneTT.save_single_session_clu_files()
        possibleClusters = np.unique(oneTT.clusters)

        ee = ee3.EphysExperiment(
            siteObj.animalName,
            siteObj.date,
            experimenter=siteObj.experimenter)

        # Iterate through the clusters, making a new figure for each cluster.
        # for indClust, cluster in enumerate([3]):
        for indClust, cluster in enumerate(possibleClusters):

            mainRasterInds = siteObj.get_session_inds_one_type(
                plotType='raster',
                report='main')
            mainRasterSessions = [
                siteObj.get_session_filenames()[i] for i in mainRasterInds]
            mainRasterTypes = [
                siteObj.get_session_types()[i] for i in mainRasterInds]

            mainTCinds = siteObj.get_session_inds_one_type(
                plotType='tc_heatmap',
                report='main')
            mainTCsessions = [
                siteObj.get_session_filenames()[i] for i in mainTCinds]

            mainTCbehavIDs = [
                siteObj.get_session_behavIDs()[i] for i in mainTCinds]
            mainTCtypes = [siteObj.get_session_types()[i] for i in mainTCinds]

            # The main report for this cluster/tetrode/session
            plt.figure()

            for indRaster, rasterSession in enumerate(mainRasterSessions):
                plt.subplot2grid(
                    (6, 6), (indRaster, 0), rowspan=1, colspan=3)
                ee.plot_session_raster(
                    rasterSession,
                    tetrode,
                    cluster=cluster,
                    replace=1,
                    ms=1)
                plt.ylabel(
                    '{}\n{}'.format(
                        mainRasterTypes[indRaster],
                        rasterSession.split('_')[1]),
                    fontsize=10)
                ax = plt.gca()
                extraplots.set_ticks_fontsize(ax, 6)

            # We can only do one main TC for now.
            plt.subplot2grid((6, 6), (0, 3), rowspan=3, colspan=3)
            tcSession = mainTCsessions[0]
            tcBehavID = mainTCbehavIDs[0]
            ee.plot_session_tc_heatmap(
                tcSession,
                tetrode,
                tcBehavID,
                replace=1,
                cluster=cluster)
            plt.title(
                "{0}\nBehavFileID = '{1}'".format(
                    tcSession,
                    tcBehavID),
                fontsize=10)

            nSpikes = len(oneTT.timestamps)
            nClusters = len(possibleClusters)
            #spikesEachCluster = np.empty((nClusters, nSpikes),dtype = bool)
            # if oneTT.clusters == None:
            # oneTT.set_clusters_from_file()
            # for indc, clusterID in enumerate (possibleClusters):
            #spikesEachCluster[indc, :] = (oneTT.clusters==clusterID)

            tsThisCluster = oneTT.timestamps[oneTT.clusters == cluster]
            wavesThisCluster = oneTT.samples[oneTT.clusters == cluster]
            # -- Plot ISI histogram --
            plt.subplot2grid((6, 6), (4, 0), rowspan=1, colspan=3)
            spikesorting.plot_isi_loghist(tsThisCluster)
            plt.ylabel(
                'c%d' %
                cluster,
                rotation=0,
                va='center',
                ha='center')
            plt.xlabel('')

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

            # -- Plot projections --
            plt.subplot2grid((6, 6), (4, 3), rowspan=1, colspan=3)
            spikesorting.plot_projections(wavesThisCluster)

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

            fig_path = oneTT.clustersDir
            fig_name = 'TT{0}Cluster{1}.png'.format(tetrode, cluster)
            full_fig_path = os.path.join(fig_path, fig_name)
            print full_fig_path
            # plt.tight_layout()

            if save: 
                plt.savefig(full_fig_path, format='png')
            if show:
                plt.show()
            if not show:
                plt.close()

        if saveClusterReport:
            plt.figure()
            oneTT.save_multisession_report()
            plt.close()
Esempio n. 40
0
def plot_dynamics_sound_type(behavData, soundType, winsize=40,fontsize=12,soundfreq=None):
    '''
    DEPRECATED - load data into two data objects (one per sound type) and use the regular func
    Plot performance in time for one session.
    First argument is an object created by loadbehavior.BehaviorData (or subclasses)
    '''

    print 'FIXME: no removal of invalid trials in sound type dynamics'

    trialsSoundType = behavData['soundType']==behavData.labels['soundType'][soundType]

    valid = behavData['valid']
    validSoundType = valid[trialsSoundType]

    freqEachTrialSoundType = behavData['targetFrequency'][trialsSoundType]

    blockIDthisSoundType = behavData['currentBlock'][trialsSoundType]
    possibleBlockID = np.unique(blockIDthisSoundType)

    ax = plt.gca()
    ax.cla()
    lineWidth = 2

    if soundfreq is None:
        possibleFreq = [min(np.unique(freqEachTrialSoundType)), max(np.unique(freqEachTrialSoundType))]
    else:
        possibleFreq = soundfreq

    #########

    possibleColors = FREQCOLORS + ['k','m','c', 'b','r','g']
    colorEachFreq = dict(zip(possibleFreq,possibleColors))

    rightChoice = behavData['choice']==behavData.labels['choice']['right']
    rightChoiceSoundType = rightChoice[trialsSoundType]

    hPlots = []
    plt.hold(True)

    for indf,thisFreq in enumerate(possibleFreq):

        thisColor = colorEachFreq[thisFreq]
        trialsThisFreqSoundType = (freqEachTrialSoundType==thisFreq)

        choiceVecThisFreq = np.ma.masked_array(rightChoiceSoundType)
        choiceVecThisFreq.mask = ~trialsThisFreqSoundType

        movAvChoice = extrafuncs.moving_average_masked(choiceVecThisFreq,winsize)

        hp, = plt.plot(range(len(movAvChoice)), 100*movAvChoice,
                        lw=lineWidth,color=thisColor)
        hPlots.append(hp)

    plt.ylim([-5,105])
    plt.axhline(50,color='0.5',ls='--')
    plt.ylabel('% rightward',fontsize=fontsize)
    plt.xlabel('Trial',fontsize=fontsize)
    extraplots.set_ticks_fontsize(ax,fontsize)
    plt.draw()
    plt.show()
    return hPlots
Esempio n. 41
0
from jaratoolbox import extraplots
from jaratoolbox import colorpalette

animal = 'amod004'
session = '20160502a'


dataObjs, soundTypes = behavioranalysis.load_behavior_sessions_sound_type(animal, [session])

figure()
clf()
bdata = dataObjs[soundTypes['tones']]
ax = subplot(121)
est = plot_psycurve_fit_and_data(bdata, 'k')
extraplots.boxoff(ax)
extraplots.set_ticks_fontsize(ax, 20)
fitline = ax.lines[3]
setp(fitline, lw=3)
setp(fitline, color=colorpalette.TangoPalette['Chameleon2'])
# pcaps= ax.lines[0]
# pbars = ax.lines[2]
# setp(pcaps, lw=2)
# setp(pbars, lw=2)
xticklabels = [item.get_text() for item in ax.get_xticklabels()]
xticks = ax.get_xticks()
newXtickLabels = logspace(xticks[0], xticks[-1], 3, base=2)
plt.ylim(-0.03, 1.03)

ax.set_xticks(np.log2(np.array(newXtickLabels)))
ax.set_xticklabels(['{:.3}'.format(x/1000.0) for x in newXtickLabels])
plt.show()