Exemplo n.º 1
0
def get_plot(mice,date,plo_typ):

    EXPERIMENTER = settings.DEFAULT_EXPERIMENTER
    paradigm = '2afc'

    subject_list = mice
    session_list = date
	
    all_file_name = []
    for subject in subject_list:
        for session in session_list:
            behavFile = loadbehavior.path_to_behavior_data(subject,EXPERIMENTER,paradigm,session)
            behavData = loadbehavior.FlexCategBehaviorData(behavFile,readmode='full')
            for plot_type in plo_typ:
                out_dict = form_out_put(sub=subject,typ=plot_type,data=behavData,sess=session)
                all_file_name.append(out_dict['filename'])
                if not check_exsit(fil_nam=out_dict['filename']):
                    #non_exsi_file.append(out_dict['filename'])
                    test_list=[]
                    test_list.append(out_dict)
                    pg.Generate(plotList=test_list)
                    #test_plot(out_dic=out_dict)
                    #print
					

    return all_file_name
Exemplo n.º 2
0
def get_plot(mice,date,plo_typ):
    '''
    Args:
        mice: A list to store the mice
        date: A list to store the dates
        plo_typ: A list to store the plot types
    Returns:
        all_file_name: A list to store all the file names that referenced in this excuction
    '''
    subject_list = mice
    session_list = date
	
    all_file_name = []
    for subject in subject_list:
        for session in session_list:
            behavData = None
            try:
                behavFile = loadbehavior.path_to_behavior_data(subject,EXPERIMENTER,paradigm,session)
                behavData = loadbehavior.FlexCategBehaviorData(behavFile,readmode='full')
            except:
                for plot_type in plo_typ:
                    out_dict = form_out_put(sub=subject,typ='summary',data=None,sess=session)
                    all_file_name.append(out_dict['filename'])
                continue
            for plot_type in plo_typ:
                out_dict = form_out_put(sub=subject,typ=plot_type,data=behavData,sess=session)
                all_file_name.append(out_dict['filename'])
                if not check_exist(fil_nam=out_dict['filename']):
                    #non_exsi_file.append(out_dict['filename'])
                    #test_list=[]
                    #test_list.append(out_dict)
                    pg.generate(plotInfo=out_dict)
    return all_file_name
Exemplo n.º 3
0
def band_SNR_laser_psychometric(animal, sessions, trialTypes='laserSide', paradigm='2afc', xlabel=True, ylabel=True):
    loader = dataloader.DataLoader(animal)
    validPerSNR = None
    rightPerSNR = None
    for ind, session in enumerate(sessions):
        behavFile = loadbehavior.path_to_behavior_data(animal,paradigm,session)
        behavData = loader.get_session_behavior(behavFile)
        ax = plt.gca()
        ax.cla()
        possibleSNRs = np.unique(behavData['currentSNR'])
        laserTrialTypes = np.unique(behavData[trialTypes])
        trialsEachCond = behavioranalysis.find_trials_each_combination(behavData['currentSNR'], possibleSNRs, 
                                                                        behavData[trialTypes], laserTrialTypes)
        valid = behavData['valid'].astype(bool)
        rightChoice = behavData['choice']==behavData.labels['choice']['right']
        if validPerSNR is None:
            validPerSNR = np.zeros((len(laserTrialTypes),len(possibleSNRs)))
            rightPerSNR = np.zeros((len(laserTrialTypes),len(possibleSNRs)))
        for las in range(len(laserTrialTypes)):
            trialsThisLaser = trialsEachCond[:,:,las]
            for inds in range(len(possibleSNRs)):
                trialsThisSNR = trialsThisLaser[:,inds]
                validThisSNR = np.sum(trialsThisSNR.astype(int)[valid])
                rightThisSNR = np.sum(trialsThisSNR.astype(int)[rightChoice])
                validPerSNR[las,inds] += validThisSNR
                rightPerSNR[las,inds] += rightThisSNR
    return validPerSNR, rightPerSNR, possibleSNRs, laserTrialTypes
Exemplo n.º 4
0
    def load_session_data(self, session, experiment, site, tetrode, cluster=None, behavClass=None):
        '''
        Return ephys and behavior data for a particular session.
        Args
            session (int or str): Can be an integer index, to be used
                                  on the list of sessions for this site/experiment,
                                  or a string with the timestamp of the session.
            experiment (int): The index of the experiment to use
            site (int): The index of the site to use
            tetrode (int): Tetrode number to load
            cluster (int): Cluster number to load (set to None to load all clusters)
            behavClass (str): name of jaratoolbox.loadbehavior class to use for loading behavior
        Returns
            ephysData (dict): dictionary of ephys data returned by jaratoolbox.ephyscore.load_ephys()
            bdata (dict): jaratoolbox.loadbehavior.BehaviorData (or subclass, depending on behavClass arg)
        '''
        sessionObj = self.get_session_obj(session, experiment, site)
        sessionDir = sessionObj.ephys_dir()

        #Some info to return about the session. TODO: Is this necessary??
        info = {'sessionDir':sessionDir}

        if behavClass == None:
            behavClass = loadbehavior.BehaviorData
        if sessionObj.behavsuffix is not None:
            dateStr = ''.join(sessionObj.date.split('-'))
            fullSessionStr = '{}{}'.format(dateStr, sessionObj.behavsuffix)
            behavDataFilePath = loadbehavior.path_to_behavior_data(sessionObj.subject,
                                                                sessionObj.paradigm,
                                                                fullSessionStr)
            bdata = behavClass(behavDataFilePath,readmode='full')
        else:
            bdata = None
        ephysData = ephyscore.load_ephys(sessionObj.subject, sessionObj.paradigm, sessionDir, tetrode, cluster)
        return ephysData, bdata, info
Exemplo n.º 5
0
def load_many_sessions(animalNames,sessions,paradigm='2afc',datesRange=None):
    '''
    Based on behavioranalysis.save_many_sessions_reversal()

    TO DO:
    - Add params='all', (it depends on loadbehavior.FlexCateg being able to load a subset of vars)
    - What to do if a parameter only exists for some sessions?
    '''
    if isinstance(animalNames,str):
        animalNames = [animalNames]
    if datesRange:
        datesLims = [parse_isodate(dateStr) for dateStr in datesRange]
        allDates = [datesLims[0]+datetime.timedelta(n) \
                        for n in range((datesLims[-1]-datesLims[0]).days+1)]
        allSessions = [oneDate.strftime('%Y%m%da') for oneDate in allDates]
    else:
        allSessions = sessions
    nAnimals = len(animalNames)
    if paradigm=='2afc':
        loadingClass = loadbehavior.FlexCategBehaviorData
    else:
        raise TypeError('Loading many sessions for that paradigm has not been implemented')

    #if params=='all':
    #    readmode = 'full'
    #else:
    #    readmode = params
    readmode = 'full'

    #allBehavData = {}
    #allBehavData['sessionID'] = np.empty(0,dtype='i2')
    #allBehavData['animalID'] = np.empty(0,dtype='i1')

    inds=0
    for inda,animalName in enumerate(animalNames):
        for indsa,thisSession in enumerate(allSessions):
            try:
                behavFile = loadbehavior.path_to_behavior_data(animalName,EXPERIMENTER,paradigm,thisSession)
                behavData = loadingClass(behavFile,readmode=readmode)
            except IOError:
                print thisSession+' does not exist'
                continue
            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):
                        allBehavData[key]=val
                    else:
                        allBehavData[key] = np.concatenate((allBehavData[key],val))
                nTrials = len(behavData['outcome']) # FIXME: what if this key does not exist?
                allBehavData['sessionID'] = np.concatenate((allBehavData['sessionID'],
                                                            np.tile(inds,nTrials)))
                allBehavData['animalID'] = np.concatenate((allBehavData['animalID'],
                                                            np.tile(inda,nTrials)))
            inds += 1
    return allBehavData
Exemplo n.º 6
0
def behav_stats(animal, sessions, paradigm='2afc'):
    loader = dataloader.DataLoader(animal)
    nValid = 0
    nCorrect = 0
    for session in sessions:
        behavFile = loadbehavior.path_to_behavior_data(animal,paradigm,session)
        behavData = loader.get_session_behavior(behavFile)
        correct = behavData['outcome']==behavData.labels['outcome']['correct']
        valid = behavData['valid'].astype(bool)
        nValid += len(valid)
        nCorrect += len(correct[correct==True])
    return nValid, nCorrect
Exemplo n.º 7
0
    def __init__(self, experimenter, paradigm, subject, session, threshold):

        # Setup the file and the data
        # FIXME: We really shouldn't be hardcoding any of this. We should be scanning through the directories, checking each one.
        self.experimenter   = experimenter
        self.paradigm       = paradigm
        self.subject        = subject
        self.session        = session
        self.behavFile      = loadbehavior.path_to_behavior_data(subject,experimenter,paradigm,session)
        self.behavData      = loadbehavior.FlexCategBehaviorData(self.behavFile, readmode='full')

        # A basic threshold, to detect if average performance falls below it. 
        self.threshold      = threshold
Exemplo n.º 8
0
def behav_laser_stats(animal, sessions, paradigm='2afc'):
    loader = dataloader.DataLoader(animal)
    nValid = [0,0]
    nCorrect = [0,0]
    for session in sessions:
        behavFile = loadbehavior.path_to_behavior_data(animal,paradigm,session)
        behavData = loader.get_session_behavior(behavFile)
        laserTrials = np.where(behavData['laserSide']!=0)
        conTrials = np.where(behavData['laserSide']==0)
        correct = behavData['outcome']==behavData.labels['outcome']['correct']
        valid = behavData['valid'].astype(bool)
        nValid[0] += len(valid[conTrials])
        nValid[1] += len(valid[laserTrials])
        nCorrect[0] += np.sum(correct[conTrials])
        nCorrect[1] += np.sum(correct[laserTrials])
    return nValid, nCorrect
Exemplo n.º 9
0
def time_differences_by_trial(animal, sessions, sortBy, paradigm = '2afc', triggers = ['Cin', 'Cout']):
    loader = dataloader.DataLoader(animal)
    timeDiff = []
    import pdb
    for ind,session in enumerate(sessions):
        behavFile = loadbehavior.path_to_behavior_data(animal,paradigm,session)
        behavData = loader.get_session_behavior(behavFile)
        possibleSort = np.unique(behavData[sortBy])
        if ind == 0:
            for sort in range(len(possibleSort)):
                timeDiff.append([])
        trialsEachCond = behavioranalysis.find_trials_each_type(behavData[sortBy], possibleSort)
        eventCode = np.array(behavData.events['eventCode'])
        eventTime = behavData.events['eventTime']
        nextState = behavData.events['nextState']
        trialEnd = np.where(nextState==behavData.stateMatrix['statesNames']['startTrial'])[0][1:]
        try:
            start = np.where(eventCode==behavData.stateMatrix['eventsNames'][triggers[0]])[0]
        except KeyError:
            start = np.where(nextState==behavData.stateMatrix['statesNames'][triggers[0]])[0]+1
        try:
            stop = np.where(eventCode==behavData.stateMatrix['eventsNames'][triggers[1]])[0]
        except KeyError:
            stop = np.where(nextState==behavData.stateMatrix['statesNames'][triggers[1]])[0]+1
        for ind in range(len(possibleSort)):
            trialsThisCond = trialsEachCond[:,ind]
            if len(trialsThisCond) > len(trialEnd):
                trialsThisCond = trialsThisCond[:-1]
            trialEndThisCond = trialEnd[trialsThisCond]
            startThisCond = np.zeros(sum(trialsThisCond))
            stopThisCond = np.zeros(sum(trialsThisCond))
            #pdb.set_trace()
            for i in range(len(trialEndThisCond)):
                startThisCond[i] = max(j for j in start if j < trialEndThisCond[i])
                stopThisCond[i] = min(k for k in stop if k > startThisCond[i])
            startThisCond = startThisCond.astype(int)
            stopThisCond = stopThisCond.astype(int)
            startTime = eventTime[startThisCond]
            stopTime = eventTime[stopThisCond]
            diffThisCond = stopTime - startTime
            #pdb.set_trace()
            timeDiff[ind].extend(diffThisCond)
    return timeDiff, possibleSort
Exemplo n.º 10
0
def loadBehavior(subject, sessionstr):
    ############################################################################################################################
    #PARAMETERS
    ############################################################################################################################
    experimenter = 'santiago'
    paradigm = '2afc'
    ############################################################################################################################

    behaviorFilename = loadbehavior.path_to_behavior_data(subject,experimenter,
                                                          paradigm,sessionstr)
    bdata = loadbehavior.BehaviorData(behaviorFilename)

    numberOfTrials = len(bdata['choice'])
    targetFrequencies = bdata['targetFrequency']

    #This gives an array of all frequencies presented
    possibleFreq = np.unique(bdata['targetFrequency'])

    #This gives an array with true and indices where the mouse made a correct decision
    correct = bdata['outcome']==bdata.labels['outcome']['correct']
    #This gives an array with true and indices where the mouse made a incorrect decision
    incorrect = bdata['outcome']==bdata.labels['outcome']['error']

    #This gives an array with true at indices of trials that are correct and went right
    rightward = bdata['choice']==bdata.labels['choice']['right']
    correctRightward = correct*rightward

    #This gives an array with true at indices of trials that are correct and went left
    leftward = bdata['choice']==bdata.labels['choice']['left']
    correctLeftward = correct*leftward

    #This gives an array with true at indices of trials that are incorrect and went right
    incorrectRightward = incorrect*rightward

    #This gives an array with true at indices of trials that are incorrect and went left
    incorrectLeftward = incorrect*leftward

    #This gives an array with true at indices of correct and incorrect (valid trials where a choice was made) trials only
    #trialsWithChoices = correct or incorrect
    
    return;
Exemplo n.º 11
0
def band_SNR_psychometric(animal, sessions, paradigm = '2afc'):
    loader = dataloader.DataLoader(animal)
    validPerSNR = None
    rightPerSNR = None
    for ind,session in enumerate(sessions):
        behavFile = loadbehavior.path_to_behavior_data(animal,paradigm,session)
        behavData = loader.get_session_behavior(behavFile)
        possibleSNRs = np.unique(behavData['currentSNR'])
        trialsEachCond = behavioranalysis.find_trials_each_type(behavData['currentSNR'], possibleSNRs)
        valid = behavData['valid'].astype(bool)
        rightChoice = behavData['choice']==behavData.labels['choice']['right']
        if validPerSNR is None:
            validPerSNR = np.zeros(len(possibleSNRs))
            rightPerSNR = np.zeros(len(possibleSNRs))
        for inds in range(len(possibleSNRs)):
            trialsThisSNR = trialsEachCond[:,inds]
            validThisSNR = np.sum(trialsThisSNR.astype(int)[valid]) 
            rightThisSNR = np.sum(trialsThisSNR.astype(int)[rightChoice])
            validPerSNR[inds] += validThisSNR
            rightPerSNR[inds] += rightThisSNR
    return validPerSNR, rightPerSNR, possibleSNRs
Exemplo n.º 12
0
def time_differences(animal, sessions, paradigm = '2afc', triggers = ['Cin', 'Cout']):
    import pdb
    loader = dataloader.DataLoader(animal)
    timeDiff = None
    for ind,session in enumerate(sessions):
        behavFile = loadbehavior.path_to_behavior_data(animal,paradigm,session)
        behavData = loader.get_session_behavior(behavFile)
        eventCode = np.array(behavData.events['eventCode'])
        eventTime = behavData.events['eventTime']
        nextState = behavData.events['nextState']
        try:
            start = np.where(eventCode==behavData.stateMatrix['eventsNames'][triggers[0]])[0]
        except KeyError:
            start = np.where(nextState==behavData.stateMatrix['statesNames'][triggers[0]])[0]+1
        try:
            stop = np.where(eventCode==behavData.stateMatrix['eventsNames'][triggers[1]])[0]
        except KeyError:
            stop = np.where(nextState==behavData.stateMatrix['statesNames'][triggers[1]])[0]+1
        if len(start)>len(stop):
            startAll = start.copy()
            start = np.zeros(len(stop))
            for i in range(len(stop)):
                start[i] = max(j for j in startAll if j < stop[i])
            start = start.astype(int)
        if len(stop)>len(start):
            stopAll = stop.copy()
            stop = np.zeros(len(start))
            for i in range(len(start)):
                stop[i] = min(j for j in stopAll if j > start[i])
            stop = stop.astype(int)
        startTime = eventTime[start]
        stopTime = eventTime[stop]
        pdb.set_trace()
        diffThisSess = stopTime-startTime
        if timeDiff is None:
            timeDiff = diffThisSess
        else:
            timeDiff = np.concatenate((timeDiff, diffThisSess))
    return timeDiff
