def plot_psycurve_fit_and_data_nohigh(bdata, plotFits=True):

    '''
    This version actually works. Calculates things in log2(freq) space.
    '''

    rightTrials = bdata['choice']==bdata.labels['choice']['right']
    freqEachTrial = bdata['targetFrequency']
    valid = bdata['valid']

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

    plot(np.log2(possibleValues), fractionHitsEachValue, 'bo')
    hold(1)

    possibleFreq = np.log2(np.unique(freqEachTrial))
    lowerFreqConstraint = possibleFreq[1]
    upperFreqConstraint = possibleFreq[-2]
    maxFreq = max(possibleFreq)
    minFreq = min(possibleFreq)

    constraints = ( 'Uniform({}, {})'.format(lowerFreqConstraint, upperFreqConstraint), 'Uniform(0,5)' ,'Uniform(0,1)', 'Uniform(0,1)')
    estimate = extrastats.psychometric_fit(possibleFreq[:-1], nTrialsEachValue[:-1], nHitsEachValue[:-1], constraints)

    xRange = possibleFreq[-1]-possibleFreq[1]
    fitxval = np.linspace(possibleFreq[0]-0.1*xRange,possibleFreq[-1]+0.1*xRange,40)

    fityvals = extrastats.psychfun(fitxval, *estimate)

    plot(fitxval, fityvals)
    ylim([0, 1])

    return estimate
def plot_psycurve_fit_and_data(bdata, plotFits=True):
    rightTrials = bdata['choice']==bdata.labels['choice']['right']
    freqEachTrial = bdata['targetFrequency']
    valid = bdata['valid']

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

    #Calculate the lower and upper freq in the bdata to set the correct constraints
    # possibleFreq = np.unique(freqEachTrial)
    possibleFreq = np.log2(np.unique(freqEachTrial))
    maxFreq = max(possibleFreq)
    minFreq = min(possibleFreq)


    #Calculating with constraints
    # constraints = ( 'Uniform({}, {})'.format(minFreq, maxFreq),'Uniform(0,20)' ,'Uniform(0,1)', 'Uniform(0,1)')
    constraints = ( 'Uniform({}, {})'.format(minFreq, maxFreq), 'Uniform(0,10)' ,'Uniform(0,0.2)', 'Uniform(0,0.2)')
    estimate = extrastats.psychometric_fit(possibleValues, nTrialsEachValue, nHitsEachValue, constraints)

    if plotFits:
        xRange = possibleFreq[-1]-possibleFreq[1]
        fitxval = np.linspace(possibleFreq[0]-0.1*xRange,possibleFreq[-1]+0.1*xRange,40)

        #The fitted points
        fityvals = extrastats.psychfun(fitxval, estimate[0], estimate[1], estimate[2], estimate[3])

        plot(fitxval, fityvals)
        # hold(1)
        # extraplots.plot_psychometric(possibleFreq, fractionHitsEachValue, ciHitsEachValue)
        plot(np.log2(possibleFreq), fractionHitsEachValue, 'bo')

    return estimate
def plot_fitted_psycurve(bdata, color='k', linestyle=None):
    rightTrials = bdata['choice'] == bdata.labels['choice']['right']
    freqEachTrial = bdata['targetFrequency']
    valid = bdata['valid']
    (possibleValues, fractionHitsEachValue, ciHitsEachValue, nTrialsEachValue,
     nHitsEachValue) = behavioranalysis.calculate_psychometric(
         rightTrials, freqEachTrial, valid)

    pline, pcaps, pbars, pdots = extraplots.plot_psychometric(
        possibleValues, fractionHitsEachValue, ciHitsEachValue)
    setp(pline, color='w')
    setp(pcaps, color=color)
    setp(pbars, color=color)
    setp(pdots, markerfacecolor=color)

    estimate = extrastats.psychometric_fit(possibleValues, nTrialsEachValue,
                                           nHitsEachValue)

    yvals = nHitsEachValue.astype(float) / nTrialsEachValue
    xvals = possibleValues
    xRange = xvals[-1] - xvals[0]
    fitxval = np.linspace(xvals[0] - 0.1 * xRange, xvals[-1] + 0.1 * xRange,
                          40)
    fityval = extrastats.psychfun(fitxval, *estimate)
    hfit = plot(fitxval, 100 * fityval, '-', linewidth=2, color=color)

    return (estimate, (pline, pcaps, pbars, pdots, hfit))
