Пример #1
0
def generate(plotInfo):
    '''
    FIXME: finish this docstring

    plotList should be a list of dictionaries, each dictionary with the following parameters:
    'type': (string) Type of plot. Accepted values are 'psychometric', 'summary', or 'dynamics' 
    'filename': (string) Output file name.
    THIS IS NOT NECESSARY, THIS METHOD SHOULD NOT CARE: using format "mousename_YYYYMMDD_plotType.svg"
    'data': raw behavior data created by jaratoolbox.loadbehavior.FlexCategBehaviorData()

    Files are saved to settings.IMAGE_PATH
   : '''
    plotData = plotInfo['data']
    if plotInfo['type'] == 'psychometric':
        behavioranalysis.plot_frequency_psycurve(plotData, fontsize=FONTSIZE)
    elif plotInfo['type'] == 'summary':
        freqsToUse = [plotData['lowFreq'][-1], plotData['highFreq'][-1]]
        behavioranalysis.plot_summary(plotData,
                                      fontsize=FONTSIZE,
                                      soundfreq=freqsToUse)
    elif plotInfo['type'] == 'dynamics':
        freqsToUse = [plotData['lowFreq'][-1], plotData['highFreq'][-1]]
        behavioranalysis.plot_dynamics(plotData,
                                       winsize=40,
                                       fontsize=FONTSIZE,
                                       soundfreq=freqsToUse)
    else:
        raise ValueError('Plot type {0} is not valid'.format(plotInfo['Type']))
    outputFile = os.path.join(settings.IMAGE_PATH, plotInfo['filename'])
    print 'Saving plot to {0}'.format(outputFile)
    plt.savefig(outputFile)
Пример #2
0
def Generate(plotList):
#plotList is the list of plot dictionaries as specified above
    #print plotList
    for plot in plotList:
        #get the data from the dictionary
        plotData = plot['data']
        #print plot['type']
        #check what the plot type is and run the coorisponding method
        #basis for method calls taken from "test032_example_read_bdata.py" by Santiago Jaramillo
        type = str(plot['type'])
        if type == "psychometric":
            print "psychometricpsychometricpsychometricpsychometric"
            #As mentioned by Santiago: parameters returned from psychometric plot are not used. Were put in place for improvments that were never finished
            (pline, pcaps, pbars, pdots) = behavioranalysis.plot_frequency_psycurve(plotData,fontsize=14)
        elif type == "summary":
            freqsToUse = [plotData['lowFreq'][-1],plotData['highFreq'][-1]]
            behavioranalysis.plot_summary(plotData,fontsize=14,soundfreq=freqsToUse)
        elif type == "dynamics":
            freqsToUse = [plotData['lowFreq'][-1],plotData['highFreq'][-1]]
            behavioranalysis.plot_dynamics(plotData,winsize=40,fontsize=14,soundfreq=freqsToUse)
        else:
            #ERROR case: plot type invalid
            print "error"
            return False
        #save the plot under the given filepath
        patha = os.path.join(path, plot['filename'])
        #print patha,"patha"
        plt.savefig(patha)
    return True 
Пример #3
0
def Generate(plotList):
    #plotList is the list of plot dictionaries as specified above
    for plot in plotList:
        #get the data from the dictionary
        plotData = plot['data']
        #check what the plot type is and run the coorisponding method
        #basis for method calls taken from "test032_example_read_bdata.py" by Santiago Jaramillo
        if plot['type'] is "psychometric":
            #As mentioned by Santiago: parameters returned from psychometric plot are not used. Were put in place for improvments that were never finished
            (pline, pcaps, pbars,
             pdots) = behavioranalysis.plot_frequency_psycurve(plotData,
                                                               fontsize=14)
        elif plot['type'] is "summary":
            freqsToUse = [plotData['lowFreq'][-1], plotData['highFreq'][-1]]
            behavioranalysis.plot_summary(plotData,
                                          fontsize=14,
                                          soundfreq=freqsToUse)
        elif plot['type'] is "dynamics":
            freqsToUse = [plotData['lowFreq'][-1], plotData['highFreq'][-1]]
            behavioranalysis.plot_dynamics(plotData,
                                           winsize=40,
                                           fontsize=14,
                                           soundfreq=freqsToUse)
        else:
            #ERROR case: plot type invalid
            return False
        #save the plot under the given filepath
        plt.savefig(os.path.join(path, plot['filename']))
    return True
Пример #4
0
def psycurveLog(bdata):
    behavioranalysis.plot_frequency_psycurve(bdata,fontsize=FONTSIZE)
    plt.gcf().set_size_inches([8,6])
    if (tight or (len(subplot.images)>0 and
                    len(subplot.lines)==0 and
                    len(subplot.patches)==0)):
        if scalex:
            subplot.set_xbound(x0, x1)
        if scaley:
            subplot.set_ybound(y0, y1)
        return

    if scalex:
        XL = subplot.xaxis.get_major_locator().view_limits(x0, x1)
        subplot.set_xbound(XL)
    if scaley:
        YL = subplot.yaxis.get_major_locator().view_limits(y0, y1)
        subplot.set_ybound(YL)