Exemplo n.º 13
0
def create_plots(subjectsList, datesList, plotsList, loaderStr=DEFAULT_LOADER):
    '''
    Return a list of plots filenames.

    Args:
        subjectsList (list): list of strings with subject names.
        datesList (list): list of strings with sessions.
        plotsList (list): list of strings with plot names.
    Returns:
        allFilenames (list): all the filenames of plots.
    '''
    allFilenames = []
    for subject in subjectsList:
        for session in datesList:
            behavData = None
            # FIXME: specify an exception type
            loader = getattr(loadbehavior,loaderStr)
            try:
                behavFile = loadbehavior.path_to_behavior_data(subject, PARADIGM, session)
                #behavData = loadbehavior.FlexCategBehaviorData(behavFile,readmode='full')
                #behavData = loadbehavior.BehaviorData(behavFile,readmode='full')
                behavData = loader(behavFile)
            except:
                for plot_type in plotsList:
                    filename = make_filename(subject, session, 'summary')
                    allFilenames.append(filename)
                continue
            for plot_type in plotsList:
                filename = make_filename(subject, session, plot_type)
                allFilenames.append(filename)
                if settings.REGENERATE_PLOTS:
                    plotter.generate(behavData, plot_type, settings.IMAGE_PATH_OUTPUT, filename)
                else:
                    if not os.path.isfile(filename):
                        plotter.generate(behavData, plot_type, settings.IMAGE_PATH_OUTPUT, filename)                        
    return allFilenames
Exemplo n.º 14
0
for cellID in range(0,numOfCells):
    oneCell = allcells.cellDB[cellID]
    if (behavSession != oneCell.behavSession):


        subject = oneCell.animalName
        behavSession = oneCell.behavSession
        ephysSession = oneCell.ephysSession
        ephysRoot = os.path.join(ephysRootDir,subject)

        if (behavSession in minPerfList): #if it is already in the list, dont add it again
            continue

        # -- Load Behavior Data --
        behaviorFilename = loadbehavior.path_to_behavior_data(subject=subject,paradigm=paradigm,sessionstr=behavSession)
        bdata = loadbehavior.BehaviorData(behaviorFilename)
        numberOfTrials = len(bdata['choice'])


        correct = bdata['outcome']==bdata.labels['outcome']['correct']
        incorrect = bdata['outcome']==bdata.labels['outcome']['error']

        possibleFreq = np.unique(bdata['targetFrequency'])
        firstFreq = bdata['targetFrequency'] == possibleFreq[0]
        lastFreq = bdata['targetFrequency'] == possibleFreq[2]

        correctFirst = sum(correct & firstFreq)
        correctLast = sum(correct & lastFreq)
        incorrectFirst = sum(incorrect & firstFreq)
        incorrectLast = sum(incorrect & lastFreq)
Exemplo n.º 15
0
        valid = behavData['valid']
        movAvChoiceMatrix = np.ndarray([len(possibleFreq), sum(valid)])
        rightChoice = behavData['choice'] == behavData.labels['choice'][
            'right']
        for indf, thisFreq in enumerate(possibleFreq):
            trialsThisFreq = (behavData['targetFrequency'] == thisFreq)
            choiceVecThisFreq = np.ma.masked_array(rightChoice[valid])
            choiceVecThisFreq.mask = ~trialsThisFreq[valid]
            movAvChoice = extrafuncs.moving_average_masked(
                choiceVecThisFreq, winsize)
            movAvChoiceMatrix[indf, :] = movAvChoice
    return movAvChoiceMatrix


for animalName, session in sessionsDict.items():
    behavFileName = loadbehavior.path_to_behavior_data(animalName, paradigm,
                                                       session)
    behavData = loadbehavior.FlexCategBehaviorData(behavFileName)
    #allBehavDataThisAnimal = behavioranalysis.load_many_sessions(animalName,sessions)
    #targetFrequency = allBehavDataThisAnimal['targetFrequency']
    #currentBlock = allBehavDataThisAnimal['currentBlock']
    #blockTypes = [allBehavDataThisAnimal.labels['currentBlock'][blockLabel] for blockLabel in blockLabels]
    #trialsEachType = behavioranalysis.find_trials_each_type(currentBlock,blockTypes)
    #choice = allBehavDataThisAnimal['choice']
    #valid = allBehavDataThisAnimal['valid']& (choice!=allBehavDataThisAnimal.labels['choice']['none'])
    #choiceRight = choice==allBehavDataThisAnimal.labels['choice']['right']
    #nBlocks = len(blockTypes)
    #nFreqs = len(np.unique(targetFrequency))
    movAvChoiceMatrix = calculate_dynamics(behavData,
                                           winsize=40,
                                           soundfreq=None,
                                           byBlock=True)
#Get onset frame numbers
ttl = rtData['ttl_log']
ttl = ttl.ravel().astype(int)  #uint8 making things strange for diff
onsets = np.flatnonzero(
    np.diff((ttl == 2).astype(int)) == 1) + 1  #leading edges
onsets = onsets[:-1]  #NOTE: Drop the last event because too close to the end
nEvents = len(onsets)

#How many samples before and after onset to average
samplesBefore = 10
samplesAfter = 30
nSamples = samplesBefore + samplesAfter

#Load the behavior data
behavFn = loadbehavior.path_to_behavior_data('imag003', 'am_tuning_curve',
                                             '20181217d')
bdata = loadbehavior.BehaviorData(behavFn)

currentFreq = bdata['currentFreq']
if len(onsets) != len(currentFreq):
    currentFreq = currentFreq[:len(
        onsets)]  #Events will stop sooner than behavior.
possibleFreq = np.unique(currentFreq)

#Initialize array to hold stim-locked traces
alignedTraces = np.empty([nROIs, nEvents, nSamples])

for indEvent, onsetFrame in enumerate(onsets):
    frameStart = onsetFrame - samplesBefore
    frameEnd = onsetFrame + samplesAfter
    for indROI in range(nROIs):
Exemplo n.º 17
0
from pylab import *
import matplotlib.pyplot as plt
from statsmodels.stats.proportion import proportion_confint #Used to compute confidence interval for the error bars. 
from jaratoolbox import settings 
import sys

animalName = 'test012'
session = '20150106a'
experimenter = 'santiago'
paradigm = '2afc'

behavioranalysis.behavior_summary(animalName,session)

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)
Exemplo n.º 18
0
def main():
    global behavSession
    global subject
    global tetrode
    global cluster
    global bdata
    global eventOnsetTimes
    global spikeTimesFromEventOnset
    global indexLimitsEachTrial
    global spikeTimesFromMovementOnset
    global indexLimitsEachMovementTrial
    global titleText

    print "SwitchingReport"
    for cellID in range(0, numOfCells):
        oneCell = allcells.cellDB[cellID]
        try:
            if (behavSession != oneCell.behavSession):

                subject = oneCell.animalName
                behavSession = oneCell.behavSession
                ephysSession = oneCell.ephysSession
                ephysRoot = os.path.join(ephysRootDir, subject)

                print behavSession

                # -- Load Behavior Data --
                behaviorFilename = loadbehavior.path_to_behavior_data(
                    subject, experimenter, paradigm, behavSession)
                bdata = loadbehavior.FlexCategBehaviorData(behaviorFilename)
                #bdata = loadbehavior.BehaviorData(behaviorFilename)
                numberOfTrials = len(bdata['choice'])

                # -- Load event data and convert event timestamps to ms --
                ephysDir = os.path.join(ephysRoot, ephysSession)
                eventFilename = os.path.join(ephysDir, 'all_channels.events')
                events = loadopenephys.Events(
                    eventFilename)  # Load events data
                eventTimes = np.array(
                    events.timestamps
                ) / SAMPLING_RATE  #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and

                soundOnsetEvents = (events.eventID == 1) & (
                    events.eventChannel == soundTriggerChannel)

                eventOnsetTimes = eventTimes[soundOnsetEvents]
                soundOnsetTimeBehav = bdata['timeTarget']

                # Find missing trials
                missingTrials = behavioranalysis.find_missing_trials(
                    eventOnsetTimes, soundOnsetTimeBehav)
                # Remove missing trials
                bdata.remove_trials(missingTrials)
                bdata.find_trials_each_block()

                ###############################################################################################
                centerOutTimes = bdata[
                    'timeCenterOut']  #This is the times that the mouse goes out of the center port
                soundStartTimes = bdata[
                    'timeTarget']  #This gives an array with the times in seconds from the start of the behavior paradigm of when the sound was presented for each trial
                timeDiff = centerOutTimes - soundStartTimes
                if (len(eventOnsetTimes) < len(timeDiff)):
                    timeDiff = timeDiff[:-1]
                    eventOnsetTimesCenter = eventOnsetTimes + timeDiff
                elif (len(eventOnsetTimes) > len(timeDiff)):
                    eventOnsetTimesCenter = eventOnsetTimes[:-1] + timeDiff
                else:
                    eventOnsetTimesCenter = eventOnsetTimes + timeDiff
                ###############################################################################################

            tetrode = oneCell.tetrode
            cluster = oneCell.cluster

            # -- Load Spike Data From Certain Cluster --
            spkData = ephyscore.CellData(oneCell)
            spkTimeStamps = spkData.spikes.timestamps

            (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
                spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange)

            (spikeTimesFromMovementOnset,movementTrialIndexForEachSpike,indexLimitsEachMovementTrial) = \
                spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimesCenter,timeRange)

            plt.clf()
            if (len(spkTimeStamps) > 0):
                ax1 = plt.subplot2grid((numRows, numCols),
                                       ((numRows - sizeClusterPlot), 0),
                                       colspan=(numCols / 3))
                spikesorting.plot_isi_loghist(spkData.spikes.timestamps)
                ax3 = plt.subplot2grid(
                    (numRows, numCols),
                    ((numRows - sizeClusterPlot), (numCols / 3) * 2),
                    colspan=(numCols / 3))
                spikesorting.plot_events_in_time(spkTimeStamps)
                samples = spkData.spikes.samples.astype(float) - 2**15
                samples = (1000.0 / spkData.spikes.gain[0, 0]) * samples
                ax2 = plt.subplot2grid(
                    (numRows, numCols),
                    ((numRows - sizeClusterPlot), (numCols / 3)),
                    colspan=(numCols / 3))
                spikesorting.plot_waveforms(samples)

            ###############################################################################
            ax4 = plt.subplot2grid((numRows, numCols), (0, 0),
                                   colspan=(numCols / 2),
                                   rowspan=sizeRasters)
            plt.setp(ax4.get_xticklabels(), visible=False)
            raster_sound_block_switching()
            ax5 = plt.subplot2grid((numRows, numCols), (sizeRasters, 0),
                                   colspan=(numCols / 2),
                                   rowspan=sizeHists,
                                   sharex=ax4)
            hist_sound_block_switching()
            ax6 = plt.subplot2grid((numRows, numCols), (0, (numCols / 2)),
                                   colspan=(numCols / 2),
                                   rowspan=sizeRasters)
            plt.setp(ax6.get_xticklabels(), visible=False)
            raster_movement_block_switching()
            ax7 = plt.subplot2grid((numRows, numCols),
                                   (sizeRasters, (numCols / 2)),
                                   colspan=(numCols / 2),
                                   rowspan=sizeHists,
                                   sharex=ax6)
            hist_movement_block_switching()

            ax8 = plt.subplot2grid((numRows, numCols),
                                   ((sizeRasters + sizeHists), 0),
                                   colspan=(numCols / 2),
                                   rowspan=sizeRasters)
            plt.setp(ax8.get_xticklabels(), visible=False)
            raster_sound_allFreq_switching()
            ax9 = plt.subplot2grid((numRows, numCols),
                                   ((2 * sizeRasters + sizeHists), 0),
                                   colspan=(numCols / 2),
                                   rowspan=sizeHists,
                                   sharex=ax8)
            hist_sound_allFreq_switching()
            ax10 = plt.subplot2grid((numRows, numCols),
                                    ((sizeRasters + sizeHists), (numCols / 2)),
                                    colspan=(numCols / 2),
                                    rowspan=sizeRasters)
            plt.setp(ax10.get_xticklabels(), visible=False)
            raster_sound_switching()
            ax11 = plt.subplot2grid(
                (numRows, numCols),
                ((2 * sizeRasters + sizeHists), (numCols / 2)),
                colspan=(numCols / 2),
                rowspan=sizeHists,
                sharex=ax10)
            hist_sound_switching()
            ###############################################################################
            #plt.tight_layout()
            modulation_index_switching()
            plt.suptitle(titleText)

            tetrodeClusterName = 'T' + str(oneCell.tetrode) + 'c' + str(
                oneCell.cluster)
            plt.gcf().set_size_inches((8.5, 11))
            figformat = 'png'  #'png' #'pdf' #'svg'
            filename = 'report_%s_%s_%s.%s' % (subject, behavSession,
                                               tetrodeClusterName, figformat)
            fulloutputDir = outputDir + subject + '/'
            fullFileName = os.path.join(fulloutputDir, filename)

            directory = os.path.dirname(fulloutputDir)
            if not os.path.exists(directory):  #makes sure output folder exists
                os.makedirs(directory)
            #print 'saving figure to %s'%fullFileName
            plt.gcf().savefig(fullFileName, format=figformat)

            #plt.show()

        except:
            print "error with session " + oneCell.behavSession
            if (oneCell.behavSession not in badSessionList):
                badSessionList.append(oneCell.behavSession)

    print 'error with sessions: '
    for badSes in badSessionList:
        print badSes
Exemplo n.º 19
0
    sessions = sys.argv[1:]

nSessions = len(sessions)
nAnimals = len(subjects)

loadingClass = loadbehavior.FlexCategBehaviorData  #using this bdata class so we get 'blocks'
paradigm = '2afc'

gs = gridspec.GridSpec(nSessions * nAnimals, 1)
gs.update(hspace=0.5, wspace=0.4)
plt.clf()

for inds, thisSession in enumerate(sessions):
    for inda, animalName in enumerate(subjects):
        try:
            behavFile = loadbehavior.path_to_behavior_data(
                animalName, EXPERIMENTER, paradigm, thisSession)
            behavData = loadingClass(behavFile, readmode='full')
        except IOError:
            print thisSession + ' does not exist'
            continue
        print 'Loaded %s %s' % (animalName, thisSession)

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

        behavData.find_trials_each_block()
        trialsEachBlock = behavData.blocks['trialsEachBlock']
from jaratoolbox import behavioranalysis
from jaratoolbox import loadbehavior
import numpy as np
from pylab import *
import matplotlib.pyplot as plt
from jaratoolbox import settings 

subjects = ['hm4d004', 'hm4d005', 'hm4d006']
sessions = ['20140824a']

for subject_ind, subject in enumerate(subjects):
    for session_ind, session in enumerate(sessions):
        fname=loadbehavior.path_to_behavior_data(subject,'nick','2afc',session)


        try:
            bdata=loadbehavior.BehaviorData(fname)
        except IOError:
            pass

        targetFrequency=bdata['targetFrequency']
        valid=bdata['valid']
        choice=bdata['choice']
        intensities=bdata['targetIntensity']
        choiceRight = choice==bdata.labels['choice']['right']


        possibleFreq = np.unique(targetFrequency)
        nFreq = len(possibleFreq) 
        fractionRightEachFreq=np.zeros(nFreq)
