def laser_response(spikeTimeStamps, eventOnsetTimes, timeRange=[0.0, 0.1], baseRange=[0.5, 0.6]): spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimeStamps, eventOnsetTimes, [min(timeRange),max(baseRange)]) zStatsEachRange,pValueEachRange,maxZvalue = spikesanalysis.response_score(spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange, timeRange) baseSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange) baselineSpikeRate = np.mean(baseSpikeCountMat)/(baseRange[1]-baseRange[0]) laserSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange) laserSpikeRate = np.mean(laserSpikeCountMat)/(timeRange[1]-timeRange[0]) return (laserSpikeRate > baselineSpikeRate and pValueEachRange[0] < 0.00001)
def laser_response(cell, timeRange=[0.0, 0.1], baseRange=[0.5, 0.6]): cellInfo = get_cell_info(cell) loader = dataloader.DataLoader(cell['subject']) if len(cellInfo['laserIndex'])>0: eventData = loader.get_session_events(cellInfo['ephysDirs'][cellInfo['laserIndex'][-1]]) spikeData = loader.get_session_spikes(cellInfo['ephysDirs'][cellInfo['laserIndex'][-1]], cellInfo['tetrode'], cluster=cellInfo['cluster']) eventOnsetTimes = loader.get_event_onset_times(eventData) spikeTimestamps = spikeData.timestamps spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimestamps, eventOnsetTimes, [min(timeRange),max(baseRange)]) zStatsEachRange,pValueEachRange,maxZvalue = spikesanalysis.response_score(spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange, timeRange) baseSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange) baselineSpikeRate = np.mean(baseSpikeCountMat)/(baseRange[1]-baseRange[0]) laserSpikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimesFromEventOnset, indexLimitsEachTrial, timeRange) laserSpikeRate = np.mean(laserSpikeCountMat)/(timeRange[1]-timeRange[0]) laserResponse = (laserSpikeRate > baselineSpikeRate and pValueEachRange[0] < 0.00001) else: laserResponse = False return laserResponse
(spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \ spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange) plt.clf() ax1=plt.subplot(2,1,1) plt.plot(spikeTimesFromEventOnset,trialIndexForEachSpike,'.') plt.show() # -- Calculate sound responsiveness -- baseRange = [-0.050,-0.025] # Baseline range (in seconds) rangeLength = np.diff(baseRange) # Time-bin size binEdges = np.arange(-8,24)*rangeLength # Edges of bins to calculate response (in seconds) #baseRange = [-0.1, 0] # Baseline range (in seconds) #binEdges = [-0.1,0, 0.1, 0.2] [zStat,pValue,maxZ] = spikesanalysis.response_score(spikeTimesFromEventOnset,indexLimitsEachTrial,baseRange,binEdges) print 'Max absolute z-score: {0}'.format(maxZ) ax2=plt.subplot(2,1,2,sharex=ax1) plt.axhline(0,ls='-',color='0.5') plt.axhline(+3,ls='--',color='0.5') plt.axhline(-3,ls='--',color='0.5') plt.step(binEdges[:-1],zStat,where='post',lw=2) plt.ylabel('z-score') plt.xlabel('time (sec)') plt.show()
# -- Load Spike Data From Certain Cluster -- for Frequency in range(numberOfFrequencies): Freq = possibleFreq[Frequency] oneFreqTrials = bdata['targetFrequency'] == Freq oneFreqEventOnsetTimes = eventOnsetTimes[oneFreqTrials] #Choose only the trials with this frequency spkData = ephyscore.CellData(oneCell) spkTimeStamps = spkData.spikes.timestamps (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \ spikesanalysis.eventlocked_spiketimes(spkTimeStamps,oneFreqEventOnsetTimes,timeRange) [zStat,pValue,maxZ] = spikesanalysis.response_score(spikeTimesFromEventOnset,indexLimitsEachTrial,baseRange,binEdges) #computes z score for each bin. zStat is array of z scores. maxZ is maximum value of z in timeRange clusterNumber = (tetrode-1)*clusNum+(cluster-1) maxZDict[behavSession][Freq][clusterNumber] = maxZ bSessionList = [] for bSession in maxZDict: bSessionList.append(bSession) bSessionList.sort() for bSession in bSessionList: text_file.write("\nBehavior Session:%s" % bSession) for freq in maxZDict[bSession]: text_file.write("\n%s " % freq) for ZVal in maxZDict[bSession][freq]: text_file.write("%s," % ZVal)
#Use a longer base timerange so that we can determine baseline firing rate timeRange = [-0.5, 1] spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimestamps, eventOnsetTimes, timeRange) maxZarray = np.zeros([len(possibleIntensity), len(possibleFreq)]) for indInt, intensity in enumerate(possibleIntensity): for indFreq, freq in enumerate(possibleFreq): trialsThisCombo = np.flatnonzero((currentIntensity==inten) & (currentFreq==freq)) indexLimitsThisCombo = indexLimitsEachTrial[:, trialsThisCombo] spikeTimesThisCombo= spikeTimesFromEventOnset[np.in1d(trialIndexForEachSpike, trialsThisCombo)] [zStat,pValue,maxZ] = spikesanalysis.response_score(spikeTimesThisCombo,indexLimitsThisCombo,baseRange,binEdges) #computes z score for each bin. zStat is array of z scores. maxZ is maximum value of z in timeRange maxZarray[indInt, indFreq] = maxZ #Testing the above method testfreq = possibleFreq[6] testinten = 60 trialsThisCombo = np.flatnonzero((currentFreq==testfreq)&(currentIntensity==testinten)) timeRange = [-0.5, 1] spikeTimesFromEventOnset, trialIndexForEachSpike, indexLimitsEachTrial = spikesanalysis.eventlocked_spiketimes( spikeTimestamps, eventOnsetTimes, timeRange)
for Frequency in range(numberOfFrequencies): Freq = possibleFreq[Frequency] oneFreqTrials = bdata['targetFrequency'] == Freq #only use a certain frequency trialsToUse = (oneFreqTrials & validTrials) oneFreqEventOnsetTimes = eventOnsetTimes[trialsToUse] #Choose only the trials with this frequency spkData = ephyscore.CellData(oneCell) spkTimeStamps = spkData.spikes.timestamps (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \ spikesanalysis.eventlocked_spiketimes(spkTimeStamps,oneFreqEventOnsetTimes,timeRange) [zStat,pValue,maxZ] = spikesanalysis.response_score(spikeTimesFromEventOnset,indexLimitsEachTrial,baseRange,binEdges) #computes z score for each bin. zStat is array of z scores. maxZ is maximum value of z in timeRange clusterNumber = (tetrode-1)*clusNum+(cluster-1) #maxZArray[clusterNumber].append(maxZ) maxZDict[behavSession][Freq][clusterNumber] = maxZ #if abs(maxZ)=<Zthreshold & onecell.soundResponsive!=True: #oneCell.soundResponsive=False #elif abs(maxZ)>Zthreshold: #oneCell.soundResponsive=True #ZscoreArray[:,Frequency,cellID] = zStat except: #print "error with session "+oneCell.behavSession if (oneCell.behavSession not in badSessionList): badSessionList.append(oneCell.behavSession)
spikesanalysis.eventlocked_spiketimes(spkTimeStamps,eventOnsetTimes,timeRange) plt.clf() ax1 = plt.subplot(2, 1, 1) plt.plot(spikeTimesFromEventOnset, trialIndexForEachSpike, '.') plt.show() # -- Calculate sound responsiveness -- baseRange = [-0.050, -0.025] # Baseline range (in seconds) rangeLength = np.diff(baseRange) # Time-bin size binEdges = np.arange( -8, 24) * rangeLength # Edges of bins to calculate response (in seconds) #baseRange = [-0.1, 0] # Baseline range (in seconds) #binEdges = [-0.1,0, 0.1, 0.2] [zStat, pValue, maxZ] = spikesanalysis.response_score(spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange, binEdges) print 'Max absolute z-score: {0}'.format(maxZ) ax2 = plt.subplot(2, 1, 2, sharex=ax1) plt.axhline(0, ls='-', color='0.5') plt.axhline(+3, ls='--', color='0.5') plt.axhline(-3, ls='--', color='0.5') plt.step(binEdges[:-1], zStat, where='post', lw=2) plt.ylabel('z-score') plt.xlabel('time (sec)') plt.show()
def tuning_curve_response(cell): ''' Calculate max Z-score during the response period for each freq-inten combo in a TC ''' try: sessiontypeIndex = cell['sessiontype'].index('TuningCurve') except ValueError: #The cell does not have this session type return None #Initialize a data loader for this animal loader = dataloader.DataLoader(cell['subject']) #Get the behavior data behavData = loader.get_session_behavior(cell['behavior'][sessiontypeIndex]) intensityEachTrial = behavData['currentIntensity'] freqEachTrial = behavData['currentFreq'] possibleFreq = np.unique(freqEachTrial) possibleIntensity = np.unique(intensityEachTrial) #Return the cluster spike data for this ephys session ephysDir = cell['ephys'][sessiontypeIndex] clusterSpikeData = loader.get_session_spikes(ephysDir, int(cell['tetrode']), cluster=int(cell['cluster'])) clusterSpikeTimes = clusterSpikeData.timestamps #Get the events for this session and calculate onset times eventData = loader.get_session_events(ephysDir) eventOnsetTimes = loader.get_event_onset_times(eventData, minEventOnsetDiff=None) timeRange = [0, 0.1] baseRange = [-0.050, -0.025] # Baseline range (in seconds) binTime = baseRange[1] - baseRange[0] # Time-bin size responseTimeRange = timeRange #Time range to calculate z value for (should be divisible by binTime responseTime = responseTimeRange[1] - responseTimeRange[0] numBins = responseTime / binTime binEdges = np.arange(responseTimeRange[0], responseTimeRange[1], binTime) zvalArray = np.zeros((len(possibleIntensity), len(possibleFreq))) for indfreq, freq in enumerate(possibleFreq): for indinten, inten in enumerate(possibleIntensity): selectinds = np.flatnonzero((freqEachTrial == freq) & (intensityEachTrial == inten)) selectedOnsetTimes = eventOnsetTimes[selectinds] (spikeTimesFromEventOnset,trialIndexForEachSpike,indexLimitsEachTrial) = \ spikesanalysis.eventlocked_spiketimes(clusterSpikeTimes,selectedOnsetTimes,timeRange) [zStat, pValue, maxZ] = spikesanalysis.response_score( spikeTimesFromEventOnset, indexLimitsEachTrial, baseRange, binEdges ) #computes z score for each bin. zStat is array of z scores. maxZ is maximum value of z in timeRange zvalArray[indinten, indfreq] = maxZ # zvalArray = np.flipud(zvalArray) return zvalArray