예제 #4
0
def psycurve_fit_from_bdata(bdata, plotFits=True):
    '''
    Nick 2016-05-20

    Calculates psychometric curve fits in log2(freq) space.

    Args:

    bdata (jaratoolbox.loadbehavior.BehaviorData object): The bdata object to fit
    plotFits (bool): whether or not to plot the data and fitted curve to the current axis

    Returns:

    estimate (list of float): The parameter estimates for the psychometric function (alpha, beta, gamma, lambda - see jaratoolbox.extrastats.psychometric_fit)
    '''

    rightTrials = bdata['choice'] == bdata.labels['choice']['right']
    freqEachTrial = bdata['targetFrequency']
    valid = bdata['valid']

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

    possibleFreq = np.log2(np.unique(freqEachTrial))
    print 'FIXME: Arbitrary constraints for alpha pos!!'
    lowerFreqConstraint = possibleFreq[1]
    upperFreqConstraint = possibleFreq[-2]
    # lowerFreqConstraint = possibleFreq[0]
    # upperFreqConstraint = possibleFreq[-1]
    maxFreq = max(possibleFreq)
    minFreq = min(possibleFreq)

    constraints = ('Uniform({}, {})'.format(lowerFreqConstraint,
                                            upperFreqConstraint),
                   'Uniform(0,5)', 'Uniform(0,0.5)', 'Uniform(0,0.5)')
    # constraints = ( 'unconstrained', 'Uniform(0,2)' ,'Uniform(0,1)', 'Uniform(0,1)')
    estimate = extrastats.psychometric_fit(possibleFreq, nTrialsEachValue,
                                           nHitsEachValue, constraints)

    if plotFits:
        ax = plt.gca()
        xRange = possibleFreq[-1] - possibleFreq[1]
        fitxval = np.linspace(possibleFreq[0] - 0.1 * xRange,
                              possibleFreq[-1] + 0.1 * xRange, 40)

        fityvals = extrastats.psychfun(fitxval, *estimate)

        ax.plot(possibleFreq, fractionHitsEachValue, 'bo')
        plt.hold(1)

        ax.plot(fitxval, fityvals)
        plt.ylim([0, 1])

    return estimate
예제 #5
0
def psycurve_fit_from_bdata(bdata, plotFits=True):

    '''
    Nick 2016-05-20

    Calculates psychometric curve fits in log2(freq) space.

    Args:

    bdata (jaratoolbox.loadbehavior.BehaviorData object): The bdata object to fit
    plotFits (bool): whether or not to plot the data and fitted curve to the current axis

    Returns:

    estimate (list of float): The parameter estimates for the psychometric function (alpha, beta, gamma, lambda - see jaratoolbox.extrastats.psychometric_fit)
    '''

    rightTrials = bdata['choice']==bdata.labels['choice']['right']
    freqEachTrial = bdata['targetFrequency']
    valid = bdata['valid']

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

    possibleFreq = np.log2(np.unique(freqEachTrial))
    print 'FIXME: Arbitrary constraints for alpha pos!!'
    lowerFreqConstraint = possibleFreq[1]
    upperFreqConstraint = possibleFreq[-2]
    # lowerFreqConstraint = possibleFreq[0]
    # upperFreqConstraint = possibleFreq[-1]
    maxFreq = max(possibleFreq)
    minFreq = min(possibleFreq)


    constraints = ( 'Uniform({}, {})'.format(lowerFreqConstraint, upperFreqConstraint), 'Uniform(0,5)' ,'Uniform(0,0.5)', 'Uniform(0,0.5)')
    # constraints = ( 'unconstrained', 'Uniform(0,2)' ,'Uniform(0,1)', 'Uniform(0,1)')
    estimate = extrastats.psychometric_fit(possibleFreq, nTrialsEachValue, nHitsEachValue, constraints)

    if plotFits:
        ax = plt.gca()
        xRange = possibleFreq[-1]-possibleFreq[1]
        fitxval = np.linspace(possibleFreq[0]-0.1*xRange,possibleFreq[-1]+0.1*xRange,40)

        fityvals = extrastats.psychfun(fitxval, *estimate)

        ax.plot(possibleFreq, fractionHitsEachValue, 'bo')
        plt.hold(1)

        ax.plot(fitxval, fityvals)
        plt.ylim([0, 1])

    return estimate