(bdataObjs, bdataSoundTypes) = soundtypes.load_behavior_sessions_sound_type(subject, [session]) 

#Not because we are plotting small values...
# bdataObjs[0]['targetFrequency'] = bdataObjs[0]['targetFrequency'] * 1e3

plt.clf()
for indbdata, bdata in enumerate(bdataObjs):
    ax = plt.subplot(1, 2, indbdata+1)
    (pline, pcaps, pbars, pdots) = behavioranalysis.plot_frequency_psycurve(bdata)
    loose_autoscale_view(ax, 0.05, scaley=False)
    # plt.margins(x=0.1, y=0)
    # ax.autoscale(axis='x', tight=True)
plt.show()
Пример #6
0
def sound_type_behavior_summary(subjects,
                                sessions,
                                output_dir,
                                trialslim=None):
    '''
    Nick 2016-05-20

    Plots a report for behavior data that has multiple sound types. Will plot a psycurve for each sound type,
    and then a dynamics plot with the different sound types as different colored lines

    Args:
    subjects (list of str): The animals to plot (example: ['amod002', 'amod003'])
    sessions (list of str): The sessions to plot for each animal (example: ['20160529a'])
    output_dir (str): FIXME currently unused, for saving the report
    trialslim (list): upper and lower trial number to plot dynamics

    '''

    if isinstance(subjects, str):
        subjects = [subjects]
    if isinstance(sessions, str):
        sessions = [sessions]
    nSessions = len(sessions)
    nAnimals = len(subjects)

    for indAnimal, animalName in enumerate(subjects):
        for indSession, session in enumerate(sessions):
            #The sound types separated into different bdata objects
            try:
                (bdataObjs,
                 bdataSoundTypes) = load_behavior_sessions_sound_type(
                     animalName, [session])
            except KeyError:  #Will happen if the bdata does not have 'soundType' key'
                print "ERROR: Data for {} - {} may not be in the correct format".format(
                    animalName, session)
                break

            #All the bdata together for plotting the dynamics
            allBehavData = behavioranalysis.load_many_sessions(
                animalName, [session])
            nSoundTypes = len(
                bdataSoundTypes
            )  #This should hopefully be the same for all the animals being plotted

            #Keeps track of the min and max for each sound type for plotting dynamics
            allFreqsToUse = []

            #The y inds for plotting
            yInd = indAnimal + indSession + indAnimal * (nSessions - 1)

            for indSoundType, soundType in enumerate(bdataSoundTypes):
                plt.subplot2grid((nAnimals * nSessions, nSoundTypes + 2),
                                 (yInd, indSoundType))
                thisBehavData = bdataObjs[indSoundType]

                #Find min and max freqs for plotting
                possibleFreq = np.unique(thisBehavData['targetFrequency'])
                freqsToUse = [min(possibleFreq), max(possibleFreq)]
                allFreqsToUse.extend(freqsToUse)

                #Plot psycurves or summaries
                if any(thisBehavData['psycurveMode']):
                    (pline, pcaps, pbars,
                     pdots) = behavioranalysis.plot_frequency_psycurve(
                         thisBehavData)
                    thisColor = FREQCOLORS[indSoundType * 2]
                    plt.setp(pline, color=thisColor)
                    plt.setp(pcaps, color=thisColor)
                    plt.setp(pbars, color=thisColor)
                    plt.setp(pdots, markerfacecolor=thisColor)
                    plt.title(soundType)
                    if not indSoundType == 0:
                        plt.ylabel('')
                else:
                    thisBehavData.find_trials_each_block()
                    behavioranalysis.plot_summary(thisBehavData,
                                                  fontsize=8,
                                                  soundfreq=freqsToUse)
                    plt.title(soundType)

            #Plot the dynamics for all the sound types
            plt.subplot2grid((nAnimals * nSessions, nSoundTypes + 2),
                             (yInd, nSoundTypes),
                             colspan=2)
            behavioranalysis.plot_dynamics(allBehavData,
                                           soundfreq=allFreqsToUse)
            plt.ylabel('')
            if trialslim:
                plt.xlim(trialslim)
            plt.title('{}, {}'.format(animalName, session))
            plt.subplots_adjust(hspace=0.7)
subject = 'adap021'
session = '20160310a'  # This is the date formatted as YYYYMMDD and one more character (usually 'a')

# -- Find the data filename and load the data into a data object (similar to a Python dict) --
behavFile = loadbehavior.path_to_behavior_data(subject, EXPERIMENTER, paradigm,
                                               session)
behavData = loadbehavior.FlexCategBehaviorData(behavFile, readmode='full')

# -- Calculate average performance --
nValidTrials = behavData['nValid'][-1]
nRewardedTrials = behavData['nRewarded'][-1]
print 'Average performance: {:0.1%}'.format(
    float(nRewardedTrials) / nValidTrials)

# -- Plot psychometric curve --
plt.clf()
(pline, pcaps, pbars,
 pdots) = behavioranalysis.plot_frequency_psycurve(behavData, fontsize=14)
