Пример #1
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 soundfreq:
        possibleFreq = np.unique(behavData['targetFrequency'])
    else:
        possibleFreq = soundfreq
    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 = []
    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)
    plt.draw()
    plt.show()
    return hPlots
Пример #2
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()
Пример #3
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 soundfreq:
        possibleFreq = np.unique(behavData['targetFrequency'])
    else:
        possibleFreq = soundfreq
    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 = []
    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)
    plt.draw()
    plt.show()
    return hPlots
Пример #4
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)
Пример #5
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)
Пример #6
0
def plot_dynamics(behavData,winsize=40,fontsize=12):
    ax = plt.gca()
    ax.cla()
    lineWidth = 2
    possibleFreq = np.unique(behavData['TargetFreq'])
    possibleColors = ['b','r','g','k','m','c']
    colorEachFreq = dict(zip(possibleFreq,possibleColors))

    behavData.find_trials_each_block()

    nBlocks = len(behavData.eachBlockID)
    trialsEachBlock = behavData.trialsEachBlock
    nValidEachBlock = np.sum(behavData.trialsEachBlock & (~behavData.early[:,np.newaxis]),axis=0)
    lastValidEachBlock = np.cumsum(nValidEachBlock)
    firstValidEachBlock = np.concatenate(([0],lastValidEachBlock[:-1]))

    for indb in range(nBlocks):
        trialsThisBlock = trialsEachBlock[:,indb]
        freqsThisBlock = np.unique(behavData['TargetFreq'][trialsThisBlock])
        validThisBlock = trialsThisBlock & (~behavData.early)
        for indf,thisFreq in enumerate(freqsThisBlock):
            thisColor = colorEachFreq[thisFreq]
            trialsThisFreq = (behavData['TargetFreq']==thisFreq)
            choiceVecThisFreq = np.ma.masked_array(behavData.rightChoice[validThisBlock])
            choiceVecThisFreq.mask = ~trialsThisFreq[validThisBlock]
            movAvChoice = extrafuncs.moving_average_masked(choiceVecThisFreq,winsize)
            plt.plot(range(firstValidEachBlock[indb],lastValidEachBlock[indb]),100*movAvChoice,
                 lw=lineWidth,color=thisColor)
            plt.hold(True)
    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()
Пример #7
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()
Пример #8
0
def plot_summary(behavData,fontsize=12):
    '''Show summary of performance.
    Input is an object created by loadbehavior.ReversalBehaviorData()
    '''
    behavData.extract_event_times()    # In case it hasn't
    behavData.find_trials_each_type()  # In case it hasn't

    percentEarly = 100*sum(behavData.early)/float(behavData['nTrials'])

    mostCommonBlock = np.argmax(np.bincount(behavData['CurrentBlock'].astype(int)))
    if mostCommonBlock != 1:
        # -- Blocks change from LowFreq to HighFreq
        g1 = behavData.lowFreqs & behavData.leftReward
        g2 = behavData.lowFreqs & behavData.rightReward
        g3 = behavData.highFreqs & behavData.leftReward
        g4 = behavData.highFreqs & behavData.rightReward
    else:
        # -- ExtremeFreq --
        g1 = behavData.leftReward
        g2 = zeros(len(behavData.leftReward)).astype(bool)
        g3 = zeros(len(behavData.leftReward)).astype(bool)
        g4 = behavData.rightReward
        
    trialsEachCond = np.array([g1,g2,g3,g4])        
    validTrialsEachCond = trialsEachCond & (~behavData.early)
    correctTrialsEachCond = validTrialsEachCond & behavData.correct
    percentEarly = 100*sum(behavData.early)/float(len(behavData.early))

    ### WARNING: this gives a different number of valid trials than matlab!
    ###          check if first empty trial is included or not

    nCorrectEachCond = np.sum(correctTrialsEachCond,axis=1)
    nValidEachCond = np.sum(validTrialsEachCond,axis=1)

    perfEachCond = nCorrectEachCond/nValidEachCond.astype(float)

    freqValues = [behavData['FreqLow'][-1],
                  behavData['FreqMid'][-1],
                  behavData['FreqMid'][-1],
                  behavData['FreqHigh'][-1]]
    freqLabels = ['%0.1f'%(x/1000) for x in freqValues]

    # --- Plot results ---
    xPos = [0,1,3,4]
    #plt.clf()
    #ax = plt.axes()
    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*perfEachCond,align='center',fc=[0.8,0.8,0.8],ec='k')
    #htrials(indtype) = text(BarXpos(indtype),10,num2str(NtrialsEachCond(indc)));
    for thispos,thistext in zip(xPos,nValidEachCond):
        plt.text(thispos,10,str(thistext),ha='center',fontsize=fontsize)
    ax.set_ylabel('% correct',fontsize=fontsize)
    ax.set_xticks(xPos)
    ax.set_xticklabels(freqLabels)

    titleStr = '%s [%s] %s\n'%(behavData['Subject'],behavData['Date'],behavData['HostName'])
    titleStr += '%d valid, %d%% early'%(sum(nValidEachCond),round(percentEarly))
    ax.set_title(titleStr,fontweight='bold',fontsize=fontsize)
    extraplots.set_ticks_fontsize(ax,fontsize)
    
    #plt.gcf().set_size_inches(4,5)

    plt.draw()
    plt.show()