def calculate_psychometric_and_estimate(bdata, fullDataPath):
    '''
    Calculates psychometric from bdata and estimates fit
    '''
    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)

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

    #Calculate the estimate for the psychometric function
    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)

    np.savez(fullDataPath,
             possibleValues=possibleValues,
             fractionHitsEachValue=fractionHitsEachValue,
             ciHitsEachValue=ciHitsEachValue,
             nTrialsEachValue=nTrialsEachValue,
             nHitsEachValue=nHitsEachValue,
             logPossibleValues=logPossibleValues,
             estimate=estimate,
             script=scriptFullPath)
    print 'Saved results to {}'.format(fullDataPath)
예제 #7
0
def plot_psycurve_fit_and_data_nohigh(bdata, plotFits=True):
    '''
    This version actually works. Calculates things in log2(freq) space.
    '''

    rightTrials = bdata['choice'] == bdata.labels['choice']['right']
    freqEachTrial = bdata['targetFrequency']
    valid = bdata['valid']

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

    plot(np.log2(possibleValues), fractionHitsEachValue, 'bo')
    hold(1)

    possibleFreq = np.log2(np.unique(freqEachTrial))
    lowerFreqConstraint = possibleFreq[1]
    upperFreqConstraint = possibleFreq[-2]
    maxFreq = max(possibleFreq)
    minFreq = min(possibleFreq)

    constraints = ('Uniform({}, {})'.format(lowerFreqConstraint,
                                            upperFreqConstraint),
                   'Uniform(0,5)', 'Uniform(0,1)', 'Uniform(0,1)')
    estimate = extrastats.psychometric_fit(possibleFreq[:-1],
                                           nTrialsEachValue[:-1],
                                           nHitsEachValue[:-1], constraints)

    xRange = possibleFreq[-1] - possibleFreq[1]
    fitxval = np.linspace(possibleFreq[0] - 0.1 * xRange,
                          possibleFreq[-1] + 0.1 * xRange, 40)

    fityvals = extrastats.psychfun(fitxval, *estimate)

    plot(fitxval, fityvals)
    ylim([0, 1])

    return estimate
def plot_fitted_psycurve(bdata, color='k', linestyle=None):
    rightTrials = bdata['choice']==bdata.labels['choice']['right']
    freqEachTrial = bdata['targetFrequency']
    valid = bdata['valid']
    (possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue) = behavioranalysis.calculate_psychometric(rightTrials, freqEachTrial, valid)

    pline, pcaps, pbars, pdots = extraplots.plot_psychometric(possibleValues, fractionHitsEachValue, ciHitsEachValue)
    setp(pline, color='w')
    setp(pcaps, color=color)
    setp(pbars, color=color)
    setp(pdots, markerfacecolor=color)

    estimate = extrastats.psychometric_fit(possibleValues, nTrialsEachValue, nHitsEachValue)

    yvals = nHitsEachValue.astype(float)/nTrialsEachValue
    xvals = possibleValues
    xRange = xvals[-1]-xvals[0]
    fitxval = np.linspace(xvals[0]-0.1*xRange,xvals[-1]+0.1*xRange,40)
    fityval = extrastats.psychfun(fitxval,*estimate)
    hfit = plot(fitxval,100*fityval,'-',linewidth=2, color=color)

    return (estimate, (pline, pcaps, pbars, pdots, hfit))