def behavior_summary(subjects,sessions,trialslim=[],outputDir='',paradigm='2afc',soundfreq=None):
    '''
    subjects: an array of animals to analyze (it can also be a string for a single animal)
    sessions: an array of sessions to analyze (it can also be a string for a single session)
    trialslim: array to set xlim() of dynamics' plot
    outputDir: where to save the figure (if not specified, nothing will be saved)
    paradigm: load data from a different paradigm. Warning: data should be loaded with
              loadbehavior.ReversalBehaviorData().
    '''
    if isinstance(subjects,str):
        subjects = [subjects]
    if isinstance(sessions,str):
        sessions = [sessions]
    nSessions = len(sessions)
    nAnimals = len(subjects)

    loadingClass = loadbehavior.FlexCategBehaviorData

    gs = gridspec.GridSpec(nSessions*nAnimals, 3)
    gs.update(hspace=0.5,wspace=0.4)
    plt.clf()
    for inds,thisSession in enumerate(sessions):
        for inda,animalName in enumerate(subjects):
            try:
                behavFile = loadbehavior.path_to_behavior_data(animalName,paradigm,thisSession)
                behavData = loadingClass(behavFile,readmode='full')
            except IOError:
                print thisSession+' does not exist'
                continue
            print 'Loaded %s %s'%(animalName,thisSession)
            # -- Plot either psychometric or average performance
            thisAnimalPos = 3*inda*nSessions
            thisPlotPos = thisAnimalPos+3*inds
            ax1=plt.subplot(gs[thisPlotPos])
            if any(behavData['psycurveMode']):
                (pline, pcaps, pbars, pdots) = plot_frequency_psycurve(behavData,fontsize=8)
                plt.setp(pdots,ms=6)
                plt.ylabel('% rightward')
                nValid = behavData['nValid'][-1]
                nTrials = len(behavData['nValid'])
                if soundfreq is None:
                    freqsToUse = [behavData['lowFreq'][-1],behavData['highFreq'][-1]]
                titleStr = '{0} [{1}] {2}\n'.format(behavData.session['subject'],behavData.session['date'],
                                                    behavData.session['hostname'])
                titleStr += '{0} valid, {1:.0%} early'.format(nValid,(nTrials-nValid)/float(nTrials))
                plt.title(titleStr,fontweight='bold',fontsize=8,y=0.95)
            else:
                behavData.find_trials_each_block()
                if soundfreq is None:
                    freqsToUse = [behavData['lowFreq'][-1],behavData['midFreq'][-1],behavData['highFreq'][-1]]
                plot_summary(behavData,fontsize=8,soundfreq=freqsToUse)

            # -- Plot dynamics --
            ax2=plt.subplot(gs[thisPlotPos+1:thisPlotPos+3])
            plot_dynamics(behavData,winsize=40,fontsize=8,soundfreq=freqsToUse)
            #plt.setp(ax1.get_xticklabels(),visible=False)
            ax1xlabel = ax1.get_xlabel()
            ax2xlabel = ax2.get_xlabel()
            ax1.set_xlabel('')
            ax2.set_xlabel('')
            if trialslim:
                plt.xlim(trialslim)
            plt.draw()
            plt.show()
    plt.setp(ax1.get_xticklabels(),visible=True)
    plt.setp(ax2.get_xticklabels(),visible=True)
    ax1.set_xlabel(ax1xlabel)
    ax2.set_xlabel(ax2xlabel)
    #plt.draw()
    #plt.show()
                      
    if len(outputDir):
        animalStr = '-'.join(subjects)
        sessionStr = '-'.join(sessions)
        plt.gcf().set_size_inches((8.5,11))
        figformat = 'png' #'png' #'pdf' #'svg'
        filename = 'behavior_%s_%s.%s'%(animalStr,sessionStr,figformat)
        fullFileName = os.path.join(outputDir,filename)
        print 'saving figure to %s'%fullFileName
        plt.gcf().savefig(fullFileName,format=figformat)
    confintervRightEachValue = [] # TO BE IMPLEMENTED LATER
    return (possibleValues,fractionRightEachValue,confintervRightEachValue,nTrialsEachValue,nRightwardEachValue)


