Exemplo n.º 1
0
def modulation_index_switching():
    global spikeTimesFromEventOnset
    global indexLimitsEachTrial
    global bdata
    global titleText
    stimulusRange = [0.0, 0.1]  #This is the length of the stimulus in seconds
    Frequency = 1  #This is the middle frequency

    rightward = bdata['choice'] == bdata.labels['choice']['right']
    leftward = bdata['choice'] == bdata.labels['choice']['left']
    invalid = bdata['outcome'] == bdata.labels['outcome']['invalid']
    correct = bdata['outcome'] == bdata.labels['outcome']['correct']
    correctRightward = rightward & correct
    correctLeftward = leftward & correct

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

    trialsToUseRight = correctRightward & oneFreq
    trialsToUseLeft = correctLeftward & oneFreq

    trialsEachCond = [trialsToUseRight, trialsToUseLeft]

    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimesFromEventOnset, indexLimitsEachTrial, stimulusRange)
    spikeCountEachTrial = spikeCountMat.flatten()
    spikeAvgRight = sum(spikeCountEachTrial[trialsToUseRight]) / float(
        sum(trialsToUseRight))
    spikeAvgLeft = sum(spikeCountEachTrial[trialsToUseLeft]) / float(
        sum(trialsToUseLeft))
    if ((spikeAvgRight + spikeAvgLeft) == 0):
        modInd = 0
    else:
        modInd = (spikeAvgRight - spikeAvgLeft) / (spikeAvgRight +
                                                   spikeAvgLeft)

    mod_sig = spikesanalysis.evaluate_modulation(spikeTimesFromEventOnset,
                                                 indexLimitsEachTrial,
                                                 stimulusRange, trialsEachCond)

    titleText = 'Modulation Index: ' + str(round(
        modInd, 3)) + ', significance (p value): ' + str(round(mod_sig[1], 3))
Exemplo n.º 2
0
def modulation_index_switching():
    global spikeTimesFromEventOnset
    global indexLimitsEachTrial
    global bdata
    global titleText
    stimulusRange = [0.0,0.1] #This is the length of the stimulus in seconds
    Frequency = 1 #This is the middle frequency


    rightward = bdata['choice']==bdata.labels['choice']['right']
    leftward = bdata['choice']==bdata.labels['choice']['left']
    invalid = bdata['outcome']==bdata.labels['outcome']['invalid']
    correct = bdata['outcome']==bdata.labels['outcome']['correct']
    correctRightward = rightward & correct
    correctLeftward = leftward & correct

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

    trialsToUseRight = correctRightward & oneFreq
    trialsToUseLeft = correctLeftward & oneFreq


    trialsEachCond = [trialsToUseRight,trialsToUseLeft]


    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,stimulusRange)
    spikeCountEachTrial = spikeCountMat.flatten()
    spikeAvgRight = sum(spikeCountEachTrial[trialsToUseRight])/float(sum(trialsToUseRight))
    spikeAvgLeft = sum(spikeCountEachTrial[trialsToUseLeft])/float(sum(trialsToUseLeft))
    if ((spikeAvgRight + spikeAvgLeft) == 0):
        modInd = 0
    else:
        modInd = (spikeAvgRight - spikeAvgLeft)/(spikeAvgRight + spikeAvgLeft)

    mod_sig = spikesanalysis.evaluate_modulation(spikeTimesFromEventOnset,indexLimitsEachTrial,stimulusRange,trialsEachCond)

    titleText = 'Modulation Index: '+str(round(modInd,3))+', significance (p value): '+ str(round(mod_sig[1],3))