예제 #9
0
def plot_psycurve_fit_and_data(bdata, plotFits=True):
    rightTrials = bdata['choice'] == bdata.labels['choice']['right']
    freqEachTrial = bdata['targetFrequency']
    valid = bdata['valid']

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

    #Calculate the lower and upper freq in the bdata to set the correct constraints
    # possibleFreq = np.unique(freqEachTrial)
    possibleFreq = np.log2(np.unique(freqEachTrial))
    maxFreq = max(possibleFreq)
    minFreq = min(possibleFreq)

    #Calculating with constraints
    # constraints = ( 'Uniform({}, {})'.format(minFreq, maxFreq),'Uniform(0,20)' ,'Uniform(0,1)', 'Uniform(0,1)')
    constraints = ('Uniform({}, {})'.format(minFreq, maxFreq), 'Uniform(0,10)',
                   'Uniform(0,0.2)', 'Uniform(0,0.2)')
    estimate = extrastats.psychometric_fit(possibleValues, nTrialsEachValue,
                                           nHitsEachValue, constraints)

    if plotFits:
        xRange = possibleFreq[-1] - possibleFreq[1]
        fitxval = np.linspace(possibleFreq[0] - 0.1 * xRange,
                              possibleFreq[-1] + 0.1 * xRange, 40)

        #The fitted points
        fityvals = extrastats.psychfun(fitxval, estimate[0], estimate[1],
                                       estimate[2], estimate[3])

        plot(fitxval, fityvals)
        # hold(1)
        # extraplots.plot_psychometric(possibleFreq, fractionHitsEachValue, ciHitsEachValue)
        plot(np.log2(possibleFreq), fractionHitsEachValue, 'bo')

    return estimate
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
figure()
# pypsignifit.psigniplot.plotPMF(B)
pypsignifit.plotMultiplePMFs(M, S)










# constraints = ( 'Uniform(0, 100)','Uniform(0,20)' ,'Uniform(0,20)', 'Uniform(0,100)')
estimate = extrastats.psychometric_fit(possibleValues, nTrialsEachValue, nHitsEachValue, constraints)

# clf()
# pypsignifit.psigniplot.plotPMF(session)
# show()






from extracellpy import behavioranalysis as exbehav

figure()
exbehav.plot_psychcurve_fit(possibleValues, nTrialsEachValue, nHitsEachValue, estimate)
show()
figure()
# pypsignifit.psigniplot.plotPMF(B)
pypsignifit.plotMultiplePMFs(M, S)


from jaratoolbox.extrastats import psychometric_fit

trialsSoundTypeSalAmp = salineData['soundType']==salineData.labels['soundType'][soundType]
rightTrialsSalAmp = (salineData['choice']==salineData.labels['choice']['right'])[trialsSoundTypeSalAmp]
freqEachTrialSalAmp = salineData['targetFrequency'][trialsSoundTypeSalAmp]
validSalAmp = salineData['valid'][trialsSoundTypeSalAmp]

(possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue) = behavioranalysis.calculate_psychometric(rightTrialsSalAmp, freqEachTrialSalAmp, validSalAmp)

estimate = psychometric_fit(possibleValues, nHitsEachValue, nTrialsEachValue)







#functions stolen from santiago
def weibull(xval,alpha,beta):
    '''Weibull function
    alpha: bias
    beta: related to slope
    NOTE: this function isnot symmetric
    '''
    return 1 - np.exp(-pow(xval/alpha,beta))
예제 #13
0
plt.clf()
#(pline, pcaps, pbars, pdots) = extraplots.plot_psychometric(possibleValues,fractionHitsEachValue,ciHitsEachValue)
#plt.setp(pdots,ms=6,mec='k',mew=2,mfc='k')
plt.plot(logPossibleValues, fractionHitsEachValue, 'o')
plt.xlabel('Frequency (log2(Hz))')
plt.ylabel('Rightward choice (%)')

plt.show()

# -- Calculate and plot psychometric fit --
#constraints = None
constraints = [
    'Uniform(10,15)', 'Uniform(0,5)', 'Uniform(0,1)', 'Uniform(0,1)'
]
curveParams = extrastats.psychometric_fit(logPossibleValues, nTrialsEachValue,
                                          nHitsEachValue, constraints)

print 'Psychometric parameters (bias, slope, upper, lower):'
print curveParams

plt.hold(True)

xValues = logPossibleValues
xRange = xValues[-1] - xValues[1]
fitxval = np.linspace(xValues[0] - 0.1 * xRange, xValues[-1] + 0.1 * xRange,
                      40)
fityval = extrastats.psychfun(fitxval, *curveParams)
hfit = plt.plot(fitxval, fityval, '-', linewidth=2, color='k')

#(hp,hfit) = extraplots.plot_psychometric_fit(possibleValues,nTrialsEachValue,
#                                           nHitsEachValue,curveParams)