plt.show()
'''
plt.clf()
freqsToUse = [behavData['lowFreq'][-1],behavData['highFreq'][-1]]
behavioranalysis.plot_summary(behavData,fontsize=14,soundfreq=freqsToUse)
plt.show()

plt.clf()
freqsToUse = [behavData['lowFreq'][-1],behavData['highFreq'][-1]]
behavioranalysis.plot_dynamics(behavData,winsize=40,fontsize=14,soundfreq=freqsToUse)
plt.show()
'''
paradigm = '2afc'

subject = 'adap021'
session = '20160310a' # This is the date formatted as YYYYMMDD and one more character (usually 'a')

# -- Find the data filename and load the data into a data object (similar to a Python dict) --
behavFile = loadbehavior.path_to_behavior_data(subject,EXPERIMENTER,paradigm,session)
behavData = loadbehavior.FlexCategBehaviorData(behavFile,readmode='full')

# -- Calculate average performance --
nValidTrials = behavData['nValid'][-1]
nRewardedTrials = behavData['nRewarded'][-1]
print 'Average performance: {:0.1%}'.format(float(nRewardedTrials)/nValidTrials)

# -- Plot psychometric curve --
plt.clf()
(pline, pcaps, pbars, pdots) = behavioranalysis.plot_frequency_psycurve(behavData,fontsize=14)
plt.show()

'''
plt.clf()
freqsToUse = [behavData['lowFreq'][-1],behavData['highFreq'][-1]]
behavioranalysis.plot_summary(behavData,fontsize=14,soundfreq=freqsToUse)
plt.show()

plt.clf()
freqsToUse = [behavData['lowFreq'][-1],behavData['highFreq'][-1]]
behavioranalysis.plot_dynamics(behavData,winsize=40,fontsize=14,soundfreq=freqsToUse)
plt.show()
'''
Пример #9
0
def sound_type_behavior_summary(subjects, sessions, output_dir, trialslim=None):

    '''
    Nick 2016-05-20

    Plots a report for behavior data that has multiple sound types. Will plot a psycurve for each sound type,
    and then a dynamics plot with the different sound types as different colored lines

    Args:
    subjects (list of str): The animals to plot (example: ['amod002', 'amod003'])
    sessions (list of str): The sessions to plot for each animal (example: ['20160529a'])
    output_dir (str): FIXME currently unused, for saving the report
    trialslim (list): upper and lower trial number to plot dynamics

    '''

    if isinstance(subjects,str):
        subjects = [subjects]
    if isinstance(sessions,str):
        sessions = [sessions]
    nSessions = len(sessions)
    nAnimals = len(subjects)

    for indAnimal, animalName in enumerate(subjects):
        for indSession, session in enumerate(sessions):
            #The sound types separated into different bdata objects
            try:
                (bdataObjs, bdataSoundTypes) = load_behavior_sessions_sound_type(animalName,
                                                                                 [session])
            except KeyError: #Will happen if the bdata does not have 'soundType' key'
                print "ERROR: Data for {} - {} may not be in the correct format".format(animalName, session)
                break

            #All the bdata together for plotting the dynamics
            allBehavData = behavioranalysis.load_many_sessions(animalName, [session])
            nSoundTypes = len(bdataSoundTypes) #This should hopefully be the same for all the animals being plotted

            #Keeps track of the min and max for each sound type for plotting dynamics
            allFreqsToUse = []

            #The y inds for plotting
            yInd = indAnimal + indSession + indAnimal*(nSessions-1)

            for indSoundType, soundType in enumerate(bdataSoundTypes):
                plt.subplot2grid((nAnimals*nSessions, nSoundTypes+2), (yInd, indSoundType))
                thisBehavData = bdataObjs[indSoundType]

                #Find min and max freqs for plotting
                possibleFreq = np.unique(thisBehavData['targetFrequency'])
                freqsToUse = [min(possibleFreq), max(possibleFreq)]
                allFreqsToUse.extend(freqsToUse)

                #Plot psycurves or summaries
                if any(thisBehavData['psycurveMode']):
                    (pline, pcaps, pbars, pdots) = behavioranalysis.plot_frequency_psycurve(thisBehavData)
                    thisColor = FREQCOLORS[indSoundType*2]
                    plt.setp(pline, color=thisColor)
                    plt.setp(pcaps, color=thisColor)
                    plt.setp(pbars, color=thisColor)
                    plt.setp(pdots, markerfacecolor=thisColor)
                    plt.title(soundType)
                    if not indSoundType==0:
                        plt.ylabel('')
                else:
                    thisBehavData.find_trials_each_block()
                    behavioranalysis.plot_summary(thisBehavData,fontsize=8,soundfreq=freqsToUse)
                    plt.title(soundType)

            #Plot the dynamics for all the sound types
            plt.subplot2grid((nAnimals*nSessions, nSoundTypes+2), (yInd, nSoundTypes), colspan=2)
            behavioranalysis.plot_dynamics(allBehavData, soundfreq = allFreqsToUse)
            plt.ylabel('')
            if trialslim:
                plt.xlim(trialslim)
            plt.title('{}, {}'.format(animalName, session))
            plt.subplots_adjust(hspace = 0.7)