Exemplo n.º 3
0
                curModDirection = 'down'
            elif (curBlockModI < blockModI):
                if (curModDirection == 'down'):
                    modDirectionScore +=1
                curModDirection = 'up'
            curBlockModI = blockModI


        spikeAvgRight = sum(spikeCountEachTrial[trialsToUseRight])/float(sum(trialsToUseRight))
        spikeAvgLeft = sum(spikeCountEachTrial[trialsToUseLeft])/float(sum(trialsToUseLeft))

        if ((spikeAvgRight + spikeAvgLeft) == 0):
            modIDict[behavSession][clusterNumber] = 0.0
            modSigDict[behavSession][clusterNumber] = 1.0
        else:
            mod_sig = spikesanalysis.evaluate_modulation(spikeTimesFromEventOnset,indexLimitsEachTrial,stimulusRange,trialsEachCond)
            currentMI = (spikeAvgRight - spikeAvgLeft)/(spikeAvgRight + spikeAvgLeft)
            modIDict[behavSession][clusterNumber] = currentMI
            modSigDict[behavSession][clusterNumber] = mod_sig[1]

        modDirectionScoreDict[behavSession][clusterNumber] = modDirectionScore

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

#########################################################################################
#This is the save all the values in a text file
#########################################################################################
bSessionList = []
for bSession in modIDict:
                if (curModDirection == 'down'):
                    modDirectionScore += 1
                curModDirection = 'up'
            curBlockModI = blockModI

        spikeAvgRight = sum(spikeCountEachTrial[trialsToUseRight]) / float(
            sum(trialsToUseRight))
        spikeAvgLeft = sum(spikeCountEachTrial[trialsToUseLeft]) / float(
            sum(trialsToUseLeft))

        if ((spikeAvgRight + spikeAvgLeft) == 0):
            modIDict[behavSession][clusterNumber] = 0.0
            modSigDict[behavSession][clusterNumber] = 1.0
        else:
            mod_sig = spikesanalysis.evaluate_modulation(
                spikeTimesFromEventOnset, indexLimitsEachTrial, stimulusRange,
                trialsEachCond)
            currentMI = (spikeAvgRight - spikeAvgLeft) / (spikeAvgRight +
                                                          spikeAvgLeft)
            modIDict[behavSession][clusterNumber] = currentMI
            modSigDict[behavSession][clusterNumber] = mod_sig[1]

        modDirectionScoreDict[behavSession][clusterNumber] = modDirectionScore

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

