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))
Esempio n. 2
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])
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)
Esempio n. 4
0
 def test(self):
     hits = bdata['outcome']==bdata.labels['outcome']['correct']
     freqEachTrial = bdata['targetFrequency']
     valid = bdata['valid']
     (possibleValues,
      fractionHitsEachValue,
      ciHitsEachValue,
      nTrialsEachValue,
      nHitsEachValue) = behavioranalysis.calculate_psychometric(hits,
                                                                freqEachTrial,
                                                                valid)
     #Get the percent correct for the low and high freqs and test against the threshol
     lowPerCorr = 100*fractionHitsEachValue[0]
     highPerCorr = 100*fractionHitsEachValue[-1]
     print 'Low Freq Percent Correct: {}'.format(lowPerCorr)
     print 'High Freq Percent Correct: {}'.format(highPerCorr)
     print 'Threshold: {}'.format(self.threshold)
     return ((lowPerCorr>self.threshold) & (highPerCorr>self.threshold))
    subplot(1, len(animalsNames), inda + 1)
    for indset, sessions in enumerate(allSessions[:2]):
        bdata = behavioranalysis.load_many_sessions(animalName, sessions)
        targetFrequency = bdata['targetFrequency']
        choice = bdata['choice']
        valid = bdata['valid'] & (choice != bdata.labels['choice']['none'])
        intensities = bdata['targetIntensity']
        choiceRight = choice == bdata.labels['choice']['right']

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

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

        hold(True)
        (pline, pcaps, pbars,
         pdots) = extraplots.plot_psychometric(possibleValues,
                                               fractionHitsEachValue,
                                               ciHitsEachValue)
        setp(pdots, ms=6, mec='k', mew=2, mfc=markerFaceColors[indset])
        plotHandles.append(pdots[0])
    xlabel('Frequency (Hz)', fontsize=fontSize)
    ylabel('Rightward choice (%)', fontsize=fontSize)
    legend(plotHandles, ['pre', 'post'],
           numpoints=1,
           loc='upper left',
           fontsize=fontSize - 2)
    title(animalName)