if __name__ == "__main__":

    CASE=6
    if CASE==1:
        from jaratoolbox import loadbehavior
        import numpy as np
        experimenter = 'santiago'
        paradigm = '2afc'
        subject = 'test020'
        session = '20140421a'

        behavFile = loadbehavior.path_to_behavior_data(subject,experimenter,paradigm,session)
        behavData = loadbehavior.FlexCategBehaviorData(behavFile,readmode='full')
        behavData.find_trials_each_block()
 
        #trialsEachBlock = behavData.blocks['trialsEachBlock']
        #nValidEachBlock = np.sum(trialsEachBlock & (~behavData['valid'][:,np.newaxis]),axis=0)
        #validEachBlock = trialsEachBlock & behavData['valid'][:,np.newaxis].astype(bool)

        #plot_dynamics(behavData,winsize=100)
        plot_summary(behavData)
        #tet = find_trials_each_type(behavData['targetFrequency'],np.unique(behavData['targetFrequency']),
        #                            behavData['currentBlock'],np.unique(behavData['currentBlock']))

    elif CASE==2:
        if 1:
            subjects = ['test011','test012','test013','test014','test015',
Exemplo n.º 23
0
if len(sys.argv)>1:
    session = sys.argv[1]+'a'
else:
    session = '20150308a'
   
for CASE in [1]:

    if CASE==1:
        subjects = ['cued001','cued002','cued003','cued004','cued005','cued006']
    elif CASE==2:
        pass

    figure(CASE)
    #behavioranalysis.behavior_summary(subjects,sessions,trialslim=[0,1000],outputDir='/var/tmp/behavior_reports/')
    for inda,animalName in enumerate(subjects):
        fname=loadbehavior.path_to_behavior_data(animalName,'santiago','2afc',session)
        try:
            bdata=loadbehavior.BehaviorData(fname)
            nReward = bdata['nRewarded'][-1]
            nValid = bdata['nValid'][-1]
            correct = nReward/float(nValid)
            print '{0} (rew/valid): {1} / {2} = {3:0.0%}'.format(animalName,nReward,nValid,correct)
        except:
            print 'Something is wrong with this session'
            pass


'''
subjects = ['test011','test015','test016']
sessions = ['20150222a','20150223a']
behavioranalysis.behavior_summary(subjects,sessions,trialslim=[0,1000],outputDir='/tmp/')
def main():
    global behavSession
    global subject
    global ephysSession
    global tetrode
    global cluster
    global bdata
    global eventOnsetTimes
    global spikeTimesFromEventOnset
    global indexLimitsEachTrial
    global spikeTimesFromMovementOnset
    global indexLimitsEachMovementTrial
    global tuningBehavior  #behavior file name of tuning curve
    global tuningEphys  #ephys session name of tuning curve

    for cellID in range(0, numOfCells):
        oneCell = allcells.cellDB[cellID]
        try:
            if (behavSession != oneCell.behavSession):

                subject = oneCell.animalName
                behavSession = oneCell.behavSession
                ephysSession = oneCell.ephysSession
                ephysRoot = os.path.join(ephysRootDir, subject)
                tuningBehavior = oneCell.tuningBehavior
                tuningEphys = oneCell.tuningSession

                print behavSession

                # -- Load Behavior Data --
                behaviorFilename = loadbehavior.path_to_behavior_data(
                    subject=subject,
                    paradigm=paradigm,
                    sessionstr=behavSession)
                bdata = loadbehavior.BehaviorData(behaviorFilename)
                numberOfTrials = len(bdata['choice'])

                # -- Load event data and convert event timestamps to ms --
                ephysDir = os.path.join(ephysRoot, ephysSession)
                eventFilename = os.path.join(ephysDir, 'all_channels.events')
                events = loadopenephys.Events(
                    eventFilename)  # Load events data
                eventTimes = np.array(
                    events.timestamps
                ) / SAMPLING_RATE  #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and

                soundOnsetEvents = (events.eventID == 1) & (
                    events.eventChannel == soundTriggerChannel)

                eventOnsetTimes = eventTimes[soundOnsetEvents]
                soundOnsetTimeBehav = bdata['timeTarget']

                # Find missing trials
                missingTrials = behavioranalysis.find_missing_trials(
                    eventOnsetTimes, soundOnsetTimeBehav)

                # Remove missing trials
                bdata.remove_trials(missingTrials)

                possibleFreq = np.unique(bdata['targetFrequency'])
                numberOfFrequencies = len(possibleFreq)
                centerFrequencies = [(numberOfFrequencies / 2 - 1),
                                     numberOfFrequencies / 2]

                #################################################################################################
                centerOutTimes = bdata[
                    'timeCenterOut']  #This is the times that the mouse goes out of the center port
                soundStartTimes = bdata[
                    'timeTarget']  #This gives an array with the times in seconds from the start of the behavior paradigm of when the sound was presented for each trial
                timeDiff = centerOutTimes - soundStartTimes

                if (len(eventOnsetTimes) < len(timeDiff)):
                    eventOnsetTimesCenter = eventOnsetTimes + timeDiff[:-1]
                elif (len(eventOnsetTimes) > len(timeDiff)):
                    eventOnsetTimesCenter = eventOnsetTimes[:-1] + timeDiff
                else:
                    eventOnsetTimesCenter = eventOnsetTimes + timeDiff
                #################################################################################################

            tetrode = oneCell.tetrode
            cluster = oneCell.cluster
            # -- Load Spike Data From Certain Cluster --
            spkData = ephyscore.CellData(oneCell)
            spkTimeStamps = spkData.spikes.timestamps

            (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
                spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange)

            (spikeTimesFromMovementOnset,movementTrialIndexForEachSpike,indexLimitsEachMovementTrial) = \
                spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimesCenter,timeRange)

            plt.clf()
            if (len(spkTimeStamps) > 0):
                ax1 = plt.subplot2grid((numRows, numCols),
                                       ((numRows - sizeClusterPlot), 0),
                                       colspan=(numCols / 3))
                spikesorting.plot_isi_loghist(spkData.spikes.timestamps)
                ax3 = plt.subplot2grid(
                    (numRows, numCols),
                    ((numRows - sizeClusterPlot), (numCols / 3) * 2),
                    colspan=(numCols / 3))
                spikesorting.plot_events_in_time(spkData.spikes.timestamps)
                samples = spkData.spikes.samples.astype(float) - 2**15
                samples = (1000.0 / spkData.spikes.gain[0, 0]) * samples
                ax2 = plt.subplot2grid(
                    (numRows, numCols),
                    ((numRows - sizeClusterPlot), (numCols / 3)),
                    colspan=(numCols / 3))
                spikesorting.plot_waveforms(samples)

            ###############################################################################
            ax4 = plt.subplot2grid((numRows, numCols), (0, 0),
                                   colspan=(numCols / 3),
                                   rowspan=3 * sizeRasters)
            #plt.setp(ax4.get_xticklabels(), visible=False)
            #raster_sound_psycurve(centerFrequencies[0])
            raster_tuning(ax4)
            axvline(x=0, ymin=0, ymax=1, color='r')
            plt.gca().set_xlim(tuning_timeRange)

            #ax5 = plt.subplot2grid((7,6), (2,0), colspan = 3, sharex=ax4)
            #hist_sound_psycurve(centerFrequencies[0])

            ax6 = plt.subplot2grid((numRows, numCols), (0, (numCols / 3)),
                                   colspan=(2 * numCols / 3),
                                   rowspan=sizeHalfRaster)
            raster_allfreq_sound_psycurve()
            ax6.set_ylabel('frequencies')
            ax6.yaxis.set_label_position("right")
            plt.setp(ax6.get_xticklabels(), visible=False)
            ax6.yaxis.tick_right()
            ax6.yaxis.set_ticks_position('both')
            plt.gca().set_xlim(timeRange)
            plt.title('Top: sound aligned, Bottom: movement aligned')

            ax7 = plt.subplot2grid((numRows, numCols),
                                   (sizeHalfRaster, (numCols / 3)),
                                   colspan=(2 * numCols / 3),
                                   rowspan=sizeHalfRaster)
            hist_allfreq_sound_psycurve(ax7)
            ax7.yaxis.tick_right()
            ax7.yaxis.set_ticks_position('both')
            plt.setp(ax7.get_xticklabels(), visible=False)
            plt.gca().set_xlim(timeRange)

            ax8 = plt.subplot2grid((numRows, numCols),
                                   (2 * sizeHalfRaster, (numCols / 3)),
                                   colspan=(2 * numCols / 3),
                                   rowspan=sizeHalfRaster)
            ax8.yaxis.tick_right()
            plt.setp(ax8.get_xticklabels(), visible=False)
            raster_allfreq_movement_psycurve()
            ax8.set_ylabel('frequencies')
            ax8.yaxis.set_label_position("right")

            ax10 = plt.subplot2grid((numRows, numCols),
                                    (3 * sizeHalfRaster, (numCols / 3)),
                                    colspan=(2 * numCols / 3),
                                    rowspan=sizeHalfRaster)
            #plt.setp(ax10.get_xticklabels(), visible=False)
            hist_allfreq_movement_psycurve(ax10)
            ax10.yaxis.tick_right()
            ax10.yaxis.set_ticks_position('both')
            plt.gca().set_xlim(timeRange)
            ax10.set_xlabel('Time (sec)')

            #ax11 = plt.subplot2grid((numRows,numCols), ((2*sizeRasters+sizeHists),(numCols/2)), colspan = (numCols/2), rowspan = sizeHists, sharex=ax10)
            #hist_sound_psycurve(centerFrequencies[1])
            #ax11.yaxis.tick_right()
            #ax11.yaxis.set_ticks_position('both')
            #plt.setp(ax11.get_yticklabels(), visible=False)
            #plt.gca().set_xlim(timeRange)
            ###############################################################################
            #plt.tight_layout()

            modulation_index_psycurve(centerFrequencies)
            plt.suptitle(titleText)

            tetrodeClusterName = 'T' + str(oneCell.tetrode) + 'c' + str(
                oneCell.cluster)
            plt.gcf().set_size_inches((8.5, 11))
            figformat = 'png'  #'png' #'pdf' #'svg'
            filename = reportname + '_%s_%s_%s.%s' % (
                subject, behavSession, tetrodeClusterName, figformat)
            fulloutputDir = outputDir + subject + '/'
            fullFileName = os.path.join(fulloutputDir, filename)

            directory = os.path.dirname(fulloutputDir)
            if not os.path.exists(directory):
                os.makedirs(directory)
            #print 'saving figure to %s'%fullFileName
            plt.gcf().savefig(fullFileName, format=figformat)

            #plt.show()

        except:
            if (oneCell.behavSession not in badSessionList):
                badSessionList.append(oneCell.behavSession)

    print 'error with sessions: '
    for badSes in badSessionList:
        print badSes
Exemplo n.º 25
0
#subject = 'hm4d003'
#session = '20140820a'

'''
subject = 'test053'
session = '20140907a'
experimenter = 'santiago'
'''

subject = 'test000'
session = '20141110a'
experimenter = 'santiago'

minIntensityToPlot = 30

fname=loadbehavior.path_to_behavior_data(subject,experimenter,'2afc',session)


bdata=loadbehavior.BehaviorData(fname)
from jaratoolbox import settings 

targetFrequency=bdata['targetFrequency']
valid=bdata['valid']
choice=bdata['choice']
intensity=bdata['targetIntensity']
choiceRight = choice==bdata.labels['choice']['right']


possibleFreq = np.unique(targetFrequency)
nFreq = len(possibleFreq) 
trialsEachFreq = behavioranalysis.find_trials_each_type(targetFrequency,possibleFreq)
Exemplo n.º 26
0
from jaratoolbox import loadopenephys

subject = 'd1pi039'
paradigm = 'am_tuning_curve'
session = '20190731h'
ephysSession = '2019-07-31_16-09-08'

# subject = 'd1pi039'
# paradigm = 'am_tuning_curve'
# session = '20190731b'
# ephysSession = '2019-07-31_11-17-46'

eventsFilename = os.path.join(settings.EPHYS_PATH, subject, ephysSession,
                              'all_channels.events')

behavFile = loadbehavior.path_to_behavior_data(subject, paradigm, session)
behavData = loadbehavior.BehaviorData(behavFile, readmode='full')

eventData = loadopenephys.Events(eventsFilename)
channelID = 0
thisChannelOn = eventData.get_event_onset_times(eventID=1,
                                                eventChannel=channelID)

behavDataSize = len(behavData['currentAmpL'])
ephysDataSize = len(thisChannelOn)

print('Behavior: {}'.format(behavDataSize))
print('Ephys:    {}'.format(ephysDataSize))

trialsToRemove = behavDataSize - ephysDataSize + 1
if trialsToRemove > 0:
Exemplo n.º 27
0
 def passes_test(self, subject, paradigm, sessionstr):
     self.behavFile = loadbehavior.path_to_behavior_data(subject, paradigm, sessionstr)
     if not os.path.exists(self.behavFile):
         get_behavior(subject)
     self.bdata = loadbehavior.BehaviorData(self.behavFile)
     return self.test()
def switch_report(mouseName, behavSession, tetrode, cluster):
    #global behavSession
    #global subject
    global bdata
    global eventOnsetTimes
    global spikeTimesFromEventOnset
    global indexLimitsEachTrial
    global spikeTimesFromMovementOnset
    global indexLimitsEachMovementTrial

    allcellsFileName = 'allcells_' + mouseName
    sys.path.append(settings.ALLCELLS_PATH)
    allcells = importlib.import_module(allcellsFileName)

    cellID = allcells.cellDB.findcell(mouseName, behavSession, tetrode,
                                      cluster)
    oneCell = allcells.cellDB[cellID]

    subject = oneCell.animalName
    behavSession = oneCell.behavSession
    ephysSession = oneCell.ephysSession
    ephysRoot = os.path.join(ephysRootDir, subject)

    # -- Load Behavior Data --
    behaviorFilename = loadbehavior.path_to_behavior_data(
        subject, experimenter, paradigm, behavSession)
    bdata = loadbehavior.FlexCategBehaviorData(behaviorFilename)
    #bdata = loadbehavior.BehaviorData(behaviorFilename)
    bdata.find_trials_each_block()
    numberOfTrials = len(bdata['choice'])

    # -- Load event data and convert event timestamps to ms --
    ephysDir = os.path.join(ephysRoot, ephysSession)
    eventFilename = os.path.join(ephysDir, 'all_channels.events')
    events = loadopenephys.Events(eventFilename)  # Load events data
    eventTimes = np.array(
        events.timestamps
    ) / SAMPLING_RATE  #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and

    soundOnsetEvents = (events.eventID == 1) & (events.eventChannel
                                                == soundTriggerChannel)

    eventOnsetTimes = eventTimes[soundOnsetEvents]

    #################################################################################################
    centerOutTimes = bdata[
        'timeCenterOut']  #This is the times that the mouse goes out of the center port
    soundStartTimes = bdata[
        'timeTarget']  #This gives an array with the times in seconds from the start of the behavior paradigm of when the sound was presented for each trial
    timeDiff = centerOutTimes - soundStartTimes
    if (len(eventOnsetTimes) < len(timeDiff)):
        timeDiff = timeDiff[:-1]
    eventOnsetTimesCenter = eventOnsetTimes + timeDiff
    #################################################################################################

    # -- Load Spike Data From Certain Cluster --
    spkData = ephyscore.CellData(oneCell)
    spkTimeStamps = spkData.spikes.timestamps

    (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
        spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange)

    (spikeTimesFromMovementOnset,movementTrialIndexForEachSpike,indexLimitsEachMovementTrial) = \
        spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimesCenter,timeRange)

    plt.clf()
    if (len(spkTimeStamps) > 0):
        ax1 = plt.subplot2grid((numRows, numCols),
                               ((numRows - sizeClusterPlot), 0),
                               colspan=(numCols / 3))
        spikesorting.plot_isi_loghist(spkData.spikes.timestamps)
        ax3 = plt.subplot2grid(
            (numRows, numCols),
            ((numRows - sizeClusterPlot), (numCols / 3) * 2),
            colspan=(numCols / 3))
        spikesorting.plot_events_in_time(spkTimeStamps)
        samples = spkData.spikes.samples.astype(float) - 2**15
        samples = (1000.0 / spkData.spikes.gain[0, 0]) * samples
        ax2 = plt.subplot2grid((numRows, numCols),
                               ((numRows - sizeClusterPlot), (numCols / 3)),
                               colspan=(numCols / 3))
        spikesorting.plot_waveforms(samples)

    ###############################################################################
    ax4 = plt.subplot2grid((numRows, numCols), (0, 0),
                           colspan=(numCols / 2),
                           rowspan=sizeRasters)
    raster_sound_block_switching()
    ax5 = plt.subplot2grid((numRows, numCols), (sizeRasters, 0),
                           colspan=(numCols / 2),
                           rowspan=sizeHists)
    hist_sound_block_switching()
    ax6 = plt.subplot2grid((numRows, numCols), (0, (numCols / 2)),
                           colspan=(numCols / 2),
                           rowspan=sizeRasters)
    raster_movement_block_switching()
    ax7 = plt.subplot2grid((numRows, numCols), (sizeRasters, (numCols / 2)),
                           colspan=(numCols / 2),
                           rowspan=sizeHists)
    hist_movement_block_switching()

    ax8 = plt.subplot2grid((numRows, numCols), ((sizeRasters + sizeHists), 0),
                           colspan=(numCols / 2),
                           rowspan=sizeRasters)
    raster_sound_allFreq_switching()
    ax9 = plt.subplot2grid((numRows, numCols),
                           ((2 * sizeRasters + sizeHists), 0),
                           colspan=(numCols / 2),
                           rowspan=sizeHists)
    hist_sound_allFreq_switching()
    ax10 = plt.subplot2grid((numRows, numCols),
                            ((sizeRasters + sizeHists), (numCols / 2)),
                            colspan=(numCols / 2),
                            rowspan=sizeRasters)
    raster_sound_switching()
    ax11 = plt.subplot2grid((numRows, numCols),
                            ((2 * sizeRasters + sizeHists), (numCols / 2)),
                            colspan=(numCols / 2),
                            rowspan=sizeHists)
    hist_sound_switching()
    ###############################################################################
    #plt.tight_layout()

    tetrodeClusterName = 'T' + str(oneCell.tetrode) + 'c' + str(
        oneCell.cluster)
    plt.suptitle(mouseName + ' ' + behavSession + ' ' + tetrodeClusterName)
    plt.gcf().set_size_inches((8.5, 11))
    #figformat = 'png' #'png' #'pdf' #'svg'
    #filename = 'report_%s_%s_%s.%s'%(subject,behavSession,tetrodeClusterName,figformat)
    #fulloutputDir = outputDir+subject +'/'
    #fullFileName = os.path.join(fulloutputDir,filename)

    #directory = os.path.dirname(fulloutputDir)
    #if not os.path.exists(directory): #makes sure output folder exists
    #os.makedirs(directory)
    #print 'saving figure to %s'%fullFileName
    #plt.gcf().savefig(fullFileName,format=figformat)

    plt.show()
Exemplo n.º 29
0
def rasterBlock(oneCell):
    subject = oneCell.animalName
    behavSession = oneCell.behavSession
    ephysSession = oneCell.ephysSession
    ephysRoot = os.path.join(ephysRootDir, subject)

    # -- Load Behavior Data --
    behaviorFilename = loadbehavior.path_to_behavior_data(
        subject, experimenter, paradigm, behavSession)
    bdata = loadbehavior.FlexCategBehaviorData(behaviorFilename)
    bdata.find_trials_each_block()

    # -- Load event data and convert event timestamps to ms --
    ephysDir = os.path.join(ephysRoot, ephysSession)
    eventFilename = os.path.join(ephysDir, 'all_channels.events')
    events = loadopenephys.Events(eventFilename)  # Load events data
    eventTimes = np.array(events.timestamps) / SAMPLING_RATE

    soundOnsetEvents = (events.eventID == 1) & (events.eventChannel
                                                == soundTriggerChannel)

    # -- Load Spike Data From Certain Cluster --
    spkData = ephyscore.CellData(oneCell)
    spkTimeStamps = spkData.spikes.timestamps

    eventOnsetTimes = eventTimes[soundOnsetEvents]

    correct = bdata['outcome'] == bdata.labels['outcome']['correct']

    possibleFreq = np.unique(bdata['targetFrequency'])
    oneFreq = bdata['targetFrequency'] == possibleFreq[middleFreq]

    correctOneFreq = oneFreq & correct
    correctTrialsEachBlock = bdata.blocks[
        'trialsEachBlock'] & correctOneFreq[:, np.newaxis]

    #trialsEachCond = np.c_[invalid,leftward,rightward]; colorEachCond = ['0.75','g','r']
    #trialsEachCond = np.c_[leftward,rightward]; colorEachCond = ['0.5','0.7','0']
    trialsEachCond = correctTrialsEachBlock

    if bdata['currentBlock'][0] == bdata.labels['currentBlock'][
            'low_boundary']:
        colorEachBlock = 3 * ['g', 'r']
    else:
        colorEachBlock = 3 * ['r', 'g']


    (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
        spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange)

    #plot(spikeTimesFromEventOnset,trialIndexForEachSpike,'.')

    plt.clf()
    ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2)
    extraplots.raster_plot(spikeTimesFromEventOnset,
                           indexLimitsEachTrial,
                           timeRange,
                           trialsEachCond=correctTrialsEachBlock,
                           colorEachCond=colorEachBlock,
                           fillWidth=None,
                           labels=None)
    #plt.yticks([0,trialsEachCond.sum()])
    #ax1.set_xticklabels([])
    plt.ylabel('Trials')

    timeVec = np.arange(timeRange[0], timeRange[-1], binWidth)
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, timeVec)

    smoothWinSize = 3
    ax2 = plt.subplot2grid((3, 1), (2, 0), sharex=ax1)

    extraplots.plot_psth(spikeCountMat / binWidth,
                         smoothWinSize,
                         timeVec,
                         trialsEachCond=correctTrialsEachBlock,
                         colorEachCond=colorEachBlock,
                         linestyle=None,
                         linewidth=3,
                         downsamplefactor=1)

    plt.xlabel('Time from sound onset (s)')
    plt.ylabel('Firing rate (spk/sec)')

    #plt.show()

    nameFreq = str(possibleFreq[middleFreq])
    tetrodeClusterName = 'T' + str(oneCell.tetrode) + 'c' + str(
        oneCell.cluster)
    plt.gcf().set_size_inches((8.5, 11))
    figformat = 'png'  #'png' #'pdf' #'svg'
    filename = 'block_%s_%s_%s_%s.%s' % (
        subject, behavSession, tetrodeClusterName, nameFreq, figformat)
    fulloutputDir = outputDir + subject + '/'
    fullFileName = os.path.join(fulloutputDir, filename)

    directory = os.path.dirname(fulloutputDir)
    if not os.path.exists(directory):
        os.makedirs(directory)
    print 'saving figure to %s' % fullFileName
    plt.gcf().savefig(fullFileName, format=figformat)
Exemplo n.º 30
0
def raster_sound_psycurve(animalName):
    oneCell = allcells.cellDB[cellID]
    if (behavSession != oneCell.behavSession):

        subject = oneCell.animalName
        behavSession = oneCell.behavSession
        ephysSession = oneCell.ephysSession
        ephysRoot = os.path.join(ephysRootDir, subject)

        # -- Load Behavior Data --
        behaviorFilename = loadbehavior.path_to_behavior_data(
            subject, experimenter, paradigm, behavSession)
        bdata = loadbehavior.BehaviorData(behaviorFilename)
        numberOfTrials = len(bdata['choice'])

        # -- Load event data and convert event timestamps to ms --
        ephysDir = os.path.join(ephysRoot, ephysSession)
        eventFilename = os.path.join(ephysDir, 'all_channels.events')
        events = loadopenephys.Events(eventFilename)  # Load events data
        eventTimes = np.array(
            events.timestamps
        ) / SAMPLING_RATE  #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and

        soundOnsetEvents = (events.eventID == 1) & (events.eventChannel
                                                    == soundTriggerChannel)

        eventOnsetTimes = eventTimes[soundOnsetEvents]

        rightward = bdata['choice'] == bdata.labels['choice']['right']
        leftward = bdata['choice'] == bdata.labels['choice']['left']
        invalid = bdata['outcome'] == bdata.labels['outcome']['invalid']

        possibleFreq = np.unique(bdata['targetFrequency'])
        numberOfFrequencies = len(possibleFreq)

    # -- Load Spike Data From Certain Cluster --
    spkData = ephyscore.CellData(oneCell)
    spkTimeStamps = spkData.spikes.timestamps

    (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
        spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange)

    for Frequency in range(numberOfFrequencies):

        Freq = possibleFreq[Frequency]
        oneFreq = bdata['targetFrequency'] == Freq

        trialsToUseRight = rightward & oneFreq
        trialsToUseLeft = leftward & oneFreq

        trialsEachCond = np.c_[trialsToUseLeft, trialsToUseRight]
        colorEachCond = ['r', 'g']

        plt.clf()
        ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2)
        extraplots.raster_plot(spikeTimesFromEventOnset,
                               indexLimitsEachTrial,
                               timeRange,
                               trialsEachCond=trialsEachCond,
                               colorEachCond=colorEachCond,
                               fillWidth=None,
                               labels=None)

        plt.ylabel('Trials')

        timeVec = np.arange(timeRange[0], timeRange[-1], binWidth)
        spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
            spikeTimesFromEventOnset, indexLimitsEachTrial, timeVec)

        smoothWinSize = 3
        ax2 = plt.subplot2grid((3, 1), (2, 0), sharex=ax1)

        extraplots.plot_psth(spikeCountMat / binWidth,
                             smoothWinSize,
                             timeVec,
                             trialsEachCond=trialsEachCond,
                             colorEachCond=colorEachCond,
                             linestyle=None,
                             linewidth=3,
                             downsamplefactor=1)

        plt.xlabel('Time from sound onset (s)')
        plt.ylabel('Firing rate (spk/sec)')

        if ((Frequency == numberOfFrequencies / 2)
                or (Frequency == (numberOfFrequencies / 2 - 1))):
            freqFile = 'Center_Frequencies'
        else:
            freqFile = 'Outside_Frequencies'
        tetrodeClusterName = 'T' + str(oneCell.tetrode) + 'c' + str(
            oneCell.cluster)
        plt.gcf().set_size_inches((8.5, 11))
        figformat = 'png'  #'png' #'pdf' #'svg'
        filename = 'rast_%s_%s_%s_%s.%s' % (subject, behavSession, Freq,
                                            tetrodeClusterName, figformat)
        fulloutputDir = outputDir + subject + '/' + freqFile + '/'
        fullFileName = os.path.join(fulloutputDir, filename)

        directory = os.path.dirname(fulloutputDir)
        if not os.path.exists(directory):
            os.makedirs(directory)
        print 'saving figure to %s' % fullFileName
        plt.gcf().savefig(fullFileName, format=figformat)
Exemplo n.º 31
0
def behavior_summary(subjects,sessions,trialslim=[],outputDir='',paradigm=None,soundfreq=None):
    '''
    subjects: an array of animals to analyze (it can also be a string for a single animal)
    sessions: an array of sessions to analyze (it can also be a string for a single session)
    trialslim: array to set xlim() of dynamics' plot
    outputDir: where to save the figure (if not specified, nothing will be saved)
    paradigm: load data from a different paradigm. Warning: data should be loaded with
              loadbehavior.ReversalBehaviorData().
    '''
    if isinstance(subjects,str):
        subjects = [subjects]
    if isinstance(sessions,str):
        sessions = [sessions]
    nSessions = len(sessions)
    nAnimals = len(subjects)

    loadingClass = loadbehavior.FlexCategBehaviorData
    paradigm = '2afc'

    gs = gridspec.GridSpec(nSessions*nAnimals, 3)
    gs.update(hspace=0.5,wspace=0.4)
    plt.clf()
    for inds,thisSession in enumerate(sessions):
        for inda,animalName in enumerate(subjects):
            try:
                behavFile = loadbehavior.path_to_behavior_data(animalName,EXPERIMENTER,paradigm,thisSession)
                behavData = loadingClass(behavFile,readmode='full')
            except IOError:
                print thisSession+' does not exist'
                continue
            print 'Loaded %s %s'%(animalName,thisSession)

            # -- Plot either psychometric or average performance
            thisAnimalPos = 3*inda*nSessions
            thisPlotPos = thisAnimalPos+3*inds
            ax1=plt.subplot(gs[thisPlotPos])
            if any(behavData['psycurveMode']):
                (pline, pcaps, pbars, pdots) = plot_frequency_psycurve(behavData,fontsize=8)
                plt.setp(pdots,ms=6)
                plt.ylabel('% rightward')
                nValid = behavData['nValid'][-1]
                nTrials = len(behavData['nValid'])
                if soundfreq is None:
                    # freqsToUse = [behavData['lowFreq'][-1],behavData['highFreq'][-1]]
                    freqsToUse = [min(np.unique(behavData['targetFrequency'])),max(np.unique(behavData['targetFrequency']))]
                titleStr = '{0} [{1}] {2}\n'.format(behavData.session['subject'],behavData.session['date'],
                                                    behavData.session['hostname'])
                titleStr += '{0} valid, {1:.0%} early'.format(nValid,(nTrials-nValid)/float(nTrials))
                plt.title(titleStr,fontweight='bold',fontsize=8,y=0.95)
            else:
                behavData.find_trials_each_block()
                if soundfreq is None:
                    # freqsToUse = [behavData['lowFreq'][-1],behavData['highFreq'][-1]]
                    freqsToUse = [min(np.unique(behavData['targetFrequency'])),max(np.unique(behavData['targetFrequency']))]
                plot_summary(behavData,fontsize=8,soundfreq=freqsToUse)

            # -- Plot dynamics --
            ax2=plt.subplot(gs[thisPlotPos+1:thisPlotPos+3])
            plot_dynamics(behavData,winsize=40,fontsize=8,soundfreq=freqsToUse)
            #plt.setp(ax1.get_xticklabels(),visible=False)
            ax1xlabel = ax1.get_xlabel()
            ax2xlabel = ax2.get_xlabel()
            ax1.set_xlabel('')
            ax2.set_xlabel('')
            if trialslim:
                plt.xlim(trialslim)
            plt.draw()
            plt.show()
    plt.setp(ax1.get_xticklabels(),visible=True)
    plt.setp(ax2.get_xticklabels(),visible=True)
    ax1.set_xlabel(ax1xlabel)
    ax2.set_xlabel(ax2xlabel)
    #plt.draw()
    #plt.show()

    if len(outputDir):
        animalStr = '-'.join(subjects)
        sessionStr = '-'.join(sessions)
        # plt.gcf().set_size_inches((8.5,11))
        figformat = 'png' #'png' #'pdf' #'svg'
        filename = 'behavior_%s_%s.%s'%(animalStr,sessionStr,figformat)
        fullFileName = os.path.join(outputDir,filename)
        print 'saving figure to %s'%fullFileName
        plt.gcf().savefig(fullFileName,format=figformat)
Exemplo n.º 32
0
subjects = ['adap005', 'adap008']
EXPERIMENTER = 'santiago'
paradigm = '2afc'
loadingClass = loadbehavior.FlexCategBehaviorData
outputDir = '/home/languo/data/behavior_reports'
settings.BEHAVIOR_PATH = '/home/languo/data/mnt/jarahubdata'
nAnimals = len(subjects)    
nSessions = len(sessions)
gs = gridspec.GridSpec(nAnimals*nSessions, 6)
gs.update(hspace=0.2,wspace=0.7)

plt.figure()
for inda, subject in enumerate(subjects):
    for inds, thisSession in enumerate(sessions):
        try:
            behavFile = loadbehavior.path_to_behavior_data(subject,EXPERIMENTER,paradigm,thisSession)
            bData = loadingClass(behavFile,readmode='full')
        except IOError:
            print thisSession+' does not exist'
            continue
        print 'Loaded %s %s'%(subject,thisSession)
        
        thisPlotPos = inda*nSessions+inds
        # -- Plot performance speed as intertrial intervals (left or right)--
        ax1=plt.subplot(gs[thisPlotPos,:-4])
        plot_ITI_dynamics(bData, winsize=20, fontsize=12)
        # -- Plot choice time based on trial outcome and actual choice--
        ax2=plt.subplot(gs[thisPlotPos,2:4])
        plot_choicetime_dynamics(bData, winsize=20, fontsize=12)
        # -- Plot reactopm time based on trial outcome and actual choice--
        ax3=plt.subplot(gs[thisPlotPos,-2:])
'''
animalList = ['gosi001','gosi002','gosi003','gosi004','gosi005',
              'gosi006','gosi007','gosi008','gosi009','gosi010',
              'gosi011','gosi012','gosi013','gosi014','gosi015']
'''

nValidAll = []
fractionValidAll = []
fractionCorrectAll = []

plt.clf()
nSubjects = len(animalList)

for inds,subject in enumerate(animalList):
    behavFile = loadbehavior.path_to_behavior_data(subject,'2afc',session)
    bdata = loadbehavior.BehaviorData(behavFile)

    delayToTargetMean = bdata['delayToTargetMean'][-1]
    delayToTargetHalfRange = bdata['delayToTargetHalfRange'][-1]
    targetDuration = bdata['targetDuration'][-1]
    delayToGoSignal = bdata['delayToGoSignal'][-1]
    
    targetFrequency = bdata['targetFrequency']
    choice = bdata['choice']
    valid = bdata['valid'] & (choice!=bdata.labels['choice']['none'])
    choiceRight = (choice==bdata.labels['choice']['right'])
    outcome = bdata['outcome']
    validCorrect = outcome[valid.astype(bool)]==bdata.labels['outcome']['correct']

    nValid = np.sum(valid)
Exemplo n.º 34
0
def main():
    global behavSession
    global subject
    global ephysSession
    global tetrodeID
    global bdata
    global eventOnsetTimes
    global spikeTimesFromEventOnset
    global indexLimitsEachTrial
    global spikeTimesFromMovementOnset
    global indexLimitsEachMovementTrial
    for cellID in range(0,numOfCells):
        oneCell = allcells.cellDB[cellID]
        try:
            if (behavSession != oneCell.behavSession):


                subject = oneCell.animalName
                behavSession = oneCell.behavSession
                ephysSession = oneCell.ephysSession
                ephysRoot = os.path.join(ephysRootDir,subject)

                print behavSession

                # -- Load Behavior Data --
                behaviorFilename = loadbehavior.path_to_behavior_data(subject,experimenter,paradigm,behavSession)
                bdata = loadbehavior.BehaviorData(behaviorFilename)
                numberOfTrials = len(bdata['choice'])

                # -- Load event data and convert event timestamps to ms --
                ephysDir = os.path.join(ephysRoot, ephysSession)
                eventFilename=os.path.join(ephysDir, 'all_channels.events')
                events = loadopenephys.Events(eventFilename) # Load events data
                eventTimes=np.array(events.timestamps)/SAMPLING_RATE #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and 

                soundOnsetEvents = (events.eventID==1) & (events.eventChannel==soundTriggerChannel)

                eventOnsetTimes = eventTimes[soundOnsetEvents]

                possibleFreq = np.unique(bdata['targetFrequency'])
                numberOfFrequencies = len(possibleFreq)
                centerFrequencies = [(numberOfFrequencies/2-1),numberOfFrequencies/2]

                #################################################################################################
                centerOutTimes = bdata['timeCenterOut'] #This is the times that the mouse goes out of the center port
                soundStartTimes = bdata['timeTarget'] #This gives an array with the times in seconds from the start of the behavior paradigm of when the sound was presented for each trial
                timeDiff = centerOutTimes - soundStartTimes
                if (len(eventOnsetTimes) < len(timeDiff)):
                    timeDiff = timeDiff[:-1]
                eventOnsetTimesCenter = eventOnsetTimes + timeDiff
                #################################################################################################



            # -- Load Spike Data From Certain Cluster --
            spkData = ephyscore.CellData(oneCell)
            spkTimeStamps = spkData.spikes.timestamps

            (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
                spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange)

            (spikeTimesFromMovementOnset,movementTrialIndexForEachSpike,indexLimitsEachMovementTrial) = \
                spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimesCenter,timeRange)

            plt.clf()
            if (len(spkTimeStamps)>0):
                ax1 = plt.subplot2grid((7,6), (6,0), colspan = 2)
                spikesorting.plot_isi_loghist(spkData.spikes.timestamps)
                ax3 = plt.subplot2grid((7,6), (6,4), colspan = 2)
                spikesorting.plot_events_in_time(spkData.spikes.timestamps)
                samples = spkData.spikes.samples.astype(float)-2**15
                samples = (1000.0/spkData.spikes.gain[0,0]) *samples
                ax2 = plt.subplot2grid((7,6), (6,2), colspan = 2)
                spikesorting.plot_waveforms(samples)


            ###############################################################################
            ax4 = plt.subplot2grid((7,6), (0,0), colspan = 3, rowspan = 2)
            raster_sound_psycurve(centerFrequencies[0])
            ax5 = plt.subplot2grid((7,6), (2,0), colspan = 3)
            hist_sound_psycurve(centerFrequencies[0])
            ax6 = plt.subplot2grid((7,6), (0,3), colspan = 3, rowspan = 2)
            raster_sound_psycurve(centerFrequencies[1])
            ax7 = plt.subplot2grid((7,6), (2,3), colspan = 3)
            hist_sound_psycurve(centerFrequencies[1])

            ax8 = plt.subplot2grid((7,6), (3,0), colspan = 3, rowspan = 2)
            raster_movement_psycurve(centerFrequencies[0])
            ax9 = plt.subplot2grid((7,6), (5,0), colspan = 3)
            hist_movement_psycurve(centerFrequencies[0])
            ax10 = plt.subplot2grid((7,6), (3,3), colspan = 3, rowspan = 2)
            raster_movement_psycurve(centerFrequencies[1])
            ax11 = plt.subplot2grid((7,6), (5,3), colspan = 3)
            hist_movement_psycurve(centerFrequencies[1])
            ###############################################################################
            #plt.tight_layout()

            tetrodeClusterName = 'T'+str(oneCell.tetrode)+'c'+str(oneCell.cluster)
            plt.gcf().set_size_inches((8.5,11))
            figformat = 'png' #'png' #'pdf' #'svg'
            filename = 'report_centerFreq_%s_%s_%s.%s'%(subject,behavSession,tetrodeClusterName,figformat)
            fulloutputDir = outputDir+subject +'/'
            fullFileName = os.path.join(fulloutputDir,filename)

            directory = os.path.dirname(fulloutputDir)
            if not os.path.exists(directory):
                os.makedirs(directory)
            #print 'saving figure to %s'%fullFileName
            plt.gcf().savefig(fullFileName,format=figformat)

            #plt.show()

        except:
        #print "error with session "+oneCell.behavSession
            if (oneCell.behavSession not in badSessionList):
                badSessionList.append(oneCell.behavSession)

    print 'error with sessions: '
    for badSes in badSessionList:
        print badSes
Exemplo n.º 35
0
text_file = open("%s/%s.txt" % (finalOutputDir, nameOfFile),
                 "w")  #open a text file to write in

text_file.write("minimum performance percentage: %s\n" % minPerf)

for cellID in range(0, numOfCells):
    oneCell = allcells.cellDB[cellID]
    if (behavSession != oneCell.behavSession):

        subject = oneCell.animalName
        behavSession = oneCell.behavSession
        ephysSession = oneCell.ephysSession
        ephysRoot = os.path.join(ephysRootDir, subject)

        # -- Load Behavior Data --
        behaviorFilename = loadbehavior.path_to_behavior_data(
            subject, experimenter, paradigm, behavSession)
        bdata = loadbehavior.BehaviorData(behaviorFilename)
        numberOfTrials = len(bdata['choice'])

        correct = bdata['outcome'] == bdata.labels['outcome']['correct']
        incorrect = bdata['outcome'] == bdata.labels['outcome']['error']

        possibleFreq = np.unique(bdata['targetFrequency'])
        firstFreq = bdata['targetFrequency'] == possibleFreq[0]
        lastFreq = bdata['targetFrequency'] == possibleFreq[2]

        correctFirst = sum(correct & firstFreq)
        correctLast = sum(correct & lastFreq)
        incorrectFirst = sum(incorrect & firstFreq)
        incorrectLast = sum(incorrect & lastFreq)
Exemplo n.º 36
0
if len(sys.argv) > 1:
    session = sys.argv[1] + 'a'
else:
    session = '20150329a'

subjects = ['cued001', 'cued002', 'cued003', 'cued004', 'cued005', 'cued006']
#subjects = ['cued004']
nAnimals = len(subjects)

smallFontSize = 8
fontSize = 10

clf()
for inda, animalName in enumerate(subjects):
    fname = loadbehavior.path_to_behavior_data(animalName, 'santiago', '2afc',
                                               session)
    try:
        bdata = loadbehavior.BehaviorData(fname)
    except IOError:
        #print fname+' does not exist'
        continue

    nReward = bdata['nRewarded'][-1]
    nValid = bdata['nValid'][-1]
    fractionCorrect = nReward / float(nValid)

    targetFrequency = bdata['targetFrequency']
    possibleTarget = unique(targetFrequency)
    cueFrequency = bdata['cueFrequency']
    possibleCue = unique(cueFrequency)
Exemplo n.º 37
0
    extraplots.set_ticks_fontsize(ax,fontsize)
    plt.draw()
    plt.show()

if __name__ == "__main__":

    CASE=6
    if CASE==1:
        from jaratoolbox import loadbehavior
        import numpy as np
        experimenter = 'santiago'
        paradigm = '2afc'
        subject = 'test020'
        session = '20140421a'

        behavFile = loadbehavior.path_to_behavior_data(subject,experimenter,paradigm,session)
        behavData = loadbehavior.FlexCategBehaviorData(behavFile,readmode='full')
        behavData.find_trials_each_block()

        #trialsEachBlock = behavData.blocks['trialsEachBlock']
        #nValidEachBlock = np.sum(trialsEachBlock & (~behavData['valid'][:,np.newaxis]),axis=0)
        #validEachBlock = trialsEachBlock & behavData['valid'][:,np.newaxis].astype(bool)

        #plot_dynamics(behavData,winsize=100)
        plot_summary(behavData)
        #tet = find_trials_each_type(behavData['targetFrequency'],np.unique(behavData['targetFrequency']),
        #                            behavData['currentBlock'],np.unique(behavData['currentBlock']))

    elif CASE==2:
        if 1:
            subjects = ['test011','test012','test013','test014','test015',
gcf().subplots_adjust(bottom=0.15)
for inda, animalName in enumerate(animalsNames):
    subplot(1, nAnimals, inda + 1)
    for inds, oneSession in enumerate(allSessions):
        typeThisSession = typeEachSessionLabels[typeEachSession[inds]]
        if (typeThisSession == 'pre') | (typeThisSession == 'post') | (
                typeThisSession == 'morepost'):
            paradigm = '2afc'
        elif typeThisSession == 'visual':
            paradigm = 'lightDiscrim'
        else:
            raise TypeError('This session type is not defined')

        try:
            fname = loadbehavior.path_to_behavior_data(animalName,
                                                       experimenter, paradigm,
                                                       oneSession)
            bdata = loadbehavior.BehaviorData(fname)
        except IOError:
            print 'It could not load {0}'.format(fname)
            continue
        '''
        print '-----------------------------'
        print bdata['nRewarded'][-1]
        print bdata['nValid'][-1]
        '''
        nCorrectEachSession[inds] = bdata['nRewarded'][-1]
        nValidEachSession[inds] = bdata['nValid'][-1]

    avPerfEachSession = nCorrectEachSession / nValidEachSession
Exemplo n.º 39
0
    return timeDiff, possibleSort

if __name__ == '__main__':
    import pdb
    SAVE = 0
    CASE = 2
    paradigm = '2afc'
    if CASE < 3:
        #animalNames = ['band011']#, 'band012']
       #animalNames = ['band011', 'band012', 'band017','band020']
        animalNames = ['band020']
        session = ['20170414a','20170415a','20170416a']
        for ind,animal in enumerate(animalNames):
            #plt.subplot(2,2,ind+1)
            loader = dataloader.DataLoader(animal)
            behavFile = loadbehavior.path_to_behavior_data(animal,paradigm,session[0])
            behavData = loader.get_session_behavior(behavFile)
            if ind<2:
                xlabel = False
            else:
                xlabel = True
            if ind%2==0:
                ylabel = True
            else:
                ylabel = False
            if CASE==0:
                plot_dynamics(behavData)
            elif CASE==1:
                band_discrim_byside(behavData)
            elif CASE==2:
                validPerSNR, rightPerSNR, possibleSNRs = band_SNR_psychometric(animal, session)
# -- Panel A: schematic of switching task -- #
#ax1 = plt.subplot(gs[0:2, 0:2])
ax1 = plt.subplot(gs[0:2, 0])
plt.axis('off')
ax1.annotate('A', xy=(labelPosX[0],labelPosY[0]), xycoords='figure fraction', fontsize=fontSizePanel, fontweight='bold')

# -- Panel B: example dynamics plot -- #
ax2 = plt.subplot(gs[2:4, 0])
ax1.annotate('B', xy=(labelPosX[0],labelPosY[1]), xycoords='figure fraction', fontsize=fontSizePanel, fontweight='bold')

animal = 'test089'
paradigm = '2afc'
session = '20160113a'
winsize = 40
behavFileName = loadbehavior.path_to_behavior_data(animal,paradigm,session)
behavData = loadbehavior.FlexCategBehaviorData(behavFileName)
hPlots = behavioranalysis.plot_dynamics_2afc_by_freq(behavData, winsize=winsize, fontsize=fontSizeLabels, soundfreq=None)
extraplots.boxoff(plt.gca())
plt.setp(hPlots[1], color=colorLeft) #Block1, midFreq
plt.setp(hPlots[2], color='grey') #Block1, highFreq
plt.setp(hPlots[3], color='grey') #Block2, lowFreq
plt.setp(hPlots[4], color=colorRight) #Block2, midFreq
plt.setp(hPlots[8], color='grey') #Block3, highFreq
plt.setp(hPlots[7], color=colorLeft) #Block3, midFreq
plt.setp(hPlots[9], color='grey') #Block4, lowFreq
plt.setp(hPlots[10], color=colorRight) #Block4, midFreq
plt.xlim([0,740])
plt.xticks([0,200,400,600])
plt.yticks([0,50,100])
plt.ylabel('Rightward\ntrials (%)', labelpad=0.5, fontsize=fontSizeLabels)
Exemplo n.º 41
0
    def cluster_color_psth(self, sessionList, plotType=None, site=-1, experiment=-1, tuningTimeRange = [0.0,0.1]):
        '''
        Display cluster waveforms and a PSTH or tuning curve for each cluster.
        Performs multisession clustering for each tetrode recorded at the site.
        Args:
            sessionList (list of indices): The indices of the sessions to be included in the multisession clustering.
            plotType (list of str): A list the same length as sessionList, containing the type of plot for that session.
                                    Current valid plotTypes are: 'psth', 'tuning'
            site (index): The index of the site to pull sessions from.
            experiment (index): The index of the experiment to get the site from.
            tuningTimeRange (list of float): List containing [start, stop] times relative to event onset over which to
                                             average spikes for tuning curve.
        Returns nothing, but .clu files and multisession cluster reports will be created.
        '''

        if not isinstance(sessionList, list):
            sessionList = list(sessionList)
        if plotType is None:
            plotType = ['psth']*len(sessionList)

        #Cluster the site, all tetrodes
        #TODO: Make sure this function is using nice new cms with numclusters=6
        self.cluster_array_multisession(sessionList, site=site, experiment=experiment)


        allSessionObj = [self.get_session_obj(session, experiment, site) for session in sessionList]
        allTetrodes=[so.tetrodes for so in allSessionObj]

        # allEventOnsetTimes = [self.loader.get_event_onset_times(ed) for ed in allEventData]

        siteObj = self.get_site_obj(site=site, experiment=experiment)
        allSessionType = [siteObj.session_types()[ind] for ind in sessionList]

        self.fig = plt.gcf()
        self.fig.clf()
        self.fig.set_facecolor('w')

        from matplotlib import gridspec
        gs = gridspec.GridSpec(2*len(allTetrodes[0]), 6+6*len(sessionList))
        gs.update(wspace=0.5, hspace=0.5)

        nClusters=6 #FIXME hardcoded number of clusters to plot

        from jaratoolbox import colorpalette
        cp = colorpalette.TangoPalette
        colors = [cp['SkyBlue1'], cp['Chameleon1'], cp['Orange1'],
                  cp['Plum1'], cp['ScarletRed1'], cp['Aluminium4']]

        for indSession, sessionObj in enumerate(allSessionObj):

            # sessionObj = allSessionObj[indSession]
            # sessionDir = allSessionDir[indSession]
            sessionDir = sessionObj.ephys_dir()

            # eventData = allEventData[indSession]
            # eventOnsetTimes = allEventOnsetTimes[indSession]

            tetrodes = allTetrodes[indSession]

            if plotType[indSession] == 'tuning':

                if sessionObj.behavsuffix is None:
                    raise AttributeError('There is no behavior suffix recorded for this session') #TODO: add session info
                behavClass = loadbehavior.BehaviorData
                dateStr = ''.join(sessionObj.date.split('-'))
                fullSessionStr = '{}{}'.format(dateStr, sessionObj.behavsuffix)
                behavDataFilePath = loadbehavior.path_to_behavior_data(sessionObj.subject,
                                                                    sessionObj.paradigm,
                                                                    fullSessionStr)
                bdata = behavClass(behavDataFilePath,readmode='full')
                #FIXME: Hardcoded variable name to sort by for tuning
                freqEachTrial = bdata['currentFreq']
                freqLabels = ["%.1f"%freq for freq in np.unique(freqEachTrial)/1000]

            for indt, tetrode in enumerate(tetrodes):

                colStart = 6+(6*indSession)
                colEnd = colStart+6
                psth_ax = plt.subplot(gs[indt*2:(indt*2)+2, colStart:colEnd])

                for indc, cluster in enumerate(range(1, nClusters+1)):

                    ephysData = ephyscore.load_ephys(sessionObj.subject, sessionObj.paradigm, sessionDir, tetrode, cluster)
                    spikeTimestamps = ephysData['spikeTimes']
                    eventOnsetTimes = ephysData['events']['stimOn']

                    clusterColor = colors[indc]
                    # spikeData= self.loader.get_session_spikes(sessionDir, tetrode, cluster)
                    # spikeTimestamps = spikeData.timestamps
                    timeRange = [-0.2, 1]
                    spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes(
                        spikeTimestamps, eventOnsetTimes, timeRange)


                    if plotType[indSession] == 'psth':
                        binEdges = np.linspace(-0.2, 1, 100)
                        spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,
                                                                                 indexLimitsEachTrial,
                                                                                 binEdges)
                        # import ipdb; ipdb.set_trace()
                        smoothWinSize = 3
                        winShape = np.concatenate((np.zeros(smoothWinSize),np.ones(smoothWinSize))) # Square (causal)
                        winShape = winShape/np.sum(winShape)

                        binsStartTime=binEdges[:-1]

                        binSize = binEdges[1]-binEdges[0]
                        thisPSTH = np.mean(spikeCountMat/binSize,axis=0)
                        smoothPSTH = np.convolve(thisPSTH,winShape,mode='same')
                        downsamplefactor=1
                        sSlice = slice(0,len(smoothPSTH),downsamplefactor)
                        psth_ax.plot(binsStartTime[sSlice],smoothPSTH[sSlice], color = clusterColor, lw=2)
                        psth_ax.set_xlim(timeRange)
                    elif plotType[indSession] == 'tuning':
                        trialsEachCond = behavioranalysis.find_trials_each_type(freqEachTrial, np.unique(freqEachTrial))
                        # spikeArray = dataplotter.avg_spikes_in_event_locked_timerange_each_cond(spikeTimestamps, trialsEachCond, eventOnsetTimes, timeRange=tuningTimeRange)
                        spikeArray = self.avg_spikes_in_event_locked_timerange_each_cond(spikeTimestamps, trialsEachCond, eventOnsetTimes, timeRange=tuningTimeRange)
                        psth_ax.plot(spikeArray, ls='-', lw=2, color = clusterColor)
                        psth_ax.set_xticks(range(len(np.unique(freqEachTrial))))
                        psth_ax.set_xticklabels(freqLabels,fontsize=8)
                    psth_ax.hold(1)
                    psth_ax.axvline(x=0, color='k')
                    if indt==0:
                        psth_ax.set_title(allSessionType[indSession])

                    crow = indc/3 + (indt*2)
                    ccolStart = (indc%3)*2
                    ccolEnd = ccolStart+2

                    if indSession==0:
                        cluster_ax = plt.subplot(gs[crow, ccolStart:ccolEnd])
                        # print 'r{}c{} : Cluster {}, {} spikes'.format(crow, ccolStart, cluster, len(spikeData.timestamps))
                        plot_colored_waveforms(ephysData['samples'], clusterColor, ax=cluster_ax)

        plt.show()
def main():
    global behavSession
    global subject
    global ephysSession
    global tetrode
    global cluster
    global bdata
    global eventOnsetTimes
    global spikeTimesFromEventOnset
    global indexLimitsEachTrial
    global spikeTimesFromMovementOnset
    global indexLimitsEachMovementTrial
    global tuningBehavior#behavior file name of tuning curve
    global tuningEphys#ephys session name of tuning curve

    print 'psycurve_tuning_report'

    for cellID in range(0,numOfCells):
            oneCell = allcells.cellDB[cellID]##########!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        #try:#######################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            if (behavSession != oneCell.behavSession):


                subject = oneCell.animalName
                behavSession = oneCell.behavSession
                ephysSession = oneCell.ephysSession
                ephysRoot = os.path.join(ephysRootDir,subject)
                tuningBehavior = oneCell.tuningBehavior
                tuningEphys = oneCell.tuningSession

                print behavSession

                # -- Load Behavior Data --
                behaviorFilename = loadbehavior.path_to_behavior_data(subject=subject,paradigm=paradigm,sessionstr=behavSession)
                bdata = loadbehavior.BehaviorData(behaviorFilename)
                numberOfTrials = len(bdata['choice'])
                #print 'numberTrials ',numberOfTrials############################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

                # -- Load event data and convert event timestamps to ms --
                ephysDir = os.path.join(ephysRoot, ephysSession)
                eventFilename=os.path.join(ephysDir, 'all_channels.events')
                events = loadopenephys.Events(eventFilename) # Load events data
                eventTimes=np.array(events.timestamps)/SAMPLING_RATE #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and 

                soundOnsetEvents = (events.eventID==1) & (events.eventChannel==soundTriggerChannel)

                eventOnsetTimes = eventTimes[soundOnsetEvents]
                soundOnsetTimeBehav = bdata['timeTarget']

                # Find missing trials
                missingTrials = behavioranalysis.find_missing_trials(eventOnsetTimes,soundOnsetTimeBehav)
                #print 'missing ',len(missingTrials)############################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                # Remove missing trials
                bdata.remove_trials(missingTrials)


                possibleFreq = np.unique(bdata['targetFrequency'])
                numberOfFrequencies = len(possibleFreq)
                centerFrequencies = [(numberOfFrequencies/2-1),numberOfFrequencies/2]

                #################################################################################################
                centerOutTimes = bdata['timeCenterOut'] #This is the times that the mouse goes out of the center port
                soundStartTimes = bdata['timeTarget'] #This gives an array with the times in seconds from the start of the behavior paradigm of when the sound was presented for each trial
                timeDiff = centerOutTimes - soundStartTimes
                #print 'timeDiff ',len(timeDiff)############################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                #print 'eventOnsetTimes ',len(eventOnsetTimes)############################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                if (len(eventOnsetTimes) < len(timeDiff)):
                    eventOnsetTimesCenter = eventOnsetTimes + timeDiff[:-1]
                elif (len(eventOnsetTimes) > len(timeDiff)):
                    eventOnsetTimesCenter = eventOnsetTimes[:-1] + timeDiff
                else:
                    eventOnsetTimesCenter = eventOnsetTimes + timeDiff
                #################################################################################################


            tetrode = oneCell.tetrode
            cluster = oneCell.cluster
            # -- Load Spike Data From Certain Cluster --
            spkData = ephyscore.CellData(oneCell)
            spkTimeStamps = spkData.spikes.timestamps

            (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
                spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange)

            (spikeTimesFromMovementOnset,movementTrialIndexForEachSpike,indexLimitsEachMovementTrial) = \
                spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimesCenter,timeRange)

            plt.clf()
            if (len(spkTimeStamps)>0):
                ax1 = plt.subplot2grid((numRows,numCols), ((numRows-sizeClusterPlot),0), colspan = (numCols/3))
                spikesorting.plot_isi_loghist(spkData.spikes.timestamps)
                ax3 = plt.subplot2grid((numRows,numCols), ((numRows-sizeClusterPlot),(numCols/3)*2), colspan = (numCols/3))
                spikesorting.plot_events_in_time(spkData.spikes.timestamps)
                samples = spkData.spikes.samples.astype(float)-2**15
                samples = (1000.0/spkData.spikes.gain[0,0]) *samples
                ax2 = plt.subplot2grid((numRows,numCols), ((numRows-sizeClusterPlot),(numCols/3)), colspan = (numCols/3))
                spikesorting.plot_waveforms(samples)


            ###############################################################################
            ax4 = plt.subplot2grid((numRows,numCols), (0,0), colspan = (numCols/2), rowspan = 3*sizeRasters)
            #plt.setp(ax4.get_xticklabels(), visible=False)
            #raster_sound_psycurve(centerFrequencies[0])
            raster_tuning(ax4)
            axvline(x=0, ymin=0, ymax=1, color='r')
            plt.gca().set_xlim(tuning_timeRange)

            #ax5 = plt.subplot2grid((7,6), (2,0), colspan = 3, sharex=ax4)
            #hist_sound_psycurve(centerFrequencies[0])

            ax6 = plt.subplot2grid((numRows,numCols), (0,(numCols/2)), colspan = (numCols/2), rowspan = sizeRasters)
            plt.setp(ax6.get_xticklabels(), visible=False)
            plt.setp(ax6.get_yticklabels(), visible=False)
            raster_sound_psycurve(centerFrequencies[0])
            plt.title('Frequency Top: '+str(possibleFreq[centerFrequencies[0]])+' Bottom: '+str(possibleFreq[centerFrequencies[1]]))
            
            ax7 = plt.subplot2grid((numRows,numCols), (sizeRasters,(numCols/2)), colspan = (numCols/2), rowspan = sizeHists, sharex=ax6)
            hist_sound_psycurve(centerFrequencies[0])
            ax7.yaxis.tick_right()
            ax7.yaxis.set_ticks_position('both')
            plt.setp(ax7.get_xticklabels(), visible=False)
            plt.gca().set_xlim(timeRange)

            #ax8 = plt.subplot2grid((7,6), (3,0), colspan = 3, rowspan = 2)
            #plt.setp(ax8.get_xticklabels(), visible=False)
            #raster_movement_psycurve(centerFrequencies[0])
            #ax9 = plt.subplot2grid((7,6), (5,0), colspan = 3, sharex=ax8)
            #hist_movement_psycurve(centerFrequencies[0])

            ax10 = plt.subplot2grid((numRows,numCols), ((sizeRasters+sizeHists),(numCols/2)), colspan = (numCols/2), rowspan = sizeRasters)
            plt.setp(ax10.get_xticklabels(), visible=False)
            plt.setp(ax10.get_yticklabels(), visible=False)
            raster_sound_psycurve(centerFrequencies[1])

            ax11 = plt.subplot2grid((numRows,numCols), ((2*sizeRasters+sizeHists),(numCols/2)), colspan = (numCols/2), rowspan = sizeHists, sharex=ax10)
            hist_sound_psycurve(centerFrequencies[1])
            ax11.yaxis.tick_right()
            ax11.yaxis.set_ticks_position('both')
            #plt.setp(ax11.get_yticklabels(), visible=False)
            plt.gca().set_xlim(timeRange)
            ###############################################################################
            #plt.tight_layout()
            
            modulation_index_psycurve(centerFrequencies)
            plt.suptitle(titleText)

            tetrodeClusterName = 'T'+str(oneCell.tetrode)+'c'+str(oneCell.cluster)
            plt.gcf().set_size_inches((8.5,11))
            figformat = 'png' #'png' #'pdf' #'svg'
            filename = 'report_centerFreq_%s_%s_%s.%s'%(subject,behavSession,tetrodeClusterName,figformat)
            fulloutputDir = outputDir+subject +'/'
            fullFileName = os.path.join(fulloutputDir,filename)

            directory = os.path.dirname(fulloutputDir)
            if not os.path.exists(directory):
                os.makedirs(directory)
            #print 'saving figure to %s'%fullFileName
            plt.gcf().savefig(fullFileName,format=figformat)

            #plt.show()

        #except:##############################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        #print "error with session "+oneCell.behavSession
            #if (oneCell.behavSession not in badSessionList):####################!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                #badSessionList.append(oneCell.behavSession)#######################!!!!!!!!!!!!!!!!!!!!!!

    print 'error with sessions: '
    for badSes in badSessionList:
        print badSes
Exemplo n.º 43
0
def main():
    global behavSession
    global subject
    global tetrode
    global cluster
    global bdata
    global eventOnsetTimes
    global spikeTimesFromEventOnset
    global indexLimitsEachTrial
    global spikeTimesFromMovementOnset
    global indexLimitsEachMovementTrial
    global titleText

    print "SwitchingReport"
    for cellID in range(0,numOfCells):
        oneCell = allcells.cellDB[cellID]
        if (behavSession != oneCell.behavSession):


            subject = oneCell.animalName
            behavSession = oneCell.behavSession
            ephysSession = oneCell.ephysSession
            ephysRoot = os.path.join(ephysRootDir,subject)

            print behavSession

            # -- Load Behavior Data --
            behaviorFilename = loadbehavior.path_to_behavior_data(subject,experimenter,paradigm,behavSession)
            bdata = loadbehavior.FlexCategBehaviorData(behaviorFilename)
            #bdata = loadbehavior.BehaviorData(behaviorFilename)
            bdata.find_trials_each_block()
            numberOfTrials = len(bdata['choice'])

            # -- Load event data and convert event timestamps to ms --
            ephysDir = os.path.join(ephysRoot, ephysSession)
            eventFilename=os.path.join(ephysDir, 'all_channels.events')
            events = loadopenephys.Events(eventFilename) # Load events data
            eventTimes=np.array(events.timestamps)/SAMPLING_RATE #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and 

            soundOnsetEvents = (events.eventID==1) & (events.eventChannel==soundTriggerChannel)

            eventOnsetTimes = eventTimes[soundOnsetEvents]

            ###############################################################################################
            centerOutTimes = bdata['timeCenterOut'] #This is the times that the mouse goes out of the center port
            soundStartTimes = bdata['timeTarget'] #This gives an array with the times in seconds from the start of the behavior paradigm of when the sound was presented for each trial
            timeDiff = centerOutTimes - soundStartTimes
            if (len(eventOnsetTimes) < len(timeDiff)):
                timeDiff = timeDiff[:-1]
            eventOnsetTimesCenter = eventOnsetTimes + timeDiff
            ###############################################################################################


        tetrode = oneCell.tetrode
        cluster = oneCell.cluster


        # -- Load Spike Data From Certain Cluster --
        spkData = ephyscore.CellData(oneCell)
        spkTimeStamps = spkData.spikes.timestamps

        (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
            spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange)

        (spikeTimesFromMovementOnset,movementTrialIndexForEachSpike,indexLimitsEachMovementTrial) = \
            spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimesCenter,timeRange)


        plt.clf()
        if (len(spkTimeStamps)>0):
            ax1 = plt.subplot2grid((numRows,numCols), ((numRows-sizeClusterPlot),0), colspan = (numCols/3))
            spikesorting.plot_isi_loghist(spkData.spikes.timestamps)
            ax3 = plt.subplot2grid((numRows,numCols), ((numRows-sizeClusterPlot),(numCols/3)*2), colspan = (numCols/3))
            spikesorting.plot_events_in_time(spkTimeStamps)
            samples = spkData.spikes.samples.astype(float)-2**15
            samples = (1000.0/spkData.spikes.gain[0,0]) *samples
            ax2 = plt.subplot2grid((numRows,numCols), ((numRows-sizeClusterPlot),(numCols/3)), colspan = (numCols/3))
            spikesorting.plot_waveforms(samples)


        ###############################################################################
        ax4 = plt.subplot2grid((numRows,numCols), (0,0), colspan = (numCols/2), rowspan = sizeRasters)
        raster_sound_block_switching()
        ax5 = plt.subplot2grid((numRows,numCols), (sizeRasters,0), colspan = (numCols/2), rowspan = sizeHists)
        hist_sound_block_switching()
        ax6 = plt.subplot2grid((numRows,numCols), (0,(numCols/2)), colspan = (numCols/2), rowspan = sizeRasters)
        raster_movement_block_switching()
        ax7 = plt.subplot2grid((numRows,numCols), (sizeRasters,(numCols/2)), colspan = (numCols/2), rowspan = sizeHists)
        hist_movement_block_switching()

        ax8 = plt.subplot2grid((numRows,numCols), ((sizeRasters+sizeHists),0), colspan = (numCols/2), rowspan = sizeRasters)
        raster_sound_allFreq_switching()     
        ax9 = plt.subplot2grid((numRows,numCols), ((2*sizeRasters+sizeHists),0), colspan = (numCols/2), rowspan = sizeHists)
        hist_sound_allFreq_switching()
        ax10 = plt.subplot2grid((numRows,numCols), ((sizeRasters+sizeHists),(numCols/2)), colspan = (numCols/2), rowspan = sizeRasters) 
        raster_sound_switching()
        ax11 = plt.subplot2grid((numRows,numCols), ((2*sizeRasters+sizeHists),(numCols/2)), colspan = (numCols/2), rowspan = sizeHists) 
        hist_sound_switching()
        ###############################################################################
        #plt.tight_layout()
        modulation_index_switching()
        plt.suptitle(titleText)

        tetrodeClusterName = 'T'+str(oneCell.tetrode)+'c'+str(oneCell.cluster)
        plt.gcf().set_size_inches((8.5,11))
        figformat = 'png' #'png' #'pdf' #'svg'
        filename = 'report_%s_%s_%s.%s'%(subject,behavSession,tetrodeClusterName,figformat)
        fulloutputDir = outputDir+subject +'/'
        fullFileName = os.path.join(fulloutputDir,filename)

        directory = os.path.dirname(fulloutputDir)
        if not os.path.exists(directory): #makes sure output folder exists
            os.makedirs(directory)
        #print 'saving figure to %s'%fullFileName
        plt.gcf().savefig(fullFileName,format=figformat)
Exemplo n.º 44
0
def overall_muscimol_performance(animal, muscimolSessions, salineSessions):

    '''
    DEPRECATED
    Plot psychometric and average performance reports for muscimol experiments
    INCOMPLETE: hard coded for chords and modulations right now. 
    '''

    #Plot the psycurves
    subplot(221)
    muscimol_plot_sound_type(animal, muscimolSessions, salineSessions, 'chords')

    subplot(223)
    muscimol_plot_sound_type(animal, muscimolSessions, salineSessions, 'amp_mod')


    #Overall muscimol and saline performance
    muscimolData = behavioranalysis.load_many_sessions(animal, muscimolSessions)
    muscimolChords = percent_correct_sound_type(muscimolData, 'chords')
    muscimolMod = percent_correct_sound_type(muscimolData, 'amp_mod')

    salineData = behavioranalysis.load_many_sessions(animal, salineSessions)
    salineChords = percent_correct_sound_type(salineData, 'chords')
    salineMod = percent_correct_sound_type(salineData, 'amp_mod')


    #Individual session muscimol and saline performance

    for indp, pair in enumerate(zip(salineSessions, muscimolSessions)):

        salineFile = loadbehavior.path_to_behavior_data(animal,settings.DEFAULT_EXPERIMENTER,'2afc',pair[0])
        salineData = loadbehavior.BehaviorData(salineFile,readmode='full')

        salineChords = percent_correct_sound_type(salineData, 'chords')
        salineMod = percent_correct_sound_type(salineData, 'amp_mod')

        muscimolFile = loadbehavior.path_to_behavior_data(animal,settings.DEFAULT_EXPERIMENTER,'2afc',pair[1])
        muscimolData = loadbehavior.BehaviorData(muscimolFile,readmode='full')

        muscimolChords = percent_correct_sound_type(muscimolData, 'chords')
        muscimolMod = percent_correct_sound_type(muscimolData, 'amp_mod')

        if indp==0:
            allPerfChords = array([salineChords, muscimolChords])
        else:
            allPerfChords = vstack([allPerfChords, array([salineChords, muscimolChords])])

        if indp==0:
            allPerfMod = array([salineMod, muscimolMod])
        else:
            allPerfMod = vstack([allPerfMod, array([salineMod, muscimolMod])])

    ## -- Chords performance
    subplot(222)
    bar([0, 1], [salineChords, muscimolChords], width=0.5, facecolor='w', edgecolor='k', linewidth = 2)
    #plot lines
    # for expt in allPerfChords:
    #     plot([0.25, 1.25], expt, '0.3', lw=2)

    #Plot points
    for point in allPerfChords[:,0]:
        plot(0.25, point, 'ko', ms=7)
    for point in allPerfChords[:,1]:
        plot(1.25, point, 'ro', ms=7)

    xlim([-0.5, 2])
    xticks([0.25, 1.25])
    ax = gca()
    ax.set_xticklabels(['Saline', 'Muscimol'])
    ylim([0, 100])
    ylabel('Percent Correct')

    ## -- Amp mod performance
    subplot(224)
    bar([0, 1], [salineMod, muscimolMod], width=0.5, facecolor='w', edgecolor='k', linewidth = 2)
    # for expt in allPerfMod:
    #     plot([0.25, 1.25], expt, '0.3', lw=2)

    #Plot points
    for point in allPerfMod[:,0]:
        plot(0.25, point, 'ko', ms=7)
    for point in allPerfMod[:,1]:
        plot(1.25, point, 'ro', ms=7)

    xlim([-0.5, 2])
    xticks([0.25, 1.25])
    ax = gca()
    ax.set_xticklabels(['Saline', 'Muscimol'])
    ylim([0, 100])
    ylabel('Percent Correct')

    return (allPerfChords, allPerfMod)
Exemplo n.º 45
0
qualityList = [1]
minZVal = 3.0
maxISIviolation = 0.02
'''

cellID = allcells.cellDB.findcell(mouseName, behavSession, tetrode, cluster)
oneCell = allcells.cellDB[cellID]
subject = oneCell.animalName

behavSession = oneCell.behavSession
ephysSession = oneCell.ephysSession
ephysRoot = os.path.join(ephysRootDir, subject)

# -- Load Behavior Data --
behaviorFilename = loadbehavior.path_to_behavior_data(subject=subject,
                                                      paradigm=paradigm,
                                                      sessionstr=behavSession)
bdata = loadbehavior.FlexCategBehaviorData(behaviorFilename)
bdata.find_trials_each_block()

# -- Load event data and convert event timestamps to ms --
ephysDir = os.path.join(ephysRoot, ephysSession)
eventFilename = os.path.join(ephysDir, 'all_channels.events')
events = loadopenephys.Events(eventFilename)  # Load events data
eventTimes = np.array(events.timestamps) / SAMPLING_RATE

soundOnsetEvents = (events.eventID == 1) & (events.eventChannel
                                            == soundTriggerChannel)

eventOnsetTimes = eventTimes[soundOnsetEvents]
Exemplo n.º 46
0
from jaratoolbox import behavioranalysis
from jaratoolbox import loadbehavior
import numpy as np
from pylab import *
import matplotlib.pyplot as plt
from statsmodels.stats.proportion import proportion_confint  #Used to compute confidence interval for the error bars.
from jaratoolbox import settings

subjects = ['hm4d004', 'hm4d005', 'hm4d006']
session = '20140826a'
positions = [(0, 0), (0, 1), (1, 0),
             (1, 1)]  #FIXME: can only place 4 mice for now

for ind, subject in enumerate(subjects):  #Iterate through each subject
    fname = loadbehavior.path_to_behavior_data(subject, 'nick', '2afc',
                                               session)

    try:  #Attempt to load the data for this subject

        bdata = loadbehavior.BehaviorData(fname)

    except IOError:  #If the data from this subject is not available:

        ax1 = plt.subplot2grid((2, 2), positions[ind])  #Alert the user
        xlim([0, 2])
        ylim([0, 2])
        ax1.text(1,
                 1,
                 "No Data Available",
                 va='center',
                 ha='center',
Exemplo n.º 47
0
Santiago Jaramillo - 2016-04-15
'''

from jaratoolbox import settings
from jaratoolbox import loadbehavior
from jaratoolbox import behavioranalysis
import matplotlib.pyplot as plt

EXPERIMENTER = settings.DEFAULT_EXPERIMENTER
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]]
Exemplo n.º 48
0
    def plot_array_raster(self, session, experiment=-1, site=-1, tetrodes=None, replace=0, sortArray='currentFreq', timeRange = [-0.5, 1], ms=4, electrodeName='Tetrode'):
        '''
        Plot rasters for each tetrode, for a single recording session.
        Args:
            session (index): The index of the session to cluster.
            experiment (index): The index of the experiment to get the site from.
            site (index): The index of the site to pull sessions from.
            tetrodes (list of int): The tetrodes to plot. Defaults to all siteObj.tetrodes
            replace (bool): True clears and uses the current figure. False makes a new figure.
            sortArray (string): Label of the bdata array used to sort the trials.
            timeRange (list): Time range around each event to align spikes.
            ms (float): matplotlib marker size for raster plots
            electrodeName (string): Name of spikes file should be {electrodeName}{electrodeNumber}.spikes
        Returns nothing - draws a figure.
        '''
        sessionObj = self.get_session_obj(session, experiment, site)
        sessionDir = sessionObj.ephys_dir()

        # behavFile = sessionObj.behav_filename()
        # if not behavFile:
        #     sortArray = []
        # else:
        #     bdata = self.loader.get_session_behavior(behavFile)
        #     sortArray = bdata[sortArray]

        behavClass = None #TODO: This should be an option somewhere.
        if behavClass == None:
            behavClass = loadbehavior.BehaviorData
        if sessionObj.behavsuffix is not None:
            dateStr = ''.join(sessionObj.date.split('-'))
            fullSessionStr = '{}{}'.format(dateStr, sessionObj.behavsuffix)
            behavDataFilePath = loadbehavior.path_to_behavior_data(sessionObj.subject,
                                                                sessionObj.paradigm,
                                                                fullSessionStr)
            bdata = behavClass(behavDataFilePath,readmode='full')
            sortArray = bdata[sortArray]
        else:
            sortArray = []

        if not tetrodes:
            tetrodes=sessionObj.tetrodes
        numTetrodes = len(tetrodes)

        # eventData = self.loader.get_session_events(sessionDir)
        # eventOnsetTimes = self.loader.get_event_onset_times(eventData)

        plotTitle = sessionDir
        if replace:
            fig = plt.gcf()
            plt.clf()
        else:
            fig = plt.figure()
        for ind , tetrode in enumerate(tetrodes):
            # spikeData = self.loader.get_session_spikes(sessionDir, tetrode)
            ephysData = ephyscore.load_ephys(sessionObj.subject, sessionObj.paradigm, sessionDir, tetrode)
            eventOnsetTimes = ephysData['events']['stimOn']
            spikeTimestamps = ephysData['spikeTimes']

            if ind == 0:
                ax = fig.add_subplot(numTetrodes,1,ind+1)
            else:
                ax = fig.add_subplot(numTetrodes,1,ind+1, sharex = fig.axes[0], sharey = fig.axes[0])
            # spikeTimestamps = spikeData.timestamps
            plot_raster(spikeTimestamps, eventOnsetTimes, sortArray=sortArray, ms=ms, timeRange = timeRange)
            if ind == 0:
                plt.title(plotTitle)
            plt.ylabel('TT {}'.format(tetrode))
        plt.xlabel('time (sec)')
        plt.show()
Exemplo n.º 49
0
stimOnsetFrame = stimOnsetFrame[:
                                -1]  # Remove last to avoid problems of not having full data
nEvents = len(stimOnsetFrame)

# -- Calculate response each trial --
ftraceEachTrial = np.empty([nCells, nEvents])

responseWindow = [0, 30]  # in frames
for indEvent, stimOnset in enumerate(stimOnsetFrame):
    # FIXME: I'm rounding the stimOnset. Not sure if this is the best option
    rangeLims = int(np.round(stimOnset)) + np.array(responseWindow)
    frameRange = np.arange(rangeLims[0], rangeLims[1])
    ftraceEachTrial[:, indEvent] = np.mean(ftraces[:, frameRange], axis=1)

# -- Load behavior --
behavFilename = loadbehavior.path_to_behavior_data(subject, paradigm,
                                                   behavSession)
bdata = loadbehavior.BehaviorData(behavFilename)
currentFreq = bdata['currentFreq']
if nEvents != len(currentFreq):
    currentFreq = currentFreq[:
                              nEvents]  #Events will stop sooner than behavior.
possibleFreq = np.unique(currentFreq)
nFreq = len(possibleFreq)
trialsEachType = behavioranalysis.find_trials_each_type(
    currentFreq, possibleFreq)

# -- Calculate response each freq --
respEachFreqMean = np.empty([nCells, nFreq])
respEachFreqStDev = np.empty([nCells, nFreq])
nTrialsEachFreq = np.sum(trialsEachType, axis=0)
for indf, oneFreq in enumerate(possibleFreq):
Exemplo n.º 50
0
    sessions = sys.argv[1:]

nSessions = len(sessions)
nAnimals = len(subjects)

loadingClass = loadbehavior.FlexCategBehaviorData  #using this bdata class so we get 'blocks'
paradigm = '2afc'

gs = gridspec.GridSpec(nSessions*nAnimals, 1)
gs.update(hspace=0.5,wspace=0.4)
plt.clf()

for inds,thisSession in enumerate(sessions):
    for inda,animalName in enumerate(subjects):
        try:
            behavFile = loadbehavior.path_to_behavior_data(animalName,EXPERIMENTER,paradigm,thisSession)
            behavData = loadingClass(behavFile,readmode='full')
        except IOError:
            print thisSession+' does not exist'
            continue
        print 'Loaded %s %s'%(animalName,thisSession)

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

        behavData.find_trials_each_block()
        trialsEachBlock = behavData.blocks['trialsEachBlock']
        #print trialsEachBlock
                maxZ_file.write("\n%s " % freq)
                for ZVal in maxZDict[behavSession][freq]:
                    maxZ_file.write("%s," % ZVal)
            maxZ_file.write("\n")

        # -- Start processing new session --
        subject = oneCell.animalName
        behavSession = oneCell.behavSession
        ephysSession = oneCell.ephysSession
        ephysRoot = os.path.join(ephysRootDir, subject)

        print oneCell.behavSession

        # -- Load Behavior Data --
        behaviorFilename = loadbehavior.path_to_behavior_data(
            subject, paradigm, behavSession
        )  #Omitted experimenter since data no longer stored in experimenter folder

        bdata = loadbehavior.BehaviorData(behaviorFilename)
        numberOfTrials = len(bdata['choice'])
        print "number of behavior trials ", numberOfTrials

        # -- Load event data and convert event timestamps to ms --
        ephysDir = os.path.join(ephysRoot, ephysSession)
        eventFilename = os.path.join(ephysDir, 'all_channels.events')
        events = loadopenephys.Events(eventFilename)  # Load events data
        eventTimes = np.array(
            events.timestamps
        ) / SAMPLING_RATE  #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and

        soundOnsetEvents = (events.eventID == 1) & (events.eventChannel
Exemplo n.º 52
0
def raster_sound_psycurve(animalName):
    oneCell = allcells.cellDB[cellID]
    if (behavSession != oneCell.behavSession):


        subject = oneCell.animalName
        behavSession = oneCell.behavSession
        ephysSession = oneCell.ephysSession
        ephysRoot = os.path.join(ephysRootDir,subject)

        # -- Load Behavior Data --
        behaviorFilename = loadbehavior.path_to_behavior_data(subject,experimenter,paradigm,behavSession)
        bdata = loadbehavior.BehaviorData(behaviorFilename)
        numberOfTrials = len(bdata['choice'])

        # -- Load event data and convert event timestamps to ms --
        ephysDir = os.path.join(ephysRoot, ephysSession)
        eventFilename=os.path.join(ephysDir, 'all_channels.events')
        events = loadopenephys.Events(eventFilename) # Load events data
        eventTimes=np.array(events.timestamps)/SAMPLING_RATE #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and 

        soundOnsetEvents = (events.eventID==1) & (events.eventChannel==soundTriggerChannel)


        eventOnsetTimes = eventTimes[soundOnsetEvents]

        rightward = bdata['choice']==bdata.labels['choice']['right']
        leftward = bdata['choice']==bdata.labels['choice']['left']
        invalid = bdata['outcome']==bdata.labels['outcome']['invalid']

        possibleFreq = np.unique(bdata['targetFrequency'])
        numberOfFrequencies = len(possibleFreq)



    # -- Load Spike Data From Certain Cluster --
    spkData = ephyscore.CellData(oneCell)
    spkTimeStamps = spkData.spikes.timestamps

    (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
        spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange)

    for Frequency in range(numberOfFrequencies):

        Freq = possibleFreq[Frequency]
        oneFreq = bdata['targetFrequency'] == Freq

        trialsToUseRight = rightward & oneFreq
        trialsToUseLeft = leftward & oneFreq

        trialsEachCond = np.c_[trialsToUseLeft,trialsToUseRight]; colorEachCond = ['r','g']

        plt.clf()
        ax1 =  plt.subplot2grid((3,1), (0, 0), rowspan=2)
        extraplots.raster_plot(spikeTimesFromEventOnset,indexLimitsEachTrial,timeRange,trialsEachCond=trialsEachCond,colorEachCond=colorEachCond,fillWidth=None,labels=None)

        plt.ylabel('Trials')

        timeVec = np.arange(timeRange[0],timeRange[-1],binWidth)
        spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,timeVec)

        smoothWinSize = 3
        ax2 = plt.subplot2grid((3,1), (2, 0), sharex=ax1)

        extraplots.plot_psth(spikeCountMat/binWidth,smoothWinSize,timeVec,trialsEachCond=trialsEachCond,
                             colorEachCond=colorEachCond,linestyle=None,linewidth=3,downsamplefactor=1)

        plt.xlabel('Time from sound onset (s)')
        plt.ylabel('Firing rate (spk/sec)')
        
        if ((Frequency == numberOfFrequencies/2) or (Frequency == (numberOfFrequencies/2 - 1))):
                freqFile = 'Center_Frequencies'
        else:
                freqFile = 'Outside_Frequencies'
        tetrodeClusterName = 'T'+str(oneCell.tetrode)+'c'+str(oneCell.cluster)
        plt.gcf().set_size_inches((8.5,11))
        figformat = 'png' #'png' #'pdf' #'svg'
        filename = 'rast_%s_%s_%s_%s.%s'%(subject,behavSession,Freq,tetrodeClusterName,figformat)
        fulloutputDir = outputDir+subject+'/'+ freqFile +'/'
        fullFileName = os.path.join(fulloutputDir,filename)

        directory = os.path.dirname(fulloutputDir)
        if not os.path.exists(directory):
            os.makedirs(directory)
        print 'saving figure to %s'%fullFileName
        plt.gcf().savefig(fullFileName,format=figformat)
Exemplo n.º 53
0
def main():
    global behavSession
    global subject
    global ephysSession
    global tetrodeID
    global bdata
    global eventOnsetTimes
    global spikeTimesFromEventOnset
    global indexLimitsEachTrial
    global spikeTimesFromMovementOnset
    global indexLimitsEachMovementTrial
    for cellID in range(0, numOfCells):
        oneCell = allcells.cellDB[cellID]
        try:
            if (behavSession != oneCell.behavSession):

                subject = oneCell.animalName
                behavSession = oneCell.behavSession
                ephysSession = oneCell.ephysSession
                ephysRoot = os.path.join(ephysRootDir, subject)

                print behavSession

                # -- Load Behavior Data --
                behaviorFilename = loadbehavior.path_to_behavior_data(
                    subject, experimenter, paradigm, behavSession)
                bdata = loadbehavior.BehaviorData(behaviorFilename)
                numberOfTrials = len(bdata['choice'])

                # -- Load event data and convert event timestamps to ms --
                ephysDir = os.path.join(ephysRoot, ephysSession)
                eventFilename = os.path.join(ephysDir, 'all_channels.events')
                events = loadopenephys.Events(
                    eventFilename)  # Load events data
                eventTimes = np.array(
                    events.timestamps
                ) / SAMPLING_RATE  #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and

                soundOnsetEvents = (events.eventID == 1) & (
                    events.eventChannel == soundTriggerChannel)

                eventOnsetTimes = eventTimes[soundOnsetEvents]

                possibleFreq = np.unique(bdata['targetFrequency'])
                numberOfFrequencies = len(possibleFreq)
                centerFrequencies = [(numberOfFrequencies / 2 - 1),
                                     numberOfFrequencies / 2]

                #################################################################################################
                centerOutTimes = bdata[
                    'timeCenterOut']  #This is the times that the mouse goes out of the center port
                soundStartTimes = bdata[
                    'timeTarget']  #This gives an array with the times in seconds from the start of the behavior paradigm of when the sound was presented for each trial
                timeDiff = centerOutTimes - soundStartTimes
                if (len(eventOnsetTimes) < len(timeDiff)):
                    timeDiff = timeDiff[:-1]
                eventOnsetTimesCenter = eventOnsetTimes + timeDiff
                #################################################################################################

            # -- Load Spike Data From Certain Cluster --
            spkData = ephyscore.CellData(oneCell)
            spkTimeStamps = spkData.spikes.timestamps

            (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
                spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange)

            (spikeTimesFromMovementOnset,movementTrialIndexForEachSpike,indexLimitsEachMovementTrial) = \
                spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimesCenter,timeRange)

            plt.clf()
            if (len(spkTimeStamps) > 0):
                ax1 = plt.subplot2grid((7, 6), (6, 0), colspan=2)
                spikesorting.plot_isi_loghist(spkData.spikes.timestamps)
                ax3 = plt.subplot2grid((7, 6), (6, 4), colspan=2)
                spikesorting.plot_events_in_time(spkData.spikes.timestamps)
                samples = spkData.spikes.samples.astype(float) - 2**15
                samples = (1000.0 / spkData.spikes.gain[0, 0]) * samples
                ax2 = plt.subplot2grid((7, 6), (6, 2), colspan=2)
                spikesorting.plot_waveforms(samples)

            ###############################################################################
            ax4 = plt.subplot2grid((7, 6), (0, 0), colspan=3, rowspan=2)
            raster_sound_psycurve(centerFrequencies[0])
            ax5 = plt.subplot2grid((7, 6), (2, 0), colspan=3)
            hist_sound_psycurve(centerFrequencies[0])
            ax6 = plt.subplot2grid((7, 6), (0, 3), colspan=3, rowspan=2)
            raster_sound_psycurve(centerFrequencies[1])
            ax7 = plt.subplot2grid((7, 6), (2, 3), colspan=3)
            hist_sound_psycurve(centerFrequencies[1])

            ax8 = plt.subplot2grid((7, 6), (3, 0), colspan=3, rowspan=2)
            raster_movement_psycurve(centerFrequencies[0])
            ax9 = plt.subplot2grid((7, 6), (5, 0), colspan=3)
            hist_movement_psycurve(centerFrequencies[0])
            ax10 = plt.subplot2grid((7, 6), (3, 3), colspan=3, rowspan=2)
            raster_movement_psycurve(centerFrequencies[1])
            ax11 = plt.subplot2grid((7, 6), (5, 3), colspan=3)
            hist_movement_psycurve(centerFrequencies[1])
            ###############################################################################
            #plt.tight_layout()

            tetrodeClusterName = 'T' + str(oneCell.tetrode) + 'c' + str(
                oneCell.cluster)
            plt.gcf().set_size_inches((8.5, 11))
            figformat = 'png'  #'png' #'pdf' #'svg'
            filename = 'report_centerFreq_%s_%s_%s.%s' % (
                subject, behavSession, tetrodeClusterName, figformat)
            fulloutputDir = outputDir + subject + '/'
            fullFileName = os.path.join(fulloutputDir, filename)

            directory = os.path.dirname(fulloutputDir)
            if not os.path.exists(directory):
                os.makedirs(directory)
            #print 'saving figure to %s'%fullFileName
            plt.gcf().savefig(fullFileName, format=figformat)

            #plt.show()

        except:
            #print "error with session "+oneCell.behavSession
            if (oneCell.behavSession not in badSessionList):
                badSessionList.append(oneCell.behavSession)

    print 'error with sessions: '
    for badSes in badSessionList:
        print badSes
    oneCell = allcells.cellDB[cellID]

    if (oneCell.behavSession in modIList): #checks to make sure the modI value is not recalculated
        continue
    try:
        if (behavSession != oneCell.behavSession):

            subject = oneCell.animalName
            behavSession = oneCell.behavSession
            ephysSession = oneCell.ephysSession
            ephysRoot = os.path.join(ephysRootDir,subject)

            print behavSession

            # -- Load Behavior Data --
            behaviorFilename = loadbehavior.path_to_behavior_data(subject,experimenter,paradigm,behavSession)
            bdata = loadbehavior.BehaviorData(behaviorFilename)

            # -- Load event data and convert event timestamps to ms --
            ephysDir = os.path.join(ephysRoot, ephysSession)
            eventFilename=os.path.join(ephysDir, 'all_channels.events')
            events = loadopenephys.Events(eventFilename) # Load events data
            eventTimes=np.array(events.timestamps)/SAMPLING_RATE #get array of timestamps for each event and convert to seconds by dividing by sampling rate (Hz). matches with eventID and 

            soundOnsetEvents = (events.eventID==1) & (events.eventChannel==soundTriggerChannel)

            eventOnsetTimes = eventTimes[soundOnsetEvents]

            rightward = bdata['choice']==bdata.labels['choice']['right']
            leftward = bdata['choice']==bdata.labels['choice']['left']
            valid = (bdata['outcome']==bdata.labels['outcome']['correct'])|(bdata['outcome']==bdata.labels['outcome']['error'])
def load_many_sessions(animalNames,
                       sessions,
                       paradigm='2afc',
                       datesRange=None):
    '''
    Based on behavioranalysis.save_many_sessions_reversal()

    TO DO:
    - Add params='all', (it depends on loadbehavior.FlexCateg being able to load a subset of vars)
    - What to do if a parameter only exists for some sessions?
    '''
    if isinstance(animalNames, str):
        animalNames = [animalNames]
    if datesRange:
        datesLims = [parse_isodate(dateStr) for dateStr in datesRange]
        allDates = [datesLims[0]+datetime.timedelta(n) \
                        for n in range((datesLims[-1]-datesLims[0]).days+1)]
        allSessions = [oneDate.strftime('%Y%m%da') for oneDate in allDates]
    else:
        allSessions = sessions
    nAnimals = len(animalNames)
    if paradigm == '2afc':
        loadingClass = loadbehavior.FlexCategBehaviorData
    else:
        raise TypeError(
            'Loading many sessions for that paradigm has not been implemented')

    #if params=='all':
    #    readmode = 'full'
    #else:
    #    readmode = params
    readmode = 'full'

    #allBehavData = {}
    #allBehavData['sessionID'] = np.empty(0,dtype='i2')
    #allBehavData['animalID'] = np.empty(0,dtype='i1')

    inds = 0
    for inda, animalName in enumerate(animalNames):
        for indsa, thisSession in enumerate(allSessions):
            try:
                behavFile = loadbehavior.path_to_behavior_data(
                    animalName, EXPERIMENTER, paradigm, thisSession)
                behavData = loadingClass(behavFile, readmode=readmode)
            except IOError:
                print thisSession + ' does not exist'
                continue
            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):
                        allBehavData[key] = val
                    else:
                        allBehavData[key] = np.concatenate(
                            (allBehavData[key], val))
                nTrials = len(behavData['outcome']
                              )  # FIXME: what if this key does not exist?
                allBehavData['sessionID'] = np.concatenate(
                    (allBehavData['sessionID'], np.tile(inds, nTrials)))
                allBehavData['animalID'] = np.concatenate(
                    (allBehavData['animalID'], np.tile(inda, nTrials)))
            inds += 1
    return allBehavData