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
def load_behavior_sessions_sound_type(animal, sessions): ''' Load many sessions (or only one) and then divide up into several bdata objects based on the type of sound that was presented. Args animal (str): The name of the animal sessions (list of strings): Sessions to load Returns dataObjs (list of jaratoolbox.behavioranalysis.LoadBehaviorData objects): Behavior data objects for each sound type dataSoundTypes (list of strings): The sound type that corresponds to each of the data objects ''' bdata = behavioranalysis.load_many_sessions(animal, sessions) soundTypes = [ bdata.labels['soundType'][x] for x in np.unique(bdata['soundType']) ] dataObjs = [] dataSoundTypes = {} for indType, thisType in enumerate(soundTypes): bdataThisType = behavioranalysis.load_many_sessions(animal, sessions) #The inds where this kind of sound was presented boolThisType = bdataThisType['soundType'] == bdataThisType.labels[ 'soundType'][thisType] #All other inds notBoolThisType = np.logical_not(boolThisType) notIndsThisType = np.flatnonzero(notBoolThisType) #Remove all trials where this type was not presented bdataThisType.remove_trials(notIndsThisType) #Save out the bdata object and the sound type dataObjs.append(bdataThisType) dataSoundTypes.update({thisType: indType}) return (dataObjs, dataSoundTypes)
def load_behavior_sessions_sound_type(animal, sessions): ''' Load many sessions (or only one) and then divide up into several bdata objects based on the type of sound that was presented. Args animal (str): The name of the animal sessions (list of strings): Sessions to load Returns dataObjs (list of jaratoolbox.behavioranalysis.LoadBehaviorData objects): Behavior data objects for each sound type dataSoundTypes (list of strings): The sound type that corresponds to each of the data objects ''' bdata = behavioranalysis.load_many_sessions(animal, sessions) soundTypes = [bdata.labels['soundType'][x] for x in np.unique(bdata['soundType'])] dataObjs = [] dataSoundTypes = {} for indType, thisType in enumerate(soundTypes): bdataThisType = behavioranalysis.load_many_sessions(animal, sessions) #The inds where this kind of sound was presented boolThisType = bdataThisType['soundType']==bdataThisType.labels['soundType'][thisType] #All other inds notBoolThisType = np.logical_not(boolThisType) notIndsThisType = np.flatnonzero(notBoolThisType) #Remove all trials where this type was not presented bdataThisType.remove_trials(notIndsThisType) #Save out the bdata object and the sound type dataObjs.append(bdataThisType) dataSoundTypes.update({thisType:indType}) return (dataObjs, dataSoundTypes)
def band_psychometric(animal, sessions, trialTypes=['currentSNR']): ''' Produces the number of valid trials and number of trials where animal went to the right for each condition. Can sort by up to three parameters. Input: animal = name of animal whose behaviour is to be used (string) sessions = file names of sessions to be used (list of strings) trialTypes = names of parameters in behavData to be used for sorting trials (list of strings, up to 3 parameters) Output: validPerCond = 1D to 3D array (depending on number of parameters given) giving number of valid trials for each condition rightPerCond = like validPerCond, only trials where animal went to the right possibleParams = possible values each parameter takes ''' behavData = behavioranalysis.load_many_sessions(animal, sessions) firstSort = behavData[trialTypes[0]] possibleFirstSort = np.unique(firstSort) possibleSecondSort = None possibleThirdSort = None if len(trialTypes) > 1: secondSort = behavData[trialTypes[1]] possibleSecondSort = np.unique(secondSort) if len(trialTypes) > 2: thirdSort = behavData[trialTypes[2]] possibleThirdSort = np.unique(thirdSort) valid = behavData['valid'].astype(bool) rightChoice = behavData['choice']==behavData.labels['choice']['right'] if len(trialTypes) == 3: trialsEachComb = find_trials_each_combination_three_params(firstSort, possibleFirstSort, secondSort, possibleSecondSort, thirdSort, possibleThirdSort) elif len(trialTypes) == 2: trialsEachComb = behavioranalysis.find_trials_each_combination(firstSort, possibleFirstSort, secondSort, possibleSecondSort) elif len(trialTypes) == 1: trialsEachComb = behavioranalysis.find_trials_each_type(firstSort, possibleFirstSort) validPerCond, rightPerCond = compute_psychometric_inputs(valid, rightChoice, trialsEachComb) possibleParams = [possibleFirstSort, possibleSecondSort, possibleThirdSort] possibleParams = [param for param in possibleParams if param is not None] return validPerCond, rightPerCond, possibleParams
dataDir = os.path.join(settings.FIGURES_DATA_PATH, figName) mouseDicts = [studyparams.unimplanted_PVCHR2, studyparams.unimplanted_PVARCHT, studyparams.unimplanted_SOMARCHT, studyparams.unimplanted_wt] percentToneDetectEachSNR = [] percentCorrectEachBand = [] biasEachBand = [] for miceThisType in mouseDicts: percentToneDetectEachSNRThisType = None percentCorrectEachBandThisType = None biasEachBandThisType = None for indMouse, mouse in enumerate(miceThisType.keys()): behavData = behavioranalysis.load_many_sessions(mouse, miceThisType[mouse]) numMice = len(miceThisType.keys()) bandEachTrial = behavData['currentBand'] noiseAmpEachTrial = behavData['currentNoiseAmp'] SNReachTrial = behavData['currentSNR'] valid = behavData['valid'].astype(bool) correct = behavData['outcome'] == behavData.labels['outcome']['correct'] rightChoice = behavData['choice'] == behavData.labels['choice']['right'] leftChoice = behavData['choice'] == behavData.labels['choice']['left'] if 'toneSide' in behavData.keys(): if behavData['toneSide'][-1] == behavData.labels['toneSide']['right']: toneChoice = rightChoice noiseChoice = leftChoice
confInt = np.array( proportion_confint(nCorrect, nValid, method='wilson')) return fractionCorrect, confInt else: return fractionCorrect plt.clf() allSaline = [] allMus = [] for animal in animalsToUse: musSessions = muscimolSessions.animals[animal]['muscimol'] salSessions = muscimolSessions.animals[animal]['saline'] musBdata = behavioranalysis.load_many_sessions([animal], musSessions) salBdata = behavioranalysis.load_many_sessions([animal], salSessions) musPercentCorrect = 100 * frac_correct(musBdata) salPercentCorrect = 100 * frac_correct(salBdata) allSaline.append(salPercentCorrect) allMus.append(musPercentCorrect) plt.plot([0, 1], [salPercentCorrect, musPercentCorrect], '-o', color=animalColor[animal], mec=animalColor[animal], ms=8, lw=1) plt.hold(1)
from jaratoolbox.behavioranalysis import load_many_sessions from statsmodels.stats.proportion import proportion_confint #Used to compute confidence interval for the error bars. from scipy.stats import fisher_exact import numpy as np from pylab import * animalNames = 'hm4d004' preSessions = ['20140826a'] postSessions = ['20140825a'] preInds = range(len(preSessions)) postInds = range(len(preSessions), len(postSessions) + len(preSessions)) sessions = preSessions + postSessions data = load_many_sessions(animalNames, sessions) validTrials = data['valid'] == 1 validEachSession = [] rewardedEachSession = [] for session in np.unique(data['sessionID']): indsThisSession = data['sessionID'] == session nValidThisSession = max(data['nValid'][indsThisSession]) nRewardedThisSession = max(data['nRewarded'][indsThisSession]) validEachSession.append(nValidThisSession) rewardedEachSession.append(nRewardedThisSession) validEachSession = np.array(validEachSession) rewardedEachSession = np.array(rewardedEachSession) validEachPre = validEachSession[preInds] validEachPost = validEachSession[postInds] rewardedEachPre = rewardedEachSession[preInds] rewardedEachPost = rewardedEachSession[postInds]
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
figName = 'figure_ac_inactivation' # dataDir = os.path.join(settings.FIGURES_DATA_PATH, studyparams.STUDY_NAME, figName) dataDir = os.path.join(settings.FIGURES_DATA_PATH, figName) PV_CHR2_MICE = studyparams.PV_CHR2_MICE laserAccuracy = None controlAccuracy = None laserBias = None controlBias = None for indMouse, mouse in enumerate(PV_CHR2_MICE): laserSessions = studyparams.miceDict[mouse]['3mW laser'] laserBehavData = behavioranalysis.load_many_sessions(mouse, laserSessions) numLasers = np.unique(laserBehavData['laserSide']) numBands = np.unique(laserBehavData['currentBand']) trialsEachCond = behavioranalysis.find_trials_each_combination( laserBehavData['laserSide'], numLasers, laserBehavData['currentBand'], numBands) # -- compute accuracies and bias for each bandwidth -- for indBand in range(len(numBands)): trialsEachLaser = trialsEachCond[:, :, indBand] # -- sort trials by laser presentation, compute accuracy as percent correct trials out of all valid trials -- valid = laserBehavData['valid'].astype(bool)
def load_subject(subject, muscimolSessions, salineSessions): muscimolData = behavioranalysis.load_many_sessions(subject, muscimolSessions) salineData = behavioranalysis.load_many_sessions(subject, salineSessions) return muscimolData, salineData
#sessions = ['20170624a'] #0.25 mW, lasers in #sessions = ['20170626a', '20170627a'] #0.25 mW, lasers on side #sessions = ['20170628a'] #0.1 mW, lasers in #sessions = ['20170629a'] #0.1 mW, lasers on side sessions = ['20170630a'] #for amod012: I:0.3, II:2.0; for amod013, I:0.3, II:1.5, lasers on side if len(sys.argv)>1: sessions = sys.argv[1:] #sessions = input("Enter sessions (in a list of strings ['','']) to check behavior performance:") #plt.figure() inds = 0 plt.figure() for indSubject, subject in enumerate(subjects): #plt.subplot(len(subjects), 1, indSubject+1) allPlines = [] bdata = behavioranalysis.load_many_sessions(subjects, sessions, 'simple2afc') ''' for indSession, session in enumerate(sessions): behavFile = loadbehavior.path_to_behavior_data(subject,'2afc',session) behavData = loadbehavior.BehaviorData(behavFile) #bdata = behavioranalysis.load_many_sessions(subject, [session]) #copied from load_many_sessions if inds==0: allBehavData = behavData # FIXME: Should it be .copy()? nTrials = len(behavData['outcome']) # FIXME: what if this key does not exist? allBehavData['sessionID'] = np.zeros(nTrials,dtype='i2') allBehavData['animalID'] = np.zeros(nTrials,dtype='i1') else: for key,val in behavData.iteritems(): if not allBehavData.has_key(key):
] for animal in sessions.keys() } muscimolSessions = { animal: [ session for session, mus in zip(sessions[animal], muscimol[animal]) if mus == 1 ] for animal in sessions.keys() } for subject in ['amod006', 'amod007', 'amod008', 'amod009']: salineThisSubject = salineSessions[subject] muscimolThisSubject = muscimolSessions[subject] bdata = behavioranalysis.load_many_sessions(subject, salineThisSubject) dataFn = 'tones_psychometric_{}_saline.npz'.format(subject) print 'Saving: {}'.format(dataFn) dataPath = os.path.join(saveDir, dataFn) calculate_psychometric_and_estimate(bdata, dataPath) # Muscimol Data bdata = behavioranalysis.load_many_sessions(subject, muscimolThisSubject) dataFn = 'tones_psychometric_{}_muscimol.npz'.format(subject) print 'Saving: {}'.format(dataFn) dataPath = os.path.join(saveDir, dataFn) calculate_psychometric_and_estimate(bdata, dataPath) # salDataObjs, salSoundTypes = soundtypes.load_behavior_sessions_sound_type(subject, salineThisSubject) # for soundType, stInd in salSoundTypes.iteritems(): # dataFn ='psychometric_{}_{}_saline.npz'.format(subject, soundType)
animalNames = ['test012'] animalNames = ['test020'] #sessions = ['20150110a'] # Pre-lesion sessions = ['20150106a','20150108a','20150109a','20150110a'] # Pre-lesion sessions = ['20150115a','20150116a','20150117a','20150118a'] # Post-lesion #sessions = ['20150119a'] # Post-lesion clf() for ind, subject in enumerate(animalNames):#enumerate(subjects): #fname=loadbehavior.path_to_behavior_data(subject,'santiago','2afc',session) try: #bdata=loadbehavior.BehaviorData(fname) bdata = behavioranalysis.load_many_sessions(animalNames,sessions) except IOError: continue from jaratoolbox import settings targetFrequency=bdata['targetFrequency'] valid=bdata['valid'] choice=bdata['choice'] intensities=bdata['targetIntensity'] choiceRight = choice==bdata.labels['choice']['right'] ########## FIX ME : HARDCODED! possibleFreq = np.unique(targetFrequency) nFreq = len(possibleFreq) fractionRightEachFreq=np.zeros(nFreq) confLimitsEachFreq=np.zeros([2, nFreq]) #Upper and lower confidence limitsi
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)
figName = 'figure_inhibitory_inactivation' # dataDir = os.path.join(settings.FIGURES_DATA_PATH, studyparams.STUDY_NAME, figName) dataDir = os.path.join(settings.FIGURES_DATA_PATH, figName) examples = [{'subject': 'band065', 'sessions': '10mW laser', 'bandwidth': 0.25}, # example SOM-ArchT psychometric {'subject': 'band081', 'sessions': '10mW laser', 'bandwidth': 0.25}] # example PV-ArchT psychometric for example in examples: sessions = studyparams.miceDict[example['subject']][example['sessions']] behavData = behavioranalysis.load_many_sessions(example['subject'], sessions) numLasers = np.unique(behavData['laserSide']) numBands = np.unique(behavData['currentBand']) numSNRs = np.unique(behavData['currentSNR']) trialsEachCond = behavioranalysis.find_trials_each_combination(behavData['laserSide'], numLasers, behavData['currentBand'], numBands) trialsEachSNR = behavioranalysis.find_trials_each_type(behavData['currentSNR'], numSNRs) trialsEachCond3Params = np.zeros((len(behavData['laserSide']), len(numLasers), len(numBands), len(numSNRs)), dtype=bool) for ind in range(len(numSNRs)): trialsEachCond3Params[:, :, :, ind] = trialsEachCond & trialsEachSNR[:, ind][:, np.newaxis, np.newaxis] valid = behavData['valid'].astype(bool)
#subjects = ['gosi002', 'gosi006'] subjects = ['gosi013', 'adap051'] #subjects = ['amod011', 'amod012', 'amod013'] # sessions = ['20160711a', '20160712a', '20160713a', '20160714a', '20160715a', '20160716a', '20160718a','20160719a', '20160720a', '20160721a', '20160722a'] #sessions = ['20170504a'] #sessions = ['20170510a'] sessions = ['20170608a'] if len(sys.argv)>1: sessions = sys.argv[1:] #sessions = input("Enter sessions (in a list of strings ['','']) to check behavior performance:") plt.figure() for indSubject, subject in enumerate(subjects): for indSession, session in enumerate(sessions): plt.subplot(len(subjects), 1, indSubject+1) bdata = behavioranalysis.load_many_sessions(subject, [session]) targetIntensity = bdata['targetIntensity'] 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):
def plot_ave_choice_n_reaction_time(animal, session, trialLimit=None): ''' Arguments: animal is a string of the animal name you want to plot. session is a list of behavior session names(strings) 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, session) #This is lazy, should use loadbehavior module instead 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'] timeCenterOut = allBehavDataThisAnimal['timeCenterOut'] if np.all(np.isnan(timeCenterOut)): timeCenterOut = calculate_center_out_times(animal, session) else: reactionTime = timeCenterOut - allBehavDataThisAnimal[ 'timeTarget'] - 0.1 # Time it takes to initiate action after sound choiceTime = allBehavDataThisAnimal[ 'timeSideIn'] - timeCenterOut # Time it takes to get to side port after leaving center port; value is NaN in invalid trials timeDf = pd.DataFrame() timeDf['valid'] = valid timeDf['choice'] = choice #For choice:0=left;1=right;2=none timeDf['type_of_stim'] = allBehavDataThisAnimal[ 'trialType'] #0=no_laser;1=left_laser;2=right_laser timeDf['reactionTime'] = reactionTime timeDf['choiceTime'] = choiceTime timeDf['choiceTime'][np.isnan(choiceTime)] = 0 import seaborn as sns g = sns.FacetGrid(timeDf, row='choice', col='type_of_stim', margin_titles=True) g.map(dot_plot_w_mean_std_by_category, 'reactionTime', 'choiceTime').set(xlim=(0.5, 2.5), ylim=(-0.05, 1.05), xticks=[1, 2], xticklabels=['Reaction time', 'Choice time'], xlabel='', ylabel='Time (sec)') print timeDf.head(20) plt.suptitle('%s_%s reaction and choice time plot' % (animal, session)) #if len(sessions)==1: # plt.suptitle('%s_%s reaction and choice time plot' %(animal,sessions[0]),fontsize=8) #else: # plt.suptitle('%s_%sto%s reaction and choice time plot'%(animal,sessions[0],sessions[-1]),fontsize=8) plt.tight_layout() plt.show()
resultsDict = {} # -- Generate data for each mouse -- # for mouse in animalName: resultsDict[mouse + 'leftHemiStim'] = [] resultsDict[mouse + 'leftHemiStimSessions'] = [] resultsDict[mouse + 'rightHemiStim'] = [] resultsDict[mouse + 'rightHemiStimSessions'] = [] # -- Calculate % contra choice change for each session and store data for left and right hemisphere photostim sessions separately -- # for hemi, sessions in sessionsDict.items(): for session in sessions: session = session + 'a' stimHemi = hemi bdata = behavioranalysis.load_many_sessions(mouse, [session]) trialType = bdata['trialType'] stimTypes = [ bdata.labels['trialType']['no_laser'], bdata.labels['trialType']['laser_left'], bdata.labels['trialType']['laser_right'] ] stimLabels = ['no_laser', 'laser_left', 'laser_right'] trialsEachType = behavioranalysis.find_trials_each_type( trialType, stimTypes) choice = bdata['choice'] valid = bdata['valid'] & (choice != bdata.labels['choice']['none']) if stimHemi == 'left_astr': #This is a session where the left hemisphere is stimulated validTrialsControl = valid[ trialsEachType[:, stimLabels.index('no_laser')]]
#sessions = ['20180916a','20180918a','20180919a','20180920a','20180921a'] #paradigm = '2afc' #subject = 'bili004' #sessions = ['20181105a','20181106a'] #paradigm = '2afc' #subject = 'bili006' #sessions = ['20181025a','20181026a','20181027a','20181028a','20181029a','20181030a','20181031a','20181101a','20181102a'] #paradigm = '2afc' #subject = 'bili007' #sessions = ['20181024a','20181025a','20181026','20181027a','20181028a'] #paradigm = '2afc' bdata = behavioranalysis.load_many_sessions(subject, sessions, paradigm) Color = [0, 0.50, 1] correct = bdata['outcome'] == bdata.labels['outcome']['correct'] targetPercentage = bdata['targetFrequency'] choiceRight = bdata['choice'] == bdata.labels['choice']['right'] valid = bdata['valid'].astype(bool) & (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.setp([pline, pcaps, pbars, pdots], color=Color)
from jaratoolbox.behavioranalysis import load_many_sessions from statsmodels.stats.proportion import proportion_confint #Used to compute confidence interval for the error bars. from scipy.stats import fisher_exact import numpy as np from pylab import * animalNames = 'hm4d004' preSessions = ['20140826a'] postSessions =['20140825a'] preInds = range(len(preSessions)) postInds = range(len(preSessions), len(postSessions)+len(preSessions)) sessions = preSessions+postSessions data = load_many_sessions(animalNames, sessions) validTrials = data['valid']==1 validEachSession=[] rewardedEachSession=[] for session in np.unique(data['sessionID']): indsThisSession = data['sessionID']==session nValidThisSession = max(data['nValid'][indsThisSession]) nRewardedThisSession = max(data['nRewarded'][indsThisSession]) validEachSession.append(nValidThisSession) rewardedEachSession.append(nRewardedThisSession) validEachSession = np.array(validEachSession) rewardedEachSession = np.array(rewardedEachSession) validEachPre = validEachSession[preInds] validEachPost = validEachSession[postInds] rewardedEachPre = rewardedEachSession[preInds] rewardedEachPost = rewardedEachSession[postInds]
#plt.style.use(['seaborn-white', 'seaborn-talk']) import matplotlib as mpl FREQCOLORS = [ colorpalette.TangoPalette['Chameleon3'], colorpalette.TangoPalette['ScarletRed1'], colorpalette.TangoPalette['SkyBlue2'], 'g', 'm', 'k' ] animal = 'd1pi015' sessions = ['20160829a'] #behavFile = loadbehavior.path_to_behavior_data(subject,'2afc',session) #bdata = loadbehavior.BehaviorData(behavFile) bdata = behavioranalysis.load_many_sessions(animal, sessions) targetFrequency = bdata['targetFrequency'] choice = bdata['choice'] valid = bdata['valid'] & (choice != bdata.labels['choice']['none']) choiceRight = choice == bdata.labels['choice']['right'] trialType = bdata['trialType'] stimTypes = [ bdata.labels['trialType']['no_laser'], bdata.labels['trialType']['laser_left'], bdata.labels['trialType']['laser_right'] ] stimLabels = ['no_laser', 'laser_left', 'laser_right'] trialsEachType = behavioranalysis.find_trials_each_type(trialType, stimTypes) nStimTypes = len(stimTypes)
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)
import os from jaratoolbox import settings from jaratoolbox import behavioranalysis from jaratoolbox import extraplots muscimolSessions = ['20160413a', '20160415a', '20160417a'] salineSessions = ['20160412a', '20160414a', '20160416a'] animal = 'amod002' muscimolData = behavioranalysis.load_many_sessions(animal, muscimolSessions) salineData = behavioranalysis.load_many_sessions(animal, salineSessions)
import pdb performance = [] upper = [] lower = [] for inds in range(len(possibleSNRs)): #pdb.set_trace() CIthisSNR = np.array(proportion_confint(rightPerSNR[inds], validPerSNR[inds], method = 'wilson')) performance.append(100.0*rightPerSNR[inds]/validPerSNR[inds]) upper.append(100.0*CIthisSNR[1]-performance[-1]) lower.append(performance[-1]-100.0*CIthisSNR[0]) plt.plot(np.arange(len(possibleSNRs)), performance, linestyle, marker='o', color=colour, lw=3, ms=10) plt.errorbar(np.arange(len(possibleSNRs)), performance, yerr = [lower, upper],color=colour) if ylabel: plt.ylabel("% rightward", fontsize=16) if xlabel: plt.xlabel('SNR (dB)', fontsize=16) plt.xticks(np.arange(len(possibleSNRs)), possibleSNRs) plt.ylim((0,100)) PVAnimals = ['band017', 'band020'] laserPVSessions = ['20170422a','20170423a','20170424a','20170426a','20170427a','20170428a','20170429a','20170430a','20170501a','20170502a','20170503a','20170504a','20170505a','20170506a','20170507a','20170508a'] bdata = behavioranalysis.load_many_sessions('band017', laserPVSessions) valid, right, pos = bb.band_psychometric('band017', laserPVSessions, trialTypes = ['currentSNR', 'currentBand', 'laserSide']) colours = ['b','r','k'] linestyle = ['-','--'] for band in range(len(pos[1])): for las in range(len(pos[2])): plot_psychometric(valid[:,band,las], right[:,band,las], pos[0], colour = colours[band], linestyle=linestyle[las]) plt.show()
#sessions = ['20190318a','20190320a'] # Right laser #sessions = ['20190408a','20190410a'] # Extra Left laser #sessions = ['20190409a','20190411a'] # Extra Right laser paradigm = '2afc' laserColor = [0, 0.75, 0] plt.clf() fontsize = 12 for inds, subject in enumerate(subjects): #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)
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() '''
nAnimals = len(animalsToUse) nSessions = 4 nCond = 2 conditions = ['saline', 'muscimol'] #0 for saline, 1 for muscimol dataMat = np.zeros((nAnimals, nSessions, nCond)) subjects = [] #For saving for indAnimal, animalName in enumerate(animalsToUse): animalSessionDict = animals[animalName] subjects.append(animalName) for indCond in [0, 1]: sessions = animalSessionDict[conditions[indCond]] for indSession, session in enumerate(sessions): bdata = behavioranalysis.load_many_sessions(animalName, [session]) nValid = num_valid(bdata) dataMat[indAnimal, indSession, indCond] = nValid ax2 = plt.subplot(111) #dataMat(subject, session, condition) ind = np.arange(len(subjects)) width = 0.35 condColors = ['k', 'r'] shiftAmt = width * 0.05 # shiftAmt = 0 fontSizeLabels = 12 fontSizeTicks = 10
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) animalSessionDict = animals[animalName] for muscimolConc in ['muscimol00625', 'muscimol0125', 'muscimol0250']: musSessions = animalSessionDict[muscimolConc] musBdata = behavioranalysis.load_many_sessions([animalName], musSessions) musFilename = '{}_{}_psychometric.npz'.format(animalName, muscimolConc) musFullPath = os.path.join(outputDir, musFilename) calculate_psychometric_and_estimate(musBdata, musFullPath) # salBdata = behavioranalysis.load_many_sessions([animalName], salSessions) # salSessions = animalSessionDict['saline'] # salFilename = '{}_saline_psychometric.npz'.format(animalName) # salFullPath = os.path.join(outputDir,salFilename) # calculate_psychometric_and_estimate(salBdata, salFullPath)
FREQCOLORS = [colorpalette.TangoPalette['Chameleon3'], colorpalette.TangoPalette['ScarletRed1'], colorpalette.TangoPalette['SkyBlue2'] , 'g', 'm', 'k'] #if len(sys.argv)>1: #sessions = sys.argv[1:] nSessions = len(sessions) nAnimals = len(subjects) gs = gridspec.GridSpec(nAnimals, 1)#changed from nAnimals to plot one animal with multiple sessions gs.update(hspace=0.5,wspace=0.4) plt.clf() for inda, thisAnimal in enumerate(subjects): allBehavDataThisAnimal = behavioranalysis.load_many_sessions(thisAnimal,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']] blockLabels = ['same_reward','more_left', 'more_right'] trialsEachType = behavioranalysis.find_trials_each_type(currentBlock,blockTypes) #print trialsEachType nBlocks = len(blockTypes) thisAnimalPos = inda ax1=plt.subplot(gs[thisAnimalPos]) fontsize = 12
plt.ylabel("% rightward", fontsize=16) if xlabel: plt.xlabel('SNR (dB)', fontsize=16) plt.xticks(np.arange(len(possibleSNRs)), possibleSNRs) plt.ylim((0, 100)) PVAnimals = ['band017', 'band020'] laserPVSessions = [ '20170422a', '20170423a', '20170424a', '20170426a', '20170427a', '20170428a', '20170429a', '20170430a', '20170501a', '20170502a', '20170503a', '20170504a', '20170505a', '20170506a', '20170507a', '20170508a' ] bdata = behavioranalysis.load_many_sessions('band017', laserPVSessions) valid, right, pos = bb.band_psychometric( 'band017', laserPVSessions, trialTypes=['currentSNR', 'currentBand', 'laserSide']) colours = ['b', 'r', 'k'] linestyle = ['-', '--'] for band in range(len(pos[1])): for las in range(len(pos[2])): plot_psychometric(valid[:, band, las], right[:, band, las], pos[0], colour=colours[band], linestyle=linestyle[las]) plt.show()