Esempio n. 6
0
        targetFrequency = bdata['targetFrequency']
        choice = bdata['choice']
        # valid=bdata['valid']& (choice!=bdata.labels['choice']['none'])
        laser = bdata['laserOn'] == 1
        noLaser = bdata['laserOn'] == 0

        choiceRight = choice == bdata.labels['choice']['right']
        possibleFreq = np.unique(targetFrequency)
        nFreq = len(possibleFreq)
        trialsEachFreq = behavioranalysis.find_trials_each_type(
            targetFrequency, possibleFreq)

        #noLaser first
        (possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue)=\
        behavioranalysis.calculate_psychometric(choiceRight,targetFrequency,noLaser)
        (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='k')
        plt.setp(pcaps, color='k')
        plt.setp(pbars, color='k')
        plt.setp(pdots, markerfacecolor='k')

        plt.hold(1)
    #bfile = loadbehavior.path_to_behavior_data(subject,paradigm,session)
    #bdata = loadbehavior.BehaviorData(bfile,readmode='full')

    bdata = behavioranalysis.load_many_sessions(subjects, sessions)

    correct = bdata['outcome'] == bdata.labels['outcome']['correct']
    targetPercentage = bdata[
        'targetFrequency']  # I used name 'frequency' initially
    choiceRight = bdata['choice'] == bdata.labels['choice']['right']
    valid = bdata['valid'].astype(bool) & (bdata['choice'] !=
                                           bdata.labels['choice']['none'])
    laserTrials = bdata['laserTrial'] == bdata.labels['laserTrial']['yes']
    validLaser = valid & laserTrials
    validNoLaser = valid & ~laserTrials
    (possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue)=\
           behavioranalysis.calculate_psychometric(choiceRight,targetPercentage,validNoLaser)
    (possibleValuesL,fractionHitsEachValueL,ciHitsEachValueL,nTrialsEachValueL,nHitsEachValueL)=\
           behavioranalysis.calculate_psychometric(choiceRight,targetPercentage,validLaser)

    nNoLaser = np.sum(validNoLaser)
    nLaser = np.sum(validLaser)
    fractionCorrectNoLaser = np.mean(correct[validNoLaser])
    fractionCorrectLaser = np.mean(correct[validLaser])
    print('Correct: NoLaser({})={:0.1%}  Laser({})={:0.1%}'.format(
        nNoLaser, fractionCorrectNoLaser, nLaser, fractionCorrectLaser))

    #plt.subplot(4,2,inds+1)
    #plt.title('{0} [{1}]'.format(subject,session))

    plt.hold(1)
    (pline, pcaps, pbars,
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. 9
0
				inds += 1
	bdata = allBehavData
	'''
	valid = bdata['valid']
	choice = bdata['choice']

	print sum(valid)

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

	noLaserTrials = valid&(bdata['trialType']==0)

	(possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue)=\
	behavioranalysis.calculate_psychometric(choiceRight, targetFreq, noLaserTrials)

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

	allPlines.append(pline)

	ax = pline.axes
	extraplots.boxoff(ax)
	extraplots.set_ticks_fontsize(ax, fontsize)

	#plt.title(subject+' - '+sessions[0]+'-'+sessions[-1], fontsize=fontsize)
	plt.xlabel('Frequency (kHz)',fontsize=fontsize)
	plt.ylabel('Rightward trials (%)',fontsize=fontsize)
	extraplots.set_ticks_fontsize(plt.gca(),fontsize)
	plt.setp(pline, color='k')
	plt.setp(pcaps, color='k')
def plot_ave_photostim_psycurve_by_trialtype(animal,
                                             sessions,
                                             trialLimit=None):
    '''
    Arguments:
    animal is a string of the animal name you want to plot.
    sessions is a list of strings of the behavior session names you want to plot.
    trialLimit is an optional parameter, should be a list of integers giving the beginning and end of trials numbers you want to plot.
    '''

    FREQCOLORS = [
        colorpalette.TangoPalette['Chameleon3'],
        colorpalette.TangoPalette['ScarletRed1'],
        colorpalette.TangoPalette['SkyBlue2'], 'g', 'm', 'k'
    ]

    allBehavDataThisAnimal = behavioranalysis.load_many_sessions(
        animal, sessions)
    targetFrequency = allBehavDataThisAnimal['targetFrequency']
    choice = allBehavDataThisAnimal['choice']
    valid = allBehavDataThisAnimal['valid'] & (
        choice != allBehavDataThisAnimal.labels['choice']['none'])
    if trialLimit:
        trialSelector = np.zeros(len(valid), dtype=bool)
        trialSelector[trialLimit[0]:trialLimit[1]] = True
    else:
        trialSelector = np.ones(len(valid), dtype=bool)
    valid = (valid & trialSelector)
    #print sum(trialSelector), sum(valid)

    choiceRight = choice == allBehavDataThisAnimal.labels['choice']['right']
    trialType = allBehavDataThisAnimal['trialType']
    stimTypes = [
        allBehavDataThisAnimal.labels['trialType']['no_laser'],
        allBehavDataThisAnimal.labels['trialType']['laser_left'],
        allBehavDataThisAnimal.labels['trialType']['laser_right']
    ]

    stimLabels = ['no_laser', 'laser_left', 'laser_right']

    trialsEachType = behavioranalysis.find_trials_each_type(
        trialType, stimTypes)
    #trialsEachType=np.vstack(( ( (trialType==0) | (trialType==2) ),trialType==1, np.zeros(len(trialType),dtype=bool) )).T  ###This is a hack when percentLaserTrials were sum of both sides and just did one side stim
    #print trialsEachType

    nBlocks = len(stimTypes)
    #thisAnimalPos = inda
    #ax1=plt.subplot(gs[thisAnimalPos,0])
    #ax1=plt.subplot(gs[thisAnimalPos])

    #plt.figure()
    fontsize = 8
    allPline = []
    curveLegends = []
    for stimType in range(nBlocks):
        if np.any(trialsEachType[:, stimType]):
            targetFrequencyThisBlock = targetFrequency[
                trialsEachType[:, stimType]]
            validThisBlock = valid[trialsEachType[:, stimType]]
            #print len(validThisBlock), sum(validThisBlock)
            choiceRightThisBlock = choiceRight[trialsEachType[:, stimType]]
            numValidTrialThisBlock = sum(validThisBlock)
            (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[stimType])
            plt.hold(True)
            plt.setp(pdots, mfc=FREQCOLORS[stimType], mec=FREQCOLORS[stimType])
            plt.hold(True)
            plt.annotate('%s: %s trials' %
                         (stimLabels[stimType], numValidTrialThisBlock),
                         xy=(0.2, 0.35 + stimType / 10.0),
                         fontsize=fontsize,
                         xycoords='axes fraction')
            allPline.append(pline)
            curveLegends.append(stimLabels[stimType])
            #plt.hold(True)
    plt.xlabel('Frequency (kHz)', fontsize=fontsize)
    plt.ylabel('Rightward trials (%)', fontsize=fontsize)
    extraplots.set_ticks_fontsize(plt.gca(), fontsize)
    legend = plt.legend(allPline,
                        curveLegends,
                        loc='best',
                        labelspacing=0.2,
                        prop={'size': 4})
    # Add the legend manually to the current Axes.
    #ax = plt.gca().add_artist(legend)
    plt.gca().add_artist(legend)

    #plt.legend(bbox_to_anchor=(1, 1), bbox_transform=plt.gcf().transFigure)
    #plt.show()
    if len(sessions) == 1:
        plt.title('%s_%s' % (animal, sessions[0]), fontsize=fontsize)
    else:
        plt.title('%s_%sto%s' % (animal, sessions[0], sessions[-1]),
                  fontsize=fontsize)
    plt.show()
    '''
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))
Esempio n. 12
0
nValid = bdata['nValid'][-1]
fractionCorrect = nReward / float(nValid)