#########################################################################################
#This is the save all the values in a text file
#########################################################################################
def evaluate_movement_selectivity_celldb(cellDb,
                                         movementTimeRange,
                                         removeSideIn=False):
    '''
    Analyse 2afc data: calculate movement selectivity index and significance;
    movementTimeRange should be a list (in seconds, time from center-out).
    '''
    print 'Calculating movement selectivity index for 2afc session in time range: ' + str(
        movementTimeRange)

    movementModI = pd.Series(np.zeros(len(cellDb)),
                             index=cellDb.index)  #default value 0
    movementModS = pd.Series(np.ones(len(cellDb)),
                             index=cellDb.index)  #default value 1

    for indCell, cell in cellDb.iterrows():
        cellObj = ephyscore.Cell(cell)
        sessiontype = 'behavior'  #2afc behavior
        #ephysData, bata = cellObj.load(sessiontype)
        sessionInd = cellObj.get_session_inds(sessiontype)[0]
        bdata = cellObj.load_behavior_by_index(sessionInd)
        possibleFreq = np.unique(bdata['targetFrequency'])
        numFreqs = len(possibleFreq)

        try:
            ephysData = cellObj.load_ephys_by_index(sessionInd)
        except ValueError:
            continue

        eventsDict = ephysData['events']
        spikeTimestamps = ephysData['spikeTimes']

        if spikeTimestamps.ndim == 0:  #There is only one spike, ! spikesanalysis.eventlocked_spiketimes cannot handle only one spike !
            continue

        soundOnsetTimes = eventsDict['{}On'.format(soundChannelType)]
        soundOnsetTimeBehav = bdata['timeTarget']

        # -- Check to see if ephys and behav recordings have same number of trials, remove missing trials from behav file -- #
        # Find missing trials
        missingTrials = behavioranalysis.find_missing_trials(
            soundOnsetTimes, soundOnsetTimeBehav)
        # Remove missing trials
        bdata.remove_trials(missingTrials)

        if len(soundOnsetTimes) != len(
                bdata['timeTarget']
        ):  #some error not handled by remove missing trials
            continue

        # -- calculate movement selectivity -- #
        rightward = bdata['choice'] == bdata.labels['choice']['right']
        leftward = bdata['choice'] == bdata.labels['choice']['left']

        diffTimes = bdata['timeCenterOut'] - bdata['timeTarget']
        movementOnsetTimes = soundOnsetTimes + diffTimes

        responseTimesEachTrial = bdata['timeSideIn'] - bdata['timeCenterOut']
        responseTimesEachTrial[np.isnan(responseTimesEachTrial)] = 0
        sideInTrials = (responseTimesEachTrial <= movementTimeRange[-1])

        if removeSideIn:
            trialsToUseRight = rightward & (~sideInTrials)
            trialsToUseLeft = leftward & (~sideInTrials)
        else:
            trialsToUseRight = rightward
            trialsToUseLeft = leftward
        trialsEachCond = [trialsToUseLeft, trialsToUseRight]
        (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \
                spikesanalysis.eventlocked_spiketimes(spikeTimestamps,movementOnsetTimes,timeRange)

        spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
            spikeTimesFromEventOnset, indexLimitsEachTrial, movementTimeRange)

        spikeCountEachTrial = spikeCountMat.flatten()
        spikeAvgLeftward = np.mean(spikeCountEachTrial[leftward])
        spikeAvgRightward = np.mean(spikeCountEachTrial[rightward])

        if ((spikeAvgRightward + spikeAvgLeftward) == 0):
            movementModI[indCell] = 0.0
            movementModS[indCell] = 1.0

        else:
            movementModI[indCell] = ((spikeAvgRightward - spikeAvgLeftward) /
                                     (spikeAvgRightward + spikeAvgLeftward))
            movementModS[indCell] = spikesanalysis.evaluate_modulation(
                spikeTimesFromEventOnset, indexLimitsEachTrial,
                movementTimeRange, trialsEachCond)[1]

    return movementModI, movementModS