targetFrequency = bdata['targetFrequency']
possibleTarget = unique(targetFrequency)
cueFrequency = bdata['cueFrequency']
possibleCue = unique(cueFrequency)

trialsEachCue = behavioranalysis.find_trials_each_type(cueFrequency,
                                                       possibleCue)
choiceRight = bdata['choice'] == (bdata.labels['choice']['right'])

colorEachCond = ['g', 'r']
clf()
hold(True)
for indcue, cueFreq in enumerate(possibleCue):
    (possibleValues,fractionHitsEachValue,ciHitsEachValue,
     nTrialsEachValue,nHitsEachValue)=\
       behavioranalysis.calculate_psychometric(choiceRight,
                                               targetFrequency,
                                               trialsEachCue[:,indcue])
    (pline, pcaps, pbars,
     pdots) = extraplots.plot_psychometric(possibleValues,
                                           fractionHitsEachValue,
                                           ciHitsEachValue)
    setp([pline, pcaps, pbars], color=colorEachCond[indcue])
    setp(pdots, mec=colorEachCond[indcue], mfc=colorEachCond[indcue])
xlabel('Target frequency')
ylabel('% rightward')
show()
Esempio n. 13
0
		valid = bdata['valid']
		choice = bdata['choice']

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

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

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

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

			allPlines.append(pline)

			plt.title(subject+' - '+session, fontsize=fontsize)
			plt.xlabel('Frequency (kHz)',fontsize=fontsize)
			plt.ylabel('Rightward trials (%)',fontsize=fontsize)
			extraplots.set_ticks_fontsize(plt.gca(),fontsize)
			plt.setp(pline, color=colors[indInt])
			plt.setp(pcaps, color=colors[indInt])
			plt.setp(pbars, color=colors[indInt])
			plt.setp(pdots, markerfacecolor=colors[indInt])
			legend = plt.legend(allPlines, possibleInt)