Exemplo n.º 6
0
                        countTimeRange
                    )  #spike counts in the window of interest for modulation
                    spikeCountEachTrial = spikeCountMat.flatten(
                    )  #spikeCountMat contains num of spikes in countTimeRange, each column is each trial, only one row because only given one time bin(countTimeRange)

                    # -- Calculate modulation index and significance p value -- #
                    spikeAvgRight = np.average(
                        spikeCountEachTrial[trialsToUseRight])
                    spikeAvgLeft = np.average(
                        spikeCountEachTrial[trialsToUseLeft])
                    if ((spikeAvgRight + spikeAvgLeft) == 0):
                        modIndex = 0.0
                        modSig = 1.0
                    else:
                        modSig = spikesanalysis.evaluate_modulation(
                            spikeTimesFromEventOnset, indexLimitsEachTrial,
                            countTimeRange, trialsEachCond)[1]
                        modIndex = (spikeAvgRight - spikeAvgLeft) / (
                            spikeAvgRight + spikeAvgLeft)
                    newTime = time.time()
                    print 'Elapsed time: {0:0.2f}  Calculated MOD INDEX & SIG'.format(
                        newTime - zeroTime)
                    zeroTime = newTime
                    sys.stdout.flush()  ### PROFILER
                    # -- Calculate modulation direction score -- #
                    ###### Interpret results: modulation direction score of 0 is when activity either just goes up or just goes down during the session #############
                    aveSpikesEachBlock = []
                    blockVec = np.zeros(len(bdata['currentBlock']))

                    for (start, end) in zip(firstTrialsEachBlock,
                                            lastTrialsEachBlock):
                    spikesanalysis.eventlocked_spiketimes(spikeTimestamps,movementOnsetTimes,timeRange)

            spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
                spikeTimesFromEventOnset, indexLimitsEachTrial,
                movementTimeRange)

            spikeCountEachTrial = spikeCountMat.flatten()
            spikeAvgLeftward = np.mean(spikeCountEachTrial[leftward])
            spikeAvgRightward = np.mean(spikeCountEachTrial[rightward])

            if ((spikeAvgRightward + spikeAvgLeftward) == 0):
                movementModI[indCell] = 0.0
                movementModS[indCell] = 1.0

            else:
                movementModI[indCell] = (
                    (spikeAvgRightward - spikeAvgLeftward) /
                    (spikeAvgRightward + spikeAvgLeftward))
                movementModS[indCell] = spikesanalysis.evaluate_modulation(
                    spikeTimesFromEventOnset, indexLimitsEachTrial,
                    movementTimeRange, trialsEachCond)[1]

        gosi008db['behavFreqs'] = behavDict['behavFreqs']
        gosi008db['behavZscore'] = behavDict['behavZscore']
        gosi008db['behavPval'] = behavDict['behavPval']
        gosi008db['behavRespIndex'] = behavDict['behavRespIndex']
        gosi008db['behavResp'] = behavDict['behavResp']
        gosi008db['movementModI'] = movementModI
        gosi008db['movementModS'] = movementModS
        gosi008db.to_hdf(databaseFullPath, key=key)
                    spikesanalysis.eventlocked_spiketimes(spkTimeStamps,EventOnsetTimes,timeRange)
                print len(spikeTimesFromEventOnset)

                spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset,indexLimitsEachTrial,countTimeRange)

                spikeCountEachTrial = spikeCountMat.flatten()
                spikeAvgMoreReward = sum(spikeCountEachTrial[trialsToUseMoreReward])/float(sum(trialsToUseMoreReward))
                spikeAvgLessReward = sum(spikeCountEachTrial[trialsToUseLessReward])/float(sum(trialsToUseLessReward))
                print 'cluster', clusterNumber, spikeAvgMoreReward, spikeAvgLessReward

                if ((spikeAvgMoreReward + spikeAvgLessReward) == 0):
                    modIDict[behavSession][Freq][clusterNumber]=0.0
                    modSigDict[behavSession][Freq][clusterNumber]=1.0
                else:
                    modIDict[behavSession][Freq][clusterNumber]=((spikeAvgMoreReward - spikeAvgLessReward)/(spikeAvgMoreReward + spikeAvgLessReward))  
                    modSig = spikesanalysis.evaluate_modulation(spikeTimesFromEventOnset,indexLimitsEachTrial,countTimeRange,trialsEachCond)
                    modSigDict[behavSession][Freq][clusterNumber]=modSig[1]
                    #print modIDict[behavSession][Freq][clusterNumber]
                modIndexArray.append([modIDict[behavSession][Freq][clusterNumber],modSigDict[behavSession][Freq][clusterNumber]])
                cellName=subject+'_'+behavSession+'_'+str(tetrode)+'_'+str(cluster)
                if (modSigDict[behavSession][freq][clusterNumber]<=minPValue) and cellName not in modCellList:
                    modCellList.append(cellName)

                #print spikeAvgMoreReward,' ', spikeAvgLessReward, ' ',modIDict[behavSession][Freq][clusterNumber]

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

    else:
        continue
Exemplo n.º 9
0
                     downsamplefactor=1)

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

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, nameFreq,
                                     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()

leftRightTrials = [trialsEachCond[:, 0], trialsEachCond[:, 1]]

mod_sig = spikesanalysis.evaluate_modulation(spikeTimesFromEventOnset,
                                             indexLimitsEachTrial,
                                             responseRange,
                                             trialsEachCond=leftRightTrials)

print mod_sig
Exemplo n.º 10
0
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)')


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,nameFreq,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()

leftRightTrials = [trialsEachCond[:,0],trialsEachCond[:,1]]

mod_sig = spikesanalysis.evaluate_modulation(spikeTimesFromEventOnset,indexLimitsEachTrial,responseRange,trialsEachCond = leftRightTrials)

print mod_sig