Esempio n. 14
0
        choice = bdata['choice']

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

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

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

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

            allPlines.append(pline)

            plt.title(subject + ' - ' + session, fontsize=fontsize)
            plt.xlabel('Frequency (kHz)', fontsize=fontsize)
            plt.ylabel('Rightward trials (%)', fontsize=fontsize)
            extraplots.set_ticks_fontsize(plt.gca(), fontsize)
            plt.setp(pline, color=colors[indInt])
            plt.setp(pcaps, color=colors[indInt])
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. 16
0
sys.exit()

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

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

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

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

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

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

(pline, pcaps, pbars) = errorbar(possibleValues, 100*fractionHitsEachValue, 
                                 yerr = [100*lowerWhisker, 100*upperWhisker],color='k')
plot(possibleValues, 100*fractionHitsEachValue, 'o',mec='none',mfc='k',ms=8)
setp(pline,lw=2)
axhline(y=50, color = '0.5',ls='--')
ax=gca()
ax.set_xscale('log')
#ax.set_xticks([3000,5000,7000,10000,14000,20000,40000])
    trialsEachType = behavioranalysis.find_trials_each_type(currentBlock,blockTypes)
    
    #print trialsEachType
    nBlocks = len(blockTypes)
    thisAnimalPos = inda
    ax1=plt.subplot(gs[thisAnimalPos])
    fontsize = 12
    allPline = []
    legendLabels = []
    for blockType in range(nBlocks):
        targetFrequencyThisBlock = targetFrequency[trialsEachType[:,blockType]]    
        validThisBlock = valid[trialsEachType[:,blockType]]
        choiceRightThisBlock = choiceRight[trialsEachType[:,blockType]]
        #currentBlockValue = currentBlock[trialsEachBlock[0,block]]
        (possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue)=\
                                                                                                behavioranalysis.calculate_psychometric(choiceRightThisBlock,targetFrequencyThisBlock,validThisBlock)
        (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)
    psycurveDict['possibleFreqs'] = possibleValues
    logPossibleValues = np.log2(possibleValues)
    psycurveDict['logPossibleFreqs'] = logPossibleValues
    psycurveDict['fractionHitsEachBlockEachFreq'] = np.empty((nBlocks,nFreqs))
    psycurveDict['ciHitsEachBlockEachFreq'] = np.empty((nBlocks,2,nFreqs))
    psycurveDict['nTrialsEachBlockEachFreq'] = np.empty((nBlocks,nFreqs))
    psycurveDict['nHitsEachBlockEachFreq'] = np.empty((nBlocks,nFreqs))
    psycurveDict['fitxval'] = np.empty((nBlocks,40))
    psycurveDict['fityval'] = np.empty((nBlocks,40))

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

            psycurveDict['fractionHitsEachBlockEachFreq'][blockType,:] = fractionHitsEachValue
            psycurveDict['ciHitsEachBlockEachFreq'][blockType,:,:] = ciHitsEachValue
            psycurveDict['nTrialsEachBlockEachFreq'][blockType,:] = nTrialsEachValue
            psycurveDict['nHitsEachBlockEachFreq'][blockType,:] = nHitsEachValue
            # -- Fit psycurve and store fitted values -- #
            lowerFreqConstraint = logPossibleValues[0]
            upperFreqConstraint = logPossibleValues[-1]
            constraints = ( 'Uniform({}, {})'.format(lowerFreqConstraint, upperFreqConstraint),
                            'Uniform(0,5)' ,
                            'Uniform(0,1)',
                            'Uniform(0,1)')
            data = np.c_[logPossibleValues,nHitsEachValue,nTrialsEachValue]
            # linear core 'ab': (x-a)/b; logistic sigmoid: 1/(1+np.exp(-(xval-alpha)/beta))
            psyCurveInference = psi.BootstrapInference(data,sample=False, sigmoid='logistic', core='ab',priors=constraints, nafc=1)